From a192e187e8ace0ffe6733d109ce6d7be3c9d5268 Mon Sep 17 00:00:00 2001 From: janlaywss Date: Tue, 31 Mar 2026 21:09:32 +0800 Subject: [PATCH] fix: keep only source-map extracted node_modules, exclude pnpm artifacts Restore node_modules to exact state from cli.js.map extraction: - Move .ignored/ and .ignored_* files back to original package paths - Remove pnpm symlinks (replaced by real source-map directories) - Update .gitignore: only exclude /dist/, .pnpm/, .bin/, .ignored* dirs - All package dist/ folders are now preserved as part of source-map files After clone, run `pnpm install` to get pnpm-managed symlinks for building. The committed node_modules contains the original TypeScript/JS source files as bundled in cli.js. --- claude-code-source/.gitignore | 90 +- .../ansi-tokenize/build/ansiCodes.js | 50 + .../@alcalzone/ansi-tokenize/build/diff.js | 17 + .../@alcalzone/ansi-tokenize/build/index.js | 7 + .../@alcalzone/ansi-tokenize/build/reduce.js | 38 + .../ansi-tokenize/build/styledChars.js | 38 + .../ansi-tokenize/build/tokenize.js | 141 + .../@alcalzone/ansi-tokenize/build/undo.js | 11 + .../bedrock-sdk/AWS_restJson1.mjs | 163 + .../@anthropic-ai/bedrock-sdk/client.mjs | 124 + .../@anthropic-ai/bedrock-sdk/core/auth.mjs | 82 + .../@anthropic-ai/bedrock-sdk/core/error.mjs | 2 + .../bedrock-sdk/core/streaming.mjs | 108 + .../@anthropic-ai/bedrock-sdk/index.mjs | 3 + .../bedrock-sdk/internal/headers.mjs | 74 + .../bedrock-sdk/internal/shims.mjs | 85 + .../bedrock-sdk/internal/utils/env.mjs | 18 + .../bedrock-sdk/internal/utils/log.mjs | 80 + .../bedrock-sdk/internal/utils/path.mjs | 74 + .../bedrock-sdk/internal/utils/values.mjs | 94 + .../@anthropic-ai/foundry-sdk/client.mjs | 98 + .../@anthropic-ai/foundry-sdk/core/error.mjs | 2 + .../@anthropic-ai/foundry-sdk/index.mjs | 3 + .../foundry-sdk/internal/headers.mjs | 74 + .../foundry-sdk/internal/utils.mjs | 8 + .../foundry-sdk/internal/utils/base64.mjs | 33 + .../foundry-sdk/internal/utils/env.mjs | 18 + .../foundry-sdk/internal/utils/log.mjs | 80 + .../foundry-sdk/internal/utils/sleep.mjs | 1 + .../foundry-sdk/internal/utils/uuid.mjs | 2 + .../foundry-sdk/internal/utils/values.mjs | 100 + .../@anthropic-ai/mcpb/dist/cli/init.js | 705 + .../@anthropic-ai/mcpb/dist/cli/pack.js | 200 + .../@anthropic-ai/mcpb/dist/cli/unpack.js | 101 + .../@anthropic-ai/mcpb/dist/index.js | 10 + .../@anthropic-ai/mcpb/dist/node/files.js | 115 + .../@anthropic-ai/mcpb/dist/node/sign.js | 333 + .../@anthropic-ai/mcpb/dist/node/validate.js | 124 + .../@anthropic-ai/mcpb/dist/schemas-loose.js | 105 + .../@anthropic-ai/mcpb/dist/schemas.js | 107 + .../@anthropic-ai/mcpb/dist/shared/config.js | 157 + .../@anthropic-ai/mcpb/dist/shared/log.js | 29 + .../sandbox-runtime/dist/index.js | 9 + .../dist/sandbox/generate-seccomp-filter.js | 263 + .../dist/sandbox/http-proxy.js | 217 + .../dist/sandbox/linux-sandbox-utils.js | 875 + .../dist/sandbox/macos-sandbox-utils.js | 630 + .../dist/sandbox/sandbox-config.js | 180 + .../dist/sandbox/sandbox-manager.js | 786 + .../dist/sandbox/sandbox-utils.js | 435 + .../dist/sandbox/sandbox-violation-store.js | 54 + .../dist/sandbox/socks-proxy.js | 95 + .../sandbox-runtime/dist/utils/debug.js | 25 + .../sandbox-runtime/dist/utils/platform.js | 49 + .../sandbox-runtime/dist/utils/ripgrep.js | 45 + .../sandbox-runtime/dist/utils/which.js | 25 + .../_vendor/partial-json-parser/parser.mjs | 223 + .../node_modules/@anthropic-ai/sdk/client.mjs | 559 + .../@anthropic-ai/sdk/core/api-promise.mjs | 72 + .../@anthropic-ai/sdk/core/error.mjs | 98 + .../@anthropic-ai/sdk/core/pagination.mjs | 177 + .../@anthropic-ai/sdk/core/resource.mjs | 7 + .../@anthropic-ai/sdk/core/streaming.mjs | 283 + .../@anthropic-ai/sdk/core/uploads.mjs | 2 + .../node_modules/@anthropic-ai/sdk/error.mjs | 2 + .../node_modules/@anthropic-ai/sdk/index.mjs | 8 + .../@anthropic-ai/sdk/internal/constants.mjs | 15 + .../sdk/internal/decoders/jsonl.mjs | 35 + .../sdk/internal/decoders/line.mjs | 108 + .../sdk/internal/detect-platform.mjs | 157 + .../@anthropic-ai/sdk/internal/errors.mjs | 36 + .../@anthropic-ai/sdk/internal/headers.mjs | 74 + .../@anthropic-ai/sdk/internal/parse.mjs | 56 + .../sdk/internal/request-options.mjs | 10 + .../@anthropic-ai/sdk/internal/shims.mjs | 85 + .../@anthropic-ai/sdk/internal/to-file.mjs | 93 + .../@anthropic-ai/sdk/internal/tslib.mjs | 17 + .../@anthropic-ai/sdk/internal/uploads.mjs | 135 + .../sdk/internal/utils/bytes.mjs | 26 + .../@anthropic-ai/sdk/internal/utils/env.mjs | 18 + .../@anthropic-ai/sdk/internal/utils/log.mjs | 80 + .../@anthropic-ai/sdk/internal/utils/path.mjs | 74 + .../sdk/internal/utils/sleep.mjs | 3 + .../@anthropic-ai/sdk/internal/utils/uuid.mjs | 15 + .../sdk/internal/utils/values.mjs | 100 + .../sdk/lib/BetaMessageStream.mjs | 616 + .../@anthropic-ai/sdk/lib/MessageStream.mjs | 591 + .../@anthropic-ai/sdk/lib/beta-parser.mjs | 75 + .../@anthropic-ai/sdk/lib/parser.mjs | 62 + .../sdk/lib/stainless-helper-header.mjs | 63 + .../sdk/lib/tools/BetaToolRunner.mjs | 372 + .../sdk/lib/tools/CompactionControl.mjs | 25 + .../@anthropic-ai/sdk/lib/tools/ToolError.mjs | 38 + .../@anthropic-ai/sdk/resources/beta/beta.mjs | 24 + .../sdk/resources/beta/files.mjs | 120 + .../sdk/resources/beta/messages/batches.mjs | 200 + .../sdk/resources/beta/messages/messages.mjs | 156 + .../sdk/resources/beta/models.mjs | 56 + .../sdk/resources/beta/skills/skills.mjs | 93 + .../sdk/resources/beta/skills/versions.mjs | 96 + .../sdk/resources/completions.mjs | 19 + .../@anthropic-ai/sdk/resources/index.mjs | 7 + .../sdk/resources/messages/batches.mjs | 149 + .../sdk/resources/messages/messages.mjs | 123 + .../@anthropic-ai/sdk/resources/models.mjs | 41 + .../@anthropic-ai/sdk/streaming.mjs | 2 + .../@anthropic-ai/sdk/version.mjs | 2 + .../@anthropic-ai/vertex-sdk/client.mjs | 114 + .../@anthropic-ai/vertex-sdk/core/error.mjs | 2 + .../@anthropic-ai/vertex-sdk/index.mjs | 3 + .../vertex-sdk/internal/headers.mjs | 74 + .../vertex-sdk/internal/utils/env.mjs | 18 + .../vertex-sdk/internal/utils/values.mjs | 94 + .../@aws-crypto/crc32/build/main/aws_crc32.js | 31 + .../@aws-crypto/crc32/build/main/index.js | 108 + .../util/build/main/convertToBuffer.js | 24 + .../@aws-crypto/util/build/main/index.js | 14 + .../util/build/main/isEmptyData.js | 13 + .../@aws-crypto/util/build/main/numToUint8.js | 15 + .../util/build/main/uint32ArrayFrom.js | 20 + .../@smithy/util-utf8/dist-cjs/index.js | 65 + .../@aws-crypto/sha256-js/build/RawSha256.js | 124 + .../@aws-crypto/sha256-js/build/constants.js | 98 + .../@aws-crypto/sha256-js/build/index.js | 5 + .../@aws-crypto/sha256-js/build/jsSha256.js | 85 + .../sha256-js/node_modules/tslib/tslib.js | 284 + .../@aws-crypto/util/build/convertToBuffer.js | 24 + .../@aws-crypto/util/build/index.js | 14 + .../@aws-crypto/util/build/isEmptyData.js | 13 + .../@aws-crypto/util/build/numToUint8.js | 15 + .../@aws-crypto/util/build/uint32ArrayFrom.js | 20 + .../dist-cjs/auth/httpAuthSchemeProvider.js | 64 + .../dist-cjs/endpoint/endpointResolver.js | 18 + .../dist-cjs/endpoint/ruleset.js | 7 + .../client-bedrock-runtime/dist-cjs/index.js | 2491 +++ .../dist-cjs/runtimeConfig.js | 83 + .../dist-cjs/runtimeConfig.shared.js | 42 + .../eventstream-serde-node/dist-cjs/index.js | 53 + .../dist-cjs/index.js | 132 + .../@smithy/protocol-http/dist-cjs/index.js | 169 + .../@smithy/smithy-client/dist-cjs/index.js | 589 + .../@smithy/types/dist-cjs/index.js | 91 + .../util-base64/dist-cjs/fromBase64.js | 16 + .../@smithy/util-base64/dist-cjs/index.js | 19 + .../@smithy/util-base64/dist-cjs/toBase64.js | 19 + .../util-buffer-from/dist-cjs/index.js | 20 + .../@smithy/is-array-buffer/dist-cjs/index.js | 6 + .../dist-cjs/auth/httpAuthSchemeProvider.js | 64 + .../dist-cjs/endpoint/endpointResolver.js | 18 + .../dist-cjs/endpoint/ruleset.js | 7 + .../@aws-sdk/client-bedrock/dist-cjs/index.js | 8222 ++++++++++ .../client-bedrock/dist-cjs/runtimeConfig.js | 79 + .../dist-cjs/runtimeConfig.shared.js | 42 + .../@smithy/protocol-http/dist-cjs/index.js | 169 + .../@smithy/smithy-client/dist-cjs/index.js | 589 + .../@smithy/types/dist-cjs/index.js | 91 + .../util-base64/dist-cjs/fromBase64.js | 16 + .../@smithy/util-base64/dist-cjs/index.js | 19 + .../@smithy/util-base64/dist-cjs/toBase64.js | 19 + .../util-buffer-from/dist-cjs/index.js | 20 + .../@smithy/is-array-buffer/dist-cjs/index.js | 6 + .../dist-cjs/auth/httpAuthSchemeProvider.js | 68 + .../dist-cjs/endpoint/endpointResolver.js | 18 + .../dist-cjs/endpoint/ruleset.js | 7 + .../client-cognito-identity/dist-cjs/index.js | 1266 ++ .../dist-cjs/runtimeConfig.js | 56 + .../dist-cjs/runtimeConfig.shared.js | 47 + .../@smithy/protocol-http/dist-cjs/index.js | 169 + .../@smithy/smithy-client/dist-cjs/index.js | 589 + .../@smithy/types/dist-cjs/index.js | 91 + .../util-base64/dist-cjs/fromBase64.js | 16 + .../@smithy/util-base64/dist-cjs/index.js | 19 + .../@smithy/util-base64/dist-cjs/toBase64.js | 19 + .../util-buffer-from/dist-cjs/index.js | 20 + .../@smithy/is-array-buffer/dist-cjs/index.js | 6 + .../dist-cjs/auth/httpAuthSchemeProvider.js | 68 + .../dist-cjs/endpoint/endpointResolver.js | 18 + .../client-sso/dist-cjs/endpoint/ruleset.js | 7 + .../@aws-sdk/client-sso/dist-cjs/index.js | 514 + .../client-sso/dist-cjs/runtimeConfig.js | 54 + .../dist-cjs/runtimeConfig.shared.js | 42 + .../@smithy/protocol-http/dist-cjs/index.js | 169 + .../@smithy/smithy-client/dist-cjs/index.js | 589 + .../@smithy/types/dist-cjs/index.js | 91 + .../util-base64/dist-cjs/fromBase64.js | 16 + .../@smithy/util-base64/dist-cjs/index.js | 19 + .../@smithy/util-base64/dist-cjs/toBase64.js | 19 + .../util-buffer-from/dist-cjs/index.js | 20 + .../@smithy/is-array-buffer/dist-cjs/index.js | 6 + .../@aws-sdk/client-sts/dist-cjs/STSClient.js | 54 + .../auth/httpAuthExtensionConfiguration.js | 43 + .../dist-cjs/auth/httpAuthSchemeProvider.js | 66 + .../dist-cjs/endpoint/EndpointParameters.js | 19 + .../dist-cjs/endpoint/endpointResolver.js | 18 + .../client-sts/dist-cjs/endpoint/ruleset.js | 7 + .../@aws-sdk/client-sts/dist-cjs/index.js | 947 ++ .../client-sts/dist-cjs/runtimeConfig.js | 70 + .../dist-cjs/runtimeConfig.shared.js | 47 + .../client-sts/dist-cjs/runtimeExtensions.js | 13 + .../@smithy/protocol-http/dist-cjs/index.js | 169 + .../@smithy/smithy-client/dist-cjs/index.js | 589 + .../@smithy/types/dist-cjs/index.js | 91 + .../util-base64/dist-cjs/fromBase64.js | 16 + .../@smithy/util-base64/dist-cjs/index.js | 19 + .../@smithy/util-base64/dist-cjs/toBase64.js | 19 + .../util-buffer-from/dist-cjs/index.js | 20 + .../@smithy/is-array-buffer/dist-cjs/index.js | 6 + .../@aws-sdk/core/dist-cjs/index.js | 2000 +++ .../core/dist-cjs/submodules/client/index.js | 51 + .../submodules/httpAuthSchemes/index.js | 299 + .../dist-cjs/submodules/protocols/index.js | 1655 ++ .../@smithy/protocol-http/dist-cjs/index.js | 169 + .../@smithy/signature-v4/dist-cjs/index.js | 556 + .../@smithy/is-array-buffer/dist-cjs/index.js | 6 + .../util-hex-encoding/dist-cjs/index.js | 38 + .../@smithy/util-uri-escape/dist-cjs/index.js | 9 + .../@smithy/smithy-client/dist-cjs/index.js | 589 + .../@smithy/types/dist-cjs/index.js | 91 + .../util-base64/dist-cjs/fromBase64.js | 16 + .../@smithy/util-base64/dist-cjs/index.js | 19 + .../@smithy/util-base64/dist-cjs/toBase64.js | 19 + .../util-buffer-from/dist-cjs/index.js | 20 + .../@smithy/is-array-buffer/dist-cjs/index.js | 6 + .../dist-cjs/index.js | 204 + .../dist-cjs/loadCognitoIdentity-BPNvueUJ.js | 18 + .../credential-provider-env/dist-cjs/index.js | 41 + .../dist-cjs/fromHttp/checkUrl.js | 46 + .../dist-cjs/fromHttp/fromHttp.js | 70 + .../dist-cjs/fromHttp/requestHelpers.js | 53 + .../dist-cjs/fromHttp/retry-wrapper.js | 17 + .../dist-cjs/index.js | 5 + .../@smithy/protocol-http/dist-cjs/index.js | 169 + .../@smithy/smithy-client/dist-cjs/index.js | 589 + .../@smithy/types/dist-cjs/index.js | 91 + .../credential-provider-ini/dist-cjs/index.js | 226 + .../dist-cjs/index.js | 286 + .../@smithy/protocol-http/dist-cjs/index.js | 169 + .../@smithy/types/dist-cjs/index.js | 91 + .../dist-cjs/index.js | 150 + .../dist-cjs/index.js | 79 + .../credential-provider-sso/dist-cjs/index.js | 190 + .../dist-cjs/loadSso-CVy8iqsZ.js | 14 + .../dist-cjs/fromTokenFile.js | 34 + .../dist-cjs/fromWebToken.js | 62 + .../dist-cjs/index.js | 19 + .../dist-cjs/createCredentialChain.js | 45 + .../dist-cjs/fromCognitoIdentity.js | 8 + .../dist-cjs/fromCognitoIdentityPool.js | 8 + .../dist-cjs/fromContainerMetadata.js | 9 + .../credential-providers/dist-cjs/fromEnv.js | 6 + .../credential-providers/dist-cjs/fromIni.js | 8 + .../dist-cjs/fromInstanceMetadata.js | 10 + .../dist-cjs/fromLoginCredentials.js | 8 + .../dist-cjs/fromNodeProviderChain.js | 8 + .../dist-cjs/fromProcess.js | 6 + .../credential-providers/dist-cjs/fromSSO.js | 8 + .../dist-cjs/fromTemporaryCredentials.base.js | 155 + .../dist-cjs/fromTemporaryCredentials.js | 17 + .../dist-cjs/fromTokenFile.js | 8 + .../dist-cjs/fromWebToken.js | 8 + .../credential-providers/dist-cjs/index.js | 20 + .../credential-providers/dist-cjs/loadSts.js | 6 + .../dist-cjs/index.js | 108 + .../middleware-eventstream/dist-cjs/index.js | 65 + .../@smithy/protocol-http/dist-cjs/index.js | 169 + .../@smithy/types/dist-cjs/index.js | 91 + .../middleware-host-header/dist-cjs/index.js | 41 + .../@smithy/protocol-http/dist-cjs/index.js | 169 + .../@smithy/types/dist-cjs/index.js | 91 + .../middleware-logger/dist-cjs/index.js | 48 + .../dist-cjs/index.js | 25 + .../dist-cjs/recursionDetectionMiddleware.js | 33 + .../@smithy/protocol-http/dist-cjs/index.js | 169 + .../@smithy/types/dist-cjs/index.js | 91 + .../middleware-user-agent/dist-cjs/index.js | 194 + .../@smithy/protocol-http/dist-cjs/index.js | 169 + .../@smithy/types/dist-cjs/index.js | 91 + .../middleware-websocket/dist-cjs/index.js | 347 + .../fetch-http-handler/dist-cjs/index.js | 216 + .../querystring-builder/dist-cjs/index.js | 26 + .../@smithy/util-uri-escape/dist-cjs/index.js | 9 + .../util-base64/dist-cjs/fromBase64.js | 16 + .../@smithy/util-base64/dist-cjs/index.js | 19 + .../@smithy/util-base64/dist-cjs/toBase64.js | 19 + .../util-buffer-from/dist-cjs/index.js | 20 + .../@smithy/is-array-buffer/dist-cjs/index.js | 6 + .../@smithy/protocol-http/dist-cjs/index.js | 169 + .../@smithy/types/dist-cjs/index.js | 91 + .../util-hex-encoding/dist-cjs/index.js | 38 + .../signin/auth/httpAuthSchemeProvider.js | 56 + .../signin/endpoint/endpointResolver.js | 18 + .../submodules/signin/endpoint/ruleset.js | 7 + .../dist-cjs/submodules/signin/index.js | 439 + .../submodules/signin/runtimeConfig.js | 54 + .../submodules/signin/runtimeConfig.shared.js | 42 + .../sso-oidc/auth/httpAuthSchemeProvider.js | 56 + .../sso-oidc/endpoint/endpointResolver.js | 18 + .../submodules/sso-oidc/endpoint/ruleset.js | 7 + .../dist-cjs/submodules/sso-oidc/index.js | 561 + .../submodules/sso-oidc/runtimeConfig.js | 54 + .../sso-oidc/runtimeConfig.shared.js | 42 + .../dist-cjs/submodules/sts/STSClient.js | 54 + .../auth/httpAuthExtensionConfiguration.js | 43 + .../sts/auth/httpAuthSchemeProvider.js | 62 + .../sts/endpoint/EndpointParameters.js | 19 + .../sts/endpoint/endpointResolver.js | 18 + .../submodules/sts/endpoint/ruleset.js | 7 + .../dist-cjs/submodules/sts/index.js | 488 + .../dist-cjs/submodules/sts/runtimeConfig.js | 68 + .../submodules/sts/runtimeConfig.shared.js | 47 + .../submodules/sts/runtimeExtensions.js | 13 + .../@smithy/protocol-http/dist-cjs/index.js | 169 + .../@smithy/smithy-client/dist-cjs/index.js | 589 + .../@smithy/types/dist-cjs/index.js | 91 + .../util-base64/dist-cjs/fromBase64.js | 16 + .../@smithy/util-base64/dist-cjs/index.js | 19 + .../@smithy/util-base64/dist-cjs/toBase64.js | 19 + .../util-buffer-from/dist-cjs/index.js | 20 + .../@smithy/is-array-buffer/dist-cjs/index.js | 6 + .../region-config-resolver/dist-cjs/index.js | 49 + .../regionConfig/stsRegionDefaultResolver.js | 20 + .../token-providers/dist-cjs/index.js | 164 + .../@aws-sdk/util-endpoints/dist-cjs/index.js | 415 + .../util-format-url/dist-cjs/index.js | 34 + .../querystring-builder/dist-cjs/index.js | 26 + .../@smithy/util-uri-escape/dist-cjs/index.js | 9 + .../util-user-agent-node/dist-cjs/index.js | 58 + .../util-utf8-browser/dist-cjs/index.js | 9 + .../util-utf8-browser/dist-cjs/pureJs.js | 47 + .../dist-cjs/whatwgEncodingApi.js | 11 + .../@aws-sdk/xml-builder/dist-cjs/index.js | 124 + .../xml-builder/dist-cjs/xml-parser.js | 18 + .../abort-controller/dist/esm/AbortError.js | 27 + .../@azure/abort-controller/dist/esm/index.js | 4 + .../@azure/core-client/dist/commonjs/state.js | 12 + .../dist/esm/deserializationPolicy.js | 233 + .../core-client/dist/esm/httpClientCache.js | 11 + .../@azure/core-client/dist/esm/index.js | 11 + .../core-client/dist/esm/interfaceHelpers.js | 39 + .../@azure/core-client/dist/esm/interfaces.js | 11 + .../@azure/core-client/dist/esm/log.js | 5 + .../core-client/dist/esm/operationHelpers.js | 94 + .../@azure/core-client/dist/esm/pipeline.js | 26 + .../dist/esm/serializationPolicy.js | 153 + .../@azure/core-client/dist/esm/serializer.js | 922 ++ .../core-client/dist/esm/serviceClient.js | 148 + .../@azure/core-client/dist/esm/state.js | 10 + .../@azure/core-client/dist/esm/urlHelpers.js | 235 + .../@azure/core-client/dist/esm/utils.js | 115 + .../core-rest-pipeline/dist/esm/constants.js | 5 + .../dist/esm/createPipelineFromOptions.js | 55 + .../dist/esm/defaultHttpClient.js | 28 + .../dist/esm/httpHeaders.js | 11 + .../core-rest-pipeline/dist/esm/index.js | 29 + .../@azure/core-rest-pipeline/dist/esm/log.js | 5 + .../core-rest-pipeline/dist/esm/pipeline.js | 11 + .../dist/esm/pipelineRequest.js | 15 + .../dist/esm/policies/agentPolicy.js | 14 + .../bearerTokenAuthenticationPolicy.js | 238 + .../esm/policies/decompressResponsePolicy.js | 15 + .../dist/esm/policies/defaultRetryPolicy.js | 17 + .../dist/esm/policies/formDataPolicy.js | 14 + .../dist/esm/policies/logPolicy.js | 16 + .../dist/esm/policies/multipartPolicy.js | 28 + .../dist/esm/policies/proxyPolicy.js | 28 + .../dist/esm/policies/redirectPolicy.js | 17 + .../dist/esm/policies/retryPolicy.js | 16 + .../esm/policies/setClientRequestIdPolicy.js | 24 + .../dist/esm/policies/tlsPolicy.js | 14 + .../dist/esm/policies/tracingPolicy.js | 132 + .../dist/esm/policies/userAgentPolicy.js | 26 + .../esm/policies/wrapAbortSignalLikePolicy.js | 30 + .../core-rest-pipeline/dist/esm/restError.js | 16 + .../core-rest-pipeline/dist/esm/util/file.js | 104 + .../dist/esm/util/tokenCycler.js | 162 + .../dist/esm/util/userAgent.js | 30 + .../dist/esm/util/userAgentPlatform.js | 29 + .../dist/esm/util/wrapAbortSignal.js | 31 + .../core-tracing/dist/commonjs/state.js | 14 + .../@azure/core-tracing/dist/esm/index.js | 5 + .../core-tracing/dist/esm/instrumenter.js | 63 + .../@azure/core-tracing/dist/esm/state.js | 10 + .../core-tracing/dist/esm/tracingClient.js | 74 + .../core-tracing/dist/esm/tracingContext.js | 47 + .../dist/esm/createAbortablePromise.js | 42 + .../@azure/core-util/dist/esm/delay.js | 39 + .../@azure/core-util/dist/esm/error.js | 30 + .../@azure/core-util/dist/esm/index.js | 131 + .../dist/esm/client/identityClient.js | 248 + .../@azure/identity/dist/esm/constants.js | 75 + .../authorizationCodeCredential.js | 60 + .../esm/credentials/azureCliCredential.js | 191 + .../azureDeveloperCliCredential.js | 173 + .../credentials/azurePipelinesCredential.js | 141 + .../credentials/azurePowerShellCredential.js | 229 + .../esm/credentials/chainedTokenCredential.js | 92 + .../credentials/clientAssertionCredential.js | 55 + .../clientCertificateCredential.js | 128 + .../esm/credentials/clientSecretCredential.js | 60 + .../esm/credentials/defaultAzureCredential.js | 196 + .../esm/credentials/deviceCodeCredential.js | 91 + .../esm/credentials/environmentCredential.js | 130 + .../interactiveBrowserCredential.js | 91 + .../managedIdentityCredential/imdsMsi.js | 99 + .../imdsRetryPolicy.js | 33 + .../managedIdentityCredential/index.js | 239 + .../tokenExchangeMsi.js | 32 + .../managedIdentityCredential/utils.js | 81 + .../esm/credentials/onBehalfOfCredential.js | 118 + .../credentials/usernamePasswordCredential.js | 68 + .../credentials/visualStudioCodeCredential.js | 196 + .../credentials/workloadIdentityCredential.js | 114 + .../@azure/identity/dist/esm/errors.js | 123 + .../@azure/identity/dist/esm/index.js | 34 + .../@azure/identity/dist/esm/msal/msal.js | 5 + .../dist/esm/msal/nodeFlows/msalClient.js | 469 + .../dist/esm/msal/nodeFlows/msalPlugins.js | 87 + .../@azure/identity/dist/esm/msal/utils.js | 238 + .../identity/dist/esm/plugins/consumer.js | 43 + .../identity/dist/esm/regionalAuthority.js | 140 + .../@azure/identity/dist/esm/tokenProvider.js | 53 + .../dist/esm/util/identityTokenEndpoint.js | 11 + .../@azure/identity/dist/esm/util/logging.js | 94 + .../esm/util/processMultiTenantRequest.js | 35 + .../identity/dist/esm/util/processUtils.js | 32 + .../identity/dist/esm/util/scopeUtils.js | 29 + .../dist/esm/util/subscriptionUtils.js | 14 + .../identity/dist/esm/util/tenantIdUtils.js | 44 + .../@azure/identity/dist/esm/util/tracing.js | 14 + .../@azure/logger/dist/esm/index.js | 40 + .../msal-common/dist/account/AccountInfo.mjs | 85 + .../msal-common/dist/account/AuthToken.mjs | 86 + .../dist/account/CcsCredential.mjs | 13 + .../msal-common/dist/account/ClientInfo.mjs | 46 + .../msal-common/dist/account/TokenClaims.mjs | 25 + .../msal-common/dist/authority/Authority.mjs | 860 + .../dist/authority/AuthorityFactory.mjs | 39 + .../dist/authority/AuthorityMetadata.mjs | 144 + .../dist/authority/AuthorityOptions.mjs | 23 + .../dist/authority/AuthorityType.mjs | 18 + .../CloudInstanceDiscoveryErrorResponse.mjs | 13 + .../CloudInstanceDiscoveryResponse.mjs | 13 + .../dist/authority/OpenIdConfigResponse.mjs | 15 + .../dist/authority/ProtocolMode.mjs | 27 + .../dist/authority/RegionDiscovery.mjs | 112 + .../msal-common/dist/cache/CacheManager.mjs | 1124 ++ .../dist/cache/entities/AccountEntity.mjs | 232 + .../cache/persistence/TokenCacheContext.mjs | 30 + .../dist/cache/utils/CacheHelpers.mjs | 270 + .../dist/client/AuthorizationCodeClient.mjs | 259 + .../msal-common/dist/client/BaseClient.mjs | 167 + .../dist/client/RefreshTokenClient.mjs | 236 + .../dist/client/SilentFlowClient.mjs | 112 + .../dist/config/ClientConfiguration.mjs | 113 + .../dist/constants/AADServerParamKeys.mjs | 67 + .../msal-common/dist/crypto/ICrypto.mjs | 44 + .../dist/crypto/PopTokenGenerator.mjs | 89 + .../msal-common/dist/error/AuthError.mjs | 56 + .../msal-common/dist/error/AuthErrorCodes.mjs | 14 + .../msal-common/dist/error/CacheError.mjs | 52 + .../dist/error/CacheErrorCodes.mjs | 11 + .../dist/error/ClientAuthError.mjs | 259 + .../dist/error/ClientAuthErrorCodes.mjs | 53 + .../dist/error/ClientConfigurationError.mjs | 150 + .../error/ClientConfigurationErrorCodes.mjs | 32 + .../error/InteractionRequiredAuthError.mjs | 98 + .../InteractionRequiredAuthErrorCodes.mjs | 19 + .../msal-common/dist/error/NetworkError.mjs | 35 + .../msal-common/dist/error/ServerError.mjs | 23 + .../@azure/msal-common/dist/index-node.mjs | 70 + .../@azure/msal-common/dist/index.mjs | 75 + .../@azure/msal-common/dist/logger/Logger.mjs | 195 + .../dist/network/RequestThumbprint.mjs | 24 + .../dist/network/ThrottlingUtils.mjs | 93 + .../msal-common/dist/packageMetadata.mjs | 8 + .../msal-common/dist/protocol/Authorize.mjs | 237 + .../dist/request/RequestParameterBuilder.mjs | 423 + .../msal-common/dist/request/ScopeSet.mjs | 204 + .../dist/response/ResponseHandler.mjs | 350 + .../performance/PerformanceEvent.mjs | 526 + .../performance/StubPerformanceClient.mjs | 83 + .../server/ServerTelemetryManager.mjs | 268 + .../@azure/msal-common/dist/url/UrlString.mjs | 172 + .../dist/utils/ClientAssertionUtils.mjs | 21 + .../msal-common/dist/utils/Constants.mjs | 325 + .../dist/utils/FunctionWrappers.mjs | 99 + .../msal-common/dist/utils/ProtocolUtils.mjs | 78 + .../msal-common/dist/utils/StringUtils.mjs | 100 + .../msal-common/dist/utils/TimeUtils.mjs | 76 + .../msal-common/dist/utils/UrlUtils.mjs | 122 + .../msal-node/dist/cache/CacheHelpers.mjs | 42 + .../msal-node/dist/cache/NodeStorage.mjs | 429 + .../msal-node/dist/cache/TokenCache.mjs | 300 + .../distributed/DistributedCachePlugin.mjs | 49 + .../dist/cache/serializer/Deserializer.mjs | 179 + .../dist/cache/serializer/Serializer.mjs | 146 + .../dist/client/ClientApplication.mjs | 385 + .../msal-node/dist/client/ClientAssertion.mjs | 153 + .../dist/client/ClientCredentialClient.mjs | 202 + .../client/ConfidentialClientApplication.mjs | 194 + .../dist/client/DeviceCodeClient.mjs | 218 + .../client/ManagedIdentityApplication.mjs | 134 + .../dist/client/ManagedIdentityClient.mjs | 79 + .../ManagedIdentitySources/AppService.mjs | 109 + .../ManagedIdentitySources/AzureArc.mjs | 248 + .../BaseManagedIdentitySource.mjs | 244 + .../ManagedIdentitySources/CloudShell.mjs | 103 + .../client/ManagedIdentitySources/Imds.mjs | 108 + .../MachineLearning.mjs | 128 + .../ManagedIdentitySources/ServiceFabric.mjs | 122 + .../dist/client/OnBehalfOfClient.mjs | 210 + .../dist/client/PublicClientApplication.mjs | 266 + .../dist/client/UsernamePasswordClient.mjs | 104 + .../msal-node/dist/config/Configuration.mjs | 114 + .../dist/config/ManagedIdentityId.mjs | 57 + .../ManagedIdentityRequestParameters.mjs | 38 + .../msal-node/dist/crypto/CryptoProvider.mjs | 100 + .../msal-node/dist/crypto/GuidGenerator.mjs | 29 + .../msal-node/dist/crypto/HashUtils.mjs | 21 + .../msal-node/dist/crypto/PkceGenerator.mjs | 60 + .../dist/error/ManagedIdentityError.mjs | 50 + .../dist/error/ManagedIdentityErrorCodes.mjs | 31 + .../msal-node/dist/error/NodeAuthError.mjs | 112 + .../@azure/msal-node/dist/index.mjs | 20 + .../@azure/msal-node/dist/internals.mjs | 14 + .../msal-node/dist/network/HttpClient.mjs | 292 + .../dist/network/HttpClientWithRetries.mjs | 46 + .../msal-node/dist/network/LoopbackClient.mjs | 92 + .../@azure/msal-node/dist/packageMetadata.mjs | 8 + .../msal-node/dist/protocol/Authorize.mjs | 43 + .../DefaultManagedIdentityRetryPolicy.mjs | 49 + .../dist/retry/ExponentialRetryStrategy.mjs | 40 + .../msal-node/dist/retry/ImdsRetryPolicy.mjs | 90 + .../dist/retry/LinearRetryStrategy.mjs | 36 + .../@azure/msal-node/dist/utils/Constants.mjs | 153 + .../msal-node/dist/utils/EncodingUtils.mjs | 51 + .../msal-node/dist/utils/NetworkUtils.mjs | 43 + .../@azure/msal-node/dist/utils/TimeUtils.mjs | 23 + .../@commander-js/extra-typings/esm.mjs | 16 + .../@commander-js/extra-typings/index.js | 28 + .../growthbook/dist/esm/GrowthBook.mjs | 829 + .../@growthbook/growthbook/dist/esm/core.mjs | 879 + .../dist/esm/feature-repository.mjs | 488 + .../@growthbook/growthbook/dist/esm/index.mjs | 8 + .../growthbook/dist/esm/mongrule.mjs | 214 + .../@growthbook/growthbook/dist/esm/util.mjs | 312 + .../@inquirer/confirm/dist/esm/index.mjs | 33 + .../@inquirer/core/dist/esm/index.mjs | 12 + .../@inquirer/core/dist/esm/lib/Separator.mjs | 21 + .../core/dist/esm/lib/create-prompt.mjs | 84 + .../@inquirer/core/dist/esm/lib/errors.mjs | 21 + .../core/dist/esm/lib/hook-engine.mjs | 110 + .../@inquirer/core/dist/esm/lib/key.mjs | 18 + .../core/dist/esm/lib/make-theme.mjs | 30 + .../core/dist/esm/lib/pagination/lines.mjs | 59 + .../core/dist/esm/lib/pagination/position.mjs | 27 + .../esm/lib/pagination/use-pagination.mjs | 30 + .../core/dist/esm/lib/promise-polyfill.mjs | 14 + .../core/dist/esm/lib/screen-manager.mjs | 85 + .../@inquirer/core/dist/esm/lib/theme.mjs | 22 + .../core/dist/esm/lib/use-effect.mjs | 11 + .../core/dist/esm/lib/use-keypress.mjs | 20 + .../@inquirer/core/dist/esm/lib/use-memo.mjs | 14 + .../core/dist/esm/lib/use-prefix.mjs | 36 + .../@inquirer/core/dist/esm/lib/use-ref.mjs | 4 + .../@inquirer/core/dist/esm/lib/use-state.mjs | 19 + .../@inquirer/core/dist/esm/lib/utils.mjs | 25 + .../@inquirer/figures/dist/esm/index.js | 309 + .../@inquirer/input/dist/esm/index.mjs | 68 + .../@inquirer/prompts/dist/esm/index.mjs | 10 + .../@inquirer/select/dist/esm/index.mjs | 150 + .../@js-sdsl/ordered-map/dist/cjs/index.js | 795 + .../sdk/dist/esm/client/auth.js | 900 ++ .../sdk/dist/esm/client/index.js | 624 + .../sdk/dist/esm/client/sse.js | 206 + .../sdk/dist/esm/client/stdio.js | 191 + .../sdk/dist/esm/client/streamableHttp.js | 477 + .../sdk/dist/esm/experimental/tasks/client.js | 184 + .../dist/esm/experimental/tasks/helpers.js | 64 + .../dist/esm/experimental/tasks/interfaces.js | 16 + .../sdk/dist/esm/experimental/tasks/server.js | 246 + .../sdk/dist/esm/server/auth/errors.js | 180 + .../sdk/dist/esm/server/index.js | 440 + .../sdk/dist/esm/server/stdio.js | 75 + .../sdk/dist/esm/server/zod-compat.js | 209 + .../dist/esm/server/zod-json-schema-compat.js | 51 + .../sdk/dist/esm/shared/auth-utils.js | 44 + .../sdk/dist/esm/shared/auth.js | 198 + .../sdk/dist/esm/shared/protocol.js | 1099 ++ .../sdk/dist/esm/shared/stdio.js | 31 + .../sdk/dist/esm/shared/transport.js | 39 + .../sdk/dist/esm/types.js | 2052 +++ .../sdk/dist/esm/validation/ajv-provider.js | 87 + .../api-logs/build/src/NoopLogger.js | 24 + .../api-logs/build/src/NoopLoggerProvider.js | 27 + .../api-logs/build/src/ProxyLogger.js | 52 + .../api-logs/build/src/ProxyLoggerProvider.js | 51 + .../api-logs/build/src/api/logs.js | 64 + .../api-logs/build/src/index.js | 28 + .../build/src/internal/global-utils.js | 42 + .../api-logs/build/src/platform/index.js | 21 + .../build/src/platform/node/globalThis.js | 22 + .../api-logs/build/src/platform/node/index.js | 21 + .../api-logs/build/src/types/LogRecord.js | 47 + .../api/build/src/api/context.js | 81 + .../@opentelemetry/api/build/src/api/diag.js | 93 + .../api/build/src/api/metrics.js | 61 + .../api/build/src/api/propagation.js | 89 + .../@opentelemetry/api/build/src/api/trace.js | 79 + .../api/build/src/baggage/context-helpers.js | 63 + .../src/baggage/internal/baggage-impl.js | 55 + .../api/build/src/baggage/internal/symbol.js | 23 + .../api/build/src/baggage/utils.js | 51 + .../api/build/src/context-api.js | 24 + .../build/src/context/NoopContextManager.js | 38 + .../api/build/src/context/context.js | 55 + .../@opentelemetry/api/build/src/diag-api.js | 29 + .../api/build/src/diag/ComponentLogger.js | 59 + .../api/build/src/diag/consoleLogger.js | 57 + .../build/src/diag/internal/logLevelLogger.js | 45 + .../api/build/src/diag/types.js | 44 + .../@opentelemetry/api/build/src/index.js | 81 + .../api/build/src/internal/global-utils.js | 64 + .../api/build/src/internal/semver.js | 122 + .../api/build/src/metrics-api.js | 24 + .../api/build/src/metrics/Metric.js | 25 + .../api/build/src/metrics/NoopMeter.js | 127 + .../build/src/metrics/NoopMeterProvider.js | 31 + .../api/build/src/platform/index.js | 29 + .../api/build/src/platform/node/globalThis.js | 22 + .../api/build/src/platform/node/index.js | 29 + .../api/build/src/propagation-api.js | 24 + .../src/propagation/NoopTextMapPropagator.js | 34 + .../src/propagation/TextMapPropagator.js | 41 + .../@opentelemetry/api/build/src/trace-api.js | 24 + .../api/build/src/trace/NonRecordingSpan.js | 69 + .../api/build/src/trace/NoopTracer.js | 75 + .../api/build/src/trace/NoopTracerProvider.js | 32 + .../api/build/src/trace/ProxyTracer.js | 55 + .../build/src/trace/ProxyTracerProvider.js | 54 + .../api/build/src/trace/SamplingResult.js | 42 + .../api/build/src/trace/context-utils.js | 82 + .../src/trace/internal/tracestate-impl.js | 103 + .../trace/internal/tracestate-validators.js | 46 + .../api/build/src/trace/internal/utils.js | 24 + .../build/src/trace/invalid-span-constants.js | 27 + .../api/build/src/trace/span_kind.js | 46 + .../api/build/src/trace/spancontext-utils.js | 49 + .../api/build/src/trace/status.js | 23 + .../api/build/src/trace/trace_flags.js | 26 + .../@opentelemetry/api/build/src/version.js | 21 + .../core/build/src/ExportResult.js | 24 + .../core/build/src/baggage/constants.js | 30 + .../propagation/W3CBaggagePropagator.js | 76 + .../core/build/src/baggage/utils.js | 76 + .../core/build/src/common/anchored-clock.js | 61 + .../core/build/src/common/attributes.js | 93 + .../build/src/common/global-error-handler.js | 41 + .../build/src/common/logging-error-handler.js | 63 + .../core/build/src/common/time.js | 171 + .../core/build/src/common/timer-util.js | 29 + .../@opentelemetry/core/build/src/index.js | 92 + .../core/build/src/internal/exporter.js | 36 + .../core/build/src/internal/validators.js | 46 + .../core/build/src/platform/index.js | 27 + .../build/src/platform/node/environment.js | 104 + .../build/src/platform/node/globalThis.js | 22 + .../core/build/src/platform/node/index.js | 30 + .../build/src/platform/node/performance.js | 21 + .../core/build/src/platform/node/sdk-info.js | 29 + .../core/build/src/propagation/composite.js | 81 + .../@opentelemetry/core/build/src/semconv.js | 32 + .../core/build/src/trace/TraceState.js | 103 + .../src/trace/W3CTraceContextPropagator.js | 104 + .../core/build/src/trace/rpc-metadata.js | 37 + .../core/build/src/trace/suppress-tracing.js | 33 + .../core/build/src/utils/callback.js | 52 + .../core/build/src/utils/configuration.js | 46 + .../core/build/src/utils/lodash.merge.js | 157 + .../core/build/src/utils/merge.js | 162 + .../core/build/src/utils/promise.js | 40 + .../core/build/src/utils/timeout.js | 56 + .../core/build/src/utils/url.js | 45 + .../@opentelemetry/core/build/src/version.js | 21 + .../build/src/OTLPLogExporter.js | 31 + .../build/src/index.js | 21 + .../build/src/index.js | 21 + .../build/src/platform/index.js | 21 + .../src/platform/node/OTLPLogExporter.js | 33 + .../build/src/platform/node/index.js | 21 + .../build/src/index.js | 21 + .../build/src/platform/index.js | 21 + .../src/platform/node/OTLPLogExporter.js | 33 + .../build/src/platform/node/index.js | 21 + .../build/src/OTLPMetricExporter.js | 31 + .../build/src/index.js | 21 + .../build/src/OTLPMetricExporterBase.js | 104 + .../build/src/OTLPMetricExporterOptions.js | 25 + .../build/src/index.js | 28 + .../build/src/platform/index.js | 21 + .../src/platform/node/OTLPMetricExporter.js | 33 + .../build/src/platform/node/index.js | 21 + .../build/src/index.js | 21 + .../build/src/platform/index.js | 21 + .../src/platform/node/OTLPMetricExporter.js | 30 + .../build/src/platform/node/index.js | 21 + .../build/src/PrometheusExporter.js | 195 + .../build/src/PrometheusSerializer.js | 264 + .../exporter-prometheus/build/src/index.js | 23 + .../build/src/OTLPTraceExporter.js | 31 + .../build/src/index.js | 21 + .../build/src/index.js | 21 + .../build/src/platform/index.js | 21 + .../src/platform/node/OTLPTraceExporter.js | 33 + .../build/src/platform/node/index.js | 21 + .../build/src/index.js | 21 + .../build/src/platform/index.js | 21 + .../src/platform/node/OTLPTraceExporter.js | 33 + .../build/src/platform/node/index.js | 21 + .../build/src/OTLPExporterBase.js | 40 + .../bounded-queue-export-promise-handler.js | 54 + .../convert-legacy-http-options.js | 27 + .../convert-legacy-node-http-options.js | 47 + .../legacy-node-configuration.js | 24 + .../configuration/otlp-http-configuration.js | 75 + .../otlp-node-http-configuration.js | 56 + .../otlp-node-http-env-configuration.js | 134 + .../src/configuration/shared-configuration.js | 60 + .../configuration/shared-env-configuration.js | 56 + .../build/src/index-node-http.js | 27 + .../otlp-exporter-base/build/src/index.js | 30 + .../build/src/is-export-retryable.js | 40 + .../build/src/logging-response-handler.js | 42 + .../build/src/otlp-export-delegate.js | 115 + .../build/src/otlp-http-export-delegate.js | 33 + .../build/src/otlp-network-export-delegate.js | 29 + .../build/src/retrying-transport.js | 73 + .../src/transport/http-exporter-transport.js | 60 + .../src/transport/http-transport-utils.js | 99 + .../otlp-exporter-base/build/src/types.js | 33 + .../otlp-exporter-base/build/src/util.js | 37 + .../otlp-exporter-base/build/src/version.js | 21 + .../convert-legacy-otlp-grpc-options.js | 35 + .../configuration/otlp-grpc-configuration.js | 89 + .../otlp-grpc-env-configuration.js | 159 + .../src/create-service-client-constructor.js | 50 + .../build/src/grpc-exporter-transport.js | 131 + .../build/src/index.js | 23 + .../build/src/otlp-grpc-export-delegate.js | 33 + .../build/src/version.js | 21 + .../build/src/common/hex-to-binary.js | 42 + .../build/src/common/internal.js | 57 + .../build/src/common/utils.js | 69 + .../build/src/generated/root.js | 13299 ++++++++++++++++ .../otlp-transformer/build/src/index.js | 31 + .../build/src/logs/internal.js | 86 + .../build/src/logs/json/index.js | 22 + .../build/src/logs/json/logs.js | 25 + .../build/src/logs/protobuf/index.js | 21 + .../build/src/logs/protobuf/logs.js | 37 + .../build/src/metrics/internal-types.js | 75 + .../build/src/metrics/internal.js | 138 + .../build/src/metrics/json/index.js | 22 + .../build/src/metrics/json/metrics.js | 21 + .../build/src/metrics/protobuf/index.js | 22 + .../build/src/metrics/protobuf/metrics.js | 34 + .../build/src/trace/internal.js | 148 + .../build/src/trace/json/index.js | 22 + .../build/src/trace/json/trace.js | 22 + .../build/src/trace/protobuf/index.js | 22 + .../build/src/trace/protobuf/trace.js | 34 + .../resources/build/src/ResourceImpl.js | 167 + .../resources/build/src/detect-resources.js | 41 + .../build/src/detectors/EnvDetector.js | 134 + .../build/src/detectors/NoopDetector.js | 28 + .../resources/build/src/detectors/index.js | 28 + .../build/src/detectors/platform/index.js | 24 + .../detectors/platform/node/HostDetector.js | 38 + .../src/detectors/platform/node/OSDetector.js | 36 + .../platform/node/ProcessDetector.js | 55 + .../node/ServiceInstanceIdDetector.js | 37 + .../src/detectors/platform/node/index.js | 27 + .../platform/node/machine-id/execAsync.js | 22 + .../node/machine-id/getMachineId-bsd.js | 40 + .../node/machine-id/getMachineId-darwin.js | 41 + .../node/machine-id/getMachineId-linux.js | 35 + .../machine-id/getMachineId-unsupported.js | 25 + .../node/machine-id/getMachineId-win.js | 41 + .../platform/node/machine-id/getMachineId.js | 47 + .../src/detectors/platform/node/utils.js | 47 + .../resources/build/src/index.js | 33 + .../resources/build/src/platform/index.js | 21 + .../src/platform/node/default-service-name.js | 23 + .../build/src/platform/node/index.js | 21 + .../resources/build/src/semconv.js | 335 + .../resources/build/src/utils.js | 29 + .../sdk-logs/build/src/LogRecordImpl.js | 193 + .../sdk-logs/build/src/Logger.js | 52 + .../sdk-logs/build/src/LoggerProvider.js | 86 + .../build/src/MultiLogRecordProcessor.js | 43 + .../sdk-logs/build/src/config.js | 56 + .../src/export/BatchLogRecordProcessorBase.js | 172 + .../src/export/ConsoleLogRecordExporter.js | 75 + .../src/export/InMemoryLogRecordExporter.js | 55 + .../src/export/NoopLogRecordProcessor.js | 29 + .../src/export/SimpleLogRecordProcessor.js | 83 + .../sdk-logs/build/src/index.js | 29 + .../src/internal/LoggerProviderSharedState.js | 44 + .../sdk-logs/build/src/platform/index.js | 21 + .../node/export/BatchLogRecordProcessor.js | 24 + .../sdk-logs/build/src/platform/node/index.js | 21 + .../build/src/InstrumentDescriptor.js | 61 + .../sdk-metrics/build/src/Instruments.js | 140 + .../sdk-metrics/build/src/Meter.js | 100 + .../sdk-metrics/build/src/MeterProvider.js | 93 + .../sdk-metrics/build/src/ObservableResult.js | 93 + .../sdk-metrics/build/src/aggregator/Drop.js | 37 + .../src/aggregator/ExponentialHistogram.js | 480 + .../build/src/aggregator/Histogram.js | 187 + .../build/src/aggregator/LastValue.js | 93 + .../sdk-metrics/build/src/aggregator/Sum.js | 101 + .../exponential-histogram/Buckets.js | 277 + .../mapping/ExponentMapping.js | 90 + .../mapping/LogarithmMapping.js | 98 + .../mapping/getMapping.js | 45 + .../exponential-histogram/mapping/ieee754.js | 94 + .../exponential-histogram/mapping/types.js | 22 + .../aggregator/exponential-histogram/util.js | 63 + .../sdk-metrics/build/src/aggregator/index.js | 33 + .../sdk-metrics/build/src/aggregator/types.js | 28 + .../build/src/export/AggregationSelector.js | 29 + .../src/export/AggregationTemporality.js | 27 + .../build/src/export/ConsoleMetricExporter.js | 67 + .../src/export/InMemoryMetricExporter.js | 66 + .../build/src/export/MetricData.js | 60 + .../build/src/export/MetricReader.js | 128 + .../export/PeriodicExportingMetricReader.js | 115 + .../sdk-metrics/build/src/index.js | 41 + .../build/src/state/AsyncMetricStorage.js | 60 + .../build/src/state/DeltaMetricProcessor.js | 103 + .../sdk-metrics/build/src/state/HashMap.js | 83 + .../src/state/MeterProviderSharedState.js | 55 + .../build/src/state/MeterSharedState.js | 120 + .../build/src/state/MetricCollector.js | 83 + .../build/src/state/MetricStorage.js | 43 + .../build/src/state/MetricStorageRegistry.js | 112 + .../src/state/MultiWritableMetricStorage.js | 34 + .../build/src/state/ObservableRegistry.js | 128 + .../build/src/state/SyncMetricStorage.js | 55 + .../src/state/TemporalMetricProcessor.js | 156 + .../sdk-metrics/build/src/utils.js | 156 + .../sdk-metrics/build/src/view/Aggregation.js | 156 + .../build/src/view/AggregationOption.js | 57 + .../build/src/view/AttributesProcessor.js | 99 + .../build/src/view/InstrumentSelector.js | 40 + .../build/src/view/MeterSelector.js | 43 + .../sdk-metrics/build/src/view/Predicate.js | 71 + .../build/src/view/RegistrationConflicts.js | 85 + .../sdk-metrics/build/src/view/View.js | 139 + .../build/src/view/ViewRegistry.js | 46 + .../build/src/BasicTracerProvider.js | 104 + .../build/src/MultiSpanProcessor.js | 68 + .../sdk-trace-base/build/src/Sampler.js | 41 + .../sdk-trace-base/build/src/Span.js | 312 + .../sdk-trace-base/build/src/Tracer.js | 152 + .../sdk-trace-base/build/src/config.js | 107 + .../sdk-trace-base/build/src/enums.js | 21 + .../src/export/BatchSpanProcessorBase.js | 223 + .../build/src/export/ConsoleSpanExporter.js | 88 + .../build/src/export/InMemorySpanExporter.js | 60 + .../build/src/export/NoopSpanProcessor.js | 31 + .../build/src/export/SimpleSpanProcessor.js | 76 + .../sdk-trace-base/build/src/index.js | 42 + .../build/src/platform/index.js | 22 + .../src/platform/node/RandomIdGenerator.js | 54 + .../node/export/BatchSpanProcessor.js | 24 + .../build/src/platform/node/index.js | 23 + .../build/src/sampler/AlwaysOffSampler.js | 32 + .../build/src/sampler/AlwaysOnSampler.js | 32 + .../build/src/sampler/ParentBasedSampler.js | 69 + .../src/sampler/TraceIdRatioBasedSampler.js | 56 + .../sdk-trace-base/build/src/utility.js | 66 + .../semantic-conventions/build/src/index.js | 43 + .../build/src/internal/utils.js | 38 + .../resource/SemanticResourceAttributes.js | 1266 ++ .../build/src/resource/index.js | 37 + .../build/src/stable_attributes.js | 1085 ++ .../build/src/stable_events.js | 26 + .../build/src/stable_metrics.js | 330 + .../build/src/trace/SemanticAttributes.js | 2379 +++ .../build/src/trace/index.js | 37 + .../@pondwader/socks5-server/dist/index.js | 346 + .../@smithy/config-resolver/dist-cjs/index.js | 186 + .../@smithy/core/dist-cjs/index.js | 349 + .../core/dist-cjs/submodules/cbor/index.js | 1050 ++ .../submodules/event-streams/index.js | 252 + .../dist-cjs/submodules/protocols/index.js | 839 + .../core/dist-cjs/submodules/schema/index.js | 620 + .../core/dist-cjs/submodules/serde/index.js | 697 + .../@smithy/protocol-http/dist-cjs/index.js | 169 + .../@smithy/types/dist-cjs/index.js | 91 + .../util-base64/dist-cjs/fromBase64.js | 16 + .../@smithy/util-base64/dist-cjs/index.js | 19 + .../@smithy/util-base64/dist-cjs/toBase64.js | 19 + .../util-buffer-from/dist-cjs/index.js | 20 + .../@smithy/is-array-buffer/dist-cjs/index.js | 6 + .../dist-cjs/index.js | 372 + .../eventstream-codec/dist-cjs/index.js | 388 + .../util-hex-encoding/dist-cjs/index.js | 38 + .../dist-cjs/index.js | 58 + .../dist-cjs/index.js | 132 + .../dist-cjs/index.js | 7 + .../eventstream-serde-node/dist-cjs/index.js | 88 + .../dist-cjs/index.js | 182 + .../eventstream-codec/dist-cjs/index.js | 468 + .../@aws-crypto/crc32/build/aws_crc32.js | 31 + .../@aws-crypto/crc32/build/index.js | 108 + .../@aws-crypto/util/build/convertToBuffer.js | 24 + .../@aws-crypto/util/build/index.js | 14 + .../@aws-crypto/util/build/isEmptyData.js | 13 + .../@aws-crypto/util/build/numToUint8.js | 15 + .../@aws-crypto/util/build/uint32ArrayFrom.js | 20 + .../crc32/node_modules/tslib/tslib.js | 284 + .../util-hex-encoding/dist-cjs/index.js | 67 + .../fetch-http-handler/dist-cjs/index.js | 264 + .../@smithy/protocol-http/dist-cjs/index.js | 262 + .../@smithy/types/dist-cjs/index.js | 144 + .../util-base64/dist-cjs/fromBase64.js | 16 + .../@smithy/util-base64/dist-cjs/index.js | 27 + .../@smithy/util-base64/dist-cjs/toBase64.js | 19 + .../util-buffer-from/dist-cjs/index.js | 20 + .../@smithy/is-array-buffer/dist-cjs/index.js | 6 + .../@smithy/hash-node/dist-cjs/index.js | 42 + .../util-buffer-from/dist-cjs/index.js | 20 + .../@smithy/is-array-buffer/dist-cjs/index.js | 6 + .../@smithy/is-array-buffer/dist-cjs/index.js | 32 + .../dist-cjs/index.js | 46 + .../@smithy/protocol-http/dist-cjs/index.js | 169 + .../@smithy/types/dist-cjs/index.js | 91 + .../adaptors/getEndpointFromConfig.js | 7 + .../dist-cjs/adaptors/getEndpointUrlConfig.js | 35 + .../middleware-endpoint/dist-cjs/index.js | 240 + .../middleware-retry/dist-cjs/index.js | 358 + .../isStreamingPayload/isStreamingPayload.js | 7 + .../@smithy/protocol-http/dist-cjs/index.js | 169 + .../@smithy/smithy-client/dist-cjs/index.js | 589 + .../@smithy/types/dist-cjs/index.js | 91 + .../middleware-serde/dist-cjs/index.js | 103 + .../@smithy/protocol-http/dist-cjs/index.js | 169 + .../@smithy/types/dist-cjs/index.js | 91 + .../middleware-stack/dist-cjs/index.js | 285 + .../node-config-provider/dist-cjs/index.js | 62 + .../node-http-handler/dist-cjs/index.js | 732 + .../@smithy/protocol-http/dist-cjs/index.js | 169 + .../querystring-builder/dist-cjs/index.js | 26 + .../@smithy/util-uri-escape/dist-cjs/index.js | 9 + .../@smithy/types/dist-cjs/index.js | 91 + .../property-provider/dist-cjs/index.js | 117 + .../@smithy/protocol-http/dist-cjs/index.js | 237 + .../querystring-builder/dist-cjs/index.js | 52 + .../@smithy/util-uri-escape/dist-cjs/index.js | 43 + .../querystring-parser/dist-cjs/index.js | 27 + .../dist-cjs/index.js | 77 + .../dist-cjs/getHomeDir.js | 26 + .../dist-cjs/getSSOTokenFilepath.js | 12 + .../dist-cjs/getSSOTokenFromFile.js | 15 + .../shared-ini-file-loader/dist-cjs/index.js | 194 + .../dist-cjs/readFile.js | 16 + .../@smithy/types/dist-cjs/index.js | 91 + .../@smithy/signature-v4/dist-cjs/index.js | 589 + .../@smithy/types/dist-cjs/index.js | 149 + .../@smithy/util-middleware/dist-cjs/index.js | 45 + .../@smithy/util-utf8/dist-cjs/index.js | 65 + .../util-buffer-from/dist-cjs/index.js | 47 + .../@smithy/smithy-client/dist-cjs/index.js | 1256 ++ .../middleware-stack/dist-cjs/index.js | 318 + .../dist-cjs/getAwsChunkedEncodingStream.js | 30 + .../@smithy/util-stream/dist-cjs/index.js | 89 + .../util-stream/dist-cjs/sdk-stream-mixin.js | 50 + .../node-http-handler/dist-cjs/index.js | 687 + .../querystring-builder/dist-cjs/index.js | 52 + .../@smithy/util-uri-escape/dist-cjs/index.js | 43 + .../@smithy/util-utf8/dist-cjs/index.js | 65 + .../@smithy/types/dist-cjs/index.js | 149 + .../@smithy/url-parser/dist-cjs/index.js | 23 + .../util-base64/dist-cjs/fromBase64.js | 16 + .../@smithy/util-base64/dist-cjs/index.js | 27 + .../@smithy/util-base64/dist-cjs/toBase64.js | 19 + .../@smithy/util-utf8/dist-cjs/index.js | 65 + .../dist-cjs/index.js | 30 + .../util-body-length-node/dist-cjs/index.js | 32 + .../util-buffer-from/dist-cjs/index.js | 47 + .../@smithy/is-array-buffer/dist-cjs/index.js | 32 + .../util-config-provider/dist-cjs/index.js | 30 + .../util-defaults-mode-node/dist-cjs/index.js | 74 + .../@smithy/util-endpoints/dist-cjs/index.js | 472 + .../@smithy/types/dist-cjs/index.js | 91 + .../util-hex-encoding/dist-cjs/index.js | 67 + .../@smithy/util-middleware/dist-cjs/index.js | 15 + .../@smithy/types/dist-cjs/index.js | 91 + .../@smithy/util-retry/dist-cjs/index.js | 278 + .../dist-cjs/ByteArrayCollector.js | 36 + .../checksum/ChecksumStream.browser.js | 7 + .../dist-cjs/checksum/ChecksumStream.js | 53 + .../checksum/createChecksumStream.browser.js | 39 + .../dist-cjs/checksum/createChecksumStream.js | 12 + .../dist-cjs/createBufferedReadable.js | 60 + .../dist-cjs/createBufferedReadableStream.js | 103 + .../dist-cjs/getAwsChunkedEncodingStream.js | 30 + .../dist-cjs/headStream.browser.js | 34 + .../util-stream/dist-cjs/headStream.js | 42 + .../@smithy/util-stream/dist-cjs/index.js | 84 + .../dist-cjs/sdk-stream-mixin.browser.js | 68 + .../util-stream/dist-cjs/sdk-stream-mixin.js | 54 + .../dist-cjs/splitStream.browser.js | 10 + .../util-stream/dist-cjs/splitStream.js | 16 + .../util-stream/dist-cjs/stream-type-check.js | 10 + .../fetch-http-handler/dist-cjs/index.js | 216 + .../@smithy/protocol-http/dist-cjs/index.js | 169 + .../querystring-builder/dist-cjs/index.js | 26 + .../@smithy/util-uri-escape/dist-cjs/index.js | 9 + .../@smithy/types/dist-cjs/index.js | 91 + .../util-base64/dist-cjs/fromBase64.js | 16 + .../@smithy/util-base64/dist-cjs/index.js | 19 + .../@smithy/util-base64/dist-cjs/toBase64.js | 19 + .../util-buffer-from/dist-cjs/index.js | 20 + .../@smithy/is-array-buffer/dist-cjs/index.js | 6 + .../util-hex-encoding/dist-cjs/index.js | 38 + .../@smithy/util-uri-escape/dist-cjs/index.js | 43 + .../@smithy/util-utf8/dist-cjs/index.js | 32 + .../util-buffer-from/dist-cjs/index.js | 20 + .../@smithy/is-array-buffer/dist-cjs/index.js | 6 + .../@smithy/uuid/dist-cjs/index.js | 36 + .../@smithy/uuid/dist-cjs/randomUUID.js | 6 + claude-code-source/node_modules/@types/node | 1 + claude-code-source/node_modules/@types/react | 1 + claude-code-source/node_modules/@types/ws | 1 + .../dist/esm/abort-controller/AbortError.js | 38 + .../ts-http-runtime/dist/esm/constants.js | 5 + .../dist/esm/defaultHttpClient.js | 10 + .../ts-http-runtime/dist/esm/httpHeaders.js | 89 + .../ts-http-runtime/dist/esm/index.js | 16 + .../@typespec/ts-http-runtime/dist/esm/log.js | 5 + .../ts-http-runtime/dist/esm/logger/debug.js | 93 + .../dist/esm/logger/internal.js | 4 + .../ts-http-runtime/dist/esm/logger/log.js | 9 + .../ts-http-runtime/dist/esm/logger/logger.js | 125 + .../dist/esm/nodeHttpClient.js | 341 + .../ts-http-runtime/dist/esm/pipeline.js | 262 + .../dist/esm/pipelineRequest.js | 37 + .../dist/esm/policies/agentPolicy.js | 22 + .../esm/policies/decompressResponsePolicy.js | 23 + .../dist/esm/policies/defaultRetryPolicy.js | 26 + .../dist/esm/policies/formDataPolicy.js | 97 + .../dist/esm/policies/internal.js | 17 + .../dist/esm/policies/logPolicy.js | 34 + .../dist/esm/policies/multipartPolicy.js | 112 + .../dist/esm/policies/proxyPolicy.js | 191 + .../dist/esm/policies/redirectPolicy.js | 52 + .../dist/esm/policies/retryPolicy.js | 105 + .../dist/esm/policies/tlsPolicy.js | 22 + .../ts-http-runtime/dist/esm/restError.js | 55 + .../exponentialRetryStrategy.js | 64 + .../throttlingRetryStrategy.js | 74 + .../dist/esm/util/bytesEncoding.js | 21 + .../dist/esm/util/checkEnvironment.js | 42 + .../ts-http-runtime/dist/esm/util/concat.js | 87 + .../ts-http-runtime/dist/esm/util/delay.js | 20 + .../ts-http-runtime/dist/esm/util/error.js | 16 + .../ts-http-runtime/dist/esm/util/helpers.js | 58 + .../ts-http-runtime/dist/esm/util/inspect.js | 5 + .../ts-http-runtime/dist/esm/util/internal.js | 12 + .../ts-http-runtime/dist/esm/util/object.js | 14 + .../ts-http-runtime/dist/esm/util/random.js | 21 + .../dist/esm/util/sanitizer.js | 149 + .../dist/esm/util/typeGuards.js | 24 + .../dist/esm/util/uuidUtils.js | 17 + .../@xmldom/xmldom/lib/conventions.js | 203 + .../@xmldom/xmldom/lib/dom-parser.js | 322 + .../node_modules/@xmldom/xmldom/lib/dom.js | 1840 +++ .../@xmldom/xmldom/lib/entities.js | 2166 +++ .../node_modules/@xmldom/xmldom/lib/index.js | 4 + .../node_modules/@xmldom/xmldom/lib/sax.js | 662 + .../node_modules/agent-base/dist/helpers.js | 66 + .../node_modules/agent-base/dist/index.js | 180 + .../node_modules/ajv-formats/dist/formats.js | 208 + .../node_modules/ajv-formats/dist/index.js | 37 + .../node_modules/ajv-formats/dist/limit.js | 69 + .../node_modules/ajv/dist/ajv.js | 50 + .../ajv/dist/compile/codegen/code.js | 156 + .../ajv/dist/compile/codegen/index.js | 697 + .../ajv/dist/compile/codegen/scope.js | 143 + .../node_modules/ajv/dist/compile/errors.js | 123 + .../node_modules/ajv/dist/compile/index.js | 242 + .../node_modules/ajv/dist/compile/names.js | 28 + .../ajv/dist/compile/ref_error.js | 12 + .../node_modules/ajv/dist/compile/resolve.js | 155 + .../node_modules/ajv/dist/compile/rules.js | 26 + .../node_modules/ajv/dist/compile/util.js | 178 + .../dist/compile/validate/applicability.js | 19 + .../ajv/dist/compile/validate/boolSchema.js | 50 + .../ajv/dist/compile/validate/dataType.js | 203 + .../ajv/dist/compile/validate/defaults.js | 35 + .../ajv/dist/compile/validate/index.js | 520 + .../ajv/dist/compile/validate/keyword.js | 124 + .../ajv/dist/compile/validate/subschema.js | 81 + .../node_modules/ajv/dist/core.js | 618 + .../node_modules/ajv/dist/runtime/equal.js | 7 + .../ajv/dist/runtime/ucs2length.js | 24 + .../node_modules/ajv/dist/runtime/uri.js | 6 + .../ajv/dist/runtime/validation_error.js | 11 + .../applicator/additionalItems.js | 49 + .../applicator/additionalProperties.js | 106 + .../ajv/dist/vocabularies/applicator/allOf.js | 23 + .../ajv/dist/vocabularies/applicator/anyOf.js | 12 + .../dist/vocabularies/applicator/contains.js | 95 + .../vocabularies/applicator/dependencies.js | 85 + .../ajv/dist/vocabularies/applicator/if.js | 66 + .../ajv/dist/vocabularies/applicator/index.js | 44 + .../ajv/dist/vocabularies/applicator/items.js | 52 + .../dist/vocabularies/applicator/items2020.js | 30 + .../ajv/dist/vocabularies/applicator/not.js | 26 + .../ajv/dist/vocabularies/applicator/oneOf.js | 60 + .../applicator/patternProperties.js | 75 + .../vocabularies/applicator/prefixItems.js | 12 + .../vocabularies/applicator/properties.js | 54 + .../vocabularies/applicator/propertyNames.js | 38 + .../dist/vocabularies/applicator/thenElse.js | 13 + .../ajv/dist/vocabularies/code.js | 131 + .../ajv/dist/vocabularies/core/id.js | 10 + .../ajv/dist/vocabularies/core/index.js | 16 + .../ajv/dist/vocabularies/core/ref.js | 122 + .../dist/vocabularies/discriminator/index.js | 104 + .../dist/vocabularies/discriminator/types.js | 9 + .../ajv/dist/vocabularies/draft7.js | 17 + .../ajv/dist/vocabularies/format/format.js | 92 + .../ajv/dist/vocabularies/format/index.js | 6 + .../ajv/dist/vocabularies/metadata.js | 18 + .../ajv/dist/vocabularies/validation/const.js | 25 + .../ajv/dist/vocabularies/validation/enum.js | 48 + .../ajv/dist/vocabularies/validation/index.js | 33 + .../vocabularies/validation/limitItems.js | 24 + .../vocabularies/validation/limitLength.js | 27 + .../vocabularies/validation/limitNumber.js | 27 + .../validation/limitProperties.js | 24 + .../vocabularies/validation/multipleOf.js | 26 + .../dist/vocabularies/validation/pattern.js | 33 + .../dist/vocabularies/validation/required.js | 79 + .../vocabularies/validation/uniqueItems.js | 64 + .../node_modules/asciichart/asciichart.js | 110 + .../node_modules/auto-bind/index.js | 41 + .../node_modules/axios/index.js | 43 + .../axios/lib/adapters/adapters.js | 130 + .../node_modules/axios/lib/adapters/fetch.js | 334 + .../node_modules/axios/lib/adapters/http.js | 949 ++ .../node_modules/axios/lib/adapters/xhr.js | 222 + .../node_modules/axios/lib/axios.js | 89 + .../axios/lib/cancel/CancelToken.js | 135 + .../axios/lib/cancel/CanceledError.js | 22 + .../node_modules/axios/lib/cancel/isCancel.js | 5 + .../node_modules/axios/lib/core/Axios.js | 263 + .../node_modules/axios/lib/core/AxiosError.js | 90 + .../axios/lib/core/AxiosHeaders.js | 344 + .../axios/lib/core/InterceptorManager.js | 72 + .../axios/lib/core/buildFullPath.js | 22 + .../axios/lib/core/dispatchRequest.js | 77 + .../axios/lib/core/mergeConfig.js | 107 + .../node_modules/axios/lib/core/settle.js | 31 + .../axios/lib/core/transformData.js | 28 + .../node_modules/axios/lib/defaults/index.js | 172 + .../axios/lib/defaults/transitional.js | 8 + .../node_modules/axios/lib/env/data.js | 1 + .../axios/lib/helpers/AxiosTransformStream.js | 156 + .../axios/lib/helpers/AxiosURLSearchParams.js | 62 + .../axios/lib/helpers/HttpStatusCode.js | 77 + .../lib/helpers/ZlibHeaderTransformStream.js | 29 + .../node_modules/axios/lib/helpers/bind.js | 14 + .../axios/lib/helpers/buildURL.js | 66 + .../axios/lib/helpers/callbackify.js | 18 + .../axios/lib/helpers/combineURLs.js | 15 + .../axios/lib/helpers/composeSignals.js | 56 + .../node_modules/axios/lib/helpers/cookies.js | 48 + .../helpers/estimateDataURLDecodedBytes.js | 73 + .../axios/lib/helpers/formDataToJSON.js | 95 + .../axios/lib/helpers/formDataToStream.js | 118 + .../axios/lib/helpers/fromDataURI.js | 53 + .../axios/lib/helpers/isAbsoluteURL.js | 19 + .../axios/lib/helpers/isAxiosError.js | 14 + .../axios/lib/helpers/isURLSameOrigin.js | 16 + .../axios/lib/helpers/parseHeaders.js | 69 + .../axios/lib/helpers/parseProtocol.js | 6 + .../axios/lib/helpers/progressEventReducer.js | 51 + .../axios/lib/helpers/readBlob.js | 15 + .../axios/lib/helpers/resolveConfig.js | 70 + .../axios/lib/helpers/speedometer.js | 55 + .../node_modules/axios/lib/helpers/spread.js | 28 + .../axios/lib/helpers/throttle.js | 44 + .../axios/lib/helpers/toFormData.js | 241 + .../axios/lib/helpers/toURLEncodedForm.js | 19 + .../axios/lib/helpers/trackStream.js | 89 + .../axios/lib/helpers/validator.js | 110 + .../axios/lib/platform/common/utils.js | 52 + .../node_modules/axios/lib/platform/index.js | 7 + .../lib/platform/node/classes/FormData.js | 3 + .../platform/node/classes/URLSearchParams.js | 4 + .../axios/lib/platform/node/index.js | 37 + .../node_modules/axios/lib/utils.js | 919 ++ .../node_modules/bidi-js/dist/bidi.js | 1010 ++ claude-code-source/node_modules/bun-types | 1 + .../node_modules/chalk/source/index.js | 225 + .../node_modules/chalk/source/utilities.js | 33 + .../chalk/source/vendor/ansi-styles/index.js | 223 + .../source/vendor/supports-color/index.js | 182 + .../node_modules/chokidar/esm/handler.js | 629 + .../node_modules/chokidar/esm/index.js | 798 + .../node_modules/cli-boxes/index.js | 6 + .../node_modules/cli-highlight/dist/index.js | 112 + .../node_modules/cli-highlight/dist/theme.js | 265 + .../node_modules/code-excerpt/dist/index.js | 27 + .../node_modules/commander/index.js | 24 + .../node_modules/commander/lib/argument.js | 149 + .../node_modules/commander/lib/command.js | 2509 +++ .../node_modules/commander/lib/error.js | 39 + .../node_modules/commander/lib/help.js | 520 + .../node_modules/commander/lib/option.js | 330 + .../commander/lib/suggestSimilar.js | 101 + .../convert-to-spaces/dist/index.js | 4 + .../node_modules/diff/libesm/diff/array.js | 16 + .../node_modules/diff/libesm/diff/base.js | 253 + .../node_modules/diff/libesm/diff/line.js | 65 + .../node_modules/diff/libesm/diff/word.js | 296 + .../node_modules/diff/libesm/index.js | 30 + .../node_modules/diff/libesm/patch/create.js | 228 + .../node_modules/diff/libesm/util/string.js | 128 + .../dist/dom-mutator.cjs.production.min.js | 2 + .../node_modules/emoji-regex/index.js | 6 + .../node_modules/env-paths/index.js | 68 + .../eventsource-parser/dist/index.js | 106 + .../eventsource-parser/dist/stream.js | 29 + .../node_modules/eventsource/dist/index.js | 273 + .../node_modules/execa/index.js | 309 + .../node_modules/execa/lib/command.js | 119 + .../node_modules/execa/lib/error.js | 87 + .../node_modules/execa/lib/kill.js | 102 + .../node_modules/execa/lib/pipe.js | 42 + .../node_modules/execa/lib/promise.js | 36 + .../node_modules/execa/lib/stdio.js | 49 + .../node_modules/execa/lib/stream.js | 133 + .../node_modules/execa/lib/verbose.js | 19 + .../node_modules/fflate/esm/index.mjs | 2679 ++++ .../node_modules/figures/index.js | 292 + .../node_modules/fuse.js/dist/fuse.mjs | 1778 +++ .../gaxios/node_modules/uuid/dist/index.js | 79 + .../gaxios/node_modules/uuid/dist/md5.js | 23 + .../gaxios/node_modules/uuid/dist/native.js | 15 + .../gaxios/node_modules/uuid/dist/nil.js | 8 + .../gaxios/node_modules/uuid/dist/parse.js | 45 + .../gaxios/node_modules/uuid/dist/regex.js | 8 + .../gaxios/node_modules/uuid/dist/rng.js | 24 + .../gaxios/node_modules/uuid/dist/sha1.js | 23 + .../node_modules/uuid/dist/stringify.js | 44 + .../gaxios/node_modules/uuid/dist/v1.js | 107 + .../gaxios/node_modules/uuid/dist/v3.js | 16 + .../gaxios/node_modules/uuid/dist/v35.js | 80 + .../gaxios/node_modules/uuid/dist/v4.js | 43 + .../gaxios/node_modules/uuid/dist/v5.js | 16 + .../gaxios/node_modules/uuid/dist/validate.js | 17 + .../gaxios/node_modules/uuid/dist/version.js | 21 + .../get-east-asian-width/index.js | 30 + .../get-east-asian-width/lookup.js | 403 + .../build/src/auth/authclient.js | 116 + .../build/src/auth/awsclient.js | 164 + .../build/src/auth/awsrequestsigner.js | 209 + .../build/src/auth/baseexternalclient.js | 468 + .../build/src/auth/computeclient.js | 117 + .../defaultawssecuritycredentialssupplier.js | 196 + .../build/src/auth/downscopedclient.js | 262 + .../build/src/auth/envDetect.js | 89 + .../build/src/auth/executable-response.js | 146 + .../externalAccountAuthorizedUserClient.js | 239 + .../build/src/auth/externalclient.js | 64 + .../src/auth/filesubjecttokensupplier.js | 81 + .../build/src/auth/googleauth.js | 841 + .../google-auth-library/build/src/auth/iam.js | 41 + .../build/src/auth/identitypoolclient.js | 107 + .../build/src/auth/idtokenclient.js | 55 + .../build/src/auth/impersonated.js | 186 + .../build/src/auth/jwtaccess.js | 192 + .../build/src/auth/jwtclient.js | 284 + .../build/src/auth/loginticket.js | 57 + .../build/src/auth/oauth2client.js | 794 + .../build/src/auth/oauth2common.js | 192 + .../build/src/auth/passthrough.js | 61 + .../build/src/auth/pluggable-auth-client.js | 215 + .../build/src/auth/pluggable-auth-handler.js | 156 + .../build/src/auth/refreshclient.js | 132 + .../build/src/auth/stscredentials.js | 109 + .../build/src/auth/urlsubjecttokensupplier.js | 63 + .../build/src/crypto/browser/crypto.js | 126 + .../build/src/crypto/crypto.js | 47 + .../build/src/crypto/node/crypto.js | 82 + .../google-auth-library/build/src/index.js | 68 + .../google-auth-library/build/src/options.js | 34 + .../build/src/transporters.js | 110 + .../google-auth-library/build/src/util.js | 125 + .../node_modules/highlight.js/lib/core.js | 2517 +++ .../node_modules/highlight.js/lib/index.js | 195 + .../highlight.js/lib/languages/1c.js | 521 + .../highlight.js/lib/languages/abnf.js | 103 + .../highlight.js/lib/languages/accesslog.js | 127 + .../lib/languages/actionscript.js | 113 + .../highlight.js/lib/languages/ada.js | 194 + .../highlight.js/lib/languages/angelscript.js | 123 + .../highlight.js/lib/languages/apache.js | 89 + .../highlight.js/lib/languages/applescript.js | 189 + .../highlight.js/lib/languages/arcade.js | 165 + .../highlight.js/lib/languages/arduino.js | 576 + .../highlight.js/lib/languages/armasm.js | 131 + .../highlight.js/lib/languages/asciidoc.js | 303 + .../highlight.js/lib/languages/aspectj.js | 186 + .../highlight.js/lib/languages/autohotkey.js | 84 + .../highlight.js/lib/languages/autoit.js | 183 + .../highlight.js/lib/languages/avrasm.js | 80 + .../highlight.js/lib/languages/awk.js | 73 + .../highlight.js/lib/languages/axapta.js | 179 + .../highlight.js/lib/languages/bash.js | 169 + .../highlight.js/lib/languages/basic.js | 65 + .../highlight.js/lib/languages/bnf.js | 38 + .../highlight.js/lib/languages/brainfuck.js | 46 + .../highlight.js/lib/languages/c-like.js | 501 + .../highlight.js/lib/languages/c.js | 309 + .../highlight.js/lib/languages/cal.js | 104 + .../highlight.js/lib/languages/capnproto.js | 64 + .../highlight.js/lib/languages/ceylon.js | 82 + .../highlight.js/lib/languages/clean.js | 40 + .../lib/languages/clojure-repl.js | 27 + .../highlight.js/lib/languages/clojure.js | 158 + .../highlight.js/lib/languages/cmake.js | 64 + .../lib/languages/coffeescript.js | 356 + .../highlight.js/lib/languages/coq.js | 79 + .../highlight.js/lib/languages/cos.js | 138 + .../highlight.js/lib/languages/cpp.js | 464 + .../highlight.js/lib/languages/crmsh.js | 102 + .../highlight.js/lib/languages/crystal.js | 326 + .../highlight.js/lib/languages/csharp.js | 441 + .../highlight.js/lib/languages/csp.js | 37 + .../highlight.js/lib/languages/css.js | 608 + .../highlight.js/lib/languages/d.js | 271 + .../highlight.js/lib/languages/dart.js | 199 + .../highlight.js/lib/languages/delphi.js | 126 + .../highlight.js/lib/languages/diff.js | 85 + .../highlight.js/lib/languages/django.js | 77 + .../highlight.js/lib/languages/dns.js | 46 + .../highlight.js/lib/languages/dockerfile.js | 34 + .../highlight.js/lib/languages/dos.js | 70 + .../highlight.js/lib/languages/dsconfig.js | 66 + .../highlight.js/lib/languages/dts.js | 153 + .../highlight.js/lib/languages/dust.js | 45 + .../highlight.js/lib/languages/ebnf.js | 53 + .../highlight.js/lib/languages/elixir.js | 259 + .../highlight.js/lib/languages/elm.js | 129 + .../highlight.js/lib/languages/erb.js | 29 + .../highlight.js/lib/languages/erlang-repl.js | 86 + .../highlight.js/lib/languages/erlang.js | 199 + .../highlight.js/lib/languages/excel.js | 64 + .../highlight.js/lib/languages/fix.js | 37 + .../highlight.js/lib/languages/flix.js | 54 + .../highlight.js/lib/languages/fortran.js | 159 + .../highlight.js/lib/languages/fsharp.js | 86 + .../highlight.js/lib/languages/gams.js | 208 + .../highlight.js/lib/languages/gauss.js | 316 + .../highlight.js/lib/languages/gcode.js | 88 + .../highlight.js/lib/languages/gherkin.js | 49 + .../highlight.js/lib/languages/glsl.js | 128 + .../highlight.js/lib/languages/gml.js | 885 + .../highlight.js/lib/languages/go.js | 74 + .../highlight.js/lib/languages/golo.js | 33 + .../highlight.js/lib/languages/gradle.js | 44 + .../highlight.js/lib/languages/groovy.js | 174 + .../highlight.js/lib/languages/haml.js | 117 + .../highlight.js/lib/languages/handlebars.js | 324 + .../highlight.js/lib/languages/haskell.js | 173 + .../highlight.js/lib/languages/haxe.js | 157 + .../highlight.js/lib/languages/hsp.js | 65 + .../highlight.js/lib/languages/htmlbars.js | 352 + .../highlight.js/lib/languages/http.js | 121 + .../highlight.js/lib/languages/hy.js | 109 + .../highlight.js/lib/languages/inform7.js | 70 + .../highlight.js/lib/languages/ini.js | 173 + .../highlight.js/lib/languages/irpf90.js | 141 + .../highlight.js/lib/languages/isbl.js | 3207 ++++ .../highlight.js/lib/languages/java.js | 181 + .../highlight.js/lib/languages/javascript.js | 604 + .../highlight.js/lib/languages/jboss-cli.js | 63 + .../highlight.js/lib/languages/json.js | 63 + .../highlight.js/lib/languages/julia-repl.js | 50 + .../highlight.js/lib/languages/julia.js | 416 + .../highlight.js/lib/languages/kotlin.js | 284 + .../highlight.js/lib/languages/lasso.js | 187 + .../highlight.js/lib/languages/latex.js | 276 + .../highlight.js/lib/languages/ldif.js | 42 + .../highlight.js/lib/languages/leaf.js | 49 + .../highlight.js/lib/languages/less.js | 666 + .../highlight.js/lib/languages/lisp.js | 111 + .../lib/languages/livecodeserver.js | 189 + .../highlight.js/lib/languages/livescript.js | 374 + .../highlight.js/lib/languages/llvm.js | 154 + .../highlight.js/lib/languages/lsl.js | 95 + .../highlight.js/lib/languages/lua.js | 82 + .../highlight.js/lib/languages/makefile.js | 92 + .../highlight.js/lib/languages/markdown.js | 258 + .../highlight.js/lib/languages/mathematica.js | 6797 ++++++++ .../highlight.js/lib/languages/matlab.js | 106 + .../highlight.js/lib/languages/maxima.js | 417 + .../highlight.js/lib/languages/mel.js | 236 + .../highlight.js/lib/languages/mercury.js | 121 + .../highlight.js/lib/languages/mipsasm.js | 109 + .../highlight.js/lib/languages/mizar.js | 29 + .../highlight.js/lib/languages/mojolicious.js | 36 + .../highlight.js/lib/languages/monkey.js | 89 + .../highlight.js/lib/languages/moonscript.js | 147 + .../highlight.js/lib/languages/n1ql.js | 77 + .../highlight.js/lib/languages/nginx.js | 140 + .../highlight.js/lib/languages/nim.js | 79 + .../highlight.js/lib/languages/nix.js | 65 + .../highlight.js/lib/languages/node-repl.js | 37 + .../highlight.js/lib/languages/nsis.js | 119 + .../highlight.js/lib/languages/objectivec.js | 121 + .../highlight.js/lib/languages/ocaml.js | 82 + .../highlight.js/lib/languages/openscad.js | 81 + .../highlight.js/lib/languages/oxygene.js | 101 + .../highlight.js/lib/languages/parser3.js | 57 + .../highlight.js/lib/languages/perl.js | 515 + .../highlight.js/lib/languages/pf.js | 59 + .../highlight.js/lib/languages/pgsql.js | 630 + .../lib/languages/php-template.js | 54 + .../highlight.js/lib/languages/php.js | 204 + .../highlight.js/lib/languages/plaintext.js | 19 + .../highlight.js/lib/languages/pony.js | 89 + .../highlight.js/lib/languages/powershell.js | 331 + .../highlight.js/lib/languages/processing.js | 58 + .../highlight.js/lib/languages/profile.js | 43 + .../highlight.js/lib/languages/prolog.js | 102 + .../highlight.js/lib/languages/properties.js | 85 + .../highlight.js/lib/languages/protobuf.js | 47 + .../highlight.js/lib/languages/puppet.js | 147 + .../highlight.js/lib/languages/purebasic.js | 101 + .../highlight.js/lib/languages/python-repl.js | 36 + .../highlight.js/lib/languages/python.js | 446 + .../highlight.js/lib/languages/q.js | 37 + .../highlight.js/lib/languages/qml.js | 225 + .../highlight.js/lib/languages/r.js | 231 + .../highlight.js/lib/languages/reasonml.js | 321 + .../highlight.js/lib/languages/rib.js | 37 + .../highlight.js/lib/languages/roboconf.js | 82 + .../highlight.js/lib/languages/routeros.js | 172 + .../highlight.js/lib/languages/rsl.js | 49 + .../highlight.js/lib/languages/ruby.js | 387 + .../lib/languages/ruleslanguage.js | 78 + .../highlight.js/lib/languages/rust.js | 146 + .../highlight.js/lib/languages/sas.js | 133 + .../highlight.js/lib/languages/scala.js | 140 + .../highlight.js/lib/languages/scheme.js | 207 + .../highlight.js/lib/languages/scilab.js | 73 + .../highlight.js/lib/languages/scss.js | 545 + .../highlight.js/lib/languages/shell.js | 30 + .../highlight.js/lib/languages/smali.js | 135 + .../highlight.js/lib/languages/smalltalk.js | 63 + .../highlight.js/lib/languages/sml.js | 81 + .../highlight.js/lib/languages/sqf.js | 448 + .../highlight.js/lib/languages/sql.js | 699 + .../highlight.js/lib/languages/sql_more.js | 183 + .../highlight.js/lib/languages/stan.js | 548 + .../highlight.js/lib/languages/stata.js | 60 + .../highlight.js/lib/languages/step21.js | 66 + .../highlight.js/lib/languages/stylus.js | 609 + .../highlight.js/lib/languages/subunit.js | 51 + .../highlight.js/lib/languages/swift.js | 873 + .../lib/languages/taggerscript.js | 52 + .../highlight.js/lib/languages/tap.js | 55 + .../highlight.js/lib/languages/tcl.js | 115 + .../highlight.js/lib/languages/thrift.js | 51 + .../highlight.js/lib/languages/tp.js | 95 + .../highlight.js/lib/languages/twig.js | 77 + .../highlight.js/lib/languages/typescript.js | 697 + .../highlight.js/lib/languages/vala.js | 61 + .../highlight.js/lib/languages/vbnet.js | 214 + .../lib/languages/vbscript-html.js | 24 + .../highlight.js/lib/languages/vbscript.js | 109 + .../highlight.js/lib/languages/verilog.js | 131 + .../highlight.js/lib/languages/vhdl.js | 71 + .../highlight.js/lib/languages/vim.js | 123 + .../highlight.js/lib/languages/x86asm.js | 163 + .../highlight.js/lib/languages/xl.js | 92 + .../highlight.js/lib/languages/xml.js | 287 + .../highlight.js/lib/languages/xquery.js | 197 + .../highlight.js/lib/languages/yaml.js | 176 + .../highlight.js/lib/languages/zephir.js | 140 + .../http-proxy-agent/dist/index.js | 148 + .../https-proxy-agent/dist/index.js | 180 + .../dist/parse-proxy-response.js | 101 + .../node_modules/ignore/index.js | 784 + .../node_modules/indent-string/index.js | 38 + claude-code-source/node_modules/ink | 1 + .../jsonc-parser/lib/esm/impl/edit.js | 185 + .../jsonc-parser/lib/esm/impl/format.js | 261 + .../jsonc-parser/lib/esm/impl/parser.js | 632 + .../jsonc-parser/lib/esm/impl/scanner.js | 443 + .../lib/esm/impl/string-intern.js | 29 + .../node_modules/jsonc-parser/lib/esm/main.js | 178 + .../node_modules/lodash-es/_DataView.js | 7 + .../node_modules/lodash-es/_Hash.js | 32 + .../node_modules/lodash-es/_ListCache.js | 32 + .../node_modules/lodash-es/_Map.js | 7 + .../node_modules/lodash-es/_MapCache.js | 32 + .../node_modules/lodash-es/_Promise.js | 7 + .../node_modules/lodash-es/_Set.js | 7 + .../node_modules/lodash-es/_SetCache.js | 27 + .../node_modules/lodash-es/_Stack.js | 27 + .../node_modules/lodash-es/_Symbol.js | 6 + .../node_modules/lodash-es/_Uint8Array.js | 6 + .../node_modules/lodash-es/_WeakMap.js | 7 + .../node_modules/lodash-es/_apply.js | 21 + .../lodash-es/_arrayAggregator.js | 22 + .../node_modules/lodash-es/_arrayEach.js | 22 + .../node_modules/lodash-es/_arrayFilter.js | 25 + .../node_modules/lodash-es/_arrayIncludes.js | 17 + .../lodash-es/_arrayIncludesWith.js | 22 + .../node_modules/lodash-es/_arrayLikeKeys.js | 49 + .../node_modules/lodash-es/_arrayMap.js | 21 + .../node_modules/lodash-es/_arrayPush.js | 20 + .../node_modules/lodash-es/_arraySample.js | 15 + .../node_modules/lodash-es/_arraySome.js | 23 + .../node_modules/lodash-es/_asciiToArray.js | 12 + .../lodash-es/_assignMergeValue.js | 20 + .../node_modules/lodash-es/_assignValue.js | 28 + .../node_modules/lodash-es/_assocIndexOf.js | 21 + .../node_modules/lodash-es/_baseAggregator.js | 21 + .../node_modules/lodash-es/_baseAssign.js | 17 + .../node_modules/lodash-es/_baseAssignIn.js | 17 + .../lodash-es/_baseAssignValue.js | 25 + .../node_modules/lodash-es/_baseClone.js | 166 + .../node_modules/lodash-es/_baseCreate.js | 30 + .../node_modules/lodash-es/_baseEach.js | 14 + .../node_modules/lodash-es/_baseFilter.js | 21 + .../node_modules/lodash-es/_baseFindIndex.js | 24 + .../node_modules/lodash-es/_baseFlatten.js | 38 + .../node_modules/lodash-es/_baseFor.js | 16 + .../node_modules/lodash-es/_baseForOwn.js | 16 + .../node_modules/lodash-es/_baseGet.js | 24 + .../node_modules/lodash-es/_baseGetAllKeys.js | 20 + .../node_modules/lodash-es/_baseGetTag.js | 28 + .../node_modules/lodash-es/_baseHasIn.js | 13 + .../node_modules/lodash-es/_baseIndexOf.js | 20 + .../lodash-es/_baseIsArguments.js | 18 + .../node_modules/lodash-es/_baseIsEqual.js | 28 + .../lodash-es/_baseIsEqualDeep.js | 83 + .../node_modules/lodash-es/_baseIsMap.js | 18 + .../node_modules/lodash-es/_baseIsMatch.js | 62 + .../node_modules/lodash-es/_baseIsNaN.js | 12 + .../node_modules/lodash-es/_baseIsNative.js | 47 + .../node_modules/lodash-es/_baseIsSet.js | 18 + .../lodash-es/_baseIsTypedArray.js | 60 + .../node_modules/lodash-es/_baseIteratee.js | 31 + .../node_modules/lodash-es/_baseKeys.js | 30 + .../node_modules/lodash-es/_baseKeysIn.js | 33 + .../node_modules/lodash-es/_baseMatches.js | 22 + .../lodash-es/_baseMatchesProperty.js | 33 + .../node_modules/lodash-es/_baseMerge.js | 42 + .../node_modules/lodash-es/_baseMergeDeep.js | 94 + .../node_modules/lodash-es/_basePickBy.js | 30 + .../node_modules/lodash-es/_baseProperty.js | 14 + .../lodash-es/_basePropertyDeep.js | 16 + .../node_modules/lodash-es/_baseRandom.js | 18 + .../node_modules/lodash-es/_baseRest.js | 17 + .../node_modules/lodash-es/_baseSample.js | 15 + .../node_modules/lodash-es/_baseSet.js | 51 + .../lodash-es/_baseSetToString.js | 22 + .../node_modules/lodash-es/_baseSlice.js | 31 + .../node_modules/lodash-es/_baseSum.js | 24 + .../node_modules/lodash-es/_baseTimes.js | 20 + .../node_modules/lodash-es/_baseToString.js | 37 + .../node_modules/lodash-es/_baseTrim.js | 19 + .../node_modules/lodash-es/_baseUnary.js | 14 + .../node_modules/lodash-es/_baseUniq.js | 72 + .../node_modules/lodash-es/_baseUnset.js | 65 + .../node_modules/lodash-es/_baseValues.js | 19 + .../node_modules/lodash-es/_baseZipObject.js | 23 + .../node_modules/lodash-es/_cacheHas.js | 13 + .../node_modules/lodash-es/_castPath.js | 21 + .../node_modules/lodash-es/_castSlice.js | 18 + .../lodash-es/_cloneArrayBuffer.js | 16 + .../node_modules/lodash-es/_cloneBuffer.js | 35 + .../node_modules/lodash-es/_cloneDataView.js | 16 + .../node_modules/lodash-es/_cloneRegExp.js | 17 + .../node_modules/lodash-es/_cloneSymbol.js | 18 + .../lodash-es/_cloneTypedArray.js | 16 + .../node_modules/lodash-es/_copyArray.js | 20 + .../node_modules/lodash-es/_copyObject.js | 40 + .../node_modules/lodash-es/_copySymbols.js | 16 + .../node_modules/lodash-es/_copySymbolsIn.js | 16 + .../node_modules/lodash-es/_coreJsData.js | 6 + .../lodash-es/_createAggregator.js | 23 + .../node_modules/lodash-es/_createAssigner.js | 37 + .../node_modules/lodash-es/_createBaseEach.js | 32 + .../node_modules/lodash-es/_createBaseFor.js | 25 + .../lodash-es/_createCaseFirst.js | 33 + .../node_modules/lodash-es/_createSet.js | 19 + .../lodash-es/_customOmitClone.js | 16 + .../node_modules/lodash-es/_defineProperty.js | 11 + .../node_modules/lodash-es/_equalArrays.js | 84 + .../node_modules/lodash-es/_equalByTag.js | 112 + .../node_modules/lodash-es/_equalObjects.js | 90 + .../node_modules/lodash-es/_flatRest.js | 16 + .../node_modules/lodash-es/_freeGlobal.js | 4 + .../node_modules/lodash-es/_getAllKeys.js | 16 + .../node_modules/lodash-es/_getAllKeysIn.js | 17 + .../node_modules/lodash-es/_getMapData.js | 18 + .../node_modules/lodash-es/_getMatchData.js | 24 + .../node_modules/lodash-es/_getNative.js | 17 + .../node_modules/lodash-es/_getPrototype.js | 6 + .../node_modules/lodash-es/_getRawTag.js | 46 + .../node_modules/lodash-es/_getSymbols.js | 30 + .../node_modules/lodash-es/_getSymbolsIn.js | 25 + .../node_modules/lodash-es/_getTag.js | 58 + .../node_modules/lodash-es/_getValue.js | 13 + .../node_modules/lodash-es/_hasPath.js | 39 + .../node_modules/lodash-es/_hasUnicode.js | 26 + .../node_modules/lodash-es/_hashClear.js | 15 + .../node_modules/lodash-es/_hashDelete.js | 17 + .../node_modules/lodash-es/_hashGet.js | 30 + .../node_modules/lodash-es/_hashHas.js | 23 + .../node_modules/lodash-es/_hashSet.js | 23 + .../node_modules/lodash-es/_initCloneArray.js | 26 + .../node_modules/lodash-es/_initCloneByTag.js | 77 + .../lodash-es/_initCloneObject.js | 18 + .../node_modules/lodash-es/_isFlattenable.js | 20 + .../node_modules/lodash-es/_isIndex.js | 25 + .../node_modules/lodash-es/_isIterateeCall.js | 30 + .../node_modules/lodash-es/_isKey.js | 29 + .../node_modules/lodash-es/_isKeyable.js | 15 + .../node_modules/lodash-es/_isMasked.js | 20 + .../node_modules/lodash-es/_isPrototype.js | 18 + .../lodash-es/_isStrictComparable.js | 15 + .../node_modules/lodash-es/_listCacheClear.js | 13 + .../lodash-es/_listCacheDelete.js | 35 + .../node_modules/lodash-es/_listCacheGet.js | 19 + .../node_modules/lodash-es/_listCacheHas.js | 16 + .../node_modules/lodash-es/_listCacheSet.js | 26 + .../node_modules/lodash-es/_mapCacheClear.js | 21 + .../node_modules/lodash-es/_mapCacheDelete.js | 18 + .../node_modules/lodash-es/_mapCacheGet.js | 16 + .../node_modules/lodash-es/_mapCacheHas.js | 16 + .../node_modules/lodash-es/_mapCacheSet.js | 22 + .../node_modules/lodash-es/_mapToArray.js | 18 + .../lodash-es/_matchesStrictComparable.js | 20 + .../node_modules/lodash-es/_memoizeCapped.js | 26 + .../node_modules/lodash-es/_nativeCreate.js | 6 + .../node_modules/lodash-es/_nativeKeys.js | 6 + .../node_modules/lodash-es/_nativeKeysIn.js | 20 + .../node_modules/lodash-es/_nodeUtil.js | 30 + .../node_modules/lodash-es/_objectToString.js | 22 + .../node_modules/lodash-es/_overArg.js | 15 + .../node_modules/lodash-es/_overRest.js | 36 + .../node_modules/lodash-es/_parent.js | 16 + .../node_modules/lodash-es/_root.js | 9 + .../node_modules/lodash-es/_safeGet.js | 21 + .../node_modules/lodash-es/_setCacheAdd.js | 19 + .../node_modules/lodash-es/_setCacheHas.js | 14 + .../node_modules/lodash-es/_setToArray.js | 18 + .../node_modules/lodash-es/_setToString.js | 14 + .../node_modules/lodash-es/_shortOut.js | 37 + .../node_modules/lodash-es/_stackClear.js | 15 + .../node_modules/lodash-es/_stackDelete.js | 18 + .../node_modules/lodash-es/_stackGet.js | 14 + .../node_modules/lodash-es/_stackHas.js | 14 + .../node_modules/lodash-es/_stackSet.js | 34 + .../node_modules/lodash-es/_strictIndexOf.js | 23 + .../node_modules/lodash-es/_stringToArray.js | 18 + .../node_modules/lodash-es/_stringToPath.js | 27 + .../node_modules/lodash-es/_toKey.js | 21 + .../node_modules/lodash-es/_toSource.js | 26 + .../lodash-es/_trimmedEndIndex.js | 19 + .../node_modules/lodash-es/_unicodeToArray.js | 40 + .../node_modules/lodash-es/capitalize.js | 23 + .../node_modules/lodash-es/cloneDeep.js | 29 + .../node_modules/lodash-es/constant.js | 26 + .../node_modules/lodash-es/debounce.js | 191 + .../node_modules/lodash-es/eq.js | 37 + .../node_modules/lodash-es/flatten.js | 22 + .../node_modules/lodash-es/get.js | 33 + .../node_modules/lodash-es/hasIn.js | 34 + .../node_modules/lodash-es/identity.js | 21 + .../node_modules/lodash-es/isArguments.js | 36 + .../node_modules/lodash-es/isArray.js | 26 + .../node_modules/lodash-es/isArrayLike.js | 33 + .../lodash-es/isArrayLikeObject.js | 33 + .../node_modules/lodash-es/isBuffer.js | 38 + .../node_modules/lodash-es/isEqual.js | 35 + .../node_modules/lodash-es/isFunction.js | 37 + .../node_modules/lodash-es/isLength.js | 35 + .../node_modules/lodash-es/isMap.js | 27 + .../node_modules/lodash-es/isObject.js | 31 + .../node_modules/lodash-es/isObjectLike.js | 29 + .../node_modules/lodash-es/isPlainObject.js | 62 + .../node_modules/lodash-es/isSet.js | 27 + .../node_modules/lodash-es/isSymbol.js | 29 + .../node_modules/lodash-es/isTypedArray.js | 27 + .../node_modules/lodash-es/keys.js | 37 + .../node_modules/lodash-es/keysIn.js | 32 + .../node_modules/lodash-es/last.js | 20 + .../node_modules/lodash-es/lodash.js | 331 + .../node_modules/lodash-es/mapValues.js | 43 + .../node_modules/lodash-es/memoize.js | 73 + .../node_modules/lodash-es/mergeWith.js | 39 + .../node_modules/lodash-es/negate.js | 40 + .../node_modules/lodash-es/noop.js | 17 + .../node_modules/lodash-es/now.js | 23 + .../node_modules/lodash-es/omit.js | 57 + .../node_modules/lodash-es/partition.js | 43 + .../node_modules/lodash-es/pickBy.js | 37 + .../node_modules/lodash-es/property.js | 32 + .../node_modules/lodash-es/reject.js | 46 + .../node_modules/lodash-es/sample.js | 24 + .../node_modules/lodash-es/setWith.js | 32 + .../node_modules/lodash-es/stubArray.js | 23 + .../node_modules/lodash-es/stubFalse.js | 18 + .../node_modules/lodash-es/sumBy.js | 33 + .../node_modules/lodash-es/throttle.js | 69 + .../node_modules/lodash-es/toNumber.js | 64 + .../node_modules/lodash-es/toPlainObject.js | 32 + .../node_modules/lodash-es/toString.js | 28 + .../node_modules/lodash-es/uniqBy.js | 31 + .../node_modules/lodash-es/upperFirst.js | 22 + .../node_modules/lodash-es/values.js | 34 + .../node_modules/lodash-es/zipObject.js | 24 + .../node_modules/lru-cache/dist/esm/index.js | 1542 ++ .../node_modules/marked/lib/marked.esm.js | 2568 +++ .../node_modules/p-map/index.js | 281 + .../node_modules/picomatch/index.js | 17 + .../node_modules/picomatch/lib/constants.js | 180 + .../node_modules/picomatch/lib/parse.js | 1085 ++ .../node_modules/picomatch/lib/picomatch.js | 341 + .../node_modules/picomatch/lib/scan.js | 391 + .../node_modules/picomatch/lib/utils.js | 72 + .../pkce-challenge/dist/index.node.js | 75 + .../node_modules/proper-lockfile/index.js | 40 + .../proper-lockfile/lib/adapter.js | 85 + .../proper-lockfile/lib/lockfile.js | 342 + .../proper-lockfile/lib/mtime-precision.js | 55 + .../node_modules/signal-exit/index.js | 202 + .../node_modules/signal-exit/signals.js | 53 + .../node_modules/qrcode/lib/browser.js | 76 + .../node_modules/qrcode/lib/can-promise.js | 7 + .../qrcode/lib/core/alignment-pattern.js | 83 + .../qrcode/lib/core/alphanumeric-data.js | 59 + .../qrcode/lib/core/bit-buffer.js | 37 + .../qrcode/lib/core/bit-matrix.js | 65 + .../node_modules/qrcode/lib/core/byte-data.js | 30 + .../qrcode/lib/core/error-correction-code.js | 135 + .../qrcode/lib/core/error-correction-level.js | 50 + .../qrcode/lib/core/finder-pattern.js | 22 + .../qrcode/lib/core/format-info.js | 29 + .../qrcode/lib/core/galois-field.js | 69 + .../qrcode/lib/core/kanji-data.js | 54 + .../qrcode/lib/core/mask-pattern.js | 234 + .../node_modules/qrcode/lib/core/mode.js | 167 + .../qrcode/lib/core/numeric-data.js | 43 + .../qrcode/lib/core/polynomial.js | 62 + .../node_modules/qrcode/lib/core/qrcode.js | 495 + .../qrcode/lib/core/reed-solomon-encoder.js | 56 + .../node_modules/qrcode/lib/core/regex.js | 31 + .../node_modules/qrcode/lib/core/segments.js | 330 + .../node_modules/qrcode/lib/core/utils.js | 63 + .../qrcode/lib/core/version-check.js | 9 + .../node_modules/qrcode/lib/core/version.js | 163 + .../qrcode/lib/renderer/canvas.js | 63 + .../node_modules/qrcode/lib/renderer/png.js | 78 + .../qrcode/lib/renderer/svg-tag.js | 81 + .../node_modules/qrcode/lib/renderer/svg.js | 19 + .../qrcode/lib/renderer/terminal.js | 9 + .../lib/renderer/terminal/terminal-small.js | 85 + .../qrcode/lib/renderer/terminal/terminal.js | 49 + .../node_modules/qrcode/lib/renderer/utf8.js | 71 + .../node_modules/qrcode/lib/renderer/utils.js | 99 + .../node_modules/qrcode/lib/server.js | 138 + .../react-reconciler-constants.production.js | 18 + .../cjs/react-reconciler.production.js | 11639 ++++++++++++++ .../scheduler/cjs/scheduler.production.js | 340 + .../cjs/react-compiler-runtime.production.js | 16 + .../react/cjs/react.production.js | 542 + .../node_modules/semver/classes/comparator.js | 143 + .../node_modules/semver/classes/range.js | 556 + .../node_modules/semver/classes/semver.js | 319 + .../node_modules/semver/functions/clean.js | 8 + .../node_modules/semver/functions/cmp.js | 54 + .../node_modules/semver/functions/coerce.js | 62 + .../semver/functions/compare-build.js | 9 + .../semver/functions/compare-loose.js | 5 + .../node_modules/semver/functions/compare.js | 7 + .../node_modules/semver/functions/diff.js | 60 + .../node_modules/semver/functions/eq.js | 5 + .../node_modules/semver/functions/gt.js | 5 + .../node_modules/semver/functions/gte.js | 5 + .../node_modules/semver/functions/inc.js | 21 + .../node_modules/semver/functions/lt.js | 5 + .../node_modules/semver/functions/lte.js | 5 + .../node_modules/semver/functions/major.js | 5 + .../node_modules/semver/functions/minor.js | 5 + .../node_modules/semver/functions/neq.js | 5 + .../node_modules/semver/functions/parse.js | 18 + .../node_modules/semver/functions/patch.js | 5 + .../semver/functions/prerelease.js | 8 + .../node_modules/semver/functions/rcompare.js | 5 + .../node_modules/semver/functions/rsort.js | 5 + .../semver/functions/satisfies.js | 12 + .../node_modules/semver/functions/sort.js | 5 + .../node_modules/semver/functions/valid.js | 8 + .../node_modules/semver/index.js | 91 + .../node_modules/semver/internal/constants.js | 37 + .../node_modules/semver/internal/debug.js | 11 + .../semver/internal/identifiers.js | 25 + .../node_modules/semver/internal/lrucache.js | 42 + .../semver/internal/parse-options.js | 17 + .../node_modules/semver/internal/re.js | 223 + .../node_modules/semver/ranges/gtr.js | 6 + .../node_modules/semver/ranges/intersects.js | 9 + .../node_modules/semver/ranges/ltr.js | 6 + .../semver/ranges/max-satisfying.js | 27 + .../semver/ranges/min-satisfying.js | 26 + .../node_modules/semver/ranges/min-version.js | 63 + .../node_modules/semver/ranges/outside.js | 82 + .../node_modules/semver/ranges/simplify.js | 49 + .../node_modules/semver/ranges/subset.js | 249 + .../semver/ranges/to-comparators.js | 10 + .../node_modules/semver/ranges/valid.js | 13 + .../node_modules/shell-quote/index.js | 4 + .../node_modules/shell-quote/parse.js | 226 + .../node_modules/shell-quote/quote.js | 19 + .../signal-exit/dist/mjs/index.js | 275 + .../signal-exit/dist/mjs/signals.js | 39 + .../node_modules/stack-utils/index.js | 344 + .../escape-string-regexp/index.js | 11 + .../node_modules/strip-ansi/index.js | 14 + .../node_modules/supports-hyperlinks/index.js | 100 + .../node_modules/supports-color/index.js | 135 + .../node_modules/tree-kill/index.js | 118 + .../node_modules/turndown/lib/turndown.cjs.js | 947 ++ claude-code-source/node_modules/type-fest | 1 + claude-code-source/node_modules/typescript | 1 + .../node_modules/undici/index.js | 169 + .../undici/lib/api/abort-signal.js | 57 + .../undici/lib/api/api-connect.js | 108 + .../undici/lib/api/api-pipeline.js | 251 + .../undici/lib/api/api-request.js | 214 + .../node_modules/undici/lib/api/api-stream.js | 220 + .../undici/lib/api/api-upgrade.js | 108 + .../node_modules/undici/lib/api/index.js | 7 + .../node_modules/undici/lib/api/readable.js | 385 + .../node_modules/undici/lib/api/util.js | 93 + .../node_modules/undici/lib/core/connect.js | 240 + .../node_modules/undici/lib/core/constants.js | 118 + .../undici/lib/core/diagnostics.js | 202 + .../node_modules/undici/lib/core/errors.js | 406 + .../node_modules/undici/lib/core/request.js | 395 + .../node_modules/undici/lib/core/symbols.js | 67 + .../node_modules/undici/lib/core/tree.js | 152 + .../node_modules/undici/lib/core/util.js | 719 + .../undici/lib/dispatcher/agent.js | 129 + .../undici/lib/dispatcher/balanced-pool.js | 209 + .../undici/lib/dispatcher/client-h1.js | 1370 ++ .../undici/lib/dispatcher/client-h2.js | 744 + .../undici/lib/dispatcher/client.js | 622 + .../undici/lib/dispatcher/dispatcher-base.js | 190 + .../undici/lib/dispatcher/dispatcher.js | 65 + .../lib/dispatcher/env-http-proxy-agent.js | 160 + .../undici/lib/dispatcher/fixed-queue.js | 117 + .../undici/lib/dispatcher/pool-base.js | 194 + .../undici/lib/dispatcher/pool-stats.js | 34 + .../undici/lib/dispatcher/pool.js | 107 + .../undici/lib/dispatcher/proxy-agent.js | 274 + .../undici/lib/dispatcher/retry-agent.js | 35 + .../node_modules/undici/lib/global.js | 32 + .../undici/lib/handler/decorator-handler.js | 44 + .../undici/lib/handler/redirect-handler.js | 232 + .../undici/lib/handler/retry-handler.js | 374 + .../undici/lib/interceptor/dns.js | 375 + .../undici/lib/interceptor/dump.js | 123 + .../lib/interceptor/redirect-interceptor.js | 21 + .../undici/lib/interceptor/redirect.js | 24 + .../undici/lib/interceptor/retry.js | 19 + .../undici/lib/llhttp/constants.js | 278 + .../undici/lib/llhttp/llhttp-wasm.js | 5 + .../undici/lib/llhttp/llhttp_simd-wasm.js | 5 + .../node_modules/undici/lib/llhttp/utils.js | 15 + .../undici/lib/mock/mock-agent.js | 160 + .../undici/lib/mock/mock-client.js | 59 + .../undici/lib/mock/mock-errors.js | 28 + .../undici/lib/mock/mock-interceptor.js | 207 + .../node_modules/undici/lib/mock/mock-pool.js | 59 + .../undici/lib/mock/mock-symbols.js | 23 + .../undici/lib/mock/mock-utils.js | 367 + .../mock/pending-interceptors-formatter.js | 43 + .../undici/lib/mock/pluralizer.js | 29 + .../node_modules/undici/lib/util/timers.js | 423 + .../undici/lib/web/cache/cache.js | 859 + .../undici/lib/web/cache/cachestorage.js | 152 + .../undici/lib/web/cache/symbols.js | 5 + .../node_modules/undici/lib/web/cache/util.js | 45 + .../undici/lib/web/cookies/constants.js | 12 + .../undici/lib/web/cookies/index.js | 184 + .../undici/lib/web/cookies/parse.js | 317 + .../undici/lib/web/cookies/util.js | 282 + .../lib/web/eventsource/eventsource-stream.js | 398 + .../undici/lib/web/eventsource/eventsource.js | 480 + .../undici/lib/web/eventsource/util.js | 37 + .../node_modules/undici/lib/web/fetch/body.js | 529 + .../undici/lib/web/fetch/constants.js | 124 + .../undici/lib/web/fetch/data-url.js | 744 + .../lib/web/fetch/dispatcher-weakref.js | 46 + .../node_modules/undici/lib/web/fetch/file.js | 126 + .../undici/lib/web/fetch/formdata-parser.js | 474 + .../undici/lib/web/fetch/formdata.js | 252 + .../undici/lib/web/fetch/global.js | 40 + .../undici/lib/web/fetch/headers.js | 687 + .../undici/lib/web/fetch/index.js | 2272 +++ .../undici/lib/web/fetch/request.js | 1037 ++ .../undici/lib/web/fetch/response.js | 610 + .../undici/lib/web/fetch/symbols.js | 9 + .../node_modules/undici/lib/web/fetch/util.js | 1632 ++ .../undici/lib/web/fetch/webidl.js | 695 + .../undici/lib/web/fileapi/encoding.js | 290 + .../undici/lib/web/fileapi/filereader.js | 344 + .../undici/lib/web/fileapi/progressevent.js | 78 + .../undici/lib/web/fileapi/symbols.js | 10 + .../undici/lib/web/fileapi/util.js | 391 + .../undici/lib/web/websocket/connection.js | 371 + .../undici/lib/web/websocket/constants.js | 66 + .../undici/lib/web/websocket/events.js | 329 + .../undici/lib/web/websocket/frame.js | 96 + .../lib/web/websocket/permessage-deflate.js | 70 + .../undici/lib/web/websocket/receiver.js | 424 + .../undici/lib/web/websocket/sender.js | 104 + .../undici/lib/web/websocket/symbols.js | 12 + .../undici/lib/web/websocket/util.js | 314 + .../undici/lib/web/websocket/websocket.js | 588 + .../node_modules/usehooks-ts/dist/index.js | 1046 ++ .../node_modules/uuid/dist/index.js | 79 + .../node_modules/uuid/dist/md5.js | 23 + .../node_modules/uuid/dist/nil.js | 8 + .../node_modules/uuid/dist/parse.js | 45 + .../node_modules/uuid/dist/regex.js | 8 + .../node_modules/uuid/dist/rng.js | 24 + .../node_modules/uuid/dist/sha1.js | 23 + .../node_modules/uuid/dist/stringify.js | 39 + .../node_modules/uuid/dist/v1.js | 107 + .../node_modules/uuid/dist/v3.js | 16 + .../node_modules/uuid/dist/v35.js | 78 + .../node_modules/uuid/dist/v4.js | 37 + .../node_modules/uuid/dist/v5.js | 16 + .../node_modules/uuid/dist/validate.js | 17 + .../node_modules/uuid/dist/version.js | 21 + .../vscode-jsonrpc/lib/common/api.js | 81 + .../vscode-jsonrpc/lib/common/cancellation.js | 96 + .../vscode-jsonrpc/lib/common/connection.js | 1214 ++ .../vscode-jsonrpc/lib/common/disposable.js | 16 + .../vscode-jsonrpc/lib/common/events.js | 128 + .../vscode-jsonrpc/lib/common/is.js | 35 + .../vscode-jsonrpc/lib/common/linkedMap.js | 398 + .../lib/common/messageBuffer.js | 152 + .../lib/common/messageReader.js | 197 + .../lib/common/messageWriter.js | 115 + .../vscode-jsonrpc/lib/common/messages.js | 306 + .../vscode-jsonrpc/lib/common/ral.js | 23 + .../vscode-jsonrpc/lib/common/semaphore.js | 68 + .../lib/common/sharedArrayCancellation.js | 76 + .../vscode-jsonrpc/lib/node/main.js | 257 + .../vscode-jsonrpc/lib/node/ril.js | 161 + .../vscode-languageserver-protocol | 1 + .../node_modules/vscode-languageserver-types | 1 + .../node_modules/wrap-ansi/index.js | 222 + .../node_modules/string-width/index.js | 82 + .../node_modules/emoji-regex/index.js | 4 + .../node_modules/ws/lib/buffer-util.js | 131 + .../node_modules/ws/lib/constants.js | 18 + .../node_modules/ws/lib/event-target.js | 292 + .../node_modules/ws/lib/extension.js | 203 + .../node_modules/ws/lib/limiter.js | 55 + .../node_modules/ws/lib/permessage-deflate.js | 528 + .../node_modules/ws/lib/receiver.js | 706 + .../node_modules/ws/lib/sender.js | 602 + .../node_modules/ws/lib/stream.js | 161 + .../node_modules/ws/lib/subprotocol.js | 62 + .../node_modules/ws/lib/validation.js | 152 + .../node_modules/ws/lib/websocket-server.js | 550 + .../node_modules/ws/lib/websocket.js | 1388 ++ .../node_modules/ws/wrapper.mjs | 8 + .../xmlbuilder/lib/DocumentPosition.js | 12 + .../node_modules/xmlbuilder/lib/NodeType.js | 25 + .../node_modules/xmlbuilder/lib/Utility.js | 88 + .../xmlbuilder/lib/WriterState.js | 10 + .../xmlbuilder/lib/XMLAttribute.js | 130 + .../node_modules/xmlbuilder/lib/XMLCData.js | 41 + .../xmlbuilder/lib/XMLCharacterData.js | 86 + .../node_modules/xmlbuilder/lib/XMLComment.js | 41 + .../xmlbuilder/lib/XMLDOMConfiguration.js | 80 + .../xmlbuilder/lib/XMLDOMErrorHandler.js | 20 + .../xmlbuilder/lib/XMLDOMImplementation.js | 55 + .../xmlbuilder/lib/XMLDOMStringList.js | 44 + .../xmlbuilder/lib/XMLDTDAttList.js | 66 + .../xmlbuilder/lib/XMLDTDElement.js | 44 + .../xmlbuilder/lib/XMLDTDEntity.js | 115 + .../xmlbuilder/lib/XMLDTDNotation.js | 66 + .../xmlbuilder/lib/XMLDeclaration.js | 51 + .../node_modules/xmlbuilder/lib/XMLDocType.js | 235 + .../xmlbuilder/lib/XMLDocument.js | 282 + .../xmlbuilder/lib/XMLDocumentCB.js | 650 + .../node_modules/xmlbuilder/lib/XMLDummy.js | 39 + .../node_modules/xmlbuilder/lib/XMLElement.js | 334 + .../xmlbuilder/lib/XMLNamedNodeMap.js | 77 + .../node_modules/xmlbuilder/lib/XMLNode.js | 999 ++ .../xmlbuilder/lib/XMLNodeList.js | 45 + .../lib/XMLProcessingInstruction.js | 56 + .../node_modules/xmlbuilder/lib/XMLRaw.js | 40 + .../xmlbuilder/lib/XMLStreamWriter.js | 209 + .../xmlbuilder/lib/XMLStringWriter.js | 40 + .../xmlbuilder/lib/XMLStringifier.js | 291 + .../node_modules/xmlbuilder/lib/XMLText.js | 82 + .../xmlbuilder/lib/XMLWriterBase.js | 485 + .../node_modules/xmlbuilder/lib/index.js | 120 + .../node_modules/xss/lib/default.js | 461 + .../node_modules/xss/lib/index.js | 51 + .../node_modules/xss/lib/parser.js | 257 + .../node_modules/xss/lib/util.js | 34 + .../node_modules/xss/lib/xss.js | 232 + .../yaml/dist/compose/compose-collection.js | 90 + .../yaml/dist/compose/compose-doc.js | 45 + .../yaml/dist/compose/compose-node.js | 105 + .../yaml/dist/compose/compose-scalar.js | 88 + .../yaml/dist/compose/composer.js | 222 + .../yaml/dist/compose/resolve-block-map.js | 117 + .../yaml/dist/compose/resolve-block-scalar.js | 200 + .../yaml/dist/compose/resolve-block-seq.js | 51 + .../yaml/dist/compose/resolve-end.js | 39 + .../dist/compose/resolve-flow-collection.js | 209 + .../yaml/dist/compose/resolve-flow-scalar.js | 225 + .../yaml/dist/compose/resolve-props.js | 148 + .../dist/compose/util-contains-newline.js | 36 + .../compose/util-empty-scalar-position.js | 28 + .../dist/compose/util-flow-indent-check.js | 17 + .../yaml/dist/compose/util-map-includes.js | 15 + .../node_modules/yaml/dist/doc/Document.js | 337 + .../node_modules/yaml/dist/doc/anchors.js | 76 + .../yaml/dist/doc/applyReviver.js | 57 + .../node_modules/yaml/dist/doc/createNode.js | 90 + .../node_modules/yaml/dist/doc/directives.js | 178 + .../node_modules/yaml/dist/errors.js | 62 + .../node_modules/yaml/dist/index.js | 50 + .../node_modules/yaml/dist/log.js | 19 + .../node_modules/yaml/dist/nodes/Alias.js | 116 + .../yaml/dist/nodes/Collection.js | 151 + .../node_modules/yaml/dist/nodes/Node.js | 40 + .../node_modules/yaml/dist/nodes/Pair.js | 39 + .../node_modules/yaml/dist/nodes/Scalar.js | 27 + .../node_modules/yaml/dist/nodes/YAMLMap.js | 147 + .../node_modules/yaml/dist/nodes/YAMLSeq.js | 115 + .../yaml/dist/nodes/addPairToJSMap.js | 65 + .../node_modules/yaml/dist/nodes/identity.js | 53 + .../node_modules/yaml/dist/nodes/toJS.js | 39 + .../yaml/dist/parse/cst-scalar.js | 218 + .../yaml/dist/parse/cst-stringify.js | 63 + .../node_modules/yaml/dist/parse/cst-visit.js | 99 + .../node_modules/yaml/dist/parse/cst.js | 112 + .../node_modules/yaml/dist/parse/lexer.js | 719 + .../yaml/dist/parse/line-counter.js | 41 + .../node_modules/yaml/dist/parse/parser.js | 972 ++ .../node_modules/yaml/dist/public-api.js | 107 + .../node_modules/yaml/dist/schema/Schema.js | 39 + .../yaml/dist/schema/common/map.js | 19 + .../yaml/dist/schema/common/null.js | 17 + .../yaml/dist/schema/common/seq.js | 19 + .../yaml/dist/schema/common/string.js | 16 + .../yaml/dist/schema/core/bool.js | 21 + .../yaml/dist/schema/core/float.js | 47 + .../node_modules/yaml/dist/schema/core/int.js | 42 + .../yaml/dist/schema/core/schema.js | 25 + .../yaml/dist/schema/json/schema.js | 64 + .../node_modules/yaml/dist/schema/tags.js | 99 + .../yaml/dist/schema/yaml-1.1/binary.js | 70 + .../yaml/dist/schema/yaml-1.1/bool.js | 29 + .../yaml/dist/schema/yaml-1.1/float.js | 50 + .../yaml/dist/schema/yaml-1.1/int.js | 76 + .../yaml/dist/schema/yaml-1.1/merge.js | 68 + .../yaml/dist/schema/yaml-1.1/omap.js | 77 + .../yaml/dist/schema/yaml-1.1/pairs.js | 82 + .../yaml/dist/schema/yaml-1.1/schema.js | 41 + .../yaml/dist/schema/yaml-1.1/set.js | 96 + .../yaml/dist/schema/yaml-1.1/timestamp.js | 105 + .../yaml/dist/stringify/foldFlowLines.js | 151 + .../yaml/dist/stringify/stringify.js | 131 + .../dist/stringify/stringifyCollection.js | 145 + .../yaml/dist/stringify/stringifyComment.js | 24 + .../yaml/dist/stringify/stringifyDocument.js | 87 + .../yaml/dist/stringify/stringifyNumber.js | 26 + .../yaml/dist/stringify/stringifyPair.js | 152 + .../yaml/dist/stringify/stringifyString.js | 338 + .../node_modules/yaml/dist/visit.js | 236 + .../zod-to-json-schema/dist/esm/Options.js | 46 + .../zod-to-json-schema/dist/esm/Refs.js | 22 + .../zod-to-json-schema/dist/esm/index.js | 40 + .../zod-to-json-schema/dist/esm/parseDef.js | 62 + .../dist/esm/parsers/array.js | 26 + .../dist/esm/parsers/branded.js | 4 + .../dist/esm/parsers/catch.js | 4 + .../dist/esm/parsers/default.js | 7 + .../dist/esm/parsers/effects.js | 7 + .../dist/esm/parsers/intersection.js | 52 + .../dist/esm/parsers/map.js | 26 + .../dist/esm/parsers/never.js | 11 + .../dist/esm/parsers/nullable.js | 33 + .../dist/esm/parsers/object.js | 72 + .../dist/esm/parsers/optional.js | 21 + .../dist/esm/parsers/pipeline.js | 20 + .../dist/esm/parsers/promise.js | 4 + .../dist/esm/parsers/readonly.js | 4 + .../dist/esm/parsers/record.js | 61 + .../dist/esm/parsers/set.js | 20 + .../dist/esm/parsers/string.js | 352 + .../dist/esm/parsers/tuple.js | 32 + .../dist/esm/parsers/undefined.js | 6 + .../dist/esm/parsers/union.js | 80 + .../dist/esm/parsers/unknown.js | 4 + .../dist/esm/selectParser.js | 105 + .../dist/esm/zodToJsonSchema.js | 87 + claude-code-source/node_modules/zod/index.js | 4 + .../node_modules/zod/v3/ZodError.js | 133 + .../node_modules/zod/v3/errors.js | 9 + .../node_modules/zod/v3/external.js | 6 + .../node_modules/zod/v3/helpers/errorUtil.js | 6 + .../node_modules/zod/v3/helpers/parseUtil.js | 109 + .../node_modules/zod/v3/helpers/util.js | 133 + .../node_modules/zod/v3/locales/en.js | 109 + .../node_modules/zod/v3/types.js | 3693 +++++ .../node_modules/zod/v4-mini/index.js | 1 + .../node_modules/zod/v4/classic/checks.js | 1 + .../node_modules/zod/v4/classic/coerce.js | 17 + .../node_modules/zod/v4/classic/compat.js | 27 + .../node_modules/zod/v4/classic/errors.js | 41 + .../node_modules/zod/v4/classic/external.js | 18 + .../node_modules/zod/v4/classic/index.js | 4 + .../node_modules/zod/v4/classic/iso.js | 30 + .../node_modules/zod/v4/classic/parse.js | 6 + .../node_modules/zod/v4/classic/schemas.js | 1006 ++ .../node_modules/zod/v4/core/api.js | 906 ++ .../node_modules/zod/v4/core/checks.js | 559 + .../node_modules/zod/v4/core/core.js | 61 + .../node_modules/zod/v4/core/doc.js | 35 + .../node_modules/zod/v4/core/errors.js | 191 + .../node_modules/zod/v4/core/function.js | 75 + .../node_modules/zod/v4/core/index.js | 15 + .../node_modules/zod/v4/core/parse.js | 57 + .../node_modules/zod/v4/core/regexes.js | 95 + .../node_modules/zod/v4/core/registries.js | 42 + .../node_modules/zod/v4/core/schemas.js | 1717 ++ .../zod/v4/core/to-json-schema.js | 825 + .../node_modules/zod/v4/core/util.js | 493 + .../node_modules/zod/v4/core/versions.js | 5 + .../node_modules/zod/v4/index.js | 3 + .../node_modules/zod/v4/locales/ar.js | 116 + .../node_modules/zod/v4/locales/az.js | 115 + .../node_modules/zod/v4/locales/be.js | 164 + .../node_modules/zod/v4/locales/ca.js | 118 + .../node_modules/zod/v4/locales/cs.js | 135 + .../node_modules/zod/v4/locales/de.js | 116 + .../node_modules/zod/v4/locales/en.js | 117 + .../node_modules/zod/v4/locales/eo.js | 116 + .../node_modules/zod/v4/locales/es.js | 117 + .../node_modules/zod/v4/locales/fa.js | 122 + .../node_modules/zod/v4/locales/fi.js | 122 + .../node_modules/zod/v4/locales/fr-CA.js | 117 + .../node_modules/zod/v4/locales/fr.js | 116 + .../node_modules/zod/v4/locales/he.js | 117 + .../node_modules/zod/v4/locales/hu.js | 117 + .../node_modules/zod/v4/locales/id.js | 116 + .../node_modules/zod/v4/locales/index.js | 39 + .../node_modules/zod/v4/locales/it.js | 117 + .../node_modules/zod/v4/locales/ja.js | 115 + .../node_modules/zod/v4/locales/kh.js | 117 + .../node_modules/zod/v4/locales/ko.js | 121 + .../node_modules/zod/v4/locales/mk.js | 118 + .../node_modules/zod/v4/locales/ms.js | 116 + .../node_modules/zod/v4/locales/nl.js | 117 + .../node_modules/zod/v4/locales/no.js | 116 + .../node_modules/zod/v4/locales/ota.js | 117 + .../node_modules/zod/v4/locales/pl.js | 117 + .../node_modules/zod/v4/locales/ps.js | 122 + .../node_modules/zod/v4/locales/pt.js | 116 + .../node_modules/zod/v4/locales/ru.js | 164 + .../node_modules/zod/v4/locales/sl.js | 117 + .../node_modules/zod/v4/locales/sv.js | 118 + .../node_modules/zod/v4/locales/ta.js | 117 + .../node_modules/zod/v4/locales/th.js | 117 + .../node_modules/zod/v4/locales/tr.js | 115 + .../node_modules/zod/v4/locales/ua.js | 117 + .../node_modules/zod/v4/locales/ur.js | 117 + .../node_modules/zod/v4/locales/vi.js | 116 + .../node_modules/zod/v4/locales/zh-CN.js | 116 + .../node_modules/zod/v4/locales/zh-TW.js | 117 + .../node_modules/zod/v4/mini/external.js | 13 + .../node_modules/zod/v4/mini/index.js | 3 + .../node_modules/zod/v4/mini/parse.js | 1 + 2211 files changed, 329136 insertions(+), 84 deletions(-) create mode 100644 claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/ansiCodes.js create mode 100644 claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/diff.js create mode 100644 claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/index.js create mode 100644 claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/reduce.js create mode 100644 claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/styledChars.js create mode 100644 claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/tokenize.js create mode 100644 claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/undo.js create mode 100644 claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/AWS_restJson1.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/client.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/core/auth.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/core/error.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/core/streaming.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/index.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/headers.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/shims.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/utils/env.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/utils/log.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/utils/path.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/utils/values.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/foundry-sdk/client.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/foundry-sdk/core/error.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/foundry-sdk/index.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/headers.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/base64.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/env.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/log.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/sleep.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/uuid.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/values.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/mcpb/dist/cli/init.js create mode 100644 claude-code-source/node_modules/@anthropic-ai/mcpb/dist/cli/pack.js create mode 100644 claude-code-source/node_modules/@anthropic-ai/mcpb/dist/cli/unpack.js create mode 100644 claude-code-source/node_modules/@anthropic-ai/mcpb/dist/index.js create mode 100644 claude-code-source/node_modules/@anthropic-ai/mcpb/dist/node/files.js create mode 100644 claude-code-source/node_modules/@anthropic-ai/mcpb/dist/node/sign.js create mode 100644 claude-code-source/node_modules/@anthropic-ai/mcpb/dist/node/validate.js create mode 100644 claude-code-source/node_modules/@anthropic-ai/mcpb/dist/schemas-loose.js create mode 100644 claude-code-source/node_modules/@anthropic-ai/mcpb/dist/schemas.js create mode 100644 claude-code-source/node_modules/@anthropic-ai/mcpb/dist/shared/config.js create mode 100644 claude-code-source/node_modules/@anthropic-ai/mcpb/dist/shared/log.js create mode 100644 claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/index.js create mode 100644 claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/generate-seccomp-filter.js create mode 100644 claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/http-proxy.js create mode 100644 claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/linux-sandbox-utils.js create mode 100644 claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/macos-sandbox-utils.js create mode 100644 claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/sandbox-config.js create mode 100644 claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/sandbox-manager.js create mode 100644 claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/sandbox-utils.js create mode 100644 claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/sandbox-violation-store.js create mode 100644 claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/socks-proxy.js create mode 100644 claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/utils/debug.js create mode 100644 claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/utils/platform.js create mode 100644 claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/utils/ripgrep.js create mode 100644 claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/utils/which.js create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/client.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/core/api-promise.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/core/error.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/core/pagination.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/core/resource.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/core/streaming.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/core/uploads.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/error.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/index.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/internal/constants.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/internal/decoders/jsonl.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/internal/errors.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/internal/headers.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/internal/parse.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/internal/request-options.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/internal/shims.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/internal/to-file.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/internal/tslib.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/internal/uploads.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/env.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/log.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/path.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/values.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/lib/BetaMessageStream.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/lib/MessageStream.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/lib/beta-parser.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/lib/parser.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/lib/stainless-helper-header.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/lib/tools/BetaToolRunner.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/lib/tools/CompactionControl.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/lib/tools/ToolError.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/beta.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/files.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/models.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/skills/skills.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/skills/versions.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/resources/completions.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/resources/index.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/resources/messages/batches.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/resources/messages/messages.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/resources/models.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/streaming.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/sdk/version.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/vertex-sdk/client.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/vertex-sdk/core/error.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/vertex-sdk/index.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/vertex-sdk/internal/headers.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/vertex-sdk/internal/utils/env.mjs create mode 100644 claude-code-source/node_modules/@anthropic-ai/vertex-sdk/internal/utils/values.mjs create mode 100644 claude-code-source/node_modules/@aws-crypto/crc32/build/main/aws_crc32.js create mode 100644 claude-code-source/node_modules/@aws-crypto/crc32/build/main/index.js create mode 100644 claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/convertToBuffer.js create mode 100644 claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/index.js create mode 100644 claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/isEmptyData.js create mode 100644 claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/numToUint8.js create mode 100644 claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/uint32ArrayFrom.js create mode 100644 claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-crypto/sha256-js/build/RawSha256.js create mode 100644 claude-code-source/node_modules/@aws-crypto/sha256-js/build/constants.js create mode 100644 claude-code-source/node_modules/@aws-crypto/sha256-js/build/index.js create mode 100644 claude-code-source/node_modules/@aws-crypto/sha256-js/build/jsSha256.js create mode 100644 claude-code-source/node_modules/@aws-crypto/sha256-js/node_modules/tslib/tslib.js create mode 100644 claude-code-source/node_modules/@aws-crypto/util/build/convertToBuffer.js create mode 100644 claude-code-source/node_modules/@aws-crypto/util/build/index.js create mode 100644 claude-code-source/node_modules/@aws-crypto/util/build/isEmptyData.js create mode 100644 claude-code-source/node_modules/@aws-crypto/util/build/numToUint8.js create mode 100644 claude-code-source/node_modules/@aws-crypto/util/build/uint32ArrayFrom.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/auth/httpAuthSchemeProvider.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/endpoint/endpointResolver.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/endpoint/ruleset.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/runtimeConfig.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/runtimeConfig.shared.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/eventstream-serde-node/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/eventstream-serde-node/node_modules/@smithy/eventstream-serde-universal/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/protocol-http/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/smithy-client/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/dist-cjs/toBase64.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/auth/httpAuthSchemeProvider.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/endpoint/endpointResolver.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/endpoint/ruleset.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/runtimeConfig.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/runtimeConfig.shared.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/protocol-http/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/smithy-client/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/dist-cjs/toBase64.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/auth/httpAuthSchemeProvider.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/endpoint/endpointResolver.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/endpoint/ruleset.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/runtimeConfig.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/runtimeConfig.shared.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/protocol-http/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/smithy-client/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/types/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/dist-cjs/toBase64.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/auth/httpAuthSchemeProvider.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/endpoint/endpointResolver.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/endpoint/ruleset.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/runtimeConfig.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/runtimeConfig.shared.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/protocol-http/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/smithy-client/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/types/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/dist-cjs/toBase64.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/STSClient.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/auth/httpAuthExtensionConfiguration.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/auth/httpAuthSchemeProvider.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/endpoint/EndpointParameters.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/endpoint/endpointResolver.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/endpoint/ruleset.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/runtimeConfig.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/runtimeConfig.shared.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/runtimeExtensions.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/protocol-http/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/smithy-client/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/dist-cjs/toBase64.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/core/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/core/dist-cjs/submodules/client/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/core/dist-cjs/submodules/httpAuthSchemes/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/core/dist-cjs/submodules/protocols/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/protocol-http/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/node_modules/@smithy/is-array-buffer/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/node_modules/@smithy/util-uri-escape/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/smithy-client/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/types/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js create mode 100644 claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/dist-cjs/toBase64.js create mode 100644 claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-cjs/loadCognitoIdentity-BPNvueUJ.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-provider-env/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/checkUrl.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/fromHttp.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/requestHelpers.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/retry-wrapper.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/protocol-http/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/smithy-client/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-provider-ini/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-provider-login/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-provider-login/node_modules/@smithy/protocol-http/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-provider-login/node_modules/@smithy/types/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-provider-node/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-provider-process/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-provider-sso/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-provider-sso/dist-cjs/loadSso-CVy8iqsZ.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/fromTokenFile.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/fromWebToken.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/createCredentialChain.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromCognitoIdentity.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromCognitoIdentityPool.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromContainerMetadata.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromEnv.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromIni.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromInstanceMetadata.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromLoginCredentials.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromNodeProviderChain.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromProcess.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromSSO.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromTemporaryCredentials.base.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromTemporaryCredentials.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromTokenFile.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromWebToken.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/loadSts.js create mode 100644 claude-code-source/node_modules/@aws-sdk/eventstream-handler-node/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/middleware-eventstream/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/middleware-eventstream/node_modules/@smithy/protocol-http/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/middleware-eventstream/node_modules/@smithy/types/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/middleware-host-header/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/protocol-http/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/types/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/middleware-logger/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/middleware-recursion-detection/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/middleware-recursion-detection/dist-cjs/recursionDetectionMiddleware.js create mode 100644 claude-code-source/node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/protocol-http/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/types/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/middleware-user-agent/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/protocol-http/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/types/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/middleware-websocket/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/querystring-builder/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js create mode 100644 claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/toBase64.js create mode 100644 claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/protocol-http/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/types/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/auth/httpAuthSchemeProvider.js create mode 100644 claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/endpoint/endpointResolver.js create mode 100644 claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/endpoint/ruleset.js create mode 100644 claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/runtimeConfig.js create mode 100644 claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/runtimeConfig.shared.js create mode 100644 claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/auth/httpAuthSchemeProvider.js create mode 100644 claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/endpoint/endpointResolver.js create mode 100644 claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/endpoint/ruleset.js create mode 100644 claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/runtimeConfig.js create mode 100644 claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/runtimeConfig.shared.js create mode 100644 claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/STSClient.js create mode 100644 claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/auth/httpAuthExtensionConfiguration.js create mode 100644 claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/auth/httpAuthSchemeProvider.js create mode 100644 claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/endpoint/EndpointParameters.js create mode 100644 claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/endpoint/endpointResolver.js create mode 100644 claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/endpoint/ruleset.js create mode 100644 claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/runtimeConfig.js create mode 100644 claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/runtimeConfig.shared.js create mode 100644 claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/runtimeExtensions.js create mode 100644 claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/protocol-http/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/smithy-client/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/types/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js create mode 100644 claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/dist-cjs/toBase64.js create mode 100644 claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/region-config-resolver/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/region-config-resolver/dist-cjs/regionConfig/stsRegionDefaultResolver.js create mode 100644 claude-code-source/node_modules/@aws-sdk/token-providers/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/util-endpoints/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/util-format-url/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/util-format-url/node_modules/@smithy/querystring-builder/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/util-format-url/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/util-user-agent-node/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/util-utf8-browser/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/util-utf8-browser/dist-cjs/pureJs.js create mode 100644 claude-code-source/node_modules/@aws-sdk/util-utf8-browser/dist-cjs/whatwgEncodingApi.js create mode 100644 claude-code-source/node_modules/@aws-sdk/xml-builder/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@aws-sdk/xml-builder/dist-cjs/xml-parser.js create mode 100644 claude-code-source/node_modules/@azure/abort-controller/dist/esm/AbortError.js create mode 100644 claude-code-source/node_modules/@azure/abort-controller/dist/esm/index.js create mode 100644 claude-code-source/node_modules/@azure/core-client/dist/commonjs/state.js create mode 100644 claude-code-source/node_modules/@azure/core-client/dist/esm/deserializationPolicy.js create mode 100644 claude-code-source/node_modules/@azure/core-client/dist/esm/httpClientCache.js create mode 100644 claude-code-source/node_modules/@azure/core-client/dist/esm/index.js create mode 100644 claude-code-source/node_modules/@azure/core-client/dist/esm/interfaceHelpers.js create mode 100644 claude-code-source/node_modules/@azure/core-client/dist/esm/interfaces.js create mode 100644 claude-code-source/node_modules/@azure/core-client/dist/esm/log.js create mode 100644 claude-code-source/node_modules/@azure/core-client/dist/esm/operationHelpers.js create mode 100644 claude-code-source/node_modules/@azure/core-client/dist/esm/pipeline.js create mode 100644 claude-code-source/node_modules/@azure/core-client/dist/esm/serializationPolicy.js create mode 100644 claude-code-source/node_modules/@azure/core-client/dist/esm/serializer.js create mode 100644 claude-code-source/node_modules/@azure/core-client/dist/esm/serviceClient.js create mode 100644 claude-code-source/node_modules/@azure/core-client/dist/esm/state.js create mode 100644 claude-code-source/node_modules/@azure/core-client/dist/esm/urlHelpers.js create mode 100644 claude-code-source/node_modules/@azure/core-client/dist/esm/utils.js create mode 100644 claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/constants.js create mode 100644 claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/createPipelineFromOptions.js create mode 100644 claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/defaultHttpClient.js create mode 100644 claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/httpHeaders.js create mode 100644 claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/index.js create mode 100644 claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/log.js create mode 100644 claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/pipeline.js create mode 100644 claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/pipelineRequest.js create mode 100644 claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/agentPolicy.js create mode 100644 claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/bearerTokenAuthenticationPolicy.js create mode 100644 claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/decompressResponsePolicy.js create mode 100644 claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/defaultRetryPolicy.js create mode 100644 claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/formDataPolicy.js create mode 100644 claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/logPolicy.js create mode 100644 claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/multipartPolicy.js create mode 100644 claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/proxyPolicy.js create mode 100644 claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/redirectPolicy.js create mode 100644 claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/retryPolicy.js create mode 100644 claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/setClientRequestIdPolicy.js create mode 100644 claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/tlsPolicy.js create mode 100644 claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/tracingPolicy.js create mode 100644 claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/userAgentPolicy.js create mode 100644 claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/wrapAbortSignalLikePolicy.js create mode 100644 claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/restError.js create mode 100644 claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/file.js create mode 100644 claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/tokenCycler.js create mode 100644 claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/userAgent.js create mode 100644 claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/userAgentPlatform.js create mode 100644 claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/wrapAbortSignal.js create mode 100644 claude-code-source/node_modules/@azure/core-tracing/dist/commonjs/state.js create mode 100644 claude-code-source/node_modules/@azure/core-tracing/dist/esm/index.js create mode 100644 claude-code-source/node_modules/@azure/core-tracing/dist/esm/instrumenter.js create mode 100644 claude-code-source/node_modules/@azure/core-tracing/dist/esm/state.js create mode 100644 claude-code-source/node_modules/@azure/core-tracing/dist/esm/tracingClient.js create mode 100644 claude-code-source/node_modules/@azure/core-tracing/dist/esm/tracingContext.js create mode 100644 claude-code-source/node_modules/@azure/core-util/dist/esm/createAbortablePromise.js create mode 100644 claude-code-source/node_modules/@azure/core-util/dist/esm/delay.js create mode 100644 claude-code-source/node_modules/@azure/core-util/dist/esm/error.js create mode 100644 claude-code-source/node_modules/@azure/core-util/dist/esm/index.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/client/identityClient.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/constants.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/credentials/authorizationCodeCredential.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/credentials/azureCliCredential.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/credentials/azureDeveloperCliCredential.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/credentials/azurePipelinesCredential.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/credentials/azurePowerShellCredential.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/credentials/chainedTokenCredential.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/credentials/clientAssertionCredential.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/credentials/clientCertificateCredential.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/credentials/clientSecretCredential.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/credentials/defaultAzureCredential.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/credentials/deviceCodeCredential.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/credentials/environmentCredential.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/credentials/interactiveBrowserCredential.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/imdsMsi.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/imdsRetryPolicy.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/index.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/tokenExchangeMsi.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/utils.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/credentials/onBehalfOfCredential.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/credentials/usernamePasswordCredential.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/credentials/visualStudioCodeCredential.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/credentials/workloadIdentityCredential.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/errors.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/index.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/msal/msal.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/msal/nodeFlows/msalClient.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/msal/nodeFlows/msalPlugins.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/msal/utils.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/plugins/consumer.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/regionalAuthority.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/tokenProvider.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/util/identityTokenEndpoint.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/util/logging.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/util/processMultiTenantRequest.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/util/processUtils.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/util/scopeUtils.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/util/subscriptionUtils.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/util/tenantIdUtils.js create mode 100644 claude-code-source/node_modules/@azure/identity/dist/esm/util/tracing.js create mode 100644 claude-code-source/node_modules/@azure/logger/dist/esm/index.js create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/account/AccountInfo.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/account/AuthToken.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/account/CcsCredential.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/account/ClientInfo.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/account/TokenClaims.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/authority/Authority.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/authority/AuthorityFactory.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/authority/AuthorityMetadata.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/authority/AuthorityOptions.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/authority/AuthorityType.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/authority/CloudInstanceDiscoveryErrorResponse.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/authority/CloudInstanceDiscoveryResponse.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/authority/OpenIdConfigResponse.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/authority/ProtocolMode.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/authority/RegionDiscovery.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/cache/CacheManager.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/cache/entities/AccountEntity.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/cache/persistence/TokenCacheContext.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/cache/utils/CacheHelpers.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/client/AuthorizationCodeClient.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/client/BaseClient.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/client/RefreshTokenClient.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/client/SilentFlowClient.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/config/ClientConfiguration.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/constants/AADServerParamKeys.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/crypto/ICrypto.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/crypto/PopTokenGenerator.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/error/AuthError.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/error/AuthErrorCodes.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/error/CacheError.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/error/CacheErrorCodes.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/error/ClientAuthError.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/error/ClientAuthErrorCodes.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/error/ClientConfigurationError.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/error/ClientConfigurationErrorCodes.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/error/InteractionRequiredAuthError.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/error/InteractionRequiredAuthErrorCodes.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/error/NetworkError.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/error/ServerError.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/index-node.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/index.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/logger/Logger.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/network/RequestThumbprint.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/network/ThrottlingUtils.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/packageMetadata.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/protocol/Authorize.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/request/RequestParameterBuilder.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/request/ScopeSet.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/response/ResponseHandler.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/telemetry/performance/PerformanceEvent.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/telemetry/performance/StubPerformanceClient.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/telemetry/server/ServerTelemetryManager.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/url/UrlString.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/utils/ClientAssertionUtils.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/utils/Constants.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/utils/FunctionWrappers.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/utils/ProtocolUtils.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/utils/StringUtils.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/utils/TimeUtils.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-common/dist/utils/UrlUtils.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/cache/CacheHelpers.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/cache/NodeStorage.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/cache/TokenCache.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/cache/distributed/DistributedCachePlugin.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/cache/serializer/Deserializer.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/cache/serializer/Serializer.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/client/ClientApplication.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/client/ClientAssertion.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/client/ClientCredentialClient.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/client/ConfidentialClientApplication.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/client/DeviceCodeClient.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentityApplication.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentityClient.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/AppService.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/AzureArc.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/BaseManagedIdentitySource.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/CloudShell.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/Imds.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/MachineLearning.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/ServiceFabric.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/client/OnBehalfOfClient.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/client/PublicClientApplication.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/client/UsernamePasswordClient.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/config/Configuration.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/config/ManagedIdentityId.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/config/ManagedIdentityRequestParameters.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/crypto/CryptoProvider.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/crypto/GuidGenerator.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/crypto/HashUtils.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/crypto/PkceGenerator.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/error/ManagedIdentityError.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/error/ManagedIdentityErrorCodes.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/error/NodeAuthError.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/index.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/internals.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/network/HttpClient.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/network/HttpClientWithRetries.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/network/LoopbackClient.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/packageMetadata.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/protocol/Authorize.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/retry/DefaultManagedIdentityRetryPolicy.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/retry/ExponentialRetryStrategy.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/retry/ImdsRetryPolicy.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/retry/LinearRetryStrategy.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/utils/Constants.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/utils/EncodingUtils.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/utils/NetworkUtils.mjs create mode 100644 claude-code-source/node_modules/@azure/msal-node/dist/utils/TimeUtils.mjs create mode 100644 claude-code-source/node_modules/@commander-js/extra-typings/esm.mjs create mode 100644 claude-code-source/node_modules/@commander-js/extra-typings/index.js create mode 100644 claude-code-source/node_modules/@growthbook/growthbook/dist/esm/GrowthBook.mjs create mode 100644 claude-code-source/node_modules/@growthbook/growthbook/dist/esm/core.mjs create mode 100644 claude-code-source/node_modules/@growthbook/growthbook/dist/esm/feature-repository.mjs create mode 100644 claude-code-source/node_modules/@growthbook/growthbook/dist/esm/index.mjs create mode 100644 claude-code-source/node_modules/@growthbook/growthbook/dist/esm/mongrule.mjs create mode 100644 claude-code-source/node_modules/@growthbook/growthbook/dist/esm/util.mjs create mode 100644 claude-code-source/node_modules/@inquirer/confirm/dist/esm/index.mjs create mode 100644 claude-code-source/node_modules/@inquirer/core/dist/esm/index.mjs create mode 100644 claude-code-source/node_modules/@inquirer/core/dist/esm/lib/Separator.mjs create mode 100644 claude-code-source/node_modules/@inquirer/core/dist/esm/lib/create-prompt.mjs create mode 100644 claude-code-source/node_modules/@inquirer/core/dist/esm/lib/errors.mjs create mode 100644 claude-code-source/node_modules/@inquirer/core/dist/esm/lib/hook-engine.mjs create mode 100644 claude-code-source/node_modules/@inquirer/core/dist/esm/lib/key.mjs create mode 100644 claude-code-source/node_modules/@inquirer/core/dist/esm/lib/make-theme.mjs create mode 100644 claude-code-source/node_modules/@inquirer/core/dist/esm/lib/pagination/lines.mjs create mode 100644 claude-code-source/node_modules/@inquirer/core/dist/esm/lib/pagination/position.mjs create mode 100644 claude-code-source/node_modules/@inquirer/core/dist/esm/lib/pagination/use-pagination.mjs create mode 100644 claude-code-source/node_modules/@inquirer/core/dist/esm/lib/promise-polyfill.mjs create mode 100644 claude-code-source/node_modules/@inquirer/core/dist/esm/lib/screen-manager.mjs create mode 100644 claude-code-source/node_modules/@inquirer/core/dist/esm/lib/theme.mjs create mode 100644 claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-effect.mjs create mode 100644 claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-keypress.mjs create mode 100644 claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-memo.mjs create mode 100644 claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-prefix.mjs create mode 100644 claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-ref.mjs create mode 100644 claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-state.mjs create mode 100644 claude-code-source/node_modules/@inquirer/core/dist/esm/lib/utils.mjs create mode 100644 claude-code-source/node_modules/@inquirer/figures/dist/esm/index.js create mode 100644 claude-code-source/node_modules/@inquirer/input/dist/esm/index.mjs create mode 100644 claude-code-source/node_modules/@inquirer/prompts/dist/esm/index.mjs create mode 100644 claude-code-source/node_modules/@inquirer/select/dist/esm/index.mjs create mode 100644 claude-code-source/node_modules/@js-sdsl/ordered-map/dist/cjs/index.js create mode 100644 claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js create mode 100644 claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js create mode 100644 claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js create mode 100644 claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js create mode 100644 claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js create mode 100644 claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js create mode 100644 claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js create mode 100644 claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js create mode 100644 claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js create mode 100644 claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js create mode 100644 claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js create mode 100644 claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js create mode 100644 claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js create mode 100644 claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js create mode 100644 claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js create mode 100644 claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js create mode 100644 claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js create mode 100644 claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js create mode 100644 claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js create mode 100644 claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js create mode 100644 claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api-logs/build/src/NoopLogger.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api-logs/build/src/NoopLoggerProvider.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api-logs/build/src/ProxyLogger.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api-logs/build/src/ProxyLoggerProvider.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api-logs/build/src/api/logs.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api-logs/build/src/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api-logs/build/src/internal/global-utils.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api-logs/build/src/platform/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api-logs/build/src/platform/node/globalThis.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api-logs/build/src/platform/node/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api-logs/build/src/types/LogRecord.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/api/context.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/api/diag.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/api/metrics.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/api/propagation.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/api/trace.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/baggage/context-helpers.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/baggage/internal/baggage-impl.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/baggage/internal/symbol.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/baggage/utils.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/context-api.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/context/NoopContextManager.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/context/context.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/diag-api.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/diag/ComponentLogger.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/diag/consoleLogger.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/diag/internal/logLevelLogger.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/diag/types.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/internal/global-utils.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/internal/semver.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/metrics-api.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/metrics/Metric.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/metrics/NoopMeter.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/metrics/NoopMeterProvider.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/platform/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/platform/node/globalThis.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/platform/node/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/propagation-api.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/propagation/NoopTextMapPropagator.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/propagation/TextMapPropagator.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/trace-api.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/trace/NonRecordingSpan.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/trace/NoopTracer.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/trace/NoopTracerProvider.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/trace/ProxyTracer.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/trace/ProxyTracerProvider.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/trace/SamplingResult.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/trace/context-utils.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-impl.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-validators.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/trace/internal/utils.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/trace/invalid-span-constants.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/trace/span_kind.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/trace/spancontext-utils.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/trace/status.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/trace/trace_flags.js create mode 100644 claude-code-source/node_modules/@opentelemetry/api/build/src/version.js create mode 100644 claude-code-source/node_modules/@opentelemetry/core/build/src/ExportResult.js create mode 100644 claude-code-source/node_modules/@opentelemetry/core/build/src/baggage/constants.js create mode 100644 claude-code-source/node_modules/@opentelemetry/core/build/src/baggage/propagation/W3CBaggagePropagator.js create mode 100644 claude-code-source/node_modules/@opentelemetry/core/build/src/baggage/utils.js create mode 100644 claude-code-source/node_modules/@opentelemetry/core/build/src/common/anchored-clock.js create mode 100644 claude-code-source/node_modules/@opentelemetry/core/build/src/common/attributes.js create mode 100644 claude-code-source/node_modules/@opentelemetry/core/build/src/common/global-error-handler.js create mode 100644 claude-code-source/node_modules/@opentelemetry/core/build/src/common/logging-error-handler.js create mode 100644 claude-code-source/node_modules/@opentelemetry/core/build/src/common/time.js create mode 100644 claude-code-source/node_modules/@opentelemetry/core/build/src/common/timer-util.js create mode 100644 claude-code-source/node_modules/@opentelemetry/core/build/src/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/core/build/src/internal/exporter.js create mode 100644 claude-code-source/node_modules/@opentelemetry/core/build/src/internal/validators.js create mode 100644 claude-code-source/node_modules/@opentelemetry/core/build/src/platform/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/environment.js create mode 100644 claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/globalThis.js create mode 100644 claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/performance.js create mode 100644 claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/sdk-info.js create mode 100644 claude-code-source/node_modules/@opentelemetry/core/build/src/propagation/composite.js create mode 100644 claude-code-source/node_modules/@opentelemetry/core/build/src/semconv.js create mode 100644 claude-code-source/node_modules/@opentelemetry/core/build/src/trace/TraceState.js create mode 100644 claude-code-source/node_modules/@opentelemetry/core/build/src/trace/W3CTraceContextPropagator.js create mode 100644 claude-code-source/node_modules/@opentelemetry/core/build/src/trace/rpc-metadata.js create mode 100644 claude-code-source/node_modules/@opentelemetry/core/build/src/trace/suppress-tracing.js create mode 100644 claude-code-source/node_modules/@opentelemetry/core/build/src/utils/callback.js create mode 100644 claude-code-source/node_modules/@opentelemetry/core/build/src/utils/configuration.js create mode 100644 claude-code-source/node_modules/@opentelemetry/core/build/src/utils/lodash.merge.js create mode 100644 claude-code-source/node_modules/@opentelemetry/core/build/src/utils/merge.js create mode 100644 claude-code-source/node_modules/@opentelemetry/core/build/src/utils/promise.js create mode 100644 claude-code-source/node_modules/@opentelemetry/core/build/src/utils/timeout.js create mode 100644 claude-code-source/node_modules/@opentelemetry/core/build/src/utils/url.js create mode 100644 claude-code-source/node_modules/@opentelemetry/core/build/src/version.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-grpc/build/src/OTLPLogExporter.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-grpc/build/src/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/node/OTLPLogExporter.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/node/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/node/OTLPLogExporter.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/node/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-grpc/build/src/OTLPMetricExporter.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-grpc/build/src/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/OTLPMetricExporterBase.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/OTLPMetricExporterOptions.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/node/OTLPMetricExporter.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/node/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/node/OTLPMetricExporter.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/node/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-prometheus/build/src/PrometheusExporter.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-prometheus/build/src/PrometheusSerializer.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-prometheus/build/src/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-grpc/build/src/OTLPTraceExporter.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-grpc/build/src/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/node/OTLPTraceExporter.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/node/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/node/OTLPTraceExporter.js create mode 100644 claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/node/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/OTLPExporterBase.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/bounded-queue-export-promise-handler.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/convert-legacy-http-options.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/convert-legacy-node-http-options.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/legacy-node-configuration.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/otlp-http-configuration.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/otlp-node-http-configuration.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/otlp-node-http-env-configuration.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/shared-configuration.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/shared-env-configuration.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/index-node-http.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/is-export-retryable.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/logging-response-handler.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/otlp-export-delegate.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/otlp-http-export-delegate.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/otlp-network-export-delegate.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/retrying-transport.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/transport/http-exporter-transport.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/transport/http-transport-utils.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/types.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/util.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/version.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/convert-legacy-otlp-grpc-options.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/otlp-grpc-configuration.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/otlp-grpc-env-configuration.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/create-service-client-constructor.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/grpc-exporter-transport.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/otlp-grpc-export-delegate.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/version.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/common/hex-to-binary.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/common/internal.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/common/utils.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/generated/root.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/internal.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/json/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/json/logs.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/protobuf/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/protobuf/logs.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/internal-types.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/internal.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/json/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/json/metrics.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/protobuf/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/protobuf/metrics.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/internal.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/json/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/json/trace.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/protobuf/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/protobuf/trace.js create mode 100644 claude-code-source/node_modules/@opentelemetry/resources/build/src/ResourceImpl.js create mode 100644 claude-code-source/node_modules/@opentelemetry/resources/build/src/detect-resources.js create mode 100644 claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/EnvDetector.js create mode 100644 claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/NoopDetector.js create mode 100644 claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/HostDetector.js create mode 100644 claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/OSDetector.js create mode 100644 claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/ProcessDetector.js create mode 100644 claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/ServiceInstanceIdDetector.js create mode 100644 claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/execAsync.js create mode 100644 claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-bsd.js create mode 100644 claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-darwin.js create mode 100644 claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-linux.js create mode 100644 claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-unsupported.js create mode 100644 claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-win.js create mode 100644 claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId.js create mode 100644 claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/utils.js create mode 100644 claude-code-source/node_modules/@opentelemetry/resources/build/src/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/resources/build/src/platform/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/resources/build/src/platform/node/default-service-name.js create mode 100644 claude-code-source/node_modules/@opentelemetry/resources/build/src/platform/node/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/resources/build/src/semconv.js create mode 100644 claude-code-source/node_modules/@opentelemetry/resources/build/src/utils.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/LogRecordImpl.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/Logger.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/LoggerProvider.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/MultiLogRecordProcessor.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/config.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/BatchLogRecordProcessorBase.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/ConsoleLogRecordExporter.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/InMemoryLogRecordExporter.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/NoopLogRecordProcessor.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/SimpleLogRecordProcessor.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/internal/LoggerProviderSharedState.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/platform/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/platform/node/export/BatchLogRecordProcessor.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/platform/node/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/InstrumentDescriptor.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/Instruments.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/Meter.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/MeterProvider.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/ObservableResult.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Drop.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/ExponentialHistogram.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Histogram.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/LastValue.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Sum.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/Buckets.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/ExponentMapping.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/LogarithmMapping.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/getMapping.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/ieee754.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/types.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/util.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/types.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/AggregationSelector.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/AggregationTemporality.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/ConsoleMetricExporter.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/InMemoryMetricExporter.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/MetricData.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/MetricReader.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/PeriodicExportingMetricReader.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/AsyncMetricStorage.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/DeltaMetricProcessor.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/HashMap.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MeterProviderSharedState.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MeterSharedState.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricCollector.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricStorage.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricStorageRegistry.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MultiWritableMetricStorage.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/ObservableRegistry.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/SyncMetricStorage.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/TemporalMetricProcessor.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/utils.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/Aggregation.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/AggregationOption.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/AttributesProcessor.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/InstrumentSelector.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/MeterSelector.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/Predicate.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/RegistrationConflicts.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/View.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/ViewRegistry.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/BasicTracerProvider.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/MultiSpanProcessor.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/Sampler.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/Span.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/Tracer.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/config.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/enums.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/BatchSpanProcessorBase.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/ConsoleSpanExporter.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/InMemorySpanExporter.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/NoopSpanProcessor.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/SimpleSpanProcessor.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/platform/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/RandomIdGenerator.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/export/BatchSpanProcessor.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/AlwaysOffSampler.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/AlwaysOnSampler.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/ParentBasedSampler.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/TraceIdRatioBasedSampler.js create mode 100644 claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/utility.js create mode 100644 claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/internal/utils.js create mode 100644 claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/resource/SemanticResourceAttributes.js create mode 100644 claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/resource/index.js create mode 100644 claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/stable_attributes.js create mode 100644 claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/stable_events.js create mode 100644 claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/stable_metrics.js create mode 100644 claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/trace/SemanticAttributes.js create mode 100644 claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/trace/index.js create mode 100644 claude-code-source/node_modules/@pondwader/socks5-server/dist/index.js create mode 100644 claude-code-source/node_modules/@smithy/config-resolver/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/core/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/cbor/index.js create mode 100644 claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/event-streams/index.js create mode 100644 claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/protocols/index.js create mode 100644 claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/schema/index.js create mode 100644 claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/serde/index.js create mode 100644 claude-code-source/node_modules/@smithy/core/node_modules/@smithy/protocol-http/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/core/node_modules/@smithy/types/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js create mode 100644 claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/dist-cjs/toBase64.js create mode 100644 claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/credential-provider-imds/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/eventstream-codec/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/eventstream-codec/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/eventstream-serde-browser/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/eventstream-serde-browser/node_modules/@smithy/eventstream-serde-universal/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/eventstream-serde-config-resolver/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/eventstream-serde-node/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/eventstream-serde-universal/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/build/aws_crc32.js create mode 100644 claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/build/index.js create mode 100644 claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/convertToBuffer.js create mode 100644 claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/index.js create mode 100644 claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/isEmptyData.js create mode 100644 claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/numToUint8.js create mode 100644 claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/uint32ArrayFrom.js create mode 100644 claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/tslib/tslib.js create mode 100644 claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/fetch-http-handler/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/types/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js create mode 100644 claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/toBase64.js create mode 100644 claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/hash-node/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/hash-node/node_modules/@smithy/util-buffer-from/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/hash-node/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/is-array-buffer/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/middleware-content-length/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/middleware-content-length/node_modules/@smithy/protocol-http/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/middleware-content-length/node_modules/@smithy/types/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointFromConfig.js create mode 100644 claude-code-source/node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointUrlConfig.js create mode 100644 claude-code-source/node_modules/@smithy/middleware-endpoint/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/middleware-retry/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/middleware-retry/dist-cjs/isStreamingPayload/isStreamingPayload.js create mode 100644 claude-code-source/node_modules/@smithy/middleware-retry/node_modules/@smithy/protocol-http/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/middleware-retry/node_modules/@smithy/smithy-client/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/middleware-retry/node_modules/@smithy/types/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/middleware-serde/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/middleware-serde/node_modules/@smithy/protocol-http/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/middleware-serde/node_modules/@smithy/types/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/middleware-stack/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/node-config-provider/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/node-http-handler/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/node-http-handler/node_modules/@smithy/protocol-http/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/node-http-handler/node_modules/@smithy/querystring-builder/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/node-http-handler/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/node-http-handler/node_modules/@smithy/types/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/property-provider/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/protocol-http/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/querystring-builder/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/querystring-parser/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/service-error-classification/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getHomeDir.js create mode 100644 claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFilepath.js create mode 100644 claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFromFile.js create mode 100644 claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/readFile.js create mode 100644 claude-code-source/node_modules/@smithy/shared-ini-file-loader/node_modules/@smithy/types/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/signature-v4/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/signature-v4/node_modules/@smithy/util-middleware/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/signature-v4/node_modules/@smithy/util-utf8/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/signature-v4/node_modules/@smithy/util-utf8/node_modules/@smithy/util-buffer-from/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/smithy-client/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/middleware-stack/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/dist-cjs/getAwsChunkedEncodingStream.js create mode 100644 claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.js create mode 100644 claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/node-http-handler/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/node-http-handler/node_modules/@smithy/querystring-builder/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/node-http-handler/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/util-utf8/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/types/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/url-parser/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js create mode 100644 claude-code-source/node_modules/@smithy/util-base64/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/util-base64/dist-cjs/toBase64.js create mode 100644 claude-code-source/node_modules/@smithy/util-base64/node_modules/@smithy/util-utf8/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/util-body-length-browser/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/util-body-length-node/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/util-buffer-from/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/util-config-provider/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/util-defaults-mode-node/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/util-endpoints/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/util-endpoints/node_modules/@smithy/types/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/util-middleware/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/util-middleware/node_modules/@smithy/types/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/util-retry/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/util-stream/dist-cjs/ByteArrayCollector.js create mode 100644 claude-code-source/node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.browser.js create mode 100644 claude-code-source/node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.js create mode 100644 claude-code-source/node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.browser.js create mode 100644 claude-code-source/node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.js create mode 100644 claude-code-source/node_modules/@smithy/util-stream/dist-cjs/createBufferedReadable.js create mode 100644 claude-code-source/node_modules/@smithy/util-stream/dist-cjs/createBufferedReadableStream.js create mode 100644 claude-code-source/node_modules/@smithy/util-stream/dist-cjs/getAwsChunkedEncodingStream.js create mode 100644 claude-code-source/node_modules/@smithy/util-stream/dist-cjs/headStream.browser.js create mode 100644 claude-code-source/node_modules/@smithy/util-stream/dist-cjs/headStream.js create mode 100644 claude-code-source/node_modules/@smithy/util-stream/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.browser.js create mode 100644 claude-code-source/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.js create mode 100644 claude-code-source/node_modules/@smithy/util-stream/dist-cjs/splitStream.browser.js create mode 100644 claude-code-source/node_modules/@smithy/util-stream/dist-cjs/splitStream.js create mode 100644 claude-code-source/node_modules/@smithy/util-stream/dist-cjs/stream-type-check.js create mode 100644 claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/fetch-http-handler/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/querystring-builder/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/types/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js create mode 100644 claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-base64/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-base64/dist-cjs/toBase64.js create mode 100644 claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-buffer-from/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/util-uri-escape/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/util-utf8/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/util-utf8/node_modules/@smithy/util-buffer-from/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/util-utf8/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/uuid/dist-cjs/index.js create mode 100644 claude-code-source/node_modules/@smithy/uuid/dist-cjs/randomUUID.js create mode 120000 claude-code-source/node_modules/@types/node create mode 120000 claude-code-source/node_modules/@types/react create mode 120000 claude-code-source/node_modules/@types/ws create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/abort-controller/AbortError.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/constants.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/defaultHttpClient.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/httpHeaders.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/index.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/log.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/logger/debug.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/logger/internal.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/logger/log.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/logger/logger.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/nodeHttpClient.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/pipeline.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/pipelineRequest.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/agentPolicy.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/decompressResponsePolicy.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/defaultRetryPolicy.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/formDataPolicy.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/internal.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/logPolicy.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/multipartPolicy.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/proxyPolicy.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/redirectPolicy.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/retryPolicy.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/tlsPolicy.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/restError.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/retryStrategies/exponentialRetryStrategy.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/retryStrategies/throttlingRetryStrategy.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/bytesEncoding.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/checkEnvironment.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/concat.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/delay.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/error.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/helpers.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/inspect.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/internal.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/object.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/random.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/sanitizer.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/typeGuards.js create mode 100644 claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/uuidUtils.js create mode 100644 claude-code-source/node_modules/@xmldom/xmldom/lib/conventions.js create mode 100644 claude-code-source/node_modules/@xmldom/xmldom/lib/dom-parser.js create mode 100644 claude-code-source/node_modules/@xmldom/xmldom/lib/dom.js create mode 100644 claude-code-source/node_modules/@xmldom/xmldom/lib/entities.js create mode 100644 claude-code-source/node_modules/@xmldom/xmldom/lib/index.js create mode 100644 claude-code-source/node_modules/@xmldom/xmldom/lib/sax.js create mode 100644 claude-code-source/node_modules/agent-base/dist/helpers.js create mode 100644 claude-code-source/node_modules/agent-base/dist/index.js create mode 100644 claude-code-source/node_modules/ajv-formats/dist/formats.js create mode 100644 claude-code-source/node_modules/ajv-formats/dist/index.js create mode 100644 claude-code-source/node_modules/ajv-formats/dist/limit.js create mode 100644 claude-code-source/node_modules/ajv/dist/ajv.js create mode 100644 claude-code-source/node_modules/ajv/dist/compile/codegen/code.js create mode 100644 claude-code-source/node_modules/ajv/dist/compile/codegen/index.js create mode 100644 claude-code-source/node_modules/ajv/dist/compile/codegen/scope.js create mode 100644 claude-code-source/node_modules/ajv/dist/compile/errors.js create mode 100644 claude-code-source/node_modules/ajv/dist/compile/index.js create mode 100644 claude-code-source/node_modules/ajv/dist/compile/names.js create mode 100644 claude-code-source/node_modules/ajv/dist/compile/ref_error.js create mode 100644 claude-code-source/node_modules/ajv/dist/compile/resolve.js create mode 100644 claude-code-source/node_modules/ajv/dist/compile/rules.js create mode 100644 claude-code-source/node_modules/ajv/dist/compile/util.js create mode 100644 claude-code-source/node_modules/ajv/dist/compile/validate/applicability.js create mode 100644 claude-code-source/node_modules/ajv/dist/compile/validate/boolSchema.js create mode 100644 claude-code-source/node_modules/ajv/dist/compile/validate/dataType.js create mode 100644 claude-code-source/node_modules/ajv/dist/compile/validate/defaults.js create mode 100644 claude-code-source/node_modules/ajv/dist/compile/validate/index.js create mode 100644 claude-code-source/node_modules/ajv/dist/compile/validate/keyword.js create mode 100644 claude-code-source/node_modules/ajv/dist/compile/validate/subschema.js create mode 100644 claude-code-source/node_modules/ajv/dist/core.js create mode 100644 claude-code-source/node_modules/ajv/dist/runtime/equal.js create mode 100644 claude-code-source/node_modules/ajv/dist/runtime/ucs2length.js create mode 100644 claude-code-source/node_modules/ajv/dist/runtime/uri.js create mode 100644 claude-code-source/node_modules/ajv/dist/runtime/validation_error.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/applicator/allOf.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/applicator/anyOf.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/applicator/contains.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/applicator/dependencies.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/applicator/if.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/applicator/index.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/applicator/items.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/applicator/items2020.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/applicator/not.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/applicator/oneOf.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/applicator/properties.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/applicator/thenElse.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/code.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/core/id.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/core/index.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/core/ref.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/discriminator/index.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/discriminator/types.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/draft7.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/format/format.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/format/index.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/metadata.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/validation/const.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/validation/enum.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/validation/index.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/validation/limitItems.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/validation/limitLength.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/validation/limitNumber.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/validation/limitProperties.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/validation/multipleOf.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/validation/pattern.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/validation/required.js create mode 100644 claude-code-source/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js create mode 100644 claude-code-source/node_modules/asciichart/asciichart.js create mode 100644 claude-code-source/node_modules/auto-bind/index.js create mode 100644 claude-code-source/node_modules/axios/index.js create mode 100644 claude-code-source/node_modules/axios/lib/adapters/adapters.js create mode 100644 claude-code-source/node_modules/axios/lib/adapters/fetch.js create mode 100644 claude-code-source/node_modules/axios/lib/adapters/http.js create mode 100644 claude-code-source/node_modules/axios/lib/adapters/xhr.js create mode 100644 claude-code-source/node_modules/axios/lib/axios.js create mode 100644 claude-code-source/node_modules/axios/lib/cancel/CancelToken.js create mode 100644 claude-code-source/node_modules/axios/lib/cancel/CanceledError.js create mode 100644 claude-code-source/node_modules/axios/lib/cancel/isCancel.js create mode 100644 claude-code-source/node_modules/axios/lib/core/Axios.js create mode 100644 claude-code-source/node_modules/axios/lib/core/AxiosError.js create mode 100644 claude-code-source/node_modules/axios/lib/core/AxiosHeaders.js create mode 100644 claude-code-source/node_modules/axios/lib/core/InterceptorManager.js create mode 100644 claude-code-source/node_modules/axios/lib/core/buildFullPath.js create mode 100644 claude-code-source/node_modules/axios/lib/core/dispatchRequest.js create mode 100644 claude-code-source/node_modules/axios/lib/core/mergeConfig.js create mode 100644 claude-code-source/node_modules/axios/lib/core/settle.js create mode 100644 claude-code-source/node_modules/axios/lib/core/transformData.js create mode 100644 claude-code-source/node_modules/axios/lib/defaults/index.js create mode 100644 claude-code-source/node_modules/axios/lib/defaults/transitional.js create mode 100644 claude-code-source/node_modules/axios/lib/env/data.js create mode 100644 claude-code-source/node_modules/axios/lib/helpers/AxiosTransformStream.js create mode 100644 claude-code-source/node_modules/axios/lib/helpers/AxiosURLSearchParams.js create mode 100644 claude-code-source/node_modules/axios/lib/helpers/HttpStatusCode.js create mode 100644 claude-code-source/node_modules/axios/lib/helpers/ZlibHeaderTransformStream.js create mode 100644 claude-code-source/node_modules/axios/lib/helpers/bind.js create mode 100644 claude-code-source/node_modules/axios/lib/helpers/buildURL.js create mode 100644 claude-code-source/node_modules/axios/lib/helpers/callbackify.js create mode 100644 claude-code-source/node_modules/axios/lib/helpers/combineURLs.js create mode 100644 claude-code-source/node_modules/axios/lib/helpers/composeSignals.js create mode 100644 claude-code-source/node_modules/axios/lib/helpers/cookies.js create mode 100644 claude-code-source/node_modules/axios/lib/helpers/estimateDataURLDecodedBytes.js create mode 100644 claude-code-source/node_modules/axios/lib/helpers/formDataToJSON.js create mode 100644 claude-code-source/node_modules/axios/lib/helpers/formDataToStream.js create mode 100644 claude-code-source/node_modules/axios/lib/helpers/fromDataURI.js create mode 100644 claude-code-source/node_modules/axios/lib/helpers/isAbsoluteURL.js create mode 100644 claude-code-source/node_modules/axios/lib/helpers/isAxiosError.js create mode 100644 claude-code-source/node_modules/axios/lib/helpers/isURLSameOrigin.js create mode 100644 claude-code-source/node_modules/axios/lib/helpers/parseHeaders.js create mode 100644 claude-code-source/node_modules/axios/lib/helpers/parseProtocol.js create mode 100644 claude-code-source/node_modules/axios/lib/helpers/progressEventReducer.js create mode 100644 claude-code-source/node_modules/axios/lib/helpers/readBlob.js create mode 100644 claude-code-source/node_modules/axios/lib/helpers/resolveConfig.js create mode 100644 claude-code-source/node_modules/axios/lib/helpers/speedometer.js create mode 100644 claude-code-source/node_modules/axios/lib/helpers/spread.js create mode 100644 claude-code-source/node_modules/axios/lib/helpers/throttle.js create mode 100644 claude-code-source/node_modules/axios/lib/helpers/toFormData.js create mode 100644 claude-code-source/node_modules/axios/lib/helpers/toURLEncodedForm.js create mode 100644 claude-code-source/node_modules/axios/lib/helpers/trackStream.js create mode 100644 claude-code-source/node_modules/axios/lib/helpers/validator.js create mode 100644 claude-code-source/node_modules/axios/lib/platform/common/utils.js create mode 100644 claude-code-source/node_modules/axios/lib/platform/index.js create mode 100644 claude-code-source/node_modules/axios/lib/platform/node/classes/FormData.js create mode 100644 claude-code-source/node_modules/axios/lib/platform/node/classes/URLSearchParams.js create mode 100644 claude-code-source/node_modules/axios/lib/platform/node/index.js create mode 100644 claude-code-source/node_modules/axios/lib/utils.js create mode 100644 claude-code-source/node_modules/bidi-js/dist/bidi.js create mode 120000 claude-code-source/node_modules/bun-types create mode 100644 claude-code-source/node_modules/chalk/source/index.js create mode 100644 claude-code-source/node_modules/chalk/source/utilities.js create mode 100644 claude-code-source/node_modules/chalk/source/vendor/ansi-styles/index.js create mode 100644 claude-code-source/node_modules/chalk/source/vendor/supports-color/index.js create mode 100644 claude-code-source/node_modules/chokidar/esm/handler.js create mode 100644 claude-code-source/node_modules/chokidar/esm/index.js create mode 100644 claude-code-source/node_modules/cli-boxes/index.js create mode 100644 claude-code-source/node_modules/cli-highlight/dist/index.js create mode 100644 claude-code-source/node_modules/cli-highlight/dist/theme.js create mode 100644 claude-code-source/node_modules/code-excerpt/dist/index.js create mode 100644 claude-code-source/node_modules/commander/index.js create mode 100644 claude-code-source/node_modules/commander/lib/argument.js create mode 100644 claude-code-source/node_modules/commander/lib/command.js create mode 100644 claude-code-source/node_modules/commander/lib/error.js create mode 100644 claude-code-source/node_modules/commander/lib/help.js create mode 100644 claude-code-source/node_modules/commander/lib/option.js create mode 100644 claude-code-source/node_modules/commander/lib/suggestSimilar.js create mode 100644 claude-code-source/node_modules/convert-to-spaces/dist/index.js create mode 100644 claude-code-source/node_modules/diff/libesm/diff/array.js create mode 100644 claude-code-source/node_modules/diff/libesm/diff/base.js create mode 100644 claude-code-source/node_modules/diff/libesm/diff/line.js create mode 100644 claude-code-source/node_modules/diff/libesm/diff/word.js create mode 100644 claude-code-source/node_modules/diff/libesm/index.js create mode 100644 claude-code-source/node_modules/diff/libesm/patch/create.js create mode 100644 claude-code-source/node_modules/diff/libesm/util/string.js create mode 100644 claude-code-source/node_modules/dom-mutator/dist/dom-mutator.cjs.production.min.js create mode 100644 claude-code-source/node_modules/emoji-regex/index.js create mode 100644 claude-code-source/node_modules/env-paths/index.js create mode 100644 claude-code-source/node_modules/eventsource-parser/dist/index.js create mode 100644 claude-code-source/node_modules/eventsource-parser/dist/stream.js create mode 100644 claude-code-source/node_modules/eventsource/dist/index.js create mode 100644 claude-code-source/node_modules/execa/index.js create mode 100644 claude-code-source/node_modules/execa/lib/command.js create mode 100644 claude-code-source/node_modules/execa/lib/error.js create mode 100644 claude-code-source/node_modules/execa/lib/kill.js create mode 100644 claude-code-source/node_modules/execa/lib/pipe.js create mode 100644 claude-code-source/node_modules/execa/lib/promise.js create mode 100644 claude-code-source/node_modules/execa/lib/stdio.js create mode 100644 claude-code-source/node_modules/execa/lib/stream.js create mode 100644 claude-code-source/node_modules/execa/lib/verbose.js create mode 100644 claude-code-source/node_modules/fflate/esm/index.mjs create mode 100644 claude-code-source/node_modules/figures/index.js create mode 100644 claude-code-source/node_modules/fuse.js/dist/fuse.mjs create mode 100644 claude-code-source/node_modules/gaxios/node_modules/uuid/dist/index.js create mode 100644 claude-code-source/node_modules/gaxios/node_modules/uuid/dist/md5.js create mode 100644 claude-code-source/node_modules/gaxios/node_modules/uuid/dist/native.js create mode 100644 claude-code-source/node_modules/gaxios/node_modules/uuid/dist/nil.js create mode 100644 claude-code-source/node_modules/gaxios/node_modules/uuid/dist/parse.js create mode 100644 claude-code-source/node_modules/gaxios/node_modules/uuid/dist/regex.js create mode 100644 claude-code-source/node_modules/gaxios/node_modules/uuid/dist/rng.js create mode 100644 claude-code-source/node_modules/gaxios/node_modules/uuid/dist/sha1.js create mode 100644 claude-code-source/node_modules/gaxios/node_modules/uuid/dist/stringify.js create mode 100644 claude-code-source/node_modules/gaxios/node_modules/uuid/dist/v1.js create mode 100644 claude-code-source/node_modules/gaxios/node_modules/uuid/dist/v3.js create mode 100644 claude-code-source/node_modules/gaxios/node_modules/uuid/dist/v35.js create mode 100644 claude-code-source/node_modules/gaxios/node_modules/uuid/dist/v4.js create mode 100644 claude-code-source/node_modules/gaxios/node_modules/uuid/dist/v5.js create mode 100644 claude-code-source/node_modules/gaxios/node_modules/uuid/dist/validate.js create mode 100644 claude-code-source/node_modules/gaxios/node_modules/uuid/dist/version.js create mode 100644 claude-code-source/node_modules/get-east-asian-width/index.js create mode 100644 claude-code-source/node_modules/get-east-asian-width/lookup.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/auth/authclient.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/auth/awsclient.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/auth/awsrequestsigner.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/auth/baseexternalclient.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/auth/computeclient.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/auth/downscopedclient.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/auth/envDetect.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/auth/executable-response.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/auth/externalclient.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/auth/googleauth.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/auth/iam.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/auth/identitypoolclient.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/auth/idtokenclient.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/auth/impersonated.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/auth/jwtaccess.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/auth/jwtclient.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/auth/loginticket.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/auth/oauth2client.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/auth/oauth2common.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/auth/passthrough.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/auth/pluggable-auth-client.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/auth/refreshclient.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/auth/stscredentials.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/crypto/browser/crypto.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/crypto/crypto.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/crypto/node/crypto.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/index.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/options.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/transporters.js create mode 100644 claude-code-source/node_modules/google-auth-library/build/src/util.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/core.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/index.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/1c.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/abnf.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/accesslog.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/actionscript.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/ada.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/angelscript.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/apache.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/applescript.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/arcade.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/arduino.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/armasm.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/asciidoc.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/aspectj.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/autohotkey.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/autoit.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/avrasm.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/awk.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/axapta.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/bash.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/basic.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/bnf.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/brainfuck.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/c-like.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/c.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/cal.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/capnproto.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/ceylon.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/clean.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/clojure-repl.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/clojure.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/cmake.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/coffeescript.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/coq.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/cos.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/cpp.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/crmsh.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/crystal.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/csharp.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/csp.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/css.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/d.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/dart.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/delphi.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/diff.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/django.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/dns.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/dockerfile.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/dos.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/dsconfig.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/dts.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/dust.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/ebnf.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/elixir.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/elm.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/erb.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/erlang-repl.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/erlang.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/excel.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/fix.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/flix.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/fortran.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/fsharp.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/gams.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/gauss.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/gcode.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/gherkin.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/glsl.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/gml.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/go.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/golo.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/gradle.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/groovy.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/haml.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/handlebars.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/haskell.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/haxe.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/hsp.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/htmlbars.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/http.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/hy.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/inform7.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/ini.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/irpf90.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/isbl.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/java.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/javascript.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/jboss-cli.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/json.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/julia-repl.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/julia.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/kotlin.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/lasso.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/latex.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/ldif.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/leaf.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/less.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/lisp.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/livecodeserver.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/livescript.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/llvm.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/lsl.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/lua.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/makefile.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/markdown.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/mathematica.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/matlab.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/maxima.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/mel.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/mercury.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/mipsasm.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/mizar.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/mojolicious.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/monkey.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/moonscript.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/n1ql.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/nginx.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/nim.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/nix.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/node-repl.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/nsis.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/objectivec.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/ocaml.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/openscad.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/oxygene.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/parser3.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/perl.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/pf.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/pgsql.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/php-template.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/php.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/plaintext.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/pony.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/powershell.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/processing.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/profile.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/prolog.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/properties.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/protobuf.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/puppet.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/purebasic.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/python-repl.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/python.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/q.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/qml.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/r.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/reasonml.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/rib.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/roboconf.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/routeros.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/rsl.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/ruby.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/ruleslanguage.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/rust.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/sas.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/scala.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/scheme.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/scilab.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/scss.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/shell.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/smali.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/smalltalk.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/sml.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/sqf.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/sql.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/sql_more.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/stan.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/stata.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/step21.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/stylus.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/subunit.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/swift.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/taggerscript.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/tap.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/tcl.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/thrift.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/tp.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/twig.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/typescript.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/vala.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/vbnet.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/vbscript-html.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/vbscript.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/verilog.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/vhdl.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/vim.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/x86asm.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/xl.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/xml.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/xquery.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/yaml.js create mode 100644 claude-code-source/node_modules/highlight.js/lib/languages/zephir.js create mode 100644 claude-code-source/node_modules/http-proxy-agent/dist/index.js create mode 100644 claude-code-source/node_modules/https-proxy-agent/dist/index.js create mode 100644 claude-code-source/node_modules/https-proxy-agent/dist/parse-proxy-response.js create mode 100644 claude-code-source/node_modules/ignore/index.js create mode 100644 claude-code-source/node_modules/indent-string/index.js create mode 120000 claude-code-source/node_modules/ink create mode 100644 claude-code-source/node_modules/jsonc-parser/lib/esm/impl/edit.js create mode 100644 claude-code-source/node_modules/jsonc-parser/lib/esm/impl/format.js create mode 100644 claude-code-source/node_modules/jsonc-parser/lib/esm/impl/parser.js create mode 100644 claude-code-source/node_modules/jsonc-parser/lib/esm/impl/scanner.js create mode 100644 claude-code-source/node_modules/jsonc-parser/lib/esm/impl/string-intern.js create mode 100644 claude-code-source/node_modules/jsonc-parser/lib/esm/main.js create mode 100644 claude-code-source/node_modules/lodash-es/_DataView.js create mode 100644 claude-code-source/node_modules/lodash-es/_Hash.js create mode 100644 claude-code-source/node_modules/lodash-es/_ListCache.js create mode 100644 claude-code-source/node_modules/lodash-es/_Map.js create mode 100644 claude-code-source/node_modules/lodash-es/_MapCache.js create mode 100644 claude-code-source/node_modules/lodash-es/_Promise.js create mode 100644 claude-code-source/node_modules/lodash-es/_Set.js create mode 100644 claude-code-source/node_modules/lodash-es/_SetCache.js create mode 100644 claude-code-source/node_modules/lodash-es/_Stack.js create mode 100644 claude-code-source/node_modules/lodash-es/_Symbol.js create mode 100644 claude-code-source/node_modules/lodash-es/_Uint8Array.js create mode 100644 claude-code-source/node_modules/lodash-es/_WeakMap.js create mode 100644 claude-code-source/node_modules/lodash-es/_apply.js create mode 100644 claude-code-source/node_modules/lodash-es/_arrayAggregator.js create mode 100644 claude-code-source/node_modules/lodash-es/_arrayEach.js create mode 100644 claude-code-source/node_modules/lodash-es/_arrayFilter.js create mode 100644 claude-code-source/node_modules/lodash-es/_arrayIncludes.js create mode 100644 claude-code-source/node_modules/lodash-es/_arrayIncludesWith.js create mode 100644 claude-code-source/node_modules/lodash-es/_arrayLikeKeys.js create mode 100644 claude-code-source/node_modules/lodash-es/_arrayMap.js create mode 100644 claude-code-source/node_modules/lodash-es/_arrayPush.js create mode 100644 claude-code-source/node_modules/lodash-es/_arraySample.js create mode 100644 claude-code-source/node_modules/lodash-es/_arraySome.js create mode 100644 claude-code-source/node_modules/lodash-es/_asciiToArray.js create mode 100644 claude-code-source/node_modules/lodash-es/_assignMergeValue.js create mode 100644 claude-code-source/node_modules/lodash-es/_assignValue.js create mode 100644 claude-code-source/node_modules/lodash-es/_assocIndexOf.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseAggregator.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseAssign.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseAssignIn.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseAssignValue.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseClone.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseCreate.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseEach.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseFilter.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseFindIndex.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseFlatten.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseFor.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseForOwn.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseGet.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseGetAllKeys.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseGetTag.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseHasIn.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseIndexOf.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseIsArguments.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseIsEqual.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseIsEqualDeep.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseIsMap.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseIsMatch.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseIsNaN.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseIsNative.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseIsSet.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseIsTypedArray.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseIteratee.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseKeys.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseKeysIn.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseMatches.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseMatchesProperty.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseMerge.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseMergeDeep.js create mode 100644 claude-code-source/node_modules/lodash-es/_basePickBy.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseProperty.js create mode 100644 claude-code-source/node_modules/lodash-es/_basePropertyDeep.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseRandom.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseRest.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseSample.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseSet.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseSetToString.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseSlice.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseSum.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseTimes.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseToString.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseTrim.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseUnary.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseUniq.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseUnset.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseValues.js create mode 100644 claude-code-source/node_modules/lodash-es/_baseZipObject.js create mode 100644 claude-code-source/node_modules/lodash-es/_cacheHas.js create mode 100644 claude-code-source/node_modules/lodash-es/_castPath.js create mode 100644 claude-code-source/node_modules/lodash-es/_castSlice.js create mode 100644 claude-code-source/node_modules/lodash-es/_cloneArrayBuffer.js create mode 100644 claude-code-source/node_modules/lodash-es/_cloneBuffer.js create mode 100644 claude-code-source/node_modules/lodash-es/_cloneDataView.js create mode 100644 claude-code-source/node_modules/lodash-es/_cloneRegExp.js create mode 100644 claude-code-source/node_modules/lodash-es/_cloneSymbol.js create mode 100644 claude-code-source/node_modules/lodash-es/_cloneTypedArray.js create mode 100644 claude-code-source/node_modules/lodash-es/_copyArray.js create mode 100644 claude-code-source/node_modules/lodash-es/_copyObject.js create mode 100644 claude-code-source/node_modules/lodash-es/_copySymbols.js create mode 100644 claude-code-source/node_modules/lodash-es/_copySymbolsIn.js create mode 100644 claude-code-source/node_modules/lodash-es/_coreJsData.js create mode 100644 claude-code-source/node_modules/lodash-es/_createAggregator.js create mode 100644 claude-code-source/node_modules/lodash-es/_createAssigner.js create mode 100644 claude-code-source/node_modules/lodash-es/_createBaseEach.js create mode 100644 claude-code-source/node_modules/lodash-es/_createBaseFor.js create mode 100644 claude-code-source/node_modules/lodash-es/_createCaseFirst.js create mode 100644 claude-code-source/node_modules/lodash-es/_createSet.js create mode 100644 claude-code-source/node_modules/lodash-es/_customOmitClone.js create mode 100644 claude-code-source/node_modules/lodash-es/_defineProperty.js create mode 100644 claude-code-source/node_modules/lodash-es/_equalArrays.js create mode 100644 claude-code-source/node_modules/lodash-es/_equalByTag.js create mode 100644 claude-code-source/node_modules/lodash-es/_equalObjects.js create mode 100644 claude-code-source/node_modules/lodash-es/_flatRest.js create mode 100644 claude-code-source/node_modules/lodash-es/_freeGlobal.js create mode 100644 claude-code-source/node_modules/lodash-es/_getAllKeys.js create mode 100644 claude-code-source/node_modules/lodash-es/_getAllKeysIn.js create mode 100644 claude-code-source/node_modules/lodash-es/_getMapData.js create mode 100644 claude-code-source/node_modules/lodash-es/_getMatchData.js create mode 100644 claude-code-source/node_modules/lodash-es/_getNative.js create mode 100644 claude-code-source/node_modules/lodash-es/_getPrototype.js create mode 100644 claude-code-source/node_modules/lodash-es/_getRawTag.js create mode 100644 claude-code-source/node_modules/lodash-es/_getSymbols.js create mode 100644 claude-code-source/node_modules/lodash-es/_getSymbolsIn.js create mode 100644 claude-code-source/node_modules/lodash-es/_getTag.js create mode 100644 claude-code-source/node_modules/lodash-es/_getValue.js create mode 100644 claude-code-source/node_modules/lodash-es/_hasPath.js create mode 100644 claude-code-source/node_modules/lodash-es/_hasUnicode.js create mode 100644 claude-code-source/node_modules/lodash-es/_hashClear.js create mode 100644 claude-code-source/node_modules/lodash-es/_hashDelete.js create mode 100644 claude-code-source/node_modules/lodash-es/_hashGet.js create mode 100644 claude-code-source/node_modules/lodash-es/_hashHas.js create mode 100644 claude-code-source/node_modules/lodash-es/_hashSet.js create mode 100644 claude-code-source/node_modules/lodash-es/_initCloneArray.js create mode 100644 claude-code-source/node_modules/lodash-es/_initCloneByTag.js create mode 100644 claude-code-source/node_modules/lodash-es/_initCloneObject.js create mode 100644 claude-code-source/node_modules/lodash-es/_isFlattenable.js create mode 100644 claude-code-source/node_modules/lodash-es/_isIndex.js create mode 100644 claude-code-source/node_modules/lodash-es/_isIterateeCall.js create mode 100644 claude-code-source/node_modules/lodash-es/_isKey.js create mode 100644 claude-code-source/node_modules/lodash-es/_isKeyable.js create mode 100644 claude-code-source/node_modules/lodash-es/_isMasked.js create mode 100644 claude-code-source/node_modules/lodash-es/_isPrototype.js create mode 100644 claude-code-source/node_modules/lodash-es/_isStrictComparable.js create mode 100644 claude-code-source/node_modules/lodash-es/_listCacheClear.js create mode 100644 claude-code-source/node_modules/lodash-es/_listCacheDelete.js create mode 100644 claude-code-source/node_modules/lodash-es/_listCacheGet.js create mode 100644 claude-code-source/node_modules/lodash-es/_listCacheHas.js create mode 100644 claude-code-source/node_modules/lodash-es/_listCacheSet.js create mode 100644 claude-code-source/node_modules/lodash-es/_mapCacheClear.js create mode 100644 claude-code-source/node_modules/lodash-es/_mapCacheDelete.js create mode 100644 claude-code-source/node_modules/lodash-es/_mapCacheGet.js create mode 100644 claude-code-source/node_modules/lodash-es/_mapCacheHas.js create mode 100644 claude-code-source/node_modules/lodash-es/_mapCacheSet.js create mode 100644 claude-code-source/node_modules/lodash-es/_mapToArray.js create mode 100644 claude-code-source/node_modules/lodash-es/_matchesStrictComparable.js create mode 100644 claude-code-source/node_modules/lodash-es/_memoizeCapped.js create mode 100644 claude-code-source/node_modules/lodash-es/_nativeCreate.js create mode 100644 claude-code-source/node_modules/lodash-es/_nativeKeys.js create mode 100644 claude-code-source/node_modules/lodash-es/_nativeKeysIn.js create mode 100644 claude-code-source/node_modules/lodash-es/_nodeUtil.js create mode 100644 claude-code-source/node_modules/lodash-es/_objectToString.js create mode 100644 claude-code-source/node_modules/lodash-es/_overArg.js create mode 100644 claude-code-source/node_modules/lodash-es/_overRest.js create mode 100644 claude-code-source/node_modules/lodash-es/_parent.js create mode 100644 claude-code-source/node_modules/lodash-es/_root.js create mode 100644 claude-code-source/node_modules/lodash-es/_safeGet.js create mode 100644 claude-code-source/node_modules/lodash-es/_setCacheAdd.js create mode 100644 claude-code-source/node_modules/lodash-es/_setCacheHas.js create mode 100644 claude-code-source/node_modules/lodash-es/_setToArray.js create mode 100644 claude-code-source/node_modules/lodash-es/_setToString.js create mode 100644 claude-code-source/node_modules/lodash-es/_shortOut.js create mode 100644 claude-code-source/node_modules/lodash-es/_stackClear.js create mode 100644 claude-code-source/node_modules/lodash-es/_stackDelete.js create mode 100644 claude-code-source/node_modules/lodash-es/_stackGet.js create mode 100644 claude-code-source/node_modules/lodash-es/_stackHas.js create mode 100644 claude-code-source/node_modules/lodash-es/_stackSet.js create mode 100644 claude-code-source/node_modules/lodash-es/_strictIndexOf.js create mode 100644 claude-code-source/node_modules/lodash-es/_stringToArray.js create mode 100644 claude-code-source/node_modules/lodash-es/_stringToPath.js create mode 100644 claude-code-source/node_modules/lodash-es/_toKey.js create mode 100644 claude-code-source/node_modules/lodash-es/_toSource.js create mode 100644 claude-code-source/node_modules/lodash-es/_trimmedEndIndex.js create mode 100644 claude-code-source/node_modules/lodash-es/_unicodeToArray.js create mode 100644 claude-code-source/node_modules/lodash-es/capitalize.js create mode 100644 claude-code-source/node_modules/lodash-es/cloneDeep.js create mode 100644 claude-code-source/node_modules/lodash-es/constant.js create mode 100644 claude-code-source/node_modules/lodash-es/debounce.js create mode 100644 claude-code-source/node_modules/lodash-es/eq.js create mode 100644 claude-code-source/node_modules/lodash-es/flatten.js create mode 100644 claude-code-source/node_modules/lodash-es/get.js create mode 100644 claude-code-source/node_modules/lodash-es/hasIn.js create mode 100644 claude-code-source/node_modules/lodash-es/identity.js create mode 100644 claude-code-source/node_modules/lodash-es/isArguments.js create mode 100644 claude-code-source/node_modules/lodash-es/isArray.js create mode 100644 claude-code-source/node_modules/lodash-es/isArrayLike.js create mode 100644 claude-code-source/node_modules/lodash-es/isArrayLikeObject.js create mode 100644 claude-code-source/node_modules/lodash-es/isBuffer.js create mode 100644 claude-code-source/node_modules/lodash-es/isEqual.js create mode 100644 claude-code-source/node_modules/lodash-es/isFunction.js create mode 100644 claude-code-source/node_modules/lodash-es/isLength.js create mode 100644 claude-code-source/node_modules/lodash-es/isMap.js create mode 100644 claude-code-source/node_modules/lodash-es/isObject.js create mode 100644 claude-code-source/node_modules/lodash-es/isObjectLike.js create mode 100644 claude-code-source/node_modules/lodash-es/isPlainObject.js create mode 100644 claude-code-source/node_modules/lodash-es/isSet.js create mode 100644 claude-code-source/node_modules/lodash-es/isSymbol.js create mode 100644 claude-code-source/node_modules/lodash-es/isTypedArray.js create mode 100644 claude-code-source/node_modules/lodash-es/keys.js create mode 100644 claude-code-source/node_modules/lodash-es/keysIn.js create mode 100644 claude-code-source/node_modules/lodash-es/last.js create mode 100644 claude-code-source/node_modules/lodash-es/lodash.js create mode 100644 claude-code-source/node_modules/lodash-es/mapValues.js create mode 100644 claude-code-source/node_modules/lodash-es/memoize.js create mode 100644 claude-code-source/node_modules/lodash-es/mergeWith.js create mode 100644 claude-code-source/node_modules/lodash-es/negate.js create mode 100644 claude-code-source/node_modules/lodash-es/noop.js create mode 100644 claude-code-source/node_modules/lodash-es/now.js create mode 100644 claude-code-source/node_modules/lodash-es/omit.js create mode 100644 claude-code-source/node_modules/lodash-es/partition.js create mode 100644 claude-code-source/node_modules/lodash-es/pickBy.js create mode 100644 claude-code-source/node_modules/lodash-es/property.js create mode 100644 claude-code-source/node_modules/lodash-es/reject.js create mode 100644 claude-code-source/node_modules/lodash-es/sample.js create mode 100644 claude-code-source/node_modules/lodash-es/setWith.js create mode 100644 claude-code-source/node_modules/lodash-es/stubArray.js create mode 100644 claude-code-source/node_modules/lodash-es/stubFalse.js create mode 100644 claude-code-source/node_modules/lodash-es/sumBy.js create mode 100644 claude-code-source/node_modules/lodash-es/throttle.js create mode 100644 claude-code-source/node_modules/lodash-es/toNumber.js create mode 100644 claude-code-source/node_modules/lodash-es/toPlainObject.js create mode 100644 claude-code-source/node_modules/lodash-es/toString.js create mode 100644 claude-code-source/node_modules/lodash-es/uniqBy.js create mode 100644 claude-code-source/node_modules/lodash-es/upperFirst.js create mode 100644 claude-code-source/node_modules/lodash-es/values.js create mode 100644 claude-code-source/node_modules/lodash-es/zipObject.js create mode 100644 claude-code-source/node_modules/lru-cache/dist/esm/index.js create mode 100644 claude-code-source/node_modules/marked/lib/marked.esm.js create mode 100644 claude-code-source/node_modules/p-map/index.js create mode 100644 claude-code-source/node_modules/picomatch/index.js create mode 100644 claude-code-source/node_modules/picomatch/lib/constants.js create mode 100644 claude-code-source/node_modules/picomatch/lib/parse.js create mode 100644 claude-code-source/node_modules/picomatch/lib/picomatch.js create mode 100644 claude-code-source/node_modules/picomatch/lib/scan.js create mode 100644 claude-code-source/node_modules/picomatch/lib/utils.js create mode 100644 claude-code-source/node_modules/pkce-challenge/dist/index.node.js create mode 100644 claude-code-source/node_modules/proper-lockfile/index.js create mode 100644 claude-code-source/node_modules/proper-lockfile/lib/adapter.js create mode 100644 claude-code-source/node_modules/proper-lockfile/lib/lockfile.js create mode 100644 claude-code-source/node_modules/proper-lockfile/lib/mtime-precision.js create mode 100644 claude-code-source/node_modules/proper-lockfile/node_modules/signal-exit/index.js create mode 100644 claude-code-source/node_modules/proper-lockfile/node_modules/signal-exit/signals.js create mode 100644 claude-code-source/node_modules/qrcode/lib/browser.js create mode 100644 claude-code-source/node_modules/qrcode/lib/can-promise.js create mode 100644 claude-code-source/node_modules/qrcode/lib/core/alignment-pattern.js create mode 100644 claude-code-source/node_modules/qrcode/lib/core/alphanumeric-data.js create mode 100644 claude-code-source/node_modules/qrcode/lib/core/bit-buffer.js create mode 100644 claude-code-source/node_modules/qrcode/lib/core/bit-matrix.js create mode 100644 claude-code-source/node_modules/qrcode/lib/core/byte-data.js create mode 100644 claude-code-source/node_modules/qrcode/lib/core/error-correction-code.js create mode 100644 claude-code-source/node_modules/qrcode/lib/core/error-correction-level.js create mode 100644 claude-code-source/node_modules/qrcode/lib/core/finder-pattern.js create mode 100644 claude-code-source/node_modules/qrcode/lib/core/format-info.js create mode 100644 claude-code-source/node_modules/qrcode/lib/core/galois-field.js create mode 100644 claude-code-source/node_modules/qrcode/lib/core/kanji-data.js create mode 100644 claude-code-source/node_modules/qrcode/lib/core/mask-pattern.js create mode 100644 claude-code-source/node_modules/qrcode/lib/core/mode.js create mode 100644 claude-code-source/node_modules/qrcode/lib/core/numeric-data.js create mode 100644 claude-code-source/node_modules/qrcode/lib/core/polynomial.js create mode 100644 claude-code-source/node_modules/qrcode/lib/core/qrcode.js create mode 100644 claude-code-source/node_modules/qrcode/lib/core/reed-solomon-encoder.js create mode 100644 claude-code-source/node_modules/qrcode/lib/core/regex.js create mode 100644 claude-code-source/node_modules/qrcode/lib/core/segments.js create mode 100644 claude-code-source/node_modules/qrcode/lib/core/utils.js create mode 100644 claude-code-source/node_modules/qrcode/lib/core/version-check.js create mode 100644 claude-code-source/node_modules/qrcode/lib/core/version.js create mode 100644 claude-code-source/node_modules/qrcode/lib/renderer/canvas.js create mode 100644 claude-code-source/node_modules/qrcode/lib/renderer/png.js create mode 100644 claude-code-source/node_modules/qrcode/lib/renderer/svg-tag.js create mode 100644 claude-code-source/node_modules/qrcode/lib/renderer/svg.js create mode 100644 claude-code-source/node_modules/qrcode/lib/renderer/terminal.js create mode 100644 claude-code-source/node_modules/qrcode/lib/renderer/terminal/terminal-small.js create mode 100644 claude-code-source/node_modules/qrcode/lib/renderer/terminal/terminal.js create mode 100644 claude-code-source/node_modules/qrcode/lib/renderer/utf8.js create mode 100644 claude-code-source/node_modules/qrcode/lib/renderer/utils.js create mode 100644 claude-code-source/node_modules/qrcode/lib/server.js create mode 100644 claude-code-source/node_modules/react-reconciler/cjs/react-reconciler-constants.production.js create mode 100644 claude-code-source/node_modules/react-reconciler/cjs/react-reconciler.production.js create mode 100644 claude-code-source/node_modules/react-reconciler/node_modules/scheduler/cjs/scheduler.production.js create mode 100644 claude-code-source/node_modules/react/cjs/react-compiler-runtime.production.js create mode 100644 claude-code-source/node_modules/react/cjs/react.production.js create mode 100644 claude-code-source/node_modules/semver/classes/comparator.js create mode 100644 claude-code-source/node_modules/semver/classes/range.js create mode 100644 claude-code-source/node_modules/semver/classes/semver.js create mode 100644 claude-code-source/node_modules/semver/functions/clean.js create mode 100644 claude-code-source/node_modules/semver/functions/cmp.js create mode 100644 claude-code-source/node_modules/semver/functions/coerce.js create mode 100644 claude-code-source/node_modules/semver/functions/compare-build.js create mode 100644 claude-code-source/node_modules/semver/functions/compare-loose.js create mode 100644 claude-code-source/node_modules/semver/functions/compare.js create mode 100644 claude-code-source/node_modules/semver/functions/diff.js create mode 100644 claude-code-source/node_modules/semver/functions/eq.js create mode 100644 claude-code-source/node_modules/semver/functions/gt.js create mode 100644 claude-code-source/node_modules/semver/functions/gte.js create mode 100644 claude-code-source/node_modules/semver/functions/inc.js create mode 100644 claude-code-source/node_modules/semver/functions/lt.js create mode 100644 claude-code-source/node_modules/semver/functions/lte.js create mode 100644 claude-code-source/node_modules/semver/functions/major.js create mode 100644 claude-code-source/node_modules/semver/functions/minor.js create mode 100644 claude-code-source/node_modules/semver/functions/neq.js create mode 100644 claude-code-source/node_modules/semver/functions/parse.js create mode 100644 claude-code-source/node_modules/semver/functions/patch.js create mode 100644 claude-code-source/node_modules/semver/functions/prerelease.js create mode 100644 claude-code-source/node_modules/semver/functions/rcompare.js create mode 100644 claude-code-source/node_modules/semver/functions/rsort.js create mode 100644 claude-code-source/node_modules/semver/functions/satisfies.js create mode 100644 claude-code-source/node_modules/semver/functions/sort.js create mode 100644 claude-code-source/node_modules/semver/functions/valid.js create mode 100644 claude-code-source/node_modules/semver/index.js create mode 100644 claude-code-source/node_modules/semver/internal/constants.js create mode 100644 claude-code-source/node_modules/semver/internal/debug.js create mode 100644 claude-code-source/node_modules/semver/internal/identifiers.js create mode 100644 claude-code-source/node_modules/semver/internal/lrucache.js create mode 100644 claude-code-source/node_modules/semver/internal/parse-options.js create mode 100644 claude-code-source/node_modules/semver/internal/re.js create mode 100644 claude-code-source/node_modules/semver/ranges/gtr.js create mode 100644 claude-code-source/node_modules/semver/ranges/intersects.js create mode 100644 claude-code-source/node_modules/semver/ranges/ltr.js create mode 100644 claude-code-source/node_modules/semver/ranges/max-satisfying.js create mode 100644 claude-code-source/node_modules/semver/ranges/min-satisfying.js create mode 100644 claude-code-source/node_modules/semver/ranges/min-version.js create mode 100644 claude-code-source/node_modules/semver/ranges/outside.js create mode 100644 claude-code-source/node_modules/semver/ranges/simplify.js create mode 100644 claude-code-source/node_modules/semver/ranges/subset.js create mode 100644 claude-code-source/node_modules/semver/ranges/to-comparators.js create mode 100644 claude-code-source/node_modules/semver/ranges/valid.js create mode 100644 claude-code-source/node_modules/shell-quote/index.js create mode 100644 claude-code-source/node_modules/shell-quote/parse.js create mode 100644 claude-code-source/node_modules/shell-quote/quote.js create mode 100644 claude-code-source/node_modules/signal-exit/dist/mjs/index.js create mode 100644 claude-code-source/node_modules/signal-exit/dist/mjs/signals.js create mode 100644 claude-code-source/node_modules/stack-utils/index.js create mode 100644 claude-code-source/node_modules/stack-utils/node_modules/escape-string-regexp/index.js create mode 100644 claude-code-source/node_modules/strip-ansi/index.js create mode 100644 claude-code-source/node_modules/supports-hyperlinks/index.js create mode 100644 claude-code-source/node_modules/supports-hyperlinks/node_modules/supports-color/index.js create mode 100644 claude-code-source/node_modules/tree-kill/index.js create mode 100644 claude-code-source/node_modules/turndown/lib/turndown.cjs.js create mode 120000 claude-code-source/node_modules/type-fest create mode 120000 claude-code-source/node_modules/typescript create mode 100644 claude-code-source/node_modules/undici/index.js create mode 100644 claude-code-source/node_modules/undici/lib/api/abort-signal.js create mode 100644 claude-code-source/node_modules/undici/lib/api/api-connect.js create mode 100644 claude-code-source/node_modules/undici/lib/api/api-pipeline.js create mode 100644 claude-code-source/node_modules/undici/lib/api/api-request.js create mode 100644 claude-code-source/node_modules/undici/lib/api/api-stream.js create mode 100644 claude-code-source/node_modules/undici/lib/api/api-upgrade.js create mode 100644 claude-code-source/node_modules/undici/lib/api/index.js create mode 100644 claude-code-source/node_modules/undici/lib/api/readable.js create mode 100644 claude-code-source/node_modules/undici/lib/api/util.js create mode 100644 claude-code-source/node_modules/undici/lib/core/connect.js create mode 100644 claude-code-source/node_modules/undici/lib/core/constants.js create mode 100644 claude-code-source/node_modules/undici/lib/core/diagnostics.js create mode 100644 claude-code-source/node_modules/undici/lib/core/errors.js create mode 100644 claude-code-source/node_modules/undici/lib/core/request.js create mode 100644 claude-code-source/node_modules/undici/lib/core/symbols.js create mode 100644 claude-code-source/node_modules/undici/lib/core/tree.js create mode 100644 claude-code-source/node_modules/undici/lib/core/util.js create mode 100644 claude-code-source/node_modules/undici/lib/dispatcher/agent.js create mode 100644 claude-code-source/node_modules/undici/lib/dispatcher/balanced-pool.js create mode 100644 claude-code-source/node_modules/undici/lib/dispatcher/client-h1.js create mode 100644 claude-code-source/node_modules/undici/lib/dispatcher/client-h2.js create mode 100644 claude-code-source/node_modules/undici/lib/dispatcher/client.js create mode 100644 claude-code-source/node_modules/undici/lib/dispatcher/dispatcher-base.js create mode 100644 claude-code-source/node_modules/undici/lib/dispatcher/dispatcher.js create mode 100644 claude-code-source/node_modules/undici/lib/dispatcher/env-http-proxy-agent.js create mode 100644 claude-code-source/node_modules/undici/lib/dispatcher/fixed-queue.js create mode 100644 claude-code-source/node_modules/undici/lib/dispatcher/pool-base.js create mode 100644 claude-code-source/node_modules/undici/lib/dispatcher/pool-stats.js create mode 100644 claude-code-source/node_modules/undici/lib/dispatcher/pool.js create mode 100644 claude-code-source/node_modules/undici/lib/dispatcher/proxy-agent.js create mode 100644 claude-code-source/node_modules/undici/lib/dispatcher/retry-agent.js create mode 100644 claude-code-source/node_modules/undici/lib/global.js create mode 100644 claude-code-source/node_modules/undici/lib/handler/decorator-handler.js create mode 100644 claude-code-source/node_modules/undici/lib/handler/redirect-handler.js create mode 100644 claude-code-source/node_modules/undici/lib/handler/retry-handler.js create mode 100644 claude-code-source/node_modules/undici/lib/interceptor/dns.js create mode 100644 claude-code-source/node_modules/undici/lib/interceptor/dump.js create mode 100644 claude-code-source/node_modules/undici/lib/interceptor/redirect-interceptor.js create mode 100644 claude-code-source/node_modules/undici/lib/interceptor/redirect.js create mode 100644 claude-code-source/node_modules/undici/lib/interceptor/retry.js create mode 100644 claude-code-source/node_modules/undici/lib/llhttp/constants.js create mode 100644 claude-code-source/node_modules/undici/lib/llhttp/llhttp-wasm.js create mode 100644 claude-code-source/node_modules/undici/lib/llhttp/llhttp_simd-wasm.js create mode 100644 claude-code-source/node_modules/undici/lib/llhttp/utils.js create mode 100644 claude-code-source/node_modules/undici/lib/mock/mock-agent.js create mode 100644 claude-code-source/node_modules/undici/lib/mock/mock-client.js create mode 100644 claude-code-source/node_modules/undici/lib/mock/mock-errors.js create mode 100644 claude-code-source/node_modules/undici/lib/mock/mock-interceptor.js create mode 100644 claude-code-source/node_modules/undici/lib/mock/mock-pool.js create mode 100644 claude-code-source/node_modules/undici/lib/mock/mock-symbols.js create mode 100644 claude-code-source/node_modules/undici/lib/mock/mock-utils.js create mode 100644 claude-code-source/node_modules/undici/lib/mock/pending-interceptors-formatter.js create mode 100644 claude-code-source/node_modules/undici/lib/mock/pluralizer.js create mode 100644 claude-code-source/node_modules/undici/lib/util/timers.js create mode 100644 claude-code-source/node_modules/undici/lib/web/cache/cache.js create mode 100644 claude-code-source/node_modules/undici/lib/web/cache/cachestorage.js create mode 100644 claude-code-source/node_modules/undici/lib/web/cache/symbols.js create mode 100644 claude-code-source/node_modules/undici/lib/web/cache/util.js create mode 100644 claude-code-source/node_modules/undici/lib/web/cookies/constants.js create mode 100644 claude-code-source/node_modules/undici/lib/web/cookies/index.js create mode 100644 claude-code-source/node_modules/undici/lib/web/cookies/parse.js create mode 100644 claude-code-source/node_modules/undici/lib/web/cookies/util.js create mode 100644 claude-code-source/node_modules/undici/lib/web/eventsource/eventsource-stream.js create mode 100644 claude-code-source/node_modules/undici/lib/web/eventsource/eventsource.js create mode 100644 claude-code-source/node_modules/undici/lib/web/eventsource/util.js create mode 100644 claude-code-source/node_modules/undici/lib/web/fetch/body.js create mode 100644 claude-code-source/node_modules/undici/lib/web/fetch/constants.js create mode 100644 claude-code-source/node_modules/undici/lib/web/fetch/data-url.js create mode 100644 claude-code-source/node_modules/undici/lib/web/fetch/dispatcher-weakref.js create mode 100644 claude-code-source/node_modules/undici/lib/web/fetch/file.js create mode 100644 claude-code-source/node_modules/undici/lib/web/fetch/formdata-parser.js create mode 100644 claude-code-source/node_modules/undici/lib/web/fetch/formdata.js create mode 100644 claude-code-source/node_modules/undici/lib/web/fetch/global.js create mode 100644 claude-code-source/node_modules/undici/lib/web/fetch/headers.js create mode 100644 claude-code-source/node_modules/undici/lib/web/fetch/index.js create mode 100644 claude-code-source/node_modules/undici/lib/web/fetch/request.js create mode 100644 claude-code-source/node_modules/undici/lib/web/fetch/response.js create mode 100644 claude-code-source/node_modules/undici/lib/web/fetch/symbols.js create mode 100644 claude-code-source/node_modules/undici/lib/web/fetch/util.js create mode 100644 claude-code-source/node_modules/undici/lib/web/fetch/webidl.js create mode 100644 claude-code-source/node_modules/undici/lib/web/fileapi/encoding.js create mode 100644 claude-code-source/node_modules/undici/lib/web/fileapi/filereader.js create mode 100644 claude-code-source/node_modules/undici/lib/web/fileapi/progressevent.js create mode 100644 claude-code-source/node_modules/undici/lib/web/fileapi/symbols.js create mode 100644 claude-code-source/node_modules/undici/lib/web/fileapi/util.js create mode 100644 claude-code-source/node_modules/undici/lib/web/websocket/connection.js create mode 100644 claude-code-source/node_modules/undici/lib/web/websocket/constants.js create mode 100644 claude-code-source/node_modules/undici/lib/web/websocket/events.js create mode 100644 claude-code-source/node_modules/undici/lib/web/websocket/frame.js create mode 100644 claude-code-source/node_modules/undici/lib/web/websocket/permessage-deflate.js create mode 100644 claude-code-source/node_modules/undici/lib/web/websocket/receiver.js create mode 100644 claude-code-source/node_modules/undici/lib/web/websocket/sender.js create mode 100644 claude-code-source/node_modules/undici/lib/web/websocket/symbols.js create mode 100644 claude-code-source/node_modules/undici/lib/web/websocket/util.js create mode 100644 claude-code-source/node_modules/undici/lib/web/websocket/websocket.js create mode 100644 claude-code-source/node_modules/usehooks-ts/dist/index.js create mode 100644 claude-code-source/node_modules/uuid/dist/index.js create mode 100644 claude-code-source/node_modules/uuid/dist/md5.js create mode 100644 claude-code-source/node_modules/uuid/dist/nil.js create mode 100644 claude-code-source/node_modules/uuid/dist/parse.js create mode 100644 claude-code-source/node_modules/uuid/dist/regex.js create mode 100644 claude-code-source/node_modules/uuid/dist/rng.js create mode 100644 claude-code-source/node_modules/uuid/dist/sha1.js create mode 100644 claude-code-source/node_modules/uuid/dist/stringify.js create mode 100644 claude-code-source/node_modules/uuid/dist/v1.js create mode 100644 claude-code-source/node_modules/uuid/dist/v3.js create mode 100644 claude-code-source/node_modules/uuid/dist/v35.js create mode 100644 claude-code-source/node_modules/uuid/dist/v4.js create mode 100644 claude-code-source/node_modules/uuid/dist/v5.js create mode 100644 claude-code-source/node_modules/uuid/dist/validate.js create mode 100644 claude-code-source/node_modules/uuid/dist/version.js create mode 100644 claude-code-source/node_modules/vscode-jsonrpc/lib/common/api.js create mode 100644 claude-code-source/node_modules/vscode-jsonrpc/lib/common/cancellation.js create mode 100644 claude-code-source/node_modules/vscode-jsonrpc/lib/common/connection.js create mode 100644 claude-code-source/node_modules/vscode-jsonrpc/lib/common/disposable.js create mode 100644 claude-code-source/node_modules/vscode-jsonrpc/lib/common/events.js create mode 100644 claude-code-source/node_modules/vscode-jsonrpc/lib/common/is.js create mode 100644 claude-code-source/node_modules/vscode-jsonrpc/lib/common/linkedMap.js create mode 100644 claude-code-source/node_modules/vscode-jsonrpc/lib/common/messageBuffer.js create mode 100644 claude-code-source/node_modules/vscode-jsonrpc/lib/common/messageReader.js create mode 100644 claude-code-source/node_modules/vscode-jsonrpc/lib/common/messageWriter.js create mode 100644 claude-code-source/node_modules/vscode-jsonrpc/lib/common/messages.js create mode 100644 claude-code-source/node_modules/vscode-jsonrpc/lib/common/ral.js create mode 100644 claude-code-source/node_modules/vscode-jsonrpc/lib/common/semaphore.js create mode 100644 claude-code-source/node_modules/vscode-jsonrpc/lib/common/sharedArrayCancellation.js create mode 100644 claude-code-source/node_modules/vscode-jsonrpc/lib/node/main.js create mode 100644 claude-code-source/node_modules/vscode-jsonrpc/lib/node/ril.js create mode 120000 claude-code-source/node_modules/vscode-languageserver-protocol create mode 120000 claude-code-source/node_modules/vscode-languageserver-types create mode 100644 claude-code-source/node_modules/wrap-ansi/index.js create mode 100644 claude-code-source/node_modules/wrap-ansi/node_modules/string-width/index.js create mode 100644 claude-code-source/node_modules/wrap-ansi/node_modules/string-width/node_modules/emoji-regex/index.js create mode 100644 claude-code-source/node_modules/ws/lib/buffer-util.js create mode 100644 claude-code-source/node_modules/ws/lib/constants.js create mode 100644 claude-code-source/node_modules/ws/lib/event-target.js create mode 100644 claude-code-source/node_modules/ws/lib/extension.js create mode 100644 claude-code-source/node_modules/ws/lib/limiter.js create mode 100644 claude-code-source/node_modules/ws/lib/permessage-deflate.js create mode 100644 claude-code-source/node_modules/ws/lib/receiver.js create mode 100644 claude-code-source/node_modules/ws/lib/sender.js create mode 100644 claude-code-source/node_modules/ws/lib/stream.js create mode 100644 claude-code-source/node_modules/ws/lib/subprotocol.js create mode 100644 claude-code-source/node_modules/ws/lib/validation.js create mode 100644 claude-code-source/node_modules/ws/lib/websocket-server.js create mode 100644 claude-code-source/node_modules/ws/lib/websocket.js create mode 100644 claude-code-source/node_modules/ws/wrapper.mjs create mode 100644 claude-code-source/node_modules/xmlbuilder/lib/DocumentPosition.js create mode 100644 claude-code-source/node_modules/xmlbuilder/lib/NodeType.js create mode 100644 claude-code-source/node_modules/xmlbuilder/lib/Utility.js create mode 100644 claude-code-source/node_modules/xmlbuilder/lib/WriterState.js create mode 100644 claude-code-source/node_modules/xmlbuilder/lib/XMLAttribute.js create mode 100644 claude-code-source/node_modules/xmlbuilder/lib/XMLCData.js create mode 100644 claude-code-source/node_modules/xmlbuilder/lib/XMLCharacterData.js create mode 100644 claude-code-source/node_modules/xmlbuilder/lib/XMLComment.js create mode 100644 claude-code-source/node_modules/xmlbuilder/lib/XMLDOMConfiguration.js create mode 100644 claude-code-source/node_modules/xmlbuilder/lib/XMLDOMErrorHandler.js create mode 100644 claude-code-source/node_modules/xmlbuilder/lib/XMLDOMImplementation.js create mode 100644 claude-code-source/node_modules/xmlbuilder/lib/XMLDOMStringList.js create mode 100644 claude-code-source/node_modules/xmlbuilder/lib/XMLDTDAttList.js create mode 100644 claude-code-source/node_modules/xmlbuilder/lib/XMLDTDElement.js create mode 100644 claude-code-source/node_modules/xmlbuilder/lib/XMLDTDEntity.js create mode 100644 claude-code-source/node_modules/xmlbuilder/lib/XMLDTDNotation.js create mode 100644 claude-code-source/node_modules/xmlbuilder/lib/XMLDeclaration.js create mode 100644 claude-code-source/node_modules/xmlbuilder/lib/XMLDocType.js create mode 100644 claude-code-source/node_modules/xmlbuilder/lib/XMLDocument.js create mode 100644 claude-code-source/node_modules/xmlbuilder/lib/XMLDocumentCB.js create mode 100644 claude-code-source/node_modules/xmlbuilder/lib/XMLDummy.js create mode 100644 claude-code-source/node_modules/xmlbuilder/lib/XMLElement.js create mode 100644 claude-code-source/node_modules/xmlbuilder/lib/XMLNamedNodeMap.js create mode 100644 claude-code-source/node_modules/xmlbuilder/lib/XMLNode.js create mode 100644 claude-code-source/node_modules/xmlbuilder/lib/XMLNodeList.js create mode 100644 claude-code-source/node_modules/xmlbuilder/lib/XMLProcessingInstruction.js create mode 100644 claude-code-source/node_modules/xmlbuilder/lib/XMLRaw.js create mode 100644 claude-code-source/node_modules/xmlbuilder/lib/XMLStreamWriter.js create mode 100644 claude-code-source/node_modules/xmlbuilder/lib/XMLStringWriter.js create mode 100644 claude-code-source/node_modules/xmlbuilder/lib/XMLStringifier.js create mode 100644 claude-code-source/node_modules/xmlbuilder/lib/XMLText.js create mode 100644 claude-code-source/node_modules/xmlbuilder/lib/XMLWriterBase.js create mode 100644 claude-code-source/node_modules/xmlbuilder/lib/index.js create mode 100644 claude-code-source/node_modules/xss/lib/default.js create mode 100644 claude-code-source/node_modules/xss/lib/index.js create mode 100644 claude-code-source/node_modules/xss/lib/parser.js create mode 100644 claude-code-source/node_modules/xss/lib/util.js create mode 100644 claude-code-source/node_modules/xss/lib/xss.js create mode 100644 claude-code-source/node_modules/yaml/dist/compose/compose-collection.js create mode 100644 claude-code-source/node_modules/yaml/dist/compose/compose-doc.js create mode 100644 claude-code-source/node_modules/yaml/dist/compose/compose-node.js create mode 100644 claude-code-source/node_modules/yaml/dist/compose/compose-scalar.js create mode 100644 claude-code-source/node_modules/yaml/dist/compose/composer.js create mode 100644 claude-code-source/node_modules/yaml/dist/compose/resolve-block-map.js create mode 100644 claude-code-source/node_modules/yaml/dist/compose/resolve-block-scalar.js create mode 100644 claude-code-source/node_modules/yaml/dist/compose/resolve-block-seq.js create mode 100644 claude-code-source/node_modules/yaml/dist/compose/resolve-end.js create mode 100644 claude-code-source/node_modules/yaml/dist/compose/resolve-flow-collection.js create mode 100644 claude-code-source/node_modules/yaml/dist/compose/resolve-flow-scalar.js create mode 100644 claude-code-source/node_modules/yaml/dist/compose/resolve-props.js create mode 100644 claude-code-source/node_modules/yaml/dist/compose/util-contains-newline.js create mode 100644 claude-code-source/node_modules/yaml/dist/compose/util-empty-scalar-position.js create mode 100644 claude-code-source/node_modules/yaml/dist/compose/util-flow-indent-check.js create mode 100644 claude-code-source/node_modules/yaml/dist/compose/util-map-includes.js create mode 100644 claude-code-source/node_modules/yaml/dist/doc/Document.js create mode 100644 claude-code-source/node_modules/yaml/dist/doc/anchors.js create mode 100644 claude-code-source/node_modules/yaml/dist/doc/applyReviver.js create mode 100644 claude-code-source/node_modules/yaml/dist/doc/createNode.js create mode 100644 claude-code-source/node_modules/yaml/dist/doc/directives.js create mode 100644 claude-code-source/node_modules/yaml/dist/errors.js create mode 100644 claude-code-source/node_modules/yaml/dist/index.js create mode 100644 claude-code-source/node_modules/yaml/dist/log.js create mode 100644 claude-code-source/node_modules/yaml/dist/nodes/Alias.js create mode 100644 claude-code-source/node_modules/yaml/dist/nodes/Collection.js create mode 100644 claude-code-source/node_modules/yaml/dist/nodes/Node.js create mode 100644 claude-code-source/node_modules/yaml/dist/nodes/Pair.js create mode 100644 claude-code-source/node_modules/yaml/dist/nodes/Scalar.js create mode 100644 claude-code-source/node_modules/yaml/dist/nodes/YAMLMap.js create mode 100644 claude-code-source/node_modules/yaml/dist/nodes/YAMLSeq.js create mode 100644 claude-code-source/node_modules/yaml/dist/nodes/addPairToJSMap.js create mode 100644 claude-code-source/node_modules/yaml/dist/nodes/identity.js create mode 100644 claude-code-source/node_modules/yaml/dist/nodes/toJS.js create mode 100644 claude-code-source/node_modules/yaml/dist/parse/cst-scalar.js create mode 100644 claude-code-source/node_modules/yaml/dist/parse/cst-stringify.js create mode 100644 claude-code-source/node_modules/yaml/dist/parse/cst-visit.js create mode 100644 claude-code-source/node_modules/yaml/dist/parse/cst.js create mode 100644 claude-code-source/node_modules/yaml/dist/parse/lexer.js create mode 100644 claude-code-source/node_modules/yaml/dist/parse/line-counter.js create mode 100644 claude-code-source/node_modules/yaml/dist/parse/parser.js create mode 100644 claude-code-source/node_modules/yaml/dist/public-api.js create mode 100644 claude-code-source/node_modules/yaml/dist/schema/Schema.js create mode 100644 claude-code-source/node_modules/yaml/dist/schema/common/map.js create mode 100644 claude-code-source/node_modules/yaml/dist/schema/common/null.js create mode 100644 claude-code-source/node_modules/yaml/dist/schema/common/seq.js create mode 100644 claude-code-source/node_modules/yaml/dist/schema/common/string.js create mode 100644 claude-code-source/node_modules/yaml/dist/schema/core/bool.js create mode 100644 claude-code-source/node_modules/yaml/dist/schema/core/float.js create mode 100644 claude-code-source/node_modules/yaml/dist/schema/core/int.js create mode 100644 claude-code-source/node_modules/yaml/dist/schema/core/schema.js create mode 100644 claude-code-source/node_modules/yaml/dist/schema/json/schema.js create mode 100644 claude-code-source/node_modules/yaml/dist/schema/tags.js create mode 100644 claude-code-source/node_modules/yaml/dist/schema/yaml-1.1/binary.js create mode 100644 claude-code-source/node_modules/yaml/dist/schema/yaml-1.1/bool.js create mode 100644 claude-code-source/node_modules/yaml/dist/schema/yaml-1.1/float.js create mode 100644 claude-code-source/node_modules/yaml/dist/schema/yaml-1.1/int.js create mode 100644 claude-code-source/node_modules/yaml/dist/schema/yaml-1.1/merge.js create mode 100644 claude-code-source/node_modules/yaml/dist/schema/yaml-1.1/omap.js create mode 100644 claude-code-source/node_modules/yaml/dist/schema/yaml-1.1/pairs.js create mode 100644 claude-code-source/node_modules/yaml/dist/schema/yaml-1.1/schema.js create mode 100644 claude-code-source/node_modules/yaml/dist/schema/yaml-1.1/set.js create mode 100644 claude-code-source/node_modules/yaml/dist/schema/yaml-1.1/timestamp.js create mode 100644 claude-code-source/node_modules/yaml/dist/stringify/foldFlowLines.js create mode 100644 claude-code-source/node_modules/yaml/dist/stringify/stringify.js create mode 100644 claude-code-source/node_modules/yaml/dist/stringify/stringifyCollection.js create mode 100644 claude-code-source/node_modules/yaml/dist/stringify/stringifyComment.js create mode 100644 claude-code-source/node_modules/yaml/dist/stringify/stringifyDocument.js create mode 100644 claude-code-source/node_modules/yaml/dist/stringify/stringifyNumber.js create mode 100644 claude-code-source/node_modules/yaml/dist/stringify/stringifyPair.js create mode 100644 claude-code-source/node_modules/yaml/dist/stringify/stringifyString.js create mode 100644 claude-code-source/node_modules/yaml/dist/visit.js create mode 100644 claude-code-source/node_modules/zod-to-json-schema/dist/esm/Options.js create mode 100644 claude-code-source/node_modules/zod-to-json-schema/dist/esm/Refs.js create mode 100644 claude-code-source/node_modules/zod-to-json-schema/dist/esm/index.js create mode 100644 claude-code-source/node_modules/zod-to-json-schema/dist/esm/parseDef.js create mode 100644 claude-code-source/node_modules/zod-to-json-schema/dist/esm/parsers/array.js create mode 100644 claude-code-source/node_modules/zod-to-json-schema/dist/esm/parsers/branded.js create mode 100644 claude-code-source/node_modules/zod-to-json-schema/dist/esm/parsers/catch.js create mode 100644 claude-code-source/node_modules/zod-to-json-schema/dist/esm/parsers/default.js create mode 100644 claude-code-source/node_modules/zod-to-json-schema/dist/esm/parsers/effects.js create mode 100644 claude-code-source/node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js create mode 100644 claude-code-source/node_modules/zod-to-json-schema/dist/esm/parsers/map.js create mode 100644 claude-code-source/node_modules/zod-to-json-schema/dist/esm/parsers/never.js create mode 100644 claude-code-source/node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js create mode 100644 claude-code-source/node_modules/zod-to-json-schema/dist/esm/parsers/object.js create mode 100644 claude-code-source/node_modules/zod-to-json-schema/dist/esm/parsers/optional.js create mode 100644 claude-code-source/node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js create mode 100644 claude-code-source/node_modules/zod-to-json-schema/dist/esm/parsers/promise.js create mode 100644 claude-code-source/node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js create mode 100644 claude-code-source/node_modules/zod-to-json-schema/dist/esm/parsers/record.js create mode 100644 claude-code-source/node_modules/zod-to-json-schema/dist/esm/parsers/set.js create mode 100644 claude-code-source/node_modules/zod-to-json-schema/dist/esm/parsers/string.js create mode 100644 claude-code-source/node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js create mode 100644 claude-code-source/node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js create mode 100644 claude-code-source/node_modules/zod-to-json-schema/dist/esm/parsers/union.js create mode 100644 claude-code-source/node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js create mode 100644 claude-code-source/node_modules/zod-to-json-schema/dist/esm/selectParser.js create mode 100644 claude-code-source/node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js create mode 100644 claude-code-source/node_modules/zod/index.js create mode 100644 claude-code-source/node_modules/zod/v3/ZodError.js create mode 100644 claude-code-source/node_modules/zod/v3/errors.js create mode 100644 claude-code-source/node_modules/zod/v3/external.js create mode 100644 claude-code-source/node_modules/zod/v3/helpers/errorUtil.js create mode 100644 claude-code-source/node_modules/zod/v3/helpers/parseUtil.js create mode 100644 claude-code-source/node_modules/zod/v3/helpers/util.js create mode 100644 claude-code-source/node_modules/zod/v3/locales/en.js create mode 100644 claude-code-source/node_modules/zod/v3/types.js create mode 100644 claude-code-source/node_modules/zod/v4-mini/index.js create mode 100644 claude-code-source/node_modules/zod/v4/classic/checks.js create mode 100644 claude-code-source/node_modules/zod/v4/classic/coerce.js create mode 100644 claude-code-source/node_modules/zod/v4/classic/compat.js create mode 100644 claude-code-source/node_modules/zod/v4/classic/errors.js create mode 100644 claude-code-source/node_modules/zod/v4/classic/external.js create mode 100644 claude-code-source/node_modules/zod/v4/classic/index.js create mode 100644 claude-code-source/node_modules/zod/v4/classic/iso.js create mode 100644 claude-code-source/node_modules/zod/v4/classic/parse.js create mode 100644 claude-code-source/node_modules/zod/v4/classic/schemas.js create mode 100644 claude-code-source/node_modules/zod/v4/core/api.js create mode 100644 claude-code-source/node_modules/zod/v4/core/checks.js create mode 100644 claude-code-source/node_modules/zod/v4/core/core.js create mode 100644 claude-code-source/node_modules/zod/v4/core/doc.js create mode 100644 claude-code-source/node_modules/zod/v4/core/errors.js create mode 100644 claude-code-source/node_modules/zod/v4/core/function.js create mode 100644 claude-code-source/node_modules/zod/v4/core/index.js create mode 100644 claude-code-source/node_modules/zod/v4/core/parse.js create mode 100644 claude-code-source/node_modules/zod/v4/core/regexes.js create mode 100644 claude-code-source/node_modules/zod/v4/core/registries.js create mode 100644 claude-code-source/node_modules/zod/v4/core/schemas.js create mode 100644 claude-code-source/node_modules/zod/v4/core/to-json-schema.js create mode 100644 claude-code-source/node_modules/zod/v4/core/util.js create mode 100644 claude-code-source/node_modules/zod/v4/core/versions.js create mode 100644 claude-code-source/node_modules/zod/v4/index.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/ar.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/az.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/be.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/ca.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/cs.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/de.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/en.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/eo.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/es.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/fa.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/fi.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/fr-CA.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/fr.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/he.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/hu.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/id.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/index.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/it.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/ja.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/kh.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/ko.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/mk.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/ms.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/nl.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/no.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/ota.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/pl.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/ps.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/pt.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/ru.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/sl.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/sv.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/ta.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/th.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/tr.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/ua.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/ur.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/vi.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/zh-CN.js create mode 100644 claude-code-source/node_modules/zod/v4/locales/zh-TW.js create mode 100644 claude-code-source/node_modules/zod/v4/mini/external.js create mode 100644 claude-code-source/node_modules/zod/v4/mini/index.js create mode 100644 claude-code-source/node_modules/zod/v4/mini/parse.js diff --git a/claude-code-source/.gitignore b/claude-code-source/.gitignore index ce1864b0..5ba4fed6 100644 --- a/claude-code-source/.gitignore +++ b/claude-code-source/.gitignore @@ -1,91 +1,13 @@ -# Build output -dist/ +# Build output (top-level only, not node_modules/*/dist) +/dist/ -# pnpm internals (generated by pnpm install) +# pnpm internals (generated by pnpm install, not from source map) node_modules/.pnpm/ node_modules/.bin/ node_modules/.modules.yaml node_modules/.pnpm-workspace-state-v1.json -# pnpm-installed packages (symlinks to .pnpm, regenerated by pnpm install) -# --- scoped --- -node_modules/@alcalzone/ -node_modules/@anthropic-ai/bedrock-sdk/ -node_modules/@anthropic-ai/foundry-sdk/ -node_modules/@anthropic-ai/sdk/ -node_modules/@anthropic-ai/vertex-sdk/ -node_modules/@aws-crypto/ -node_modules/@aws-sdk/ -node_modules/@azure/ -node_modules/@commander-js/ -node_modules/@growthbook/ -node_modules/@modelcontextprotocol/ -node_modules/@opentelemetry/ -node_modules/@smithy/ -node_modules/@types/ -node_modules/@xmldom/ -# --- unscoped --- -node_modules/ajv/ -node_modules/ajv-formats/ -node_modules/asciichart/ -node_modules/auto-bind/ -node_modules/axios/ -node_modules/bidi-js/ -node_modules/bun-types/ -node_modules/chalk/ -node_modules/chokidar/ -node_modules/cli-boxes/ -node_modules/code-excerpt/ -node_modules/commander/ -node_modules/diff/ -node_modules/emoji-regex/ -node_modules/env-paths/ -node_modules/execa/ -node_modules/fflate/ -node_modules/figures/ -node_modules/fuse.js/ -node_modules/get-east-asian-width/ -node_modules/google-auth-library/ -node_modules/highlight.js/ -node_modules/https-proxy-agent/ -node_modules/ignore/ -node_modules/indent-string/ -node_modules/ink/ -node_modules/jsonc-parser/ -node_modules/lodash-es/ -node_modules/lru-cache/ -node_modules/marked/ -node_modules/p-map/ -node_modules/picomatch/ -node_modules/proper-lockfile/ -node_modules/qrcode/ -node_modules/react/ -node_modules/react-reconciler/ -node_modules/semver/ -node_modules/shell-quote/ -node_modules/signal-exit/ -node_modules/stack-utils/ -node_modules/strip-ansi/ -node_modules/supports-hyperlinks/ -node_modules/tree-kill/ -node_modules/turndown/ -node_modules/type-fest/ -node_modules/typescript/ -node_modules/undici/ -node_modules/usehooks-ts/ -node_modules/vscode-jsonrpc/ -node_modules/vscode-languageserver-protocol/ -node_modules/vscode-languageserver-types/ -node_modules/wrap-ansi/ -node_modules/ws/ -node_modules/xmlbuilder/ -node_modules/xss/ -node_modules/yaml/ -node_modules/zod/ -node_modules/zod-to-json-schema/ - -# pnpm-renamed source-map directories (stale, replaced by installed packages) -node_modules/**/.ignored_*/ -node_modules/.ignored_*/ +# pnpm artefacts: source-map dirs moved aside during install node_modules/.ignored/ -node_modules/.ignored_* +node_modules/.ignored_*/ +node_modules/**/.ignored_*/ diff --git a/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/ansiCodes.js b/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/ansiCodes.js new file mode 100644 index 00000000..7f7dacd2 --- /dev/null +++ b/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/ansiCodes.js @@ -0,0 +1,50 @@ +import ansiStyles from "ansi-styles"; +export const ESCAPES = new Set([27, 155]); // \x1b and \x9b +export const CSI = "[".codePointAt(0); +export const OSC = "]".codePointAt(0); +export const endCodesSet = new Set(); +const endCodesMap = new Map(); +for (const [start, end] of ansiStyles.codes) { + endCodesSet.add(ansiStyles.color.ansi(end)); + endCodesMap.set(ansiStyles.color.ansi(start), ansiStyles.color.ansi(end)); +} +export const linkStartCodePrefix = "\x1B]8;;"; +export const linkStartCodePrefixCharCodes = linkStartCodePrefix + .split("") + .map((char) => char.charCodeAt(0)); +export const linkCodeSuffix = "\x07"; +export const linkCodeSuffixCharCode = linkCodeSuffix.charCodeAt(0); +export const linkEndCode = `\x1B]8;;${linkCodeSuffix}`; +export function getLinkStartCode(url) { + return `${linkStartCodePrefix}${url}${linkCodeSuffix}`; +} +export function getEndCode(code) { + if (endCodesSet.has(code)) + return code; + if (endCodesMap.has(code)) + return endCodesMap.get(code); + // We have a few special cases to handle here: + // Links: + if (code.startsWith(linkStartCodePrefix)) + return linkEndCode; + code = code.slice(2); + // 8-bit/24-bit colors: + if (code.startsWith("38")) { + return ansiStyles.color.close; + } + else if (code.startsWith("48")) { + return ansiStyles.bgColor.close; + } + // Otherwise find the reset code in the ansi-styles map + const ret = ansiStyles.codes.get(parseInt(code, 10)); + if (ret) { + return ansiStyles.color.ansi(ret); + } + else { + return ansiStyles.reset.open; + } +} +export function ansiCodesToString(codes) { + return codes.map((code) => code.code).join(""); +} +//# sourceMappingURL=ansiCodes.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/diff.js b/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/diff.js new file mode 100644 index 00000000..8148779d --- /dev/null +++ b/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/diff.js @@ -0,0 +1,17 @@ +import { undoAnsiCodes } from "./undo.js"; +/** + * Returns the minimum amount of ANSI codes necessary to get from the compound style `from` to `to`. + * Both `from` and `to` are expected to be reduced. + */ +export function diffAnsiCodes(from, to) { + const endCodesInTo = new Set(to.map((code) => code.endCode)); + const startCodesInFrom = new Set(from.map((code) => code.code)); + return [ + // Ignore all styles in `from` that are not overwritten or removed by `to` + // Disable all styles in `from` that are removed in `to` + ...undoAnsiCodes(from.filter((code) => !endCodesInTo.has(code.endCode))), + // Add all styles in `to` that don't exist in `from` + ...to.filter((code) => !startCodesInFrom.has(code.code)), + ]; +} +//# sourceMappingURL=diff.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/index.js b/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/index.js new file mode 100644 index 00000000..9e66dca3 --- /dev/null +++ b/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/index.js @@ -0,0 +1,7 @@ +export { ansiCodesToString } from "./ansiCodes.js"; +export { diffAnsiCodes } from "./diff.js"; +export { reduceAnsiCodes, reduceAnsiCodesIncremental } from "./reduce.js"; +export * from "./styledChars.js"; +export * from "./tokenize.js"; +export { undoAnsiCodes } from "./undo.js"; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/reduce.js b/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/reduce.js new file mode 100644 index 00000000..0e91e9dc --- /dev/null +++ b/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/reduce.js @@ -0,0 +1,38 @@ +import ansiStyles from "ansi-styles"; +import { endCodesSet } from "./ansiCodes.js"; +/** Reduces the given array of ANSI codes to the minimum necessary to render with the same style */ +export function reduceAnsiCodes(codes) { + return reduceAnsiCodesIncremental([], codes); +} +/** Like {@link reduceAnsiCodes}, but assumes that `codes` is already reduced. Further reductions are only done for the items in `newCodes`. */ +export function reduceAnsiCodesIncremental(codes, newCodes) { + let ret = [...codes]; + for (const code of newCodes) { + if (code.code === ansiStyles.reset.open) { + // Reset code, disable all codes + ret = []; + } + else if (endCodesSet.has(code.code)) { + // This is an end code, disable all matching start codes + ret = ret.filter((retCode) => retCode.endCode !== code.code); + } + else { + // This is a start code. Remove codes it "overrides", then add it. + // If a new code has the same endCode, it "overrides" existing ones. + // Special case: Intensity codes (1m, 2m) can coexist (both end with 22m). + const isIntensityCode = code.code === ansiStyles.bold.open || code.code === ansiStyles.dim.open; + // Add intensity codes only if not already present + if (isIntensityCode) { + if (!ret.find((retCode) => retCode.code === code.code && retCode.endCode === code.endCode)) { + ret.push(code); + } + } + else { + ret = ret.filter((retCode) => retCode.endCode !== code.endCode); + ret.push(code); + } + } + } + return ret; +} +//# sourceMappingURL=reduce.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/styledChars.js b/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/styledChars.js new file mode 100644 index 00000000..13016ee6 --- /dev/null +++ b/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/styledChars.js @@ -0,0 +1,38 @@ +import { ansiCodesToString } from "./ansiCodes.js"; +import { diffAnsiCodes } from "./diff.js"; +import { reduceAnsiCodesIncremental } from "./reduce.js"; +export function styledCharsFromTokens(tokens) { + let codes = []; + const ret = []; + for (const token of tokens) { + if (token.type === "ansi") { + codes = reduceAnsiCodesIncremental(codes, [token]); + } + else if (token.type === "char") { + ret.push({ + ...token, + styles: [...codes], + }); + } + } + return ret; +} +export function styledCharsToString(chars) { + let ret = ""; + for (let i = 0; i < chars.length; i++) { + const char = chars[i]; + if (i === 0) { + ret += ansiCodesToString(char.styles); + } + else { + ret += ansiCodesToString(diffAnsiCodes(chars[i - 1].styles, char.styles)); + } + ret += char.value; + // reset active styles at the end of the string + if (i === chars.length - 1) { + ret += ansiCodesToString(diffAnsiCodes(char.styles, [])); + } + } + return ret; +} +//# sourceMappingURL=styledChars.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/tokenize.js b/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/tokenize.js new file mode 100644 index 00000000..0d2055e9 --- /dev/null +++ b/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/tokenize.js @@ -0,0 +1,141 @@ +import isFullwidthCodePoint from "is-fullwidth-code-point"; +import { CSI, ESCAPES, getEndCode, linkStartCodePrefix, linkStartCodePrefixCharCodes, OSC, } from "./ansiCodes.js"; +// HOT PATH: Use only basic string/char code operations for maximum performance +function parseLinkCode(string, offset) { + string = string.slice(offset); + for (let index = 1; index < linkStartCodePrefixCharCodes.length; index++) { + if (string.charCodeAt(index) !== linkStartCodePrefixCharCodes[index]) { + return undefined; + } + } + // This is a link code (with or without the URL part). Find the end of it. + const endIndex = string.indexOf("\x07", linkStartCodePrefix.length); + if (endIndex === -1) + return undefined; + return string.slice(0, endIndex + 1); +} +const CC_0 = "0".charCodeAt(0); +const CC_9 = "9".charCodeAt(0); +const CC_SEMI = ";".charCodeAt(0); +const CC_M = "m".charCodeAt(0); +/** + * Scans through the given string and finds the index of the last character of an SGR sequence + * like `\x1B[38;2;123;123;123m`. This assumes that the string has been checked to start with `\x1B[`. + * Returns -1 if no valid SGR sequence is found. + */ +function findSGRSequenceEndIndex(str) { + for (let index = 2; index < str.length; index++) { + const charCode = str.charCodeAt(index); + // m marks the end of the SGR sequence + if (charCode === CC_M) + return index; + // Digits and semicolons are valid + if (charCode === CC_SEMI) + continue; + if (charCode >= CC_0 && charCode <= CC_9) + continue; + // Everything else is invalid + break; + } + return -1; +} +// HOT PATH: Use only basic string/char code operations for maximum performance +function parseSGRSequence(string, offset) { + string = string.slice(offset); + const endIndex = findSGRSequenceEndIndex(string); + if (endIndex === -1) + return; + return string.slice(0, endIndex + 1); +} +/** + * Splits compound SGR sequences like `\x1B[1;3;31m` into individual components + */ +function splitCompoundSGRSequences(code) { + if (!code.includes(";")) { + // Not a compound code + return [code]; + } + const codeParts = code + // Strip off the escape sequences \x1B[ and m + .slice(2, -1) + .split(";"); + const ret = []; + for (let i = 0; i < codeParts.length; i++) { + const rawCode = codeParts[i]; + // Keep 8-bit and 24-bit color codes (containing multiple ";") together + if (rawCode === "38" || rawCode === "48") { + if (i + 2 < codeParts.length && codeParts[i + 1] === "5") { + // 8-bit color, followed by another number + ret.push(codeParts.slice(i, i + 3).join(";")); + i += 2; + continue; + } + else if (i + 4 < codeParts.length && codeParts[i + 1] === "2") { + // 24-bit color, followed by three numbers + ret.push(codeParts.slice(i, i + 5).join(";")); + i += 4; + continue; + } + } + // Not a (valid) 8/24-bit color code, push as is + ret.push(rawCode); + } + return ret.map((part) => `\x1b[${part}m`); +} +export function tokenize(str, endChar = Number.POSITIVE_INFINITY) { + const ret = []; + let index = 0; + let visible = 0; + while (index < str.length) { + const codePoint = str.codePointAt(index); + if (ESCAPES.has(codePoint)) { + let code; + // Peek the next code point to determine the type of ANSI sequence + const nextCodePoint = str.codePointAt(index + 1); + if (nextCodePoint === OSC) { + // ] = operating system commands, like links + code = parseLinkCode(str, index); + if (code) { + ret.push({ + type: "ansi", + code: code, + endCode: getEndCode(code), + }); + } + } + else if (nextCodePoint === CSI) { + // [ = control sequence introducer, like SGR sequences [...m + code = parseSGRSequence(str, index); + if (code) { + // Split compound codes into individual tokens + const codes = splitCompoundSGRSequences(code); + for (const individualCode of codes) { + ret.push({ + type: "ansi", + code: individualCode, + endCode: getEndCode(individualCode), + }); + } + } + } + if (code) { + index += code.length; + continue; + } + } + const fullWidth = isFullwidthCodePoint(codePoint); + const character = String.fromCodePoint(codePoint); + ret.push({ + type: "char", + value: character, + fullWidth, + }); + index += character.length; + visible += fullWidth ? 2 : character.length; + if (visible >= endChar) { + break; + } + } + return ret; +} +//# sourceMappingURL=tokenize.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/undo.js b/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/undo.js new file mode 100644 index 00000000..9465b411 --- /dev/null +++ b/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/undo.js @@ -0,0 +1,11 @@ +import { reduceAnsiCodes } from "./reduce.js"; +/** Returns the combination of ANSI codes needed to undo the given ANSI codes */ +export function undoAnsiCodes(codes) { + return reduceAnsiCodes(codes) + .reverse() + .map((code) => ({ + ...code, + code: code.endCode, + })); +} +//# sourceMappingURL=undo.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/AWS_restJson1.mjs b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/AWS_restJson1.mjs new file mode 100644 index 00000000..7f7417c9 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/AWS_restJson1.mjs @@ -0,0 +1,163 @@ +// Copied from https://github.com/aws/aws-sdk-js-v3/blob/bee66fbd2a519a16b57c787b2689af857af720af/clients/client-bedrock-runtime/src/protocols/Aws_restJson1.ts +// Modified to remove unnecessary code (we only need to call `de_ResponseStream`) and to adjust imports. +import { collectBody, decorateServiceException as __decorateServiceException, expectInt32 as __expectInt32, expectString as __expectString, map, take, } from '@smithy/smithy-client'; +import { InternalServerException, ModelStreamErrorException, ThrottlingException, ValidationException, } from '@aws-sdk/client-bedrock-runtime'; +/** + * deserializeAws_restJson1InternalServerExceptionRes + */ +const de_InternalServerExceptionRes = async (parsedOutput, context) => { + const contents = map({}); + const data = parsedOutput.body; + const doc = take(data, { + message: __expectString, + }); + Object.assign(contents, doc); + const exception = new InternalServerException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents, + }); + return __decorateServiceException(exception, parsedOutput.body); +}; +/** + * deserializeAws_restJson1ModelStreamErrorExceptionRes + */ +const de_ModelStreamErrorExceptionRes = async (parsedOutput, context) => { + const contents = map({}); + const data = parsedOutput.body; + const doc = take(data, { + message: __expectString, + originalMessage: __expectString, + originalStatusCode: __expectInt32, + }); + Object.assign(contents, doc); + const exception = new ModelStreamErrorException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents, + }); + return __decorateServiceException(exception, parsedOutput.body); +}; +/** + * deserializeAws_restJson1ThrottlingExceptionRes + */ +const de_ThrottlingExceptionRes = async (parsedOutput, context) => { + const contents = map({}); + const data = parsedOutput.body; + const doc = take(data, { + message: __expectString, + }); + Object.assign(contents, doc); + const exception = new ThrottlingException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents, + }); + return __decorateServiceException(exception, parsedOutput.body); +}; +/** + * deserializeAws_restJson1ValidationExceptionRes + */ +const de_ValidationExceptionRes = async (parsedOutput, context) => { + const contents = map({}); + const data = parsedOutput.body; + const doc = take(data, { + message: __expectString, + }); + Object.assign(contents, doc); + const exception = new ValidationException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents, + }); + return __decorateServiceException(exception, parsedOutput.body); +}; +/** + * deserializeAws_restJson1ResponseStream + */ +export const de_ResponseStream = (output, context) => { + return context.eventStreamMarshaller.deserialize(output, async (event) => { + if (event['chunk'] != null) { + return { + chunk: await de_PayloadPart_event(event['chunk'], context), + }; + } + if (event['internalServerException'] != null) { + return { + internalServerException: await de_InternalServerException_event(event['internalServerException'], context), + }; + } + if (event['modelStreamErrorException'] != null) { + return { + modelStreamErrorException: await de_ModelStreamErrorException_event(event['modelStreamErrorException'], context), + }; + } + if (event['validationException'] != null) { + return { + validationException: await de_ValidationException_event(event['validationException'], context), + }; + } + if (event['throttlingException'] != null) { + return { + throttlingException: await de_ThrottlingException_event(event['throttlingException'], context), + }; + } + return { $unknown: output }; + }); +}; +const de_InternalServerException_event = async (output, context) => { + const parsedOutput = { + ...output, + body: await parseBody(output.body, context), + }; + return de_InternalServerExceptionRes(parsedOutput, context); +}; +const de_ModelStreamErrorException_event = async (output, context) => { + const parsedOutput = { + ...output, + body: await parseBody(output.body, context), + }; + return de_ModelStreamErrorExceptionRes(parsedOutput, context); +}; +const de_PayloadPart_event = async (output, context) => { + const contents = {}; + const data = await parseBody(output.body, context); + Object.assign(contents, de_PayloadPart(data, context)); + return contents; +}; +const de_ThrottlingException_event = async (output, context) => { + const parsedOutput = { + ...output, + body: await parseBody(output.body, context), + }; + return de_ThrottlingExceptionRes(parsedOutput, context); +}; +const de_ValidationException_event = async (output, context) => { + const parsedOutput = { + ...output, + body: await parseBody(output.body, context), + }; + return de_ValidationExceptionRes(parsedOutput, context); +}; +/** + * deserializeAws_restJson1PayloadPart + */ +const de_PayloadPart = (output, context) => { + return take(output, { + bytes: context.base64Decoder, + }); +}; +const deserializeMetadata = (output) => ({ + httpStatusCode: output.statusCode, + requestId: output.headers['x-amzn-requestid'] ?? + output.headers['x-amzn-request-id'] ?? + output.headers['x-amz-request-id'] ?? + '', + extendedRequestId: output.headers['x-amz-id-2'] ?? '', + cfId: output.headers['x-amz-cf-id'] ?? '', +}); +// Encode Uint8Array data into string with utf-8. +const collectBodyString = (streamBody, context) => collectBody(streamBody, context).then((body) => context.utf8Encoder(body)); +const parseBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { + if (encoded.length) { + return JSON.parse(encoded); + } + return {}; +}); +//# sourceMappingURL=AWS_restJson1.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/client.mjs b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/client.mjs new file mode 100644 index 00000000..b8d14b13 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/client.mjs @@ -0,0 +1,124 @@ +import { BaseAnthropic } from '@anthropic-ai/sdk/client'; +import * as Resources from '@anthropic-ai/sdk/resources/index'; +import { getAuthHeaders } from "./core/auth.mjs"; +import { Stream } from "./core/streaming.mjs"; +import { readEnv } from "./internal/utils/env.mjs"; +import { isObj } from "./internal/utils/values.mjs"; +import { buildHeaders } from "./internal/headers.mjs"; +import { path } from "./internal/utils/path.mjs"; +export { BaseAnthropic } from '@anthropic-ai/sdk/client'; +const DEFAULT_VERSION = 'bedrock-2023-05-31'; +const MODEL_ENDPOINTS = new Set(['/v1/complete', '/v1/messages', '/v1/messages?beta=true']); +/** API Client for interfacing with the Anthropic Bedrock API. */ +export class AnthropicBedrock extends BaseAnthropic { + /** + * API Client for interfacing with the Anthropic Bedrock API. + * + * @param {string | null | undefined} [opts.awsSecretKey] + * @param {string | null | undefined} [opts.awsAccessKey] + * @param {string | undefined} [opts.awsRegion=process.env['AWS_REGION'] ?? us-east-1] + * @param {string | null | undefined} [opts.awsSessionToken] + * @param {(() => Promise) | null} [opts.providerChainResolver] - Custom provider chain resolver for AWS credentials. Useful for non-Node environments. + * @param {string} [opts.baseURL=process.env['ANTHROPIC_BEDROCK_BASE_URL'] ?? https://bedrock-runtime.${this.awsRegion}.amazonaws.com] - Override the default base URL for the API. + * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. + * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. + * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. + * @param {boolean} [opts.skipAuth=false] - Skip authentication for this request. This is useful if you have an internal proxy that handles authentication for you. + */ + constructor({ awsRegion = readEnv('AWS_REGION') ?? 'us-east-1', baseURL = readEnv('ANTHROPIC_BEDROCK_BASE_URL') ?? `https://bedrock-runtime.${awsRegion}.amazonaws.com`, awsSecretKey = null, awsAccessKey = null, awsSessionToken = null, providerChainResolver = null, ...opts } = {}) { + super({ + baseURL, + ...opts, + }); + this.skipAuth = false; + this.messages = makeMessagesResource(this); + this.completions = new Resources.Completions(this); + this.beta = makeBetaResource(this); + this.awsSecretKey = awsSecretKey; + this.awsAccessKey = awsAccessKey; + this.awsRegion = awsRegion; + this.awsSessionToken = awsSessionToken; + this.skipAuth = opts.skipAuth ?? false; + this.providerChainResolver = providerChainResolver; + } + validateHeaders() { + // auth validation is handled in prepareRequest since it needs to be async + } + async prepareRequest(request, { url, options }) { + if (this.skipAuth) { + return; + } + const regionName = this.awsRegion; + if (!regionName) { + throw new Error('Expected `awsRegion` option to be passed to the client or the `AWS_REGION` environment variable to be present'); + } + const headers = await getAuthHeaders(request, { + url, + regionName, + awsAccessKey: this.awsAccessKey, + awsSecretKey: this.awsSecretKey, + awsSessionToken: this.awsSessionToken, + fetchOptions: this.fetchOptions, + providerChainResolver: this.providerChainResolver, + }); + request.headers = buildHeaders([headers, request.headers]).values; + } + async buildRequest(options) { + options.__streamClass = Stream; + if (isObj(options.body)) { + // create a shallow copy of the request body so that code that mutates it later + // doesn't mutate the original user-provided object + options.body = { ...options.body }; + } + if (isObj(options.body)) { + if (!options.body['anthropic_version']) { + options.body['anthropic_version'] = DEFAULT_VERSION; + } + if (options.headers && !options.body['anthropic_beta']) { + const betas = buildHeaders([options.headers]).values.get('anthropic-beta'); + if (betas != null) { + options.body['anthropic_beta'] = betas.split(','); + } + } + } + if (MODEL_ENDPOINTS.has(options.path) && options.method === 'post') { + if (!isObj(options.body)) { + throw new Error('Expected request body to be an object for post /v1/messages'); + } + const model = options.body['model']; + options.body['model'] = undefined; + const stream = options.body['stream']; + options.body['stream'] = undefined; + if (stream) { + options.path = path `/model/${model}/invoke-with-response-stream`; + } + else { + options.path = path `/model/${model}/invoke`; + } + } + return super.buildRequest(options); + } +} +function makeMessagesResource(client) { + const resource = new Resources.Messages(client); + // @ts-expect-error we're deleting non-optional properties + delete resource.batches; + // @ts-expect-error we're deleting non-optional properties + delete resource.countTokens; + return resource; +} +function makeBetaResource(client) { + const resource = new Resources.Beta(client); + // @ts-expect-error we're deleting non-optional properties + delete resource.promptCaching; + // @ts-expect-error we're deleting non-optional properties + delete resource.messages.batches; + // @ts-expect-error we're deleting non-optional properties + delete resource.messages.countTokens; + return resource; +} +//# sourceMappingURL=client.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/core/auth.mjs b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/core/auth.mjs new file mode 100644 index 00000000..05bf307d --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/core/auth.mjs @@ -0,0 +1,82 @@ +import { Sha256 } from '@aws-crypto/sha256-js'; +import { FetchHttpHandler } from '@smithy/fetch-http-handler'; +import { HttpRequest } from '@smithy/protocol-http'; +import { SignatureV4 } from '@smithy/signature-v4'; +import assert from 'assert'; +const DEFAULT_PROVIDER_CHAIN_RESOLVER = () => import('@aws-sdk/credential-providers').then(({ fromNodeProviderChain }) => fromNodeProviderChain({ + clientConfig: { + requestHandler: new FetchHttpHandler({ + requestInit: (httpRequest) => { + return { + ...httpRequest, + }; + }, + }), + }, +})) + .catch((error) => { + throw new Error(`Failed to import '@aws-sdk/credential-providers'.` + + `You can provide a custom \`providerChainResolver\` in the client options if your runtime does not have access to '@aws-sdk/credential-providers': ` + + `\`new AnthropicBedrock({ providerChainResolver })\` ` + + `Original error: ${error.message}`); +}); +export const getAuthHeaders = async (req, props) => { + assert(req.method, 'Expected request method property to be set'); + const providerChain = await (props.providerChainResolver ? + props.providerChainResolver() + : DEFAULT_PROVIDER_CHAIN_RESOLVER()); + const credentials = await withTempEnv(() => { + // Temporarily set the appropriate environment variables if we've been + // explicitly given credentials so that the credentials provider can + // resolve them. + // + // Note: the environment provider is only not run first if the `AWS_PROFILE` + // environment variable is set. + // https://github.com/aws/aws-sdk-js-v3/blob/44a18a34b2c93feccdfcd162928d13e6dbdcaf30/packages/credential-provider-node/src/defaultProvider.ts#L49 + if (props.awsAccessKey) { + process.env['AWS_ACCESS_KEY_ID'] = props.awsAccessKey; + } + if (props.awsSecretKey) { + process.env['AWS_SECRET_ACCESS_KEY'] = props.awsSecretKey; + } + if (props.awsSessionToken) { + process.env['AWS_SESSION_TOKEN'] = props.awsSessionToken; + } + }, () => providerChain()); + const signer = new SignatureV4({ + service: 'bedrock', + region: props.regionName, + credentials, + sha256: Sha256, + }); + const url = new URL(props.url); + const headers = !req.headers ? {} + : Symbol.iterator in req.headers ? + Object.fromEntries(Array.from(req.headers).map((header) => [...header])) + : { ...req.headers }; + // The connection header may be stripped by a proxy somewhere, so the receiver + // of this message may not see this header, so we remove it from the set of headers + // that are signed. + delete headers['connection']; + headers['host'] = url.hostname; + const request = new HttpRequest({ + method: req.method.toUpperCase(), + protocol: url.protocol, + path: url.pathname, + headers, + body: req.body, + }); + const signed = await signer.sign(request); + return signed.headers; +}; +const withTempEnv = async (updateEnv, fn) => { + const previousEnv = { ...process.env }; + try { + updateEnv(); + return await fn(); + } + finally { + process.env = previousEnv; + } +}; +//# sourceMappingURL=auth.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/core/error.mjs b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/core/error.mjs new file mode 100644 index 00000000..ea9269e5 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/core/error.mjs @@ -0,0 +1,2 @@ +export * from '@anthropic-ai/sdk/core/error'; +//# sourceMappingURL=error.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/core/streaming.mjs b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/core/streaming.mjs new file mode 100644 index 00000000..af05ecd9 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/core/streaming.mjs @@ -0,0 +1,108 @@ +import { EventStreamMarshaller } from '@smithy/eventstream-serde-node'; +import { fromBase64, toBase64 } from '@smithy/util-base64'; +import { streamCollector } from '@smithy/fetch-http-handler'; +import { Stream as CoreStream } from '@anthropic-ai/sdk/streaming'; +import { AnthropicError } from '@anthropic-ai/sdk/error'; +import { APIError } from '@anthropic-ai/sdk'; +import { de_ResponseStream } from "../AWS_restJson1.mjs"; +import { ReadableStreamToAsyncIterable } from "../internal/shims.mjs"; +import { safeJSON } from "../internal/utils/values.mjs"; +import { loggerFor } from "../internal/utils/log.mjs"; +export const toUtf8 = (input) => new TextDecoder('utf-8').decode(input); +export const fromUtf8 = (input) => new TextEncoder().encode(input); +// `de_ResponseStream` parses a Bedrock response stream and emits events as they are found. +// It requires a "context" argument which has many fields, but for what we're using it for +// it only needs this. +export const getMinimalSerdeContext = () => { + const marshaller = new EventStreamMarshaller({ utf8Encoder: toUtf8, utf8Decoder: fromUtf8 }); + return { + base64Decoder: fromBase64, + base64Encoder: toBase64, + utf8Decoder: fromUtf8, + utf8Encoder: toUtf8, + eventStreamMarshaller: marshaller, + streamCollector: streamCollector, + }; +}; +export class Stream extends CoreStream { + static fromSSEResponse(response, controller, client) { + let consumed = false; + const logger = client ? loggerFor(client) : console; + async function* iterMessages() { + if (!response.body) { + controller.abort(); + throw new AnthropicError(`Attempted to iterate over a response with no body`); + } + const responseBodyIter = ReadableStreamToAsyncIterable(response.body); + const eventStream = de_ResponseStream(responseBodyIter, getMinimalSerdeContext()); + for await (const event of eventStream) { + if (event.chunk && event.chunk.bytes) { + const s = toUtf8(event.chunk.bytes); + yield { event: 'chunk', data: s, raw: [] }; + } + else if (event.internalServerException) { + yield { event: 'error', data: 'InternalServerException', raw: [] }; + } + else if (event.modelStreamErrorException) { + yield { event: 'error', data: 'ModelStreamErrorException', raw: [] }; + } + else if (event.validationException) { + yield { event: 'error', data: 'ValidationException', raw: [] }; + } + else if (event.throttlingException) { + yield { event: 'error', data: 'ThrottlingException', raw: [] }; + } + } + } + // Note: this function is copied entirely from the core SDK + async function* iterator() { + if (consumed) { + throw new Error('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); + } + consumed = true; + let done = false; + try { + for await (const sse of iterMessages()) { + if (sse.event === 'chunk') { + try { + yield JSON.parse(sse.data); + } + catch (e) { + logger.error(`Could not parse message into JSON:`, sse.data); + logger.error(`From chunk:`, sse.raw); + throw e; + } + } + if (sse.event === 'error') { + const errText = sse.data; + const errJSON = safeJSON(errText); + const errMessage = errJSON ? undefined : errText; + throw APIError.generate(undefined, errJSON, errMessage, response.headers); + } + } + done = true; + } + catch (e) { + // If the user calls `stream.controller.abort()`, we should exit without throwing. + if (isAbortError(e)) + return; + throw e; + } + finally { + // If the user `break`s, abort the ongoing request. + if (!done) + controller.abort(); + } + } + return new Stream(iterator, controller); + } +} +function isAbortError(err) { + return (typeof err === 'object' && + err !== null && + // Spec-compliant fetch implementations + (('name' in err && err.name === 'AbortError') || + // Expo fetch + ('message' in err && String(err.message).includes('FetchRequestCanceledException')))); +} +//# sourceMappingURL=streaming.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/index.mjs b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/index.mjs new file mode 100644 index 00000000..11c1728f --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/index.mjs @@ -0,0 +1,3 @@ +export * from "./client.mjs"; +export { AnthropicBedrock as default } from "./client.mjs"; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/headers.mjs b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/headers.mjs new file mode 100644 index 00000000..94b059b4 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/headers.mjs @@ -0,0 +1,74 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { isReadonlyArray } from "./utils/values.mjs"; +const brand_privateNullableHeaders = Symbol.for('brand.privateNullableHeaders'); +function* iterateHeaders(headers) { + if (!headers) + return; + if (brand_privateNullableHeaders in headers) { + const { values, nulls } = headers; + yield* values.entries(); + for (const name of nulls) { + yield [name, null]; + } + return; + } + let shouldClear = false; + let iter; + if (headers instanceof Headers) { + iter = headers.entries(); + } + else if (isReadonlyArray(headers)) { + iter = headers; + } + else { + shouldClear = true; + iter = Object.entries(headers ?? {}); + } + for (let row of iter) { + const name = row[0]; + if (typeof name !== 'string') + throw new TypeError('expected header name to be a string'); + const values = isReadonlyArray(row[1]) ? row[1] : [row[1]]; + let didClear = false; + for (const value of values) { + if (value === undefined) + continue; + // Objects keys always overwrite older headers, they never append. + // Yield a null to clear the header before adding the new values. + if (shouldClear && !didClear) { + didClear = true; + yield [name, null]; + } + yield [name, value]; + } + } +} +export const buildHeaders = (newHeaders) => { + const targetHeaders = new Headers(); + const nullHeaders = new Set(); + for (const headers of newHeaders) { + const seenHeaders = new Set(); + for (const [name, value] of iterateHeaders(headers)) { + const lowerName = name.toLowerCase(); + if (!seenHeaders.has(lowerName)) { + targetHeaders.delete(name); + seenHeaders.add(lowerName); + } + if (value === null) { + targetHeaders.delete(name); + nullHeaders.add(lowerName); + } + else { + targetHeaders.append(name, value); + nullHeaders.delete(lowerName); + } + } + } + return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders }; +}; +export const isEmptyHeaders = (headers) => { + for (const _ of iterateHeaders(headers)) + return false; + return true; +}; +//# sourceMappingURL=headers.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/shims.mjs b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/shims.mjs new file mode 100644 index 00000000..c511fe86 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/shims.mjs @@ -0,0 +1,85 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +export function getDefaultFetch() { + if (typeof fetch !== 'undefined') { + return fetch; + } + throw new Error('`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`'); +} +export function makeReadableStream(...args) { + const ReadableStream = globalThis.ReadableStream; + if (typeof ReadableStream === 'undefined') { + // Note: All of the platforms / runtimes we officially support already define + // `ReadableStream` as a global, so this should only ever be hit on unsupported runtimes. + throw new Error('`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`'); + } + return new ReadableStream(...args); +} +export function ReadableStreamFrom(iterable) { + let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); + return makeReadableStream({ + start() { }, + async pull(controller) { + const { done, value } = await iter.next(); + if (done) { + controller.close(); + } + else { + controller.enqueue(value); + } + }, + async cancel() { + await iter.return?.(); + }, + }); +} +/** + * Most browsers don't yet have async iterable support for ReadableStream, + * and Node has a very different way of reading bytes from its "ReadableStream". + * + * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490 + */ +export function ReadableStreamToAsyncIterable(stream) { + if (stream[Symbol.asyncIterator]) + return stream; + const reader = stream.getReader(); + return { + async next() { + try { + const result = await reader.read(); + if (result?.done) + reader.releaseLock(); // release lock when stream becomes closed + return result; + } + catch (e) { + reader.releaseLock(); // release lock when stream becomes errored + throw e; + } + }, + async return() { + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; + return { done: true, value: undefined }; + }, + [Symbol.asyncIterator]() { + return this; + }, + }; +} +/** + * Cancels a ReadableStream we don't need to consume. + * See https://undici.nodejs.org/#/?id=garbage-collection + */ +export async function CancelReadableStream(stream) { + if (stream === null || typeof stream !== 'object') + return; + if (stream[Symbol.asyncIterator]) { + await stream[Symbol.asyncIterator]().return?.(); + return; + } + const reader = stream.getReader(); + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; +} +//# sourceMappingURL=shims.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/utils/env.mjs b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/utils/env.mjs new file mode 100644 index 00000000..58ddfda1 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/utils/env.mjs @@ -0,0 +1,18 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +/** + * Read an environment variable. + * + * Trims beginning and trailing whitespace. + * + * Will return undefined if the environment variable doesn't exist or cannot be accessed. + */ +export const readEnv = (env) => { + if (typeof globalThis.process !== 'undefined') { + return globalThis.process.env?.[env]?.trim() ?? undefined; + } + if (typeof globalThis.Deno !== 'undefined') { + return globalThis.Deno.env?.get?.(env)?.trim(); + } + return undefined; +}; +//# sourceMappingURL=env.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/utils/log.mjs b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/utils/log.mjs new file mode 100644 index 00000000..95cdd225 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/utils/log.mjs @@ -0,0 +1,80 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { hasOwn } from "./values.mjs"; +const levelNumbers = { + off: 0, + error: 200, + warn: 300, + info: 400, + debug: 500, +}; +export const parseLogLevel = (maybeLevel, sourceName, client) => { + if (!maybeLevel) { + return undefined; + } + if (hasOwn(levelNumbers, maybeLevel)) { + return maybeLevel; + } + loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`); + return undefined; +}; +function noop() { } +function makeLogFn(fnLevel, logger, logLevel) { + if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) { + return noop; + } + else { + // Don't wrap logger functions, we want the stacktrace intact! + return logger[fnLevel].bind(logger); + } +} +const noopLogger = { + error: noop, + warn: noop, + info: noop, + debug: noop, +}; +let cachedLoggers = /* @__PURE__ */ new WeakMap(); +export function loggerFor(client) { + const logger = client.logger; + const logLevel = client.logLevel ?? 'off'; + if (!logger) { + return noopLogger; + } + const cachedLogger = cachedLoggers.get(logger); + if (cachedLogger && cachedLogger[0] === logLevel) { + return cachedLogger[1]; + } + const levelLogger = { + error: makeLogFn('error', logger, logLevel), + warn: makeLogFn('warn', logger, logLevel), + info: makeLogFn('info', logger, logLevel), + debug: makeLogFn('debug', logger, logLevel), + }; + cachedLoggers.set(logger, [logLevel, levelLogger]); + return levelLogger; +} +export const formatRequestDetails = (details) => { + if (details.options) { + details.options = { ...details.options }; + delete details.options['headers']; // redundant + leaks internals + } + if (details.headers) { + details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ + name, + (name.toLowerCase() === 'x-api-key' || + name.toLowerCase() === 'authorization' || + name.toLowerCase() === 'cookie' || + name.toLowerCase() === 'set-cookie') ? + '***' + : value, + ])); + } + if ('retryOfRequestLogID' in details) { + if (details.retryOfRequestLogID) { + details.retryOf = details.retryOfRequestLogID; + } + delete details.retryOfRequestLogID; + } + return details; +}; +//# sourceMappingURL=log.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/utils/path.mjs b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/utils/path.mjs new file mode 100644 index 00000000..0586cbe1 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/utils/path.mjs @@ -0,0 +1,74 @@ +import { AnthropicError } from "../../core/error.mjs"; +/** + * Percent-encode everything that isn't safe to have in a path without encoding safe chars. + * + * Taken from https://datatracker.ietf.org/doc/html/rfc3986#section-3.3: + * > unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" + * > sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" + * > pchar = unreserved / pct-encoded / sub-delims / ":" / "@" + */ +export function encodeURIPath(str) { + return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); +} +const EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); +export const createPathTagFunction = (pathEncoder = encodeURIPath) => function path(statics, ...params) { + // If there are no params, no processing is needed. + if (statics.length === 1) + return statics[0]; + let postPath = false; + const invalidSegments = []; + const path = statics.reduce((previousValue, currentValue, index) => { + if (/[?#]/.test(currentValue)) { + postPath = true; + } + const value = params[index]; + let encoded = (postPath ? encodeURIComponent : pathEncoder)('' + value); + if (index !== params.length && + (value == null || + (typeof value === 'object' && + // handle values from other realms + value.toString === + Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY) ?? EMPTY) + ?.toString))) { + encoded = value + ''; + invalidSegments.push({ + start: previousValue.length + currentValue.length, + length: encoded.length, + error: `Value of type ${Object.prototype.toString + .call(value) + .slice(8, -1)} is not a valid path parameter`, + }); + } + return previousValue + currentValue + (index === params.length ? '' : encoded); + }, ''); + const pathOnly = path.split(/[?#]/, 1)[0]; + const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; + let match; + // Find all invalid segments + while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) { + invalidSegments.push({ + start: match.index, + length: match[0].length, + error: `Value "${match[0]}" can\'t be safely passed as a path parameter`, + }); + } + invalidSegments.sort((a, b) => a.start - b.start); + if (invalidSegments.length > 0) { + let lastEnd = 0; + const underline = invalidSegments.reduce((acc, segment) => { + const spaces = ' '.repeat(segment.start - lastEnd); + const arrows = '^'.repeat(segment.length); + lastEnd = segment.start + segment.length; + return acc + spaces + arrows; + }, ''); + throw new AnthropicError(`Path parameters result in path with invalid segments:\n${invalidSegments + .map((e) => e.error) + .join('\n')}\n${path}\n${underline}`); + } + return path; +}; +/** + * URI-encodes path params and ensures no unsafe /./ or /../ path segments are introduced. + */ +export const path = /* @__PURE__ */ createPathTagFunction(encodeURIPath); +//# sourceMappingURL=path.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/utils/values.mjs b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/utils/values.mjs new file mode 100644 index 00000000..40388cf3 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/utils/values.mjs @@ -0,0 +1,94 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { AnthropicError } from "../../core/error.mjs"; +// https://url.spec.whatwg.org/#url-scheme-string +const startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i; +export const isAbsoluteURL = (url) => { + return startsWithSchemeRegexp.test(url); +}; +export let isArray = (val) => ((isArray = Array.isArray), isArray(val)); +export let isReadonlyArray = isArray; +/** Returns an object if the given value isn't an object, otherwise returns as-is */ +export function maybeObj(x) { + if (typeof x !== 'object') { + return {}; + } + return x ?? {}; +} +// https://stackoverflow.com/a/34491287 +export function isEmptyObj(obj) { + if (!obj) + return true; + for (const _k in obj) + return false; + return true; +} +// https://eslint.org/docs/latest/rules/no-prototype-builtins +export function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} +export function isObj(obj) { + return obj != null && typeof obj === 'object' && !Array.isArray(obj); +} +export const ensurePresent = (value) => { + if (value == null) { + throw new AnthropicError(`Expected a value to be given but received ${value} instead.`); + } + return value; +}; +export const validatePositiveInteger = (name, n) => { + if (typeof n !== 'number' || !Number.isInteger(n)) { + throw new AnthropicError(`${name} must be an integer`); + } + if (n < 0) { + throw new AnthropicError(`${name} must be a positive integer`); + } + return n; +}; +export const coerceInteger = (value) => { + if (typeof value === 'number') + return Math.round(value); + if (typeof value === 'string') + return parseInt(value, 10); + throw new AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`); +}; +export const coerceFloat = (value) => { + if (typeof value === 'number') + return value; + if (typeof value === 'string') + return parseFloat(value); + throw new AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`); +}; +export const coerceBoolean = (value) => { + if (typeof value === 'boolean') + return value; + if (typeof value === 'string') + return value === 'true'; + return Boolean(value); +}; +export const maybeCoerceInteger = (value) => { + if (value == null) { + return undefined; + } + return coerceInteger(value); +}; +export const maybeCoerceFloat = (value) => { + if (value == null) { + return undefined; + } + return coerceFloat(value); +}; +export const maybeCoerceBoolean = (value) => { + if (value == null) { + return undefined; + } + return coerceBoolean(value); +}; +export const safeJSON = (text) => { + try { + return JSON.parse(text); + } + catch (err) { + return undefined; + } +}; +//# sourceMappingURL=values.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/client.mjs b/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/client.mjs new file mode 100644 index 00000000..70476b52 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/client.mjs @@ -0,0 +1,98 @@ +import { buildHeaders } from "./internal/headers.mjs"; +import * as Errors from "./core/error.mjs"; +import { readEnv } from "./internal/utils.mjs"; +import { Anthropic } from '@anthropic-ai/sdk/client'; +export { BaseAnthropic } from '@anthropic-ai/sdk/client'; +import * as Resources from '@anthropic-ai/sdk/resources/index'; +/** API Client for interfacing with the Anthropic Foundry API. */ +export class AnthropicFoundry extends Anthropic { + /** + * API Client for interfacing with the Anthropic Foundry API. + * + * @param {string | undefined} [opts.resource=process.env['ANTHROPIC_FOUNDRY_RESOURCE'] ?? undefined] - Your Foundry resource name + * @param {string | undefined} [opts.apiKey=process.env['ANTHROPIC_FOUNDRY_API_KEY'] ?? undefined] + * @param {string | null | undefined} [opts.organization=process.env['ANTHROPIC_ORG_ID'] ?? null] + * @param {string} [opts.baseURL=process.env['ANTHROPIC_FOUNDRY_BASE_URL']] - Sets the base URL for the API, e.g. `https://example-resource.azure.anthropic.com/anthropic/`. + * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections. + * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {Headers} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API. + * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. + */ + constructor({ baseURL = readEnv('ANTHROPIC_FOUNDRY_BASE_URL'), apiKey = readEnv('ANTHROPIC_FOUNDRY_API_KEY'), resource = readEnv('ANTHROPIC_FOUNDRY_RESOURCE'), azureADTokenProvider, dangerouslyAllowBrowser, ...opts } = {}) { + if (typeof azureADTokenProvider === 'function') { + dangerouslyAllowBrowser = true; + } + if (!azureADTokenProvider && !apiKey) { + throw new Errors.AnthropicError('Missing credentials. Please pass one of `apiKey` and `azureTokenProvider`, or set the `ANTHROPIC_FOUNDRY_API_KEY` environment variable.'); + } + if (azureADTokenProvider && apiKey) { + throw new Errors.AnthropicError('The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.'); + } + if (!baseURL) { + if (!resource) { + throw new Errors.AnthropicError('Must provide one of the `baseURL` or `resource` arguments, or the `ANTHROPIC_FOUNDRY_RESOURCE` environment variable'); + } + baseURL = `https://${resource}.services.ai.azure.com/anthropic/`; + } + else { + if (resource) { + throw new Errors.AnthropicError('baseURL and resource are mutually exclusive'); + } + } + super({ + apiKey: azureADTokenProvider ?? apiKey, + baseURL, + ...opts, + ...(dangerouslyAllowBrowser !== undefined ? { dangerouslyAllowBrowser } : {}), + }); + this.resource = null; + // @ts-expect-error are using a different Messages type that omits batches + this.messages = makeMessagesResource(this); + // @ts-expect-error are using a different Beta type that omits batches + this.beta = makeBetaResource(this); + // @ts-expect-error Anthropic Foundry does not support models endpoint + this.models = undefined; + } + async authHeaders() { + if (typeof this._options.apiKey === 'function') { + let token; + try { + token = await this._options.apiKey(); + } + catch (err) { + if (err instanceof Errors.AnthropicError) + throw err; + throw new Errors.AnthropicError(`Failed to get token from azureADTokenProvider: ${err.message}`, + // @ts-ignore + { cause: err }); + } + if (typeof token !== 'string' || !token) { + throw new Errors.AnthropicError(`Expected azureADTokenProvider function argument to return a string but it returned ${token}`); + } + return buildHeaders([{ Authorization: `Bearer ${token}` }]); + } + if (typeof this._options.apiKey === 'string') { + return buildHeaders([{ 'x-api-key': this.apiKey }]); + } + return undefined; + } + validateHeaders() { + return; + } +} +function makeMessagesResource(client) { + const resource = new Resources.Messages(client); + // @ts-expect-error we're deleting non-optional properties + delete resource.batches; + return resource; +} +function makeBetaResource(client) { + const resource = new Resources.Beta(client); + // @ts-expect-error we're deleting non-optional properties + delete resource.messages.batches; + return resource; +} +//# sourceMappingURL=client.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/core/error.mjs b/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/core/error.mjs new file mode 100644 index 00000000..ea9269e5 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/core/error.mjs @@ -0,0 +1,2 @@ +export * from '@anthropic-ai/sdk/core/error'; +//# sourceMappingURL=error.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/index.mjs b/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/index.mjs new file mode 100644 index 00000000..6b20cb90 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/index.mjs @@ -0,0 +1,3 @@ +export * from "./client.mjs"; +export { AnthropicFoundry as default } from "./client.mjs"; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/headers.mjs b/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/headers.mjs new file mode 100644 index 00000000..94b059b4 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/headers.mjs @@ -0,0 +1,74 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { isReadonlyArray } from "./utils/values.mjs"; +const brand_privateNullableHeaders = Symbol.for('brand.privateNullableHeaders'); +function* iterateHeaders(headers) { + if (!headers) + return; + if (brand_privateNullableHeaders in headers) { + const { values, nulls } = headers; + yield* values.entries(); + for (const name of nulls) { + yield [name, null]; + } + return; + } + let shouldClear = false; + let iter; + if (headers instanceof Headers) { + iter = headers.entries(); + } + else if (isReadonlyArray(headers)) { + iter = headers; + } + else { + shouldClear = true; + iter = Object.entries(headers ?? {}); + } + for (let row of iter) { + const name = row[0]; + if (typeof name !== 'string') + throw new TypeError('expected header name to be a string'); + const values = isReadonlyArray(row[1]) ? row[1] : [row[1]]; + let didClear = false; + for (const value of values) { + if (value === undefined) + continue; + // Objects keys always overwrite older headers, they never append. + // Yield a null to clear the header before adding the new values. + if (shouldClear && !didClear) { + didClear = true; + yield [name, null]; + } + yield [name, value]; + } + } +} +export const buildHeaders = (newHeaders) => { + const targetHeaders = new Headers(); + const nullHeaders = new Set(); + for (const headers of newHeaders) { + const seenHeaders = new Set(); + for (const [name, value] of iterateHeaders(headers)) { + const lowerName = name.toLowerCase(); + if (!seenHeaders.has(lowerName)) { + targetHeaders.delete(name); + seenHeaders.add(lowerName); + } + if (value === null) { + targetHeaders.delete(name); + nullHeaders.add(lowerName); + } + else { + targetHeaders.append(name, value); + nullHeaders.delete(lowerName); + } + } + } + return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders }; +}; +export const isEmptyHeaders = (headers) => { + for (const _ of iterateHeaders(headers)) + return false; + return true; +}; +//# sourceMappingURL=headers.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils.mjs b/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils.mjs new file mode 100644 index 00000000..01563e2e --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils.mjs @@ -0,0 +1,8 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +export * from "./utils/values.mjs"; +export * from "./utils/base64.mjs"; +export * from "./utils/env.mjs"; +export * from "./utils/log.mjs"; +export * from "./utils/uuid.mjs"; +export * from "./utils/sleep.mjs"; +//# sourceMappingURL=utils.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/base64.mjs b/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/base64.mjs new file mode 100644 index 00000000..7e1a83df --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/base64.mjs @@ -0,0 +1,33 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { AnthropicError } from "../../core/error.mjs"; +import { encodeUTF8 } from "./bytes.mjs"; +export const toBase64 = (data) => { + if (!data) + return ''; + if (typeof globalThis.Buffer !== 'undefined') { + return globalThis.Buffer.from(data).toString('base64'); + } + if (typeof data === 'string') { + data = encodeUTF8(data); + } + if (typeof btoa !== 'undefined') { + return btoa(String.fromCharCode.apply(null, data)); + } + throw new AnthropicError('Cannot generate base64 string; Expected `Buffer` or `btoa` to be defined'); +}; +export const fromBase64 = (str) => { + if (typeof globalThis.Buffer !== 'undefined') { + const buf = globalThis.Buffer.from(str, 'base64'); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + } + if (typeof atob !== 'undefined') { + const bstr = atob(str); + const buf = new Uint8Array(bstr.length); + for (let i = 0; i < bstr.length; i++) { + buf[i] = bstr.charCodeAt(i); + } + return buf; + } + throw new AnthropicError('Cannot decode base64 string; Expected `Buffer` or `atob` to be defined'); +}; +//# sourceMappingURL=base64.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/env.mjs b/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/env.mjs new file mode 100644 index 00000000..58ddfda1 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/env.mjs @@ -0,0 +1,18 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +/** + * Read an environment variable. + * + * Trims beginning and trailing whitespace. + * + * Will return undefined if the environment variable doesn't exist or cannot be accessed. + */ +export const readEnv = (env) => { + if (typeof globalThis.process !== 'undefined') { + return globalThis.process.env?.[env]?.trim() ?? undefined; + } + if (typeof globalThis.Deno !== 'undefined') { + return globalThis.Deno.env?.get?.(env)?.trim(); + } + return undefined; +}; +//# sourceMappingURL=env.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/log.mjs b/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/log.mjs new file mode 100644 index 00000000..95cdd225 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/log.mjs @@ -0,0 +1,80 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { hasOwn } from "./values.mjs"; +const levelNumbers = { + off: 0, + error: 200, + warn: 300, + info: 400, + debug: 500, +}; +export const parseLogLevel = (maybeLevel, sourceName, client) => { + if (!maybeLevel) { + return undefined; + } + if (hasOwn(levelNumbers, maybeLevel)) { + return maybeLevel; + } + loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`); + return undefined; +}; +function noop() { } +function makeLogFn(fnLevel, logger, logLevel) { + if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) { + return noop; + } + else { + // Don't wrap logger functions, we want the stacktrace intact! + return logger[fnLevel].bind(logger); + } +} +const noopLogger = { + error: noop, + warn: noop, + info: noop, + debug: noop, +}; +let cachedLoggers = /* @__PURE__ */ new WeakMap(); +export function loggerFor(client) { + const logger = client.logger; + const logLevel = client.logLevel ?? 'off'; + if (!logger) { + return noopLogger; + } + const cachedLogger = cachedLoggers.get(logger); + if (cachedLogger && cachedLogger[0] === logLevel) { + return cachedLogger[1]; + } + const levelLogger = { + error: makeLogFn('error', logger, logLevel), + warn: makeLogFn('warn', logger, logLevel), + info: makeLogFn('info', logger, logLevel), + debug: makeLogFn('debug', logger, logLevel), + }; + cachedLoggers.set(logger, [logLevel, levelLogger]); + return levelLogger; +} +export const formatRequestDetails = (details) => { + if (details.options) { + details.options = { ...details.options }; + delete details.options['headers']; // redundant + leaks internals + } + if (details.headers) { + details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ + name, + (name.toLowerCase() === 'x-api-key' || + name.toLowerCase() === 'authorization' || + name.toLowerCase() === 'cookie' || + name.toLowerCase() === 'set-cookie') ? + '***' + : value, + ])); + } + if ('retryOfRequestLogID' in details) { + if (details.retryOfRequestLogID) { + details.retryOf = details.retryOfRequestLogID; + } + delete details.retryOfRequestLogID; + } + return details; +}; +//# sourceMappingURL=log.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/sleep.mjs b/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/sleep.mjs new file mode 100644 index 00000000..9d192686 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/sleep.mjs @@ -0,0 +1 @@ +export function sleep(ms) { return new Promise(r => setTimeout(r, ms)) } diff --git a/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/uuid.mjs b/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/uuid.mjs new file mode 100644 index 00000000..bfb66d9d --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/uuid.mjs @@ -0,0 +1,2 @@ +import { randomUUID } from 'crypto' +export function generateUUID() { return randomUUID() } diff --git a/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/values.mjs b/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/values.mjs new file mode 100644 index 00000000..7b9bf757 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/values.mjs @@ -0,0 +1,100 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { AnthropicError } from "../../core/error.mjs"; +// https://url.spec.whatwg.org/#url-scheme-string +const startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i; +export const isAbsoluteURL = (url) => { + return startsWithSchemeRegexp.test(url); +}; +export let isArray = (val) => ((isArray = Array.isArray), isArray(val)); +export let isReadonlyArray = isArray; +/** Returns an object if the given value isn't an object, otherwise returns as-is */ +export function maybeObj(x) { + if (typeof x !== 'object') { + return {}; + } + return x ?? {}; +} +// https://stackoverflow.com/a/34491287 +export function isEmptyObj(obj) { + if (!obj) + return true; + for (const _k in obj) + return false; + return true; +} +// https://eslint.org/docs/latest/rules/no-prototype-builtins +export function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} +export function isObj(obj) { + return obj != null && typeof obj === 'object' && !Array.isArray(obj); +} +export const ensurePresent = (value) => { + if (value == null) { + throw new AnthropicError(`Expected a value to be given but received ${value} instead.`); + } + return value; +}; +export const validatePositiveInteger = (name, n) => { + if (typeof n !== 'number' || !Number.isInteger(n)) { + throw new AnthropicError(`${name} must be an integer`); + } + if (n < 0) { + throw new AnthropicError(`${name} must be a positive integer`); + } + return n; +}; +export const coerceInteger = (value) => { + if (typeof value === 'number') + return Math.round(value); + if (typeof value === 'string') + return parseInt(value, 10); + throw new AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`); +}; +export const coerceFloat = (value) => { + if (typeof value === 'number') + return value; + if (typeof value === 'string') + return parseFloat(value); + throw new AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`); +}; +export const coerceBoolean = (value) => { + if (typeof value === 'boolean') + return value; + if (typeof value === 'string') + return value === 'true'; + return Boolean(value); +}; +export const maybeCoerceInteger = (value) => { + if (value == null) { + return undefined; + } + return coerceInteger(value); +}; +export const maybeCoerceFloat = (value) => { + if (value == null) { + return undefined; + } + return coerceFloat(value); +}; +export const maybeCoerceBoolean = (value) => { + if (value == null) { + return undefined; + } + return coerceBoolean(value); +}; +export const safeJSON = (text) => { + try { + return JSON.parse(text); + } + catch (err) { + return undefined; + } +}; +// Gets a value from an object, deletes the key, and returns the value (or undefined if not found) +export const pop = (obj, key) => { + const value = obj[key]; + delete obj[key]; + return value; +}; +//# sourceMappingURL=values.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/mcpb/dist/cli/init.js b/claude-code-source/node_modules/@anthropic-ai/mcpb/dist/cli/init.js new file mode 100644 index 00000000..33367b7b --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/mcpb/dist/cli/init.js @@ -0,0 +1,705 @@ +import { confirm, input, select } from "@inquirer/prompts"; +import { existsSync, readFileSync, writeFileSync } from "fs"; +import { basename, join, resolve } from "path"; +import { CURRENT_MANIFEST_VERSION } from "../schemas.js"; +export function readPackageJson(dirPath) { + const packageJsonPath = join(dirPath, "package.json"); + if (existsSync(packageJsonPath)) { + try { + return JSON.parse(readFileSync(packageJsonPath, "utf-8")); + } + catch (e) { + // Ignore package.json parsing errors + } + } + return {}; +} +export function getDefaultAuthorName(packageData) { + if (typeof packageData.author === "string") { + return packageData.author; + } + return packageData.author?.name || ""; +} +export function getDefaultAuthorEmail(packageData) { + if (typeof packageData.author === "object") { + return packageData.author?.email || ""; + } + return ""; +} +export function getDefaultAuthorUrl(packageData) { + if (typeof packageData.author === "object") { + return packageData.author?.url || ""; + } + return ""; +} +export function getDefaultRepositoryUrl(packageData) { + if (typeof packageData.repository === "string") { + return packageData.repository; + } + return packageData.repository?.url || ""; +} +export function getDefaultBasicInfo(packageData, resolvedPath) { + const name = packageData.name || basename(resolvedPath); + const authorName = getDefaultAuthorName(packageData) || "Unknown Author"; + const displayName = name; + const version = packageData.version || "1.0.0"; + const description = packageData.description || "A MCPB bundle"; + return { name, authorName, displayName, version, description }; +} +export function getDefaultAuthorInfo(packageData) { + return { + authorEmail: getDefaultAuthorEmail(packageData), + authorUrl: getDefaultAuthorUrl(packageData), + }; +} +export function getDefaultServerConfig(packageData) { + const serverType = "node"; + const entryPoint = getDefaultEntryPoint(serverType, packageData); + const mcp_config = createMcpConfig(serverType, entryPoint); + return { serverType, entryPoint, mcp_config }; +} +export function getDefaultOptionalFields(packageData) { + return { + keywords: "", + license: packageData.license || "MIT", + repository: undefined, + }; +} +export function createMcpConfig(serverType, entryPoint) { + switch (serverType) { + case "node": + return { + command: "node", + args: ["${__dirname}/" + entryPoint], + env: {}, + }; + case "python": + return { + command: "python", + args: ["${__dirname}/" + entryPoint], + env: { + PYTHONPATH: "${__dirname}/server/lib", + }, + }; + case "binary": + return { + command: "${__dirname}/" + entryPoint, + args: [], + env: {}, + }; + } +} +export function getDefaultEntryPoint(serverType, packageData) { + switch (serverType) { + case "node": + return packageData?.main || "server/index.js"; + case "python": + return "server/main.py"; + case "binary": + return "server/my-server"; + } +} +export async function promptBasicInfo(packageData, resolvedPath) { + const defaultName = packageData.name || basename(resolvedPath); + const name = await input({ + message: "Extension name:", + default: defaultName, + validate: (value) => value.trim().length > 0 || "Name is required", + }); + const authorName = await input({ + message: "Author name:", + default: getDefaultAuthorName(packageData), + validate: (value) => value.trim().length > 0 || "Author name is required", + }); + const displayName = await input({ + message: "Display name (optional):", + default: name, + }); + const version = await input({ + message: "Version:", + default: packageData.version || "1.0.0", + validate: (value) => { + if (!value.trim()) + return "Version is required"; + if (!/^\d+\.\d+\.\d+/.test(value)) { + return "Version must follow semantic versioning (e.g., 1.0.0)"; + } + return true; + }, + }); + const description = await input({ + message: "Description:", + default: packageData.description || "", + validate: (value) => value.trim().length > 0 || "Description is required", + }); + return { name, authorName, displayName, version, description }; +} +export async function promptAuthorInfo(packageData) { + const authorEmail = await input({ + message: "Author email (optional):", + default: getDefaultAuthorEmail(packageData), + }); + const authorUrl = await input({ + message: "Author URL (optional):", + default: getDefaultAuthorUrl(packageData), + }); + return { authorEmail, authorUrl }; +} +export async function promptServerConfig(packageData) { + const serverType = (await select({ + message: "Server type:", + choices: [ + { name: "Node.js", value: "node" }, + { name: "Python", value: "python" }, + { name: "Binary", value: "binary" }, + ], + default: "node", + })); + const entryPoint = await input({ + message: "Entry point:", + default: getDefaultEntryPoint(serverType, packageData), + }); + const mcp_config = createMcpConfig(serverType, entryPoint); + return { serverType, entryPoint, mcp_config }; +} +export async function promptTools() { + const addTools = await confirm({ + message: "Does your MCP Server provide tools you want to advertise (optional)?", + default: true, + }); + const tools = []; + let toolsGenerated = false; + if (addTools) { + let addMore = true; + while (addMore) { + const toolName = await input({ + message: "Tool name:", + validate: (value) => value.trim().length > 0 || "Tool name is required", + }); + const toolDescription = await input({ + message: "Tool description (optional):", + }); + tools.push({ + name: toolName, + ...(toolDescription ? { description: toolDescription } : {}), + }); + addMore = await confirm({ + message: "Add another tool?", + default: false, + }); + } + // Ask about generated tools + toolsGenerated = await confirm({ + message: "Does your server generate additional tools at runtime?", + default: false, + }); + } + return { tools, toolsGenerated }; +} +export async function promptPrompts() { + const addPrompts = await confirm({ + message: "Does your MCP Server provide prompts you want to advertise (optional)?", + default: false, + }); + const prompts = []; + let promptsGenerated = false; + if (addPrompts) { + let addMore = true; + while (addMore) { + const promptName = await input({ + message: "Prompt name:", + validate: (value) => value.trim().length > 0 || "Prompt name is required", + }); + const promptDescription = await input({ + message: "Prompt description (optional):", + }); + // Ask about arguments + const hasArguments = await confirm({ + message: "Does this prompt have arguments?", + default: false, + }); + const argumentNames = []; + if (hasArguments) { + let addMoreArgs = true; + while (addMoreArgs) { + const argName = await input({ + message: "Argument name:", + validate: (value) => { + if (!value.trim()) + return "Argument name is required"; + if (argumentNames.includes(value)) { + return "Argument names must be unique"; + } + return true; + }, + }); + argumentNames.push(argName); + addMoreArgs = await confirm({ + message: "Add another argument?", + default: false, + }); + } + } + // Prompt for the text template + const promptText = await input({ + message: hasArguments + ? `Prompt text (use \${arguments.name} for arguments: ${argumentNames.join(", ")}):` + : "Prompt text:", + validate: (value) => value.trim().length > 0 || "Prompt text is required", + }); + prompts.push({ + name: promptName, + ...(promptDescription ? { description: promptDescription } : {}), + ...(argumentNames.length > 0 ? { arguments: argumentNames } : {}), + text: promptText, + }); + addMore = await confirm({ + message: "Add another prompt?", + default: false, + }); + } + // Ask about generated prompts + promptsGenerated = await confirm({ + message: "Does your server generate additional prompts at runtime?", + default: false, + }); + } + return { prompts, promptsGenerated }; +} +export async function promptOptionalFields(packageData) { + const keywords = await input({ + message: "Keywords (comma-separated, optional):", + default: "", + }); + const license = await input({ + message: "License:", + default: packageData.license || "MIT", + }); + const addRepository = await confirm({ + message: "Add repository information?", + default: !!packageData.repository, + }); + let repository; + if (addRepository) { + const repoUrl = await input({ + message: "Repository URL:", + default: getDefaultRepositoryUrl(packageData), + }); + if (repoUrl) { + repository = { + type: "git", + url: repoUrl, + }; + } + } + return { keywords, license, repository }; +} +export async function promptLongDescription(description) { + const hasLongDescription = await confirm({ + message: "Add a detailed long description?", + default: false, + }); + if (hasLongDescription) { + const longDescription = await input({ + message: "Long description (supports basic markdown):", + default: description, + }); + return longDescription; + } + return undefined; +} +export async function promptUrls() { + const homepage = await input({ + message: "Homepage URL (optional):", + validate: (value) => { + if (!value.trim()) + return true; + try { + new URL(value); + return true; + } + catch { + return "Must be a valid URL (e.g., https://example.com)"; + } + }, + }); + const documentation = await input({ + message: "Documentation URL (optional):", + validate: (value) => { + if (!value.trim()) + return true; + try { + new URL(value); + return true; + } + catch { + return "Must be a valid URL"; + } + }, + }); + const support = await input({ + message: "Support URL (optional):", + validate: (value) => { + if (!value.trim()) + return true; + try { + new URL(value); + return true; + } + catch { + return "Must be a valid URL"; + } + }, + }); + return { homepage, documentation, support }; +} +export async function promptVisualAssets() { + const icon = await input({ + message: "Icon file path (optional, relative to manifest):", + validate: (value) => { + if (!value.trim()) + return true; + if (value.includes("..")) + return "Relative paths cannot include '..'"; + return true; + }, + }); + const addScreenshots = await confirm({ + message: "Add screenshots?", + default: false, + }); + const screenshots = []; + if (addScreenshots) { + let addMore = true; + while (addMore) { + const screenshot = await input({ + message: "Screenshot file path (relative to manifest):", + validate: (value) => { + if (!value.trim()) + return "Screenshot path is required"; + if (value.includes("..")) + return "Relative paths cannot include '..'"; + return true; + }, + }); + screenshots.push(screenshot); + addMore = await confirm({ + message: "Add another screenshot?", + default: false, + }); + } + } + return { icon, screenshots }; +} +export async function promptCompatibility(serverType) { + const addCompatibility = await confirm({ + message: "Add compatibility constraints?", + default: false, + }); + if (!addCompatibility) { + return undefined; + } + const addPlatforms = await confirm({ + message: "Specify supported platforms?", + default: false, + }); + let platforms; + if (addPlatforms) { + const selectedPlatforms = []; + const supportsDarwin = await confirm({ + message: "Support macOS (darwin)?", + default: true, + }); + if (supportsDarwin) + selectedPlatforms.push("darwin"); + const supportsWin32 = await confirm({ + message: "Support Windows (win32)?", + default: true, + }); + if (supportsWin32) + selectedPlatforms.push("win32"); + const supportsLinux = await confirm({ + message: "Support Linux?", + default: true, + }); + if (supportsLinux) + selectedPlatforms.push("linux"); + platforms = selectedPlatforms.length > 0 ? selectedPlatforms : undefined; + } + let runtimes; + if (serverType !== "binary") { + const addRuntimes = await confirm({ + message: "Specify runtime version constraints?", + default: false, + }); + if (addRuntimes) { + if (serverType === "python") { + const pythonVersion = await input({ + message: "Python version constraint (e.g., >=3.8,<4.0):", + validate: (value) => value.trim().length > 0 || "Python version constraint is required", + }); + runtimes = { python: pythonVersion }; + } + else if (serverType === "node") { + const nodeVersion = await input({ + message: "Node.js version constraint (e.g., >=16.0.0):", + validate: (value) => value.trim().length > 0 || "Node.js version constraint is required", + }); + runtimes = { node: nodeVersion }; + } + } + } + return { + ...(platforms ? { platforms } : {}), + ...(runtimes ? { runtimes } : {}), + }; +} +export async function promptUserConfig() { + const addUserConfig = await confirm({ + message: "Add user-configurable options?", + default: false, + }); + if (!addUserConfig) { + return {}; + } + const userConfig = {}; + let addMore = true; + while (addMore) { + const optionKey = await input({ + message: "Configuration option key (unique identifier):", + validate: (value) => { + if (!value.trim()) + return "Key is required"; + if (userConfig[value]) + return "Key must be unique"; + return true; + }, + }); + const optionType = (await select({ + message: "Option type:", + choices: [ + { name: "String", value: "string" }, + { name: "Number", value: "number" }, + { name: "Boolean", value: "boolean" }, + { name: "Directory", value: "directory" }, + { name: "File", value: "file" }, + ], + })); + const optionTitle = await input({ + message: "Option title (human-readable name):", + validate: (value) => value.trim().length > 0 || "Title is required", + }); + const optionDescription = await input({ + message: "Option description:", + validate: (value) => value.trim().length > 0 || "Description is required", + }); + const optionRequired = await confirm({ + message: "Is this option required?", + default: false, + }); + const optionSensitive = await confirm({ + message: "Is this option sensitive (like a password)?", + default: false, + }); + // Build the option object + const option = { + type: optionType, + title: optionTitle, + description: optionDescription, + required: optionRequired, + sensitive: optionSensitive, + }; + // Add default value if not required + if (!optionRequired) { + let defaultValue; + if (optionType === "boolean") { + defaultValue = await confirm({ + message: "Default value:", + default: false, + }); + } + else if (optionType === "number") { + const defaultStr = await input({ + message: "Default value (number):", + validate: (value) => { + if (!value.trim()) + return true; + return !isNaN(Number(value)) || "Must be a valid number"; + }, + }); + defaultValue = defaultStr ? Number(defaultStr) : undefined; + } + else { + defaultValue = await input({ + message: "Default value (optional):", + }); + } + if (defaultValue !== undefined && defaultValue !== "") { + option.default = defaultValue; + } + } + // Add constraints for number types + if (optionType === "number") { + const addConstraints = await confirm({ + message: "Add min/max constraints?", + default: false, + }); + if (addConstraints) { + const min = await input({ + message: "Minimum value (optional):", + validate: (value) => { + if (!value.trim()) + return true; + return !isNaN(Number(value)) || "Must be a valid number"; + }, + }); + const max = await input({ + message: "Maximum value (optional):", + validate: (value) => { + if (!value.trim()) + return true; + return !isNaN(Number(value)) || "Must be a valid number"; + }, + }); + if (min) + option.min = Number(min); + if (max) + option.max = Number(max); + } + } + userConfig[optionKey] = option; + addMore = await confirm({ + message: "Add another configuration option?", + default: false, + }); + } + return userConfig; +} +export function buildManifest(basicInfo, longDescription, authorInfo, urls, visualAssets, serverConfig, tools, toolsGenerated, prompts, promptsGenerated, compatibility, userConfig, optionalFields) { + const { name, displayName, version, description, authorName } = basicInfo; + const { authorEmail, authorUrl } = authorInfo; + const { serverType, entryPoint, mcp_config } = serverConfig; + const { keywords, license, repository } = optionalFields; + return { + manifest_version: CURRENT_MANIFEST_VERSION, + name, + ...(displayName && displayName !== name + ? { display_name: displayName } + : {}), + version, + description, + ...(longDescription ? { long_description: longDescription } : {}), + author: { + name: authorName, + ...(authorEmail ? { email: authorEmail } : {}), + ...(authorUrl ? { url: authorUrl } : {}), + }, + ...(urls.homepage ? { homepage: urls.homepage } : {}), + ...(urls.documentation ? { documentation: urls.documentation } : {}), + ...(urls.support ? { support: urls.support } : {}), + ...(visualAssets.icon ? { icon: visualAssets.icon } : {}), + ...(visualAssets.screenshots.length > 0 + ? { screenshots: visualAssets.screenshots } + : {}), + server: { + type: serverType, + entry_point: entryPoint, + mcp_config, + }, + ...(tools.length > 0 ? { tools } : {}), + ...(toolsGenerated ? { tools_generated: true } : {}), + ...(prompts.length > 0 ? { prompts } : {}), + ...(promptsGenerated ? { prompts_generated: true } : {}), + ...(compatibility ? { compatibility } : {}), + ...(Object.keys(userConfig).length > 0 ? { user_config: userConfig } : {}), + ...(keywords + ? { + keywords: keywords + .split(",") + .map((k) => k.trim()) + .filter((k) => k), + } + : {}), + ...(license ? { license } : {}), + ...(repository ? { repository } : {}), + }; +} +export function printNextSteps() { + console.log("\nNext steps:"); + console.log(`1. Ensure all your production dependencies are in this directory`); + console.log(`2. Run 'mcpb pack' to create your .mcpb file`); +} +export async function initExtension(targetPath = process.cwd(), nonInteractive = false) { + const resolvedPath = resolve(targetPath); + const manifestPath = join(resolvedPath, "manifest.json"); + if (existsSync(manifestPath)) { + if (nonInteractive) { + console.log("manifest.json already exists. Use --force to overwrite in non-interactive mode."); + return false; + } + const overwrite = await confirm({ + message: "manifest.json already exists. Overwrite?", + default: false, + }); + if (!overwrite) { + console.log("Cancelled"); + return false; + } + } + if (!nonInteractive) { + console.log("This utility will help you create a manifest.json file for your MCPB bundle."); + console.log("Press ^C at any time to quit.\n"); + } + else { + console.log("Creating manifest.json with default values..."); + } + try { + const packageData = readPackageJson(resolvedPath); + // Prompt for all information or use defaults + const basicInfo = nonInteractive + ? getDefaultBasicInfo(packageData, resolvedPath) + : await promptBasicInfo(packageData, resolvedPath); + const longDescription = nonInteractive + ? undefined + : await promptLongDescription(basicInfo.description); + const authorInfo = nonInteractive + ? getDefaultAuthorInfo(packageData) + : await promptAuthorInfo(packageData); + const urls = nonInteractive + ? { homepage: "", documentation: "", support: "" } + : await promptUrls(); + const visualAssets = nonInteractive + ? { icon: "", screenshots: [] } + : await promptVisualAssets(); + const serverConfig = nonInteractive + ? getDefaultServerConfig(packageData) + : await promptServerConfig(packageData); + const toolsData = nonInteractive + ? { tools: [], toolsGenerated: false } + : await promptTools(); + const promptsData = nonInteractive + ? { prompts: [], promptsGenerated: false } + : await promptPrompts(); + const compatibility = nonInteractive + ? undefined + : await promptCompatibility(serverConfig.serverType); + const userConfig = nonInteractive ? {} : await promptUserConfig(); + const optionalFields = nonInteractive + ? getDefaultOptionalFields(packageData) + : await promptOptionalFields(packageData); + // Build manifest + const manifest = buildManifest(basicInfo, longDescription, authorInfo, urls, visualAssets, serverConfig, toolsData.tools, toolsData.toolsGenerated, promptsData.prompts, promptsData.promptsGenerated, compatibility, userConfig, optionalFields); + // Write manifest + writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + "\n"); + console.log(`\nCreated manifest.json at ${manifestPath}`); + printNextSteps(); + return true; + } + catch (error) { + if (error instanceof Error && error.message.includes("User force closed")) { + console.log("\nCancelled"); + return false; + } + throw error; + } +} diff --git a/claude-code-source/node_modules/@anthropic-ai/mcpb/dist/cli/pack.js b/claude-code-source/node_modules/@anthropic-ai/mcpb/dist/cli/pack.js new file mode 100644 index 00000000..433de659 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/mcpb/dist/cli/pack.js @@ -0,0 +1,200 @@ +import { confirm } from "@inquirer/prompts"; +import { createHash } from "crypto"; +import { zipSync } from "fflate"; +import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync, } from "fs"; +import { basename, join, relative, resolve, sep } from "path"; +import { getAllFilesWithCount, readMcpbIgnorePatterns } from "../node/files.js"; +import { validateManifest } from "../node/validate.js"; +import { CURRENT_MANIFEST_VERSION, McpbManifestSchema } from "../schemas.js"; +import { getLogger } from "../shared/log.js"; +import { initExtension } from "./init.js"; +function formatFileSize(bytes) { + if (bytes < 1024) { + return `${bytes}B`; + } + else if (bytes < 1024 * 1024) { + return `${(bytes / 1024).toFixed(1)}kB`; + } + else { + return `${(bytes / (1024 * 1024)).toFixed(1)}MB`; + } +} +function sanitizeNameForFilename(name) { + // Replace spaces with hyphens + // Remove or replace characters that are problematic in filenames + return name + .toLowerCase() + .replace(/\s+/g, "-") // Replace spaces with hyphens + .replace(/[^a-z0-9-_.]/g, "") // Keep only alphanumeric, hyphens, underscores, and dots + .replace(/-+/g, "-") // Replace multiple hyphens with single hyphen + .replace(/^-+|-+$/g, "") // Remove leading/trailing hyphens + .substring(0, 100); // Limit length to 100 characters +} +export async function packExtension({ extensionPath, outputPath, silent, }) { + const resolvedPath = resolve(extensionPath); + const logger = getLogger({ silent }); + // Check if directory exists + if (!existsSync(resolvedPath) || !statSync(resolvedPath).isDirectory()) { + logger.error(`ERROR: Directory not found: ${extensionPath}`); + return false; + } + // Check if manifest exists + const manifestPath = join(resolvedPath, "manifest.json"); + if (!existsSync(manifestPath)) { + logger.log(`No manifest.json found in ${extensionPath}`); + const shouldInit = await confirm({ + message: "Would you like to create a manifest.json file?", + default: true, + }); + if (shouldInit) { + const success = await initExtension(extensionPath); + if (!success) { + logger.error("ERROR: Failed to create manifest"); + return false; + } + } + else { + logger.error("ERROR: Cannot pack extension without manifest.json"); + return false; + } + } + // Validate manifest first + logger.log("Validating manifest..."); + if (!validateManifest(manifestPath)) { + logger.error("ERROR: Cannot pack extension with invalid manifest"); + return false; + } + // Read and parse manifest + let manifest; + try { + const manifestContent = readFileSync(manifestPath, "utf-8"); + const manifestData = JSON.parse(manifestContent); + manifest = McpbManifestSchema.parse(manifestData); + } + catch (error) { + logger.error("ERROR: Failed to parse manifest.json"); + if (error instanceof Error) { + logger.error(` ${error.message}`); + } + return false; + } + const manifestVersion = manifest.manifest_version || manifest.dxt_version; + if (manifestVersion !== CURRENT_MANIFEST_VERSION) { + logger.error(`ERROR: Manifest version mismatch. Expected "${CURRENT_MANIFEST_VERSION}", found "${manifestVersion}"`); + logger.error(` Please update the manifest_version in your manifest.json to "${CURRENT_MANIFEST_VERSION}"`); + return false; + } + // Determine output path + const extensionName = basename(resolvedPath); + const finalOutputPath = outputPath + ? resolve(outputPath) + : resolve(`${extensionName}.mcpb`); + // Ensure output directory exists + const outputDir = join(finalOutputPath, ".."); + mkdirSync(outputDir, { recursive: true }); + try { + // Read .mcpbignore patterns if present + const mcpbIgnorePatterns = readMcpbIgnorePatterns(resolvedPath); + // Get all files in the extension directory + const { files, ignoredCount } = getAllFilesWithCount(resolvedPath, resolvedPath, {}, mcpbIgnorePatterns); + // Print package header + logger.log(`\n📦 ${manifest.name}@${manifest.version}`); + // Print file list + logger.log("Archive Contents"); + const fileEntries = Object.entries(files); + let totalUnpackedSize = 0; + // Sort files for consistent output + fileEntries.sort(([a], [b]) => a.localeCompare(b)); + // Group files by directory for deep nesting + const directoryGroups = new Map(); + const shallowFiles = []; + for (const [filePath, fileData] of fileEntries) { + const relPath = relative(resolvedPath, filePath); + const content = fileData.data; + const size = typeof content === "string" + ? Buffer.byteLength(content, "utf8") + : content.length; + totalUnpackedSize += size; + // Check if file is deeply nested (3+ levels) + const parts = relPath.split(sep); + if (parts.length > 3) { + // Group by the first 3 directory levels + const groupKey = parts.slice(0, 3).join("/"); + if (!directoryGroups.has(groupKey)) { + directoryGroups.set(groupKey, { files: [], totalSize: 0 }); + } + const group = directoryGroups.get(groupKey); + group.files.push(relPath); + group.totalSize += size; + } + else { + shallowFiles.push({ path: relPath, size }); + } + } + // Print shallow files first + for (const { path, size } of shallowFiles) { + logger.log(`${formatFileSize(size).padStart(8)} ${path}`); + } + // Print grouped directories + for (const [dir, { files, totalSize }] of directoryGroups) { + if (files.length === 1) { + // If only one file in the group, print it normally + const filePath = files[0]; + const fileSize = totalSize; + logger.log(`${formatFileSize(fileSize).padStart(8)} ${filePath}`); + } + else { + // Print directory summary + logger.log(`${formatFileSize(totalSize).padStart(8)} ${dir}/ [and ${files.length} more files]`); + } + } + // Create zip with preserved file permissions + const zipFiles = {}; + const isUnix = process.platform !== "win32"; + for (const [filePath, fileData] of Object.entries(files)) { + if (isUnix) { + // Set external file attributes to preserve Unix permissions + // The mode needs to be shifted to the upper 16 bits for ZIP format + zipFiles[filePath] = [ + fileData.data, + { os: 3, attrs: (fileData.mode & 0o777) << 16 }, + ]; + } + else { + // On Windows, use default ZIP attributes (no Unix permissions) + zipFiles[filePath] = fileData.data; + } + } + const zipData = zipSync(zipFiles, { + level: 9, // Maximum compression + mtime: new Date(), + }); + // Write zip file + writeFileSync(finalOutputPath, zipData); + // Calculate SHA sum + const shasum = createHash("sha1").update(zipData).digest("hex"); + // Print archive details + const sanitizedName = sanitizeNameForFilename(manifest.name); + const archiveName = `${sanitizedName}-${manifest.version}.mcpb`; + logger.log("\nArchive Details"); + logger.log(`name: ${manifest.name}`); + logger.log(`version: ${manifest.version}`); + logger.log(`filename: ${archiveName}`); + logger.log(`package size: ${formatFileSize(zipData.length)}`); + logger.log(`unpacked size: ${formatFileSize(totalUnpackedSize)}`); + logger.log(`shasum: ${shasum}`); + logger.log(`total files: ${fileEntries.length}`); + logger.log(`ignored (.mcpbignore) files: ${ignoredCount}`); + logger.log(`\nOutput: ${finalOutputPath}`); + return true; + } + catch (error) { + if (error instanceof Error) { + logger.error(`ERROR: Archive error: ${error.message}`); + } + else { + logger.error("ERROR: Unknown archive error occurred"); + } + return false; + } +} diff --git a/claude-code-source/node_modules/@anthropic-ai/mcpb/dist/cli/unpack.js b/claude-code-source/node_modules/@anthropic-ai/mcpb/dist/cli/unpack.js new file mode 100644 index 00000000..a2801bff --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/mcpb/dist/cli/unpack.js @@ -0,0 +1,101 @@ +import { unzipSync } from "fflate"; +import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync, } from "fs"; +import { join, resolve, sep } from "path"; +import { extractSignatureBlock } from "../node/sign.js"; +import { getLogger } from "../shared/log.js"; +export async function unpackExtension({ mcpbPath, outputDir, silent, }) { + const logger = getLogger({ silent }); + const resolvedMcpbPath = resolve(mcpbPath); + if (!existsSync(resolvedMcpbPath)) { + logger.error(`ERROR: MCPB file not found: ${mcpbPath}`); + return false; + } + const finalOutputDir = outputDir ? resolve(outputDir) : process.cwd(); + if (!existsSync(finalOutputDir)) { + mkdirSync(finalOutputDir, { recursive: true }); + } + try { + const fileContent = readFileSync(resolvedMcpbPath); + const { originalContent } = extractSignatureBlock(fileContent); + // Parse file attributes from ZIP central directory + const fileAttributes = new Map(); + const isUnix = process.platform !== "win32"; + if (isUnix) { + // Parse ZIP central directory to extract file attributes + const zipBuffer = originalContent; + // Find end of central directory record + let eocdOffset = -1; + for (let i = zipBuffer.length - 22; i >= 0; i--) { + if (zipBuffer.readUInt32LE(i) === 0x06054b50) { + eocdOffset = i; + break; + } + } + if (eocdOffset !== -1) { + const centralDirOffset = zipBuffer.readUInt32LE(eocdOffset + 16); + const centralDirEntries = zipBuffer.readUInt16LE(eocdOffset + 8); + let offset = centralDirOffset; + for (let i = 0; i < centralDirEntries; i++) { + if (zipBuffer.readUInt32LE(offset) === 0x02014b50) { + const externalAttrs = zipBuffer.readUInt32LE(offset + 38); + const filenameLength = zipBuffer.readUInt16LE(offset + 28); + const filename = zipBuffer.toString("utf8", offset + 46, offset + 46 + filenameLength); + // Extract Unix permissions from external attributes (upper 16 bits) + const mode = (externalAttrs >> 16) & 0o777; + if (mode > 0) { + fileAttributes.set(filename, mode); + } + const extraFieldLength = zipBuffer.readUInt16LE(offset + 30); + const commentLength = zipBuffer.readUInt16LE(offset + 32); + offset += 46 + filenameLength + extraFieldLength + commentLength; + } + else { + break; + } + } + } + } + const decompressed = unzipSync(originalContent); + for (const relativePath in decompressed) { + if (Object.prototype.hasOwnProperty.call(decompressed, relativePath)) { + const data = decompressed[relativePath]; + const fullPath = join(finalOutputDir, relativePath); + // Prevent zip slip attacks by validating the resolved path + const normalizedPath = resolve(fullPath); + const normalizedOutputDir = resolve(finalOutputDir); + if (!normalizedPath.startsWith(normalizedOutputDir + sep) && + normalizedPath !== normalizedOutputDir) { + throw new Error(`Path traversal attempt detected: ${relativePath}`); + } + const dir = join(fullPath, ".."); + if (!existsSync(dir)) { + mkdirSync(dir, { recursive: true }); + } + writeFileSync(fullPath, data); + // Restore Unix file permissions if available + if (isUnix && fileAttributes.has(relativePath)) { + try { + const mode = fileAttributes.get(relativePath); + if (mode !== undefined) { + chmodSync(fullPath, mode); + } + } + catch (error) { + // Silently ignore permission errors + } + } + } + } + logger.log(`Extension unpacked successfully to ${finalOutputDir}`); + return true; + } + catch (error) { + if (error instanceof Error) { + logger.error(`ERROR: Failed to unpack extension: ${error.message}`); + } + else { + logger.error("ERROR: An unknown error occurred during unpacking."); + } + return false; + } +} diff --git a/claude-code-source/node_modules/@anthropic-ai/mcpb/dist/index.js b/claude-code-source/node_modules/@anthropic-ai/mcpb/dist/index.js new file mode 100644 index 00000000..eea22d75 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/mcpb/dist/index.js @@ -0,0 +1,10 @@ +// Default export includes everything (backward compatibility) +export * from "./cli/init.js"; +export * from "./cli/pack.js"; +export * from "./cli/unpack.js"; +export * from "./node/files.js"; +export * from "./node/sign.js"; +export * from "./node/validate.js"; +export * from "./schemas.js"; +export * from "./shared/config.js"; +export * from "./types.js"; diff --git a/claude-code-source/node_modules/@anthropic-ai/mcpb/dist/node/files.js b/claude-code-source/node_modules/@anthropic-ai/mcpb/dist/node/files.js new file mode 100644 index 00000000..4b735efd --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/mcpb/dist/node/files.js @@ -0,0 +1,115 @@ +import { existsSync, readdirSync, readFileSync, statSync } from "fs"; +import ignore from "ignore"; +import { join, relative, sep } from "path"; +// Files/patterns to exclude from the package +export const EXCLUDE_PATTERNS = [ + ".DS_Store", + "Thumbs.db", + ".gitignore", + ".git", + ".mcpbignore", + "*.log", + ".env*", + ".npm", + ".npmrc", + ".yarnrc", + ".yarn", + ".eslintrc", + ".editorconfig", + ".prettierrc", + ".prettierignore", + ".eslintignore", + ".nycrc", + ".babelrc", + ".pnp.*", + "node_modules/.cache", + "node_modules/.bin", + "*.map", + ".env.local", + ".env.*.local", + "npm-debug.log*", + "yarn-debug.log*", + "yarn-error.log*", + "package-lock.json", + "yarn.lock", + "*.mcpb", + "*.d.ts", + "*.tsbuildinfo", + "tsconfig.json", +]; +/** + * Read and parse .mcpbignore file patterns + */ +export function readMcpbIgnorePatterns(baseDir) { + const mcpbIgnorePath = join(baseDir, ".mcpbignore"); + if (!existsSync(mcpbIgnorePath)) { + return []; + } + try { + const content = readFileSync(mcpbIgnorePath, "utf-8"); + return content + .split(/\r?\n/) + .map((line) => line.trim()) + .filter((line) => line.length > 0 && !line.startsWith("#")); + } + catch (error) { + console.warn(`Warning: Could not read .mcpbignore file: ${error instanceof Error ? error.message : "Unknown error"}`); + return []; + } +} +function buildIgnoreChecker(additionalPatterns) { + return ignore().add(EXCLUDE_PATTERNS).add(additionalPatterns); +} +/** + * Used for testing, calls the same methods as the other ignore checks + */ +export function shouldExclude(filePath, additionalPatterns = []) { + return buildIgnoreChecker(additionalPatterns).ignores(filePath); +} +export function getAllFiles(dirPath, baseDir = dirPath, fileList = {}, additionalPatterns = []) { + const files = readdirSync(dirPath); + const ignoreChecker = buildIgnoreChecker(additionalPatterns); + for (const file of files) { + const filePath = join(dirPath, file); + const relativePath = relative(baseDir, filePath); + if (ignoreChecker.ignores(relativePath)) { + continue; + } + const stat = statSync(filePath); + if (stat.isDirectory()) { + getAllFiles(filePath, baseDir, fileList, additionalPatterns); + } + else { + // Use forward slashes in zip file paths + const zipPath = relativePath.split(sep).join("/"); + fileList[zipPath] = readFileSync(filePath); + } + } + return fileList; +} +export function getAllFilesWithCount(dirPath, baseDir = dirPath, fileList = {}, additionalPatterns = [], ignoredCount = 0) { + const files = readdirSync(dirPath); + const ignoreChecker = buildIgnoreChecker(additionalPatterns); + for (const file of files) { + const filePath = join(dirPath, file); + const relativePath = relative(baseDir, filePath); + if (ignoreChecker.ignores(relativePath)) { + ignoredCount++; + continue; + } + const stat = statSync(filePath); + if (stat.isDirectory()) { + const result = getAllFilesWithCount(filePath, baseDir, fileList, additionalPatterns, ignoredCount); + ignoredCount = result.ignoredCount; + } + else { + // Use forward slashes in zip file paths + const zipPath = relativePath.split(sep).join("/"); + fileList[zipPath] = { + data: readFileSync(filePath), + mode: stat.mode, + }; + } + } + return { files: fileList, ignoredCount }; +} diff --git a/claude-code-source/node_modules/@anthropic-ai/mcpb/dist/node/sign.js b/claude-code-source/node_modules/@anthropic-ai/mcpb/dist/node/sign.js new file mode 100644 index 00000000..4774a67d --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/mcpb/dist/node/sign.js @@ -0,0 +1,333 @@ +import { execFile } from "child_process"; +import { readFileSync, writeFileSync } from "fs"; +import { mkdtemp, rm, writeFile } from "fs/promises"; +import forge from "node-forge"; +import { tmpdir } from "os"; +import { join } from "path"; +import { promisify } from "util"; +// Signature block markers +const SIGNATURE_HEADER = "MCPB_SIG_V1"; +const SIGNATURE_FOOTER = "MCPB_SIG_END"; +const execFileAsync = promisify(execFile); +/** + * Signs a MCPB file with the given certificate and private key using PKCS#7 + * + * @param mcpbPath Path to the MCPB file to sign + * @param certPath Path to the certificate file (PEM format) + * @param keyPath Path to the private key file (PEM format) + * @param intermediates Optional array of intermediate certificate paths + */ +export function signMcpbFile(mcpbPath, certPath, keyPath, intermediates) { + // Read the original MCPB file + const mcpbContent = readFileSync(mcpbPath); + // Read certificate and key + const certificatePem = readFileSync(certPath, "utf-8"); + const privateKeyPem = readFileSync(keyPath, "utf-8"); + // Read intermediate certificates if provided + const intermediatePems = intermediates?.map((path) => readFileSync(path, "utf-8")); + // Create PKCS#7 signed data + const p7 = forge.pkcs7.createSignedData(); + p7.content = forge.util.createBuffer(mcpbContent); + // Parse and add certificates + const signingCert = forge.pki.certificateFromPem(certificatePem); + const privateKey = forge.pki.privateKeyFromPem(privateKeyPem); + p7.addCertificate(signingCert); + // Add intermediate certificates + if (intermediatePems) { + for (const pem of intermediatePems) { + p7.addCertificate(forge.pki.certificateFromPem(pem)); + } + } + // Add signer + p7.addSigner({ + key: privateKey, + certificate: signingCert, + digestAlgorithm: forge.pki.oids.sha256, + authenticatedAttributes: [ + { + type: forge.pki.oids.contentType, + value: forge.pki.oids.data, + }, + { + type: forge.pki.oids.messageDigest, + // Value will be auto-populated + }, + { + type: forge.pki.oids.signingTime, + // Value will be auto-populated with current time + }, + ], + }); + // Sign with detached signature + p7.sign({ detached: true }); + // Convert to DER format + const asn1 = forge.asn1.toDer(p7.toAsn1()); + const pkcs7Signature = Buffer.from(asn1.getBytes(), "binary"); + // Create signature block with PKCS#7 data + const signatureBlock = createSignatureBlock(pkcs7Signature); + // Append signature block to MCPB file + const signedContent = Buffer.concat([mcpbContent, signatureBlock]); + writeFileSync(mcpbPath, signedContent); +} +/** + * Verifies a signed MCPB file using OS certificate store + * + * @param mcpbPath Path to the signed MCPB file + * @returns Signature information including verification status + */ +export async function verifyMcpbFile(mcpbPath) { + try { + const fileContent = readFileSync(mcpbPath); + // Find and extract signature block + const { originalContent, pkcs7Signature } = extractSignatureBlock(fileContent); + if (!pkcs7Signature) { + return { status: "unsigned" }; + } + // Parse PKCS#7 signature + const asn1 = forge.asn1.fromDer(pkcs7Signature.toString("binary")); + const p7Message = forge.pkcs7.messageFromAsn1(asn1); + // Verify it's signed data and cast to correct type + if (!("type" in p7Message) || + p7Message.type !== forge.pki.oids.signedData) { + return { status: "unsigned" }; + } + // Now we know it's PkcsSignedData. The types are incorrect, so we'll + // fix them there + const p7 = p7Message; + // Extract certificates from PKCS#7 + const certificates = p7.certificates || []; + if (certificates.length === 0) { + return { status: "unsigned" }; + } + // Get the signing certificate (first one) + const signingCert = certificates[0]; + // Verify PKCS#7 signature + const contentBuf = forge.util.createBuffer(originalContent); + try { + p7.verify({ authenticatedAttributes: true }); + // Also verify the content matches + const signerInfos = p7.signerInfos; + const signerInfo = signerInfos?.[0]; + if (signerInfo) { + const md = forge.md.sha256.create(); + md.update(contentBuf.getBytes()); + const digest = md.digest().getBytes(); + // Find the message digest attribute + let messageDigest = null; + for (const attr of signerInfo.authenticatedAttributes) { + if (attr.type === forge.pki.oids.messageDigest) { + messageDigest = attr.value; + break; + } + } + if (!messageDigest || messageDigest !== digest) { + return { status: "unsigned" }; + } + } + } + catch (error) { + return { status: "unsigned" }; + } + // Convert forge certificate to PEM for OS verification + const certPem = forge.pki.certificateToPem(signingCert); + const intermediatePems = certificates + .slice(1) + .map((cert) => Buffer.from(forge.pki.certificateToPem(cert))); + // Verify certificate chain against OS trust store + const chainValid = await verifyCertificateChain(Buffer.from(certPem), intermediatePems); + if (!chainValid) { + // Signature is valid but certificate is not trusted + return { status: "unsigned" }; + } + // Extract certificate info + const isSelfSigned = signingCert.issuer.getField("CN")?.value === + signingCert.subject.getField("CN")?.value; + return { + status: isSelfSigned ? "self-signed" : "signed", + publisher: signingCert.subject.getField("CN")?.value || "Unknown", + issuer: signingCert.issuer.getField("CN")?.value || "Unknown", + valid_from: signingCert.validity.notBefore.toISOString(), + valid_to: signingCert.validity.notAfter.toISOString(), + fingerprint: forge.md.sha256 + .create() + .update(forge.asn1.toDer(forge.pki.certificateToAsn1(signingCert)).getBytes()) + .digest() + .toHex(), + }; + } + catch (error) { + throw new Error(`Failed to verify MCPB file: ${error}`); + } +} +/** + * Creates a signature block buffer with PKCS#7 signature + */ +function createSignatureBlock(pkcs7Signature) { + const parts = []; + // Header + parts.push(Buffer.from(SIGNATURE_HEADER, "utf-8")); + // PKCS#7 signature length and data + const sigLengthBuffer = Buffer.alloc(4); + sigLengthBuffer.writeUInt32LE(pkcs7Signature.length, 0); + parts.push(sigLengthBuffer); + parts.push(pkcs7Signature); + // Footer + parts.push(Buffer.from(SIGNATURE_FOOTER, "utf-8")); + return Buffer.concat(parts); +} +/** + * Extracts the signature block from a signed MCPB file + */ +export function extractSignatureBlock(fileContent) { + // Look for signature footer at the end + const footerBytes = Buffer.from(SIGNATURE_FOOTER, "utf-8"); + const footerIndex = fileContent.lastIndexOf(footerBytes); + if (footerIndex === -1) { + return { originalContent: fileContent }; + } + // Look for signature header before footer + const headerBytes = Buffer.from(SIGNATURE_HEADER, "utf-8"); + let headerIndex = -1; + // Search backwards from footer + for (let i = footerIndex - 1; i >= 0; i--) { + if (fileContent.slice(i, i + headerBytes.length).equals(headerBytes)) { + headerIndex = i; + break; + } + } + if (headerIndex === -1) { + return { originalContent: fileContent }; + } + // Extract original content (everything before signature block) + const originalContent = fileContent.slice(0, headerIndex); + // Parse signature block + let offset = headerIndex + headerBytes.length; + try { + // Read PKCS#7 signature length + const sigLength = fileContent.readUInt32LE(offset); + offset += 4; + // Read PKCS#7 signature + const pkcs7Signature = fileContent.slice(offset, offset + sigLength); + return { + originalContent, + pkcs7Signature, + }; + } + catch { + return { originalContent: fileContent }; + } +} +/** + * Verifies certificate chain against OS trust store + */ +export async function verifyCertificateChain(certificate, intermediates) { + let tempDir = null; + try { + tempDir = await mkdtemp(join(tmpdir(), "mcpb-verify-")); + const certChainPath = join(tempDir, "chain.pem"); + const certChain = [certificate, ...(intermediates || [])].join("\n"); + await writeFile(certChainPath, certChain); + // Platform-specific verification + if (process.platform === "darwin") { + try { + await execFileAsync("security", [ + "verify-cert", + "-c", + certChainPath, + "-p", + "codeSign", + ]); + return true; + } + catch (error) { + return false; + } + } + else if (process.platform === "win32") { + const psCommand = ` + $ErrorActionPreference = 'Stop' + $certCollection = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection + $certCollection.Import('${certChainPath}') + + if ($certCollection.Count -eq 0) { + Write-Error 'No certificates found' + exit 1 + } + + $leafCert = $certCollection[0] + $chain = New-Object System.Security.Cryptography.X509Certificates.X509Chain + + # Enable revocation checking + $chain.ChainPolicy.RevocationMode = 'Online' + $chain.ChainPolicy.RevocationFlag = 'EntireChain' + $chain.ChainPolicy.UrlRetrievalTimeout = New-TimeSpan -Seconds 30 + + # Add code signing application policy + $codeSignOid = New-Object System.Security.Cryptography.Oid '1.3.6.1.5.5.7.3.3' + $chain.ChainPolicy.ApplicationPolicy.Add($codeSignOid) + + # Add intermediate certificates to extra store + for ($i = 1; $i -lt $certCollection.Count; $i++) { + [void]$chain.ChainPolicy.ExtraStore.Add($certCollection[$i]) + } + + # Build and validate chain + $result = $chain.Build($leafCert) + + if ($result) { + 'Valid' + } else { + $chain.ChainStatus | ForEach-Object { + Write-Error "$($_.Status): $($_.StatusInformation)" + } + exit 1 + } + `.trim(); + const { stdout } = await execFileAsync("powershell.exe", [ + "-NoProfile", + "-NonInteractive", + "-Command", + psCommand, + ]); + return stdout.includes("Valid"); + } + else { + // Linux: Use openssl + try { + await execFileAsync("openssl", [ + "verify", + "-purpose", + "codesigning", + "-CApath", + "/etc/ssl/certs", + certChainPath, + ]); + return true; + } + catch (error) { + return false; + } + } + } + catch (error) { + return false; + } + finally { + if (tempDir) { + try { + await rm(tempDir, { recursive: true, force: true }); + } + catch { + // Ignore cleanup errors + } + } + } +} +/** + * Removes signature from a MCPB file + */ +export function unsignMcpbFile(mcpbPath) { + const fileContent = readFileSync(mcpbPath); + const { originalContent } = extractSignatureBlock(fileContent); + writeFileSync(mcpbPath, originalContent); +} diff --git a/claude-code-source/node_modules/@anthropic-ai/mcpb/dist/node/validate.js b/claude-code-source/node_modules/@anthropic-ai/mcpb/dist/node/validate.js new file mode 100644 index 00000000..06c6bad3 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/mcpb/dist/node/validate.js @@ -0,0 +1,124 @@ +import { existsSync, readFileSync, statSync } from "fs"; +import * as fs from "fs/promises"; +import { DestroyerOfModules } from "galactus"; +import * as os from "os"; +import { join, resolve } from "path"; +import prettyBytes from "pretty-bytes"; +import { unpackExtension } from "../cli/unpack.js"; +import { McpbManifestSchema } from "../schemas.js"; +import { McpbManifestSchema as LooseMcpbManifestSchema } from "../schemas-loose.js"; +export function validateManifest(inputPath) { + try { + const resolvedPath = resolve(inputPath); + let manifestPath = resolvedPath; + // If input is a directory, look for manifest.json inside it + if (existsSync(resolvedPath) && statSync(resolvedPath).isDirectory()) { + manifestPath = join(resolvedPath, "manifest.json"); + } + const manifestContent = readFileSync(manifestPath, "utf-8"); + const manifestData = JSON.parse(manifestContent); + const result = McpbManifestSchema.safeParse(manifestData); + if (result.success) { + console.log("Manifest schema validation passes!"); + return true; + } + else { + console.log("ERROR: Manifest validation failed:\n"); + result.error.issues.forEach((issue) => { + const path = issue.path.join("."); + console.log(` - ${path ? `${path}: ` : ""}${issue.message}`); + }); + return false; + } + } + catch (error) { + if (error instanceof Error) { + if (error.message.includes("ENOENT")) { + console.error(`ERROR: File not found: ${inputPath}`); + if (existsSync(resolve(inputPath)) && + statSync(resolve(inputPath)).isDirectory()) { + console.error(` (No manifest.json found in directory)`); + } + } + else if (error.message.includes("JSON")) { + console.error(`ERROR: Invalid JSON in manifest file: ${error.message}`); + } + else { + console.error(`ERROR: Error reading manifest: ${error.message}`); + } + } + else { + console.error("ERROR: Unknown error occurred"); + } + return false; + } +} +export async function cleanMcpb(inputPath) { + const tmpDir = await fs.mkdtemp(resolve(os.tmpdir(), "mcpb-clean-")); + const mcpbPath = resolve(tmpDir, "in.mcpb"); + const unpackPath = resolve(tmpDir, "out"); + console.log(" -- Cleaning MCPB..."); + try { + await fs.copyFile(inputPath, mcpbPath); + console.log(" -- Unpacking MCPB..."); + await unpackExtension({ mcpbPath, silent: true, outputDir: unpackPath }); + const manifestPath = resolve(unpackPath, "manifest.json"); + const originalManifest = await fs.readFile(manifestPath, "utf-8"); + const manifestData = JSON.parse(originalManifest); + const result = LooseMcpbManifestSchema.safeParse(manifestData); + if (!result.success) { + throw new Error(`Unrecoverable manifest issues, please run "mcpb validate"`); + } + await fs.writeFile(manifestPath, JSON.stringify(result.data, null, 2)); + if (originalManifest.trim() !== + (await fs.readFile(manifestPath, "utf8")).trim()) { + console.log(" -- Update manifest to be valid per MCPB schema"); + } + else { + console.log(" -- Manifest already valid per MCPB schema"); + } + const nodeModulesPath = resolve(unpackPath, "node_modules"); + if (existsSync(nodeModulesPath)) { + console.log(" -- node_modules found, deleting development dependencies"); + const destroyer = new DestroyerOfModules({ + rootDirectory: unpackPath, + }); + try { + await destroyer.destroy(); + } + catch (error) { + // If modules have already been deleted in a previous clean, the walker + // will fail when it can't find required dependencies. This is expected + // and safe to ignore. + if (error instanceof Error && + error.message.includes("Failed to locate module")) { + console.log(" -- Some modules already removed, skipping remaining cleanup"); + } + else { + throw error; + } + } + console.log(" -- Removed development dependencies from node_modules"); + } + else { + console.log(" -- No node_modules, not pruning"); + } + const before = await fs.stat(inputPath); + const { packExtension } = await import("../cli/pack.js"); + await packExtension({ + extensionPath: unpackPath, + outputPath: inputPath, + silent: true, + }); + const after = await fs.stat(inputPath); + console.log("\nClean Complete:"); + console.log("Before:", prettyBytes(before.size)); + console.log("After:", prettyBytes(after.size)); + } + finally { + await fs.rm(tmpDir, { + recursive: true, + force: true, + }); + } +} diff --git a/claude-code-source/node_modules/@anthropic-ai/mcpb/dist/schemas-loose.js b/claude-code-source/node_modules/@anthropic-ai/mcpb/dist/schemas-loose.js new file mode 100644 index 00000000..0df79844 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/mcpb/dist/schemas-loose.js @@ -0,0 +1,105 @@ +import * as z from "zod"; +export const McpServerConfigSchema = z.object({ + command: z.string(), + args: z.array(z.string()).optional(), + env: z.record(z.string(), z.string()).optional(), +}); +export const McpbManifestAuthorSchema = z.object({ + name: z.string(), + email: z.string().email().optional(), + url: z.string().url().optional(), +}); +export const McpbManifestRepositorySchema = z.object({ + type: z.string(), + url: z.string().url(), +}); +export const McpbManifestPlatformOverrideSchema = McpServerConfigSchema.partial(); +export const McpbManifestMcpConfigSchema = McpServerConfigSchema.extend({ + platform_overrides: z + .record(z.string(), McpbManifestPlatformOverrideSchema) + .optional(), +}); +export const McpbManifestServerSchema = z.object({ + type: z.enum(["python", "node", "binary"]), + entry_point: z.string(), + mcp_config: McpbManifestMcpConfigSchema, +}); +export const McpbManifestCompatibilitySchema = z + .object({ + claude_desktop: z.string().optional(), + platforms: z.array(z.enum(["darwin", "win32", "linux"])).optional(), + runtimes: z + .object({ + python: z.string().optional(), + node: z.string().optional(), + }) + .optional(), +}) + .passthrough(); +export const McpbManifestToolSchema = z.object({ + name: z.string(), + description: z.string().optional(), +}); +export const McpbManifestPromptSchema = z.object({ + name: z.string(), + description: z.string().optional(), + arguments: z.array(z.string()).optional(), + text: z.string(), +}); +export const McpbUserConfigurationOptionSchema = z.object({ + type: z.enum(["string", "number", "boolean", "directory", "file"]), + title: z.string(), + description: z.string(), + required: z.boolean().optional(), + default: z + .union([z.string(), z.number(), z.boolean(), z.array(z.string())]) + .optional(), + multiple: z.boolean().optional(), + sensitive: z.boolean().optional(), + min: z.number().optional(), + max: z.number().optional(), +}); +export const McpbUserConfigValuesSchema = z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])); +export const McpbManifestSchema = z + .object({ + $schema: z.string().optional(), + dxt_version: z + .string() + .optional() + .describe("@deprecated Use manifest_version instead"), + manifest_version: z.string().optional(), + name: z.string(), + display_name: z.string().optional(), + version: z.string(), + description: z.string(), + long_description: z.string().optional(), + author: McpbManifestAuthorSchema, + repository: McpbManifestRepositorySchema.optional(), + homepage: z.string().url().optional(), + documentation: z.string().url().optional(), + support: z.string().url().optional(), + icon: z.string().optional(), + screenshots: z.array(z.string()).optional(), + server: McpbManifestServerSchema, + tools: z.array(McpbManifestToolSchema).optional(), + tools_generated: z.boolean().optional(), + prompts: z.array(McpbManifestPromptSchema).optional(), + prompts_generated: z.boolean().optional(), + keywords: z.array(z.string()).optional(), + license: z.string().optional(), + compatibility: McpbManifestCompatibilitySchema.optional(), + user_config: z + .record(z.string(), McpbUserConfigurationOptionSchema) + .optional(), +}) + .refine((data) => !!(data.dxt_version || data.manifest_version), { + message: "Either 'dxt_version' (deprecated) or 'manifest_version' must be provided", +}); +export const McpbSignatureInfoSchema = z.object({ + status: z.enum(["signed", "unsigned", "self-signed"]), + publisher: z.string().optional(), + issuer: z.string().optional(), + valid_from: z.string().optional(), + valid_to: z.string().optional(), + fingerprint: z.string().optional(), +}); diff --git a/claude-code-source/node_modules/@anthropic-ai/mcpb/dist/schemas.js b/claude-code-source/node_modules/@anthropic-ai/mcpb/dist/schemas.js new file mode 100644 index 00000000..f4a3020a --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/mcpb/dist/schemas.js @@ -0,0 +1,107 @@ +import * as z from "zod"; +export const CURRENT_MANIFEST_VERSION = "0.2"; +export const McpServerConfigSchema = z.strictObject({ + command: z.string(), + args: z.array(z.string()).optional(), + env: z.record(z.string(), z.string()).optional(), +}); +export const McpbManifestAuthorSchema = z.strictObject({ + name: z.string(), + email: z.string().email().optional(), + url: z.string().url().optional(), +}); +export const McpbManifestRepositorySchema = z.strictObject({ + type: z.string(), + url: z.string().url(), +}); +export const McpbManifestPlatformOverrideSchema = McpServerConfigSchema.partial(); +export const McpbManifestMcpConfigSchema = McpServerConfigSchema.extend({ + platform_overrides: z + .record(z.string(), McpbManifestPlatformOverrideSchema) + .optional(), +}); +export const McpbManifestServerSchema = z.strictObject({ + type: z.enum(["python", "node", "binary"]), + entry_point: z.string(), + mcp_config: McpbManifestMcpConfigSchema, +}); +export const McpbManifestCompatibilitySchema = z + .strictObject({ + claude_desktop: z.string().optional(), + platforms: z.array(z.enum(["darwin", "win32", "linux"])).optional(), + runtimes: z + .strictObject({ + python: z.string().optional(), + node: z.string().optional(), + }) + .optional(), +}) + .passthrough(); +export const McpbManifestToolSchema = z.strictObject({ + name: z.string(), + description: z.string().optional(), +}); +export const McpbManifestPromptSchema = z.strictObject({ + name: z.string(), + description: z.string().optional(), + arguments: z.array(z.string()).optional(), + text: z.string(), +}); +export const McpbUserConfigurationOptionSchema = z.strictObject({ + type: z.enum(["string", "number", "boolean", "directory", "file"]), + title: z.string(), + description: z.string(), + required: z.boolean().optional(), + default: z + .union([z.string(), z.number(), z.boolean(), z.array(z.string())]) + .optional(), + multiple: z.boolean().optional(), + sensitive: z.boolean().optional(), + min: z.number().optional(), + max: z.number().optional(), +}); +export const McpbUserConfigValuesSchema = z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])); +export const McpbManifestSchema = z + .strictObject({ + $schema: z.string().optional(), + dxt_version: z + .string() + .optional() + .describe("@deprecated Use manifest_version instead"), + manifest_version: z.string().optional(), + name: z.string(), + display_name: z.string().optional(), + version: z.string(), + description: z.string(), + long_description: z.string().optional(), + author: McpbManifestAuthorSchema, + repository: McpbManifestRepositorySchema.optional(), + homepage: z.string().url().optional(), + documentation: z.string().url().optional(), + support: z.string().url().optional(), + icon: z.string().optional(), + screenshots: z.array(z.string()).optional(), + server: McpbManifestServerSchema, + tools: z.array(McpbManifestToolSchema).optional(), + tools_generated: z.boolean().optional(), + prompts: z.array(McpbManifestPromptSchema).optional(), + prompts_generated: z.boolean().optional(), + keywords: z.array(z.string()).optional(), + license: z.string().optional(), + privacy_policies: z.array(z.string()).optional(), + compatibility: McpbManifestCompatibilitySchema.optional(), + user_config: z + .record(z.string(), McpbUserConfigurationOptionSchema) + .optional(), +}) + .refine((data) => !!(data.dxt_version || data.manifest_version), { + message: "Either 'dxt_version' (deprecated) or 'manifest_version' must be provided", +}); +export const McpbSignatureInfoSchema = z.strictObject({ + status: z.enum(["signed", "unsigned", "self-signed"]), + publisher: z.string().optional(), + issuer: z.string().optional(), + valid_from: z.string().optional(), + valid_to: z.string().optional(), + fingerprint: z.string().optional(), +}); diff --git a/claude-code-source/node_modules/@anthropic-ai/mcpb/dist/shared/config.js b/claude-code-source/node_modules/@anthropic-ai/mcpb/dist/shared/config.js new file mode 100644 index 00000000..7b4c4a48 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/mcpb/dist/shared/config.js @@ -0,0 +1,157 @@ +/** + * This file contains utility functions for handling MCPB configuration, + * including variable replacement and MCP server configuration generation. + */ +/** + * Recursively replaces variables in any value. Handles strings, arrays, and objects. + * + * @param value The value to process + * @param variables Object containing variable replacements + * @returns The processed value with all variables replaced + */ +export function replaceVariables(value, variables) { + if (typeof value === "string") { + let result = value; + // Replace all variables in the string + for (const [key, replacement] of Object.entries(variables)) { + const pattern = new RegExp(`\\$\\{${key}\\}`, "g"); + // Check if this pattern actually exists in the string + if (result.match(pattern)) { + if (Array.isArray(replacement)) { + console.warn(`Cannot replace ${key} with array value in string context: "${value}"`, { key, replacement }); + } + else { + result = result.replace(pattern, replacement); + } + } + } + return result; + } + else if (Array.isArray(value)) { + // For arrays, we need to handle special case of array expansion + const result = []; + for (const item of value) { + if (typeof item === "string" && + item.match(/^\$\{user_config\.[^}]+\}$/)) { + // This is a user config variable that might expand to multiple values + const varName = item.match(/^\$\{([^}]+)\}$/)?.[1]; + if (varName && variables[varName]) { + const replacement = variables[varName]; + if (Array.isArray(replacement)) { + // Expand array inline + result.push(...replacement); + } + else { + result.push(replacement); + } + } + else { + // Variable not found, keep original + result.push(item); + } + } + else { + // Recursively process non-variable items + result.push(replaceVariables(item, variables)); + } + } + return result; + } + else if (value && typeof value === "object") { + const result = {}; + for (const [key, val] of Object.entries(value)) { + result[key] = replaceVariables(val, variables); + } + return result; + } + return value; +} +export async function getMcpConfigForManifest(options) { + const { manifest, extensionPath, systemDirs, userConfig, pathSeparator, logger, } = options; + const baseConfig = manifest.server?.mcp_config; + if (!baseConfig) { + return undefined; + } + let result = { + ...baseConfig, + }; + if (baseConfig.platform_overrides) { + if (process.platform in baseConfig.platform_overrides) { + const platformConfig = baseConfig.platform_overrides[process.platform]; + result.command = platformConfig.command || result.command; + result.args = platformConfig.args || result.args; + result.env = platformConfig.env || result.env; + } + } + // Check if required configuration is missing + if (hasRequiredConfigMissing({ manifest, userConfig })) { + logger?.warn(`Extension ${manifest.name} has missing required configuration, skipping MCP config`); + return undefined; + } + const variables = { + __dirname: extensionPath, + pathSeparator, + "/": pathSeparator, + ...systemDirs, + }; + // Build merged configuration from defaults and user settings + const mergedConfig = {}; + // First, add defaults from manifest + if (manifest.user_config) { + for (const [key, configOption] of Object.entries(manifest.user_config)) { + if (configOption.default !== undefined) { + mergedConfig[key] = configOption.default; + } + } + } + // Then, override with user settings + if (userConfig) { + Object.assign(mergedConfig, userConfig); + } + // Add merged configuration variables for substitution + for (const [key, value] of Object.entries(mergedConfig)) { + // Convert user config to the format expected by variable substitution + const userConfigKey = `user_config.${key}`; + if (Array.isArray(value)) { + // Keep arrays as arrays for proper expansion + variables[userConfigKey] = value.map(String); + } + else if (typeof value === "boolean") { + // Convert booleans to "true"/"false" strings as per spec + variables[userConfigKey] = value ? "true" : "false"; + } + else { + // Convert other types to strings + variables[userConfigKey] = String(value); + } + } + // Replace all variables in the config + result = replaceVariables(result, variables); + return result; +} +function isInvalidSingleValue(value) { + return value === undefined || value === null || value === ""; +} +/** + * Check if an extension has missing required configuration + * @param manifest The extension manifest + * @param userConfig The user configuration + * @returns true if required configuration is missing + */ +export function hasRequiredConfigMissing({ manifest, userConfig, }) { + if (!manifest.user_config) { + return false; + } + const config = userConfig || {}; + for (const [key, configOption] of Object.entries(manifest.user_config)) { + if (configOption.required) { + const value = config[key]; + if (isInvalidSingleValue(value) || + (Array.isArray(value) && + (value.length === 0 || value.some(isInvalidSingleValue)))) { + return true; + } + } + } + return false; +} diff --git a/claude-code-source/node_modules/@anthropic-ai/mcpb/dist/shared/log.js b/claude-code-source/node_modules/@anthropic-ai/mcpb/dist/shared/log.js new file mode 100644 index 00000000..43d384a1 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/mcpb/dist/shared/log.js @@ -0,0 +1,29 @@ +export function getLogger({ silent = false } = {}) { + return { + log: (...args) => { + if (!silent) { + console.log(...args); + } + }, + error: (...args) => { + if (!silent) { + console.error(...args); + } + }, + warn: (...args) => { + if (!silent) { + console.warn(...args); + } + }, + info: (...args) => { + if (!silent) { + console.info(...args); + } + }, + debug: (...args) => { + if (!silent) { + console.debug(...args); + } + }, + }; +} diff --git a/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/index.js b/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/index.js new file mode 100644 index 00000000..893bcd5f --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/index.js @@ -0,0 +1,9 @@ +// Library exports +export { SandboxManager } from './sandbox/sandbox-manager.js'; +export { SandboxViolationStore } from './sandbox/sandbox-violation-store.js'; +export { SandboxRuntimeConfigSchema, NetworkConfigSchema, FilesystemConfigSchema, IgnoreViolationsConfigSchema, RipgrepConfigSchema, } from './sandbox/sandbox-config.js'; +// Utility functions +export { getDefaultWritePaths } from './sandbox/sandbox-utils.js'; +// Platform utilities +export { getWslVersion } from './utils/platform.js'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/generate-seccomp-filter.js b/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/generate-seccomp-filter.js new file mode 100644 index 00000000..f9defc3d --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/generate-seccomp-filter.js @@ -0,0 +1,263 @@ +import { join, dirname } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import * as fs from 'node:fs'; +import { execSync } from 'node:child_process'; +import { homedir } from 'node:os'; +import { logForDebugging } from '../utils/debug.js'; +// Cache for path lookups (key: explicit path or empty string, value: resolved path or null) +const bpfPathCache = new Map(); +const applySeccompPathCache = new Map(); +// Cache for global npm paths (computed once per process) +let cachedGlobalNpmPaths = null; +/** + * Get paths to check for globally installed @anthropic-ai/sandbox-runtime package. + * This is used as a fallback when the binaries aren't bundled (e.g., native builds). + */ +function getGlobalNpmPaths() { + if (cachedGlobalNpmPaths) + return cachedGlobalNpmPaths; + const paths = []; + // Try to get the actual global npm root + try { + const npmRoot = execSync('npm root -g', { + encoding: 'utf8', + timeout: 5000, + stdio: ['pipe', 'pipe', 'ignore'], + }).trim(); + if (npmRoot) { + paths.push(join(npmRoot, '@anthropic-ai', 'sandbox-runtime')); + } + } + catch { + // npm not available or failed + } + // Common global npm locations as fallbacks + const home = homedir(); + paths.push( + // npm global (Linux/macOS) + join('/usr', 'lib', 'node_modules', '@anthropic-ai', 'sandbox-runtime'), join('/usr', 'local', 'lib', 'node_modules', '@anthropic-ai', 'sandbox-runtime'), + // npm global with prefix (common on macOS with homebrew) + join('/opt', 'homebrew', 'lib', 'node_modules', '@anthropic-ai', 'sandbox-runtime'), + // User-local npm global + join(home, '.npm', 'lib', 'node_modules', '@anthropic-ai', 'sandbox-runtime'), join(home, '.npm-global', 'lib', 'node_modules', '@anthropic-ai', 'sandbox-runtime')); + cachedGlobalNpmPaths = paths; + return paths; +} +/** + * Map Node.js process.arch to our vendor directory architecture names + * Returns null for unsupported architectures + */ +function getVendorArchitecture() { + const arch = process.arch; + switch (arch) { + case 'x64': + case 'x86_64': + return 'x64'; + case 'arm64': + case 'aarch64': + return 'arm64'; + case 'ia32': + case 'x86': + // TODO: Add support for 32-bit x86 (ia32) + // Currently blocked because the seccomp filter does not block the socketcall() syscall, + // which is used on 32-bit x86 for all socket operations (socket, socketpair, bind, connect, etc.). + // On 32-bit x86, the direct socket() syscall doesn't exist - instead, all socket operations + // are multiplexed through socketcall(SYS_SOCKET, ...), socketcall(SYS_SOCKETPAIR, ...), etc. + // + // To properly support 32-bit x86, we need to: + // 1. Build a separate i386 BPF filter (BPF bytecode is architecture-specific) + // 2. Modify vendor/seccomp-src/seccomp-unix-block.c to conditionally add rules that block: + // - socketcall(SYS_SOCKET, [AF_UNIX, ...]) + // - socketcall(SYS_SOCKETPAIR, [AF_UNIX, ...]) + // 3. This requires complex BPF logic to inspect socketcall's sub-function argument + // + // Until then, 32-bit x86 is not supported to avoid a security bypass. + logForDebugging(`[SeccompFilter] 32-bit x86 (ia32) is not currently supported due to missing socketcall() syscall blocking. ` + + `The current seccomp filter only blocks socket(AF_UNIX, ...), but on 32-bit x86, socketcall() can be used to bypass this.`, { level: 'error' }); + return null; + default: + logForDebugging(`[SeccompFilter] Unsupported architecture: ${arch}. Only x64 and arm64 are supported.`); + return null; + } +} +/** + * Get local paths to check for seccomp files (bundled or package installs). + */ +function getLocalSeccompPaths(filename) { + const arch = getVendorArchitecture(); + if (!arch) + return []; + const baseDir = dirname(fileURLToPath(import.meta.url)); + const relativePath = join('vendor', 'seccomp', arch, filename); + return [ + join(baseDir, relativePath), // bundled: same directory as bundle (e.g., when bundled into claude-cli) + join(baseDir, '..', '..', relativePath), // package root: vendor/seccomp/... + join(baseDir, '..', relativePath), // dist: dist/vendor/seccomp/... + ]; +} +/** + * Get the path to a pre-generated BPF filter file from the vendor directory + * Returns the path if it exists, null otherwise + * + * Pre-generated BPF files are organized by architecture: + * - vendor/seccomp/{x64,arm64}/unix-block.bpf + * + * Tries multiple paths for resilience: + * 0. Explicit path provided via parameter (checked first if provided) + * 1. vendor/seccomp/{arch}/unix-block.bpf (bundled - when bundled into consuming packages) + * 2. ../../vendor/seccomp/{arch}/unix-block.bpf (package root - standard npm installs) + * 3. ../vendor/seccomp/{arch}/unix-block.bpf (dist/vendor - for bundlers) + * 4. Global npm install (if seccompBinaryPath not provided) - for native builds + * + * @param seccompBinaryPath - Optional explicit path to the BPF filter file. If provided and + * exists, it will be used. If not provided, falls back to searching local paths and then + * global npm install (for native builds where vendor directory isn't bundled). + */ +export function getPreGeneratedBpfPath(seccompBinaryPath) { + const cacheKey = seccompBinaryPath ?? ''; + if (bpfPathCache.has(cacheKey)) { + return bpfPathCache.get(cacheKey); + } + const result = findBpfPath(seccompBinaryPath); + bpfPathCache.set(cacheKey, result); + return result; +} +// NOTE: This is a slow operation (synchronous fs lookups + execSync). Ensure calls +// are memoized at the top level rather than invoked repeatedly. +function findBpfPath(seccompBinaryPath) { + // Check explicit path first (highest priority) + if (seccompBinaryPath) { + if (fs.existsSync(seccompBinaryPath)) { + logForDebugging(`[SeccompFilter] Using BPF filter from explicit path: ${seccompBinaryPath}`); + return seccompBinaryPath; + } + logForDebugging(`[SeccompFilter] Explicit path provided but file not found: ${seccompBinaryPath}`); + } + const arch = getVendorArchitecture(); + if (!arch) { + logForDebugging(`[SeccompFilter] Cannot find pre-generated BPF filter: unsupported architecture ${process.arch}`); + return null; + } + logForDebugging(`[SeccompFilter] Detected architecture: ${arch}`); + // Check local paths first (bundled or package install) + for (const bpfPath of getLocalSeccompPaths('unix-block.bpf')) { + if (fs.existsSync(bpfPath)) { + logForDebugging(`[SeccompFilter] Found pre-generated BPF filter: ${bpfPath} (${arch})`); + return bpfPath; + } + } + // Fallback: check global npm install (for native builds without bundled vendor) + for (const globalBase of getGlobalNpmPaths()) { + const bpfPath = join(globalBase, 'vendor', 'seccomp', arch, 'unix-block.bpf'); + if (fs.existsSync(bpfPath)) { + logForDebugging(`[SeccompFilter] Found pre-generated BPF filter in global install: ${bpfPath} (${arch})`); + return bpfPath; + } + } + logForDebugging(`[SeccompFilter] Pre-generated BPF filter not found in any expected location (${arch})`); + return null; +} +/** + * Get the path to the apply-seccomp binary from the vendor directory + * Returns the path if it exists, null otherwise + * + * Pre-built apply-seccomp binaries are organized by architecture: + * - vendor/seccomp/{x64,arm64}/apply-seccomp + * + * Tries multiple paths for resilience: + * 0. Explicit path provided via parameter (checked first if provided) + * 1. vendor/seccomp/{arch}/apply-seccomp (bundled - when bundled into consuming packages) + * 2. ../../vendor/seccomp/{arch}/apply-seccomp (package root - standard npm installs) + * 3. ../vendor/seccomp/{arch}/apply-seccomp (dist/vendor - for bundlers) + * 4. Global npm install (if seccompBinaryPath not provided) - for native builds + * + * @param seccompBinaryPath - Optional explicit path to the apply-seccomp binary. If provided + * and exists, it will be used. If not provided, falls back to searching local paths and + * then global npm install (for native builds where vendor directory isn't bundled). + */ +export function getApplySeccompBinaryPath(seccompBinaryPath) { + const cacheKey = seccompBinaryPath ?? ''; + if (applySeccompPathCache.has(cacheKey)) { + return applySeccompPathCache.get(cacheKey); + } + const result = findApplySeccompPath(seccompBinaryPath); + applySeccompPathCache.set(cacheKey, result); + return result; +} +function findApplySeccompPath(seccompBinaryPath) { + // Check explicit path first (highest priority) + if (seccompBinaryPath) { + if (fs.existsSync(seccompBinaryPath)) { + logForDebugging(`[SeccompFilter] Using apply-seccomp binary from explicit path: ${seccompBinaryPath}`); + return seccompBinaryPath; + } + logForDebugging(`[SeccompFilter] Explicit path provided but file not found: ${seccompBinaryPath}`); + } + const arch = getVendorArchitecture(); + if (!arch) { + logForDebugging(`[SeccompFilter] Cannot find apply-seccomp binary: unsupported architecture ${process.arch}`); + return null; + } + logForDebugging(`[SeccompFilter] Looking for apply-seccomp binary for architecture: ${arch}`); + // Check local paths first (bundled or package install) + for (const binaryPath of getLocalSeccompPaths('apply-seccomp')) { + if (fs.existsSync(binaryPath)) { + logForDebugging(`[SeccompFilter] Found apply-seccomp binary: ${binaryPath} (${arch})`); + return binaryPath; + } + } + // Fallback: check global npm install (for native builds without bundled vendor) + for (const globalBase of getGlobalNpmPaths()) { + const binaryPath = join(globalBase, 'vendor', 'seccomp', arch, 'apply-seccomp'); + if (fs.existsSync(binaryPath)) { + logForDebugging(`[SeccompFilter] Found apply-seccomp binary in global install: ${binaryPath} (${arch})`); + return binaryPath; + } + } + logForDebugging(`[SeccompFilter] apply-seccomp binary not found in any expected location (${arch})`); + return null; +} +/** + * Get the path to a pre-generated seccomp BPF filter that blocks Unix domain socket creation + * Returns the path to the BPF filter file, or null if not available + * + * The filter blocks socket(AF_UNIX, ...) syscalls while allowing all other syscalls. + * This prevents creation of new Unix domain socket file descriptors. + * + * Security scope: + * - Blocks: socket(AF_UNIX, ...) syscall (creating new Unix socket FDs) + * - Does NOT block: Operations on inherited Unix socket FDs (bind, connect, sendto, etc.) + * - Does NOT block: Unix socket FDs passed via SCM_RIGHTS + * - For most sandboxing scenarios, blocking socket creation is sufficient + * + * Note: This blocks ALL Unix socket creation, regardless of path. The allowUnixSockets + * configuration is not supported on Linux due to seccomp-bpf limitations (it cannot + * read user-space memory to inspect socket paths). + * + * Requirements: + * - Pre-generated BPF filters included for x64 and ARM64 only + * - Other architectures are not supported + * + * @param seccompBinaryPath - Optional explicit path to the BPF filter file + * @returns Path to the pre-generated BPF filter file, or null if not available + */ +export function generateSeccompFilter(seccompBinaryPath) { + const preGeneratedBpf = getPreGeneratedBpfPath(seccompBinaryPath); + if (preGeneratedBpf) { + logForDebugging('[SeccompFilter] Using pre-generated BPF filter'); + return preGeneratedBpf; + } + logForDebugging('[SeccompFilter] Pre-generated BPF filter not available for this architecture. ' + + 'Only x64 and arm64 are supported.', { level: 'error' }); + return null; +} +/** + * Clean up a seccomp filter file + * Since we only use pre-generated BPF files from vendor/, this is a no-op. + * Pre-generated files are never deleted. + * Kept for backward compatibility with existing code that calls it. + */ +export function cleanupSeccompFilter(_filterPath) { + // No-op: pre-generated BPF files are never cleaned up +} +//# sourceMappingURL=generate-seccomp-filter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/http-proxy.js b/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/http-proxy.js new file mode 100644 index 00000000..21ff4888 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/http-proxy.js @@ -0,0 +1,217 @@ +import { Agent, createServer } from 'node:http'; +import { request as httpRequest } from 'node:http'; +import { request as httpsRequest } from 'node:https'; +import { connect } from 'node:net'; +import { URL } from 'node:url'; +import { logForDebugging } from '../utils/debug.js'; +export function createHttpProxyServer(options) { + const server = createServer(); + // Handle CONNECT requests for HTTPS traffic + server.on('connect', async (req, socket) => { + // Attach error handler immediately to prevent unhandled errors + socket.on('error', err => { + logForDebugging(`Client socket error: ${err.message}`, { level: 'error' }); + }); + try { + const [hostname, portStr] = req.url.split(':'); + const port = portStr === undefined ? undefined : parseInt(portStr, 10); + if (!hostname || !port) { + logForDebugging(`Invalid CONNECT request: ${req.url}`, { + level: 'error', + }); + socket.end('HTTP/1.1 400 Bad Request\r\n\r\n'); + return; + } + const allowed = await options.filter(port, hostname, socket); + if (!allowed) { + logForDebugging(`Connection blocked to ${hostname}:${port}`, { + level: 'error', + }); + socket.end('HTTP/1.1 403 Forbidden\r\n' + + 'Content-Type: text/plain\r\n' + + 'X-Proxy-Error: blocked-by-allowlist\r\n' + + '\r\n' + + 'Connection blocked by network allowlist'); + return; + } + // Check if this host should be routed through a MITM proxy + const mitmSocketPath = options.getMitmSocketPath?.(hostname); + if (mitmSocketPath) { + // Route through MITM proxy via Unix socket + logForDebugging(`Routing CONNECT ${hostname}:${port} through MITM proxy at ${mitmSocketPath}`); + const mitmSocket = connect({ path: mitmSocketPath }, () => { + // Send CONNECT request to the MITM proxy + mitmSocket.write(`CONNECT ${hostname}:${port} HTTP/1.1\r\n` + + `Host: ${hostname}:${port}\r\n` + + '\r\n'); + }); + // Buffer to accumulate the MITM proxy's response + let responseBuffer = ''; + const onMitmData = (chunk) => { + responseBuffer += chunk.toString(); + // Check if we've received the full HTTP response headers + const headerEndIndex = responseBuffer.indexOf('\r\n\r\n'); + if (headerEndIndex !== -1) { + // Remove data listener, we're done parsing the response + mitmSocket.removeListener('data', onMitmData); + // Check if MITM proxy accepted the connection + const statusLine = responseBuffer.substring(0, responseBuffer.indexOf('\r\n')); + if (statusLine.includes(' 200 ')) { + // Connection established, now pipe data between client and MITM + socket.write('HTTP/1.1 200 Connection Established\r\n\r\n'); + // If there's any data after the headers, write it to the client + const remainingData = responseBuffer.substring(headerEndIndex + 4); + if (remainingData.length > 0) { + socket.write(remainingData); + } + mitmSocket.pipe(socket); + socket.pipe(mitmSocket); + } + else { + logForDebugging(`MITM proxy rejected CONNECT: ${statusLine}`, { + level: 'error', + }); + socket.end('HTTP/1.1 502 Bad Gateway\r\n\r\n'); + mitmSocket.destroy(); + } + } + }; + mitmSocket.on('data', onMitmData); + mitmSocket.on('error', err => { + logForDebugging(`MITM proxy connection failed: ${err.message}`, { + level: 'error', + }); + socket.end('HTTP/1.1 502 Bad Gateway\r\n\r\n'); + }); + socket.on('error', err => { + logForDebugging(`Client socket error: ${err.message}`, { + level: 'error', + }); + mitmSocket.destroy(); + }); + socket.on('end', () => mitmSocket.end()); + mitmSocket.on('end', () => socket.end()); + } + else { + // Direct connection (original behavior) + const serverSocket = connect(port, hostname, () => { + socket.write('HTTP/1.1 200 Connection Established\r\n\r\n'); + serverSocket.pipe(socket); + socket.pipe(serverSocket); + }); + serverSocket.on('error', err => { + logForDebugging(`CONNECT tunnel failed: ${err.message}`, { + level: 'error', + }); + socket.end('HTTP/1.1 502 Bad Gateway\r\n\r\n'); + }); + socket.on('error', err => { + logForDebugging(`Client socket error: ${err.message}`, { + level: 'error', + }); + serverSocket.destroy(); + }); + socket.on('end', () => serverSocket.end()); + serverSocket.on('end', () => socket.end()); + } + } + catch (err) { + logForDebugging(`Error handling CONNECT: ${err}`, { level: 'error' }); + socket.end('HTTP/1.1 500 Internal Server Error\r\n\r\n'); + } + }); + // Handle regular HTTP requests + server.on('request', async (req, res) => { + try { + const url = new URL(req.url); + const hostname = url.hostname; + const port = url.port + ? parseInt(url.port, 10) + : url.protocol === 'https:' + ? 443 + : 80; + const allowed = await options.filter(port, hostname, req.socket); + if (!allowed) { + logForDebugging(`HTTP request blocked to ${hostname}:${port}`, { + level: 'error', + }); + res.writeHead(403, { + 'Content-Type': 'text/plain', + 'X-Proxy-Error': 'blocked-by-allowlist', + }); + res.end('Connection blocked by network allowlist'); + return; + } + // Check if this host should be routed through a MITM proxy + const mitmSocketPath = options.getMitmSocketPath?.(hostname); + if (mitmSocketPath) { + // Route through MITM proxy via Unix socket + // Use an agent that connects via the Unix socket + logForDebugging(`Routing HTTP ${req.method} ${hostname}:${port} through MITM proxy at ${mitmSocketPath}`); + const mitmAgent = new Agent({ + // @ts-expect-error - socketPath is valid but not in types + socketPath: mitmSocketPath, + }); + // Send request to MITM proxy with full URL (proxy-style request) + const proxyReq = httpRequest({ + agent: mitmAgent, + // For proxy requests, path should be the full URL + path: req.url, + method: req.method, + headers: { + ...req.headers, + host: url.host, + }, + }, proxyRes => { + res.writeHead(proxyRes.statusCode, proxyRes.headers); + proxyRes.pipe(res); + }); + proxyReq.on('error', err => { + logForDebugging(`MITM proxy request failed: ${err.message}`, { + level: 'error', + }); + if (!res.headersSent) { + res.writeHead(502, { 'Content-Type': 'text/plain' }); + res.end('Bad Gateway'); + } + }); + req.pipe(proxyReq); + } + else { + // Direct request (original behavior) + // Choose http or https module + const requestFn = url.protocol === 'https:' ? httpsRequest : httpRequest; + const proxyReq = requestFn({ + hostname, + port, + path: url.pathname + url.search, + method: req.method, + headers: { + ...req.headers, + host: url.host, + }, + }, proxyRes => { + res.writeHead(proxyRes.statusCode, proxyRes.headers); + proxyRes.pipe(res); + }); + proxyReq.on('error', err => { + logForDebugging(`Proxy request failed: ${err.message}`, { + level: 'error', + }); + if (!res.headersSent) { + res.writeHead(502, { 'Content-Type': 'text/plain' }); + res.end('Bad Gateway'); + } + }); + req.pipe(proxyReq); + } + } + catch (err) { + logForDebugging(`Error handling HTTP request: ${err}`, { level: 'error' }); + res.writeHead(500, { 'Content-Type': 'text/plain' }); + res.end('Internal Server Error'); + } + }); + return server; +} +//# sourceMappingURL=http-proxy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/linux-sandbox-utils.js b/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/linux-sandbox-utils.js new file mode 100644 index 00000000..dda6e042 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/linux-sandbox-utils.js @@ -0,0 +1,875 @@ +import shellquote from 'shell-quote'; +import { logForDebugging } from '../utils/debug.js'; +import { whichSync } from '../utils/which.js'; +import { randomBytes } from 'node:crypto'; +import * as fs from 'fs'; +import { spawn } from 'node:child_process'; +import { tmpdir } from 'node:os'; +import path, { join } from 'node:path'; +import { ripGrep } from '../utils/ripgrep.js'; +import { generateProxyEnvVars, normalizePathForSandbox, normalizeCaseForComparison, isSymlinkOutsideBoundary, DANGEROUS_FILES, getDangerousDirectories, } from './sandbox-utils.js'; +import { generateSeccompFilter, cleanupSeccompFilter, getPreGeneratedBpfPath, getApplySeccompBinaryPath, } from './generate-seccomp-filter.js'; +/** Default max depth for searching dangerous files */ +const DEFAULT_MANDATORY_DENY_SEARCH_DEPTH = 3; +/** + * Find if any component of the path is a symlink within the allowed write paths. + * Returns the symlink path if found, or null if no symlinks. + * + * This is used to detect and block symlink replacement attacks where an attacker + * could delete a symlink and create a real directory with malicious content. + */ +function findSymlinkInPath(targetPath, allowedWritePaths) { + const parts = targetPath.split(path.sep); + let currentPath = ''; + for (const part of parts) { + if (!part) + continue; // Skip empty parts (leading /) + const nextPath = currentPath + path.sep + part; + try { + const stats = fs.lstatSync(nextPath); + if (stats.isSymbolicLink()) { + // Check if this symlink is within an allowed write path + const isWithinAllowedPath = allowedWritePaths.some(allowedPath => nextPath.startsWith(allowedPath + '/') || nextPath === allowedPath); + if (isWithinAllowedPath) { + return nextPath; + } + } + } + catch { + // Path doesn't exist - no symlink issue here + break; + } + currentPath = nextPath; + } + return null; +} +/** + * Check if any existing component in the path is a file (not a directory). + * If so, the target path can never be created because you can't mkdir under a file. + * + * This handles the git worktree case: .git is a file, so .git/hooks can never + * exist and there's nothing to deny. + */ +function hasFileAncestor(targetPath) { + const parts = targetPath.split(path.sep); + let currentPath = ''; + for (const part of parts) { + if (!part) + continue; // Skip empty parts (leading /) + const nextPath = currentPath + path.sep + part; + try { + const stat = fs.statSync(nextPath); + if (stat.isFile() || stat.isSymbolicLink()) { + // This component exists as a file — nothing below it can be created + return true; + } + } + catch { + // Path doesn't exist — stop checking + break; + } + currentPath = nextPath; + } + return false; +} +/** + * Find the first non-existent path component. + * E.g., for "/existing/parent/nonexistent/child/file.txt" where /existing/parent exists, + * returns "/existing/parent/nonexistent" + * + * This is used to block creation of non-existent deny paths by mounting /dev/null + * at the first missing component, preventing mkdir from creating the parent directories. + */ +function findFirstNonExistentComponent(targetPath) { + const parts = targetPath.split(path.sep); + let currentPath = ''; + for (const part of parts) { + if (!part) + continue; // Skip empty parts (leading /) + const nextPath = currentPath + path.sep + part; + if (!fs.existsSync(nextPath)) { + return nextPath; + } + currentPath = nextPath; + } + return targetPath; // Shouldn't reach here if called correctly +} +/** + * Get mandatory deny paths using ripgrep (Linux only). + * Uses a SINGLE ripgrep call with multiple glob patterns for efficiency. + * With --max-depth limiting, this is fast enough to run on each command without memoization. + */ +async function linuxGetMandatoryDenyPaths(ripgrepConfig = { command: 'rg' }, maxDepth = DEFAULT_MANDATORY_DENY_SEARCH_DEPTH, allowGitConfig = false, abortSignal) { + const cwd = process.cwd(); + // Use provided signal or create a fallback controller + const fallbackController = new AbortController(); + const signal = abortSignal ?? fallbackController.signal; + const dangerousDirectories = getDangerousDirectories(); + // Note: Settings files are added at the callsite in sandbox-manager.ts + const denyPaths = [ + // Dangerous files in CWD + ...DANGEROUS_FILES.map(f => path.resolve(cwd, f)), + // Dangerous directories in CWD + ...dangerousDirectories.map(d => path.resolve(cwd, d)), + ]; + // Git hooks and config are only denied when .git exists as a directory. + // In git worktrees, .git is a file (e.g., "gitdir: /path/..."), so + // .git/hooks can never exist — denying it would cause bwrap to fail. + // When .git doesn't exist at all, mounting at .git would block its + // creation and break git init. + const dotGitPath = path.resolve(cwd, '.git'); + let dotGitIsDirectory = false; + try { + dotGitIsDirectory = fs.statSync(dotGitPath).isDirectory(); + } + catch { + // .git doesn't exist + } + if (dotGitIsDirectory) { + // Git hooks always blocked for security + denyPaths.push(path.resolve(cwd, '.git/hooks')); + // Git config conditionally blocked based on allowGitConfig setting + if (!allowGitConfig) { + denyPaths.push(path.resolve(cwd, '.git/config')); + } + } + // Build iglob args for all patterns in one ripgrep call + const iglobArgs = []; + for (const fileName of DANGEROUS_FILES) { + iglobArgs.push('--iglob', fileName); + } + for (const dirName of dangerousDirectories) { + iglobArgs.push('--iglob', `**/${dirName}/**`); + } + // Git hooks always blocked in nested repos + iglobArgs.push('--iglob', '**/.git/hooks/**'); + // Git config conditionally blocked in nested repos + if (!allowGitConfig) { + iglobArgs.push('--iglob', '**/.git/config'); + } + // Single ripgrep call to find all dangerous paths in subdirectories + // Limit depth for performance - deeply nested dangerous files are rare + // and the security benefit doesn't justify the traversal cost + let matches = []; + try { + matches = await ripGrep([ + '--files', + '--hidden', + '--max-depth', + String(maxDepth), + ...iglobArgs, + '-g', + '!**/node_modules/**', + ], cwd, signal, ripgrepConfig); + } + catch (error) { + logForDebugging(`[Sandbox] ripgrep scan failed: ${error}`); + } + // Process matches + for (const match of matches) { + const absolutePath = path.resolve(cwd, match); + // File inside a dangerous directory -> add the directory path + let foundDir = false; + for (const dirName of [...dangerousDirectories, '.git']) { + const normalizedDirName = normalizeCaseForComparison(dirName); + const segments = absolutePath.split(path.sep); + const dirIndex = segments.findIndex(s => normalizeCaseForComparison(s) === normalizedDirName); + if (dirIndex !== -1) { + // For .git, we want hooks/ or config, not the whole .git dir + if (dirName === '.git') { + const gitDir = segments.slice(0, dirIndex + 1).join(path.sep); + if (match.includes('.git/hooks')) { + denyPaths.push(path.join(gitDir, 'hooks')); + } + else if (match.includes('.git/config')) { + denyPaths.push(path.join(gitDir, 'config')); + } + } + else { + denyPaths.push(segments.slice(0, dirIndex + 1).join(path.sep)); + } + foundDir = true; + break; + } + } + // Dangerous file match + if (!foundDir) { + denyPaths.push(absolutePath); + } + } + return [...new Set(denyPaths)]; +} +// Track generated seccomp filters for cleanup on process exit +const generatedSeccompFilters = new Set(); +// Track mount points created by bwrap for non-existent deny paths. +// When bwrap does --ro-bind /dev/null /nonexistent/path, it creates an empty +// file on the host as a mount point. These persist after bwrap exits and must +// be cleaned up explicitly. +const bwrapMountPoints = new Set(); +let exitHandlerRegistered = false; +/** + * Register cleanup handler for generated seccomp filters and bwrap mount points + */ +function registerExitCleanupHandler() { + if (exitHandlerRegistered) { + return; + } + process.on('exit', () => { + for (const filterPath of generatedSeccompFilters) { + try { + cleanupSeccompFilter(filterPath); + } + catch { + // Ignore cleanup errors during exit + } + } + cleanupBwrapMountPoints(); + }); + exitHandlerRegistered = true; +} +/** + * Clean up mount point files created by bwrap for non-existent deny paths. + * + * When protecting non-existent deny paths, bwrap creates empty files on the + * host filesystem as mount points for --ro-bind. These files persist after + * bwrap exits. This function removes them. + * + * This should be called after each sandboxed command completes to prevent + * ghost dotfiles (e.g. .bashrc, .gitconfig) from appearing in the working + * directory. It is also called automatically on process exit as a safety net. + * + * Safe to call at any time — it only removes files that were tracked during + * generateFilesystemArgs() and skips any that no longer exist. + */ +export function cleanupBwrapMountPoints() { + for (const mountPoint of bwrapMountPoints) { + try { + // Only remove if it's still the empty file/directory bwrap created. + // If something else has written real content, leave it alone. + const stat = fs.statSync(mountPoint); + if (stat.isFile() && stat.size === 0) { + fs.unlinkSync(mountPoint); + logForDebugging(`[Sandbox Linux] Cleaned up bwrap mount point (file): ${mountPoint}`); + } + else if (stat.isDirectory()) { + // Empty directory mount points are created for intermediate + // components (Fix 2). Only remove if still empty. + const entries = fs.readdirSync(mountPoint); + if (entries.length === 0) { + fs.rmdirSync(mountPoint); + logForDebugging(`[Sandbox Linux] Cleaned up bwrap mount point (dir): ${mountPoint}`); + } + } + } + catch { + // Ignore cleanup errors — the file may have already been removed + } + } + bwrapMountPoints.clear(); +} +/** + * Get detailed status of Linux sandbox dependencies + */ +export function getLinuxDependencyStatus(seccompConfig) { + return { + hasBwrap: whichSync('bwrap') !== null, + hasSocat: whichSync('socat') !== null, + hasSeccompBpf: getPreGeneratedBpfPath(seccompConfig?.bpfPath) !== null, + hasSeccompApply: getApplySeccompBinaryPath(seccompConfig?.applyPath) !== null, + }; +} +/** + * Check sandbox dependencies and return structured result + */ +export function checkLinuxDependencies(seccompConfig) { + const errors = []; + const warnings = []; + if (whichSync('bwrap') === null) + errors.push('bubblewrap (bwrap) not installed'); + if (whichSync('socat') === null) + errors.push('socat not installed'); + const hasBpf = getPreGeneratedBpfPath(seccompConfig?.bpfPath) !== null; + const hasApply = getApplySeccompBinaryPath(seccompConfig?.applyPath) !== null; + if (!hasBpf || !hasApply) { + warnings.push('seccomp not available - unix socket access not restricted'); + } + return { warnings, errors }; +} +/** + * Initialize the Linux network bridge for sandbox networking + * + * ARCHITECTURE NOTE: + * Linux network sandboxing uses bwrap --unshare-net which creates a completely isolated + * network namespace with NO network access. To enable network access, we: + * + * 1. Host side: Run socat bridges that listen on Unix sockets and forward to host proxy servers + * - HTTP bridge: Unix socket -> host HTTP proxy (for HTTP/HTTPS traffic) + * - SOCKS bridge: Unix socket -> host SOCKS5 proxy (for SSH/git traffic) + * + * 2. Sandbox side: Bind the Unix sockets into the isolated namespace and run socat listeners + * - HTTP listener on port 3128 -> HTTP Unix socket -> host HTTP proxy + * - SOCKS listener on port 1080 -> SOCKS Unix socket -> host SOCKS5 proxy + * + * 3. Configure environment: + * - HTTP_PROXY=http://localhost:3128 for HTTP/HTTPS tools + * - GIT_SSH_COMMAND with socat for SSH through SOCKS5 + * + * LIMITATION: Unlike macOS sandbox which can enforce domain-based allowlists at the kernel level, + * Linux's --unshare-net provides only all-or-nothing network isolation. Domain filtering happens + * at the host proxy level, not the sandbox boundary. This means network restrictions on Linux + * depend on the proxy's filtering capabilities. + * + * DEPENDENCIES: Requires bwrap (bubblewrap) and socat + */ +export async function initializeLinuxNetworkBridge(httpProxyPort, socksProxyPort) { + const socketId = randomBytes(8).toString('hex'); + const httpSocketPath = join(tmpdir(), `claude-http-${socketId}.sock`); + const socksSocketPath = join(tmpdir(), `claude-socks-${socketId}.sock`); + // Start HTTP bridge + const httpSocatArgs = [ + `UNIX-LISTEN:${httpSocketPath},fork,reuseaddr`, + `TCP:localhost:${httpProxyPort},keepalive,keepidle=10,keepintvl=5,keepcnt=3`, + ]; + logForDebugging(`Starting HTTP bridge: socat ${httpSocatArgs.join(' ')}`); + const httpBridgeProcess = spawn('socat', httpSocatArgs, { + stdio: 'ignore', + }); + if (!httpBridgeProcess.pid) { + throw new Error('Failed to start HTTP bridge process'); + } + // Add error and exit handlers to monitor bridge health + httpBridgeProcess.on('error', err => { + logForDebugging(`HTTP bridge process error: ${err}`, { level: 'error' }); + }); + httpBridgeProcess.on('exit', (code, signal) => { + logForDebugging(`HTTP bridge process exited with code ${code}, signal ${signal}`, { level: code === 0 ? 'info' : 'error' }); + }); + // Start SOCKS bridge + const socksSocatArgs = [ + `UNIX-LISTEN:${socksSocketPath},fork,reuseaddr`, + `TCP:localhost:${socksProxyPort},keepalive,keepidle=10,keepintvl=5,keepcnt=3`, + ]; + logForDebugging(`Starting SOCKS bridge: socat ${socksSocatArgs.join(' ')}`); + const socksBridgeProcess = spawn('socat', socksSocatArgs, { + stdio: 'ignore', + }); + if (!socksBridgeProcess.pid) { + // Clean up HTTP bridge + if (httpBridgeProcess.pid) { + try { + process.kill(httpBridgeProcess.pid, 'SIGTERM'); + } + catch { + // Ignore errors + } + } + throw new Error('Failed to start SOCKS bridge process'); + } + // Add error and exit handlers to monitor bridge health + socksBridgeProcess.on('error', err => { + logForDebugging(`SOCKS bridge process error: ${err}`, { level: 'error' }); + }); + socksBridgeProcess.on('exit', (code, signal) => { + logForDebugging(`SOCKS bridge process exited with code ${code}, signal ${signal}`, { level: code === 0 ? 'info' : 'error' }); + }); + // Wait for both sockets to be ready + const maxAttempts = 5; + for (let i = 0; i < maxAttempts; i++) { + if (!httpBridgeProcess.pid || + httpBridgeProcess.killed || + !socksBridgeProcess.pid || + socksBridgeProcess.killed) { + throw new Error('Linux bridge process died unexpectedly'); + } + try { + // fs already imported + if (fs.existsSync(httpSocketPath) && fs.existsSync(socksSocketPath)) { + logForDebugging(`Linux bridges ready after ${i + 1} attempts`); + break; + } + } + catch (err) { + logForDebugging(`Error checking sockets (attempt ${i + 1}): ${err}`, { + level: 'error', + }); + } + if (i === maxAttempts - 1) { + // Clean up both processes + if (httpBridgeProcess.pid) { + try { + process.kill(httpBridgeProcess.pid, 'SIGTERM'); + } + catch { + // Ignore errors + } + } + if (socksBridgeProcess.pid) { + try { + process.kill(socksBridgeProcess.pid, 'SIGTERM'); + } + catch { + // Ignore errors + } + } + throw new Error(`Failed to create bridge sockets after ${maxAttempts} attempts`); + } + await new Promise(resolve => setTimeout(resolve, i * 100)); + } + return { + httpSocketPath, + socksSocketPath, + httpBridgeProcess, + socksBridgeProcess, + httpProxyPort, + socksProxyPort, + }; +} +/** + * Build the command that runs inside the sandbox. + * Sets up HTTP proxy on port 3128 and SOCKS proxy on port 1080 + */ +function buildSandboxCommand(httpSocketPath, socksSocketPath, userCommand, seccompFilterPath, shell, applySeccompPath) { + // Default to bash for backward compatibility + const shellPath = shell || 'bash'; + const socatCommands = [ + `socat TCP-LISTEN:3128,fork,reuseaddr UNIX-CONNECT:${httpSocketPath} >/dev/null 2>&1 &`, + `socat TCP-LISTEN:1080,fork,reuseaddr UNIX-CONNECT:${socksSocketPath} >/dev/null 2>&1 &`, + 'trap "kill %1 %2 2>/dev/null; exit" EXIT', + ]; + // If seccomp filter is provided, use apply-seccomp to apply it + if (seccompFilterPath) { + // apply-seccomp approach: + // 1. Outer bwrap/bash: starts socat processes (can use Unix sockets) + // 2. apply-seccomp: applies seccomp filter and execs user command + // 3. User command runs with seccomp active (Unix sockets blocked) + // + // apply-seccomp is a simple C program that: + // - Sets PR_SET_NO_NEW_PRIVS + // - Applies the seccomp BPF filter via prctl(PR_SET_SECCOMP) + // - Execs the user command + // + // This is simpler and more portable than nested bwrap, with no FD redirects needed. + const applySeccompBinary = getApplySeccompBinaryPath(applySeccompPath); + if (!applySeccompBinary) { + throw new Error('apply-seccomp binary not found. This should have been caught earlier. ' + + 'Ensure vendor/seccomp/{x64,arm64}/apply-seccomp binaries are included in the package.'); + } + const applySeccompCmd = shellquote.quote([ + applySeccompBinary, + seccompFilterPath, + shellPath, + '-c', + userCommand, + ]); + const innerScript = [...socatCommands, applySeccompCmd].join('\n'); + return `${shellPath} -c ${shellquote.quote([innerScript])}`; + } + else { + // No seccomp filter - run user command directly + const innerScript = [ + ...socatCommands, + `eval ${shellquote.quote([userCommand])}`, + ].join('\n'); + return `${shellPath} -c ${shellquote.quote([innerScript])}`; + } +} +/** + * Generate filesystem bind mount arguments for bwrap + */ +async function generateFilesystemArgs(readConfig, writeConfig, ripgrepConfig = { command: 'rg' }, mandatoryDenySearchDepth = DEFAULT_MANDATORY_DENY_SEARCH_DEPTH, allowGitConfig = false, abortSignal) { + const args = []; + // fs already imported + // Determine initial root mount based on write restrictions + if (writeConfig) { + // Write restrictions: Start with read-only root, then allow writes to specific paths + args.push('--ro-bind', '/', '/'); + // Collect normalized allowed write paths for later checking + const allowedWritePaths = []; + // Allow writes to specific paths + for (const pathPattern of writeConfig.allowOnly || []) { + const normalizedPath = normalizePathForSandbox(pathPattern); + logForDebugging(`[Sandbox Linux] Processing write path: ${pathPattern} -> ${normalizedPath}`); + // Skip /dev/* paths since --dev /dev already handles them + if (normalizedPath.startsWith('/dev/')) { + logForDebugging(`[Sandbox Linux] Skipping /dev path: ${normalizedPath}`); + continue; + } + if (!fs.existsSync(normalizedPath)) { + logForDebugging(`[Sandbox Linux] Skipping non-existent write path: ${normalizedPath}`); + continue; + } + // Check if path is a symlink pointing outside expected boundaries + // bwrap follows symlinks, so --bind on a symlink makes the target writable + // This could unexpectedly expose paths the user didn't intend to allow + try { + const resolvedPath = fs.realpathSync(normalizedPath); + // Trim trailing slashes before comparing: realpathSync never returns + // a trailing slash, but normalizedPath may have one, which would cause + // a false mismatch and incorrectly treat the path as a symlink. + const normalizedForComparison = normalizedPath.replace(/\/+$/, ''); + if (resolvedPath !== normalizedForComparison && + isSymlinkOutsideBoundary(normalizedPath, resolvedPath)) { + logForDebugging(`[Sandbox Linux] Skipping symlink write path pointing outside expected location: ${pathPattern} -> ${resolvedPath}`); + continue; + } + } + catch { + // realpathSync failed - path might not exist or be accessible, skip it + logForDebugging(`[Sandbox Linux] Skipping write path that could not be resolved: ${normalizedPath}`); + continue; + } + args.push('--bind', normalizedPath, normalizedPath); + allowedWritePaths.push(normalizedPath); + } + // Deny writes within allowed paths (user-specified + mandatory denies) + const denyPaths = [ + ...(writeConfig.denyWithinAllow || []), + ...(await linuxGetMandatoryDenyPaths(ripgrepConfig, mandatoryDenySearchDepth, allowGitConfig, abortSignal)), + ]; + for (const pathPattern of denyPaths) { + const normalizedPath = normalizePathForSandbox(pathPattern); + // Skip /dev/* paths since --dev /dev already handles them + if (normalizedPath.startsWith('/dev/')) { + continue; + } + // Check for symlinks in the path - if any parent component is a symlink, + // mount /dev/null there to prevent symlink replacement attacks. + // Attack scenario: .claude is a symlink to ./decoy/, attacker deletes + // symlink and creates real .claude/settings.json with malicious hooks. + const symlinkInPath = findSymlinkInPath(normalizedPath, allowedWritePaths); + if (symlinkInPath) { + args.push('--ro-bind', '/dev/null', symlinkInPath); + logForDebugging(`[Sandbox Linux] Mounted /dev/null at symlink ${symlinkInPath} to prevent symlink replacement attack`); + continue; + } + // Handle non-existent paths by mounting /dev/null to block creation. + // Without this, a sandboxed process could mkdir+write a denied path that + // doesn't exist yet, bypassing the deny rule entirely. + // + // bwrap creates empty files on the host as mount points for these binds. + // We track them in bwrapMountPoints so cleanupBwrapMountPoints() can + // remove them after the command exits. + if (!fs.existsSync(normalizedPath)) { + // Fix 1 (worktree): If any existing component in the deny path is a + // file (not a directory), skip the deny entirely. You can't mkdir + // under a file, so the deny path can never be created. This handles + // git worktrees where .git is a file. + if (hasFileAncestor(normalizedPath)) { + logForDebugging(`[Sandbox Linux] Skipping deny path with file ancestor (cannot create paths under a file): ${normalizedPath}`); + continue; + } + // Find the deepest existing ancestor directory + let ancestorPath = path.dirname(normalizedPath); + while (ancestorPath !== '/' && !fs.existsSync(ancestorPath)) { + ancestorPath = path.dirname(ancestorPath); + } + // Only protect if the existing ancestor is within an allowed write path. + // If not, the path is already read-only from --ro-bind / /. + const ancestorIsWithinAllowedPath = allowedWritePaths.some(allowedPath => ancestorPath.startsWith(allowedPath + '/') || + ancestorPath === allowedPath || + normalizedPath.startsWith(allowedPath + '/')); + if (ancestorIsWithinAllowedPath) { + const firstNonExistent = findFirstNonExistentComponent(normalizedPath); + // Fix 2: If firstNonExistent is an intermediate component (not the + // leaf deny path itself), mount a read-only empty directory instead + // of /dev/null. This prevents the component from appearing as a file + // which breaks tools that expect to traverse it as a directory. + if (firstNonExistent !== normalizedPath) { + const emptyDir = fs.mkdtempSync(path.join(tmpdir(), 'claude-empty-')); + args.push('--ro-bind', emptyDir, firstNonExistent); + bwrapMountPoints.add(firstNonExistent); + registerExitCleanupHandler(); + logForDebugging(`[Sandbox Linux] Mounted empty dir at ${firstNonExistent} to block creation of ${normalizedPath}`); + } + else { + args.push('--ro-bind', '/dev/null', firstNonExistent); + bwrapMountPoints.add(firstNonExistent); + registerExitCleanupHandler(); + logForDebugging(`[Sandbox Linux] Mounted /dev/null at ${firstNonExistent} to block creation of ${normalizedPath}`); + } + } + else { + logForDebugging(`[Sandbox Linux] Skipping non-existent deny path not within allowed paths: ${normalizedPath}`); + } + continue; + } + // Only add deny binding if this path is within an allowed write path + // Otherwise it's already read-only from the initial --ro-bind / / + const isWithinAllowedPath = allowedWritePaths.some(allowedPath => normalizedPath.startsWith(allowedPath + '/') || + normalizedPath === allowedPath); + if (isWithinAllowedPath) { + args.push('--ro-bind', normalizedPath, normalizedPath); + } + else { + logForDebugging(`[Sandbox Linux] Skipping deny path not within allowed paths: ${normalizedPath}`); + } + } + } + else { + // No write restrictions: Allow all writes + args.push('--bind', '/', '/'); + } + // Handle read restrictions by mounting tmpfs over denied paths + const readDenyPaths = [...(readConfig?.denyOnly || [])]; + const readAllowPaths = (readConfig?.allowWithinDeny || []).map(p => normalizePathForSandbox(p)); + // Always hide /etc/ssh/ssh_config.d to avoid permission issues with OrbStack + // SSH is very strict about config file permissions and ownership, and they can + // appear wrong inside the sandbox causing "Bad owner or permissions" errors + if (fs.existsSync('/etc/ssh/ssh_config.d')) { + readDenyPaths.push('/etc/ssh/ssh_config.d'); + } + for (const pathPattern of readDenyPaths) { + const normalizedPath = normalizePathForSandbox(pathPattern); + if (!fs.existsSync(normalizedPath)) { + logForDebugging(`[Sandbox Linux] Skipping non-existent read deny path: ${normalizedPath}`); + continue; + } + const readDenyStat = fs.statSync(normalizedPath); + if (readDenyStat.isDirectory()) { + args.push('--tmpfs', normalizedPath); + // Re-allow specific paths within the denied directory (allowRead overrides denyRead). + // After mounting tmpfs over the denied dir, bind back the allowed subdirectories + // so they are readable again. + for (const allowPath of readAllowPaths) { + if (allowPath.startsWith(normalizedPath + '/') || + allowPath === normalizedPath) { + if (!fs.existsSync(allowPath)) { + logForDebugging(`[Sandbox Linux] Skipping non-existent read allow path: ${allowPath}`); + continue; + } + // Bind the allowed path back over the tmpfs so it's readable + args.push('--ro-bind', allowPath, allowPath); + logForDebugging(`[Sandbox Linux] Re-allowed read access within denied region: ${allowPath}`); + } + } + } + else { + // For files, check if this specific file is re-allowed + const isReAllowed = readAllowPaths.some(allowPath => normalizedPath === allowPath || + normalizedPath.startsWith(allowPath + '/')); + if (isReAllowed) { + logForDebugging(`[Sandbox Linux] Skipping read deny for re-allowed path: ${normalizedPath}`); + continue; + } + // For files, bind /dev/null instead of tmpfs + args.push('--ro-bind', '/dev/null', normalizedPath); + } + } + return args; +} +/** + * Wrap a command with sandbox restrictions on Linux + * + * UNIX SOCKET BLOCKING (APPLY-SECCOMP): + * This implementation uses a custom apply-seccomp binary to block Unix domain socket + * creation for user commands while allowing network infrastructure: + * + * Stage 1: Outer bwrap - Network and filesystem isolation (NO seccomp) + * - Bubblewrap starts with isolated network namespace (--unshare-net) + * - Bubblewrap applies PID namespace isolation (--unshare-pid and --proc) + * - Filesystem restrictions are applied (read-only mounts, bind mounts, etc.) + * - Socat processes start and connect to Unix socket bridges (can use socket(AF_UNIX, ...)) + * + * Stage 2: apply-seccomp - Seccomp filter application (ONLY seccomp) + * - apply-seccomp binary applies seccomp filter via prctl(PR_SET_SECCOMP) + * - Sets PR_SET_NO_NEW_PRIVS to allow seccomp without root + * - Execs user command with seccomp active (cannot create new Unix sockets) + * + * This solves the conflict between: + * - Security: Blocking arbitrary Unix socket creation in user commands + * - Functionality: Network sandboxing requires socat to call socket(AF_UNIX, ...) for bridge connections + * + * The seccomp-bpf filter blocks socket(AF_UNIX, ...) syscalls, preventing: + * - Creating new Unix domain socket file descriptors + * + * Security limitations: + * - Does NOT block operations (bind, connect, sendto, etc.) on inherited Unix socket FDs + * - Does NOT prevent passing Unix socket FDs via SCM_RIGHTS + * - For most sandboxing use cases, blocking socket creation is sufficient + * + * The filter allows: + * - All TCP/UDP sockets (AF_INET, AF_INET6) for normal network operations + * - All other syscalls + * + * PLATFORM NOTE: + * The allowUnixSockets configuration is not path-based on Linux (unlike macOS) + * because seccomp-bpf cannot inspect user-space memory to read socket paths. + * + * Requirements for seccomp filtering: + * - Pre-built apply-seccomp binaries are included for x64 and ARM64 + * - Pre-generated BPF filters are included for x64 and ARM64 + * - Other architectures are not currently supported (no apply-seccomp binary available) + * - To use sandboxing without Unix socket blocking on unsupported architectures, + * set allowAllUnixSockets: true in your configuration + * Dependencies are checked by checkLinuxDependencies() before enabling the sandbox. + */ +export async function wrapCommandWithSandboxLinux(params) { + const { command, needsNetworkRestriction, httpSocketPath, socksSocketPath, httpProxyPort, socksProxyPort, readConfig, writeConfig, enableWeakerNestedSandbox, allowAllUnixSockets, binShell, ripgrepConfig = { command: 'rg' }, mandatoryDenySearchDepth = DEFAULT_MANDATORY_DENY_SEARCH_DEPTH, allowGitConfig = false, seccompConfig, abortSignal, } = params; + // Determine if we have restrictions to apply + // Read: denyOnly pattern - empty array means no restrictions + // Write: allowOnly pattern - undefined means no restrictions, any config means restrictions + const hasReadRestrictions = readConfig && readConfig.denyOnly.length > 0; + const hasWriteRestrictions = writeConfig !== undefined; + // Check if we need any sandboxing + if (!needsNetworkRestriction && + !hasReadRestrictions && + !hasWriteRestrictions) { + return command; + } + const bwrapArgs = ['--new-session', '--die-with-parent']; + let seccompFilterPath = undefined; + try { + // ========== SECCOMP FILTER (Unix Socket Blocking) ========== + // Use bwrap's --seccomp flag to apply BPF filter that blocks Unix socket creation + // + // NOTE: Seccomp filtering is only enabled when allowAllUnixSockets is false + // (when true, Unix sockets are allowed) + if (!allowAllUnixSockets) { + seccompFilterPath = + generateSeccompFilter(seccompConfig?.bpfPath) ?? undefined; + const applySeccompBinary = getApplySeccompBinaryPath(seccompConfig?.applyPath); + if (!seccompFilterPath || !applySeccompBinary) { + // Seccomp binaries not found - warn but continue without unix socket blocking + logForDebugging('[Sandbox Linux] Seccomp binaries not available - unix socket blocking disabled. ' + + 'Install @anthropic-ai/sandbox-runtime globally for full protection.', { level: 'warn' }); + // Clear the filter path so we don't try to use it + seccompFilterPath = undefined; + } + else { + // Track filter for cleanup and register exit handler + // Only track runtime-generated filters (not pre-generated ones from vendor/) + if (!seccompFilterPath.includes('/vendor/seccomp/')) { + generatedSeccompFilters.add(seccompFilterPath); + registerExitCleanupHandler(); + } + logForDebugging('[Sandbox Linux] Generated seccomp BPF filter for Unix socket blocking'); + } + } + else { + logForDebugging('[Sandbox Linux] Skipping seccomp filter - allowAllUnixSockets is enabled'); + } + // ========== NETWORK RESTRICTIONS ========== + if (needsNetworkRestriction) { + // Always unshare network namespace to isolate network access + // This removes all network interfaces, effectively blocking all network + bwrapArgs.push('--unshare-net'); + // If proxy sockets are provided, bind them into the sandbox to allow + // filtered network access through the proxy. If not provided, network + // is completely blocked (empty allowedDomains = block all) + if (httpSocketPath && socksSocketPath) { + // Verify socket files still exist before trying to bind them + if (!fs.existsSync(httpSocketPath)) { + throw new Error(`Linux HTTP bridge socket does not exist: ${httpSocketPath}. ` + + 'The bridge process may have died. Try reinitializing the sandbox.'); + } + if (!fs.existsSync(socksSocketPath)) { + throw new Error(`Linux SOCKS bridge socket does not exist: ${socksSocketPath}. ` + + 'The bridge process may have died. Try reinitializing the sandbox.'); + } + // Bind both sockets into the sandbox + bwrapArgs.push('--bind', httpSocketPath, httpSocketPath); + bwrapArgs.push('--bind', socksSocketPath, socksSocketPath); + // Add proxy environment variables + // HTTP_PROXY points to the socat listener inside the sandbox (port 3128) + // which forwards to the Unix socket that bridges to the host's proxy server + const proxyEnv = generateProxyEnvVars(3128, // Internal HTTP listener port + 1080); + bwrapArgs.push(...proxyEnv.flatMap((env) => { + const firstEq = env.indexOf('='); + const key = env.slice(0, firstEq); + const value = env.slice(firstEq + 1); + return ['--setenv', key, value]; + })); + // Add host proxy port environment variables for debugging/transparency + // These show which host ports the Unix socket bridges connect to + if (httpProxyPort !== undefined) { + bwrapArgs.push('--setenv', 'CLAUDE_CODE_HOST_HTTP_PROXY_PORT', String(httpProxyPort)); + } + if (socksProxyPort !== undefined) { + bwrapArgs.push('--setenv', 'CLAUDE_CODE_HOST_SOCKS_PROXY_PORT', String(socksProxyPort)); + } + } + // If no sockets provided, network is completely blocked (--unshare-net without proxy) + } + // ========== FILESYSTEM RESTRICTIONS ========== + const fsArgs = await generateFilesystemArgs(readConfig, writeConfig, ripgrepConfig, mandatoryDenySearchDepth, allowGitConfig, abortSignal); + bwrapArgs.push(...fsArgs); + // Always bind /dev + bwrapArgs.push('--dev', '/dev'); + // ========== PID NAMESPACE ISOLATION ========== + // IMPORTANT: These must come AFTER filesystem binds for nested bwrap to work + // By default, always unshare PID namespace and mount fresh /proc. + // If we don't have --unshare-pid, it is possible to escape the sandbox. + // If we don't have --proc, it is possible to read host /proc and leak information about code running + // outside the sandbox. But, --proc is not available when running in unprivileged docker containers + // so we support running without it if explicitly requested. + bwrapArgs.push('--unshare-pid'); + if (!enableWeakerNestedSandbox) { + // Mount fresh /proc if PID namespace is isolated (secure mode) + bwrapArgs.push('--proc', '/proc'); + } + // ========== COMMAND ========== + // Use the user's shell (zsh, bash, etc.) to ensure aliases/snapshots work + // Resolve the full path to the shell binary since bwrap doesn't use $PATH + const shellName = binShell || 'bash'; + const shell = whichSync(shellName); + if (!shell) { + throw new Error(`Shell '${shellName}' not found in PATH`); + } + bwrapArgs.push('--', shell, '-c'); + // If we have network restrictions, use the network bridge setup with apply-seccomp for seccomp + // Otherwise, just run the command directly with apply-seccomp if needed + if (needsNetworkRestriction && httpSocketPath && socksSocketPath) { + // Pass seccomp filter to buildSandboxCommand for apply-seccomp application + // This allows socat to start before seccomp is applied + const sandboxCommand = buildSandboxCommand(httpSocketPath, socksSocketPath, command, seccompFilterPath, shell, seccompConfig?.applyPath); + bwrapArgs.push(sandboxCommand); + } + else if (seccompFilterPath) { + // No network restrictions but we have seccomp - use apply-seccomp directly + // apply-seccomp is a simple C program that applies the seccomp filter and execs the command + const applySeccompBinary = getApplySeccompBinaryPath(seccompConfig?.applyPath); + if (!applySeccompBinary) { + throw new Error('apply-seccomp binary not found. This should have been caught earlier. ' + + 'Ensure vendor/seccomp/{x64,arm64}/apply-seccomp binaries are included in the package.'); + } + const applySeccompCmd = shellquote.quote([ + applySeccompBinary, + seccompFilterPath, + shell, + '-c', + command, + ]); + bwrapArgs.push(applySeccompCmd); + } + else { + bwrapArgs.push(command); + } + // Build the outer bwrap command + const wrappedCommand = shellquote.quote(['bwrap', ...bwrapArgs]); + const restrictions = []; + if (needsNetworkRestriction) + restrictions.push('network'); + if (hasReadRestrictions || hasWriteRestrictions) + restrictions.push('filesystem'); + if (seccompFilterPath) + restrictions.push('seccomp(unix-block)'); + logForDebugging(`[Sandbox Linux] Wrapped command with bwrap (${restrictions.join(', ')} restrictions)`); + return wrappedCommand; + } + catch (error) { + // Clean up seccomp filter on error + if (seccompFilterPath && !seccompFilterPath.includes('/vendor/seccomp/')) { + generatedSeccompFilters.delete(seccompFilterPath); + try { + cleanupSeccompFilter(seccompFilterPath); + } + catch (cleanupError) { + logForDebugging(`[Sandbox Linux] Failed to clean up seccomp filter on error: ${cleanupError}`, { level: 'error' }); + } + } + // Re-throw the original error + throw error; + } +} +//# sourceMappingURL=linux-sandbox-utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/macos-sandbox-utils.js b/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/macos-sandbox-utils.js new file mode 100644 index 00000000..b92421ea --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/macos-sandbox-utils.js @@ -0,0 +1,630 @@ +import shellquote from 'shell-quote'; +import { spawn } from 'child_process'; +import * as path from 'path'; +import { logForDebugging } from '../utils/debug.js'; +import { whichSync } from '../utils/which.js'; +import { normalizePathForSandbox, generateProxyEnvVars, encodeSandboxedCommand, decodeSandboxedCommand, containsGlobChars, globToRegex, DANGEROUS_FILES, getDangerousDirectories, } from './sandbox-utils.js'; +/** + * Get mandatory deny patterns as glob patterns (no filesystem scanning). + * macOS sandbox profile supports regex/glob matching directly via globToRegex(). + */ +export function macGetMandatoryDenyPatterns(allowGitConfig = false) { + const cwd = process.cwd(); + const denyPaths = []; + // Dangerous files - static paths in CWD + glob patterns for subtree + for (const fileName of DANGEROUS_FILES) { + denyPaths.push(path.resolve(cwd, fileName)); + denyPaths.push(`**/${fileName}`); + } + // Dangerous directories + for (const dirName of getDangerousDirectories()) { + denyPaths.push(path.resolve(cwd, dirName)); + denyPaths.push(`**/${dirName}/**`); + } + // Git hooks are always blocked for security + denyPaths.push(path.resolve(cwd, '.git/hooks')); + denyPaths.push('**/.git/hooks/**'); + // Git config - conditionally blocked based on allowGitConfig setting + if (!allowGitConfig) { + denyPaths.push(path.resolve(cwd, '.git/config')); + denyPaths.push('**/.git/config'); + } + return [...new Set(denyPaths)]; +} +const sessionSuffix = `_${Math.random().toString(36).slice(2, 11)}_SBX`; +/** + * Generate a unique log tag for sandbox monitoring + * @param command - The command being executed (will be base64 encoded) + */ +function generateLogTag(command) { + const encodedCommand = encodeSandboxedCommand(command); + return `CMD64_${encodedCommand}_END_${sessionSuffix}`; +} +/** + * Get all ancestor directories for a path, up to (but not including) root + * Example: /private/tmp/test/file.txt -> ["/private/tmp/test", "/private/tmp", "/private"] + */ +function getAncestorDirectories(pathStr) { + const ancestors = []; + let currentPath = path.dirname(pathStr); + // Walk up the directory tree until we reach root + while (currentPath !== '/' && currentPath !== '.') { + ancestors.push(currentPath); + const parentPath = path.dirname(currentPath); + // Break if we've reached the top (path.dirname returns the same path for root) + if (parentPath === currentPath) { + break; + } + currentPath = parentPath; + } + return ancestors; +} +/** + * Generate deny rules for file movement (file-write-unlink) to protect paths + * This prevents bypassing read or write restrictions by moving files/directories + * + * @param pathPatterns - Array of path patterns to protect (can include globs) + * @param logTag - Log tag for sandbox violations + * @returns Array of sandbox profile rule lines + */ +function generateMoveBlockingRules(pathPatterns, logTag) { + const rules = []; + for (const pathPattern of pathPatterns) { + const normalizedPath = normalizePathForSandbox(pathPattern); + if (containsGlobChars(normalizedPath)) { + // Use regex matching for glob patterns + const regexPattern = globToRegex(normalizedPath); + // Block moving/renaming files matching this pattern + rules.push(`(deny file-write-unlink`, ` (regex ${escapePath(regexPattern)})`, ` (with message "${logTag}"))`); + // For glob patterns, extract the static prefix and block ancestor moves + // Remove glob characters to get the directory prefix + const staticPrefix = normalizedPath.split(/[*?[\]]/)[0]; + if (staticPrefix && staticPrefix !== '/') { + // Get the directory containing the glob pattern + const baseDir = staticPrefix.endsWith('/') + ? staticPrefix.slice(0, -1) + : path.dirname(staticPrefix); + // Block moves of the base directory itself + rules.push(`(deny file-write-unlink`, ` (literal ${escapePath(baseDir)})`, ` (with message "${logTag}"))`); + // Block moves of ancestor directories + for (const ancestorDir of getAncestorDirectories(baseDir)) { + rules.push(`(deny file-write-unlink`, ` (literal ${escapePath(ancestorDir)})`, ` (with message "${logTag}"))`); + } + } + } + else { + // Use subpath matching for literal paths + // Block moving/renaming the denied path itself + rules.push(`(deny file-write-unlink`, ` (subpath ${escapePath(normalizedPath)})`, ` (with message "${logTag}"))`); + // Block moves of ancestor directories + for (const ancestorDir of getAncestorDirectories(normalizedPath)) { + rules.push(`(deny file-write-unlink`, ` (literal ${escapePath(ancestorDir)})`, ` (with message "${logTag}"))`); + } + } + } + return rules; +} +/** + * Generate filesystem read rules for sandbox profile + * + * Supports two layers: + * 1. denyOnly: deny reads from these paths (broad regions like /Users) + * 2. allowWithinDeny: re-allow reads within denied regions (like CWD) + * allowWithinDeny takes precedence over denyOnly. + * + * In Seatbelt profiles, later rules take precedence, so we emit: + * (allow file-read*) ← default: allow everything + * (deny file-read* ...) ← deny broad regions + * (allow file-read* ...) ← re-allow specific paths within denied regions + */ +function generateReadRules(config, logTag) { + if (!config) { + return [`(allow file-read*)`]; + } + const rules = []; + // Start by allowing everything + rules.push(`(allow file-read*)`); + // Then deny specific paths + for (const pathPattern of config.denyOnly || []) { + const normalizedPath = normalizePathForSandbox(pathPattern); + if (containsGlobChars(normalizedPath)) { + // Use regex matching for glob patterns + const regexPattern = globToRegex(normalizedPath); + rules.push(`(deny file-read*`, ` (regex ${escapePath(regexPattern)})`, ` (with message "${logTag}"))`); + } + else { + // Use subpath matching for literal paths + rules.push(`(deny file-read*`, ` (subpath ${escapePath(normalizedPath)})`, ` (with message "${logTag}"))`); + } + } + // Re-allow specific paths within denied regions (allowWithinDeny takes precedence) + for (const pathPattern of config.allowWithinDeny || []) { + const normalizedPath = normalizePathForSandbox(pathPattern); + if (containsGlobChars(normalizedPath)) { + const regexPattern = globToRegex(normalizedPath); + rules.push(`(allow file-read*`, ` (regex ${escapePath(regexPattern)})`, ` (with message "${logTag}"))`); + } + else { + rules.push(`(allow file-read*`, ` (subpath ${escapePath(normalizedPath)})`, ` (with message "${logTag}"))`); + } + } + // Allow stat/lstat on all directories so that realpath() can traverse + // path components within denied regions. Without this, C realpath() fails + // when resolving symlinks because it needs to lstat every intermediate + // directory (e.g. /Users, /Users/chris) even if only a subdirectory like + // ~/.local is in allowWithinDeny. This only allows metadata reads on + // directories — not listing contents (readdir) or reading files. + if ((config.denyOnly).length > 0) { + rules.push(`(allow file-read-metadata`, ` (vnode-type DIRECTORY))`); + } + // Block file movement to prevent bypass via mv/rename + rules.push(...generateMoveBlockingRules(config.denyOnly || [], logTag)); + return rules; +} +/** + * Generate filesystem write rules for sandbox profile + */ +function generateWriteRules(config, logTag, allowGitConfig = false) { + if (!config) { + return [`(allow file-write*)`]; + } + const rules = []; + // Automatically allow TMPDIR parent on macOS when write restrictions are enabled + const tmpdirParents = getTmpdirParentIfMacOSPattern(); + for (const tmpdirParent of tmpdirParents) { + const normalizedPath = normalizePathForSandbox(tmpdirParent); + rules.push(`(allow file-write*`, ` (subpath ${escapePath(normalizedPath)})`, ` (with message "${logTag}"))`); + } + // Generate allow rules + for (const pathPattern of config.allowOnly || []) { + const normalizedPath = normalizePathForSandbox(pathPattern); + if (containsGlobChars(normalizedPath)) { + // Use regex matching for glob patterns + const regexPattern = globToRegex(normalizedPath); + rules.push(`(allow file-write*`, ` (regex ${escapePath(regexPattern)})`, ` (with message "${logTag}"))`); + } + else { + // Use subpath matching for literal paths + rules.push(`(allow file-write*`, ` (subpath ${escapePath(normalizedPath)})`, ` (with message "${logTag}"))`); + } + } + // Combine user-specified and mandatory deny patterns (no ripgrep needed on macOS) + const denyPaths = [ + ...(config.denyWithinAllow || []), + ...macGetMandatoryDenyPatterns(allowGitConfig), + ]; + for (const pathPattern of denyPaths) { + const normalizedPath = normalizePathForSandbox(pathPattern); + if (containsGlobChars(normalizedPath)) { + // Use regex matching for glob patterns + const regexPattern = globToRegex(normalizedPath); + rules.push(`(deny file-write*`, ` (regex ${escapePath(regexPattern)})`, ` (with message "${logTag}"))`); + } + else { + // Use subpath matching for literal paths + rules.push(`(deny file-write*`, ` (subpath ${escapePath(normalizedPath)})`, ` (with message "${logTag}"))`); + } + } + // Block file movement to prevent bypass via mv/rename + rules.push(...generateMoveBlockingRules(denyPaths, logTag)); + return rules; +} +/** + * Generate complete sandbox profile + */ +function generateSandboxProfile({ readConfig, writeConfig, httpProxyPort, socksProxyPort, needsNetworkRestriction, allowUnixSockets, allowAllUnixSockets, allowLocalBinding, allowPty, allowGitConfig = false, enableWeakerNetworkIsolation = false, logTag, }) { + const profile = [ + '(version 1)', + `(deny default (with message "${logTag}"))`, + '', + `; LogTag: ${logTag}`, + '', + '; Essential permissions - based on Chrome sandbox policy', + '; Process permissions', + '(allow process-exec)', + '(allow process-fork)', + '(allow process-info* (target same-sandbox))', + '(allow signal (target same-sandbox))', + '(allow mach-priv-task-port (target same-sandbox))', + '', + '; User preferences', + '(allow user-preference-read)', + '', + '; Mach IPC - specific services only (no wildcard)', + '(allow mach-lookup', + ' (global-name "com.apple.audio.systemsoundserver")', + ' (global-name "com.apple.distributed_notifications@Uv3")', + ' (global-name "com.apple.FontObjectsServer")', + ' (global-name "com.apple.fonts")', + ' (global-name "com.apple.logd")', + ' (global-name "com.apple.lsd.mapdb")', + ' (global-name "com.apple.PowerManagement.control")', + ' (global-name "com.apple.system.logger")', + ' (global-name "com.apple.system.notification_center")', + ' (global-name "com.apple.system.opendirectoryd.libinfo")', + ' (global-name "com.apple.system.opendirectoryd.membership")', + ' (global-name "com.apple.bsd.dirhelper")', + ' (global-name "com.apple.securityd.xpc")', + ' (global-name "com.apple.coreservices.launchservicesd")', + ')', + '', + ...(enableWeakerNetworkIsolation + ? [ + '; trustd.agent - needed for Go TLS certificate verification (weaker network isolation)', + '(allow mach-lookup (global-name "com.apple.trustd.agent"))', + ] + : []), + '', + '; POSIX IPC - shared memory', + '(allow ipc-posix-shm)', + '', + '; POSIX IPC - semaphores for Python multiprocessing', + '(allow ipc-posix-sem)', + '', + '; IOKit - specific operations only', + '(allow iokit-open', + ' (iokit-registry-entry-class "IOSurfaceRootUserClient")', + ' (iokit-registry-entry-class "RootDomainUserClient")', + ' (iokit-user-client-class "IOSurfaceSendRight")', + ')', + '', + '; IOKit properties', + '(allow iokit-get-properties)', + '', + "; Specific safe system-sockets, doesn't allow network access", + '(allow system-socket (require-all (socket-domain AF_SYSTEM) (socket-protocol 2)))', + '', + '; sysctl - specific sysctls only', + '(allow sysctl-read', + ' (sysctl-name "hw.activecpu")', + ' (sysctl-name "hw.busfrequency_compat")', + ' (sysctl-name "hw.byteorder")', + ' (sysctl-name "hw.cacheconfig")', + ' (sysctl-name "hw.cachelinesize_compat")', + ' (sysctl-name "hw.cpufamily")', + ' (sysctl-name "hw.cpufrequency")', + ' (sysctl-name "hw.cpufrequency_compat")', + ' (sysctl-name "hw.cputype")', + ' (sysctl-name "hw.l1dcachesize_compat")', + ' (sysctl-name "hw.l1icachesize_compat")', + ' (sysctl-name "hw.l2cachesize_compat")', + ' (sysctl-name "hw.l3cachesize_compat")', + ' (sysctl-name "hw.logicalcpu")', + ' (sysctl-name "hw.logicalcpu_max")', + ' (sysctl-name "hw.machine")', + ' (sysctl-name "hw.memsize")', + ' (sysctl-name "hw.ncpu")', + ' (sysctl-name "hw.nperflevels")', + ' (sysctl-name "hw.packages")', + ' (sysctl-name "hw.pagesize_compat")', + ' (sysctl-name "hw.pagesize")', + ' (sysctl-name "hw.physicalcpu")', + ' (sysctl-name "hw.physicalcpu_max")', + ' (sysctl-name "hw.tbfrequency_compat")', + ' (sysctl-name "hw.vectorunit")', + ' (sysctl-name "kern.argmax")', + ' (sysctl-name "kern.bootargs")', + ' (sysctl-name "kern.hostname")', + ' (sysctl-name "kern.maxfiles")', + ' (sysctl-name "kern.maxfilesperproc")', + ' (sysctl-name "kern.maxproc")', + ' (sysctl-name "kern.ngroups")', + ' (sysctl-name "kern.osproductversion")', + ' (sysctl-name "kern.osrelease")', + ' (sysctl-name "kern.ostype")', + ' (sysctl-name "kern.osvariant_status")', + ' (sysctl-name "kern.osversion")', + ' (sysctl-name "kern.secure_kernel")', + ' (sysctl-name "kern.tcsm_available")', + ' (sysctl-name "kern.tcsm_enable")', + ' (sysctl-name "kern.usrstack64")', + ' (sysctl-name "kern.version")', + ' (sysctl-name "kern.willshutdown")', + ' (sysctl-name "machdep.cpu.brand_string")', + ' (sysctl-name "machdep.ptrauth_enabled")', + ' (sysctl-name "security.mac.lockdown_mode_state")', + ' (sysctl-name "sysctl.proc_cputype")', + ' (sysctl-name "vm.loadavg")', + ' (sysctl-name-prefix "hw.optional.arm")', + ' (sysctl-name-prefix "hw.optional.arm.")', + ' (sysctl-name-prefix "hw.optional.armv8_")', + ' (sysctl-name-prefix "hw.perflevel")', + ' (sysctl-name-prefix "kern.proc.all")', + ' (sysctl-name-prefix "kern.proc.pgrp.")', + ' (sysctl-name-prefix "kern.proc.pid.")', + ' (sysctl-name-prefix "machdep.cpu.")', + ' (sysctl-name-prefix "net.routetable.")', + ')', + '', + '; V8 thread calculations', + '(allow sysctl-write', + ' (sysctl-name "kern.tcsm_enable")', + ')', + '', + '; Distributed notifications', + '(allow distributed-notification-post)', + '', + '; Specific mach-lookup permissions for security operations', + '(allow mach-lookup (global-name "com.apple.SecurityServer"))', + '', + '; File I/O on device files', + '(allow file-ioctl (literal "/dev/null"))', + '(allow file-ioctl (literal "/dev/zero"))', + '(allow file-ioctl (literal "/dev/random"))', + '(allow file-ioctl (literal "/dev/urandom"))', + '(allow file-ioctl (literal "/dev/dtracehelper"))', + '(allow file-ioctl (literal "/dev/tty"))', + '', + '(allow file-ioctl file-read-data file-write-data', + ' (require-all', + ' (literal "/dev/null")', + ' (vnode-type CHARACTER-DEVICE)', + ' )', + ')', + '', + ]; + // Network rules + profile.push('; Network'); + if (!needsNetworkRestriction) { + profile.push('(allow network*)'); + } + else { + // Allow local binding if requested + // Use "*:*" instead of "localhost:*" because modern runtimes (Java, etc.) create + // IPv6 dual-stack sockets by default. When binding such a socket to 127.0.0.1, + // the kernel represents it as ::ffff:127.0.0.1 (IPv4-mapped IPv6). Seatbelt's + // "localhost" filter only matches 127.0.0.1 and ::1, NOT ::ffff:127.0.0.1. + // Using (local ip "*:*") is safe because it only matches the LOCAL endpoint — + // internet-bound connections originate from non-loopback interfaces, so they + // remain blocked by (deny default). + if (allowLocalBinding) { + profile.push('(allow network-bind (local ip "*:*"))'); + profile.push('(allow network-inbound (local ip "*:*"))'); + profile.push('(allow network-outbound (local ip "*:*"))'); + } + // Unix domain sockets for local IPC (SSH agent, Docker, Gradle, etc.) + // Three separate operations must be allowed: + // 1. system-socket: socket(AF_UNIX, ...) syscall — creates the socket fd (no path context) + // 2. network-bind: bind() to a local Unix socket path + // 3. network-outbound: connect() to a remote Unix socket path + // Note: (subpath ...) and (path-regex ...) are path-based filters that can only match + // bind/connect operations — socket() creation has no path, so it requires system-socket. + if (allowAllUnixSockets) { + // Allow creating AF_UNIX sockets and all Unix socket paths + profile.push('(allow system-socket (socket-domain AF_UNIX))'); + profile.push('(allow network-bind (local unix-socket (path-regex #"^/")))'); + profile.push('(allow network-outbound (remote unix-socket (path-regex #"^/")))'); + } + else if (allowUnixSockets && allowUnixSockets.length > 0) { + // Allow creating AF_UNIX sockets (required for any Unix socket use) + profile.push('(allow system-socket (socket-domain AF_UNIX))'); + // Allow specific Unix socket paths + for (const socketPath of allowUnixSockets) { + const normalizedPath = normalizePathForSandbox(socketPath); + profile.push(`(allow network-bind (local unix-socket (subpath ${escapePath(normalizedPath)})))`); + profile.push(`(allow network-outbound (remote unix-socket (subpath ${escapePath(normalizedPath)})))`); + } + } + // If both allowAllUnixSockets and allowUnixSockets are false/undefined/empty, Unix sockets are blocked by default + // Allow localhost TCP operations for the HTTP proxy + if (httpProxyPort !== undefined) { + profile.push(`(allow network-bind (local ip "localhost:${httpProxyPort}"))`); + profile.push(`(allow network-inbound (local ip "localhost:${httpProxyPort}"))`); + profile.push(`(allow network-outbound (remote ip "localhost:${httpProxyPort}"))`); + } + // Allow localhost TCP operations for the SOCKS proxy + if (socksProxyPort !== undefined) { + profile.push(`(allow network-bind (local ip "localhost:${socksProxyPort}"))`); + profile.push(`(allow network-inbound (local ip "localhost:${socksProxyPort}"))`); + profile.push(`(allow network-outbound (remote ip "localhost:${socksProxyPort}"))`); + } + } + profile.push(''); + // Read rules + profile.push('; File read'); + profile.push(...generateReadRules(readConfig, logTag)); + profile.push(''); + // Write rules + profile.push('; File write'); + profile.push(...generateWriteRules(writeConfig, logTag, allowGitConfig)); + // Pseudo-terminal (pty) support + if (allowPty) { + profile.push(''); + profile.push('; Pseudo-terminal (pty) support'); + profile.push('(allow pseudo-tty)'); + profile.push('(allow file-ioctl'); + profile.push(' (literal "/dev/ptmx")'); + profile.push(' (regex #"^/dev/ttys")'); + profile.push(')'); + profile.push('(allow file-read* file-write*'); + profile.push(' (literal "/dev/ptmx")'); + profile.push(' (regex #"^/dev/ttys")'); + profile.push(')'); + } + return profile.join('\n'); +} +/** + * Escape path for sandbox profile using JSON.stringify for proper escaping + */ +function escapePath(pathStr) { + return JSON.stringify(pathStr); +} +/** + * Get TMPDIR parent directory if it matches macOS pattern /var/folders/XX/YYY/T/ + * Returns both /var/ and /private/var/ versions since /var is a symlink + */ +function getTmpdirParentIfMacOSPattern() { + const tmpdir = process.env.TMPDIR; + if (!tmpdir) + return []; + const match = tmpdir.match(/^\/(private\/)?var\/folders\/[^/]{2}\/[^/]+\/T\/?$/); + if (!match) + return []; + const parent = tmpdir.replace(/\/T\/?$/, ''); + // Return both /var/ and /private/var/ versions since /var is a symlink + if (parent.startsWith('/private/var/')) { + return [parent, parent.replace('/private', '')]; + } + else if (parent.startsWith('/var/')) { + return [parent, '/private' + parent]; + } + return [parent]; +} +/** + * Wrap command with macOS sandbox + */ +export function wrapCommandWithSandboxMacOS(params) { + const { command, needsNetworkRestriction, httpProxyPort, socksProxyPort, allowUnixSockets, allowAllUnixSockets, allowLocalBinding, readConfig, writeConfig, allowPty, allowGitConfig = false, enableWeakerNetworkIsolation = false, binShell, } = params; + // Determine if we have restrictions to apply + // Read: denyOnly pattern - empty array means no restrictions + // Write: allowOnly pattern - undefined means no restrictions, any config means restrictions + const hasReadRestrictions = readConfig && readConfig.denyOnly.length > 0; + const hasWriteRestrictions = writeConfig !== undefined; + // No sandboxing needed + if (!needsNetworkRestriction && + !hasReadRestrictions && + !hasWriteRestrictions) { + return command; + } + const logTag = generateLogTag(command); + const profile = generateSandboxProfile({ + readConfig, + writeConfig, + httpProxyPort, + socksProxyPort, + needsNetworkRestriction, + allowUnixSockets, + allowAllUnixSockets, + allowLocalBinding, + allowPty, + allowGitConfig, + enableWeakerNetworkIsolation, + logTag, + }); + // Generate proxy environment variables using shared utility + const proxyEnvArgs = generateProxyEnvVars(httpProxyPort, socksProxyPort); + // Use the user's shell (zsh, bash, etc.) to ensure aliases/snapshots work + // Resolve the full path to the shell binary + const shellName = binShell || 'bash'; + const shell = whichSync(shellName); + if (!shell) { + throw new Error(`Shell '${shellName}' not found in PATH`); + } + // Use `env` command to set environment variables - each VAR=value is a separate + // argument that shellquote handles properly, avoiding shell quoting issues + const wrappedCommand = shellquote.quote([ + 'env', + ...proxyEnvArgs, + 'sandbox-exec', + '-p', + profile, + shell, + '-c', + command, + ]); + logForDebugging(`[Sandbox macOS] Applied restrictions - network: ${!!(httpProxyPort || socksProxyPort)}, read: ${readConfig + ? 'allowAllExcept' in readConfig + ? 'allowAllExcept' + : 'denyAllExcept' + : 'none'}, write: ${writeConfig + ? 'allowAllExcept' in writeConfig + ? 'allowAllExcept' + : 'denyAllExcept' + : 'none'}`); + return wrappedCommand; +} +/** + * Start monitoring macOS system logs for sandbox violations + * Look for sandbox-related kernel deny events ending in {logTag} + */ +export function startMacOSSandboxLogMonitor(callback, ignoreViolations) { + // Pre-compile regex patterns for better performance + const cmdExtractRegex = /CMD64_(.+?)_END/; + const sandboxExtractRegex = /Sandbox:\s+(.+)$/; + // Pre-process ignore patterns for faster lookup + const wildcardPaths = ignoreViolations?.['*'] || []; + const commandPatterns = ignoreViolations + ? Object.entries(ignoreViolations).filter(([pattern]) => pattern !== '*') + : []; + // Stream and filter kernel logs for all sandbox violations + // We can't filter by specific logTag since it's dynamic per command + const logProcess = spawn('log', [ + 'stream', + '--predicate', + `(eventMessage ENDSWITH "${sessionSuffix}")`, + '--style', + 'compact', + ]); + logProcess.stdout?.on('data', (data) => { + const lines = data.toString().split('\n'); + // Get violation and command lines + const violationLine = lines.find(line => line.includes('Sandbox:') && line.includes('deny')); + const commandLine = lines.find(line => line.startsWith('CMD64_')); + if (!violationLine) + return; + // Extract violation details + const sandboxMatch = violationLine.match(sandboxExtractRegex); + if (!sandboxMatch?.[1]) + return; + const violationDetails = sandboxMatch[1]; + // Try to get command + let command; + let encodedCommand; + if (commandLine) { + const cmdMatch = commandLine.match(cmdExtractRegex); + encodedCommand = cmdMatch?.[1]; + if (encodedCommand) { + try { + command = decodeSandboxedCommand(encodedCommand); + } + catch { + // Failed to decode, continue without command + } + } + } + // Always filter out noisey violations + if (violationDetails.includes('mDNSResponder') || + violationDetails.includes('mach-lookup com.apple.diagnosticd') || + violationDetails.includes('mach-lookup com.apple.analyticsd')) { + return; + } + // Check if we should ignore this violation + if (ignoreViolations && command) { + // Check wildcard patterns first + if (wildcardPaths.length > 0) { + const shouldIgnore = wildcardPaths.some(path => violationDetails.includes(path)); + if (shouldIgnore) + return; + } + // Check command-specific patterns + for (const [pattern, paths] of commandPatterns) { + if (command.includes(pattern)) { + const shouldIgnore = paths.some(path => violationDetails.includes(path)); + if (shouldIgnore) + return; + } + } + } + // Not ignored - report the violation + callback({ + line: violationDetails, + command, + encodedCommand, + timestamp: new Date(), // We could parse the timestamp from the log but this feels more reliable + }); + }); + logProcess.stderr?.on('data', (data) => { + logForDebugging(`[Sandbox Monitor] Log stream stderr: ${data.toString()}`); + }); + logProcess.on('error', (error) => { + logForDebugging(`[Sandbox Monitor] Failed to start log stream: ${error.message}`); + }); + logProcess.on('exit', (code) => { + logForDebugging(`[Sandbox Monitor] Log stream exited with code: ${code}`); + }); + return () => { + logForDebugging('[Sandbox Monitor] Stopping log monitor'); + logProcess.kill('SIGTERM'); + }; +} +//# sourceMappingURL=macos-sandbox-utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/sandbox-config.js b/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/sandbox-config.js new file mode 100644 index 00000000..f61e67d5 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/sandbox-config.js @@ -0,0 +1,180 @@ +/** + * Configuration for Sandbox Runtime + * This is the main configuration interface that consumers pass to SandboxManager.initialize() + */ +import { z } from 'zod'; +/** + * Schema for domain patterns (e.g., "example.com", "*.npmjs.org") + * Validates that domain patterns are safe and don't include overly broad wildcards + */ +const domainPatternSchema = z.string().refine(val => { + // Reject protocols, paths, ports, etc. + if (val.includes('://') || val.includes('/') || val.includes(':')) { + return false; + } + // Allow localhost + if (val === 'localhost') + return true; + // Allow wildcard domains like *.example.com + if (val.startsWith('*.')) { + const domain = val.slice(2); + // After the *. there must be a valid domain with at least one more dot + // e.g., *.example.com is valid, *.com is not (too broad) + if (!domain.includes('.') || + domain.startsWith('.') || + domain.endsWith('.')) { + return false; + } + // Count dots - must have at least 2 parts after the wildcard (e.g., example.com) + const parts = domain.split('.'); + return parts.length >= 2 && parts.every(p => p.length > 0); + } + // Reject any other use of wildcards (e.g., *, *., etc.) + if (val.includes('*')) { + return false; + } + // Regular domains must have at least one dot and only valid characters + return val.includes('.') && !val.startsWith('.') && !val.endsWith('.'); +}, { + message: 'Invalid domain pattern. Must be a valid domain (e.g., "example.com") or wildcard (e.g., "*.example.com"). Overly broad patterns like "*.com" or "*" are not allowed for security reasons.', +}); +/** + * Schema for filesystem paths + */ +const filesystemPathSchema = z.string().min(1, 'Path cannot be empty'); +/** + * Schema for MITM proxy configuration + * Allows routing specific domains through an upstream MITM proxy via Unix socket + */ +const MitmProxyConfigSchema = z.object({ + socketPath: z.string().min(1).describe('Unix socket path to the MITM proxy'), + domains: z + .array(domainPatternSchema) + .min(1) + .describe('Domains to route through the MITM proxy (e.g., ["api.example.com", "*.internal.org"])'), +}); +/** + * Network configuration schema for validation + */ +export const NetworkConfigSchema = z.object({ + allowedDomains: z + .array(domainPatternSchema) + .describe('List of allowed domains (e.g., ["github.com", "*.npmjs.org"])'), + deniedDomains: z + .array(domainPatternSchema) + .describe('List of denied domains'), + allowUnixSockets: z + .array(z.string()) + .optional() + .describe('macOS only: Unix socket paths to allow. Ignored on Linux (seccomp cannot filter by path).'), + allowAllUnixSockets: z + .boolean() + .optional() + .describe('If true, allow all Unix sockets (disables blocking on both platforms).'), + allowLocalBinding: z + .boolean() + .optional() + .describe('Whether to allow binding to local ports (default: false)'), + httpProxyPort: z + .number() + .int() + .min(1) + .max(65535) + .optional() + .describe('Port of an external HTTP proxy to use instead of starting a local one. When provided, the library will skip starting its own HTTP proxy and use this port. The external proxy must handle domain filtering.'), + socksProxyPort: z + .number() + .int() + .min(1) + .max(65535) + .optional() + .describe('Port of an external SOCKS proxy to use instead of starting a local one. When provided, the library will skip starting its own SOCKS proxy and use this port. The external proxy must handle domain filtering.'), + mitmProxy: MitmProxyConfigSchema.optional().describe('Optional MITM proxy configuration. Routes matching domains through an upstream proxy via Unix socket while SRT still handles allow/deny filtering.'), +}); +/** + * Filesystem configuration schema for validation + */ +export const FilesystemConfigSchema = z.object({ + denyRead: z.array(filesystemPathSchema).describe('Paths denied for reading'), + allowRead: z + .array(filesystemPathSchema) + .optional() + .describe('Paths to re-allow reading within denied regions (takes precedence over denyRead). ' + + 'Use with denyRead to deny a broad region then allow back specific subdirectories.'), + allowWrite: z + .array(filesystemPathSchema) + .describe('Paths allowed for writing'), + denyWrite: z + .array(filesystemPathSchema) + .describe('Paths denied for writing (takes precedence over allowWrite)'), + allowGitConfig: z + .boolean() + .optional() + .describe('Allow writes to .git/config files (default: false). Enables git remote URL updates while keeping .git/hooks protected.'), +}); +/** + * Configuration schema for ignoring specific sandbox violations + * Maps command patterns to filesystem paths to ignore violations for. + */ +export const IgnoreViolationsConfigSchema = z + .record(z.string(), z.array(z.string())) + .describe('Map of command patterns to filesystem paths to ignore violations for. Use "*" to match all commands'); +/** + * Ripgrep configuration schema + */ +export const RipgrepConfigSchema = z.object({ + command: z.string().describe('The ripgrep command to execute'), + args: z + .array(z.string()) + .optional() + .describe('Additional arguments to pass before ripgrep args'), + argv0: z + .string() + .optional() + .describe('Override argv[0] when spawning (for multicall binaries that dispatch on argv[0])'), +}); +/** + * Seccomp configuration schema (Linux only) + * Allows specifying custom paths to seccomp binaries + */ +export const SeccompConfigSchema = z.object({ + bpfPath: z + .string() + .optional() + .describe('Path to the unix-block.bpf filter file'), + applyPath: z.string().optional().describe('Path to the apply-seccomp binary'), +}); +/** + * Main configuration schema for Sandbox Runtime validation + */ +export const SandboxRuntimeConfigSchema = z.object({ + network: NetworkConfigSchema.describe('Network restrictions configuration'), + filesystem: FilesystemConfigSchema.describe('Filesystem restrictions configuration'), + ignoreViolations: IgnoreViolationsConfigSchema.optional().describe('Optional configuration for ignoring specific violations'), + enableWeakerNestedSandbox: z + .boolean() + .optional() + .describe('Enable weaker nested sandbox mode (for Docker environments)'), + enableWeakerNetworkIsolation: z + .boolean() + .optional() + .describe('Enable weaker network isolation to allow access to com.apple.trustd.agent (macOS only). ' + + 'This is needed for Go programs (gh, gcloud, terraform, kubectl, etc.) to verify TLS certificates ' + + 'when using httpProxyPort with a MITM proxy and custom CA. Enabling this opens a potential data ' + + 'exfiltration vector through the trustd service. Only enable if you need Go TLS verification.'), + ripgrep: RipgrepConfigSchema.optional().describe('Custom ripgrep configuration (default: { command: "rg" })'), + mandatoryDenySearchDepth: z + .number() + .int() + .min(1) + .max(10) + .optional() + .describe('Maximum directory depth to search for dangerous files on Linux (default: 3). ' + + 'Higher values provide more protection but slower performance.'), + allowPty: z + .boolean() + .optional() + .describe('Allow pseudo-terminal (pty) operations (macOS only)'), + seccomp: SeccompConfigSchema.optional().describe('Custom seccomp binary paths (Linux only).'), +}); +//# sourceMappingURL=sandbox-config.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/sandbox-manager.js b/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/sandbox-manager.js new file mode 100644 index 00000000..604a318d --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/sandbox-manager.js @@ -0,0 +1,786 @@ +import { createHttpProxyServer } from './http-proxy.js'; +import { createSocksProxyServer } from './socks-proxy.js'; +import { logForDebugging } from '../utils/debug.js'; +import { whichSync } from '../utils/which.js'; +import { cloneDeep } from 'lodash-es'; +import { getPlatform, getWslVersion } from '../utils/platform.js'; +import * as fs from 'fs'; +import { wrapCommandWithSandboxLinux, initializeLinuxNetworkBridge, checkLinuxDependencies, cleanupBwrapMountPoints, } from './linux-sandbox-utils.js'; +import { wrapCommandWithSandboxMacOS, startMacOSSandboxLogMonitor, } from './macos-sandbox-utils.js'; +import { getDefaultWritePaths, containsGlobChars, removeTrailingGlobSuffix, expandGlobPattern, } from './sandbox-utils.js'; +import { SandboxViolationStore } from './sandbox-violation-store.js'; +import { EOL } from 'node:os'; +// ============================================================================ +// Private Module State +// ============================================================================ +let config; +let httpProxyServer; +let socksProxyServer; +let managerContext; +let initializationPromise; +let cleanupRegistered = false; +let logMonitorShutdown; +const sandboxViolationStore = new SandboxViolationStore(); +// ============================================================================ +// Private Helper Functions (not exported) +// ============================================================================ +function registerCleanup() { + if (cleanupRegistered) { + return; + } + const cleanupHandler = () => reset().catch(e => { + logForDebugging(`Cleanup failed in registerCleanup ${e}`, { + level: 'error', + }); + }); + process.once('exit', cleanupHandler); + process.once('SIGINT', cleanupHandler); + process.once('SIGTERM', cleanupHandler); + cleanupRegistered = true; +} +function matchesDomainPattern(hostname, pattern) { + // Support wildcard patterns like *.example.com + // This matches any subdomain but not the base domain itself + if (pattern.startsWith('*.')) { + const baseDomain = pattern.substring(2); // Remove '*.' + return hostname.toLowerCase().endsWith('.' + baseDomain.toLowerCase()); + } + // Exact match for non-wildcard patterns + return hostname.toLowerCase() === pattern.toLowerCase(); +} +async function filterNetworkRequest(port, host, sandboxAskCallback) { + if (!config) { + logForDebugging('No config available, denying network request'); + return false; + } + // Check denied domains first + for (const deniedDomain of config.network.deniedDomains) { + if (matchesDomainPattern(host, deniedDomain)) { + logForDebugging(`Denied by config rule: ${host}:${port}`); + return false; + } + } + // Check allowed domains + for (const allowedDomain of config.network.allowedDomains) { + if (matchesDomainPattern(host, allowedDomain)) { + logForDebugging(`Allowed by config rule: ${host}:${port}`); + return true; + } + } + // No matching rules - ask user or deny + if (!sandboxAskCallback) { + logForDebugging(`No matching config rule, denying: ${host}:${port}`); + return false; + } + logForDebugging(`No matching config rule, asking user: ${host}:${port}`); + try { + const userAllowed = await sandboxAskCallback({ host, port }); + if (userAllowed) { + logForDebugging(`User allowed: ${host}:${port}`); + return true; + } + else { + logForDebugging(`User denied: ${host}:${port}`); + return false; + } + } + catch (error) { + logForDebugging(`Error in permission callback: ${error}`, { + level: 'error', + }); + return false; + } +} +/** + * Get the MITM proxy socket path for a given host, if configured. + * Returns the socket path if the host matches any MITM domain pattern, + * otherwise returns undefined. + */ +function getMitmSocketPath(host) { + if (!config?.network.mitmProxy) { + return undefined; + } + const { socketPath, domains } = config.network.mitmProxy; + for (const pattern of domains) { + if (matchesDomainPattern(host, pattern)) { + logForDebugging(`Host ${host} matches MITM pattern ${pattern}`); + return socketPath; + } + } + return undefined; +} +async function startHttpProxyServer(sandboxAskCallback) { + httpProxyServer = createHttpProxyServer({ + filter: (port, host) => filterNetworkRequest(port, host, sandboxAskCallback), + getMitmSocketPath, + }); + return new Promise((resolve, reject) => { + if (!httpProxyServer) { + reject(new Error('HTTP proxy server undefined before listen')); + return; + } + const server = httpProxyServer; + server.once('error', reject); + server.once('listening', () => { + const address = server.address(); + if (address && typeof address === 'object') { + server.unref(); + logForDebugging(`HTTP proxy listening on localhost:${address.port}`); + resolve(address.port); + } + else { + reject(new Error('Failed to get proxy server address')); + } + }); + server.listen(0, '127.0.0.1'); + }); +} +async function startSocksProxyServer(sandboxAskCallback) { + socksProxyServer = createSocksProxyServer({ + filter: (port, host) => filterNetworkRequest(port, host, sandboxAskCallback), + }); + return new Promise((resolve, reject) => { + if (!socksProxyServer) { + // This is mostly just for the typechecker + reject(new Error('SOCKS proxy server undefined before listen')); + return; + } + socksProxyServer + .listen(0, '127.0.0.1') + .then((port) => { + socksProxyServer?.unref(); + resolve(port); + }) + .catch(reject); + }); +} +// ============================================================================ +// Public Module Functions (will be exported via namespace) +// ============================================================================ +async function initialize(runtimeConfig, sandboxAskCallback, enableLogMonitor = false) { + // Return if already initializing + if (initializationPromise) { + await initializationPromise; + return; + } + // Store config for use by other functions + config = runtimeConfig; + // Check dependencies + const deps = checkDependencies(); + if (deps.errors.length > 0) { + throw new Error(`Sandbox dependencies not available: ${deps.errors.join(', ')}`); + } + // Start log monitor for macOS if enabled + if (enableLogMonitor && getPlatform() === 'macos') { + logMonitorShutdown = startMacOSSandboxLogMonitor(sandboxViolationStore.addViolation.bind(sandboxViolationStore), config.ignoreViolations); + logForDebugging('Started macOS sandbox log monitor'); + } + // Register cleanup handlers first time + registerCleanup(); + // Initialize network infrastructure + initializationPromise = (async () => { + try { + // Conditionally start proxy servers based on config + let httpProxyPort; + if (config.network.httpProxyPort !== undefined) { + // Use external HTTP proxy (don't start a server) + httpProxyPort = config.network.httpProxyPort; + logForDebugging(`Using external HTTP proxy on port ${httpProxyPort}`); + } + else { + // Start local HTTP proxy + httpProxyPort = await startHttpProxyServer(sandboxAskCallback); + } + let socksProxyPort; + if (config.network.socksProxyPort !== undefined) { + // Use external SOCKS proxy (don't start a server) + socksProxyPort = config.network.socksProxyPort; + logForDebugging(`Using external SOCKS proxy on port ${socksProxyPort}`); + } + else { + // Start local SOCKS proxy + socksProxyPort = await startSocksProxyServer(sandboxAskCallback); + } + // Initialize platform-specific infrastructure + let linuxBridge; + if (getPlatform() === 'linux') { + linuxBridge = await initializeLinuxNetworkBridge(httpProxyPort, socksProxyPort); + } + const context = { + httpProxyPort, + socksProxyPort, + linuxBridge, + }; + managerContext = context; + logForDebugging('Network infrastructure initialized'); + return context; + } + catch (error) { + // Clear state on error so initialization can be retried + initializationPromise = undefined; + managerContext = undefined; + reset().catch(e => { + logForDebugging(`Cleanup failed in initializationPromise ${e}`, { + level: 'error', + }); + }); + throw error; + } + })(); + await initializationPromise; +} +function isSupportedPlatform() { + const platform = getPlatform(); + if (platform === 'linux') { + // WSL1 doesn't support bubblewrap + return getWslVersion() !== '1'; + } + return platform === 'macos'; +} +function isSandboxingEnabled() { + // Sandboxing is enabled if config has been set (via initialize()) + return config !== undefined; +} +/** + * Check sandbox dependencies for the current platform + * @param ripgrepConfig - Ripgrep command to check. If not provided, uses config from initialization or defaults to 'rg' + * @returns { warnings, errors } - errors mean sandbox cannot run, warnings mean degraded functionality + */ +function checkDependencies(ripgrepConfig) { + if (!isSupportedPlatform()) { + return { errors: ['Unsupported platform'], warnings: [] }; + } + const errors = []; + const warnings = []; + // Check ripgrep - use provided config, then initialized config, then default 'rg' + const rgToCheck = ripgrepConfig ?? config?.ripgrep ?? { command: 'rg' }; + if (whichSync(rgToCheck.command) === null) { + errors.push(`ripgrep (${rgToCheck.command}) not found`); + } + const platform = getPlatform(); + if (platform === 'linux') { + const linuxDeps = checkLinuxDependencies(config?.seccomp); + errors.push(...linuxDeps.errors); + warnings.push(...linuxDeps.warnings); + } + return { errors, warnings }; +} +function getFsReadConfig() { + if (!config) { + return { denyOnly: [], allowWithinDeny: [] }; + } + const denyPaths = []; + for (const p of config.filesystem.denyRead) { + const stripped = removeTrailingGlobSuffix(p); + if (getPlatform() === 'linux' && containsGlobChars(stripped)) { + // Expand glob to concrete paths on Linux (bubblewrap doesn't support globs) + const expanded = expandGlobPattern(p); + logForDebugging(`[Sandbox] Expanded glob pattern "${p}" to ${expanded.length} paths on Linux`); + denyPaths.push(...expanded); + } + else { + denyPaths.push(stripped); + } + } + // Process allowRead paths (re-allow within denied regions) + const allowPaths = []; + for (const p of config.filesystem.allowRead ?? []) { + const stripped = removeTrailingGlobSuffix(p); + if (getPlatform() === 'linux' && containsGlobChars(stripped)) { + const expanded = expandGlobPattern(p); + logForDebugging(`[Sandbox] Expanded allowRead glob pattern "${p}" to ${expanded.length} paths on Linux`); + allowPaths.push(...expanded); + } + else { + allowPaths.push(stripped); + } + } + return { + denyOnly: denyPaths, + allowWithinDeny: allowPaths, + }; +} +function getFsWriteConfig() { + if (!config) { + return { allowOnly: getDefaultWritePaths(), denyWithinAllow: [] }; + } + // Filter out glob patterns on Linux/WSL for allowWrite (bubblewrap doesn't support globs) + const allowPaths = config.filesystem.allowWrite + .map(path => removeTrailingGlobSuffix(path)) + .filter(path => { + if (getPlatform() === 'linux' && containsGlobChars(path)) { + logForDebugging(`Skipping glob pattern on Linux/WSL: ${path}`); + return false; + } + return true; + }); + // Filter out glob patterns on Linux/WSL for denyWrite (bubblewrap doesn't support globs) + const denyPaths = config.filesystem.denyWrite + .map(path => removeTrailingGlobSuffix(path)) + .filter(path => { + if (getPlatform() === 'linux' && containsGlobChars(path)) { + logForDebugging(`Skipping glob pattern on Linux/WSL: ${path}`); + return false; + } + return true; + }); + // Build allowOnly list: default paths + configured allow paths + const allowOnly = [...getDefaultWritePaths(), ...allowPaths]; + return { + allowOnly, + denyWithinAllow: denyPaths, + }; +} +function getNetworkRestrictionConfig() { + if (!config) { + return {}; + } + const allowedHosts = config.network.allowedDomains; + const deniedHosts = config.network.deniedDomains; + return { + ...(allowedHosts.length > 0 && { allowedHosts }), + ...(deniedHosts.length > 0 && { deniedHosts }), + }; +} +function getAllowUnixSockets() { + return config?.network?.allowUnixSockets; +} +function getAllowAllUnixSockets() { + return config?.network?.allowAllUnixSockets; +} +function getAllowLocalBinding() { + return config?.network?.allowLocalBinding; +} +function getIgnoreViolations() { + return config?.ignoreViolations; +} +function getEnableWeakerNestedSandbox() { + return config?.enableWeakerNestedSandbox; +} +function getEnableWeakerNetworkIsolation() { + return config?.enableWeakerNetworkIsolation; +} +function getRipgrepConfig() { + return config?.ripgrep ?? { command: 'rg' }; +} +function getMandatoryDenySearchDepth() { + return config?.mandatoryDenySearchDepth ?? 3; +} +function getAllowGitConfig() { + return config?.filesystem?.allowGitConfig ?? false; +} +function getSeccompConfig() { + return config?.seccomp; +} +function getProxyPort() { + return managerContext?.httpProxyPort; +} +function getSocksProxyPort() { + return managerContext?.socksProxyPort; +} +function getLinuxHttpSocketPath() { + return managerContext?.linuxBridge?.httpSocketPath; +} +function getLinuxSocksSocketPath() { + return managerContext?.linuxBridge?.socksSocketPath; +} +/** + * Wait for network initialization to complete if already in progress + * Returns true if initialized successfully, false otherwise + */ +async function waitForNetworkInitialization() { + if (!config) { + return false; + } + if (initializationPromise) { + try { + await initializationPromise; + return true; + } + catch { + return false; + } + } + return managerContext !== undefined; +} +async function wrapWithSandbox(command, binShell, customConfig, abortSignal) { + const platform = getPlatform(); + // Get configs - use custom if provided, otherwise fall back to main config + // If neither exists, defaults to empty arrays (most restrictive) + // Always include default system write paths (like /dev/null, /tmp/claude) + // + // Strip trailing /** and filter remaining globs on Linux (bwrap needs + // real paths, not globs; macOS subpath matching is also recursive so + // stripping is harmless there). + const stripWriteGlobs = (paths) => paths + .map(p => removeTrailingGlobSuffix(p)) + .filter(p => { + if (getPlatform() === 'linux' && containsGlobChars(p)) { + logForDebugging(`[Sandbox] Skipping glob write pattern on Linux: ${p}`); + return false; + } + return true; + }); + const userAllowWrite = stripWriteGlobs(customConfig?.filesystem?.allowWrite ?? config?.filesystem.allowWrite ?? []); + const writeConfig = { + allowOnly: [...getDefaultWritePaths(), ...userAllowWrite], + denyWithinAllow: stripWriteGlobs(customConfig?.filesystem?.denyWrite ?? config?.filesystem.denyWrite ?? []), + }; + const rawDenyRead = customConfig?.filesystem?.denyRead ?? config?.filesystem.denyRead ?? []; + const expandedDenyRead = []; + for (const p of rawDenyRead) { + const stripped = removeTrailingGlobSuffix(p); + if (getPlatform() === 'linux' && containsGlobChars(stripped)) { + expandedDenyRead.push(...expandGlobPattern(p)); + } + else { + expandedDenyRead.push(stripped); + } + } + const rawAllowRead = customConfig?.filesystem?.allowRead ?? config?.filesystem.allowRead ?? []; + const expandedAllowRead = []; + for (const p of rawAllowRead) { + const stripped = removeTrailingGlobSuffix(p); + if (getPlatform() === 'linux' && containsGlobChars(stripped)) { + expandedAllowRead.push(...expandGlobPattern(p)); + } + else { + expandedAllowRead.push(stripped); + } + } + const readConfig = { + denyOnly: expandedDenyRead, + allowWithinDeny: expandedAllowRead, + }; + // Check if network config is specified - this determines if we need network restrictions + // Network restriction is needed when: + // 1. customConfig has network.allowedDomains defined (even if empty array = block all) + // 2. OR config has network.allowedDomains defined (even if empty array = block all) + // An empty allowedDomains array means "no domains allowed" = block all network access + const hasNetworkConfig = customConfig?.network?.allowedDomains !== undefined || + config?.network?.allowedDomains !== undefined; + // Network RESTRICTION is needed whenever network config is specified + // This includes empty allowedDomains which means "block all network" + const needsNetworkRestriction = hasNetworkConfig; + // Network PROXY is needed whenever network config is specified + // Even with empty allowedDomains, we route through proxy so that: + // 1. updateConfig() can enable network access for already-running processes + // 2. The proxy blocks all requests when allowlist is empty + const needsNetworkProxy = hasNetworkConfig; + // Wait for network initialization only if proxy is actually needed + if (needsNetworkProxy) { + await waitForNetworkInitialization(); + } + // Check custom config to allow pseudo-terminal (can be applied dynamically) + const allowPty = customConfig?.allowPty ?? config?.allowPty; + switch (platform) { + case 'macos': + // macOS sandbox profile supports glob patterns directly, no ripgrep needed + return wrapCommandWithSandboxMacOS({ + command, + needsNetworkRestriction, + // Only pass proxy ports if proxy is running (when there are domains to filter) + httpProxyPort: needsNetworkProxy ? getProxyPort() : undefined, + socksProxyPort: needsNetworkProxy ? getSocksProxyPort() : undefined, + readConfig, + writeConfig, + allowUnixSockets: getAllowUnixSockets(), + allowAllUnixSockets: getAllowAllUnixSockets(), + allowLocalBinding: getAllowLocalBinding(), + ignoreViolations: getIgnoreViolations(), + allowPty, + allowGitConfig: getAllowGitConfig(), + enableWeakerNetworkIsolation: getEnableWeakerNetworkIsolation(), + binShell, + }); + case 'linux': + return wrapCommandWithSandboxLinux({ + command, + needsNetworkRestriction, + // Only pass socket paths if proxy is running (when there are domains to filter) + httpSocketPath: needsNetworkProxy + ? getLinuxHttpSocketPath() + : undefined, + socksSocketPath: needsNetworkProxy + ? getLinuxSocksSocketPath() + : undefined, + httpProxyPort: needsNetworkProxy + ? managerContext?.httpProxyPort + : undefined, + socksProxyPort: needsNetworkProxy + ? managerContext?.socksProxyPort + : undefined, + readConfig, + writeConfig, + enableWeakerNestedSandbox: getEnableWeakerNestedSandbox(), + allowAllUnixSockets: getAllowAllUnixSockets(), + binShell, + ripgrepConfig: getRipgrepConfig(), + mandatoryDenySearchDepth: getMandatoryDenySearchDepth(), + allowGitConfig: getAllowGitConfig(), + seccompConfig: getSeccompConfig(), + abortSignal, + }); + default: + // Unsupported platform - this should not happen since isSandboxingEnabled() checks platform support + throw new Error(`Sandbox configuration is not supported on platform: ${platform}`); + } +} +/** + * Get the current sandbox configuration + * @returns The current configuration, or undefined if not initialized + */ +function getConfig() { + return config; +} +/** + * Update the sandbox configuration + * @param newConfig - The new configuration to use + */ +function updateConfig(newConfig) { + // Deep clone the config to avoid mutations + config = cloneDeep(newConfig); + logForDebugging('Sandbox configuration updated'); +} +/** + * Lightweight cleanup to call after each sandboxed command completes. + * + * On Linux, bwrap creates empty files on the host filesystem as mount points + * when protecting non-existent deny paths (e.g. ~/.bashrc, ~/.gitconfig). + * These persist after bwrap exits. This function removes them. + * + * Safe to call on any platform — it's a no-op on macOS. + * Also called automatically by reset() and on process exit as safety nets. + */ +function cleanupAfterCommand() { + cleanupBwrapMountPoints(); +} +async function reset() { + // Clean up any leftover bwrap mount points + cleanupAfterCommand(); + // Stop log monitor + if (logMonitorShutdown) { + logMonitorShutdown(); + logMonitorShutdown = undefined; + } + if (managerContext?.linuxBridge) { + const { httpSocketPath, socksSocketPath, httpBridgeProcess, socksBridgeProcess, } = managerContext.linuxBridge; + // Create array to wait for process exits + const exitPromises = []; + // Kill HTTP bridge and wait for it to exit + if (httpBridgeProcess.pid && !httpBridgeProcess.killed) { + try { + process.kill(httpBridgeProcess.pid, 'SIGTERM'); + logForDebugging('Sent SIGTERM to HTTP bridge process'); + // Wait for process to exit + exitPromises.push(new Promise(resolve => { + httpBridgeProcess.once('exit', () => { + logForDebugging('HTTP bridge process exited'); + resolve(); + }); + // Timeout after 5 seconds + setTimeout(() => { + if (!httpBridgeProcess.killed) { + logForDebugging('HTTP bridge did not exit, forcing SIGKILL', { + level: 'warn', + }); + try { + if (httpBridgeProcess.pid) { + process.kill(httpBridgeProcess.pid, 'SIGKILL'); + } + } + catch { + // Process may have already exited + } + } + resolve(); + }, 5000); + })); + } + catch (err) { + if (err.code !== 'ESRCH') { + logForDebugging(`Error killing HTTP bridge: ${err}`, { + level: 'error', + }); + } + } + } + // Kill SOCKS bridge and wait for it to exit + if (socksBridgeProcess.pid && !socksBridgeProcess.killed) { + try { + process.kill(socksBridgeProcess.pid, 'SIGTERM'); + logForDebugging('Sent SIGTERM to SOCKS bridge process'); + // Wait for process to exit + exitPromises.push(new Promise(resolve => { + socksBridgeProcess.once('exit', () => { + logForDebugging('SOCKS bridge process exited'); + resolve(); + }); + // Timeout after 5 seconds + setTimeout(() => { + if (!socksBridgeProcess.killed) { + logForDebugging('SOCKS bridge did not exit, forcing SIGKILL', { + level: 'warn', + }); + try { + if (socksBridgeProcess.pid) { + process.kill(socksBridgeProcess.pid, 'SIGKILL'); + } + } + catch { + // Process may have already exited + } + } + resolve(); + }, 5000); + })); + } + catch (err) { + if (err.code !== 'ESRCH') { + logForDebugging(`Error killing SOCKS bridge: ${err}`, { + level: 'error', + }); + } + } + } + // Wait for both processes to exit + await Promise.all(exitPromises); + // Clean up sockets + if (httpSocketPath) { + try { + fs.rmSync(httpSocketPath, { force: true }); + logForDebugging('Cleaned up HTTP socket'); + } + catch (err) { + logForDebugging(`HTTP socket cleanup error: ${err}`, { + level: 'error', + }); + } + } + if (socksSocketPath) { + try { + fs.rmSync(socksSocketPath, { force: true }); + logForDebugging('Cleaned up SOCKS socket'); + } + catch (err) { + logForDebugging(`SOCKS socket cleanup error: ${err}`, { + level: 'error', + }); + } + } + } + // Close servers in parallel (only if they exist, i.e., were started by us) + const closePromises = []; + if (httpProxyServer) { + const server = httpProxyServer; // Capture reference to avoid TypeScript error + const httpClose = new Promise(resolve => { + server.close(error => { + if (error && error.message !== 'Server is not running.') { + logForDebugging(`Error closing HTTP proxy server: ${error.message}`, { + level: 'error', + }); + } + resolve(); + }); + }); + closePromises.push(httpClose); + } + if (socksProxyServer) { + const socksClose = socksProxyServer.close().catch((error) => { + logForDebugging(`Error closing SOCKS proxy server: ${error.message}`, { + level: 'error', + }); + }); + closePromises.push(socksClose); + } + // Wait for all servers to close + await Promise.all(closePromises); + // Clear references + httpProxyServer = undefined; + socksProxyServer = undefined; + managerContext = undefined; + initializationPromise = undefined; +} +function getSandboxViolationStore() { + return sandboxViolationStore; +} +function annotateStderrWithSandboxFailures(command, stderr) { + if (!config) { + return stderr; + } + const violations = sandboxViolationStore.getViolationsForCommand(command); + if (violations.length === 0) { + return stderr; + } + let annotated = stderr; + annotated += EOL + '' + EOL; + for (const violation of violations) { + annotated += violation.line + EOL; + } + annotated += ''; + return annotated; +} +/** + * Returns glob patterns from Edit/Read permission rules that are not + * fully supported on Linux. Returns empty array on macOS or when + * sandboxing is disabled. + * + * Patterns ending with /** are excluded since they work as subpaths. + */ +function getLinuxGlobPatternWarnings() { + // Only warn on Linux/WSL (bubblewrap doesn't support globs) + // macOS supports glob patterns via regex conversion + if (getPlatform() !== 'linux' || !config) { + return []; + } + const globPatterns = []; + // Check filesystem paths for glob patterns + // Note: denyRead is excluded because globs are now expanded to concrete paths on Linux + const allPaths = [ + ...config.filesystem.allowWrite, + ...config.filesystem.denyWrite, + ]; + for (const path of allPaths) { + // Strip trailing /** since that's just a subpath (directory and everything under it) + const pathWithoutTrailingStar = removeTrailingGlobSuffix(path); + // Only warn if there are still glob characters after removing trailing /** + if (containsGlobChars(pathWithoutTrailingStar)) { + globPatterns.push(path); + } + } + return globPatterns; +} +// ============================================================================ +// Export as Namespace with Interface +// ============================================================================ +/** + * Global sandbox manager that handles both network and filesystem restrictions + * for this session. This runs outside of the sandbox, on the host machine. + */ +export const SandboxManager = { + initialize, + isSupportedPlatform, + isSandboxingEnabled, + checkDependencies, + getFsReadConfig, + getFsWriteConfig, + getNetworkRestrictionConfig, + getAllowUnixSockets, + getAllowLocalBinding, + getIgnoreViolations, + getEnableWeakerNestedSandbox, + getProxyPort, + getSocksProxyPort, + getLinuxHttpSocketPath, + getLinuxSocksSocketPath, + waitForNetworkInitialization, + wrapWithSandbox, + cleanupAfterCommand, + reset, + getSandboxViolationStore, + annotateStderrWithSandboxFailures, + getLinuxGlobPatternWarnings, + getConfig, + updateConfig, +}; +//# sourceMappingURL=sandbox-manager.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/sandbox-utils.js b/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/sandbox-utils.js new file mode 100644 index 00000000..dcfef2ca --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/sandbox-utils.js @@ -0,0 +1,435 @@ +import { homedir } from 'os'; +import * as path from 'path'; +import * as fs from 'fs'; +import { getPlatform } from '../utils/platform.js'; +import { logForDebugging } from '../utils/debug.js'; +/** + * Dangerous files that should be protected from writes. + * These files can be used for code execution or data exfiltration. + */ +export const DANGEROUS_FILES = [ + '.gitconfig', + '.gitmodules', + '.bashrc', + '.bash_profile', + '.zshrc', + '.zprofile', + '.profile', + '.ripgreprc', + '.mcp.json', +]; +/** + * Dangerous directories that should be protected from writes. + * These directories contain sensitive configuration or executable files. + */ +export const DANGEROUS_DIRECTORIES = ['.git', '.vscode', '.idea']; +/** + * Get the list of dangerous directories to deny writes to. + * Excludes .git since we need it writable for git operations - + * instead we block specific paths within .git (hooks and config). + */ +export function getDangerousDirectories() { + return [ + ...DANGEROUS_DIRECTORIES.filter(d => d !== '.git'), + '.claude/commands', + '.claude/agents', + ]; +} +/** + * Normalizes a path for case-insensitive comparison. + * This prevents bypassing security checks using mixed-case paths on case-insensitive + * filesystems (macOS/Windows) like `.cLauDe/Settings.locaL.json`. + * + * We always normalize to lowercase regardless of platform for consistent security. + * @param path The path to normalize + * @returns The lowercase path for safe comparison + */ +export function normalizeCaseForComparison(pathStr) { + return pathStr.toLowerCase(); +} +/** + * Check if a path pattern contains glob characters + */ +export function containsGlobChars(pathPattern) { + return (pathPattern.includes('*') || + pathPattern.includes('?') || + pathPattern.includes('[') || + pathPattern.includes(']')); +} +/** + * Remove trailing /** glob suffix from a path pattern + * Used to normalize path patterns since /** just means "directory and everything under it" + */ +export function removeTrailingGlobSuffix(pathPattern) { + const stripped = pathPattern.replace(/\/\*\*$/, ''); + return stripped || '/'; +} +/** + * Check if a symlink resolution crosses expected path boundaries. + * + * When resolving symlinks for sandbox path normalization, we need to ensure + * the resolved path doesn't unexpectedly broaden the scope. This function + * returns true if the resolved path is an ancestor of the original path + * or resolves to a system root, which would indicate the symlink points + * outside expected boundaries. + * + * @param originalPath - The original path before symlink resolution + * @param resolvedPath - The path after fs.realpathSync() resolution + * @returns true if the resolved path is outside expected boundaries + */ +export function isSymlinkOutsideBoundary(originalPath, resolvedPath) { + const normalizedOriginal = path.normalize(originalPath); + const normalizedResolved = path.normalize(resolvedPath); + // Same path after normalization - OK + if (normalizedResolved === normalizedOriginal) { + return false; + } + // Handle macOS /tmp -> /private/tmp canonical resolution + // This is a legitimate system symlink that should be allowed + // /tmp/claude -> /private/tmp/claude is OK + // /var/folders/... -> /private/var/folders/... is OK + if (normalizedOriginal.startsWith('/tmp/') && + normalizedResolved === '/private' + normalizedOriginal) { + return false; + } + if (normalizedOriginal.startsWith('/var/') && + normalizedResolved === '/private' + normalizedOriginal) { + return false; + } + // Also handle the reverse: /private/tmp/... resolving to itself + if (normalizedOriginal.startsWith('/private/tmp/') && + normalizedResolved === normalizedOriginal) { + return false; + } + if (normalizedOriginal.startsWith('/private/var/') && + normalizedResolved === normalizedOriginal) { + return false; + } + // If resolved path is "/" it's outside expected boundaries + if (normalizedResolved === '/') { + return true; + } + // If resolved path is very short (single component like /tmp, /usr, /var), + // it's likely outside expected boundaries + const resolvedParts = normalizedResolved.split('/').filter(Boolean); + if (resolvedParts.length <= 1) { + return true; + } + // If original path starts with resolved path, the resolved path is an ancestor + // e.g., /tmp/claude -> /tmp means the symlink points to a broader scope + if (normalizedOriginal.startsWith(normalizedResolved + '/')) { + return true; + } + // Also check the canonical form of the original path for macOS + // e.g., /tmp/claude should also be checked as /private/tmp/claude + let canonicalOriginal = normalizedOriginal; + if (normalizedOriginal.startsWith('/tmp/')) { + canonicalOriginal = '/private' + normalizedOriginal; + } + else if (normalizedOriginal.startsWith('/var/')) { + canonicalOriginal = '/private' + normalizedOriginal; + } + if (canonicalOriginal !== normalizedOriginal && + canonicalOriginal.startsWith(normalizedResolved + '/')) { + return true; + } + // STRICT CHECK: Only allow resolutions that stay within the expected path tree + // The resolved path must either: + // 1. Start with the original path (deeper/same) - already covered by returning false below + // 2. Start with the canonical original (deeper/same under canonical form) + // 3. BE the canonical form of the original (e.g., /tmp/x -> /private/tmp/x) + // Any other resolution (e.g., /tmp/claude -> /Users/dworken) is outside expected bounds + const resolvedStartsWithOriginal = normalizedResolved.startsWith(normalizedOriginal + '/'); + const resolvedStartsWithCanonical = canonicalOriginal !== normalizedOriginal && + normalizedResolved.startsWith(canonicalOriginal + '/'); + const resolvedIsCanonical = canonicalOriginal !== normalizedOriginal && + normalizedResolved === canonicalOriginal; + const resolvedIsSame = normalizedResolved === normalizedOriginal; + // If resolved path is not within expected tree, it's outside boundary + if (!resolvedIsSame && + !resolvedIsCanonical && + !resolvedStartsWithOriginal && + !resolvedStartsWithCanonical) { + return true; + } + // Allow resolution to same directory level or deeper within expected tree + return false; +} +/** + * Normalize a path for use in sandbox configurations + * Handles: + * - Tilde (~) expansion for home directory + * - Relative paths (./foo, ../foo, etc.) converted to absolute + * - Absolute paths remain unchanged + * - Symlinks are resolved to their real paths for non-glob patterns + * - Glob patterns preserve wildcards after path normalization + * + * Returns the absolute path with symlinks resolved (or normalized glob pattern) + */ +export function normalizePathForSandbox(pathPattern) { + const cwd = process.cwd(); + let normalizedPath = pathPattern; + // Expand ~ to home directory + if (pathPattern === '~') { + normalizedPath = homedir(); + } + else if (pathPattern.startsWith('~/')) { + normalizedPath = homedir() + pathPattern.slice(1); + } + else if (pathPattern.startsWith('./') || pathPattern.startsWith('../')) { + // Convert relative to absolute based on current working directory + normalizedPath = path.resolve(cwd, pathPattern); + } + else if (!path.isAbsolute(pathPattern)) { + // Handle other relative paths (e.g., ".", "..", "foo/bar") + normalizedPath = path.resolve(cwd, pathPattern); + } + // For glob patterns, resolve symlinks for the directory portion only + if (containsGlobChars(normalizedPath)) { + // Extract the static directory prefix before glob characters + const staticPrefix = normalizedPath.split(/[*?[\]]/)[0]; + if (staticPrefix && staticPrefix !== '/') { + // Get the directory containing the glob pattern + // If staticPrefix ends with /, remove it to get the directory + const baseDir = staticPrefix.endsWith('/') + ? staticPrefix.slice(0, -1) + : path.dirname(staticPrefix); + // Try to resolve symlinks for the base directory + try { + const resolvedBaseDir = fs.realpathSync(baseDir); + // Validate that resolution stays within expected boundaries + if (!isSymlinkOutsideBoundary(baseDir, resolvedBaseDir)) { + // Reconstruct the pattern with the resolved directory + const patternSuffix = normalizedPath.slice(baseDir.length); + return resolvedBaseDir + patternSuffix; + } + // If resolution would broaden scope, keep original pattern + } + catch { + // If directory doesn't exist or can't be resolved, keep the original pattern + } + } + return normalizedPath; + } + // Resolve symlinks to real paths to avoid bwrap issues + // Validate that the resolution stays within expected boundaries + try { + const resolvedPath = fs.realpathSync(normalizedPath); + // Only use resolved path if it doesn't cross boundary (e.g., symlink to parent dir) + if (isSymlinkOutsideBoundary(normalizedPath, resolvedPath)) { + // Symlink points outside expected boundaries - keep original path + } + else { + normalizedPath = resolvedPath; + } + } + catch { + // If path doesn't exist or can't be resolved, keep the normalized path + } + return normalizedPath; +} +/** + * Get recommended system paths that should be writable for commands to work properly + * + * WARNING: These default paths are intentionally broad for compatibility but may + * allow access to files from other processes. In highly security-sensitive + * environments, you should configure more restrictive write paths. + */ +export function getDefaultWritePaths() { + const homeDir = homedir(); + const recommendedPaths = [ + '/dev/stdout', + '/dev/stderr', + '/dev/null', + '/dev/tty', + '/dev/dtracehelper', + '/dev/autofs_nowait', + '/tmp/claude', + '/private/tmp/claude', + path.join(homeDir, '.npm/_logs'), + path.join(homeDir, '.claude/debug'), + ]; + return recommendedPaths; +} +/** + * Generate proxy environment variables for sandboxed processes + */ +export function generateProxyEnvVars(httpProxyPort, socksProxyPort) { + // Respect CLAUDE_TMPDIR if set, otherwise default to /tmp/claude + const tmpdir = process.env.CLAUDE_TMPDIR || '/tmp/claude'; + const envVars = [`SANDBOX_RUNTIME=1`, `TMPDIR=${tmpdir}`]; + // If no proxy ports provided, return minimal env vars + if (!httpProxyPort && !socksProxyPort) { + return envVars; + } + // Always set NO_PROXY to exclude localhost and private networks from proxying + const noProxyAddresses = [ + 'localhost', + '127.0.0.1', + '::1', + '*.local', + '.local', + '169.254.0.0/16', // Link-local + '10.0.0.0/8', // Private network + '172.16.0.0/12', // Private network + '192.168.0.0/16', // Private network + ].join(','); + envVars.push(`NO_PROXY=${noProxyAddresses}`); + envVars.push(`no_proxy=${noProxyAddresses}`); + if (httpProxyPort) { + envVars.push(`HTTP_PROXY=http://localhost:${httpProxyPort}`); + envVars.push(`HTTPS_PROXY=http://localhost:${httpProxyPort}`); + // Lowercase versions for compatibility with some tools + envVars.push(`http_proxy=http://localhost:${httpProxyPort}`); + envVars.push(`https_proxy=http://localhost:${httpProxyPort}`); + } + if (socksProxyPort) { + // Use socks5h:// for proper DNS resolution through proxy + envVars.push(`ALL_PROXY=socks5h://localhost:${socksProxyPort}`); + envVars.push(`all_proxy=socks5h://localhost:${socksProxyPort}`); + // Configure Git to use SSH through the proxy so DNS resolution happens outside the sandbox + const platform = getPlatform(); + if (platform === 'macos') { + // macOS: use BSD nc SOCKS5 proxy support (-X 5 -x) + envVars.push(`GIT_SSH_COMMAND=ssh -o ProxyCommand='nc -X 5 -x localhost:${socksProxyPort} %h %p'`); + } + else if (platform === 'linux' && httpProxyPort) { + // Linux: use socat HTTP CONNECT via the HTTP proxy bridge. + // socat is already a required Linux sandbox dependency, and PROXY: is + // portable across all socat versions (unlike SOCKS5-CONNECT which needs >= 1.8.0). + envVars.push(`GIT_SSH_COMMAND=ssh -o ProxyCommand='socat - PROXY:localhost:%h:%p,proxyport=${httpProxyPort}'`); + } + // FTP proxy support (use socks5h for DNS resolution through proxy) + envVars.push(`FTP_PROXY=socks5h://localhost:${socksProxyPort}`); + envVars.push(`ftp_proxy=socks5h://localhost:${socksProxyPort}`); + // rsync proxy support + envVars.push(`RSYNC_PROXY=localhost:${socksProxyPort}`); + // Database tools NOTE: Most database clients don't have built-in proxy support + // You typically need to use SSH tunneling or a SOCKS wrapper like tsocks/proxychains + // Docker CLI uses HTTP for the API + // This makes Docker use the HTTP proxy for registry operations + envVars.push(`DOCKER_HTTP_PROXY=http://localhost:${httpProxyPort || socksProxyPort}`); + envVars.push(`DOCKER_HTTPS_PROXY=http://localhost:${httpProxyPort || socksProxyPort}`); + // Kubernetes kubectl - uses standard HTTPS_PROXY + // kubectl respects HTTPS_PROXY which we already set above + // AWS CLI - uses standard HTTPS_PROXY (v2 supports it well) + // AWS CLI v2 respects HTTPS_PROXY which we already set above + // Google Cloud SDK - has specific proxy settings + // Use HTTPS proxy to match other HTTP-based tools + if (httpProxyPort) { + envVars.push(`CLOUDSDK_PROXY_TYPE=https`); + envVars.push(`CLOUDSDK_PROXY_ADDRESS=localhost`); + envVars.push(`CLOUDSDK_PROXY_PORT=${httpProxyPort}`); + } + // Azure CLI - uses HTTPS_PROXY + // Azure CLI respects HTTPS_PROXY which we already set above + // Terraform - uses standard HTTP/HTTPS proxy vars + // Terraform respects HTTP_PROXY/HTTPS_PROXY which we already set above + // gRPC-based tools - use standard proxy vars + envVars.push(`GRPC_PROXY=socks5h://localhost:${socksProxyPort}`); + envVars.push(`grpc_proxy=socks5h://localhost:${socksProxyPort}`); + } + // WARNING: Do not set HTTP_PROXY/HTTPS_PROXY to SOCKS URLs when only SOCKS proxy is available + // Most HTTP clients do not support SOCKS URLs in these variables and will fail, and we want + // to avoid overriding the client otherwise respecting the ALL_PROXY env var which points to SOCKS. + return envVars; +} +/** + * Encode a command for sandbox monitoring + * Truncates to 100 chars and base64 encodes to avoid parsing issues + */ +export function encodeSandboxedCommand(command) { + const truncatedCommand = command.slice(0, 100); + return Buffer.from(truncatedCommand).toString('base64'); +} +/** + * Decode a base64-encoded command from sandbox monitoring + */ +export function decodeSandboxedCommand(encodedCommand) { + return Buffer.from(encodedCommand, 'base64').toString('utf8'); +} +/** + * Convert a glob pattern to a regular expression + * + * This implements gitignore-style pattern matching to match the behavior of the + * `ignore` library used by the permission system. + * + * Supported patterns: + * - * matches any characters except / (e.g., *.ts matches foo.ts but not foo/bar.ts) + * - ** matches any characters including / (e.g., src/**\/*.ts matches all .ts files in src/) + * - ? matches any single character except / (e.g., file?.txt matches file1.txt) + * - [abc] matches any character in the set (e.g., file[0-9].txt matches file3.txt) + * + * Exported for testing and shared between macOS sandbox profiles and Linux glob expansion. + */ +export function globToRegex(globPattern) { + return ('^' + + globPattern + // Escape regex special characters (except glob chars * ? [ ]) + .replace(/[.^$+{}()|\\]/g, '\\$&') + // Escape unclosed brackets (no matching ]) + .replace(/\[([^\]]*?)$/g, '\\[$1') + // Convert glob patterns to regex (order matters - ** before *) + .replace(/\*\*\//g, '__GLOBSTAR_SLASH__') // Placeholder for **/ + .replace(/\*\*/g, '__GLOBSTAR__') // Placeholder for ** + .replace(/\*/g, '[^/]*') // * matches anything except / + .replace(/\?/g, '[^/]') // ? matches single character except / + // Restore placeholders + .replace(/__GLOBSTAR_SLASH__/g, '(.*/)?') // **/ matches zero or more dirs + .replace(/__GLOBSTAR__/g, '.*') + // ** matches anything including / + '$'); +} +/** + * Expand a glob pattern into concrete file paths. + * + * Used on Linux where bubblewrap doesn't support glob patterns natively. + * Resolves the static directory prefix, lists files recursively, and filters + * using globToRegex(). + * + * @param globPath - A path pattern containing glob characters (e.g., ~/test/*.env) + * @returns Array of absolute paths matching the glob pattern + */ +export function expandGlobPattern(globPath) { + const normalizedPattern = normalizePathForSandbox(globPath); + // Extract the static directory prefix before any glob characters + const staticPrefix = normalizedPattern.split(/[*?[\]]/)[0]; + if (!staticPrefix || staticPrefix === '/') { + logForDebugging(`[Sandbox] Glob pattern too broad, skipping: ${globPath}`); + return []; + } + // Get the base directory from the static prefix + const baseDir = staticPrefix.endsWith('/') + ? staticPrefix.slice(0, -1) + : path.dirname(staticPrefix); + if (!fs.existsSync(baseDir)) { + logForDebugging(`[Sandbox] Base directory for glob does not exist: ${baseDir}`); + return []; + } + // Build regex from the normalized glob pattern + const regex = new RegExp(globToRegex(normalizedPattern)); + // List all entries recursively under the base directory + const results = []; + try { + const entries = fs.readdirSync(baseDir, { + recursive: true, + withFileTypes: true, + }); + for (const entry of entries) { + // Build the full path for this entry + // entry.parentPath is the directory containing this entry (available in Node 20+/Bun) + // For compatibility, fall back to entry.path if parentPath is not available + const parentDir = entry.parentPath ?? + entry.path ?? + baseDir; + const fullPath = path.join(parentDir, entry.name); + if (regex.test(fullPath)) { + results.push(fullPath); + } + } + } + catch (err) { + logForDebugging(`[Sandbox] Error expanding glob pattern ${globPath}: ${err}`); + } + return results; +} +//# sourceMappingURL=sandbox-utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/sandbox-violation-store.js b/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/sandbox-violation-store.js new file mode 100644 index 00000000..385a3189 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/sandbox-violation-store.js @@ -0,0 +1,54 @@ +import { encodeSandboxedCommand } from './sandbox-utils.js'; +/** + * In-memory tail for sandbox violations + */ +export class SandboxViolationStore { + constructor() { + this.violations = []; + this.totalCount = 0; + this.maxSize = 100; + this.listeners = new Set(); + } + addViolation(violation) { + this.violations.push(violation); + this.totalCount++; + if (this.violations.length > this.maxSize) { + this.violations = this.violations.slice(-this.maxSize); + } + this.notifyListeners(); + } + getViolations(limit) { + if (limit === undefined) { + return [...this.violations]; + } + return this.violations.slice(-limit); + } + getCount() { + return this.violations.length; + } + getTotalCount() { + return this.totalCount; + } + getViolationsForCommand(command) { + const commandBase64 = encodeSandboxedCommand(command); + return this.violations.filter(v => v.encodedCommand === commandBase64); + } + clear() { + this.violations = []; + // Don't reset totalCount when clearing + this.notifyListeners(); + } + subscribe(listener) { + this.listeners.add(listener); + listener(this.getViolations()); + return () => { + this.listeners.delete(listener); + }; + } + notifyListeners() { + // Always notify with all violations so listeners can track the full count + const violations = this.getViolations(); + this.listeners.forEach(listener => listener(violations)); + } +} +//# sourceMappingURL=sandbox-violation-store.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/socks-proxy.js b/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/socks-proxy.js new file mode 100644 index 00000000..9ce95435 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/socks-proxy.js @@ -0,0 +1,95 @@ +import { createServer } from '@pondwader/socks5-server'; +import { logForDebugging } from '../utils/debug.js'; +export function createSocksProxyServer(options) { + const socksServer = createServer(); + socksServer.setRulesetValidator(async (conn) => { + try { + const hostname = conn.destAddress; + const port = conn.destPort; + logForDebugging(`Connection request to ${hostname}:${port}`); + const allowed = await options.filter(port, hostname); + if (!allowed) { + logForDebugging(`Connection blocked to ${hostname}:${port}`, { + level: 'error', + }); + return false; + } + logForDebugging(`Connection allowed to ${hostname}:${port}`); + return true; + } + catch (error) { + logForDebugging(`Error validating connection: ${error}`, { + level: 'error', + }); + return false; + } + }); + return { + server: socksServer, + getPort() { + // Access the internal server to get the port + // We need to use type assertion here as the server property is private + try { + const serverInternal = socksServer?.server; + if (serverInternal && typeof serverInternal?.address === 'function') { + const address = serverInternal.address(); + if (address && typeof address === 'object' && 'port' in address) { + return address.port; + } + } + } + catch (error) { + // Server might not be listening yet or property access failed + logForDebugging(`Error getting port: ${error}`, { level: 'error' }); + } + return undefined; + }, + listen(port, hostname) { + return new Promise((resolve, reject) => { + const listeningCallback = () => { + const actualPort = this.getPort(); + if (actualPort) { + logForDebugging(`SOCKS proxy listening on ${hostname}:${actualPort}`); + resolve(actualPort); + } + else { + reject(new Error('Failed to get SOCKS proxy server port')); + } + }; + socksServer.listen(port, hostname, listeningCallback); + }); + }, + async close() { + return new Promise((resolve, reject) => { + socksServer.close(error => { + if (error) { + // Only reject for actual errors, not for "already closed" states + // Check for common "already closed" error patterns + const errorMessage = error.message?.toLowerCase() || ''; + const isAlreadyClosed = errorMessage.includes('not running') || + errorMessage.includes('already closed') || + errorMessage.includes('not listening'); + if (!isAlreadyClosed) { + reject(error); + return; + } + } + resolve(); + }); + }); + }, + unref() { + // Access the internal server to call unref + try { + const serverInternal = socksServer?.server; + if (serverInternal && typeof serverInternal?.unref === 'function') { + serverInternal.unref(); + } + } + catch (error) { + logForDebugging(`Error calling unref: ${error}`, { level: 'error' }); + } + }, + }; +} +//# sourceMappingURL=socks-proxy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/utils/debug.js b/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/utils/debug.js new file mode 100644 index 00000000..95c2e84a --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/utils/debug.js @@ -0,0 +1,25 @@ +/** + * Simple debug logging for standalone sandbox + */ +export function logForDebugging(message, options) { + // Only log if SRT_DEBUG environment variable is set + // Using SRT_DEBUG instead of DEBUG to avoid conflicts with other tools + // (DEBUG is commonly used by Node.js debug libraries and VS Code) + if (!process.env.SRT_DEBUG) { + return; + } + const level = options?.level || 'info'; + const prefix = '[SandboxDebug]'; + // Always use stderr to avoid corrupting stdout JSON streams + switch (level) { + case 'error': + console.error(`${prefix} ${message}`); + break; + case 'warn': + console.warn(`${prefix} ${message}`); + break; + default: + console.error(`${prefix} ${message}`); + } +} +//# sourceMappingURL=debug.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/utils/platform.js b/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/utils/platform.js new file mode 100644 index 00000000..9b30e57e --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/utils/platform.js @@ -0,0 +1,49 @@ +/** + * Platform detection utilities + */ +import * as fs from 'fs'; +/** + * Get the WSL version (1 or 2+) if running in WSL. + * Returns undefined if not running in WSL. + */ +export function getWslVersion() { + if (process.platform !== 'linux') { + return undefined; + } + try { + const procVersion = fs.readFileSync('/proc/version', { encoding: 'utf8' }); + // Check for explicit WSL version markers (e.g., "WSL2", "WSL3", etc.) + const wslVersionMatch = procVersion.match(/WSL(\d+)/i); + if (wslVersionMatch && wslVersionMatch[1]) { + return wslVersionMatch[1]; + } + // If no explicit WSL version but contains Microsoft, assume WSL1 + // This handles the original WSL1 format: "4.4.0-19041-Microsoft" + if (procVersion.toLowerCase().includes('microsoft')) { + return '1'; + } + return undefined; + } + catch { + return undefined; + } +} +/** + * Detect the current platform. + * Note: All Linux including WSL returns 'linux'. Use getWslVersion() to detect WSL1 (unsupported). + */ +export function getPlatform() { + switch (process.platform) { + case 'darwin': + return 'macos'; + case 'linux': + // WSL2+ is treated as Linux (same sandboxing) + // WSL1 is also returned as 'linux' but will fail isSupportedPlatform check + return 'linux'; + case 'win32': + return 'windows'; + default: + return 'unknown'; + } +} +//# sourceMappingURL=platform.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/utils/ripgrep.js b/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/utils/ripgrep.js new file mode 100644 index 00000000..76eb341f --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/utils/ripgrep.js @@ -0,0 +1,45 @@ +import { spawn } from 'child_process'; +import { text } from 'node:stream/consumers'; +import { whichSync } from './which.js'; +/** + * Check if ripgrep (rg) is available synchronously + * Returns true if rg is installed, false otherwise + */ +export function hasRipgrepSync() { + return whichSync('rg') !== null; +} +/** + * Execute ripgrep with the given arguments + * @param args Command-line arguments to pass to rg + * @param target Target directory or file to search + * @param abortSignal AbortSignal to cancel the operation + * @param config Ripgrep configuration (command and optional args) + * @returns Array of matching lines (one per line of output) + * @throws Error if ripgrep exits with non-zero status (except exit code 1 which means no matches) + */ +export async function ripGrep(args, target, abortSignal, config = { command: 'rg' }) { + const { command, args: commandArgs = [], argv0 } = config; + const child = spawn(command, [...commandArgs, ...args, target], { + argv0, + signal: abortSignal, + timeout: 10000, + windowsHide: true, + }); + const [stdout, stderr, code] = await Promise.all([ + text(child.stdout), + text(child.stderr), + new Promise((resolve, reject) => { + child.on('close', resolve); + child.on('error', reject); + }), + ]); + if (code === 0) { + return stdout.trim().split('\n').filter(Boolean); + } + if (code === 1) { + // Exit code 1 means "no matches found" - this is normal + return []; + } + throw new Error(`ripgrep failed with exit code ${code}: ${stderr}`); +} +//# sourceMappingURL=ripgrep.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/utils/which.js b/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/utils/which.js new file mode 100644 index 00000000..cc877007 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sandbox-runtime/dist/utils/which.js @@ -0,0 +1,25 @@ +import { spawnSync } from 'node:child_process'; +/** + * Find the path to an executable, similar to the `which` command. + * Uses Bun.which when running in Bun, falls back to spawnSync for Node.js. + * + * @param bin - The name of the executable to find + * @returns The full path to the executable, or null if not found + */ +export function whichSync(bin) { + // Check if we're running in Bun + if (typeof globalThis.Bun !== 'undefined') { + return globalThis.Bun.which(bin); + } + // Fallback to Node.js implementation + const result = spawnSync('which', [bin], { + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'ignore'], + timeout: 1000, + }); + if (result.status === 0 && result.stdout) { + return result.stdout.trim(); + } + return null; +} +//# sourceMappingURL=which.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs new file mode 100644 index 00000000..d2e0d5cb --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs @@ -0,0 +1,223 @@ +const tokenize = (input) => { + let current = 0; + let tokens = []; + while (current < input.length) { + let char = input[current]; + if (char === '\\') { + current++; + continue; + } + if (char === '{') { + tokens.push({ + type: 'brace', + value: '{', + }); + current++; + continue; + } + if (char === '}') { + tokens.push({ + type: 'brace', + value: '}', + }); + current++; + continue; + } + if (char === '[') { + tokens.push({ + type: 'paren', + value: '[', + }); + current++; + continue; + } + if (char === ']') { + tokens.push({ + type: 'paren', + value: ']', + }); + current++; + continue; + } + if (char === ':') { + tokens.push({ + type: 'separator', + value: ':', + }); + current++; + continue; + } + if (char === ',') { + tokens.push({ + type: 'delimiter', + value: ',', + }); + current++; + continue; + } + if (char === '"') { + let value = ''; + let danglingQuote = false; + char = input[++current]; + while (char !== '"') { + if (current === input.length) { + danglingQuote = true; + break; + } + if (char === '\\') { + current++; + if (current === input.length) { + danglingQuote = true; + break; + } + value += char + input[current]; + char = input[++current]; + } + else { + value += char; + char = input[++current]; + } + } + char = input[++current]; + if (!danglingQuote) { + tokens.push({ + type: 'string', + value, + }); + } + continue; + } + let WHITESPACE = /\s/; + if (char && WHITESPACE.test(char)) { + current++; + continue; + } + let NUMBERS = /[0-9]/; + if ((char && NUMBERS.test(char)) || char === '-' || char === '.') { + let value = ''; + if (char === '-') { + value += char; + char = input[++current]; + } + while ((char && NUMBERS.test(char)) || char === '.') { + value += char; + char = input[++current]; + } + tokens.push({ + type: 'number', + value, + }); + continue; + } + let LETTERS = /[a-z]/i; + if (char && LETTERS.test(char)) { + let value = ''; + while (char && LETTERS.test(char)) { + if (current === input.length) { + break; + } + value += char; + char = input[++current]; + } + if (value == 'true' || value == 'false' || value === 'null') { + tokens.push({ + type: 'name', + value, + }); + } + else { + // unknown token, e.g. `nul` which isn't quite `null` + current++; + continue; + } + continue; + } + current++; + } + return tokens; +}, strip = (tokens) => { + if (tokens.length === 0) { + return tokens; + } + let lastToken = tokens[tokens.length - 1]; + switch (lastToken.type) { + case 'separator': + tokens = tokens.slice(0, tokens.length - 1); + return strip(tokens); + break; + case 'number': + let lastCharacterOfLastToken = lastToken.value[lastToken.value.length - 1]; + if (lastCharacterOfLastToken === '.' || lastCharacterOfLastToken === '-') { + tokens = tokens.slice(0, tokens.length - 1); + return strip(tokens); + } + case 'string': + let tokenBeforeTheLastToken = tokens[tokens.length - 2]; + if (tokenBeforeTheLastToken?.type === 'delimiter') { + tokens = tokens.slice(0, tokens.length - 1); + return strip(tokens); + } + else if (tokenBeforeTheLastToken?.type === 'brace' && tokenBeforeTheLastToken.value === '{') { + tokens = tokens.slice(0, tokens.length - 1); + return strip(tokens); + } + break; + case 'delimiter': + tokens = tokens.slice(0, tokens.length - 1); + return strip(tokens); + break; + } + return tokens; +}, unstrip = (tokens) => { + let tail = []; + tokens.map((token) => { + if (token.type === 'brace') { + if (token.value === '{') { + tail.push('}'); + } + else { + tail.splice(tail.lastIndexOf('}'), 1); + } + } + if (token.type === 'paren') { + if (token.value === '[') { + tail.push(']'); + } + else { + tail.splice(tail.lastIndexOf(']'), 1); + } + } + }); + if (tail.length > 0) { + tail.reverse().map((item) => { + if (item === '}') { + tokens.push({ + type: 'brace', + value: '}', + }); + } + else if (item === ']') { + tokens.push({ + type: 'paren', + value: ']', + }); + } + }); + } + return tokens; +}, generate = (tokens) => { + let output = ''; + tokens.map((token) => { + switch (token.type) { + case 'string': + output += '"' + token.value + '"'; + break; + default: + output += token.value; + break; + } + }); + return output; +}, partialParse = (input) => JSON.parse(generate(unstrip(strip(tokenize(input))))); +export { partialParse }; +//# sourceMappingURL=parser.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/client.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/client.mjs new file mode 100644 index 00000000..8be4f0c6 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/client.mjs @@ -0,0 +1,559 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var _BaseAnthropic_instances, _a, _BaseAnthropic_encoder, _BaseAnthropic_baseURLOverridden; +import { __classPrivateFieldGet, __classPrivateFieldSet } from "./internal/tslib.mjs"; +import { uuid4 } from "./internal/utils/uuid.mjs"; +import { validatePositiveInteger, isAbsoluteURL, safeJSON } from "./internal/utils/values.mjs"; +import { sleep } from "./internal/utils/sleep.mjs"; +import { castToError, isAbortError } from "./internal/errors.mjs"; +import { getPlatformHeaders } from "./internal/detect-platform.mjs"; +import * as Shims from "./internal/shims.mjs"; +import * as Opts from "./internal/request-options.mjs"; +import { VERSION } from "./version.mjs"; +import * as Errors from "./core/error.mjs"; +import * as Pagination from "./core/pagination.mjs"; +import * as Uploads from "./core/uploads.mjs"; +import * as API from "./resources/index.mjs"; +import { APIPromise } from "./core/api-promise.mjs"; +import { Completions, } from "./resources/completions.mjs"; +import { Models } from "./resources/models.mjs"; +import { Beta, } from "./resources/beta/beta.mjs"; +import { Messages, } from "./resources/messages/messages.mjs"; +import { isRunningInBrowser } from "./internal/detect-platform.mjs"; +import { buildHeaders } from "./internal/headers.mjs"; +import { readEnv } from "./internal/utils/env.mjs"; +import { formatRequestDetails, loggerFor, parseLogLevel, } from "./internal/utils/log.mjs"; +import { isEmptyObj } from "./internal/utils/values.mjs"; +export const HUMAN_PROMPT = '\\n\\nHuman:'; +export const AI_PROMPT = '\\n\\nAssistant:'; +/** + * Base class for Anthropic API clients. + */ +export class BaseAnthropic { + /** + * API Client for interfacing with the Anthropic API. + * + * @param {string | null | undefined} [opts.apiKey=process.env['ANTHROPIC_API_KEY'] ?? null] + * @param {string | null | undefined} [opts.authToken=process.env['ANTHROPIC_AUTH_TOKEN'] ?? null] + * @param {string} [opts.baseURL=process.env['ANTHROPIC_BASE_URL'] ?? https://api.anthropic.com] - Override the default base URL for the API. + * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. + * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. + * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. + */ + constructor({ baseURL = readEnv('ANTHROPIC_BASE_URL'), apiKey = readEnv('ANTHROPIC_API_KEY') ?? null, authToken = readEnv('ANTHROPIC_AUTH_TOKEN') ?? null, ...opts } = {}) { + _BaseAnthropic_instances.add(this); + _BaseAnthropic_encoder.set(this, void 0); + const options = { + apiKey, + authToken, + ...opts, + baseURL: baseURL || `https://api.anthropic.com`, + }; + if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) { + throw new Errors.AnthropicError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n"); + } + this.baseURL = options.baseURL; + this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT /* 10 minutes */; + this.logger = options.logger ?? console; + const defaultLogLevel = 'warn'; + // Set default logLevel early so that we can log a warning in parseLogLevel. + this.logLevel = defaultLogLevel; + this.logLevel = + parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ?? + parseLogLevel(readEnv('ANTHROPIC_LOG'), "process.env['ANTHROPIC_LOG']", this) ?? + defaultLogLevel; + this.fetchOptions = options.fetchOptions; + this.maxRetries = options.maxRetries ?? 2; + this.fetch = options.fetch ?? Shims.getDefaultFetch(); + __classPrivateFieldSet(this, _BaseAnthropic_encoder, Opts.FallbackEncoder, "f"); + this._options = options; + this.apiKey = typeof apiKey === 'string' ? apiKey : null; + this.authToken = authToken; + } + /** + * Create a new client instance re-using the same options given to the current client with optional overriding. + */ + withOptions(options) { + const client = new this.constructor({ + ...this._options, + baseURL: this.baseURL, + maxRetries: this.maxRetries, + timeout: this.timeout, + logger: this.logger, + logLevel: this.logLevel, + fetch: this.fetch, + fetchOptions: this.fetchOptions, + apiKey: this.apiKey, + authToken: this.authToken, + ...options, + }); + return client; + } + defaultQuery() { + return this._options.defaultQuery; + } + validateHeaders({ values, nulls }) { + if (values.get('x-api-key') || values.get('authorization')) { + return; + } + if (this.apiKey && values.get('x-api-key')) { + return; + } + if (nulls.has('x-api-key')) { + return; + } + if (this.authToken && values.get('authorization')) { + return; + } + if (nulls.has('authorization')) { + return; + } + throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted'); + } + async authHeaders(opts) { + return buildHeaders([await this.apiKeyAuth(opts), await this.bearerAuth(opts)]); + } + async apiKeyAuth(opts) { + if (this.apiKey == null) { + return undefined; + } + return buildHeaders([{ 'X-Api-Key': this.apiKey }]); + } + async bearerAuth(opts) { + if (this.authToken == null) { + return undefined; + } + return buildHeaders([{ Authorization: `Bearer ${this.authToken}` }]); + } + /** + * Basic re-implementation of `qs.stringify` for primitive types. + */ + stringifyQuery(query) { + return Object.entries(query) + .filter(([_, value]) => typeof value !== 'undefined') + .map(([key, value]) => { + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`; + } + if (value === null) { + return `${encodeURIComponent(key)}=`; + } + throw new Errors.AnthropicError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`); + }) + .join('&'); + } + getUserAgent() { + return `${this.constructor.name}/JS ${VERSION}`; + } + defaultIdempotencyKey() { + return `stainless-node-retry-${uuid4()}`; + } + makeStatusError(status, error, message, headers) { + return Errors.APIError.generate(status, error, message, headers); + } + buildURL(path, query, defaultBaseURL) { + const baseURL = (!__classPrivateFieldGet(this, _BaseAnthropic_instances, "m", _BaseAnthropic_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL; + const url = isAbsoluteURL(path) ? + new URL(path) + : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path)); + const defaultQuery = this.defaultQuery(); + if (!isEmptyObj(defaultQuery)) { + query = { ...defaultQuery, ...query }; + } + if (typeof query === 'object' && query && !Array.isArray(query)) { + url.search = this.stringifyQuery(query); + } + return url.toString(); + } + _calculateNonstreamingTimeout(maxTokens) { + const defaultTimeout = 10 * 60; + const expectedTimeout = (60 * 60 * maxTokens) / 128000; + if (expectedTimeout > defaultTimeout) { + throw new Errors.AnthropicError('Streaming is required for operations that may take longer than 10 minutes. ' + + 'See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details'); + } + return defaultTimeout * 1000; + } + /** + * Used as a callback for mutating the given `FinalRequestOptions` object. + */ + async prepareOptions(options) { } + /** + * Used as a callback for mutating the given `RequestInit` object. + * + * This is useful for cases where you want to add certain headers based off of + * the request properties, e.g. `method` or `url`. + */ + async prepareRequest(request, { url, options }) { } + get(path, opts) { + return this.methodRequest('get', path, opts); + } + post(path, opts) { + return this.methodRequest('post', path, opts); + } + patch(path, opts) { + return this.methodRequest('patch', path, opts); + } + put(path, opts) { + return this.methodRequest('put', path, opts); + } + delete(path, opts) { + return this.methodRequest('delete', path, opts); + } + methodRequest(method, path, opts) { + return this.request(Promise.resolve(opts).then((opts) => { + return { method, path, ...opts }; + })); + } + request(options, remainingRetries = null) { + return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined)); + } + async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { + const options = await optionsInput; + const maxRetries = options.maxRetries ?? this.maxRetries; + if (retriesRemaining == null) { + retriesRemaining = maxRetries; + } + await this.prepareOptions(options); + const { req, url, timeout } = await this.buildRequest(options, { + retryCount: maxRetries - retriesRemaining, + }); + await this.prepareRequest(req, { url, options }); + /** Not an API request ID, just for correlating local log entries. */ + const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0'); + const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`; + const startTime = Date.now(); + loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({ + retryOfRequestLogID, + method: options.method, + url, + options, + headers: req.headers, + })); + if (options.signal?.aborted) { + throw new Errors.APIUserAbortError(); + } + const controller = new AbortController(); + const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError); + const headersTime = Date.now(); + if (response instanceof globalThis.Error) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + if (options.signal?.aborted) { + throw new Errors.APIUserAbortError(); + } + // detect native connection timeout errors + // deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)" + // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)" + // others do not provide enough information to distinguish timeouts from other connection errors + const isTimeout = isAbortError(response) || + /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : '')); + if (retriesRemaining) { + loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`); + loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message, + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); + } + loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`); + loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message, + })); + if (isTimeout) { + throw new Errors.APIConnectionTimeoutError(); + } + throw new Errors.APIConnectionError({ cause: response }); + } + const specialHeaders = [...response.headers.entries()] + .filter(([name]) => name === 'request-id') + .map(([name, value]) => ', ' + name + ': ' + JSON.stringify(value)) + .join(''); + const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`; + if (!response.ok) { + const shouldRetry = await this.shouldRetry(response); + if (retriesRemaining && shouldRetry) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + // We don't need the body of this response. + await Shims.CancelReadableStream(response.body); + loggerFor(this).info(`${responseInfo} - ${retryMessage}`); + loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime, + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); + } + const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; + loggerFor(this).info(`${responseInfo} - ${retryMessage}`); + const errText = await response.text().catch((err) => castToError(err).message); + const errJSON = safeJSON(errText); + const errMessage = errJSON ? undefined : errText; + loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + message: errMessage, + durationMs: Date.now() - startTime, + })); + const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); + throw err; + } + loggerFor(this).info(responseInfo); + loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime, + })); + return { response, options, controller, requestLogID, retryOfRequestLogID, startTime }; + } + getAPIList(path, Page, opts) { + return this.requestAPIList(Page, opts && 'then' in opts ? + opts.then((opts) => ({ method: 'get', path, ...opts })) + : { method: 'get', path, ...opts }); + } + requestAPIList(Page, options) { + const request = this.makeRequest(options, null, undefined); + return new Pagination.PagePromise(this, request, Page); + } + async fetchWithTimeout(url, init, ms, controller) { + const { signal, method, ...options } = init || {}; + // Avoid creating a closure over `this`, `init`, or `options` to prevent memory leaks. + // An arrow function like `() => controller.abort()` captures the surrounding scope, + // which includes the request body and other large objects. When the user passes a + // long-lived AbortSignal, the listener prevents those objects from being GC'd for + // the lifetime of the signal. Using `.bind()` only retains a reference to the + // controller itself. + const abort = this._makeAbort(controller); + if (signal) + signal.addEventListener('abort', abort, { once: true }); + const timeout = setTimeout(abort, ms); + const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) || + (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body); + const fetchOptions = { + signal: controller.signal, + ...(isReadableBody ? { duplex: 'half' } : {}), + method: 'GET', + ...options, + }; + if (method) { + // Custom methods like 'patch' need to be uppercased + // See https://github.com/nodejs/undici/issues/2294 + fetchOptions.method = method.toUpperCase(); + } + try { + // use undefined this binding; fetch errors if bound to something else in browser/cloudflare + return await this.fetch.call(undefined, url, fetchOptions); + } + finally { + clearTimeout(timeout); + } + } + async shouldRetry(response) { + // Note this is not a standard header. + const shouldRetryHeader = response.headers.get('x-should-retry'); + // If the server explicitly says whether or not to retry, obey. + if (shouldRetryHeader === 'true') + return true; + if (shouldRetryHeader === 'false') + return false; + // Retry on request timeouts. + if (response.status === 408) + return true; + // Retry on lock timeouts. + if (response.status === 409) + return true; + // Retry on rate limits. + if (response.status === 429) + return true; + // Retry internal errors. + if (response.status >= 500) + return true; + return false; + } + async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) { + let timeoutMillis; + // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it. + const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms'); + if (retryAfterMillisHeader) { + const timeoutMs = parseFloat(retryAfterMillisHeader); + if (!Number.isNaN(timeoutMs)) { + timeoutMillis = timeoutMs; + } + } + // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After + const retryAfterHeader = responseHeaders?.get('retry-after'); + if (retryAfterHeader && !timeoutMillis) { + const timeoutSeconds = parseFloat(retryAfterHeader); + if (!Number.isNaN(timeoutSeconds)) { + timeoutMillis = timeoutSeconds * 1000; + } + else { + timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); + } + } + // If the API asks us to wait a certain amount of time (and it's a reasonable amount), + // just do what it says, but otherwise calculate a default + if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) { + const maxRetries = options.maxRetries ?? this.maxRetries; + timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); + } + await sleep(timeoutMillis); + return this.makeRequest(options, retriesRemaining - 1, requestLogID); + } + calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { + const initialRetryDelay = 0.5; + const maxRetryDelay = 8.0; + const numRetries = maxRetries - retriesRemaining; + // Apply exponential backoff, but not more than the max. + const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); + // Apply some jitter, take up to at most 25 percent of the retry time. + const jitter = 1 - Math.random() * 0.25; + return sleepSeconds * jitter * 1000; + } + calculateNonstreamingTimeout(maxTokens, maxNonstreamingTokens) { + const maxTime = 60 * 60 * 1000; // 60 minutes + const defaultTime = 60 * 10 * 1000; // 10 minutes + const expectedTime = (maxTime * maxTokens) / 128000; + if (expectedTime > defaultTime || (maxNonstreamingTokens != null && maxTokens > maxNonstreamingTokens)) { + throw new Errors.AnthropicError('Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details'); + } + return defaultTime; + } + async buildRequest(inputOptions, { retryCount = 0 } = {}) { + const options = { ...inputOptions }; + const { method, path, query, defaultBaseURL } = options; + const url = this.buildURL(path, query, defaultBaseURL); + if ('timeout' in options) + validatePositiveInteger('timeout', options.timeout); + options.timeout = options.timeout ?? this.timeout; + const { bodyHeaders, body } = this.buildBody({ options }); + const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); + const req = { + method, + headers: reqHeaders, + ...(options.signal && { signal: options.signal }), + ...(globalThis.ReadableStream && + body instanceof globalThis.ReadableStream && { duplex: 'half' }), + ...(body && { body }), + ...(this.fetchOptions ?? {}), + ...(options.fetchOptions ?? {}), + }; + return { req, url, timeout: options.timeout }; + } + async buildHeaders({ options, method, bodyHeaders, retryCount, }) { + let idempotencyHeaders = {}; + if (this.idempotencyHeader && method !== 'get') { + if (!options.idempotencyKey) + options.idempotencyKey = this.defaultIdempotencyKey(); + idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; + } + const headers = buildHeaders([ + idempotencyHeaders, + { + Accept: 'application/json', + 'User-Agent': this.getUserAgent(), + 'X-Stainless-Retry-Count': String(retryCount), + ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}), + ...getPlatformHeaders(), + ...(this._options.dangerouslyAllowBrowser ? + { 'anthropic-dangerous-direct-browser-access': 'true' } + : undefined), + 'anthropic-version': '2023-06-01', + }, + await this.authHeaders(options), + this._options.defaultHeaders, + bodyHeaders, + options.headers, + ]); + this.validateHeaders(headers); + return headers.values; + } + _makeAbort(controller) { + // note: we can't just inline this method inside `fetchWithTimeout()` because then the closure + // would capture all request options, and cause a memory leak. + return () => controller.abort(); + } + buildBody({ options: { body, headers: rawHeaders } }) { + if (!body) { + return { bodyHeaders: undefined, body: undefined }; + } + const headers = buildHeaders([rawHeaders]); + if ( + // Pass raw type verbatim + ArrayBuffer.isView(body) || + body instanceof ArrayBuffer || + body instanceof DataView || + (typeof body === 'string' && + // Preserve legacy string encoding behavior for now + headers.values.has('content-type')) || + // `Blob` is superset of `File` + (globalThis.Blob && body instanceof globalThis.Blob) || + // `FormData` -> `multipart/form-data` + body instanceof FormData || + // `URLSearchParams` -> `application/x-www-form-urlencoded` + body instanceof URLSearchParams || + // Send chunked stream (each chunk has own `length`) + (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) { + return { bodyHeaders: undefined, body: body }; + } + else if (typeof body === 'object' && + (Symbol.asyncIterator in body || + (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) { + return { bodyHeaders: undefined, body: Shims.ReadableStreamFrom(body) }; + } + else { + return __classPrivateFieldGet(this, _BaseAnthropic_encoder, "f").call(this, { body, headers }); + } + } +} +_a = BaseAnthropic, _BaseAnthropic_encoder = new WeakMap(), _BaseAnthropic_instances = new WeakSet(), _BaseAnthropic_baseURLOverridden = function _BaseAnthropic_baseURLOverridden() { + return this.baseURL !== 'https://api.anthropic.com'; +}; +BaseAnthropic.Anthropic = _a; +BaseAnthropic.HUMAN_PROMPT = HUMAN_PROMPT; +BaseAnthropic.AI_PROMPT = AI_PROMPT; +BaseAnthropic.DEFAULT_TIMEOUT = 600000; // 10 minutes +BaseAnthropic.AnthropicError = Errors.AnthropicError; +BaseAnthropic.APIError = Errors.APIError; +BaseAnthropic.APIConnectionError = Errors.APIConnectionError; +BaseAnthropic.APIConnectionTimeoutError = Errors.APIConnectionTimeoutError; +BaseAnthropic.APIUserAbortError = Errors.APIUserAbortError; +BaseAnthropic.NotFoundError = Errors.NotFoundError; +BaseAnthropic.ConflictError = Errors.ConflictError; +BaseAnthropic.RateLimitError = Errors.RateLimitError; +BaseAnthropic.BadRequestError = Errors.BadRequestError; +BaseAnthropic.AuthenticationError = Errors.AuthenticationError; +BaseAnthropic.InternalServerError = Errors.InternalServerError; +BaseAnthropic.PermissionDeniedError = Errors.PermissionDeniedError; +BaseAnthropic.UnprocessableEntityError = Errors.UnprocessableEntityError; +BaseAnthropic.toFile = Uploads.toFile; +/** + * API Client for interfacing with the Anthropic API. + */ +export class Anthropic extends BaseAnthropic { + constructor() { + super(...arguments); + this.completions = new API.Completions(this); + this.messages = new API.Messages(this); + this.models = new API.Models(this); + this.beta = new API.Beta(this); + } +} +Anthropic.Completions = Completions; +Anthropic.Messages = Messages; +Anthropic.Models = Models; +Anthropic.Beta = Beta; +//# sourceMappingURL=client.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/core/api-promise.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/core/api-promise.mjs new file mode 100644 index 00000000..3d67649a --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/core/api-promise.mjs @@ -0,0 +1,72 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var _APIPromise_client; +import { __classPrivateFieldGet, __classPrivateFieldSet } from "../internal/tslib.mjs"; +import { defaultParseResponse, addRequestID, } from "../internal/parse.mjs"; +/** + * A subclass of `Promise` providing additional helper methods + * for interacting with the SDK. + */ +export class APIPromise extends Promise { + constructor(client, responsePromise, parseResponse = defaultParseResponse) { + super((resolve) => { + // this is maybe a bit weird but this has to be a no-op to not implicitly + // parse the response body; instead .then, .catch, .finally are overridden + // to parse the response + resolve(null); + }); + this.responsePromise = responsePromise; + this.parseResponse = parseResponse; + _APIPromise_client.set(this, void 0); + __classPrivateFieldSet(this, _APIPromise_client, client, "f"); + } + _thenUnwrap(transform) { + return new APIPromise(__classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client, props) => addRequestID(transform(await this.parseResponse(client, props), props), props.response)); + } + /** + * Gets the raw `Response` instance instead of parsing the response + * data. + * + * If you want to parse the response body but still get the `Response` + * instance, you can use {@link withResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + asResponse() { + return this.responsePromise.then((p) => p.response); + } + /** + * Gets the parsed response data, the raw `Response` instance and the ID of the request, + * returned via the `request-id` header which is useful for debugging requests and resporting + * issues to Anthropic. + * + * If you just want to get the raw `Response` instance without parsing it, + * you can use {@link asResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + async withResponse() { + const [data, response] = await Promise.all([this.parse(), this.asResponse()]); + return { data, response, request_id: response.headers.get('request-id') }; + } + parse() { + if (!this.parsedPromise) { + this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet(this, _APIPromise_client, "f"), data)); + } + return this.parsedPromise; + } + then(onfulfilled, onrejected) { + return this.parse().then(onfulfilled, onrejected); + } + catch(onrejected) { + return this.parse().catch(onrejected); + } + finally(onfinally) { + return this.parse().finally(onfinally); + } +} +_APIPromise_client = new WeakMap(); +//# sourceMappingURL=api-promise.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/core/error.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/core/error.mjs new file mode 100644 index 00000000..b2e189f8 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/core/error.mjs @@ -0,0 +1,98 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { castToError } from "../internal/errors.mjs"; +export class AnthropicError extends Error { +} +export class APIError extends AnthropicError { + constructor(status, error, message, headers) { + super(`${APIError.makeMessage(status, error, message)}`); + this.status = status; + this.headers = headers; + this.requestID = headers?.get('request-id'); + this.error = error; + } + static makeMessage(status, error, message) { + const msg = error?.message ? + typeof error.message === 'string' ? + error.message + : JSON.stringify(error.message) + : error ? JSON.stringify(error) + : message; + if (status && msg) { + return `${status} ${msg}`; + } + if (status) { + return `${status} status code (no body)`; + } + if (msg) { + return msg; + } + return '(no status code or body)'; + } + static generate(status, errorResponse, message, headers) { + if (!status || !headers) { + return new APIConnectionError({ message, cause: castToError(errorResponse) }); + } + const error = errorResponse; + if (status === 400) { + return new BadRequestError(status, error, message, headers); + } + if (status === 401) { + return new AuthenticationError(status, error, message, headers); + } + if (status === 403) { + return new PermissionDeniedError(status, error, message, headers); + } + if (status === 404) { + return new NotFoundError(status, error, message, headers); + } + if (status === 409) { + return new ConflictError(status, error, message, headers); + } + if (status === 422) { + return new UnprocessableEntityError(status, error, message, headers); + } + if (status === 429) { + return new RateLimitError(status, error, message, headers); + } + if (status >= 500) { + return new InternalServerError(status, error, message, headers); + } + return new APIError(status, error, message, headers); + } +} +export class APIUserAbortError extends APIError { + constructor({ message } = {}) { + super(undefined, undefined, message || 'Request was aborted.', undefined); + } +} +export class APIConnectionError extends APIError { + constructor({ message, cause }) { + super(undefined, undefined, message || 'Connection error.', undefined); + // in some environments the 'cause' property is already declared + // @ts-ignore + if (cause) + this.cause = cause; + } +} +export class APIConnectionTimeoutError extends APIConnectionError { + constructor({ message } = {}) { + super({ message: message ?? 'Request timed out.' }); + } +} +export class BadRequestError extends APIError { +} +export class AuthenticationError extends APIError { +} +export class PermissionDeniedError extends APIError { +} +export class NotFoundError extends APIError { +} +export class ConflictError extends APIError { +} +export class UnprocessableEntityError extends APIError { +} +export class RateLimitError extends APIError { +} +export class InternalServerError extends APIError { +} +//# sourceMappingURL=error.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/core/pagination.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/core/pagination.mjs new file mode 100644 index 00000000..3c9870f5 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/core/pagination.mjs @@ -0,0 +1,177 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var _AbstractPage_client; +import { __classPrivateFieldGet, __classPrivateFieldSet } from "../internal/tslib.mjs"; +import { AnthropicError } from "./error.mjs"; +import { defaultParseResponse } from "../internal/parse.mjs"; +import { APIPromise } from "./api-promise.mjs"; +import { maybeObj } from "../internal/utils/values.mjs"; +export class AbstractPage { + constructor(client, response, body, options) { + _AbstractPage_client.set(this, void 0); + __classPrivateFieldSet(this, _AbstractPage_client, client, "f"); + this.options = options; + this.response = response; + this.body = body; + } + hasNextPage() { + const items = this.getPaginatedItems(); + if (!items.length) + return false; + return this.nextPageRequestOptions() != null; + } + async getNextPage() { + const nextOptions = this.nextPageRequestOptions(); + if (!nextOptions) { + throw new AnthropicError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.'); + } + return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions); + } + async *iterPages() { + let page = this; + yield page; + while (page.hasNextPage()) { + page = await page.getNextPage(); + yield page; + } + } + async *[(_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() { + for await (const page of this.iterPages()) { + for (const item of page.getPaginatedItems()) { + yield item; + } + } + } +} +/** + * This subclass of Promise will resolve to an instantiated Page once the request completes. + * + * It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ +export class PagePromise extends APIPromise { + constructor(client, request, Page) { + super(client, request, async (client, props) => new Page(client, props.response, await defaultParseResponse(client, props), props.options)); + } + /** + * Allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ + async *[Symbol.asyncIterator]() { + const page = await this; + for await (const item of page) { + yield item; + } + } +} +export class Page extends AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + this.has_more = body.has_more || false; + this.first_id = body.first_id || null; + this.last_id = body.last_id || null; + } + getPaginatedItems() { + return this.data ?? []; + } + hasNextPage() { + if (this.has_more === false) { + return false; + } + return super.hasNextPage(); + } + nextPageRequestOptions() { + if (this.options.query?.['before_id']) { + // in reverse + const first_id = this.first_id; + if (!first_id) { + return null; + } + return { + ...this.options, + query: { + ...maybeObj(this.options.query), + before_id: first_id, + }, + }; + } + const cursor = this.last_id; + if (!cursor) { + return null; + } + return { + ...this.options, + query: { + ...maybeObj(this.options.query), + after_id: cursor, + }, + }; + } +} +export class TokenPage extends AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + this.has_more = body.has_more || false; + this.next_page = body.next_page || null; + } + getPaginatedItems() { + return this.data ?? []; + } + hasNextPage() { + if (this.has_more === false) { + return false; + } + return super.hasNextPage(); + } + nextPageRequestOptions() { + const cursor = this.next_page; + if (!cursor) { + return null; + } + return { + ...this.options, + query: { + ...maybeObj(this.options.query), + page_token: cursor, + }, + }; + } +} +export class PageCursor extends AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + this.has_more = body.has_more || false; + this.next_page = body.next_page || null; + } + getPaginatedItems() { + return this.data ?? []; + } + hasNextPage() { + if (this.has_more === false) { + return false; + } + return super.hasNextPage(); + } + nextPageRequestOptions() { + const cursor = this.next_page; + if (!cursor) { + return null; + } + return { + ...this.options, + query: { + ...maybeObj(this.options.query), + page: cursor, + }, + }; + } +} +//# sourceMappingURL=pagination.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/core/resource.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/core/resource.mjs new file mode 100644 index 00000000..98ee0dc7 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/core/resource.mjs @@ -0,0 +1,7 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +export class APIResource { + constructor(client) { + this._client = client; + } +} +//# sourceMappingURL=resource.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/core/streaming.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/core/streaming.mjs new file mode 100644 index 00000000..1a73032a --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/core/streaming.mjs @@ -0,0 +1,283 @@ +var _Stream_client; +import { __classPrivateFieldGet, __classPrivateFieldSet } from "../internal/tslib.mjs"; +import { AnthropicError } from "./error.mjs"; +import { makeReadableStream } from "../internal/shims.mjs"; +import { findDoubleNewlineIndex, LineDecoder } from "../internal/decoders/line.mjs"; +import { ReadableStreamToAsyncIterable } from "../internal/shims.mjs"; +import { isAbortError } from "../internal/errors.mjs"; +import { safeJSON } from "../internal/utils/values.mjs"; +import { encodeUTF8 } from "../internal/utils/bytes.mjs"; +import { loggerFor } from "../internal/utils/log.mjs"; +import { APIError } from "./error.mjs"; +export class Stream { + constructor(iterator, controller, client) { + this.iterator = iterator; + _Stream_client.set(this, void 0); + this.controller = controller; + __classPrivateFieldSet(this, _Stream_client, client, "f"); + } + static fromSSEResponse(response, controller, client) { + let consumed = false; + const logger = client ? loggerFor(client) : console; + async function* iterator() { + if (consumed) { + throw new AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); + } + consumed = true; + let done = false; + try { + for await (const sse of _iterSSEMessages(response, controller)) { + if (sse.event === 'completion') { + try { + yield JSON.parse(sse.data); + } + catch (e) { + logger.error(`Could not parse message into JSON:`, sse.data); + logger.error(`From chunk:`, sse.raw); + throw e; + } + } + if (sse.event === 'message_start' || + sse.event === 'message_delta' || + sse.event === 'message_stop' || + sse.event === 'content_block_start' || + sse.event === 'content_block_delta' || + sse.event === 'content_block_stop') { + try { + yield JSON.parse(sse.data); + } + catch (e) { + logger.error(`Could not parse message into JSON:`, sse.data); + logger.error(`From chunk:`, sse.raw); + throw e; + } + } + if (sse.event === 'ping') { + continue; + } + if (sse.event === 'error') { + throw new APIError(undefined, safeJSON(sse.data) ?? sse.data, undefined, response.headers); + } + } + done = true; + } + catch (e) { + // If the user calls `stream.controller.abort()`, we should exit without throwing. + if (isAbortError(e)) + return; + throw e; + } + finally { + // If the user `break`s, abort the ongoing request. + if (!done) + controller.abort(); + } + } + return new Stream(iterator, controller, client); + } + /** + * Generates a Stream from a newline-separated ReadableStream + * where each item is a JSON value. + */ + static fromReadableStream(readableStream, controller, client) { + let consumed = false; + async function* iterLines() { + const lineDecoder = new LineDecoder(); + const iter = ReadableStreamToAsyncIterable(readableStream); + for await (const chunk of iter) { + for (const line of lineDecoder.decode(chunk)) { + yield line; + } + } + for (const line of lineDecoder.flush()) { + yield line; + } + } + async function* iterator() { + if (consumed) { + throw new AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); + } + consumed = true; + let done = false; + try { + for await (const line of iterLines()) { + if (done) + continue; + if (line) + yield JSON.parse(line); + } + done = true; + } + catch (e) { + // If the user calls `stream.controller.abort()`, we should exit without throwing. + if (isAbortError(e)) + return; + throw e; + } + finally { + // If the user `break`s, abort the ongoing request. + if (!done) + controller.abort(); + } + } + return new Stream(iterator, controller, client); + } + [(_Stream_client = new WeakMap(), Symbol.asyncIterator)]() { + return this.iterator(); + } + /** + * Splits the stream into two streams which can be + * independently read from at different speeds. + */ + tee() { + const left = []; + const right = []; + const iterator = this.iterator(); + const teeIterator = (queue) => { + return { + next: () => { + if (queue.length === 0) { + const result = iterator.next(); + left.push(result); + right.push(result); + } + return queue.shift(); + }, + }; + }; + return [ + new Stream(() => teeIterator(left), this.controller, __classPrivateFieldGet(this, _Stream_client, "f")), + new Stream(() => teeIterator(right), this.controller, __classPrivateFieldGet(this, _Stream_client, "f")), + ]; + } + /** + * Converts this stream to a newline-separated ReadableStream of + * JSON stringified values in the stream + * which can be turned back into a Stream with `Stream.fromReadableStream()`. + */ + toReadableStream() { + const self = this; + let iter; + return makeReadableStream({ + async start() { + iter = self[Symbol.asyncIterator](); + }, + async pull(ctrl) { + try { + const { value, done } = await iter.next(); + if (done) + return ctrl.close(); + const bytes = encodeUTF8(JSON.stringify(value) + '\n'); + ctrl.enqueue(bytes); + } + catch (err) { + ctrl.error(err); + } + }, + async cancel() { + await iter.return?.(); + }, + }); + } +} +export async function* _iterSSEMessages(response, controller) { + if (!response.body) { + controller.abort(); + if (typeof globalThis.navigator !== 'undefined' && + globalThis.navigator.product === 'ReactNative') { + throw new AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`); + } + throw new AnthropicError(`Attempted to iterate over a response with no body`); + } + const sseDecoder = new SSEDecoder(); + const lineDecoder = new LineDecoder(); + const iter = ReadableStreamToAsyncIterable(response.body); + for await (const sseChunk of iterSSEChunks(iter)) { + for (const line of lineDecoder.decode(sseChunk)) { + const sse = sseDecoder.decode(line); + if (sse) + yield sse; + } + } + for (const line of lineDecoder.flush()) { + const sse = sseDecoder.decode(line); + if (sse) + yield sse; + } +} +/** + * Given an async iterable iterator, iterates over it and yields full + * SSE chunks, i.e. yields when a double new-line is encountered. + */ +async function* iterSSEChunks(iterator) { + let data = new Uint8Array(); + for await (const chunk of iterator) { + if (chunk == null) { + continue; + } + const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) + : typeof chunk === 'string' ? encodeUTF8(chunk) + : chunk; + let newData = new Uint8Array(data.length + binaryChunk.length); + newData.set(data); + newData.set(binaryChunk, data.length); + data = newData; + let patternIndex; + while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) { + yield data.slice(0, patternIndex); + data = data.slice(patternIndex); + } + } + if (data.length > 0) { + yield data; + } +} +class SSEDecoder { + constructor() { + this.event = null; + this.data = []; + this.chunks = []; + } + decode(line) { + if (line.endsWith('\r')) { + line = line.substring(0, line.length - 1); + } + if (!line) { + // empty line and we didn't previously encounter any messages + if (!this.event && !this.data.length) + return null; + const sse = { + event: this.event, + data: this.data.join('\n'), + raw: this.chunks, + }; + this.event = null; + this.data = []; + this.chunks = []; + return sse; + } + this.chunks.push(line); + if (line.startsWith(':')) { + return null; + } + let [fieldname, _, value] = partition(line, ':'); + if (value.startsWith(' ')) { + value = value.substring(1); + } + if (fieldname === 'event') { + this.event = value; + } + else if (fieldname === 'data') { + this.data.push(value); + } + return null; + } +} +function partition(str, delimiter) { + const index = str.indexOf(delimiter); + if (index !== -1) { + return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)]; + } + return [str, '', '']; +} +//# sourceMappingURL=streaming.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/core/uploads.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/core/uploads.mjs new file mode 100644 index 00000000..40d3593e --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/core/uploads.mjs @@ -0,0 +1,2 @@ +export { toFile } from "../internal/to-file.mjs"; +//# sourceMappingURL=uploads.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/error.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/error.mjs new file mode 100644 index 00000000..350c6d43 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/error.mjs @@ -0,0 +1,2 @@ +export * from "./core/error.mjs"; +//# sourceMappingURL=error.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/index.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/index.mjs new file mode 100644 index 00000000..5d7711c4 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/index.mjs @@ -0,0 +1,8 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +export { Anthropic as default } from "./client.mjs"; +export { toFile } from "./core/uploads.mjs"; +export { APIPromise } from "./core/api-promise.mjs"; +export { BaseAnthropic, Anthropic, HUMAN_PROMPT, AI_PROMPT } from "./client.mjs"; +export { PagePromise } from "./core/pagination.mjs"; +export { AnthropicError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, NotFoundError, ConflictError, RateLimitError, BadRequestError, AuthenticationError, InternalServerError, PermissionDeniedError, UnprocessableEntityError, } from "./core/error.mjs"; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/constants.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/constants.mjs new file mode 100644 index 00000000..4b001aae --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/constants.mjs @@ -0,0 +1,15 @@ +// File containing shared constants +/** + * Model-specific timeout constraints for non-streaming requests + */ +export const MODEL_NONSTREAMING_TOKENS = { + 'claude-opus-4-20250514': 8192, + 'claude-opus-4-0': 8192, + 'claude-4-opus-20250514': 8192, + 'anthropic.claude-opus-4-20250514-v1:0': 8192, + 'claude-opus-4@20250514': 8192, + 'claude-opus-4-1-20250805': 8192, + 'anthropic.claude-opus-4-1-20250805-v1:0': 8192, + 'claude-opus-4-1@20250805': 8192, +}; +//# sourceMappingURL=constants.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/decoders/jsonl.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/decoders/jsonl.mjs new file mode 100644 index 00000000..6d3f4b9e --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/decoders/jsonl.mjs @@ -0,0 +1,35 @@ +import { AnthropicError } from "../../core/error.mjs"; +import { ReadableStreamToAsyncIterable } from "../shims.mjs"; +import { LineDecoder } from "./line.mjs"; +export class JSONLDecoder { + constructor(iterator, controller) { + this.iterator = iterator; + this.controller = controller; + } + async *decoder() { + const lineDecoder = new LineDecoder(); + for await (const chunk of this.iterator) { + for (const line of lineDecoder.decode(chunk)) { + yield JSON.parse(line); + } + } + for (const line of lineDecoder.flush()) { + yield JSON.parse(line); + } + } + [Symbol.asyncIterator]() { + return this.decoder(); + } + static fromResponse(response, controller) { + if (!response.body) { + controller.abort(); + if (typeof globalThis.navigator !== 'undefined' && + globalThis.navigator.product === 'ReactNative') { + throw new AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`); + } + throw new AnthropicError(`Attempted to iterate over a response with no body`); + } + return new JSONLDecoder(ReadableStreamToAsyncIterable(response.body), controller); + } +} +//# sourceMappingURL=jsonl.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs new file mode 100644 index 00000000..3e1207c0 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs @@ -0,0 +1,108 @@ +var _LineDecoder_buffer, _LineDecoder_carriageReturnIndex; +import { __classPrivateFieldGet, __classPrivateFieldSet } from "../tslib.mjs"; +import { concatBytes, decodeUTF8, encodeUTF8 } from "../utils/bytes.mjs"; +/** + * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally + * reading lines from text. + * + * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258 + */ +export class LineDecoder { + constructor() { + _LineDecoder_buffer.set(this, void 0); + _LineDecoder_carriageReturnIndex.set(this, void 0); + __classPrivateFieldSet(this, _LineDecoder_buffer, new Uint8Array(), "f"); + __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); + } + decode(chunk) { + if (chunk == null) { + return []; + } + const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) + : typeof chunk === 'string' ? encodeUTF8(chunk) + : chunk; + __classPrivateFieldSet(this, _LineDecoder_buffer, concatBytes([__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), binaryChunk]), "f"); + const lines = []; + let patternIndex; + while ((patternIndex = findNewlineIndex(__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f"))) != null) { + if (patternIndex.carriage && __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") == null) { + // skip until we either get a corresponding `\n`, a new `\r` or nothing + __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, patternIndex.index, "f"); + continue; + } + // we got double \r or \rtext\n + if (__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") != null && + (patternIndex.index !== __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") + 1 || patternIndex.carriage)) { + lines.push(decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") - 1))); + __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f")), "f"); + __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); + continue; + } + const endIndex = __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding; + const line = decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, endIndex)); + lines.push(line); + __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(patternIndex.index), "f"); + __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); + } + return lines; + } + flush() { + if (!__classPrivateFieldGet(this, _LineDecoder_buffer, "f").length) { + return []; + } + return this.decode('\n'); + } +} +_LineDecoder_buffer = new WeakMap(), _LineDecoder_carriageReturnIndex = new WeakMap(); +// prettier-ignore +LineDecoder.NEWLINE_CHARS = new Set(['\n', '\r']); +LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g; +/** + * This function searches the buffer for the end patterns, (\r or \n) + * and returns an object with the index preceding the matched newline and the + * index after the newline char. `null` is returned if no new line is found. + * + * ```ts + * findNewLineIndex('abc\ndef') -> { preceding: 2, index: 3 } + * ``` + */ +function findNewlineIndex(buffer, startIndex) { + const newline = 0x0a; // \n + const carriage = 0x0d; // \r + for (let i = startIndex ?? 0; i < buffer.length; i++) { + if (buffer[i] === newline) { + return { preceding: i, index: i + 1, carriage: false }; + } + if (buffer[i] === carriage) { + return { preceding: i, index: i + 1, carriage: true }; + } + } + return null; +} +export function findDoubleNewlineIndex(buffer) { + // This function searches the buffer for the end patterns (\r\r, \n\n, \r\n\r\n) + // and returns the index right after the first occurrence of any pattern, + // or -1 if none of the patterns are found. + const newline = 0x0a; // \n + const carriage = 0x0d; // \r + for (let i = 0; i < buffer.length - 1; i++) { + if (buffer[i] === newline && buffer[i + 1] === newline) { + // \n\n + return i + 2; + } + if (buffer[i] === carriage && buffer[i + 1] === carriage) { + // \r\r + return i + 2; + } + if (buffer[i] === carriage && + buffer[i + 1] === newline && + i + 3 < buffer.length && + buffer[i + 2] === carriage && + buffer[i + 3] === newline) { + // \r\n\r\n + return i + 4; + } + } + return -1; +} +//# sourceMappingURL=line.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs new file mode 100644 index 00000000..7e828ecf --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs @@ -0,0 +1,157 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { VERSION } from "../version.mjs"; +export const isRunningInBrowser = () => { + return ( + // @ts-ignore + typeof window !== 'undefined' && + // @ts-ignore + typeof window.document !== 'undefined' && + // @ts-ignore + typeof navigator !== 'undefined'); +}; +/** + * Note this does not detect 'browser'; for that, use getBrowserInfo(). + */ +function getDetectedPlatform() { + if (typeof Deno !== 'undefined' && Deno.build != null) { + return 'deno'; + } + if (typeof EdgeRuntime !== 'undefined') { + return 'edge'; + } + if (Object.prototype.toString.call(typeof globalThis.process !== 'undefined' ? globalThis.process : 0) === '[object process]') { + return 'node'; + } + return 'unknown'; +} +const getPlatformProperties = () => { + const detectedPlatform = getDetectedPlatform(); + if (detectedPlatform === 'deno') { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': normalizePlatform(Deno.build.os), + 'X-Stainless-Arch': normalizeArch(Deno.build.arch), + 'X-Stainless-Runtime': 'deno', + 'X-Stainless-Runtime-Version': typeof Deno.version === 'string' ? Deno.version : Deno.version?.deno ?? 'unknown', + }; + } + if (typeof EdgeRuntime !== 'undefined') { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': `other:${EdgeRuntime}`, + 'X-Stainless-Runtime': 'edge', + 'X-Stainless-Runtime-Version': globalThis.process.version, + }; + } + // Check if Node.js + if (detectedPlatform === 'node') { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': normalizePlatform(globalThis.process.platform ?? 'unknown'), + 'X-Stainless-Arch': normalizeArch(globalThis.process.arch ?? 'unknown'), + 'X-Stainless-Runtime': 'node', + 'X-Stainless-Runtime-Version': globalThis.process.version ?? 'unknown', + }; + } + const browserInfo = getBrowserInfo(); + if (browserInfo) { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': 'unknown', + 'X-Stainless-Runtime': `browser:${browserInfo.browser}`, + 'X-Stainless-Runtime-Version': browserInfo.version, + }; + } + // TODO add support for Cloudflare workers, etc. + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': 'unknown', + 'X-Stainless-Runtime': 'unknown', + 'X-Stainless-Runtime-Version': 'unknown', + }; +}; +// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts +function getBrowserInfo() { + if (typeof navigator === 'undefined' || !navigator) { + return null; + } + // NOTE: The order matters here! + const browserPatterns = [ + { key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }, + ]; + // Find the FIRST matching browser + for (const { key, pattern } of browserPatterns) { + const match = pattern.exec(navigator.userAgent); + if (match) { + const major = match[1] || 0; + const minor = match[2] || 0; + const patch = match[3] || 0; + return { browser: key, version: `${major}.${minor}.${patch}` }; + } + } + return null; +} +const normalizeArch = (arch) => { + // Node docs: + // - https://nodejs.org/api/process.html#processarch + // Deno docs: + // - https://doc.deno.land/deno/stable/~/Deno.build + if (arch === 'x32') + return 'x32'; + if (arch === 'x86_64' || arch === 'x64') + return 'x64'; + if (arch === 'arm') + return 'arm'; + if (arch === 'aarch64' || arch === 'arm64') + return 'arm64'; + if (arch) + return `other:${arch}`; + return 'unknown'; +}; +const normalizePlatform = (platform) => { + // Node platforms: + // - https://nodejs.org/api/process.html#processplatform + // Deno platforms: + // - https://doc.deno.land/deno/stable/~/Deno.build + // - https://github.com/denoland/deno/issues/14799 + platform = platform.toLowerCase(); + // NOTE: this iOS check is untested and may not work + // Node does not work natively on IOS, there is a fork at + // https://github.com/nodejs-mobile/nodejs-mobile + // however it is unknown at the time of writing how to detect if it is running + if (platform.includes('ios')) + return 'iOS'; + if (platform === 'android') + return 'Android'; + if (platform === 'darwin') + return 'MacOS'; + if (platform === 'win32') + return 'Windows'; + if (platform === 'freebsd') + return 'FreeBSD'; + if (platform === 'openbsd') + return 'OpenBSD'; + if (platform === 'linux') + return 'Linux'; + if (platform) + return `Other:${platform}`; + return 'Unknown'; +}; +let _platformHeaders; +export const getPlatformHeaders = () => { + return (_platformHeaders ?? (_platformHeaders = getPlatformProperties())); +}; +//# sourceMappingURL=detect-platform.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/errors.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/errors.mjs new file mode 100644 index 00000000..8b7356eb --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/errors.mjs @@ -0,0 +1,36 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +export function isAbortError(err) { + return (typeof err === 'object' && + err !== null && + // Spec-compliant fetch implementations + (('name' in err && err.name === 'AbortError') || + // Expo fetch + ('message' in err && String(err.message).includes('FetchRequestCanceledException')))); +} +export const castToError = (err) => { + if (err instanceof Error) + return err; + if (typeof err === 'object' && err !== null) { + try { + if (Object.prototype.toString.call(err) === '[object Error]') { + // @ts-ignore - not all envs have native support for cause yet + const error = new Error(err.message, err.cause ? { cause: err.cause } : {}); + if (err.stack) + error.stack = err.stack; + // @ts-ignore - not all envs have native support for cause yet + if (err.cause && !error.cause) + error.cause = err.cause; + if (err.name) + error.name = err.name; + return error; + } + } + catch { } + try { + return new Error(JSON.stringify(err)); + } + catch { } + } + return new Error(err); +}; +//# sourceMappingURL=errors.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/headers.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/headers.mjs new file mode 100644 index 00000000..94b059b4 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/headers.mjs @@ -0,0 +1,74 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { isReadonlyArray } from "./utils/values.mjs"; +const brand_privateNullableHeaders = Symbol.for('brand.privateNullableHeaders'); +function* iterateHeaders(headers) { + if (!headers) + return; + if (brand_privateNullableHeaders in headers) { + const { values, nulls } = headers; + yield* values.entries(); + for (const name of nulls) { + yield [name, null]; + } + return; + } + let shouldClear = false; + let iter; + if (headers instanceof Headers) { + iter = headers.entries(); + } + else if (isReadonlyArray(headers)) { + iter = headers; + } + else { + shouldClear = true; + iter = Object.entries(headers ?? {}); + } + for (let row of iter) { + const name = row[0]; + if (typeof name !== 'string') + throw new TypeError('expected header name to be a string'); + const values = isReadonlyArray(row[1]) ? row[1] : [row[1]]; + let didClear = false; + for (const value of values) { + if (value === undefined) + continue; + // Objects keys always overwrite older headers, they never append. + // Yield a null to clear the header before adding the new values. + if (shouldClear && !didClear) { + didClear = true; + yield [name, null]; + } + yield [name, value]; + } + } +} +export const buildHeaders = (newHeaders) => { + const targetHeaders = new Headers(); + const nullHeaders = new Set(); + for (const headers of newHeaders) { + const seenHeaders = new Set(); + for (const [name, value] of iterateHeaders(headers)) { + const lowerName = name.toLowerCase(); + if (!seenHeaders.has(lowerName)) { + targetHeaders.delete(name); + seenHeaders.add(lowerName); + } + if (value === null) { + targetHeaders.delete(name); + nullHeaders.add(lowerName); + } + else { + targetHeaders.append(name, value); + nullHeaders.delete(lowerName); + } + } + } + return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders }; +}; +export const isEmptyHeaders = (headers) => { + for (const _ of iterateHeaders(headers)) + return false; + return true; +}; +//# sourceMappingURL=headers.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/parse.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/parse.mjs new file mode 100644 index 00000000..50a84eda --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/parse.mjs @@ -0,0 +1,56 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { Stream } from "../core/streaming.mjs"; +import { formatRequestDetails, loggerFor } from "./utils/log.mjs"; +export async function defaultParseResponse(client, props) { + const { response, requestLogID, retryOfRequestLogID, startTime } = props; + const body = await (async () => { + if (props.options.stream) { + loggerFor(client).debug('response', response.status, response.url, response.headers, response.body); + // Note: there is an invariant here that isn't represented in the type system + // that if you set `stream: true` the response type must also be `Stream` + if (props.options.__streamClass) { + return props.options.__streamClass.fromSSEResponse(response, props.controller); + } + return Stream.fromSSEResponse(response, props.controller); + } + // fetch refuses to read the body when the status code is 204. + if (response.status === 204) { + return null; + } + if (props.options.__binaryResponse) { + return response; + } + const contentType = response.headers.get('content-type'); + const mediaType = contentType?.split(';')[0]?.trim(); + const isJSON = mediaType?.includes('application/json') || mediaType?.endsWith('+json'); + if (isJSON) { + const contentLength = response.headers.get('content-length'); + if (contentLength === '0') { + // if there is no content we can't do anything + return undefined; + } + const json = await response.json(); + return addRequestID(json, response); + } + const text = await response.text(); + return text; + })(); + loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + body, + durationMs: Date.now() - startTime, + })); + return body; +} +export function addRequestID(value, response) { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + return value; + } + return Object.defineProperty(value, '_request_id', { + value: response.headers.get('request-id'), + enumerable: false, + }); +} +//# sourceMappingURL=parse.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/request-options.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/request-options.mjs new file mode 100644 index 00000000..312df353 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/request-options.mjs @@ -0,0 +1,10 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +export const FallbackEncoder = ({ headers, body }) => { + return { + bodyHeaders: { + 'content-type': 'application/json', + }, + body: JSON.stringify(body), + }; +}; +//# sourceMappingURL=request-options.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/shims.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/shims.mjs new file mode 100644 index 00000000..c511fe86 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/shims.mjs @@ -0,0 +1,85 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +export function getDefaultFetch() { + if (typeof fetch !== 'undefined') { + return fetch; + } + throw new Error('`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`'); +} +export function makeReadableStream(...args) { + const ReadableStream = globalThis.ReadableStream; + if (typeof ReadableStream === 'undefined') { + // Note: All of the platforms / runtimes we officially support already define + // `ReadableStream` as a global, so this should only ever be hit on unsupported runtimes. + throw new Error('`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`'); + } + return new ReadableStream(...args); +} +export function ReadableStreamFrom(iterable) { + let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); + return makeReadableStream({ + start() { }, + async pull(controller) { + const { done, value } = await iter.next(); + if (done) { + controller.close(); + } + else { + controller.enqueue(value); + } + }, + async cancel() { + await iter.return?.(); + }, + }); +} +/** + * Most browsers don't yet have async iterable support for ReadableStream, + * and Node has a very different way of reading bytes from its "ReadableStream". + * + * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490 + */ +export function ReadableStreamToAsyncIterable(stream) { + if (stream[Symbol.asyncIterator]) + return stream; + const reader = stream.getReader(); + return { + async next() { + try { + const result = await reader.read(); + if (result?.done) + reader.releaseLock(); // release lock when stream becomes closed + return result; + } + catch (e) { + reader.releaseLock(); // release lock when stream becomes errored + throw e; + } + }, + async return() { + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; + return { done: true, value: undefined }; + }, + [Symbol.asyncIterator]() { + return this; + }, + }; +} +/** + * Cancels a ReadableStream we don't need to consume. + * See https://undici.nodejs.org/#/?id=garbage-collection + */ +export async function CancelReadableStream(stream) { + if (stream === null || typeof stream !== 'object') + return; + if (stream[Symbol.asyncIterator]) { + await stream[Symbol.asyncIterator]().return?.(); + return; + } + const reader = stream.getReader(); + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; +} +//# sourceMappingURL=shims.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/to-file.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/to-file.mjs new file mode 100644 index 00000000..5644c71e --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/to-file.mjs @@ -0,0 +1,93 @@ +import { getName, makeFile, isAsyncIterable } from "./uploads.mjs"; +import { checkFileSupport } from "./uploads.mjs"; +/** + * This check adds the arrayBuffer() method type because it is available and used at runtime + */ +const isBlobLike = (value) => value != null && + typeof value === 'object' && + typeof value.size === 'number' && + typeof value.type === 'string' && + typeof value.text === 'function' && + typeof value.slice === 'function' && + typeof value.arrayBuffer === 'function'; +/** + * This check adds the arrayBuffer() method type because it is available and used at runtime + */ +const isFileLike = (value) => value != null && + typeof value === 'object' && + typeof value.name === 'string' && + typeof value.lastModified === 'number' && + isBlobLike(value); +const isResponseLike = (value) => value != null && + typeof value === 'object' && + typeof value.url === 'string' && + typeof value.blob === 'function'; +/** + * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats + * @param value the raw content of the file. Can be an {@link Uploadable}, BlobLikePart, or AsyncIterable of BlobLikeParts + * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible + * @param {Object=} options additional properties + * @param {string=} options.type the MIME type of the content + * @param {number=} options.lastModified the last modified timestamp + * @returns a {@link File} with the given properties + */ +export async function toFile(value, name, options) { + checkFileSupport(); + // If it's a promise, resolve it. + value = await value; + name || (name = getName(value, true)); + // If we've been given a `File` we don't need to do anything if the name / options + // have not been customised. + if (isFileLike(value)) { + if (value instanceof File && name == null && options == null) { + return value; + } + return makeFile([await value.arrayBuffer()], name ?? value.name, { + type: value.type, + lastModified: value.lastModified, + ...options, + }); + } + if (isResponseLike(value)) { + const blob = await value.blob(); + name || (name = new URL(value.url).pathname.split(/[\\/]/).pop()); + return makeFile(await getBytes(blob), name, options); + } + const parts = await getBytes(value); + if (!options?.type) { + const type = parts.find((part) => typeof part === 'object' && 'type' in part && part.type); + if (typeof type === 'string') { + options = { ...options, type }; + } + } + return makeFile(parts, name, options); +} +async function getBytes(value) { + let parts = []; + if (typeof value === 'string' || + ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc. + value instanceof ArrayBuffer) { + parts.push(value); + } + else if (isBlobLike(value)) { + parts.push(value instanceof Blob ? value : await value.arrayBuffer()); + } + else if (isAsyncIterable(value) // includes Readable, ReadableStream, etc. + ) { + for await (const chunk of value) { + parts.push(...(await getBytes(chunk))); // TODO, consider validating? + } + } + else { + const constructor = value?.constructor?.name; + throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ''}${propsForError(value)}`); + } + return parts; +} +function propsForError(value) { + if (typeof value !== 'object' || value === null) + return ''; + const props = Object.getOwnPropertyNames(value); + return `; props: [${props.map((p) => `"${p}"`).join(', ')}]`; +} +//# sourceMappingURL=to-file.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/tslib.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/tslib.mjs new file mode 100644 index 00000000..a80a1321 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/tslib.mjs @@ -0,0 +1,17 @@ +function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") + throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) + throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? (f.value = value) : state.set(receiver, value), value; +} +function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) + throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} +export { __classPrivateFieldSet, __classPrivateFieldGet }; diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/uploads.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/uploads.mjs new file mode 100644 index 00000000..24680872 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/uploads.mjs @@ -0,0 +1,135 @@ +import { ReadableStreamFrom } from "./shims.mjs"; +export const checkFileSupport = () => { + if (typeof File === 'undefined') { + const { process } = globalThis; + const isOldNode = typeof process?.versions?.node === 'string' && parseInt(process.versions.node.split('.')) < 20; + throw new Error('`File` is not defined as a global, which is required for file uploads.' + + (isOldNode ? + " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." + : '')); + } +}; +/** + * Construct a `File` instance. This is used to ensure a helpful error is thrown + * for environments that don't define a global `File` yet. + */ +export function makeFile(fileBits, fileName, options) { + checkFileSupport(); + return new File(fileBits, fileName ?? 'unknown_file', options); +} +export function getName(value, stripPath) { + const val = (typeof value === 'object' && + value !== null && + (('name' in value && value.name && String(value.name)) || + ('url' in value && value.url && String(value.url)) || + ('filename' in value && value.filename && String(value.filename)) || + ('path' in value && value.path && String(value.path)))) || + ''; + return stripPath ? val.split(/[\\/]/).pop() || undefined : val; +} +export const isAsyncIterable = (value) => value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function'; +/** + * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value. + * Otherwise returns the request as is. + */ +export const maybeMultipartFormRequestOptions = async (opts, fetch) => { + if (!hasUploadableValue(opts.body)) + return opts; + return { ...opts, body: await createForm(opts.body, fetch) }; +}; +export const multipartFormRequestOptions = async (opts, fetch, stripFilenames = true) => { + return { ...opts, body: await createForm(opts.body, fetch, stripFilenames) }; +}; +const supportsFormDataMap = /* @__PURE__ */ new WeakMap(); +/** + * node-fetch doesn't support the global FormData object in recent node versions. Instead of sending + * properly-encoded form data, it just stringifies the object, resulting in a request body of "[object FormData]". + * This function detects if the fetch function provided supports the global FormData object to avoid + * confusing error messages later on. + */ +function supportsFormData(fetchObject) { + const fetch = typeof fetchObject === 'function' ? fetchObject : fetchObject.fetch; + const cached = supportsFormDataMap.get(fetch); + if (cached) + return cached; + const promise = (async () => { + try { + const FetchResponse = ('Response' in fetch ? + fetch.Response + : (await fetch('data:,')).constructor); + const data = new FormData(); + if (data.toString() === (await new FetchResponse(data).text())) { + return false; + } + return true; + } + catch { + // avoid false negatives + return true; + } + })(); + supportsFormDataMap.set(fetch, promise); + return promise; +} +export const createForm = async (body, fetch, stripFilenames = true) => { + if (!(await supportsFormData(fetch))) { + throw new TypeError('The provided fetch function does not support file uploads with the current global FormData class.'); + } + const form = new FormData(); + await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value, stripFilenames))); + return form; +}; +// We check for Blob not File because Bun.File doesn't inherit from File, +// but they both inherit from Blob and have a `name` property at runtime. +const isNamedBlob = (value) => value instanceof Blob && 'name' in value; +const isUploadable = (value) => typeof value === 'object' && + value !== null && + (value instanceof Response || isAsyncIterable(value) || isNamedBlob(value)); +const hasUploadableValue = (value) => { + if (isUploadable(value)) + return true; + if (Array.isArray(value)) + return value.some(hasUploadableValue); + if (value && typeof value === 'object') { + for (const k in value) { + if (hasUploadableValue(value[k])) + return true; + } + } + return false; +}; +const addFormValue = async (form, key, value, stripFilenames) => { + if (value === undefined) + return; + if (value == null) { + throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`); + } + // TODO: make nested formats configurable + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + form.append(key, String(value)); + } + else if (value instanceof Response) { + let options = {}; + const contentType = value.headers.get('Content-Type'); + if (contentType) { + options = { type: contentType }; + } + form.append(key, makeFile([await value.blob()], getName(value, stripFilenames), options)); + } + else if (isAsyncIterable(value)) { + form.append(key, makeFile([await new Response(ReadableStreamFrom(value)).blob()], getName(value, stripFilenames))); + } + else if (isNamedBlob(value)) { + form.append(key, makeFile([value], getName(value, stripFilenames), { type: value.type })); + } + else if (Array.isArray(value)) { + await Promise.all(value.map((entry) => addFormValue(form, key + '[]', entry, stripFilenames))); + } + else if (typeof value === 'object') { + await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop, stripFilenames))); + } + else { + throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`); + } +}; +//# sourceMappingURL=uploads.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs new file mode 100644 index 00000000..5b9bb389 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs @@ -0,0 +1,26 @@ +export function concatBytes(buffers) { + let length = 0; + for (const buffer of buffers) { + length += buffer.length; + } + const output = new Uint8Array(length); + let index = 0; + for (const buffer of buffers) { + output.set(buffer, index); + index += buffer.length; + } + return output; +} +let encodeUTF8_; +export function encodeUTF8(str) { + let encoder; + return (encodeUTF8_ ?? + ((encoder = new globalThis.TextEncoder()), (encodeUTF8_ = encoder.encode.bind(encoder))))(str); +} +let decodeUTF8_; +export function decodeUTF8(bytes) { + let decoder; + return (decodeUTF8_ ?? + ((decoder = new globalThis.TextDecoder()), (decodeUTF8_ = decoder.decode.bind(decoder))))(bytes); +} +//# sourceMappingURL=bytes.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/env.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/env.mjs new file mode 100644 index 00000000..58ddfda1 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/env.mjs @@ -0,0 +1,18 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +/** + * Read an environment variable. + * + * Trims beginning and trailing whitespace. + * + * Will return undefined if the environment variable doesn't exist or cannot be accessed. + */ +export const readEnv = (env) => { + if (typeof globalThis.process !== 'undefined') { + return globalThis.process.env?.[env]?.trim() ?? undefined; + } + if (typeof globalThis.Deno !== 'undefined') { + return globalThis.Deno.env?.get?.(env)?.trim(); + } + return undefined; +}; +//# sourceMappingURL=env.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/log.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/log.mjs new file mode 100644 index 00000000..95cdd225 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/log.mjs @@ -0,0 +1,80 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { hasOwn } from "./values.mjs"; +const levelNumbers = { + off: 0, + error: 200, + warn: 300, + info: 400, + debug: 500, +}; +export const parseLogLevel = (maybeLevel, sourceName, client) => { + if (!maybeLevel) { + return undefined; + } + if (hasOwn(levelNumbers, maybeLevel)) { + return maybeLevel; + } + loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`); + return undefined; +}; +function noop() { } +function makeLogFn(fnLevel, logger, logLevel) { + if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) { + return noop; + } + else { + // Don't wrap logger functions, we want the stacktrace intact! + return logger[fnLevel].bind(logger); + } +} +const noopLogger = { + error: noop, + warn: noop, + info: noop, + debug: noop, +}; +let cachedLoggers = /* @__PURE__ */ new WeakMap(); +export function loggerFor(client) { + const logger = client.logger; + const logLevel = client.logLevel ?? 'off'; + if (!logger) { + return noopLogger; + } + const cachedLogger = cachedLoggers.get(logger); + if (cachedLogger && cachedLogger[0] === logLevel) { + return cachedLogger[1]; + } + const levelLogger = { + error: makeLogFn('error', logger, logLevel), + warn: makeLogFn('warn', logger, logLevel), + info: makeLogFn('info', logger, logLevel), + debug: makeLogFn('debug', logger, logLevel), + }; + cachedLoggers.set(logger, [logLevel, levelLogger]); + return levelLogger; +} +export const formatRequestDetails = (details) => { + if (details.options) { + details.options = { ...details.options }; + delete details.options['headers']; // redundant + leaks internals + } + if (details.headers) { + details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ + name, + (name.toLowerCase() === 'x-api-key' || + name.toLowerCase() === 'authorization' || + name.toLowerCase() === 'cookie' || + name.toLowerCase() === 'set-cookie') ? + '***' + : value, + ])); + } + if ('retryOfRequestLogID' in details) { + if (details.retryOfRequestLogID) { + details.retryOf = details.retryOfRequestLogID; + } + delete details.retryOfRequestLogID; + } + return details; +}; +//# sourceMappingURL=log.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/path.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/path.mjs new file mode 100644 index 00000000..0586cbe1 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/path.mjs @@ -0,0 +1,74 @@ +import { AnthropicError } from "../../core/error.mjs"; +/** + * Percent-encode everything that isn't safe to have in a path without encoding safe chars. + * + * Taken from https://datatracker.ietf.org/doc/html/rfc3986#section-3.3: + * > unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" + * > sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" + * > pchar = unreserved / pct-encoded / sub-delims / ":" / "@" + */ +export function encodeURIPath(str) { + return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); +} +const EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); +export const createPathTagFunction = (pathEncoder = encodeURIPath) => function path(statics, ...params) { + // If there are no params, no processing is needed. + if (statics.length === 1) + return statics[0]; + let postPath = false; + const invalidSegments = []; + const path = statics.reduce((previousValue, currentValue, index) => { + if (/[?#]/.test(currentValue)) { + postPath = true; + } + const value = params[index]; + let encoded = (postPath ? encodeURIComponent : pathEncoder)('' + value); + if (index !== params.length && + (value == null || + (typeof value === 'object' && + // handle values from other realms + value.toString === + Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY) ?? EMPTY) + ?.toString))) { + encoded = value + ''; + invalidSegments.push({ + start: previousValue.length + currentValue.length, + length: encoded.length, + error: `Value of type ${Object.prototype.toString + .call(value) + .slice(8, -1)} is not a valid path parameter`, + }); + } + return previousValue + currentValue + (index === params.length ? '' : encoded); + }, ''); + const pathOnly = path.split(/[?#]/, 1)[0]; + const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; + let match; + // Find all invalid segments + while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) { + invalidSegments.push({ + start: match.index, + length: match[0].length, + error: `Value "${match[0]}" can\'t be safely passed as a path parameter`, + }); + } + invalidSegments.sort((a, b) => a.start - b.start); + if (invalidSegments.length > 0) { + let lastEnd = 0; + const underline = invalidSegments.reduce((acc, segment) => { + const spaces = ' '.repeat(segment.start - lastEnd); + const arrows = '^'.repeat(segment.length); + lastEnd = segment.start + segment.length; + return acc + spaces + arrows; + }, ''); + throw new AnthropicError(`Path parameters result in path with invalid segments:\n${invalidSegments + .map((e) => e.error) + .join('\n')}\n${path}\n${underline}`); + } + return path; +}; +/** + * URI-encodes path params and ensures no unsafe /./ or /../ path segments are introduced. + */ +export const path = /* @__PURE__ */ createPathTagFunction(encodeURIPath); +//# sourceMappingURL=path.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs new file mode 100644 index 00000000..784954ac --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs @@ -0,0 +1,3 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +//# sourceMappingURL=sleep.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs new file mode 100644 index 00000000..4fe2cb25 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs @@ -0,0 +1,15 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +/** + * https://stackoverflow.com/a/2117523 + */ +export let uuid4 = function () { + const { crypto } = globalThis; + if (crypto?.randomUUID) { + uuid4 = crypto.randomUUID.bind(crypto); + return crypto.randomUUID(); + } + const u8 = new Uint8Array(1); + const randomByte = crypto ? () => crypto.getRandomValues(u8)[0] : () => (Math.random() * 0xff) & 0xff; + return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, (c) => (+c ^ (randomByte() & (15 >> (+c / 4)))).toString(16)); +}; +//# sourceMappingURL=uuid.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/values.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/values.mjs new file mode 100644 index 00000000..7b9bf757 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/values.mjs @@ -0,0 +1,100 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { AnthropicError } from "../../core/error.mjs"; +// https://url.spec.whatwg.org/#url-scheme-string +const startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i; +export const isAbsoluteURL = (url) => { + return startsWithSchemeRegexp.test(url); +}; +export let isArray = (val) => ((isArray = Array.isArray), isArray(val)); +export let isReadonlyArray = isArray; +/** Returns an object if the given value isn't an object, otherwise returns as-is */ +export function maybeObj(x) { + if (typeof x !== 'object') { + return {}; + } + return x ?? {}; +} +// https://stackoverflow.com/a/34491287 +export function isEmptyObj(obj) { + if (!obj) + return true; + for (const _k in obj) + return false; + return true; +} +// https://eslint.org/docs/latest/rules/no-prototype-builtins +export function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} +export function isObj(obj) { + return obj != null && typeof obj === 'object' && !Array.isArray(obj); +} +export const ensurePresent = (value) => { + if (value == null) { + throw new AnthropicError(`Expected a value to be given but received ${value} instead.`); + } + return value; +}; +export const validatePositiveInteger = (name, n) => { + if (typeof n !== 'number' || !Number.isInteger(n)) { + throw new AnthropicError(`${name} must be an integer`); + } + if (n < 0) { + throw new AnthropicError(`${name} must be a positive integer`); + } + return n; +}; +export const coerceInteger = (value) => { + if (typeof value === 'number') + return Math.round(value); + if (typeof value === 'string') + return parseInt(value, 10); + throw new AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`); +}; +export const coerceFloat = (value) => { + if (typeof value === 'number') + return value; + if (typeof value === 'string') + return parseFloat(value); + throw new AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`); +}; +export const coerceBoolean = (value) => { + if (typeof value === 'boolean') + return value; + if (typeof value === 'string') + return value === 'true'; + return Boolean(value); +}; +export const maybeCoerceInteger = (value) => { + if (value == null) { + return undefined; + } + return coerceInteger(value); +}; +export const maybeCoerceFloat = (value) => { + if (value == null) { + return undefined; + } + return coerceFloat(value); +}; +export const maybeCoerceBoolean = (value) => { + if (value == null) { + return undefined; + } + return coerceBoolean(value); +}; +export const safeJSON = (text) => { + try { + return JSON.parse(text); + } + catch (err) { + return undefined; + } +}; +// Gets a value from an object, deletes the key, and returns the value (or undefined if not found) +export const pop = (obj, key) => { + const value = obj[key]; + delete obj[key]; + return value; +}; +//# sourceMappingURL=values.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/lib/BetaMessageStream.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/lib/BetaMessageStream.mjs new file mode 100644 index 00000000..4b9c2355 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/lib/BetaMessageStream.mjs @@ -0,0 +1,616 @@ +var _BetaMessageStream_instances, _BetaMessageStream_currentMessageSnapshot, _BetaMessageStream_params, _BetaMessageStream_connectedPromise, _BetaMessageStream_resolveConnectedPromise, _BetaMessageStream_rejectConnectedPromise, _BetaMessageStream_endPromise, _BetaMessageStream_resolveEndPromise, _BetaMessageStream_rejectEndPromise, _BetaMessageStream_listeners, _BetaMessageStream_ended, _BetaMessageStream_errored, _BetaMessageStream_aborted, _BetaMessageStream_catchingPromiseCreated, _BetaMessageStream_response, _BetaMessageStream_request_id, _BetaMessageStream_logger, _BetaMessageStream_getFinalMessage, _BetaMessageStream_getFinalText, _BetaMessageStream_handleError, _BetaMessageStream_beginRequest, _BetaMessageStream_addStreamEvent, _BetaMessageStream_endRequest, _BetaMessageStream_accumulateMessage; +import { __classPrivateFieldGet, __classPrivateFieldSet } from "../internal/tslib.mjs"; +import { partialParse } from "../_vendor/partial-json-parser/parser.mjs"; +import { AnthropicError, APIUserAbortError } from "../error.mjs"; +import { isAbortError } from "../internal/errors.mjs"; +import { Stream } from "../streaming.mjs"; +import { maybeParseBetaMessage } from "./beta-parser.mjs"; +const JSON_BUF_PROPERTY = '__json_buf'; +function tracksToolInput(content) { + return content.type === 'tool_use' || content.type === 'server_tool_use' || content.type === 'mcp_tool_use'; +} +export class BetaMessageStream { + constructor(params, opts) { + _BetaMessageStream_instances.add(this); + this.messages = []; + this.receivedMessages = []; + _BetaMessageStream_currentMessageSnapshot.set(this, void 0); + _BetaMessageStream_params.set(this, null); + this.controller = new AbortController(); + _BetaMessageStream_connectedPromise.set(this, void 0); + _BetaMessageStream_resolveConnectedPromise.set(this, () => { }); + _BetaMessageStream_rejectConnectedPromise.set(this, () => { }); + _BetaMessageStream_endPromise.set(this, void 0); + _BetaMessageStream_resolveEndPromise.set(this, () => { }); + _BetaMessageStream_rejectEndPromise.set(this, () => { }); + _BetaMessageStream_listeners.set(this, {}); + _BetaMessageStream_ended.set(this, false); + _BetaMessageStream_errored.set(this, false); + _BetaMessageStream_aborted.set(this, false); + _BetaMessageStream_catchingPromiseCreated.set(this, false); + _BetaMessageStream_response.set(this, void 0); + _BetaMessageStream_request_id.set(this, void 0); + _BetaMessageStream_logger.set(this, void 0); + _BetaMessageStream_handleError.set(this, (error) => { + __classPrivateFieldSet(this, _BetaMessageStream_errored, true, "f"); + if (isAbortError(error)) { + error = new APIUserAbortError(); + } + if (error instanceof APIUserAbortError) { + __classPrivateFieldSet(this, _BetaMessageStream_aborted, true, "f"); + return this._emit('abort', error); + } + if (error instanceof AnthropicError) { + return this._emit('error', error); + } + if (error instanceof Error) { + const anthropicError = new AnthropicError(error.message); + // @ts-ignore + anthropicError.cause = error; + return this._emit('error', anthropicError); + } + return this._emit('error', new AnthropicError(String(error))); + }); + __classPrivateFieldSet(this, _BetaMessageStream_connectedPromise, new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _BetaMessageStream_resolveConnectedPromise, resolve, "f"); + __classPrivateFieldSet(this, _BetaMessageStream_rejectConnectedPromise, reject, "f"); + }), "f"); + __classPrivateFieldSet(this, _BetaMessageStream_endPromise, new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _BetaMessageStream_resolveEndPromise, resolve, "f"); + __classPrivateFieldSet(this, _BetaMessageStream_rejectEndPromise, reject, "f"); + }), "f"); + // Don't let these promises cause unhandled rejection errors. + // we will manually cause an unhandled rejection error later + // if the user hasn't registered any error listener or called + // any promise-returning method. + __classPrivateFieldGet(this, _BetaMessageStream_connectedPromise, "f").catch(() => { }); + __classPrivateFieldGet(this, _BetaMessageStream_endPromise, "f").catch(() => { }); + __classPrivateFieldSet(this, _BetaMessageStream_params, params, "f"); + __classPrivateFieldSet(this, _BetaMessageStream_logger, opts?.logger ?? console, "f"); + } + get response() { + return __classPrivateFieldGet(this, _BetaMessageStream_response, "f"); + } + get request_id() { + return __classPrivateFieldGet(this, _BetaMessageStream_request_id, "f"); + } + /** + * Returns the `MessageStream` data, the raw `Response` instance and the ID of the request, + * returned vie the `request-id` header which is useful for debugging requests and resporting + * issues to Anthropic. + * + * This is the same as the `APIPromise.withResponse()` method. + * + * This method will raise an error if you created the stream using `MessageStream.fromReadableStream` + * as no `Response` is available. + */ + async withResponse() { + __classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f"); + const response = await __classPrivateFieldGet(this, _BetaMessageStream_connectedPromise, "f"); + if (!response) { + throw new Error('Could not resolve a `Response` object'); + } + return { + data: this, + response, + request_id: response.headers.get('request-id'), + }; + } + /** + * Intended for use on the frontend, consuming a stream produced with + * `.toReadableStream()` on the backend. + * + * Note that messages sent to the model do not appear in `.on('message')` + * in this context. + */ + static fromReadableStream(stream) { + const runner = new BetaMessageStream(null); + runner._run(() => runner._fromReadableStream(stream)); + return runner; + } + static createMessage(messages, params, options, { logger } = {}) { + const runner = new BetaMessageStream(params, { logger }); + for (const message of params.messages) { + runner._addMessageParam(message); + } + __classPrivateFieldSet(runner, _BetaMessageStream_params, { ...params, stream: true }, "f"); + runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } })); + return runner; + } + _run(executor) { + executor().then(() => { + this._emitFinal(); + this._emit('end'); + }, __classPrivateFieldGet(this, _BetaMessageStream_handleError, "f")); + } + _addMessageParam(message) { + this.messages.push(message); + } + _addMessage(message, emit = true) { + this.receivedMessages.push(message); + if (emit) { + this._emit('message', message); + } + } + async _createMessage(messages, params, options) { + const signal = options?.signal; + let abortHandler; + if (signal) { + if (signal.aborted) + this.controller.abort(); + abortHandler = this.controller.abort.bind(this.controller); + signal.addEventListener('abort', abortHandler); + } + try { + __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this); + const { response, data: stream } = await messages + .create({ ...params, stream: true }, { ...options, signal: this.controller.signal }) + .withResponse(); + this._connected(response); + for await (const event of stream) { + __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event); + } + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this); + } + finally { + if (signal && abortHandler) { + signal.removeEventListener('abort', abortHandler); + } + } + } + _connected(response) { + if (this.ended) + return; + __classPrivateFieldSet(this, _BetaMessageStream_response, response, "f"); + __classPrivateFieldSet(this, _BetaMessageStream_request_id, response?.headers.get('request-id'), "f"); + __classPrivateFieldGet(this, _BetaMessageStream_resolveConnectedPromise, "f").call(this, response); + this._emit('connect'); + } + get ended() { + return __classPrivateFieldGet(this, _BetaMessageStream_ended, "f"); + } + get errored() { + return __classPrivateFieldGet(this, _BetaMessageStream_errored, "f"); + } + get aborted() { + return __classPrivateFieldGet(this, _BetaMessageStream_aborted, "f"); + } + abort() { + this.controller.abort(); + } + /** + * Adds the listener function to the end of the listeners array for the event. + * No checks are made to see if the listener has already been added. Multiple calls passing + * the same combination of event and listener will result in the listener being added, and + * called, multiple times. + * @returns this MessageStream, so that calls can be chained + */ + on(event, listener) { + const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = []); + listeners.push({ listener }); + return this; + } + /** + * Removes the specified listener from the listener array for the event. + * off() will remove, at most, one instance of a listener from the listener array. If any single + * listener has been added multiple times to the listener array for the specified event, then + * off() must be called multiple times to remove each instance. + * @returns this MessageStream, so that calls can be chained + */ + off(event, listener) { + const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event]; + if (!listeners) + return this; + const index = listeners.findIndex((l) => l.listener === listener); + if (index >= 0) + listeners.splice(index, 1); + return this; + } + /** + * Adds a one-time listener function for the event. The next time the event is triggered, + * this listener is removed and then invoked. + * @returns this MessageStream, so that calls can be chained + */ + once(event, listener) { + const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = []); + listeners.push({ listener, once: true }); + return this; + } + /** + * This is similar to `.once()`, but returns a Promise that resolves the next time + * the event is triggered, instead of calling a listener callback. + * @returns a Promise that resolves the next time given event is triggered, + * or rejects if an error is emitted. (If you request the 'error' event, + * returns a promise that resolves with the error). + * + * Example: + * + * const message = await stream.emitted('message') // rejects if the stream errors + */ + emitted(event) { + return new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f"); + if (event !== 'error') + this.once('error', reject); + this.once(event, resolve); + }); + } + async done() { + __classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f"); + await __classPrivateFieldGet(this, _BetaMessageStream_endPromise, "f"); + } + get currentMessage() { + return __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f"); + } + /** + * @returns a promise that resolves with the the final assistant Message response, + * or rejects if an error occurred or the stream ended prematurely without producing a Message. + * If structured outputs were used, this will be a ParsedMessage with a `parsed` field. + */ + async finalMessage() { + await this.done(); + return __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this); + } + /** + * @returns a promise that resolves with the the final assistant Message's text response, concatenated + * together if there are more than one text blocks. + * Rejects if an error occurred or the stream ended prematurely without producing a Message. + */ + async finalText() { + await this.done(); + return __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalText).call(this); + } + _emit(event, ...args) { + // make sure we don't emit any MessageStreamEvents after end + if (__classPrivateFieldGet(this, _BetaMessageStream_ended, "f")) + return; + if (event === 'end') { + __classPrivateFieldSet(this, _BetaMessageStream_ended, true, "f"); + __classPrivateFieldGet(this, _BetaMessageStream_resolveEndPromise, "f").call(this); + } + const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event]; + if (listeners) { + __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = listeners.filter((l) => !l.once); + listeners.forEach(({ listener }) => listener(...args)); + } + if (event === 'abort') { + const error = args[0]; + if (!__classPrivateFieldGet(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) { + Promise.reject(error); + } + __classPrivateFieldGet(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error); + this._emit('end'); + return; + } + if (event === 'error') { + // NOTE: _emit('error', error) should only be called from #handleError(). + const error = args[0]; + if (!__classPrivateFieldGet(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) { + // Trigger an unhandled rejection if the user hasn't registered any error handlers. + // If you are seeing stack traces here, make sure to handle errors via either: + // - runner.on('error', () => ...) + // - await runner.done() + // - await runner.final...() + // - etc. + Promise.reject(error); + } + __classPrivateFieldGet(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error); + this._emit('end'); + } + } + _emitFinal() { + const finalMessage = this.receivedMessages.at(-1); + if (finalMessage) { + this._emit('finalMessage', __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this)); + } + } + async _fromReadableStream(readableStream, options) { + const signal = options?.signal; + let abortHandler; + if (signal) { + if (signal.aborted) + this.controller.abort(); + abortHandler = this.controller.abort.bind(this.controller); + signal.addEventListener('abort', abortHandler); + } + try { + __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this); + this._connected(null); + const stream = Stream.fromReadableStream(readableStream, this.controller); + for await (const event of stream) { + __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event); + } + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this); + } + finally { + if (signal && abortHandler) { + signal.removeEventListener('abort', abortHandler); + } + } + } + [(_BetaMessageStream_currentMessageSnapshot = new WeakMap(), _BetaMessageStream_params = new WeakMap(), _BetaMessageStream_connectedPromise = new WeakMap(), _BetaMessageStream_resolveConnectedPromise = new WeakMap(), _BetaMessageStream_rejectConnectedPromise = new WeakMap(), _BetaMessageStream_endPromise = new WeakMap(), _BetaMessageStream_resolveEndPromise = new WeakMap(), _BetaMessageStream_rejectEndPromise = new WeakMap(), _BetaMessageStream_listeners = new WeakMap(), _BetaMessageStream_ended = new WeakMap(), _BetaMessageStream_errored = new WeakMap(), _BetaMessageStream_aborted = new WeakMap(), _BetaMessageStream_catchingPromiseCreated = new WeakMap(), _BetaMessageStream_response = new WeakMap(), _BetaMessageStream_request_id = new WeakMap(), _BetaMessageStream_logger = new WeakMap(), _BetaMessageStream_handleError = new WeakMap(), _BetaMessageStream_instances = new WeakSet(), _BetaMessageStream_getFinalMessage = function _BetaMessageStream_getFinalMessage() { + if (this.receivedMessages.length === 0) { + throw new AnthropicError('stream ended without producing a Message with role=assistant'); + } + return this.receivedMessages.at(-1); + }, _BetaMessageStream_getFinalText = function _BetaMessageStream_getFinalText() { + if (this.receivedMessages.length === 0) { + throw new AnthropicError('stream ended without producing a Message with role=assistant'); + } + const textBlocks = this.receivedMessages + .at(-1) + .content.filter((block) => block.type === 'text') + .map((block) => block.text); + if (textBlocks.length === 0) { + throw new AnthropicError('stream ended without producing a content block with type=text'); + } + return textBlocks.join(' '); + }, _BetaMessageStream_beginRequest = function _BetaMessageStream_beginRequest() { + if (this.ended) + return; + __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, undefined, "f"); + }, _BetaMessageStream_addStreamEvent = function _BetaMessageStream_addStreamEvent(event) { + if (this.ended) + return; + const messageSnapshot = __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_accumulateMessage).call(this, event); + this._emit('streamEvent', event, messageSnapshot); + switch (event.type) { + case 'content_block_delta': { + const content = messageSnapshot.content.at(-1); + switch (event.delta.type) { + case 'text_delta': { + if (content.type === 'text') { + this._emit('text', event.delta.text, content.text || ''); + } + break; + } + case 'citations_delta': { + if (content.type === 'text') { + this._emit('citation', event.delta.citation, content.citations ?? []); + } + break; + } + case 'input_json_delta': { + if (tracksToolInput(content) && content.input) { + this._emit('inputJson', event.delta.partial_json, content.input); + } + break; + } + case 'thinking_delta': { + if (content.type === 'thinking') { + this._emit('thinking', event.delta.thinking, content.thinking); + } + break; + } + case 'signature_delta': { + if (content.type === 'thinking') { + this._emit('signature', content.signature); + } + break; + } + case 'compaction_delta': { + if (content.type === 'compaction' && content.content) { + this._emit('compaction', content.content); + } + break; + } + default: + checkNever(event.delta); + } + break; + } + case 'message_stop': { + this._addMessageParam(messageSnapshot); + this._addMessage(maybeParseBetaMessage(messageSnapshot, __classPrivateFieldGet(this, _BetaMessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _BetaMessageStream_logger, "f") }), true); + break; + } + case 'content_block_stop': { + this._emit('contentBlock', messageSnapshot.content.at(-1)); + break; + } + case 'message_start': { + __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, messageSnapshot, "f"); + break; + } + case 'content_block_start': + case 'message_delta': + break; + } + }, _BetaMessageStream_endRequest = function _BetaMessageStream_endRequest() { + if (this.ended) { + throw new AnthropicError(`stream has ended, this shouldn't happen`); + } + const snapshot = __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f"); + if (!snapshot) { + throw new AnthropicError(`request ended without sending any chunks`); + } + __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, undefined, "f"); + return maybeParseBetaMessage(snapshot, __classPrivateFieldGet(this, _BetaMessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _BetaMessageStream_logger, "f") }); + }, _BetaMessageStream_accumulateMessage = function _BetaMessageStream_accumulateMessage(event) { + let snapshot = __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f"); + if (event.type === 'message_start') { + if (snapshot) { + throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`); + } + return event.message; + } + if (!snapshot) { + throw new AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`); + } + switch (event.type) { + case 'message_stop': + return snapshot; + case 'message_delta': + snapshot.container = event.delta.container; + snapshot.stop_reason = event.delta.stop_reason; + snapshot.stop_sequence = event.delta.stop_sequence; + snapshot.usage.output_tokens = event.usage.output_tokens; + snapshot.context_management = event.context_management; + if (event.usage.input_tokens != null) { + snapshot.usage.input_tokens = event.usage.input_tokens; + } + if (event.usage.cache_creation_input_tokens != null) { + snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens; + } + if (event.usage.cache_read_input_tokens != null) { + snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens; + } + if (event.usage.server_tool_use != null) { + snapshot.usage.server_tool_use = event.usage.server_tool_use; + } + if (event.usage.iterations != null) { + snapshot.usage.iterations = event.usage.iterations; + } + return snapshot; + case 'content_block_start': + snapshot.content.push(event.content_block); + return snapshot; + case 'content_block_delta': { + const snapshotContent = snapshot.content.at(event.index); + switch (event.delta.type) { + case 'text_delta': { + if (snapshotContent?.type === 'text') { + snapshot.content[event.index] = { + ...snapshotContent, + text: (snapshotContent.text || '') + event.delta.text, + }; + } + break; + } + case 'citations_delta': { + if (snapshotContent?.type === 'text') { + snapshot.content[event.index] = { + ...snapshotContent, + citations: [...(snapshotContent.citations ?? []), event.delta.citation], + }; + } + break; + } + case 'input_json_delta': { + if (snapshotContent && tracksToolInput(snapshotContent)) { + // we need to keep track of the raw JSON string as well so that we can + // re-parse it for each delta, for now we just store it as an untyped + // non-enumerable property on the snapshot + let jsonBuf = snapshotContent[JSON_BUF_PROPERTY] || ''; + jsonBuf += event.delta.partial_json; + const newContent = { ...snapshotContent }; + Object.defineProperty(newContent, JSON_BUF_PROPERTY, { + value: jsonBuf, + enumerable: false, + writable: true, + }); + if (jsonBuf) { + try { + newContent.input = partialParse(jsonBuf); + } + catch (err) { + const error = new AnthropicError(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${err}. JSON: ${jsonBuf}`); + __classPrivateFieldGet(this, _BetaMessageStream_handleError, "f").call(this, error); + } + } + snapshot.content[event.index] = newContent; + } + break; + } + case 'thinking_delta': { + if (snapshotContent?.type === 'thinking') { + snapshot.content[event.index] = { + ...snapshotContent, + thinking: snapshotContent.thinking + event.delta.thinking, + }; + } + break; + } + case 'signature_delta': { + if (snapshotContent?.type === 'thinking') { + snapshot.content[event.index] = { + ...snapshotContent, + signature: event.delta.signature, + }; + } + break; + } + case 'compaction_delta': { + if (snapshotContent?.type === 'compaction') { + snapshot.content[event.index] = { + ...snapshotContent, + content: (snapshotContent.content || '') + event.delta.content, + }; + } + break; + } + default: + checkNever(event.delta); + } + return snapshot; + } + case 'content_block_stop': + return snapshot; + } + }, Symbol.asyncIterator)]() { + const pushQueue = []; + const readQueue = []; + let done = false; + this.on('streamEvent', (event) => { + const reader = readQueue.shift(); + if (reader) { + reader.resolve(event); + } + else { + pushQueue.push(event); + } + }); + this.on('end', () => { + done = true; + for (const reader of readQueue) { + reader.resolve(undefined); + } + readQueue.length = 0; + }); + this.on('abort', (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + this.on('error', (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + return { + next: async () => { + if (!pushQueue.length) { + if (done) { + return { value: undefined, done: true }; + } + return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true })); + } + const chunk = pushQueue.shift(); + return { value: chunk, done: false }; + }, + return: async () => { + this.abort(); + return { value: undefined, done: true }; + }, + }; + } + toReadableStream() { + const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller); + return stream.toReadableStream(); + } +} +// used to ensure exhaustive case matching without throwing a runtime error +function checkNever(x) { } +//# sourceMappingURL=BetaMessageStream.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/lib/MessageStream.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/lib/MessageStream.mjs new file mode 100644 index 00000000..bca6c2f7 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/lib/MessageStream.mjs @@ -0,0 +1,591 @@ +var _MessageStream_instances, _MessageStream_currentMessageSnapshot, _MessageStream_params, _MessageStream_connectedPromise, _MessageStream_resolveConnectedPromise, _MessageStream_rejectConnectedPromise, _MessageStream_endPromise, _MessageStream_resolveEndPromise, _MessageStream_rejectEndPromise, _MessageStream_listeners, _MessageStream_ended, _MessageStream_errored, _MessageStream_aborted, _MessageStream_catchingPromiseCreated, _MessageStream_response, _MessageStream_request_id, _MessageStream_logger, _MessageStream_getFinalMessage, _MessageStream_getFinalText, _MessageStream_handleError, _MessageStream_beginRequest, _MessageStream_addStreamEvent, _MessageStream_endRequest, _MessageStream_accumulateMessage; +import { __classPrivateFieldGet, __classPrivateFieldSet } from "../internal/tslib.mjs"; +import { isAbortError } from "../internal/errors.mjs"; +import { AnthropicError, APIUserAbortError } from "../error.mjs"; +import { Stream } from "../streaming.mjs"; +import { partialParse } from "../_vendor/partial-json-parser/parser.mjs"; +import { maybeParseMessage } from "./parser.mjs"; +const JSON_BUF_PROPERTY = '__json_buf'; +function tracksToolInput(content) { + return content.type === 'tool_use' || content.type === 'server_tool_use'; +} +export class MessageStream { + constructor(params, opts) { + _MessageStream_instances.add(this); + this.messages = []; + this.receivedMessages = []; + _MessageStream_currentMessageSnapshot.set(this, void 0); + _MessageStream_params.set(this, null); + this.controller = new AbortController(); + _MessageStream_connectedPromise.set(this, void 0); + _MessageStream_resolveConnectedPromise.set(this, () => { }); + _MessageStream_rejectConnectedPromise.set(this, () => { }); + _MessageStream_endPromise.set(this, void 0); + _MessageStream_resolveEndPromise.set(this, () => { }); + _MessageStream_rejectEndPromise.set(this, () => { }); + _MessageStream_listeners.set(this, {}); + _MessageStream_ended.set(this, false); + _MessageStream_errored.set(this, false); + _MessageStream_aborted.set(this, false); + _MessageStream_catchingPromiseCreated.set(this, false); + _MessageStream_response.set(this, void 0); + _MessageStream_request_id.set(this, void 0); + _MessageStream_logger.set(this, void 0); + _MessageStream_handleError.set(this, (error) => { + __classPrivateFieldSet(this, _MessageStream_errored, true, "f"); + if (isAbortError(error)) { + error = new APIUserAbortError(); + } + if (error instanceof APIUserAbortError) { + __classPrivateFieldSet(this, _MessageStream_aborted, true, "f"); + return this._emit('abort', error); + } + if (error instanceof AnthropicError) { + return this._emit('error', error); + } + if (error instanceof Error) { + const anthropicError = new AnthropicError(error.message); + // @ts-ignore + anthropicError.cause = error; + return this._emit('error', anthropicError); + } + return this._emit('error', new AnthropicError(String(error))); + }); + __classPrivateFieldSet(this, _MessageStream_connectedPromise, new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _MessageStream_resolveConnectedPromise, resolve, "f"); + __classPrivateFieldSet(this, _MessageStream_rejectConnectedPromise, reject, "f"); + }), "f"); + __classPrivateFieldSet(this, _MessageStream_endPromise, new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _MessageStream_resolveEndPromise, resolve, "f"); + __classPrivateFieldSet(this, _MessageStream_rejectEndPromise, reject, "f"); + }), "f"); + // Don't let these promises cause unhandled rejection errors. + // we will manually cause an unhandled rejection error later + // if the user hasn't registered any error listener or called + // any promise-returning method. + __classPrivateFieldGet(this, _MessageStream_connectedPromise, "f").catch(() => { }); + __classPrivateFieldGet(this, _MessageStream_endPromise, "f").catch(() => { }); + __classPrivateFieldSet(this, _MessageStream_params, params, "f"); + __classPrivateFieldSet(this, _MessageStream_logger, opts?.logger ?? console, "f"); + } + get response() { + return __classPrivateFieldGet(this, _MessageStream_response, "f"); + } + get request_id() { + return __classPrivateFieldGet(this, _MessageStream_request_id, "f"); + } + /** + * Returns the `MessageStream` data, the raw `Response` instance and the ID of the request, + * returned vie the `request-id` header which is useful for debugging requests and resporting + * issues to Anthropic. + * + * This is the same as the `APIPromise.withResponse()` method. + * + * This method will raise an error if you created the stream using `MessageStream.fromReadableStream` + * as no `Response` is available. + */ + async withResponse() { + __classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f"); + const response = await __classPrivateFieldGet(this, _MessageStream_connectedPromise, "f"); + if (!response) { + throw new Error('Could not resolve a `Response` object'); + } + return { + data: this, + response, + request_id: response.headers.get('request-id'), + }; + } + /** + * Intended for use on the frontend, consuming a stream produced with + * `.toReadableStream()` on the backend. + * + * Note that messages sent to the model do not appear in `.on('message')` + * in this context. + */ + static fromReadableStream(stream) { + const runner = new MessageStream(null); + runner._run(() => runner._fromReadableStream(stream)); + return runner; + } + static createMessage(messages, params, options, { logger } = {}) { + const runner = new MessageStream(params, { logger }); + for (const message of params.messages) { + runner._addMessageParam(message); + } + __classPrivateFieldSet(runner, _MessageStream_params, { ...params, stream: true }, "f"); + runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } })); + return runner; + } + _run(executor) { + executor().then(() => { + this._emitFinal(); + this._emit('end'); + }, __classPrivateFieldGet(this, _MessageStream_handleError, "f")); + } + _addMessageParam(message) { + this.messages.push(message); + } + _addMessage(message, emit = true) { + this.receivedMessages.push(message); + if (emit) { + this._emit('message', message); + } + } + async _createMessage(messages, params, options) { + const signal = options?.signal; + let abortHandler; + if (signal) { + if (signal.aborted) + this.controller.abort(); + abortHandler = this.controller.abort.bind(this.controller); + signal.addEventListener('abort', abortHandler); + } + try { + __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this); + const { response, data: stream } = await messages + .create({ ...params, stream: true }, { ...options, signal: this.controller.signal }) + .withResponse(); + this._connected(response); + for await (const event of stream) { + __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event); + } + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this); + } + finally { + if (signal && abortHandler) { + signal.removeEventListener('abort', abortHandler); + } + } + } + _connected(response) { + if (this.ended) + return; + __classPrivateFieldSet(this, _MessageStream_response, response, "f"); + __classPrivateFieldSet(this, _MessageStream_request_id, response?.headers.get('request-id'), "f"); + __classPrivateFieldGet(this, _MessageStream_resolveConnectedPromise, "f").call(this, response); + this._emit('connect'); + } + get ended() { + return __classPrivateFieldGet(this, _MessageStream_ended, "f"); + } + get errored() { + return __classPrivateFieldGet(this, _MessageStream_errored, "f"); + } + get aborted() { + return __classPrivateFieldGet(this, _MessageStream_aborted, "f"); + } + abort() { + this.controller.abort(); + } + /** + * Adds the listener function to the end of the listeners array for the event. + * No checks are made to see if the listener has already been added. Multiple calls passing + * the same combination of event and listener will result in the listener being added, and + * called, multiple times. + * @returns this MessageStream, so that calls can be chained + */ + on(event, listener) { + const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = []); + listeners.push({ listener }); + return this; + } + /** + * Removes the specified listener from the listener array for the event. + * off() will remove, at most, one instance of a listener from the listener array. If any single + * listener has been added multiple times to the listener array for the specified event, then + * off() must be called multiple times to remove each instance. + * @returns this MessageStream, so that calls can be chained + */ + off(event, listener) { + const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event]; + if (!listeners) + return this; + const index = listeners.findIndex((l) => l.listener === listener); + if (index >= 0) + listeners.splice(index, 1); + return this; + } + /** + * Adds a one-time listener function for the event. The next time the event is triggered, + * this listener is removed and then invoked. + * @returns this MessageStream, so that calls can be chained + */ + once(event, listener) { + const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = []); + listeners.push({ listener, once: true }); + return this; + } + /** + * This is similar to `.once()`, but returns a Promise that resolves the next time + * the event is triggered, instead of calling a listener callback. + * @returns a Promise that resolves the next time given event is triggered, + * or rejects if an error is emitted. (If you request the 'error' event, + * returns a promise that resolves with the error). + * + * Example: + * + * const message = await stream.emitted('message') // rejects if the stream errors + */ + emitted(event) { + return new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f"); + if (event !== 'error') + this.once('error', reject); + this.once(event, resolve); + }); + } + async done() { + __classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f"); + await __classPrivateFieldGet(this, _MessageStream_endPromise, "f"); + } + get currentMessage() { + return __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f"); + } + /** + * @returns a promise that resolves with the the final assistant Message response, + * or rejects if an error occurred or the stream ended prematurely without producing a Message. + * If structured outputs were used, this will be a ParsedMessage with a `parsed_output` field. + */ + async finalMessage() { + await this.done(); + return __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this); + } + /** + * @returns a promise that resolves with the the final assistant Message's text response, concatenated + * together if there are more than one text blocks. + * Rejects if an error occurred or the stream ended prematurely without producing a Message. + */ + async finalText() { + await this.done(); + return __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalText).call(this); + } + _emit(event, ...args) { + // make sure we don't emit any MessageStreamEvents after end + if (__classPrivateFieldGet(this, _MessageStream_ended, "f")) + return; + if (event === 'end') { + __classPrivateFieldSet(this, _MessageStream_ended, true, "f"); + __classPrivateFieldGet(this, _MessageStream_resolveEndPromise, "f").call(this); + } + const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event]; + if (listeners) { + __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = listeners.filter((l) => !l.once); + listeners.forEach(({ listener }) => listener(...args)); + } + if (event === 'abort') { + const error = args[0]; + if (!__classPrivateFieldGet(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) { + Promise.reject(error); + } + __classPrivateFieldGet(this, _MessageStream_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet(this, _MessageStream_rejectEndPromise, "f").call(this, error); + this._emit('end'); + return; + } + if (event === 'error') { + // NOTE: _emit('error', error) should only be called from #handleError(). + const error = args[0]; + if (!__classPrivateFieldGet(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) { + // Trigger an unhandled rejection if the user hasn't registered any error handlers. + // If you are seeing stack traces here, make sure to handle errors via either: + // - runner.on('error', () => ...) + // - await runner.done() + // - await runner.final...() + // - etc. + Promise.reject(error); + } + __classPrivateFieldGet(this, _MessageStream_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet(this, _MessageStream_rejectEndPromise, "f").call(this, error); + this._emit('end'); + } + } + _emitFinal() { + const finalMessage = this.receivedMessages.at(-1); + if (finalMessage) { + this._emit('finalMessage', __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this)); + } + } + async _fromReadableStream(readableStream, options) { + const signal = options?.signal; + let abortHandler; + if (signal) { + if (signal.aborted) + this.controller.abort(); + abortHandler = this.controller.abort.bind(this.controller); + signal.addEventListener('abort', abortHandler); + } + try { + __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this); + this._connected(null); + const stream = Stream.fromReadableStream(readableStream, this.controller); + for await (const event of stream) { + __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event); + } + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this); + } + finally { + if (signal && abortHandler) { + signal.removeEventListener('abort', abortHandler); + } + } + } + [(_MessageStream_currentMessageSnapshot = new WeakMap(), _MessageStream_params = new WeakMap(), _MessageStream_connectedPromise = new WeakMap(), _MessageStream_resolveConnectedPromise = new WeakMap(), _MessageStream_rejectConnectedPromise = new WeakMap(), _MessageStream_endPromise = new WeakMap(), _MessageStream_resolveEndPromise = new WeakMap(), _MessageStream_rejectEndPromise = new WeakMap(), _MessageStream_listeners = new WeakMap(), _MessageStream_ended = new WeakMap(), _MessageStream_errored = new WeakMap(), _MessageStream_aborted = new WeakMap(), _MessageStream_catchingPromiseCreated = new WeakMap(), _MessageStream_response = new WeakMap(), _MessageStream_request_id = new WeakMap(), _MessageStream_logger = new WeakMap(), _MessageStream_handleError = new WeakMap(), _MessageStream_instances = new WeakSet(), _MessageStream_getFinalMessage = function _MessageStream_getFinalMessage() { + if (this.receivedMessages.length === 0) { + throw new AnthropicError('stream ended without producing a Message with role=assistant'); + } + return this.receivedMessages.at(-1); + }, _MessageStream_getFinalText = function _MessageStream_getFinalText() { + if (this.receivedMessages.length === 0) { + throw new AnthropicError('stream ended without producing a Message with role=assistant'); + } + const textBlocks = this.receivedMessages + .at(-1) + .content.filter((block) => block.type === 'text') + .map((block) => block.text); + if (textBlocks.length === 0) { + throw new AnthropicError('stream ended without producing a content block with type=text'); + } + return textBlocks.join(' '); + }, _MessageStream_beginRequest = function _MessageStream_beginRequest() { + if (this.ended) + return; + __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, undefined, "f"); + }, _MessageStream_addStreamEvent = function _MessageStream_addStreamEvent(event) { + if (this.ended) + return; + const messageSnapshot = __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_accumulateMessage).call(this, event); + this._emit('streamEvent', event, messageSnapshot); + switch (event.type) { + case 'content_block_delta': { + const content = messageSnapshot.content.at(-1); + switch (event.delta.type) { + case 'text_delta': { + if (content.type === 'text') { + this._emit('text', event.delta.text, content.text || ''); + } + break; + } + case 'citations_delta': { + if (content.type === 'text') { + this._emit('citation', event.delta.citation, content.citations ?? []); + } + break; + } + case 'input_json_delta': { + if (tracksToolInput(content) && content.input) { + this._emit('inputJson', event.delta.partial_json, content.input); + } + break; + } + case 'thinking_delta': { + if (content.type === 'thinking') { + this._emit('thinking', event.delta.thinking, content.thinking); + } + break; + } + case 'signature_delta': { + if (content.type === 'thinking') { + this._emit('signature', content.signature); + } + break; + } + default: + checkNever(event.delta); + } + break; + } + case 'message_stop': { + this._addMessageParam(messageSnapshot); + this._addMessage(maybeParseMessage(messageSnapshot, __classPrivateFieldGet(this, _MessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _MessageStream_logger, "f") }), true); + break; + } + case 'content_block_stop': { + this._emit('contentBlock', messageSnapshot.content.at(-1)); + break; + } + case 'message_start': { + __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, messageSnapshot, "f"); + break; + } + case 'content_block_start': + case 'message_delta': + break; + } + }, _MessageStream_endRequest = function _MessageStream_endRequest() { + if (this.ended) { + throw new AnthropicError(`stream has ended, this shouldn't happen`); + } + const snapshot = __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f"); + if (!snapshot) { + throw new AnthropicError(`request ended without sending any chunks`); + } + __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, undefined, "f"); + return maybeParseMessage(snapshot, __classPrivateFieldGet(this, _MessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _MessageStream_logger, "f") }); + }, _MessageStream_accumulateMessage = function _MessageStream_accumulateMessage(event) { + let snapshot = __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f"); + if (event.type === 'message_start') { + if (snapshot) { + throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`); + } + return event.message; + } + if (!snapshot) { + throw new AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`); + } + switch (event.type) { + case 'message_stop': + return snapshot; + case 'message_delta': + snapshot.stop_reason = event.delta.stop_reason; + snapshot.stop_sequence = event.delta.stop_sequence; + snapshot.usage.output_tokens = event.usage.output_tokens; + // Update other usage fields if they exist in the event + if (event.usage.input_tokens != null) { + snapshot.usage.input_tokens = event.usage.input_tokens; + } + if (event.usage.cache_creation_input_tokens != null) { + snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens; + } + if (event.usage.cache_read_input_tokens != null) { + snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens; + } + if (event.usage.server_tool_use != null) { + snapshot.usage.server_tool_use = event.usage.server_tool_use; + } + return snapshot; + case 'content_block_start': + snapshot.content.push({ ...event.content_block }); + return snapshot; + case 'content_block_delta': { + const snapshotContent = snapshot.content.at(event.index); + switch (event.delta.type) { + case 'text_delta': { + if (snapshotContent?.type === 'text') { + snapshot.content[event.index] = { + ...snapshotContent, + text: (snapshotContent.text || '') + event.delta.text, + }; + } + break; + } + case 'citations_delta': { + if (snapshotContent?.type === 'text') { + snapshot.content[event.index] = { + ...snapshotContent, + citations: [...(snapshotContent.citations ?? []), event.delta.citation], + }; + } + break; + } + case 'input_json_delta': { + if (snapshotContent && tracksToolInput(snapshotContent)) { + // we need to keep track of the raw JSON string as well so that we can + // re-parse it for each delta, for now we just store it as an untyped + // non-enumerable property on the snapshot + let jsonBuf = snapshotContent[JSON_BUF_PROPERTY] || ''; + jsonBuf += event.delta.partial_json; + const newContent = { ...snapshotContent }; + Object.defineProperty(newContent, JSON_BUF_PROPERTY, { + value: jsonBuf, + enumerable: false, + writable: true, + }); + if (jsonBuf) { + newContent.input = partialParse(jsonBuf); + } + snapshot.content[event.index] = newContent; + } + break; + } + case 'thinking_delta': { + if (snapshotContent?.type === 'thinking') { + snapshot.content[event.index] = { + ...snapshotContent, + thinking: snapshotContent.thinking + event.delta.thinking, + }; + } + break; + } + case 'signature_delta': { + if (snapshotContent?.type === 'thinking') { + snapshot.content[event.index] = { + ...snapshotContent, + signature: event.delta.signature, + }; + } + break; + } + default: + checkNever(event.delta); + } + return snapshot; + } + case 'content_block_stop': + return snapshot; + } + }, Symbol.asyncIterator)]() { + const pushQueue = []; + const readQueue = []; + let done = false; + this.on('streamEvent', (event) => { + const reader = readQueue.shift(); + if (reader) { + reader.resolve(event); + } + else { + pushQueue.push(event); + } + }); + this.on('end', () => { + done = true; + for (const reader of readQueue) { + reader.resolve(undefined); + } + readQueue.length = 0; + }); + this.on('abort', (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + this.on('error', (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + return { + next: async () => { + if (!pushQueue.length) { + if (done) { + return { value: undefined, done: true }; + } + return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true })); + } + const chunk = pushQueue.shift(); + return { value: chunk, done: false }; + }, + return: async () => { + this.abort(); + return { value: undefined, done: true }; + }, + }; + } + toReadableStream() { + const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller); + return stream.toReadableStream(); + } +} +// used to ensure exhaustive case matching without throwing a runtime error +function checkNever(x) { } +//# sourceMappingURL=MessageStream.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/lib/beta-parser.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/lib/beta-parser.mjs new file mode 100644 index 00000000..8d5ba0a6 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/lib/beta-parser.mjs @@ -0,0 +1,75 @@ +import { AnthropicError } from "../core/error.mjs"; +function getOutputFormat(params) { + // Prefer output_format (deprecated) over output_config.format for backward compatibility + return params?.output_format ?? params?.output_config?.format; +} +export function maybeParseBetaMessage(message, params, opts) { + const outputFormat = getOutputFormat(params); + if (!params || !('parse' in (outputFormat ?? {}))) { + return { + ...message, + content: message.content.map((block) => { + if (block.type === 'text') { + const parsedBlock = Object.defineProperty({ ...block }, 'parsed_output', { + value: null, + enumerable: false, + }); + return Object.defineProperty(parsedBlock, 'parsed', { + get() { + opts.logger.warn('The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead.'); + return null; + }, + enumerable: false, + }); + } + return block; + }), + parsed_output: null, + }; + } + return parseBetaMessage(message, params, opts); +} +export function parseBetaMessage(message, params, opts) { + let firstParsedOutput = null; + const content = message.content.map((block) => { + if (block.type === 'text') { + const parsedOutput = parseBetaOutputFormat(params, block.text); + if (firstParsedOutput === null) { + firstParsedOutput = parsedOutput; + } + const parsedBlock = Object.defineProperty({ ...block }, 'parsed_output', { + value: parsedOutput, + enumerable: false, + }); + return Object.defineProperty(parsedBlock, 'parsed', { + get() { + opts.logger.warn('The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead.'); + return parsedOutput; + }, + enumerable: false, + }); + } + return block; + }); + return { + ...message, + content, + parsed_output: firstParsedOutput, + }; +} +function parseBetaOutputFormat(params, content) { + const outputFormat = getOutputFormat(params); + if (outputFormat?.type !== 'json_schema') { + return null; + } + try { + if ('parse' in outputFormat) { + return outputFormat.parse(content); + } + return JSON.parse(content); + } + catch (error) { + throw new AnthropicError(`Failed to parse structured output: ${error}`); + } +} +//# sourceMappingURL=beta-parser.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/lib/parser.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/lib/parser.mjs new file mode 100644 index 00000000..86a0f957 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/lib/parser.mjs @@ -0,0 +1,62 @@ +import { AnthropicError } from "../core/error.mjs"; +function getOutputFormat(params) { + return params?.output_config?.format; +} +export function maybeParseMessage(message, params, opts) { + const outputFormat = getOutputFormat(params); + if (!params || !('parse' in (outputFormat ?? {}))) { + return { + ...message, + content: message.content.map((block) => { + if (block.type === 'text') { + const parsedBlock = Object.defineProperty({ ...block }, 'parsed_output', { + value: null, + enumerable: false, + }); + return parsedBlock; + } + return block; + }), + parsed_output: null, + }; + } + return parseMessage(message, params, opts); +} +export function parseMessage(message, params, opts) { + let firstParsedOutput = null; + const content = message.content.map((block) => { + if (block.type === 'text') { + const parsedOutput = parseOutputFormat(params, block.text); + if (firstParsedOutput === null) { + firstParsedOutput = parsedOutput; + } + const parsedBlock = Object.defineProperty({ ...block }, 'parsed_output', { + value: parsedOutput, + enumerable: false, + }); + return parsedBlock; + } + return block; + }); + return { + ...message, + content, + parsed_output: firstParsedOutput, + }; +} +function parseOutputFormat(params, content) { + const outputFormat = getOutputFormat(params); + if (outputFormat?.type !== 'json_schema') { + return null; + } + try { + if ('parse' in outputFormat) { + return outputFormat.parse(content); + } + return JSON.parse(content); + } + catch (error) { + throw new AnthropicError(`Failed to parse structured output: ${error}`); + } +} +//# sourceMappingURL=parser.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/lib/stainless-helper-header.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/lib/stainless-helper-header.mjs new file mode 100644 index 00000000..cc62422d --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/lib/stainless-helper-header.mjs @@ -0,0 +1,63 @@ +/** + * Shared utilities for tracking SDK helper usage. + */ +/** + * Symbol used to mark objects created by SDK helpers for tracking. + * The value is the helper name (e.g., 'mcpTool', 'betaZodTool'). + */ +export const SDK_HELPER_SYMBOL = Symbol('anthropic.sdk.stainlessHelper'); +export function wasCreatedByStainlessHelper(value) { + return typeof value === 'object' && value !== null && SDK_HELPER_SYMBOL in value; +} +/** + * Collects helper names from tools and messages arrays. + * Returns a deduplicated array of helper names found. + */ +export function collectStainlessHelpers(tools, messages) { + const helpers = new Set(); + // Collect from tools + if (tools) { + for (const tool of tools) { + if (wasCreatedByStainlessHelper(tool)) { + helpers.add(tool[SDK_HELPER_SYMBOL]); + } + } + } + // Collect from messages and their content blocks + if (messages) { + for (const message of messages) { + if (wasCreatedByStainlessHelper(message)) { + helpers.add(message[SDK_HELPER_SYMBOL]); + } + if (Array.isArray(message.content)) { + for (const block of message.content) { + if (wasCreatedByStainlessHelper(block)) { + helpers.add(block[SDK_HELPER_SYMBOL]); + } + } + } + } + } + return Array.from(helpers); +} +/** + * Builds x-stainless-helper header value from tools and messages. + * Returns an empty object if no helpers are found. + */ +export function stainlessHelperHeader(tools, messages) { + const helpers = collectStainlessHelpers(tools, messages); + if (helpers.length === 0) + return {}; + return { 'x-stainless-helper': helpers.join(', ') }; +} +/** + * Builds x-stainless-helper header value from a file object. + * Returns an empty object if the file is not marked with a helper. + */ +export function stainlessHelperHeaderFromFile(file) { + if (wasCreatedByStainlessHelper(file)) { + return { 'x-stainless-helper': file[SDK_HELPER_SYMBOL] }; + } + return {}; +} +//# sourceMappingURL=stainless-helper-header.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/lib/tools/BetaToolRunner.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/lib/tools/BetaToolRunner.mjs new file mode 100644 index 00000000..fa6e3c14 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/lib/tools/BetaToolRunner.mjs @@ -0,0 +1,372 @@ +var _BetaToolRunner_instances, _BetaToolRunner_consumed, _BetaToolRunner_mutated, _BetaToolRunner_state, _BetaToolRunner_options, _BetaToolRunner_message, _BetaToolRunner_toolResponse, _BetaToolRunner_completion, _BetaToolRunner_iterationCount, _BetaToolRunner_checkAndCompact, _BetaToolRunner_generateToolResponse; +import { __classPrivateFieldGet, __classPrivateFieldSet } from "../../internal/tslib.mjs"; +import { ToolError } from "./ToolError.mjs"; +import { AnthropicError } from "../../core/error.mjs"; +import { buildHeaders } from "../../internal/headers.mjs"; +import { DEFAULT_SUMMARY_PROMPT, DEFAULT_TOKEN_THRESHOLD } from "./CompactionControl.mjs"; +import { collectStainlessHelpers } from "../stainless-helper-header.mjs"; +/** + * Just Promise.withResolvers(), which is not available in all environments. + */ +function promiseWithResolvers() { + let resolve; + let reject; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve: resolve, reject: reject }; +} +/** + * A ToolRunner handles the automatic conversation loop between the assistant and tools. + * + * A ToolRunner is an async iterable that yields either BetaMessage or BetaMessageStream objects + * depending on the streaming configuration. + */ +export class BetaToolRunner { + constructor(client, params, options) { + _BetaToolRunner_instances.add(this); + this.client = client; + /** Whether the async iterator has been consumed */ + _BetaToolRunner_consumed.set(this, false); + /** Whether parameters have been mutated since the last API call */ + _BetaToolRunner_mutated.set(this, false); + /** Current state containing the request parameters */ + _BetaToolRunner_state.set(this, void 0); + _BetaToolRunner_options.set(this, void 0); + /** Promise for the last message received from the assistant */ + _BetaToolRunner_message.set(this, void 0); + /** Cached tool response to avoid redundant executions */ + _BetaToolRunner_toolResponse.set(this, void 0); + /** Promise resolvers for waiting on completion */ + _BetaToolRunner_completion.set(this, void 0); + /** Number of iterations (API requests) made so far */ + _BetaToolRunner_iterationCount.set(this, 0); + __classPrivateFieldSet(this, _BetaToolRunner_state, { + params: { + // You can't clone the entire params since there are functions as handlers. + // You also don't really need to clone params.messages, but it probably will prevent a foot gun + // somewhere. + ...params, + messages: structuredClone(params.messages), + }, + }, "f"); + const helpers = collectStainlessHelpers(params.tools, params.messages); + const helperValue = ['BetaToolRunner', ...helpers].join(', '); + __classPrivateFieldSet(this, _BetaToolRunner_options, { + ...options, + headers: buildHeaders([{ 'x-stainless-helper': helperValue }, options?.headers]), + }, "f"); + __classPrivateFieldSet(this, _BetaToolRunner_completion, promiseWithResolvers(), "f"); + } + async *[(_BetaToolRunner_consumed = new WeakMap(), _BetaToolRunner_mutated = new WeakMap(), _BetaToolRunner_state = new WeakMap(), _BetaToolRunner_options = new WeakMap(), _BetaToolRunner_message = new WeakMap(), _BetaToolRunner_toolResponse = new WeakMap(), _BetaToolRunner_completion = new WeakMap(), _BetaToolRunner_iterationCount = new WeakMap(), _BetaToolRunner_instances = new WeakSet(), _BetaToolRunner_checkAndCompact = async function _BetaToolRunner_checkAndCompact() { + const compactionControl = __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.compactionControl; + if (!compactionControl || !compactionControl.enabled) { + return false; + } + let tokensUsed = 0; + if (__classPrivateFieldGet(this, _BetaToolRunner_message, "f") !== undefined) { + try { + const message = await __classPrivateFieldGet(this, _BetaToolRunner_message, "f"); + const totalInputTokens = message.usage.input_tokens + + (message.usage.cache_creation_input_tokens ?? 0) + + (message.usage.cache_read_input_tokens ?? 0); + tokensUsed = totalInputTokens + message.usage.output_tokens; + } + catch { + // If we can't get the message, skip compaction + return false; + } + } + const threshold = compactionControl.contextTokenThreshold ?? DEFAULT_TOKEN_THRESHOLD; + if (tokensUsed < threshold) { + return false; + } + const model = compactionControl.model ?? __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.model; + const summaryPrompt = compactionControl.summaryPrompt ?? DEFAULT_SUMMARY_PROMPT; + const messages = __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages; + if (messages[messages.length - 1].role === 'assistant') { + // Remove tool_use blocks from the last message to avoid 400 error + // (tool_use requires tool_result, which we don't have yet) + const lastMessage = messages[messages.length - 1]; + if (Array.isArray(lastMessage.content)) { + const nonToolBlocks = lastMessage.content.filter((block) => block.type !== 'tool_use'); + if (nonToolBlocks.length === 0) { + // If all blocks were tool_use, just remove the message entirely + messages.pop(); + } + else { + lastMessage.content = nonToolBlocks; + } + } + } + const response = await this.client.beta.messages.create({ + model, + messages: [ + ...messages, + { + role: 'user', + content: [ + { + type: 'text', + text: summaryPrompt, + }, + ], + }, + ], + max_tokens: __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_tokens, + }, { + headers: { 'x-stainless-helper': 'compaction' }, + }); + if (response.content[0]?.type !== 'text') { + throw new AnthropicError('Expected text response for compaction'); + } + __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages = [ + { + role: 'user', + content: response.content, + }, + ]; + return true; + }, Symbol.asyncIterator)]() { + var _a; + if (__classPrivateFieldGet(this, _BetaToolRunner_consumed, "f")) { + throw new AnthropicError('Cannot iterate over a consumed stream'); + } + __classPrivateFieldSet(this, _BetaToolRunner_consumed, true, "f"); + __classPrivateFieldSet(this, _BetaToolRunner_mutated, true, "f"); + __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, undefined, "f"); + try { + while (true) { + let stream; + try { + if (__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_iterations && + __classPrivateFieldGet(this, _BetaToolRunner_iterationCount, "f") >= __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_iterations) { + break; + } + __classPrivateFieldSet(this, _BetaToolRunner_mutated, false, "f"); + __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, undefined, "f"); + __classPrivateFieldSet(this, _BetaToolRunner_iterationCount, (_a = __classPrivateFieldGet(this, _BetaToolRunner_iterationCount, "f"), _a++, _a), "f"); + __classPrivateFieldSet(this, _BetaToolRunner_message, undefined, "f"); + const { max_iterations, compactionControl, ...params } = __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params; + if (params.stream) { + stream = this.client.beta.messages.stream({ ...params }, __classPrivateFieldGet(this, _BetaToolRunner_options, "f")); + __classPrivateFieldSet(this, _BetaToolRunner_message, stream.finalMessage(), "f"); + // Make sure that this promise doesn't throw before we get the option to do something about it. + // Error will be caught when we call await this.#message ultimately + __classPrivateFieldGet(this, _BetaToolRunner_message, "f").catch(() => { }); + yield stream; + } + else { + __classPrivateFieldSet(this, _BetaToolRunner_message, this.client.beta.messages.create({ ...params, stream: false }, __classPrivateFieldGet(this, _BetaToolRunner_options, "f")), "f"); + yield __classPrivateFieldGet(this, _BetaToolRunner_message, "f"); + } + const isCompacted = await __classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_checkAndCompact).call(this); + if (!isCompacted) { + if (!__classPrivateFieldGet(this, _BetaToolRunner_mutated, "f")) { + const { role, content } = await __classPrivateFieldGet(this, _BetaToolRunner_message, "f"); + __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.push({ role, content }); + } + const toolMessage = await __classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_generateToolResponse).call(this, __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.at(-1)); + if (toolMessage) { + __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.push(toolMessage); + } + else if (!__classPrivateFieldGet(this, _BetaToolRunner_mutated, "f")) { + break; + } + } + } + finally { + if (stream) { + stream.abort(); + } + } + } + if (!__classPrivateFieldGet(this, _BetaToolRunner_message, "f")) { + throw new AnthropicError('ToolRunner concluded without a message from the server'); + } + __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").resolve(await __classPrivateFieldGet(this, _BetaToolRunner_message, "f")); + } + catch (error) { + __classPrivateFieldSet(this, _BetaToolRunner_consumed, false, "f"); + // Silence unhandled promise errors + __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").promise.catch(() => { }); + __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").reject(error); + __classPrivateFieldSet(this, _BetaToolRunner_completion, promiseWithResolvers(), "f"); + throw error; + } + } + setMessagesParams(paramsOrMutator) { + if (typeof paramsOrMutator === 'function') { + __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params = paramsOrMutator(__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params); + } + else { + __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params = paramsOrMutator; + } + __classPrivateFieldSet(this, _BetaToolRunner_mutated, true, "f"); + // Invalidate cached tool response since parameters changed + __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, undefined, "f"); + } + /** + * Get the tool response for the last message from the assistant. + * Avoids redundant tool executions by caching results. + * + * @returns A promise that resolves to a BetaMessageParam containing tool results, or null if no tools need to be executed + * + * @example + * const toolResponse = await runner.generateToolResponse(); + * if (toolResponse) { + * console.log('Tool results:', toolResponse.content); + * } + */ + async generateToolResponse() { + const message = (await __classPrivateFieldGet(this, _BetaToolRunner_message, "f")) ?? this.params.messages.at(-1); + if (!message) { + return null; + } + return __classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_generateToolResponse).call(this, message); + } + /** + * Wait for the async iterator to complete. This works even if the async iterator hasn't yet started, and + * will wait for an instance to start and go to completion. + * + * @returns A promise that resolves to the final BetaMessage when the iterator completes + * + * @example + * // Start consuming the iterator + * for await (const message of runner) { + * console.log('Message:', message.content); + * } + * + * // Meanwhile, wait for completion from another part of the code + * const finalMessage = await runner.done(); + * console.log('Final response:', finalMessage.content); + */ + done() { + return __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").promise; + } + /** + * Returns a promise indicating that the stream is done. Unlike .done(), this will eagerly read the stream: + * * If the iterator has not been consumed, consume the entire iterator and return the final message from the + * assistant. + * * If the iterator has been consumed, waits for it to complete and returns the final message. + * + * @returns A promise that resolves to the final BetaMessage from the conversation + * @throws {AnthropicError} If no messages were processed during the conversation + * + * @example + * const finalMessage = await runner.runUntilDone(); + * console.log('Final response:', finalMessage.content); + */ + async runUntilDone() { + // If not yet consumed, start consuming and wait for completion + if (!__classPrivateFieldGet(this, _BetaToolRunner_consumed, "f")) { + for await (const _ of this) { + // Iterator naturally populates this.#message + } + } + // If consumed but not completed, wait for completion + return this.done(); + } + /** + * Get the current parameters being used by the ToolRunner. + * + * @returns A readonly view of the current ToolRunnerParams + * + * @example + * const currentParams = runner.params; + * console.log('Current model:', currentParams.model); + * console.log('Message count:', currentParams.messages.length); + */ + get params() { + return __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params; + } + /** + * Add one or more messages to the conversation history. + * + * @param messages - One or more BetaMessageParam objects to add to the conversation + * + * @example + * runner.pushMessages( + * { role: 'user', content: 'Also, what about the weather in NYC?' } + * ); + * + * @example + * // Adding multiple messages + * runner.pushMessages( + * { role: 'user', content: 'What about NYC?' }, + * { role: 'user', content: 'And Boston?' } + * ); + */ + pushMessages(...messages) { + this.setMessagesParams((params) => ({ + ...params, + messages: [...params.messages, ...messages], + })); + } + /** + * Makes the ToolRunner directly awaitable, equivalent to calling .runUntilDone() + * This allows using `await runner` instead of `await runner.runUntilDone()` + */ + then(onfulfilled, onrejected) { + return this.runUntilDone().then(onfulfilled, onrejected); + } +} +_BetaToolRunner_generateToolResponse = async function _BetaToolRunner_generateToolResponse(lastMessage) { + if (__classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f") !== undefined) { + return __classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f"); + } + __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, generateToolResponse(__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params, lastMessage), "f"); + return __classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f"); +}; +async function generateToolResponse(params, lastMessage = params.messages.at(-1)) { + // Only process if the last message is from the assistant and has tool use blocks + if (!lastMessage || + lastMessage.role !== 'assistant' || + !lastMessage.content || + typeof lastMessage.content === 'string') { + return null; + } + const toolUseBlocks = lastMessage.content.filter((content) => content.type === 'tool_use'); + if (toolUseBlocks.length === 0) { + return null; + } + const toolResults = await Promise.all(toolUseBlocks.map(async (toolUse) => { + const tool = params.tools.find((t) => ('name' in t ? t.name : t.mcp_server_name) === toolUse.name); + if (!tool || !('run' in tool)) { + return { + type: 'tool_result', + tool_use_id: toolUse.id, + content: `Error: Tool '${toolUse.name}' not found`, + is_error: true, + }; + } + try { + let input = toolUse.input; + if ('parse' in tool && tool.parse) { + input = tool.parse(input); + } + const result = await tool.run(input); + return { + type: 'tool_result', + tool_use_id: toolUse.id, + content: result, + }; + } + catch (error) { + return { + type: 'tool_result', + tool_use_id: toolUse.id, + content: error instanceof ToolError ? + error.content + : `Error: ${error instanceof Error ? error.message : String(error)}`, + is_error: true, + }; + } + })); + return { + role: 'user', + content: toolResults, + }; +} +//# sourceMappingURL=BetaToolRunner.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/lib/tools/CompactionControl.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/lib/tools/CompactionControl.mjs new file mode 100644 index 00000000..14e54dd7 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/lib/tools/CompactionControl.mjs @@ -0,0 +1,25 @@ +export const DEFAULT_TOKEN_THRESHOLD = 100000; +export const DEFAULT_SUMMARY_PROMPT = `You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include: +1. Task Overview +The user's core request and success criteria +Any clarifications or constraints they specified +2. Current State +What has been completed so far +Files created, modified, or analyzed (with paths if relevant) +Key outputs or artifacts produced +3. Important Discoveries +Technical constraints or requirements uncovered +Decisions made and their rationale +Errors encountered and how they were resolved +What approaches were tried that didn't work (and why) +4. Next Steps +Specific actions needed to complete the task +Any blockers or open questions to resolve +Priority order if multiple steps remain +5. Context to Preserve +User preferences or style requirements +Domain-specific details that aren't obvious +Any promises made to the user +Be concise but complete—err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task. +Wrap your summary in tags.`; +//# sourceMappingURL=CompactionControl.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/lib/tools/ToolError.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/lib/tools/ToolError.mjs new file mode 100644 index 00000000..805a6a1c --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/lib/tools/ToolError.mjs @@ -0,0 +1,38 @@ +/** + * An error that can be thrown from a tool's `run` method to return structured + * content blocks as the error result, rather than just a string message. + * + * When the ToolRunner catches this error, it will use the `content` property + * as the tool result with `is_error: true`. + * + * @example + * ```ts + * const tool = { + * name: 'my_tool', + * run: async (input) => { + * if (somethingWentWrong) { + * throw new ToolError([ + * { type: 'text', text: 'Error details here' }, + * { type: 'image', source: { type: 'base64', data: '...', media_type: 'image/png' } }, + * ]); + * } + * return 'success'; + * }, + * }; + * ``` + */ +export class ToolError extends Error { + constructor(content) { + const message = typeof content === 'string' ? content : (content + .map((block) => { + if (block.type === 'text') + return block.text; + return `[${block.type}]`; + }) + .join(' ')); + super(message); + this.name = 'ToolError'; + this.content = content; + } +} +//# sourceMappingURL=ToolError.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/beta.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/beta.mjs new file mode 100644 index 00000000..7a998aa4 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/beta.mjs @@ -0,0 +1,24 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from "../../core/resource.mjs"; +import * as FilesAPI from "./files.mjs"; +import { Files, } from "./files.mjs"; +import * as ModelsAPI from "./models.mjs"; +import { Models } from "./models.mjs"; +import * as MessagesAPI from "./messages/messages.mjs"; +import { Messages, } from "./messages/messages.mjs"; +import * as SkillsAPI from "./skills/skills.mjs"; +import { Skills, } from "./skills/skills.mjs"; +export class Beta extends APIResource { + constructor() { + super(...arguments); + this.models = new ModelsAPI.Models(this._client); + this.messages = new MessagesAPI.Messages(this._client); + this.files = new FilesAPI.Files(this._client); + this.skills = new SkillsAPI.Skills(this._client); + } +} +Beta.Models = Models; +Beta.Messages = Messages; +Beta.Files = Files; +Beta.Skills = Skills; +//# sourceMappingURL=beta.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/files.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/files.mjs new file mode 100644 index 00000000..f99b133f --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/files.mjs @@ -0,0 +1,120 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from "../../core/resource.mjs"; +import { Page } from "../../core/pagination.mjs"; +import { buildHeaders } from "../../internal/headers.mjs"; +import { stainlessHelperHeaderFromFile } from "../../lib/stainless-helper-header.mjs"; +import { multipartFormRequestOptions } from "../../internal/uploads.mjs"; +import { path } from "../../internal/utils/path.mjs"; +export class Files extends APIResource { + /** + * List Files + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fileMetadata of client.beta.files.list()) { + * // ... + * } + * ``` + */ + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList('/v1/files', (Page), { + query, + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() }, + options?.headers, + ]), + }); + } + /** + * Delete File + * + * @example + * ```ts + * const deletedFile = await client.beta.files.delete( + * 'file_id', + * ); + * ``` + */ + delete(fileID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.delete(path `/v1/files/${fileID}`, { + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() }, + options?.headers, + ]), + }); + } + /** + * Download File + * + * @example + * ```ts + * const response = await client.beta.files.download( + * 'file_id', + * ); + * + * const content = await response.blob(); + * console.log(content); + * ``` + */ + download(fileID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path `/v1/files/${fileID}/content`, { + ...options, + headers: buildHeaders([ + { + 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString(), + Accept: 'application/binary', + }, + options?.headers, + ]), + __binaryResponse: true, + }); + } + /** + * Get File Metadata + * + * @example + * ```ts + * const fileMetadata = + * await client.beta.files.retrieveMetadata('file_id'); + * ``` + */ + retrieveMetadata(fileID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path `/v1/files/${fileID}`, { + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() }, + options?.headers, + ]), + }); + } + /** + * Upload File + * + * @example + * ```ts + * const fileMetadata = await client.beta.files.upload({ + * file: fs.createReadStream('path/to/file'), + * }); + * ``` + */ + upload(params, options) { + const { betas, ...body } = params; + return this._client.post('/v1/files', multipartFormRequestOptions({ + body, + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() }, + stainlessHelperHeaderFromFile(body.file), + options?.headers, + ]), + }, this._client)); + } +} +//# sourceMappingURL=files.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.mjs new file mode 100644 index 00000000..259c0011 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.mjs @@ -0,0 +1,200 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from "../../../core/resource.mjs"; +import { Page } from "../../../core/pagination.mjs"; +import { buildHeaders } from "../../../internal/headers.mjs"; +import { JSONLDecoder } from "../../../internal/decoders/jsonl.mjs"; +import { AnthropicError } from "../../../error.mjs"; +import { path } from "../../../internal/utils/path.mjs"; +export class Batches extends APIResource { + /** + * Send a batch of Message creation requests. + * + * The Message Batches API can be used to process multiple Messages API requests at + * once. Once a Message Batch is created, it begins processing immediately. Batches + * can take up to 24 hours to complete. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const betaMessageBatch = + * await client.beta.messages.batches.create({ + * requests: [ + * { + * custom_id: 'my-custom-id-1', + * params: { + * max_tokens: 1024, + * messages: [ + * { content: 'Hello, world', role: 'user' }, + * ], + * model: 'claude-opus-4-6', + * }, + * }, + * ], + * }); + * ``` + */ + create(params, options) { + const { betas, ...body } = params; + return this._client.post('/v1/messages/batches?beta=true', { + body, + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, + options?.headers, + ]), + }); + } + /** + * This endpoint is idempotent and can be used to poll for Message Batch + * completion. To access the results of a Message Batch, make a request to the + * `results_url` field in the response. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const betaMessageBatch = + * await client.beta.messages.batches.retrieve( + * 'message_batch_id', + * ); + * ``` + */ + retrieve(messageBatchID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path `/v1/messages/batches/${messageBatchID}?beta=true`, { + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, + options?.headers, + ]), + }); + } + /** + * List all Message Batches within a Workspace. Most recently created batches are + * returned first. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const betaMessageBatch of client.beta.messages.batches.list()) { + * // ... + * } + * ``` + */ + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList('/v1/messages/batches?beta=true', (Page), { + query, + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, + options?.headers, + ]), + }); + } + /** + * Delete a Message Batch. + * + * Message Batches can only be deleted once they've finished processing. If you'd + * like to delete an in-progress batch, you must first cancel it. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const betaDeletedMessageBatch = + * await client.beta.messages.batches.delete( + * 'message_batch_id', + * ); + * ``` + */ + delete(messageBatchID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.delete(path `/v1/messages/batches/${messageBatchID}?beta=true`, { + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, + options?.headers, + ]), + }); + } + /** + * Batches may be canceled any time before processing ends. Once cancellation is + * initiated, the batch enters a `canceling` state, at which time the system may + * complete any in-progress, non-interruptible requests before finalizing + * cancellation. + * + * The number of canceled requests is specified in `request_counts`. To determine + * which requests were canceled, check the individual results within the batch. + * Note that cancellation may not result in any canceled requests if they were + * non-interruptible. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const betaMessageBatch = + * await client.beta.messages.batches.cancel( + * 'message_batch_id', + * ); + * ``` + */ + cancel(messageBatchID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.post(path `/v1/messages/batches/${messageBatchID}/cancel?beta=true`, { + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, + options?.headers, + ]), + }); + } + /** + * Streams the results of a Message Batch as a `.jsonl` file. + * + * Each line in the file is a JSON object containing the result of a single request + * in the Message Batch. Results are not guaranteed to be in the same order as + * requests. Use the `custom_id` field to match results to requests. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const betaMessageBatchIndividualResponse = + * await client.beta.messages.batches.results( + * 'message_batch_id', + * ); + * ``` + */ + async results(messageBatchID, params = {}, options) { + const batch = await this.retrieve(messageBatchID); + if (!batch.results_url) { + throw new AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`); + } + const { betas } = params ?? {}; + return this._client + .get(batch.results_url, { + ...options, + headers: buildHeaders([ + { + 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString(), + Accept: 'application/binary', + }, + options?.headers, + ]), + stream: true, + __binaryResponse: true, + }) + ._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller)); + } +} +//# sourceMappingURL=batches.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.mjs new file mode 100644 index 00000000..e3fcfd1e --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.mjs @@ -0,0 +1,156 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { AnthropicError } from "../../../error.mjs"; +import { APIResource } from "../../../core/resource.mjs"; +import { MODEL_NONSTREAMING_TOKENS } from "../../../internal/constants.mjs"; +import { buildHeaders } from "../../../internal/headers.mjs"; +import { stainlessHelperHeader } from "../../../lib/stainless-helper-header.mjs"; +import { parseBetaMessage, } from "../../../lib/beta-parser.mjs"; +import { BetaMessageStream } from "../../../lib/BetaMessageStream.mjs"; +import { BetaToolRunner, } from "../../../lib/tools/BetaToolRunner.mjs"; +import { ToolError } from "../../../lib/tools/ToolError.mjs"; +import * as BatchesAPI from "./batches.mjs"; +import { Batches, } from "./batches.mjs"; +const DEPRECATED_MODELS = { + 'claude-1.3': 'November 6th, 2024', + 'claude-1.3-100k': 'November 6th, 2024', + 'claude-instant-1.1': 'November 6th, 2024', + 'claude-instant-1.1-100k': 'November 6th, 2024', + 'claude-instant-1.2': 'November 6th, 2024', + 'claude-3-sonnet-20240229': 'July 21st, 2025', + 'claude-3-opus-20240229': 'January 5th, 2026', + 'claude-2.1': 'July 21st, 2025', + 'claude-2.0': 'July 21st, 2025', + 'claude-3-7-sonnet-latest': 'February 19th, 2026', + 'claude-3-7-sonnet-20250219': 'February 19th, 2026', +}; +const MODELS_TO_WARN_WITH_THINKING_ENABLED = ['claude-opus-4-6']; +export class Messages extends APIResource { + constructor() { + super(...arguments); + this.batches = new BatchesAPI.Batches(this._client); + } + create(params, options) { + // Transform deprecated output_format to output_config.format + const modifiedParams = transformOutputFormat(params); + const { betas, ...body } = modifiedParams; + if (body.model in DEPRECATED_MODELS) { + console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS[body.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`); + } + if (body.model in MODELS_TO_WARN_WITH_THINKING_ENABLED && + body.thinking && + body.thinking.type === 'enabled') { + console.warn(`Using Claude with ${body.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`); + } + let timeout = this._client._options.timeout; + if (!body.stream && timeout == null) { + const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? undefined; + timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens); + } + // Collect helper info from tools and messages + const helperHeader = stainlessHelperHeader(body.tools, body.messages); + return this._client.post('/v1/messages?beta=true', { + body, + timeout: timeout ?? 600000, + ...options, + headers: buildHeaders([ + { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, + helperHeader, + options?.headers, + ]), + stream: modifiedParams.stream ?? false, + }); + } + /** + * Send a structured list of input messages with text and/or image content, along with an expected `output_format` and + * the response will be automatically parsed and available in the `parsed_output` property of the message. + * + * @example + * ```ts + * const message = await client.beta.messages.parse({ + * model: 'claude-3-5-sonnet-20241022', + * max_tokens: 1024, + * messages: [{ role: 'user', content: 'What is 2+2?' }], + * output_format: zodOutputFormat(z.object({ answer: z.number() }), 'math'), + * }); + * + * console.log(message.parsed_output?.answer); // 4 + * ``` + */ + parse(params, options) { + options = { + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(params.betas ?? []), 'structured-outputs-2025-12-15'].toString() }, + options?.headers, + ]), + }; + return this.create(params, options).then((message) => parseBetaMessage(message, params, { logger: this._client.logger ?? console })); + } + /** + * Create a Message stream + */ + stream(body, options) { + return BetaMessageStream.createMessage(this, body, options); + } + /** + * Count the number of tokens in a Message. + * + * The Token Count API can be used to count the number of tokens in a Message, + * including tools, images, and documents, without creating it. + * + * Learn more about token counting in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/token-counting) + * + * @example + * ```ts + * const betaMessageTokensCount = + * await client.beta.messages.countTokens({ + * messages: [{ content: 'string', role: 'user' }], + * model: 'claude-opus-4-6', + * }); + * ``` + */ + countTokens(params, options) { + // Transform deprecated output_format to output_config.format + const modifiedParams = transformOutputFormat(params); + const { betas, ...body } = modifiedParams; + return this._client.post('/v1/messages/count_tokens?beta=true', { + body, + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'token-counting-2024-11-01'].toString() }, + options?.headers, + ]), + }); + } + toolRunner(body, options) { + return new BetaToolRunner(this._client, body, options); + } +} +/** + * Transform deprecated output_format to output_config.format + * Returns a modified copy of the params without mutating the original + */ +function transformOutputFormat(params) { + if (!params.output_format) { + return params; + } + if (params.output_config?.format) { + throw new AnthropicError('Both output_format and output_config.format were provided. ' + + 'Please use only output_config.format (output_format is deprecated).'); + } + const { output_format, ...rest } = params; + return { + ...rest, + output_config: { + ...params.output_config, + format: output_format, + }, + }; +} +export { BetaToolRunner } from "../../../lib/tools/BetaToolRunner.mjs"; +export { ToolError } from "../../../lib/tools/ToolError.mjs"; +Messages.Batches = Batches; +Messages.BetaToolRunner = BetaToolRunner; +Messages.ToolError = ToolError; +//# sourceMappingURL=messages.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/models.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/models.mjs new file mode 100644 index 00000000..645c853d --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/models.mjs @@ -0,0 +1,56 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from "../../core/resource.mjs"; +import { Page } from "../../core/pagination.mjs"; +import { buildHeaders } from "../../internal/headers.mjs"; +import { path } from "../../internal/utils/path.mjs"; +export class Models extends APIResource { + /** + * Get a specific model. + * + * The Models API response can be used to determine information about a specific + * model or resolve a model alias to a model ID. + * + * @example + * ```ts + * const betaModelInfo = await client.beta.models.retrieve( + * 'model_id', + * ); + * ``` + */ + retrieve(modelID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path `/v1/models/${modelID}?beta=true`, { + ...options, + headers: buildHeaders([ + { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, + options?.headers, + ]), + }); + } + /** + * List available models. + * + * The Models API response can be used to determine which models are available for + * use in the API. More recently released models are listed first. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const betaModelInfo of client.beta.models.list()) { + * // ... + * } + * ``` + */ + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList('/v1/models?beta=true', (Page), { + query, + ...options, + headers: buildHeaders([ + { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, + options?.headers, + ]), + }); + } +} +//# sourceMappingURL=models.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/skills/skills.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/skills/skills.mjs new file mode 100644 index 00000000..73f3508e --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/skills/skills.mjs @@ -0,0 +1,93 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from "../../../core/resource.mjs"; +import * as VersionsAPI from "./versions.mjs"; +import { Versions, } from "./versions.mjs"; +import { PageCursor } from "../../../core/pagination.mjs"; +import { buildHeaders } from "../../../internal/headers.mjs"; +import { multipartFormRequestOptions } from "../../../internal/uploads.mjs"; +import { path } from "../../../internal/utils/path.mjs"; +export class Skills extends APIResource { + constructor() { + super(...arguments); + this.versions = new VersionsAPI.Versions(this._client); + } + /** + * Create Skill + * + * @example + * ```ts + * const skill = await client.beta.skills.create(); + * ``` + */ + create(params = {}, options) { + const { betas, ...body } = params ?? {}; + return this._client.post('/v1/skills?beta=true', multipartFormRequestOptions({ + body, + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() }, + options?.headers, + ]), + }, this._client, false)); + } + /** + * Get Skill + * + * @example + * ```ts + * const skill = await client.beta.skills.retrieve('skill_id'); + * ``` + */ + retrieve(skillID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path `/v1/skills/${skillID}?beta=true`, { + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() }, + options?.headers, + ]), + }); + } + /** + * List Skills + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const skillListResponse of client.beta.skills.list()) { + * // ... + * } + * ``` + */ + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList('/v1/skills?beta=true', (PageCursor), { + query, + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() }, + options?.headers, + ]), + }); + } + /** + * Delete Skill + * + * @example + * ```ts + * const skill = await client.beta.skills.delete('skill_id'); + * ``` + */ + delete(skillID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.delete(path `/v1/skills/${skillID}?beta=true`, { + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() }, + options?.headers, + ]), + }); + } +} +Skills.Versions = Versions; +//# sourceMappingURL=skills.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/skills/versions.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/skills/versions.mjs new file mode 100644 index 00000000..699cdd11 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/skills/versions.mjs @@ -0,0 +1,96 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from "../../../core/resource.mjs"; +import { PageCursor } from "../../../core/pagination.mjs"; +import { buildHeaders } from "../../../internal/headers.mjs"; +import { multipartFormRequestOptions } from "../../../internal/uploads.mjs"; +import { path } from "../../../internal/utils/path.mjs"; +export class Versions extends APIResource { + /** + * Create Skill Version + * + * @example + * ```ts + * const version = await client.beta.skills.versions.create( + * 'skill_id', + * ); + * ``` + */ + create(skillID, params = {}, options) { + const { betas, ...body } = params ?? {}; + return this._client.post(path `/v1/skills/${skillID}/versions?beta=true`, multipartFormRequestOptions({ + body, + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() }, + options?.headers, + ]), + }, this._client)); + } + /** + * Get Skill Version + * + * @example + * ```ts + * const version = await client.beta.skills.versions.retrieve( + * 'version', + * { skill_id: 'skill_id' }, + * ); + * ``` + */ + retrieve(version, params, options) { + const { skill_id, betas } = params; + return this._client.get(path `/v1/skills/${skill_id}/versions/${version}?beta=true`, { + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() }, + options?.headers, + ]), + }); + } + /** + * List Skill Versions + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const versionListResponse of client.beta.skills.versions.list( + * 'skill_id', + * )) { + * // ... + * } + * ``` + */ + list(skillID, params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList(path `/v1/skills/${skillID}/versions?beta=true`, (PageCursor), { + query, + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() }, + options?.headers, + ]), + }); + } + /** + * Delete Skill Version + * + * @example + * ```ts + * const version = await client.beta.skills.versions.delete( + * 'version', + * { skill_id: 'skill_id' }, + * ); + * ``` + */ + delete(version, params, options) { + const { skill_id, betas } = params; + return this._client.delete(path `/v1/skills/${skill_id}/versions/${version}?beta=true`, { + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() }, + options?.headers, + ]), + }); + } +} +//# sourceMappingURL=versions.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/completions.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/completions.mjs new file mode 100644 index 00000000..648f8e96 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/completions.mjs @@ -0,0 +1,19 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from "../core/resource.mjs"; +import { buildHeaders } from "../internal/headers.mjs"; +export class Completions extends APIResource { + create(params, options) { + const { betas, ...body } = params; + return this._client.post('/v1/complete', { + body, + timeout: this._client._options.timeout ?? 600000, + ...options, + headers: buildHeaders([ + { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, + options?.headers, + ]), + stream: params.stream ?? false, + }); + } +} +//# sourceMappingURL=completions.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/index.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/index.mjs new file mode 100644 index 00000000..01d72943 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/index.mjs @@ -0,0 +1,7 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +export * from "./shared.mjs"; +export { Beta, } from "./beta/beta.mjs"; +export { Completions, } from "./completions.mjs"; +export { Messages, } from "./messages/messages.mjs"; +export { Models, } from "./models.mjs"; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/messages/batches.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/messages/batches.mjs new file mode 100644 index 00000000..d0fedfec --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/messages/batches.mjs @@ -0,0 +1,149 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from "../../core/resource.mjs"; +import { Page } from "../../core/pagination.mjs"; +import { buildHeaders } from "../../internal/headers.mjs"; +import { JSONLDecoder } from "../../internal/decoders/jsonl.mjs"; +import { AnthropicError } from "../../error.mjs"; +import { path } from "../../internal/utils/path.mjs"; +export class Batches extends APIResource { + /** + * Send a batch of Message creation requests. + * + * The Message Batches API can be used to process multiple Messages API requests at + * once. Once a Message Batch is created, it begins processing immediately. Batches + * can take up to 24 hours to complete. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const messageBatch = await client.messages.batches.create({ + * requests: [ + * { + * custom_id: 'my-custom-id-1', + * params: { + * max_tokens: 1024, + * messages: [ + * { content: 'Hello, world', role: 'user' }, + * ], + * model: 'claude-opus-4-6', + * }, + * }, + * ], + * }); + * ``` + */ + create(body, options) { + return this._client.post('/v1/messages/batches', { body, ...options }); + } + /** + * This endpoint is idempotent and can be used to poll for Message Batch + * completion. To access the results of a Message Batch, make a request to the + * `results_url` field in the response. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const messageBatch = await client.messages.batches.retrieve( + * 'message_batch_id', + * ); + * ``` + */ + retrieve(messageBatchID, options) { + return this._client.get(path `/v1/messages/batches/${messageBatchID}`, options); + } + /** + * List all Message Batches within a Workspace. Most recently created batches are + * returned first. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const messageBatch of client.messages.batches.list()) { + * // ... + * } + * ``` + */ + list(query = {}, options) { + return this._client.getAPIList('/v1/messages/batches', (Page), { query, ...options }); + } + /** + * Delete a Message Batch. + * + * Message Batches can only be deleted once they've finished processing. If you'd + * like to delete an in-progress batch, you must first cancel it. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const deletedMessageBatch = + * await client.messages.batches.delete('message_batch_id'); + * ``` + */ + delete(messageBatchID, options) { + return this._client.delete(path `/v1/messages/batches/${messageBatchID}`, options); + } + /** + * Batches may be canceled any time before processing ends. Once cancellation is + * initiated, the batch enters a `canceling` state, at which time the system may + * complete any in-progress, non-interruptible requests before finalizing + * cancellation. + * + * The number of canceled requests is specified in `request_counts`. To determine + * which requests were canceled, check the individual results within the batch. + * Note that cancellation may not result in any canceled requests if they were + * non-interruptible. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const messageBatch = await client.messages.batches.cancel( + * 'message_batch_id', + * ); + * ``` + */ + cancel(messageBatchID, options) { + return this._client.post(path `/v1/messages/batches/${messageBatchID}/cancel`, options); + } + /** + * Streams the results of a Message Batch as a `.jsonl` file. + * + * Each line in the file is a JSON object containing the result of a single request + * in the Message Batch. Results are not guaranteed to be in the same order as + * requests. Use the `custom_id` field to match results to requests. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const messageBatchIndividualResponse = + * await client.messages.batches.results('message_batch_id'); + * ``` + */ + async results(messageBatchID, options) { + const batch = await this.retrieve(messageBatchID); + if (!batch.results_url) { + throw new AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`); + } + return this._client + .get(batch.results_url, { + ...options, + headers: buildHeaders([{ Accept: 'application/binary' }, options?.headers]), + stream: true, + __binaryResponse: true, + }) + ._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller)); + } +} +//# sourceMappingURL=batches.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/messages/messages.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/messages/messages.mjs new file mode 100644 index 00000000..7f0bb155 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/messages/messages.mjs @@ -0,0 +1,123 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from "../../core/resource.mjs"; +import { buildHeaders } from "../../internal/headers.mjs"; +import { stainlessHelperHeader } from "../../lib/stainless-helper-header.mjs"; +import { MessageStream } from "../../lib/MessageStream.mjs"; +import { parseMessage, } from "../../lib/parser.mjs"; +import * as BatchesAPI from "./batches.mjs"; +import { Batches, } from "./batches.mjs"; +import { MODEL_NONSTREAMING_TOKENS } from "../../internal/constants.mjs"; +export class Messages extends APIResource { + constructor() { + super(...arguments); + this.batches = new BatchesAPI.Batches(this._client); + } + create(body, options) { + if (body.model in DEPRECATED_MODELS) { + console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS[body.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`); + } + if (body.model in MODELS_TO_WARN_WITH_THINKING_ENABLED && + body.thinking && + body.thinking.type === 'enabled') { + console.warn(`Using Claude with ${body.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`); + } + let timeout = this._client._options.timeout; + if (!body.stream && timeout == null) { + const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? undefined; + timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens); + } + // Collect helper info from tools and messages + const helperHeader = stainlessHelperHeader(body.tools, body.messages); + return this._client.post('/v1/messages', { + body, + timeout: timeout ?? 600000, + ...options, + headers: buildHeaders([helperHeader, options?.headers]), + stream: body.stream ?? false, + }); + } + /** + * Send a structured list of input messages with text and/or image content, along with an expected `output_config.format` and + * the response will be automatically parsed and available in the `parsed_output` property of the message. + * + * @example + * ```ts + * const message = await client.messages.parse({ + * model: 'claude-sonnet-4-5-20250929', + * max_tokens: 1024, + * messages: [{ role: 'user', content: 'What is 2+2?' }], + * output_config: { + * format: zodOutputFormat(z.object({ answer: z.number() })), + * }, + * }); + * + * console.log(message.parsed_output?.answer); // 4 + * ``` + */ + parse(params, options) { + return this.create(params, options).then((message) => parseMessage(message, params, { logger: this._client.logger ?? console })); + } + /** + * Create a Message stream. + * + * If `output_config.format` is provided with a parseable format (like `zodOutputFormat()`), + * the final message will include a `parsed_output` property with the parsed content. + * + * @example + * ```ts + * const stream = client.messages.stream({ + * model: 'claude-sonnet-4-5-20250929', + * max_tokens: 1024, + * messages: [{ role: 'user', content: 'What is 2+2?' }], + * output_config: { + * format: zodOutputFormat(z.object({ answer: z.number() })), + * }, + * }); + * + * const message = await stream.finalMessage(); + * console.log(message.parsed_output?.answer); // 4 + * ``` + */ + stream(body, options) { + return MessageStream.createMessage(this, body, options, { logger: this._client.logger ?? console }); + } + /** + * Count the number of tokens in a Message. + * + * The Token Count API can be used to count the number of tokens in a Message, + * including tools, images, and documents, without creating it. + * + * Learn more about token counting in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/token-counting) + * + * @example + * ```ts + * const messageTokensCount = + * await client.messages.countTokens({ + * messages: [{ content: 'string', role: 'user' }], + * model: 'claude-opus-4-6', + * }); + * ``` + */ + countTokens(body, options) { + return this._client.post('/v1/messages/count_tokens', { body, ...options }); + } +} +const DEPRECATED_MODELS = { + 'claude-1.3': 'November 6th, 2024', + 'claude-1.3-100k': 'November 6th, 2024', + 'claude-instant-1.1': 'November 6th, 2024', + 'claude-instant-1.1-100k': 'November 6th, 2024', + 'claude-instant-1.2': 'November 6th, 2024', + 'claude-3-sonnet-20240229': 'July 21st, 2025', + 'claude-3-opus-20240229': 'January 5th, 2026', + 'claude-2.1': 'July 21st, 2025', + 'claude-2.0': 'July 21st, 2025', + 'claude-3-7-sonnet-latest': 'February 19th, 2026', + 'claude-3-7-sonnet-20250219': 'February 19th, 2026', + 'claude-3-5-haiku-latest': 'February 19th, 2026', + 'claude-3-5-haiku-20241022': 'February 19th, 2026', +}; +const MODELS_TO_WARN_WITH_THINKING_ENABLED = ['claude-opus-4-6']; +Messages.Batches = Batches; +//# sourceMappingURL=messages.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/models.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/models.mjs new file mode 100644 index 00000000..15e0aff8 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/models.mjs @@ -0,0 +1,41 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from "../core/resource.mjs"; +import { Page } from "../core/pagination.mjs"; +import { buildHeaders } from "../internal/headers.mjs"; +import { path } from "../internal/utils/path.mjs"; +export class Models extends APIResource { + /** + * Get a specific model. + * + * The Models API response can be used to determine information about a specific + * model or resolve a model alias to a model ID. + */ + retrieve(modelID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path `/v1/models/${modelID}`, { + ...options, + headers: buildHeaders([ + { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, + options?.headers, + ]), + }); + } + /** + * List available models. + * + * The Models API response can be used to determine which models are available for + * use in the API. More recently released models are listed first. + */ + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList('/v1/models', (Page), { + query, + ...options, + headers: buildHeaders([ + { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, + options?.headers, + ]), + }); + } +} +//# sourceMappingURL=models.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/streaming.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/streaming.mjs new file mode 100644 index 00000000..5ca840af --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/streaming.mjs @@ -0,0 +1,2 @@ +export * from "./core/streaming.mjs"; +//# sourceMappingURL=streaming.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/version.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/version.mjs new file mode 100644 index 00000000..7e0b250b --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/sdk/version.mjs @@ -0,0 +1,2 @@ +export const VERSION = '0.74.0'; // x-release-please-version +//# sourceMappingURL=version.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/client.mjs b/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/client.mjs new file mode 100644 index 00000000..db0d13a9 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/client.mjs @@ -0,0 +1,114 @@ +import { BaseAnthropic } from '@anthropic-ai/sdk/client'; +import * as Resources from '@anthropic-ai/sdk/resources/index'; +import { GoogleAuth } from 'google-auth-library'; +import { readEnv } from "./internal/utils/env.mjs"; +import { isObj } from "./internal/utils/values.mjs"; +import { buildHeaders } from "./internal/headers.mjs"; +export { BaseAnthropic } from '@anthropic-ai/sdk/client'; +const DEFAULT_VERSION = 'vertex-2023-10-16'; +const MODEL_ENDPOINTS = new Set(['/v1/messages', '/v1/messages?beta=true']); +export class AnthropicVertex extends BaseAnthropic { + /** + * API Client for interfacing with the Anthropic Vertex API. + * + * @param {string | null} opts.accessToken + * @param {string | null} opts.projectId + * @param {GoogleAuth} opts.googleAuth - Override the default google auth config + * @param {AuthClient} opts.authClient - Provide a pre-configured AuthClient instance (alternative to googleAuth) + * @param {string | null} [opts.region=process.env['CLOUD_ML_REGION']] - The region to use for the API. Use 'global' for global endpoint. [More details here](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations). + * @param {string} [opts.baseURL=process.env['ANTHROPIC_VERTEX__BASE_URL'] ?? https://${region}-aiplatform.googleapis.com/v1] - Override the default base URL for the API. + * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. + * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. + * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. + */ + constructor({ baseURL = readEnv('ANTHROPIC_VERTEX_BASE_URL'), region = readEnv('CLOUD_ML_REGION') ?? null, projectId = readEnv('ANTHROPIC_VERTEX_PROJECT_ID') ?? null, ...opts } = {}) { + if (!region) { + throw new Error('No region was given. The client should be instantiated with the `region` option or the `CLOUD_ML_REGION` environment variable should be set.'); + } + super({ + baseURL: baseURL || + (region === 'global' ? + 'https://aiplatform.googleapis.com/v1' + : `https://${region}-aiplatform.googleapis.com/v1`), + ...opts, + }); + this.messages = makeMessagesResource(this); + this.beta = makeBetaResource(this); + this.region = region; + this.projectId = projectId; + this.accessToken = opts.accessToken ?? null; + if (opts.authClient && opts.googleAuth) { + throw new Error('You cannot provide both `authClient` and `googleAuth`. Please provide only one of them.'); + } + else if (opts.authClient) { + this._authClientPromise = Promise.resolve(opts.authClient); + } + else { + this._auth = + opts.googleAuth ?? new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/cloud-platform' }); + this._authClientPromise = this._auth.getClient(); + } + } + validateHeaders() { + // auth validation is handled in prepareOptions since it needs to be async + } + async prepareOptions(options) { + const authClient = await this._authClientPromise; + const authHeaders = await authClient.getRequestHeaders(); + const projectId = authClient.projectId ?? authHeaders['x-goog-user-project']; + if (!this.projectId && projectId) { + this.projectId = projectId; + } + options.headers = buildHeaders([authHeaders, options.headers]); + } + async buildRequest(options) { + if (isObj(options.body)) { + // create a shallow copy of the request body so that code that mutates it later + // doesn't mutate the original user-provided object + options.body = { ...options.body }; + } + if (isObj(options.body)) { + if (!options.body['anthropic_version']) { + options.body['anthropic_version'] = DEFAULT_VERSION; + } + } + if (MODEL_ENDPOINTS.has(options.path) && options.method === 'post') { + if (!this.projectId) { + throw new Error('No projectId was given and it could not be resolved from credentials. The client should be instantiated with the `projectId` option or the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable should be set.'); + } + if (!isObj(options.body)) { + throw new Error('Expected request body to be an object for post /v1/messages'); + } + const model = options.body['model']; + options.body['model'] = undefined; + const stream = options.body['stream'] ?? false; + const specifier = stream ? 'streamRawPredict' : 'rawPredict'; + options.path = `/projects/${this.projectId}/locations/${this.region}/publishers/anthropic/models/${model}:${specifier}`; + } + if (options.path === '/v1/messages/count_tokens' || + (options.path == '/v1/messages/count_tokens?beta=true' && options.method === 'post')) { + if (!this.projectId) { + throw new Error('No projectId was given and it could not be resolved from credentials. The client should be instantiated with the `projectId` option or the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable should be set.'); + } + options.path = `/projects/${this.projectId}/locations/${this.region}/publishers/anthropic/models/count-tokens:rawPredict`; + } + return super.buildRequest(options); + } +} +function makeMessagesResource(client) { + const resource = new Resources.Messages(client); + // @ts-expect-error we're deleting non-optional properties + delete resource.batches; + return resource; +} +function makeBetaResource(client) { + const resource = new Resources.Beta(client); + // @ts-expect-error we're deleting non-optional properties + delete resource.messages.batches; + return resource; +} +//# sourceMappingURL=client.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/core/error.mjs b/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/core/error.mjs new file mode 100644 index 00000000..ea9269e5 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/core/error.mjs @@ -0,0 +1,2 @@ +export * from '@anthropic-ai/sdk/core/error'; +//# sourceMappingURL=error.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/index.mjs b/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/index.mjs new file mode 100644 index 00000000..3f2aa54b --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/index.mjs @@ -0,0 +1,3 @@ +export * from "./client.mjs"; +export { AnthropicVertex as default } from "./client.mjs"; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/internal/headers.mjs b/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/internal/headers.mjs new file mode 100644 index 00000000..94b059b4 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/internal/headers.mjs @@ -0,0 +1,74 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { isReadonlyArray } from "./utils/values.mjs"; +const brand_privateNullableHeaders = Symbol.for('brand.privateNullableHeaders'); +function* iterateHeaders(headers) { + if (!headers) + return; + if (brand_privateNullableHeaders in headers) { + const { values, nulls } = headers; + yield* values.entries(); + for (const name of nulls) { + yield [name, null]; + } + return; + } + let shouldClear = false; + let iter; + if (headers instanceof Headers) { + iter = headers.entries(); + } + else if (isReadonlyArray(headers)) { + iter = headers; + } + else { + shouldClear = true; + iter = Object.entries(headers ?? {}); + } + for (let row of iter) { + const name = row[0]; + if (typeof name !== 'string') + throw new TypeError('expected header name to be a string'); + const values = isReadonlyArray(row[1]) ? row[1] : [row[1]]; + let didClear = false; + for (const value of values) { + if (value === undefined) + continue; + // Objects keys always overwrite older headers, they never append. + // Yield a null to clear the header before adding the new values. + if (shouldClear && !didClear) { + didClear = true; + yield [name, null]; + } + yield [name, value]; + } + } +} +export const buildHeaders = (newHeaders) => { + const targetHeaders = new Headers(); + const nullHeaders = new Set(); + for (const headers of newHeaders) { + const seenHeaders = new Set(); + for (const [name, value] of iterateHeaders(headers)) { + const lowerName = name.toLowerCase(); + if (!seenHeaders.has(lowerName)) { + targetHeaders.delete(name); + seenHeaders.add(lowerName); + } + if (value === null) { + targetHeaders.delete(name); + nullHeaders.add(lowerName); + } + else { + targetHeaders.append(name, value); + nullHeaders.delete(lowerName); + } + } + } + return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders }; +}; +export const isEmptyHeaders = (headers) => { + for (const _ of iterateHeaders(headers)) + return false; + return true; +}; +//# sourceMappingURL=headers.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/internal/utils/env.mjs b/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/internal/utils/env.mjs new file mode 100644 index 00000000..58ddfda1 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/internal/utils/env.mjs @@ -0,0 +1,18 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +/** + * Read an environment variable. + * + * Trims beginning and trailing whitespace. + * + * Will return undefined if the environment variable doesn't exist or cannot be accessed. + */ +export const readEnv = (env) => { + if (typeof globalThis.process !== 'undefined') { + return globalThis.process.env?.[env]?.trim() ?? undefined; + } + if (typeof globalThis.Deno !== 'undefined') { + return globalThis.Deno.env?.get?.(env)?.trim(); + } + return undefined; +}; +//# sourceMappingURL=env.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/internal/utils/values.mjs b/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/internal/utils/values.mjs new file mode 100644 index 00000000..40388cf3 --- /dev/null +++ b/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/internal/utils/values.mjs @@ -0,0 +1,94 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { AnthropicError } from "../../core/error.mjs"; +// https://url.spec.whatwg.org/#url-scheme-string +const startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i; +export const isAbsoluteURL = (url) => { + return startsWithSchemeRegexp.test(url); +}; +export let isArray = (val) => ((isArray = Array.isArray), isArray(val)); +export let isReadonlyArray = isArray; +/** Returns an object if the given value isn't an object, otherwise returns as-is */ +export function maybeObj(x) { + if (typeof x !== 'object') { + return {}; + } + return x ?? {}; +} +// https://stackoverflow.com/a/34491287 +export function isEmptyObj(obj) { + if (!obj) + return true; + for (const _k in obj) + return false; + return true; +} +// https://eslint.org/docs/latest/rules/no-prototype-builtins +export function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} +export function isObj(obj) { + return obj != null && typeof obj === 'object' && !Array.isArray(obj); +} +export const ensurePresent = (value) => { + if (value == null) { + throw new AnthropicError(`Expected a value to be given but received ${value} instead.`); + } + return value; +}; +export const validatePositiveInteger = (name, n) => { + if (typeof n !== 'number' || !Number.isInteger(n)) { + throw new AnthropicError(`${name} must be an integer`); + } + if (n < 0) { + throw new AnthropicError(`${name} must be a positive integer`); + } + return n; +}; +export const coerceInteger = (value) => { + if (typeof value === 'number') + return Math.round(value); + if (typeof value === 'string') + return parseInt(value, 10); + throw new AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`); +}; +export const coerceFloat = (value) => { + if (typeof value === 'number') + return value; + if (typeof value === 'string') + return parseFloat(value); + throw new AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`); +}; +export const coerceBoolean = (value) => { + if (typeof value === 'boolean') + return value; + if (typeof value === 'string') + return value === 'true'; + return Boolean(value); +}; +export const maybeCoerceInteger = (value) => { + if (value == null) { + return undefined; + } + return coerceInteger(value); +}; +export const maybeCoerceFloat = (value) => { + if (value == null) { + return undefined; + } + return coerceFloat(value); +}; +export const maybeCoerceBoolean = (value) => { + if (value == null) { + return undefined; + } + return coerceBoolean(value); +}; +export const safeJSON = (text) => { + try { + return JSON.parse(text); + } + catch (err) { + return undefined; + } +}; +//# sourceMappingURL=values.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@aws-crypto/crc32/build/main/aws_crc32.js b/claude-code-source/node_modules/@aws-crypto/crc32/build/main/aws_crc32.js new file mode 100644 index 00000000..09c304cd --- /dev/null +++ b/claude-code-source/node_modules/@aws-crypto/crc32/build/main/aws_crc32.js @@ -0,0 +1,31 @@ +"use strict"; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AwsCrc32 = void 0; +var tslib_1 = require("tslib"); +var util_1 = require("@aws-crypto/util"); +var index_1 = require("./index"); +var AwsCrc32 = /** @class */ (function () { + function AwsCrc32() { + this.crc32 = new index_1.Crc32(); + } + AwsCrc32.prototype.update = function (toHash) { + if ((0, util_1.isEmptyData)(toHash)) + return; + this.crc32.update((0, util_1.convertToBuffer)(toHash)); + }; + AwsCrc32.prototype.digest = function () { + return tslib_1.__awaiter(this, void 0, void 0, function () { + return tslib_1.__generator(this, function (_a) { + return [2 /*return*/, (0, util_1.numToUint8)(this.crc32.digest())]; + }); + }); + }; + AwsCrc32.prototype.reset = function () { + this.crc32 = new index_1.Crc32(); + }; + return AwsCrc32; +}()); +exports.AwsCrc32 = AwsCrc32; +//# sourceMappingURL=aws_crc32.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@aws-crypto/crc32/build/main/index.js b/claude-code-source/node_modules/@aws-crypto/crc32/build/main/index.js new file mode 100644 index 00000000..fa789688 --- /dev/null +++ b/claude-code-source/node_modules/@aws-crypto/crc32/build/main/index.js @@ -0,0 +1,108 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AwsCrc32 = exports.Crc32 = exports.crc32 = void 0; +var tslib_1 = require("tslib"); +var util_1 = require("@aws-crypto/util"); +function crc32(data) { + return new Crc32().update(data).digest(); +} +exports.crc32 = crc32; +var Crc32 = /** @class */ (function () { + function Crc32() { + this.checksum = 0xffffffff; + } + Crc32.prototype.update = function (data) { + var e_1, _a; + try { + for (var data_1 = tslib_1.__values(data), data_1_1 = data_1.next(); !data_1_1.done; data_1_1 = data_1.next()) { + var byte = data_1_1.value; + this.checksum = + (this.checksum >>> 8) ^ lookupTable[(this.checksum ^ byte) & 0xff]; + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (data_1_1 && !data_1_1.done && (_a = data_1.return)) _a.call(data_1); + } + finally { if (e_1) throw e_1.error; } + } + return this; + }; + Crc32.prototype.digest = function () { + return (this.checksum ^ 0xffffffff) >>> 0; + }; + return Crc32; +}()); +exports.Crc32 = Crc32; +// prettier-ignore +var a_lookUpTable = [ + 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, + 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, + 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, + 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, + 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, + 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, + 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, + 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, + 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, + 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, + 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, + 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, + 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, + 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, + 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, + 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, + 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, + 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, + 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, + 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, + 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, + 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, + 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, + 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, + 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, + 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, + 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, + 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, + 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, + 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, + 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, + 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, + 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, + 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, + 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, + 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, + 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, + 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, + 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, + 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, + 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, + 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, + 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, + 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, + 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, + 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, + 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, + 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, + 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, + 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, + 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, + 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, + 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, + 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, + 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, + 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, + 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, + 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, + 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, + 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, + 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, + 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, + 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, + 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D, +]; +var lookupTable = (0, util_1.uint32ArrayFrom)(a_lookUpTable); +var aws_crc32_1 = require("./aws_crc32"); +Object.defineProperty(exports, "AwsCrc32", { enumerable: true, get: function () { return aws_crc32_1.AwsCrc32; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/convertToBuffer.js b/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/convertToBuffer.js new file mode 100644 index 00000000..85bc8af4 --- /dev/null +++ b/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/convertToBuffer.js @@ -0,0 +1,24 @@ +"use strict"; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +Object.defineProperty(exports, "__esModule", { value: true }); +exports.convertToBuffer = void 0; +var util_utf8_1 = require("@smithy/util-utf8"); +// Quick polyfill +var fromUtf8 = typeof Buffer !== "undefined" && Buffer.from + ? function (input) { return Buffer.from(input, "utf8"); } + : util_utf8_1.fromUtf8; +function convertToBuffer(data) { + // Already a Uint8, do nothing + if (data instanceof Uint8Array) + return data; + if (typeof data === "string") { + return fromUtf8(data); + } + if (ArrayBuffer.isView(data)) { + return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); + } + return new Uint8Array(data); +} +exports.convertToBuffer = convertToBuffer; +//# sourceMappingURL=convertToBuffer.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/index.js b/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/index.js new file mode 100644 index 00000000..94e1ca90 --- /dev/null +++ b/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/index.js @@ -0,0 +1,14 @@ +"use strict"; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +Object.defineProperty(exports, "__esModule", { value: true }); +exports.uint32ArrayFrom = exports.numToUint8 = exports.isEmptyData = exports.convertToBuffer = void 0; +var convertToBuffer_1 = require("./convertToBuffer"); +Object.defineProperty(exports, "convertToBuffer", { enumerable: true, get: function () { return convertToBuffer_1.convertToBuffer; } }); +var isEmptyData_1 = require("./isEmptyData"); +Object.defineProperty(exports, "isEmptyData", { enumerable: true, get: function () { return isEmptyData_1.isEmptyData; } }); +var numToUint8_1 = require("./numToUint8"); +Object.defineProperty(exports, "numToUint8", { enumerable: true, get: function () { return numToUint8_1.numToUint8; } }); +var uint32ArrayFrom_1 = require("./uint32ArrayFrom"); +Object.defineProperty(exports, "uint32ArrayFrom", { enumerable: true, get: function () { return uint32ArrayFrom_1.uint32ArrayFrom; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/isEmptyData.js b/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/isEmptyData.js new file mode 100644 index 00000000..6af1e89e --- /dev/null +++ b/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/isEmptyData.js @@ -0,0 +1,13 @@ +"use strict"; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isEmptyData = void 0; +function isEmptyData(data) { + if (typeof data === "string") { + return data.length === 0; + } + return data.byteLength === 0; +} +exports.isEmptyData = isEmptyData; +//# sourceMappingURL=isEmptyData.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/numToUint8.js b/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/numToUint8.js new file mode 100644 index 00000000..2f070e10 --- /dev/null +++ b/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/numToUint8.js @@ -0,0 +1,15 @@ +"use strict"; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +Object.defineProperty(exports, "__esModule", { value: true }); +exports.numToUint8 = void 0; +function numToUint8(num) { + return new Uint8Array([ + (num & 0xff000000) >> 24, + (num & 0x00ff0000) >> 16, + (num & 0x0000ff00) >> 8, + num & 0x000000ff, + ]); +} +exports.numToUint8 = numToUint8; +//# sourceMappingURL=numToUint8.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/uint32ArrayFrom.js b/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/uint32ArrayFrom.js new file mode 100644 index 00000000..226cdc3d --- /dev/null +++ b/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/uint32ArrayFrom.js @@ -0,0 +1,20 @@ +"use strict"; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +Object.defineProperty(exports, "__esModule", { value: true }); +exports.uint32ArrayFrom = void 0; +// IE 11 does not support Array.from, so we do it manually +function uint32ArrayFrom(a_lookUpTable) { + if (!Uint32Array.from) { + var return_array = new Uint32Array(a_lookUpTable.length); + var a_index = 0; + while (a_index < a_lookUpTable.length) { + return_array[a_index] = a_lookUpTable[a_index]; + a_index += 1; + } + return return_array; + } + return Uint32Array.from(a_lookUpTable); +} +exports.uint32ArrayFrom = uint32ArrayFrom; +//# sourceMappingURL=uint32ArrayFrom.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8/dist-cjs/index.js b/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8/dist-cjs/index.js new file mode 100644 index 00000000..0b22680a --- /dev/null +++ b/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8/dist-cjs/index.js @@ -0,0 +1,65 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + fromUtf8: () => fromUtf8, + toUint8Array: () => toUint8Array, + toUtf8: () => toUtf8 +}); +module.exports = __toCommonJS(src_exports); + +// src/fromUtf8.ts +var import_util_buffer_from = require("@smithy/util-buffer-from"); +var fromUtf8 = /* @__PURE__ */ __name((input) => { + const buf = (0, import_util_buffer_from.fromString)(input, "utf8"); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); +}, "fromUtf8"); + +// src/toUint8Array.ts +var toUint8Array = /* @__PURE__ */ __name((data) => { + if (typeof data === "string") { + return fromUtf8(data); + } + if (ArrayBuffer.isView(data)) { + return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); + } + return new Uint8Array(data); +}, "toUint8Array"); + +// src/toUtf8.ts + +var toUtf8 = /* @__PURE__ */ __name((input) => { + if (typeof input === "string") { + return input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); + } + return (0, import_util_buffer_from.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); +}, "toUtf8"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (module.exports = { + fromUtf8, + toUint8Array, + toUtf8 +}); + diff --git a/claude-code-source/node_modules/@aws-crypto/sha256-js/build/RawSha256.js b/claude-code-source/node_modules/@aws-crypto/sha256-js/build/RawSha256.js new file mode 100644 index 00000000..68ceaccd --- /dev/null +++ b/claude-code-source/node_modules/@aws-crypto/sha256-js/build/RawSha256.js @@ -0,0 +1,124 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RawSha256 = void 0; +var constants_1 = require("./constants"); +/** + * @internal + */ +var RawSha256 = /** @class */ (function () { + function RawSha256() { + this.state = Int32Array.from(constants_1.INIT); + this.temp = new Int32Array(64); + this.buffer = new Uint8Array(64); + this.bufferLength = 0; + this.bytesHashed = 0; + /** + * @internal + */ + this.finished = false; + } + RawSha256.prototype.update = function (data) { + if (this.finished) { + throw new Error("Attempted to update an already finished hash."); + } + var position = 0; + var byteLength = data.byteLength; + this.bytesHashed += byteLength; + if (this.bytesHashed * 8 > constants_1.MAX_HASHABLE_LENGTH) { + throw new Error("Cannot hash more than 2^53 - 1 bits"); + } + while (byteLength > 0) { + this.buffer[this.bufferLength++] = data[position++]; + byteLength--; + if (this.bufferLength === constants_1.BLOCK_SIZE) { + this.hashBuffer(); + this.bufferLength = 0; + } + } + }; + RawSha256.prototype.digest = function () { + if (!this.finished) { + var bitsHashed = this.bytesHashed * 8; + var bufferView = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength); + var undecoratedLength = this.bufferLength; + bufferView.setUint8(this.bufferLength++, 0x80); + // Ensure the final block has enough room for the hashed length + if (undecoratedLength % constants_1.BLOCK_SIZE >= constants_1.BLOCK_SIZE - 8) { + for (var i = this.bufferLength; i < constants_1.BLOCK_SIZE; i++) { + bufferView.setUint8(i, 0); + } + this.hashBuffer(); + this.bufferLength = 0; + } + for (var i = this.bufferLength; i < constants_1.BLOCK_SIZE - 8; i++) { + bufferView.setUint8(i, 0); + } + bufferView.setUint32(constants_1.BLOCK_SIZE - 8, Math.floor(bitsHashed / 0x100000000), true); + bufferView.setUint32(constants_1.BLOCK_SIZE - 4, bitsHashed); + this.hashBuffer(); + this.finished = true; + } + // The value in state is little-endian rather than big-endian, so flip + // each word into a new Uint8Array + var out = new Uint8Array(constants_1.DIGEST_LENGTH); + for (var i = 0; i < 8; i++) { + out[i * 4] = (this.state[i] >>> 24) & 0xff; + out[i * 4 + 1] = (this.state[i] >>> 16) & 0xff; + out[i * 4 + 2] = (this.state[i] >>> 8) & 0xff; + out[i * 4 + 3] = (this.state[i] >>> 0) & 0xff; + } + return out; + }; + RawSha256.prototype.hashBuffer = function () { + var _a = this, buffer = _a.buffer, state = _a.state; + var state0 = state[0], state1 = state[1], state2 = state[2], state3 = state[3], state4 = state[4], state5 = state[5], state6 = state[6], state7 = state[7]; + for (var i = 0; i < constants_1.BLOCK_SIZE; i++) { + if (i < 16) { + this.temp[i] = + ((buffer[i * 4] & 0xff) << 24) | + ((buffer[i * 4 + 1] & 0xff) << 16) | + ((buffer[i * 4 + 2] & 0xff) << 8) | + (buffer[i * 4 + 3] & 0xff); + } + else { + var u = this.temp[i - 2]; + var t1_1 = ((u >>> 17) | (u << 15)) ^ ((u >>> 19) | (u << 13)) ^ (u >>> 10); + u = this.temp[i - 15]; + var t2_1 = ((u >>> 7) | (u << 25)) ^ ((u >>> 18) | (u << 14)) ^ (u >>> 3); + this.temp[i] = + ((t1_1 + this.temp[i - 7]) | 0) + ((t2_1 + this.temp[i - 16]) | 0); + } + var t1 = ((((((state4 >>> 6) | (state4 << 26)) ^ + ((state4 >>> 11) | (state4 << 21)) ^ + ((state4 >>> 25) | (state4 << 7))) + + ((state4 & state5) ^ (~state4 & state6))) | + 0) + + ((state7 + ((constants_1.KEY[i] + this.temp[i]) | 0)) | 0)) | + 0; + var t2 = ((((state0 >>> 2) | (state0 << 30)) ^ + ((state0 >>> 13) | (state0 << 19)) ^ + ((state0 >>> 22) | (state0 << 10))) + + ((state0 & state1) ^ (state0 & state2) ^ (state1 & state2))) | + 0; + state7 = state6; + state6 = state5; + state5 = state4; + state4 = (state3 + t1) | 0; + state3 = state2; + state2 = state1; + state1 = state0; + state0 = (t1 + t2) | 0; + } + state[0] += state0; + state[1] += state1; + state[2] += state2; + state[3] += state3; + state[4] += state4; + state[5] += state5; + state[6] += state6; + state[7] += state7; + }; + return RawSha256; +}()); +exports.RawSha256 = RawSha256; +//# sourceMappingURL=RawSha256.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@aws-crypto/sha256-js/build/constants.js b/claude-code-source/node_modules/@aws-crypto/sha256-js/build/constants.js new file mode 100644 index 00000000..c83aa099 --- /dev/null +++ b/claude-code-source/node_modules/@aws-crypto/sha256-js/build/constants.js @@ -0,0 +1,98 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MAX_HASHABLE_LENGTH = exports.INIT = exports.KEY = exports.DIGEST_LENGTH = exports.BLOCK_SIZE = void 0; +/** + * @internal + */ +exports.BLOCK_SIZE = 64; +/** + * @internal + */ +exports.DIGEST_LENGTH = 32; +/** + * @internal + */ +exports.KEY = new Uint32Array([ + 0x428a2f98, + 0x71374491, + 0xb5c0fbcf, + 0xe9b5dba5, + 0x3956c25b, + 0x59f111f1, + 0x923f82a4, + 0xab1c5ed5, + 0xd807aa98, + 0x12835b01, + 0x243185be, + 0x550c7dc3, + 0x72be5d74, + 0x80deb1fe, + 0x9bdc06a7, + 0xc19bf174, + 0xe49b69c1, + 0xefbe4786, + 0x0fc19dc6, + 0x240ca1cc, + 0x2de92c6f, + 0x4a7484aa, + 0x5cb0a9dc, + 0x76f988da, + 0x983e5152, + 0xa831c66d, + 0xb00327c8, + 0xbf597fc7, + 0xc6e00bf3, + 0xd5a79147, + 0x06ca6351, + 0x14292967, + 0x27b70a85, + 0x2e1b2138, + 0x4d2c6dfc, + 0x53380d13, + 0x650a7354, + 0x766a0abb, + 0x81c2c92e, + 0x92722c85, + 0xa2bfe8a1, + 0xa81a664b, + 0xc24b8b70, + 0xc76c51a3, + 0xd192e819, + 0xd6990624, + 0xf40e3585, + 0x106aa070, + 0x19a4c116, + 0x1e376c08, + 0x2748774c, + 0x34b0bcb5, + 0x391c0cb3, + 0x4ed8aa4a, + 0x5b9cca4f, + 0x682e6ff3, + 0x748f82ee, + 0x78a5636f, + 0x84c87814, + 0x8cc70208, + 0x90befffa, + 0xa4506ceb, + 0xbef9a3f7, + 0xc67178f2 +]); +/** + * @internal + */ +exports.INIT = [ + 0x6a09e667, + 0xbb67ae85, + 0x3c6ef372, + 0xa54ff53a, + 0x510e527f, + 0x9b05688c, + 0x1f83d9ab, + 0x5be0cd19 +]; +/** + * @internal + */ +exports.MAX_HASHABLE_LENGTH = Math.pow(2, 53) - 1; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@aws-crypto/sha256-js/build/index.js b/claude-code-source/node_modules/@aws-crypto/sha256-js/build/index.js new file mode 100644 index 00000000..4329f109 --- /dev/null +++ b/claude-code-source/node_modules/@aws-crypto/sha256-js/build/index.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var tslib_1 = require("tslib"); +tslib_1.__exportStar(require("./jsSha256"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@aws-crypto/sha256-js/build/jsSha256.js b/claude-code-source/node_modules/@aws-crypto/sha256-js/build/jsSha256.js new file mode 100644 index 00000000..2a4f2f19 --- /dev/null +++ b/claude-code-source/node_modules/@aws-crypto/sha256-js/build/jsSha256.js @@ -0,0 +1,85 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Sha256 = void 0; +var tslib_1 = require("tslib"); +var constants_1 = require("./constants"); +var RawSha256_1 = require("./RawSha256"); +var util_1 = require("@aws-crypto/util"); +var Sha256 = /** @class */ (function () { + function Sha256(secret) { + this.secret = secret; + this.hash = new RawSha256_1.RawSha256(); + this.reset(); + } + Sha256.prototype.update = function (toHash) { + if ((0, util_1.isEmptyData)(toHash) || this.error) { + return; + } + try { + this.hash.update((0, util_1.convertToBuffer)(toHash)); + } + catch (e) { + this.error = e; + } + }; + /* This synchronous method keeps compatibility + * with the v2 aws-sdk. + */ + Sha256.prototype.digestSync = function () { + if (this.error) { + throw this.error; + } + if (this.outer) { + if (!this.outer.finished) { + this.outer.update(this.hash.digest()); + } + return this.outer.digest(); + } + return this.hash.digest(); + }; + /* The underlying digest method here is synchronous. + * To keep the same interface with the other hash functions + * the default is to expose this as an async method. + * However, it can sometimes be useful to have a sync method. + */ + Sha256.prototype.digest = function () { + return tslib_1.__awaiter(this, void 0, void 0, function () { + return tslib_1.__generator(this, function (_a) { + return [2 /*return*/, this.digestSync()]; + }); + }); + }; + Sha256.prototype.reset = function () { + this.hash = new RawSha256_1.RawSha256(); + if (this.secret) { + this.outer = new RawSha256_1.RawSha256(); + var inner = bufferFromSecret(this.secret); + var outer = new Uint8Array(constants_1.BLOCK_SIZE); + outer.set(inner); + for (var i = 0; i < constants_1.BLOCK_SIZE; i++) { + inner[i] ^= 0x36; + outer[i] ^= 0x5c; + } + this.hash.update(inner); + this.outer.update(outer); + // overwrite the copied key in memory + for (var i = 0; i < inner.byteLength; i++) { + inner[i] = 0; + } + } + }; + return Sha256; +}()); +exports.Sha256 = Sha256; +function bufferFromSecret(secret) { + var input = (0, util_1.convertToBuffer)(secret); + if (input.byteLength > constants_1.BLOCK_SIZE) { + var bufferHash = new RawSha256_1.RawSha256(); + bufferHash.update(input); + input = bufferHash.digest(); + } + var buffer = new Uint8Array(constants_1.BLOCK_SIZE); + buffer.set(input); + return buffer; +} +//# sourceMappingURL=jsSha256.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@aws-crypto/sha256-js/node_modules/tslib/tslib.js b/claude-code-source/node_modules/@aws-crypto/sha256-js/node_modules/tslib/tslib.js new file mode 100644 index 00000000..e5b7c9b8 --- /dev/null +++ b/claude-code-source/node_modules/@aws-crypto/sha256-js/node_modules/tslib/tslib.js @@ -0,0 +1,284 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ + +/* global global, define, System, Reflect, Promise */ +var __extends; +var __assign; +var __rest; +var __decorate; +var __param; +var __metadata; +var __awaiter; +var __generator; +var __exportStar; +var __values; +var __read; +var __spread; +var __spreadArrays; +var __await; +var __asyncGenerator; +var __asyncDelegator; +var __asyncValues; +var __makeTemplateObject; +var __importStar; +var __importDefault; +var __classPrivateFieldGet; +var __classPrivateFieldSet; +var __createBinding; +(function (factory) { + var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; + if (typeof define === "function" && define.amd) { + define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); + } + else if (typeof module === "object" && typeof module.exports === "object") { + factory(createExporter(root, createExporter(module.exports))); + } + else { + factory(createExporter(root)); + } + function createExporter(exports, previous) { + if (exports !== root) { + if (typeof Object.create === "function") { + Object.defineProperty(exports, "__esModule", { value: true }); + } + else { + exports.__esModule = true; + } + } + return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; + } +}) +(function (exporter) { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + + __extends = function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + + __assign = Object.assign || function (t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + + __rest = function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; + }; + + __decorate = function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + + __param = function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + + __metadata = function (metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); + }; + + __awaiter = function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + + __generator = function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + + __createBinding = function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }; + + __exportStar = function (m, exports) { + for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) exports[p] = m[p]; + }; + + __values = function (o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + + __read = function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + + __spread = function () { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; + }; + + __spreadArrays = function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; + }; + + __await = function (v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + }; + + __asyncGenerator = function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + }; + + __asyncDelegator = function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } + }; + + __asyncValues = function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } + }; + + __makeTemplateObject = function (cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; + }; + + __importStar = function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; + }; + + __importDefault = function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + + __classPrivateFieldGet = function (receiver, privateMap) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to get private field on non-instance"); + } + return privateMap.get(receiver); + }; + + __classPrivateFieldSet = function (receiver, privateMap, value) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to set private field on non-instance"); + } + privateMap.set(receiver, value); + return value; + }; + + exporter("__extends", __extends); + exporter("__assign", __assign); + exporter("__rest", __rest); + exporter("__decorate", __decorate); + exporter("__param", __param); + exporter("__metadata", __metadata); + exporter("__awaiter", __awaiter); + exporter("__generator", __generator); + exporter("__exportStar", __exportStar); + exporter("__createBinding", __createBinding); + exporter("__values", __values); + exporter("__read", __read); + exporter("__spread", __spread); + exporter("__spreadArrays", __spreadArrays); + exporter("__await", __await); + exporter("__asyncGenerator", __asyncGenerator); + exporter("__asyncDelegator", __asyncDelegator); + exporter("__asyncValues", __asyncValues); + exporter("__makeTemplateObject", __makeTemplateObject); + exporter("__importStar", __importStar); + exporter("__importDefault", __importDefault); + exporter("__classPrivateFieldGet", __classPrivateFieldGet); + exporter("__classPrivateFieldSet", __classPrivateFieldSet); +}); diff --git a/claude-code-source/node_modules/@aws-crypto/util/build/convertToBuffer.js b/claude-code-source/node_modules/@aws-crypto/util/build/convertToBuffer.js new file mode 100644 index 00000000..6cc8bcfe --- /dev/null +++ b/claude-code-source/node_modules/@aws-crypto/util/build/convertToBuffer.js @@ -0,0 +1,24 @@ +"use strict"; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +Object.defineProperty(exports, "__esModule", { value: true }); +exports.convertToBuffer = void 0; +var util_utf8_browser_1 = require("@aws-sdk/util-utf8-browser"); +// Quick polyfill +var fromUtf8 = typeof Buffer !== "undefined" && Buffer.from + ? function (input) { return Buffer.from(input, "utf8"); } + : util_utf8_browser_1.fromUtf8; +function convertToBuffer(data) { + // Already a Uint8, do nothing + if (data instanceof Uint8Array) + return data; + if (typeof data === "string") { + return fromUtf8(data); + } + if (ArrayBuffer.isView(data)) { + return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); + } + return new Uint8Array(data); +} +exports.convertToBuffer = convertToBuffer; +//# sourceMappingURL=convertToBuffer.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@aws-crypto/util/build/index.js b/claude-code-source/node_modules/@aws-crypto/util/build/index.js new file mode 100644 index 00000000..94e1ca90 --- /dev/null +++ b/claude-code-source/node_modules/@aws-crypto/util/build/index.js @@ -0,0 +1,14 @@ +"use strict"; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +Object.defineProperty(exports, "__esModule", { value: true }); +exports.uint32ArrayFrom = exports.numToUint8 = exports.isEmptyData = exports.convertToBuffer = void 0; +var convertToBuffer_1 = require("./convertToBuffer"); +Object.defineProperty(exports, "convertToBuffer", { enumerable: true, get: function () { return convertToBuffer_1.convertToBuffer; } }); +var isEmptyData_1 = require("./isEmptyData"); +Object.defineProperty(exports, "isEmptyData", { enumerable: true, get: function () { return isEmptyData_1.isEmptyData; } }); +var numToUint8_1 = require("./numToUint8"); +Object.defineProperty(exports, "numToUint8", { enumerable: true, get: function () { return numToUint8_1.numToUint8; } }); +var uint32ArrayFrom_1 = require("./uint32ArrayFrom"); +Object.defineProperty(exports, "uint32ArrayFrom", { enumerable: true, get: function () { return uint32ArrayFrom_1.uint32ArrayFrom; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@aws-crypto/util/build/isEmptyData.js b/claude-code-source/node_modules/@aws-crypto/util/build/isEmptyData.js new file mode 100644 index 00000000..6af1e89e --- /dev/null +++ b/claude-code-source/node_modules/@aws-crypto/util/build/isEmptyData.js @@ -0,0 +1,13 @@ +"use strict"; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isEmptyData = void 0; +function isEmptyData(data) { + if (typeof data === "string") { + return data.length === 0; + } + return data.byteLength === 0; +} +exports.isEmptyData = isEmptyData; +//# sourceMappingURL=isEmptyData.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@aws-crypto/util/build/numToUint8.js b/claude-code-source/node_modules/@aws-crypto/util/build/numToUint8.js new file mode 100644 index 00000000..2f070e10 --- /dev/null +++ b/claude-code-source/node_modules/@aws-crypto/util/build/numToUint8.js @@ -0,0 +1,15 @@ +"use strict"; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +Object.defineProperty(exports, "__esModule", { value: true }); +exports.numToUint8 = void 0; +function numToUint8(num) { + return new Uint8Array([ + (num & 0xff000000) >> 24, + (num & 0x00ff0000) >> 16, + (num & 0x0000ff00) >> 8, + num & 0x000000ff, + ]); +} +exports.numToUint8 = numToUint8; +//# sourceMappingURL=numToUint8.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@aws-crypto/util/build/uint32ArrayFrom.js b/claude-code-source/node_modules/@aws-crypto/util/build/uint32ArrayFrom.js new file mode 100644 index 00000000..226cdc3d --- /dev/null +++ b/claude-code-source/node_modules/@aws-crypto/util/build/uint32ArrayFrom.js @@ -0,0 +1,20 @@ +"use strict"; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +Object.defineProperty(exports, "__esModule", { value: true }); +exports.uint32ArrayFrom = void 0; +// IE 11 does not support Array.from, so we do it manually +function uint32ArrayFrom(a_lookUpTable) { + if (!Uint32Array.from) { + var return_array = new Uint32Array(a_lookUpTable.length); + var a_index = 0; + while (a_index < a_lookUpTable.length) { + return_array[a_index] = a_lookUpTable[a_index]; + a_index += 1; + } + return return_array; + } + return Uint32Array.from(a_lookUpTable); +} +exports.uint32ArrayFrom = uint32ArrayFrom; +//# sourceMappingURL=uint32ArrayFrom.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/auth/httpAuthSchemeProvider.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/auth/httpAuthSchemeProvider.js new file mode 100644 index 00000000..8f0cd2ea --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/auth/httpAuthSchemeProvider.js @@ -0,0 +1,64 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.resolveHttpAuthSchemeConfig = exports.defaultBedrockRuntimeHttpAuthSchemeProvider = exports.defaultBedrockRuntimeHttpAuthSchemeParametersProvider = void 0; +const core_1 = require("@aws-sdk/core"); +const core_2 = require("@smithy/core"); +const util_middleware_1 = require("@smithy/util-middleware"); +const defaultBedrockRuntimeHttpAuthSchemeParametersProvider = async (config, context, input) => { + return { + operation: (0, util_middleware_1.getSmithyContext)(context).operation, + region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || + (() => { + throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); + })(), + }; +}; +exports.defaultBedrockRuntimeHttpAuthSchemeParametersProvider = defaultBedrockRuntimeHttpAuthSchemeParametersProvider; +function createAwsAuthSigv4HttpAuthOption(authParameters) { + return { + schemeId: "aws.auth#sigv4", + signingProperties: { + name: "bedrock", + region: authParameters.region, + }, + propertiesExtractor: (config, context) => ({ + signingProperties: { + config, + context, + }, + }), + }; +} +function createSmithyApiHttpBearerAuthHttpAuthOption(authParameters) { + return { + schemeId: "smithy.api#httpBearerAuth", + propertiesExtractor: ({ profile, filepath, configFilepath, ignoreCache }, context) => ({ + identityProperties: { + profile, + filepath, + configFilepath, + ignoreCache, + }, + }), + }; +} +const defaultBedrockRuntimeHttpAuthSchemeProvider = (authParameters) => { + const options = []; + switch (authParameters.operation) { + default: { + options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); + options.push(createSmithyApiHttpBearerAuthHttpAuthOption(authParameters)); + } + } + return options; +}; +exports.defaultBedrockRuntimeHttpAuthSchemeProvider = defaultBedrockRuntimeHttpAuthSchemeProvider; +const resolveHttpAuthSchemeConfig = (config) => { + const token = (0, core_2.memoizeIdentityProvider)(config.token, core_2.isIdentityExpired, core_2.doesIdentityRequireRefresh); + const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config); + return Object.assign(config_0, { + authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), + token, + }); +}; +exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/endpoint/endpointResolver.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/endpoint/endpointResolver.js new file mode 100644 index 00000000..7258a356 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/endpoint/endpointResolver.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defaultEndpointResolver = void 0; +const util_endpoints_1 = require("@aws-sdk/util-endpoints"); +const util_endpoints_2 = require("@smithy/util-endpoints"); +const ruleset_1 = require("./ruleset"); +const cache = new util_endpoints_2.EndpointCache({ + size: 50, + params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"], +}); +const defaultEndpointResolver = (endpointParams, context = {}) => { + return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { + endpointParams: endpointParams, + logger: context.logger, + })); +}; +exports.defaultEndpointResolver = defaultEndpointResolver; +util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/endpoint/ruleset.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/endpoint/ruleset.js new file mode 100644 index 00000000..cb5b4ac6 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/endpoint/ruleset.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ruleSet = void 0; +const s = "required", t = "fn", u = "argv", v = "ref"; +const a = true, b = "isSet", c = "booleanEquals", d = "error", e = "endpoint", f = "tree", g = "PartitionResult", h = { [s]: false, "type": "string" }, i = { [s]: true, "default": false, "type": "boolean" }, j = { [v]: "Endpoint" }, k = { [t]: c, [u]: [{ [v]: "UseFIPS" }, true] }, l = { [t]: c, [u]: [{ [v]: "UseDualStack" }, true] }, m = {}, n = { [t]: "getAttr", [u]: [{ [v]: g }, "supportsFIPS"] }, o = { [t]: c, [u]: [true, { [t]: "getAttr", [u]: [{ [v]: g }, "supportsDualStack"] }] }, p = [k], q = [l], r = [{ [v]: "Region" }]; +const _data = { version: "1.0", parameters: { Region: h, UseDualStack: i, UseFIPS: i, Endpoint: h }, rules: [{ conditions: [{ [t]: b, [u]: [j] }], rules: [{ conditions: p, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d }, { rules: [{ conditions: q, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d }, { endpoint: { url: j, properties: m, headers: m }, type: e }], type: f }], type: f }, { rules: [{ conditions: [{ [t]: b, [u]: r }], rules: [{ conditions: [{ [t]: "aws.partition", [u]: r, assign: g }], rules: [{ conditions: [k, l], rules: [{ conditions: [{ [t]: c, [u]: [a, n] }, o], rules: [{ rules: [{ endpoint: { url: "https://bedrock-runtime-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: m, headers: m }, type: e }], type: f }], type: f }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d }], type: f }, { conditions: p, rules: [{ conditions: [{ [t]: c, [u]: [n, a] }], rules: [{ rules: [{ endpoint: { url: "https://bedrock-runtime-fips.{Region}.{PartitionResult#dnsSuffix}", properties: m, headers: m }, type: e }], type: f }], type: f }, { error: "FIPS is enabled but this partition does not support FIPS", type: d }], type: f }, { conditions: q, rules: [{ conditions: [o], rules: [{ rules: [{ endpoint: { url: "https://bedrock-runtime.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: m, headers: m }, type: e }], type: f }], type: f }, { error: "DualStack is enabled but this partition does not support DualStack", type: d }], type: f }, { rules: [{ endpoint: { url: "https://bedrock-runtime.{Region}.{PartitionResult#dnsSuffix}", properties: m, headers: m }, type: e }], type: f }], type: f }], type: f }, { error: "Invalid Configuration: Missing Region", type: d }], type: f }] }; +exports.ruleSet = _data; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/index.js new file mode 100644 index 00000000..f541fdbe --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/index.js @@ -0,0 +1,2491 @@ +'use strict'; + +var middlewareEventstream = require('@aws-sdk/middleware-eventstream'); +var middlewareHostHeader = require('@aws-sdk/middleware-host-header'); +var middlewareLogger = require('@aws-sdk/middleware-logger'); +var middlewareRecursionDetection = require('@aws-sdk/middleware-recursion-detection'); +var middlewareUserAgent = require('@aws-sdk/middleware-user-agent'); +var middlewareWebsocket = require('@aws-sdk/middleware-websocket'); +var configResolver = require('@smithy/config-resolver'); +var core = require('@smithy/core'); +var schema = require('@smithy/core/schema'); +var eventstreamSerdeConfigResolver = require('@smithy/eventstream-serde-config-resolver'); +var middlewareContentLength = require('@smithy/middleware-content-length'); +var middlewareEndpoint = require('@smithy/middleware-endpoint'); +var middlewareRetry = require('@smithy/middleware-retry'); +var smithyClient = require('@smithy/smithy-client'); +var httpAuthSchemeProvider = require('./auth/httpAuthSchemeProvider'); +var runtimeConfig = require('./runtimeConfig'); +var regionConfigResolver = require('@aws-sdk/region-config-resolver'); +var protocolHttp = require('@smithy/protocol-http'); + +const resolveClientEndpointParameters = (options) => { + return Object.assign(options, { + useDualstackEndpoint: options.useDualstackEndpoint ?? false, + useFipsEndpoint: options.useFipsEndpoint ?? false, + defaultSigningName: "bedrock", + }); +}; +const commonParams = { + UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, + Endpoint: { type: "builtInParams", name: "endpoint" }, + Region: { type: "builtInParams", name: "region" }, + UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, +}; + +const getHttpAuthExtensionConfiguration = (runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + let _token = runtimeConfig.token; + return { + setHttpAuthScheme(httpAuthScheme) { + const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } + else { + _httpAuthSchemes.splice(index, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; + }, + setToken(token) { + _token = token; + }, + token() { + return _token; + }, + }; +}; +const resolveHttpAuthRuntimeConfig = (config) => { + return { + httpAuthSchemes: config.httpAuthSchemes(), + httpAuthSchemeProvider: config.httpAuthSchemeProvider(), + credentials: config.credentials(), + token: config.token(), + }; +}; + +const resolveRuntimeExtensions = (runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign(regionConfigResolver.getAwsRegionExtensionConfiguration(runtimeConfig), smithyClient.getDefaultExtensionConfiguration(runtimeConfig), protocolHttp.getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig)); + extensions.forEach((extension) => extension.configure(extensionConfiguration)); + return Object.assign(runtimeConfig, regionConfigResolver.resolveAwsRegionExtensionConfiguration(extensionConfiguration), smithyClient.resolveDefaultRuntimeConfig(extensionConfiguration), protocolHttp.resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration)); +}; + +class BedrockRuntimeClient extends smithyClient.Client { + config; + constructor(...[configuration]) { + const _config_0 = runtimeConfig.getRuntimeConfig(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = resolveClientEndpointParameters(_config_0); + const _config_2 = middlewareUserAgent.resolveUserAgentConfig(_config_1); + const _config_3 = middlewareRetry.resolveRetryConfig(_config_2); + const _config_4 = configResolver.resolveRegionConfig(_config_3); + const _config_5 = middlewareHostHeader.resolveHostHeaderConfig(_config_4); + const _config_6 = middlewareEndpoint.resolveEndpointConfig(_config_5); + const _config_7 = eventstreamSerdeConfigResolver.resolveEventStreamSerdeConfig(_config_6); + const _config_8 = httpAuthSchemeProvider.resolveHttpAuthSchemeConfig(_config_7); + const _config_9 = middlewareEventstream.resolveEventStreamConfig(_config_8); + const _config_10 = middlewareWebsocket.resolveWebSocketConfig(_config_9); + const _config_11 = resolveRuntimeExtensions(_config_10, configuration?.extensions || []); + this.config = _config_11; + this.middlewareStack.use(schema.getSchemaSerdePlugin(this.config)); + this.middlewareStack.use(middlewareUserAgent.getUserAgentPlugin(this.config)); + this.middlewareStack.use(middlewareRetry.getRetryPlugin(this.config)); + this.middlewareStack.use(middlewareContentLength.getContentLengthPlugin(this.config)); + this.middlewareStack.use(middlewareHostHeader.getHostHeaderPlugin(this.config)); + this.middlewareStack.use(middlewareLogger.getLoggerPlugin(this.config)); + this.middlewareStack.use(middlewareRecursionDetection.getRecursionDetectionPlugin(this.config)); + this.middlewareStack.use(core.getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { + httpAuthSchemeParametersProvider: httpAuthSchemeProvider.defaultBedrockRuntimeHttpAuthSchemeParametersProvider, + identityProviderConfigProvider: async (config) => new core.DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config.credentials, + "smithy.api#httpBearerAuth": config.token, + }), + })); + this.middlewareStack.use(core.getHttpSigningPlugin(this.config)); + } + destroy() { + super.destroy(); + } +} + +let BedrockRuntimeServiceException$1 = class BedrockRuntimeServiceException extends smithyClient.ServiceException { + constructor(options) { + super(options); + Object.setPrototypeOf(this, BedrockRuntimeServiceException.prototype); + } +}; + +let AccessDeniedException$1 = class AccessDeniedException extends BedrockRuntimeServiceException$1 { + name = "AccessDeniedException"; + $fault = "client"; + constructor(opts) { + super({ + name: "AccessDeniedException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, AccessDeniedException.prototype); + } +}; +let InternalServerException$1 = class InternalServerException extends BedrockRuntimeServiceException$1 { + name = "InternalServerException"; + $fault = "server"; + constructor(opts) { + super({ + name: "InternalServerException", + $fault: "server", + ...opts, + }); + Object.setPrototypeOf(this, InternalServerException.prototype); + } +}; +let ThrottlingException$1 = class ThrottlingException extends BedrockRuntimeServiceException$1 { + name = "ThrottlingException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ThrottlingException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ThrottlingException.prototype); + } +}; +let ValidationException$1 = class ValidationException extends BedrockRuntimeServiceException$1 { + name = "ValidationException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ValidationException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ValidationException.prototype); + } +}; +let ConflictException$1 = class ConflictException extends BedrockRuntimeServiceException$1 { + name = "ConflictException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ConflictException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ConflictException.prototype); + } +}; +let ResourceNotFoundException$1 = class ResourceNotFoundException extends BedrockRuntimeServiceException$1 { + name = "ResourceNotFoundException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ResourceNotFoundException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ResourceNotFoundException.prototype); + } +}; +let ServiceQuotaExceededException$1 = class ServiceQuotaExceededException extends BedrockRuntimeServiceException$1 { + name = "ServiceQuotaExceededException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ServiceQuotaExceededException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ServiceQuotaExceededException.prototype); + } +}; +let ServiceUnavailableException$1 = class ServiceUnavailableException extends BedrockRuntimeServiceException$1 { + name = "ServiceUnavailableException"; + $fault = "server"; + constructor(opts) { + super({ + name: "ServiceUnavailableException", + $fault: "server", + ...opts, + }); + Object.setPrototypeOf(this, ServiceUnavailableException.prototype); + } +}; +let ModelErrorException$1 = class ModelErrorException extends BedrockRuntimeServiceException$1 { + name = "ModelErrorException"; + $fault = "client"; + originalStatusCode; + resourceName; + constructor(opts) { + super({ + name: "ModelErrorException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ModelErrorException.prototype); + this.originalStatusCode = opts.originalStatusCode; + this.resourceName = opts.resourceName; + } +}; +let ModelNotReadyException$1 = class ModelNotReadyException extends BedrockRuntimeServiceException$1 { + name = "ModelNotReadyException"; + $fault = "client"; + $retryable = {}; + constructor(opts) { + super({ + name: "ModelNotReadyException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ModelNotReadyException.prototype); + } +}; +let ModelTimeoutException$1 = class ModelTimeoutException extends BedrockRuntimeServiceException$1 { + name = "ModelTimeoutException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ModelTimeoutException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ModelTimeoutException.prototype); + } +}; +let ModelStreamErrorException$1 = class ModelStreamErrorException extends BedrockRuntimeServiceException$1 { + name = "ModelStreamErrorException"; + $fault = "client"; + originalStatusCode; + originalMessage; + constructor(opts) { + super({ + name: "ModelStreamErrorException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ModelStreamErrorException.prototype); + this.originalStatusCode = opts.originalStatusCode; + this.originalMessage = opts.originalMessage; + } +}; + +const _A = "Accept"; +const _ADE = "AccessDeniedException"; +const _AG = "ApplyGuardrail"; +const _AGR = "ApplyGuardrailRequest"; +const _AGRp = "ApplyGuardrailResponse"; +const _AIM = "AsyncInvokeMessage"; +const _AIODC = "AsyncInvokeOutputDataConfig"; +const _AIS = "AsyncInvokeSummary"; +const _AISODC = "AsyncInvokeS3OutputDataConfig"; +const _AISs = "AsyncInvokeSummaries"; +const _ATC = "AnyToolChoice"; +const _ATCu = "AutoToolChoice"; +const _B = "Body"; +const _BIPP = "BidirectionalInputPayloadPart"; +const _BOPP = "BidirectionalOutputPayloadPart"; +const _C = "Citation"; +const _CB = "ContentBlocks"; +const _CBD = "ContentBlockDelta"; +const _CBDE = "ContentBlockDeltaEvent"; +const _CBS = "ContentBlockStart"; +const _CBSE = "ContentBlockStartEvent"; +const _CBSEo = "ContentBlockStopEvent"; +const _CBo = "ContentBlock"; +const _CC = "CitationsConfig"; +const _CCB = "CitationsContentBlock"; +const _CD = "CitationsDelta"; +const _CE = "ConflictException"; +const _CGC = "CitationGeneratedContent"; +const _CGCL = "CitationGeneratedContentList"; +const _CL = "CitationLocation"; +const _CM = "ConverseMetrics"; +const _CO = "ConverseOutput"; +const _CPB = "CachePointBlock"; +const _CR = "ConverseRequest"; +const _CRo = "ConverseResponse"; +const _CS = "ConverseStream"; +const _CSC = "CitationSourceContent"; +const _CSCD = "CitationSourceContentDelta"; +const _CSCL = "CitationSourceContentList"; +const _CSCLD = "CitationSourceContentListDelta"; +const _CSM = "ConverseStreamMetrics"; +const _CSME = "ConverseStreamMetadataEvent"; +const _CSO = "ConverseStreamOutput"; +const _CSR = "ConverseStreamRequest"; +const _CSRo = "ConverseStreamResponse"; +const _CST = "ConverseStreamTrace"; +const _CT = "ConverseTrace"; +const _CTI = "CountTokensInput"; +const _CTR = "ConverseTokensRequest"; +const _CTRo = "CountTokensRequest"; +const _CTRou = "CountTokensResponse"; +const _CT_ = "Content-Type"; +const _CTo = "CountTokens"; +const _Ci = "Citations"; +const _Co = "Converse"; +const _DB = "DocumentBlock"; +const _DCB = "DocumentContentBlocks"; +const _DCBo = "DocumentContentBlock"; +const _DCL = "DocumentCharLocation"; +const _DCLo = "DocumentChunkLocation"; +const _DPL = "DocumentPageLocation"; +const _DS = "DocumentSource"; +const _GA = "GuardrailAssessment"; +const _GAI = "GetAsyncInvoke"; +const _GAIR = "GetAsyncInvokeRequest"; +const _GAIRe = "GetAsyncInvokeResponse"; +const _GAL = "GuardrailAssessmentList"; +const _GALM = "GuardrailAssessmentListMap"; +const _GAM = "GuardrailAssessmentMap"; +const _GARDSL = "GuardrailAutomatedReasoningDifferenceScenarioList"; +const _GARF = "GuardrailAutomatedReasoningFinding"; +const _GARFL = "GuardrailAutomatedReasoningFindingList"; +const _GARIF = "GuardrailAutomatedReasoningImpossibleFinding"; +const _GARIFu = "GuardrailAutomatedReasoningInvalidFinding"; +const _GARITR = "GuardrailAutomatedReasoningInputTextReference"; +const _GARITRL = "GuardrailAutomatedReasoningInputTextReferenceList"; +const _GARLW = "GuardrailAutomatedReasoningLogicWarning"; +const _GARNTF = "GuardrailAutomatedReasoningNoTranslationsFinding"; +const _GARPA = "GuardrailAutomatedReasoningPolicyAssessment"; +const _GARR = "GuardrailAutomatedReasoningRule"; +const _GARRL = "GuardrailAutomatedReasoningRuleList"; +const _GARS = "GuardrailAutomatedReasoningScenario"; +const _GARSF = "GuardrailAutomatedReasoningSatisfiableFinding"; +const _GARSL = "GuardrailAutomatedReasoningStatementList"; +const _GARSLC = "GuardrailAutomatedReasoningStatementLogicContent"; +const _GARSNLC = "GuardrailAutomatedReasoningStatementNaturalLanguageContent"; +const _GARSu = "GuardrailAutomatedReasoningStatement"; +const _GART = "GuardrailAutomatedReasoningTranslation"; +const _GARTAF = "GuardrailAutomatedReasoningTranslationAmbiguousFinding"; +const _GARTCF = "GuardrailAutomatedReasoningTooComplexFinding"; +const _GARTL = "GuardrailAutomatedReasoningTranslationList"; +const _GARTO = "GuardrailAutomatedReasoningTranslationOption"; +const _GARTOL = "GuardrailAutomatedReasoningTranslationOptionList"; +const _GARVF = "GuardrailAutomatedReasoningValidFinding"; +const _GC = "GuardrailConfiguration"; +const _GCB = "GuardrailContentBlock"; +const _GCBL = "GuardrailContentBlockList"; +const _GCCB = "GuardrailConverseContentBlock"; +const _GCF = "GuardrailContentFilter"; +const _GCFL = "GuardrailContentFilterList"; +const _GCGF = "GuardrailContextualGroundingFilter"; +const _GCGFu = "GuardrailContextualGroundingFilters"; +const _GCGPA = "GuardrailContextualGroundingPolicyAssessment"; +const _GCIB = "GuardrailConverseImageBlock"; +const _GCIS = "GuardrailConverseImageSource"; +const _GCPA = "GuardrailContentPolicyAssessment"; +const _GCTB = "GuardrailConverseTextBlock"; +const _GCW = "GuardrailCustomWord"; +const _GCWL = "GuardrailCustomWordList"; +const _GCu = "GuardrailCoverage"; +const _GIB = "GuardrailImageBlock"; +const _GIC = "GuardrailImageCoverage"; +const _GIM = "GuardrailInvocationMetrics"; +const _GIS = "GuardrailImageSource"; +const _GMW = "GuardrailManagedWord"; +const _GMWL = "GuardrailManagedWordList"; +const _GOC = "GuardrailOutputContent"; +const _GOCL = "GuardrailOutputContentList"; +const _GPEF = "GuardrailPiiEntityFilter"; +const _GPEFL = "GuardrailPiiEntityFilterList"; +const _GRF = "GuardrailRegexFilter"; +const _GRFL = "GuardrailRegexFilterList"; +const _GSC = "GuardrailStreamConfiguration"; +const _GSIPA = "GuardrailSensitiveInformationPolicyAssessment"; +const _GT = "GuardrailTopic"; +const _GTA = "GuardrailTraceAssessment"; +const _GTB = "GuardrailTextBlock"; +const _GTCC = "GuardrailTextCharactersCoverage"; +const _GTL = "GuardrailTopicList"; +const _GTPA = "GuardrailTopicPolicyAssessment"; +const _GU = "GuardrailUsage"; +const _GWPA = "GuardrailWordPolicyAssessment"; +const _IB = "ImageBlock"; +const _IC = "InferenceConfiguration"; +const _IM = "InvokeModel"; +const _IMR = "InvokeModelRequest"; +const _IMRn = "InvokeModelResponse"; +const _IMTR = "InvokeModelTokensRequest"; +const _IMWBS = "InvokeModelWithBidirectionalStream"; +const _IMWBSI = "InvokeModelWithBidirectionalStreamInput"; +const _IMWBSO = "InvokeModelWithBidirectionalStreamOutput"; +const _IMWBSR = "InvokeModelWithBidirectionalStreamRequest"; +const _IMWBSRn = "InvokeModelWithBidirectionalStreamResponse"; +const _IMWRS = "InvokeModelWithResponseStream"; +const _IMWRSR = "InvokeModelWithResponseStreamRequest"; +const _IMWRSRn = "InvokeModelWithResponseStreamResponse"; +const _IS = "ImageSource"; +const _ISE = "InternalServerException"; +const _LAI = "ListAsyncInvokes"; +const _LAIR = "ListAsyncInvokesRequest"; +const _LAIRi = "ListAsyncInvokesResponse"; +const _M = "Message"; +const _MEE = "ModelErrorException"; +const _MIP = "ModelInputPayload"; +const _MNRE = "ModelNotReadyException"; +const _MSE = "MessageStartEvent"; +const _MSEE = "ModelStreamErrorException"; +const _MSEe = "MessageStopEvent"; +const _MTE = "ModelTimeoutException"; +const _Me = "Messages"; +const _PB = "PartBody"; +const _PC = "PerformanceConfiguration"; +const _PP = "PayloadPart"; +const _PRT = "PromptRouterTrace"; +const _PVM = "PromptVariableMap"; +const _PVV = "PromptVariableValues"; +const _RCB = "ReasoningContentBlock"; +const _RCBD = "ReasoningContentBlockDelta"; +const _RM = "RequestMetadata"; +const _RNFE = "ResourceNotFoundException"; +const _RS = "ResponseStream"; +const _RTB = "ReasoningTextBlock"; +const _SAI = "StartAsyncInvoke"; +const _SAIR = "StartAsyncInvokeRequest"; +const _SAIRt = "StartAsyncInvokeResponse"; +const _SCB = "SystemContentBlocks"; +const _SCBy = "SystemContentBlock"; +const _SL = "S3Location"; +const _SQEE = "ServiceQuotaExceededException"; +const _SRB = "SearchResultBlock"; +const _SRCB = "SearchResultContentBlock"; +const _SRCBe = "SearchResultContentBlocks"; +const _SRL = "SearchResultLocation"; +const _ST = "ServiceTier"; +const _STC = "SpecificToolChoice"; +const _STy = "SystemTool"; +const _SUE = "ServiceUnavailableException"; +const _T = "Tag"; +const _TC = "ToolConfiguration"; +const _TCo = "ToolChoice"; +const _TE = "ThrottlingException"; +const _TIS = "ToolInputSchema"; +const _TL = "TagList"; +const _TRB = "ToolResultBlock"; +const _TRBD = "ToolResultBlocksDelta"; +const _TRBDo = "ToolResultBlockDelta"; +const _TRBS = "ToolResultBlockStart"; +const _TRCB = "ToolResultContentBlocks"; +const _TRCBo = "ToolResultContentBlock"; +const _TS = "ToolSpecification"; +const _TU = "TokenUsage"; +const _TUB = "ToolUseBlock"; +const _TUBD = "ToolUseBlockDelta"; +const _TUBS = "ToolUseBlockStart"; +const _To = "Tools"; +const _Too = "Tool"; +const _VB = "VideoBlock"; +const _VE = "ValidationException"; +const _VS = "VideoSource"; +const _WL = "WebLocation"; +const _XABA = "X-Amzn-Bedrock-Accept"; +const _XABCT = "X-Amzn-Bedrock-Content-Type"; +const _XABG = "X-Amzn-Bedrock-GuardrailIdentifier"; +const _XABG_ = "X-Amzn-Bedrock-GuardrailVersion"; +const _XABPL = "X-Amzn-Bedrock-PerformanceConfig-Latency"; +const _XABST = "X-Amzn-Bedrock-Service-Tier"; +const _XABT = "X-Amzn-Bedrock-Trace"; +const _a = "action"; +const _aIS = "asyncInvokeSummaries"; +const _aMRF = "additionalModelRequestFields"; +const _aMRFP = "additionalModelResponseFieldPaths"; +const _aMRFd = "additionalModelResponseFields"; +const _aR = "actionReason"; +const _aRP = "automatedReasoningPolicy"; +const _aRPU = "automatedReasoningPolicyUnits"; +const _aRPu = "automatedReasoningPolicies"; +const _ac = "accept"; +const _an = "any"; +const _as = "assessments"; +const _au = "auto"; +const _b = "bytes"; +const _bO = "bucketOwner"; +const _bo = "body"; +const _c = "client"; +const _cBD = "contentBlockDelta"; +const _cBI = "contentBlockIndex"; +const _cBS = "contentBlockStart"; +const _cBSo = "contentBlockStop"; +const _cC = "citationsContent"; +const _cFS = "claimsFalseScenario"; +const _cGP = "contextualGroundingPolicy"; +const _cGPU = "contextualGroundingPolicyUnits"; +const _cP = "contentPolicy"; +const _cPIU = "contentPolicyImageUnits"; +const _cPU = "contentPolicyUnits"; +const _cPa = "cachePoint"; +const _cR = "contradictingRules"; +const _cRIT = "cacheReadInputTokens"; +const _cRT = "clientRequestToken"; +const _cT = "contentType"; +const _cTS = "claimsTrueScenario"; +const _cW = "customWords"; +const _cWIT = "cacheWriteInputTokens"; +const _ch = "chunk"; +const _ci = "citations"; +const _cit = "citation"; +const _cl = "claims"; +const _co = "content"; +const _con = "context"; +const _conf = "confidence"; +const _conv = "converse"; +const _d = "delta"; +const _dC = "documentChar"; +const _dCo = "documentChunk"; +const _dI = "documentIndex"; +const _dP = "documentPage"; +const _dS = "differenceScenarios"; +const _de = "detected"; +const _des = "description"; +const _do = "domain"; +const _doc = "document"; +const _e = "error"; +const _eT = "endTime"; +const _en = "enabled"; +const _end = "end"; +const _f = "format"; +const _fM = "failureMessage"; +const _fS = "filterStrength"; +const _fi = "findings"; +const _fil = "filters"; +const _g = "guardrail"; +const _gC = "guardrailCoverage"; +const _gCu = "guardrailConfig"; +const _gCua = "guardContent"; +const _gI = "guardrailIdentifier"; +const _gPL = "guardrailProcessingLatency"; +const _gV = "guardrailVersion"; +const _gu = "guarded"; +const _h = "http"; +const _hE = "httpError"; +const _hH = "httpHeader"; +const _hQ = "httpQuery"; +const _i = "input"; +const _iA = "invocationArn"; +const _iAn = "inputAssessment"; +const _iC = "inferenceConfig"; +const _iM = "invocationMetrics"; +const _iMI = "invokedModelId"; +const _iMn = "invokeModel"; +const _iS = "inputSchema"; +const _iSE = "internalServerException"; +const _iT = "inputTokens"; +const _id = "identifier"; +const _im = "images"; +const _ima = "image"; +const _imp = "impossible"; +const _in = "invalid"; +const _j = "json"; +const _k = "key"; +const _kKI = "kmsKeyId"; +const _l = "location"; +const _lM = "latencyMs"; +const _lMT = "lastModifiedTime"; +const _lW = "logicWarning"; +const _la = "latency"; +const _lo = "logic"; +const _m = "message"; +const _mA = "modelArn"; +const _mI = "modelId"; +const _mIo = "modelInput"; +const _mO = "modelOutput"; +const _mR = "maxResults"; +const _mS = "messageStart"; +const _mSEE = "modelStreamErrorException"; +const _mSe = "messageStop"; +const _mT = "maxTokens"; +const _mTE = "modelTimeoutException"; +const _mWL = "managedWordLists"; +const _ma = "match"; +const _me = "messages"; +const _met = "metrics"; +const _meta = "metadata"; +const _n = "name"; +const _nL = "naturalLanguage"; +const _nT = "nextToken"; +const _nTo = "noTranslations"; +const _o = "outputs"; +const _oA = "outputAssessments"; +const _oDC = "outputDataConfig"; +const _oM = "originalMessage"; +const _oS = "outputScope"; +const _oSC = "originalStatusCode"; +const _oT = "outputTokens"; +const _op = "options"; +const _ou = "output"; +const _p = "premises"; +const _pC = "performanceConfig"; +const _pCL = "performanceConfigLatency"; +const _pE = "piiEntities"; +const _pR = "promptRouter"; +const _pV = "promptVariables"; +const _pVA = "policyVersionArn"; +const _q = "qualifiers"; +const _r = "regex"; +const _rC = "reasoningContent"; +const _rCe = "redactedContent"; +const _rM = "requestMetadata"; +const _rN = "resourceName"; +const _rT = "reasoningText"; +const _re = "regexes"; +const _ro = "role"; +const _s = "source"; +const _sB = "sortBy"; +const _sC = "sourceContent"; +const _sE = "statusEquals"; +const _sIP = "sensitiveInformationPolicy"; +const _sIPFU = "sensitiveInformationPolicyFreeUnits"; +const _sIPU = "sensitiveInformationPolicyUnits"; +const _sL = "s3Location"; +const _sO = "sortOrder"; +const _sODC = "s3OutputDataConfig"; +const _sPM = "streamProcessingMode"; +const _sR = "stopReason"; +const _sRI = "searchResultIndex"; +const _sRL = "searchResultLocation"; +const _sRe = "searchResult"; +const _sRu = "supportingRules"; +const _sS = "stopSequences"; +const _sT = "submitTime"; +const _sTA = "submitTimeAfter"; +const _sTB = "submitTimeBefore"; +const _sTe = "serviceTier"; +const _sTy = "systemTool"; +const _sU = "s3Uri"; +const _sUE = "serviceUnavailableException"; +const _sa = "satisfiable"; +const _sc = "score"; +const _se = "server"; +const _si = "signature"; +const _sm = "smithy.ts.sdk.synthetic.com.amazonaws.bedrockruntime"; +const _st = "status"; +const _sta = "start"; +const _stat = "statements"; +const _str = "stream"; +const _stre = "streaming"; +const _sy = "system"; +const _t = "type"; +const _tA = "translationAmbiguous"; +const _tC = "toolConfig"; +const _tCe = "textCharacters"; +const _tCo = "toolChoice"; +const _tCoo = "tooComplex"; +const _tE = "throttlingException"; +const _tP = "topicPolicy"; +const _tPU = "topicPolicyUnits"; +const _tPo = "topP"; +const _tR = "toolResult"; +const _tS = "toolSpec"; +const _tT = "totalTokens"; +const _tU = "toolUse"; +const _tUI = "toolUseId"; +const _ta = "tags"; +const _te = "text"; +const _tem = "temperature"; +const _th = "threshold"; +const _ti = "title"; +const _to = "total"; +const _too = "tools"; +const _tool = "tool"; +const _top = "topics"; +const _tr = "trace"; +const _tra = "translation"; +const _tran = "translations"; +const _u = "usage"; +const _uC = "untranslatedClaims"; +const _uP = "untranslatedPremises"; +const _ur = "uri"; +const _url = "url"; +const _v = "value"; +const _vE = "validationException"; +const _va = "valid"; +const _vi = "video"; +const _w = "web"; +const _wP = "wordPolicy"; +const _wPU = "wordPolicyUnits"; +const n0 = "com.amazonaws.bedrockruntime"; +var AsyncInvokeMessage = [0, n0, _AIM, 8, 0]; +var Body = [0, n0, _B, 8, 21]; +var GuardrailAutomatedReasoningStatementLogicContent = [0, n0, _GARSLC, 8, 0]; +var GuardrailAutomatedReasoningStatementNaturalLanguageContent = [0, n0, _GARSNLC, 8, 0]; +var ModelInputPayload = [0, n0, _MIP, 8, 15]; +var PartBody = [0, n0, _PB, 8, 21]; +var AccessDeniedException = [ + -3, + n0, + _ADE, + { + [_e]: _c, + [_hE]: 403, + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(AccessDeniedException, AccessDeniedException$1); +var AnyToolChoice = [3, n0, _ATC, 0, [], []]; +var ApplyGuardrailRequest = [ + 3, + n0, + _AGR, + 0, + [_gI, _gV, _s, _co, _oS], + [[0, 1], [0, 1], 0, [() => GuardrailContentBlockList, 0], 0], +]; +var ApplyGuardrailResponse = [ + 3, + n0, + _AGRp, + 0, + [_u, _a, _aR, _o, _as, _gC], + [ + () => GuardrailUsage, + 0, + 0, + () => GuardrailOutputContentList, + [() => GuardrailAssessmentList, 0], + () => GuardrailCoverage, + ], +]; +var AsyncInvokeS3OutputDataConfig = [3, n0, _AISODC, 0, [_sU, _kKI, _bO], [0, 0, 0]]; +var AsyncInvokeSummary = [ + 3, + n0, + _AIS, + 0, + [_iA, _mA, _cRT, _st, _fM, _sT, _lMT, _eT, _oDC], + [0, 0, 0, 0, [() => AsyncInvokeMessage, 0], 5, 5, 5, () => AsyncInvokeOutputDataConfig], +]; +var AutoToolChoice = [3, n0, _ATCu, 0, [], []]; +var BidirectionalInputPayloadPart = [3, n0, _BIPP, 8, [_b], [[() => PartBody, 0]]]; +var BidirectionalOutputPayloadPart = [3, n0, _BOPP, 8, [_b], [[() => PartBody, 0]]]; +var CachePointBlock = [3, n0, _CPB, 0, [_t], [0]]; +var Citation = [ + 3, + n0, + _C, + 0, + [_ti, _s, _sC, _l], + [0, 0, () => CitationSourceContentList, () => CitationLocation], +]; +var CitationsConfig = [3, n0, _CC, 0, [_en], [2]]; +var CitationsContentBlock = [ + 3, + n0, + _CCB, + 0, + [_co, _ci], + [() => CitationGeneratedContentList, () => Citations], +]; +var CitationsDelta = [ + 3, + n0, + _CD, + 0, + [_ti, _s, _sC, _l], + [0, 0, () => CitationSourceContentListDelta, () => CitationLocation], +]; +var CitationSourceContentDelta = [3, n0, _CSCD, 0, [_te], [0]]; +var ConflictException = [ + -3, + n0, + _CE, + { + [_e]: _c, + [_hE]: 400, + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(ConflictException, ConflictException$1); +var ContentBlockDeltaEvent = [ + 3, + n0, + _CBDE, + 0, + [_d, _cBI], + [[() => ContentBlockDelta, 0], 1], +]; +var ContentBlockStartEvent = [ + 3, + n0, + _CBSE, + 0, + [_sta, _cBI], + [() => ContentBlockStart, 1], +]; +var ContentBlockStopEvent = [3, n0, _CBSEo, 0, [_cBI], [1]]; +var ConverseMetrics = [3, n0, _CM, 0, [_lM], [1]]; +var ConverseRequest = [ + 3, + n0, + _CR, + 0, + [_mI, _me, _sy, _iC, _tC, _gCu, _aMRF, _pV, _aMRFP, _rM, _pC, _sTe], + [ + [0, 1], + [() => Messages, 0], + [() => SystemContentBlocks, 0], + () => InferenceConfiguration, + () => ToolConfiguration, + () => GuardrailConfiguration, + 15, + [() => PromptVariableMap, 0], + 64 | 0, + [() => RequestMetadata, 0], + () => PerformanceConfiguration, + () => ServiceTier, + ], +]; +var ConverseResponse = [ + 3, + n0, + _CRo, + 0, + [_ou, _sR, _u, _met, _aMRFd, _tr, _pC, _sTe], + [ + [() => ConverseOutput, 0], + 0, + () => TokenUsage, + () => ConverseMetrics, + 15, + [() => ConverseTrace, 0], + () => PerformanceConfiguration, + () => ServiceTier, + ], +]; +var ConverseStreamMetadataEvent = [ + 3, + n0, + _CSME, + 0, + [_u, _met, _tr, _pC, _sTe], + [ + () => TokenUsage, + () => ConverseStreamMetrics, + [() => ConverseStreamTrace, 0], + () => PerformanceConfiguration, + () => ServiceTier, + ], +]; +var ConverseStreamMetrics = [3, n0, _CSM, 0, [_lM], [1]]; +var ConverseStreamRequest = [ + 3, + n0, + _CSR, + 0, + [_mI, _me, _sy, _iC, _tC, _gCu, _aMRF, _pV, _aMRFP, _rM, _pC, _sTe], + [ + [0, 1], + [() => Messages, 0], + [() => SystemContentBlocks, 0], + () => InferenceConfiguration, + () => ToolConfiguration, + () => GuardrailStreamConfiguration, + 15, + [() => PromptVariableMap, 0], + 64 | 0, + [() => RequestMetadata, 0], + () => PerformanceConfiguration, + () => ServiceTier, + ], +]; +var ConverseStreamResponse = [ + 3, + n0, + _CSRo, + 0, + [_str], + [[() => ConverseStreamOutput, 16]], +]; +var ConverseStreamTrace = [ + 3, + n0, + _CST, + 0, + [_g, _pR], + [[() => GuardrailTraceAssessment, 0], () => PromptRouterTrace], +]; +var ConverseTokensRequest = [ + 3, + n0, + _CTR, + 0, + [_me, _sy, _tC, _aMRF], + [[() => Messages, 0], [() => SystemContentBlocks, 0], () => ToolConfiguration, 15], +]; +var ConverseTrace = [ + 3, + n0, + _CT, + 0, + [_g, _pR], + [[() => GuardrailTraceAssessment, 0], () => PromptRouterTrace], +]; +var CountTokensRequest = [ + 3, + n0, + _CTRo, + 0, + [_mI, _i], + [ + [0, 1], + [() => CountTokensInput, 0], + ], +]; +var CountTokensResponse = [3, n0, _CTRou, 0, [_iT], [1]]; +var DocumentBlock = [ + 3, + n0, + _DB, + 0, + [_f, _n, _s, _con, _ci], + [0, 0, () => DocumentSource, 0, () => CitationsConfig], +]; +var DocumentCharLocation = [3, n0, _DCL, 0, [_dI, _sta, _end], [1, 1, 1]]; +var DocumentChunkLocation = [3, n0, _DCLo, 0, [_dI, _sta, _end], [1, 1, 1]]; +var DocumentPageLocation = [3, n0, _DPL, 0, [_dI, _sta, _end], [1, 1, 1]]; +var GetAsyncInvokeRequest = [3, n0, _GAIR, 0, [_iA], [[0, 1]]]; +var GetAsyncInvokeResponse = [ + 3, + n0, + _GAIRe, + 0, + [_iA, _mA, _cRT, _st, _fM, _sT, _lMT, _eT, _oDC], + [0, 0, 0, 0, [() => AsyncInvokeMessage, 0], 5, 5, 5, () => AsyncInvokeOutputDataConfig], +]; +var GuardrailAssessment = [ + 3, + n0, + _GA, + 0, + [_tP, _cP, _wP, _sIP, _cGP, _aRP, _iM], + [ + () => GuardrailTopicPolicyAssessment, + () => GuardrailContentPolicyAssessment, + () => GuardrailWordPolicyAssessment, + () => GuardrailSensitiveInformationPolicyAssessment, + () => GuardrailContextualGroundingPolicyAssessment, + [() => GuardrailAutomatedReasoningPolicyAssessment, 0], + () => GuardrailInvocationMetrics, + ], +]; +var GuardrailAutomatedReasoningImpossibleFinding = [ + 3, + n0, + _GARIF, + 0, + [_tra, _cR, _lW], + [ + [() => GuardrailAutomatedReasoningTranslation, 0], + () => GuardrailAutomatedReasoningRuleList, + [() => GuardrailAutomatedReasoningLogicWarning, 0], + ], +]; +var GuardrailAutomatedReasoningInputTextReference = [ + 3, + n0, + _GARITR, + 0, + [_te], + [[() => GuardrailAutomatedReasoningStatementNaturalLanguageContent, 0]], +]; +var GuardrailAutomatedReasoningInvalidFinding = [ + 3, + n0, + _GARIFu, + 0, + [_tra, _cR, _lW], + [ + [() => GuardrailAutomatedReasoningTranslation, 0], + () => GuardrailAutomatedReasoningRuleList, + [() => GuardrailAutomatedReasoningLogicWarning, 0], + ], +]; +var GuardrailAutomatedReasoningLogicWarning = [ + 3, + n0, + _GARLW, + 0, + [_t, _p, _cl], + [0, [() => GuardrailAutomatedReasoningStatementList, 0], [() => GuardrailAutomatedReasoningStatementList, 0]], +]; +var GuardrailAutomatedReasoningNoTranslationsFinding = [3, n0, _GARNTF, 0, [], []]; +var GuardrailAutomatedReasoningPolicyAssessment = [ + 3, + n0, + _GARPA, + 0, + [_fi], + [[() => GuardrailAutomatedReasoningFindingList, 0]], +]; +var GuardrailAutomatedReasoningRule = [3, n0, _GARR, 0, [_id, _pVA], [0, 0]]; +var GuardrailAutomatedReasoningSatisfiableFinding = [ + 3, + n0, + _GARSF, + 0, + [_tra, _cTS, _cFS, _lW], + [ + [() => GuardrailAutomatedReasoningTranslation, 0], + [() => GuardrailAutomatedReasoningScenario, 0], + [() => GuardrailAutomatedReasoningScenario, 0], + [() => GuardrailAutomatedReasoningLogicWarning, 0], + ], +]; +var GuardrailAutomatedReasoningScenario = [ + 3, + n0, + _GARS, + 0, + [_stat], + [[() => GuardrailAutomatedReasoningStatementList, 0]], +]; +var GuardrailAutomatedReasoningStatement = [ + 3, + n0, + _GARSu, + 0, + [_lo, _nL], + [ + [() => GuardrailAutomatedReasoningStatementLogicContent, 0], + [() => GuardrailAutomatedReasoningStatementNaturalLanguageContent, 0], + ], +]; +var GuardrailAutomatedReasoningTooComplexFinding = [3, n0, _GARTCF, 0, [], []]; +var GuardrailAutomatedReasoningTranslation = [ + 3, + n0, + _GART, + 0, + [_p, _cl, _uP, _uC, _conf], + [ + [() => GuardrailAutomatedReasoningStatementList, 0], + [() => GuardrailAutomatedReasoningStatementList, 0], + [() => GuardrailAutomatedReasoningInputTextReferenceList, 0], + [() => GuardrailAutomatedReasoningInputTextReferenceList, 0], + 1, + ], +]; +var GuardrailAutomatedReasoningTranslationAmbiguousFinding = [ + 3, + n0, + _GARTAF, + 0, + [_op, _dS], + [ + [() => GuardrailAutomatedReasoningTranslationOptionList, 0], + [() => GuardrailAutomatedReasoningDifferenceScenarioList, 0], + ], +]; +var GuardrailAutomatedReasoningTranslationOption = [ + 3, + n0, + _GARTO, + 0, + [_tran], + [[() => GuardrailAutomatedReasoningTranslationList, 0]], +]; +var GuardrailAutomatedReasoningValidFinding = [ + 3, + n0, + _GARVF, + 0, + [_tra, _cTS, _sRu, _lW], + [ + [() => GuardrailAutomatedReasoningTranslation, 0], + [() => GuardrailAutomatedReasoningScenario, 0], + () => GuardrailAutomatedReasoningRuleList, + [() => GuardrailAutomatedReasoningLogicWarning, 0], + ], +]; +var GuardrailConfiguration = [3, n0, _GC, 0, [_gI, _gV, _tr], [0, 0, 0]]; +var GuardrailContentFilter = [3, n0, _GCF, 0, [_t, _conf, _fS, _a, _de], [0, 0, 0, 0, 2]]; +var GuardrailContentPolicyAssessment = [ + 3, + n0, + _GCPA, + 0, + [_fil], + [() => GuardrailContentFilterList], +]; +var GuardrailContextualGroundingFilter = [ + 3, + n0, + _GCGF, + 0, + [_t, _th, _sc, _a, _de], + [0, 1, 1, 0, 2], +]; +var GuardrailContextualGroundingPolicyAssessment = [ + 3, + n0, + _GCGPA, + 0, + [_fil], + [() => GuardrailContextualGroundingFilters], +]; +var GuardrailConverseImageBlock = [ + 3, + n0, + _GCIB, + 8, + [_f, _s], + [0, [() => GuardrailConverseImageSource, 0]], +]; +var GuardrailConverseTextBlock = [3, n0, _GCTB, 0, [_te, _q], [0, 64 | 0]]; +var GuardrailCoverage = [ + 3, + n0, + _GCu, + 0, + [_tCe, _im], + [() => GuardrailTextCharactersCoverage, () => GuardrailImageCoverage], +]; +var GuardrailCustomWord = [3, n0, _GCW, 0, [_ma, _a, _de], [0, 0, 2]]; +var GuardrailImageBlock = [ + 3, + n0, + _GIB, + 8, + [_f, _s], + [0, [() => GuardrailImageSource, 0]], +]; +var GuardrailImageCoverage = [3, n0, _GIC, 0, [_gu, _to], [1, 1]]; +var GuardrailInvocationMetrics = [ + 3, + n0, + _GIM, + 0, + [_gPL, _u, _gC], + [1, () => GuardrailUsage, () => GuardrailCoverage], +]; +var GuardrailManagedWord = [3, n0, _GMW, 0, [_ma, _t, _a, _de], [0, 0, 0, 2]]; +var GuardrailOutputContent = [3, n0, _GOC, 0, [_te], [0]]; +var GuardrailPiiEntityFilter = [3, n0, _GPEF, 0, [_ma, _t, _a, _de], [0, 0, 0, 2]]; +var GuardrailRegexFilter = [3, n0, _GRF, 0, [_n, _ma, _r, _a, _de], [0, 0, 0, 0, 2]]; +var GuardrailSensitiveInformationPolicyAssessment = [ + 3, + n0, + _GSIPA, + 0, + [_pE, _re], + [() => GuardrailPiiEntityFilterList, () => GuardrailRegexFilterList], +]; +var GuardrailStreamConfiguration = [3, n0, _GSC, 0, [_gI, _gV, _tr, _sPM], [0, 0, 0, 0]]; +var GuardrailTextBlock = [3, n0, _GTB, 0, [_te, _q], [0, 64 | 0]]; +var GuardrailTextCharactersCoverage = [3, n0, _GTCC, 0, [_gu, _to], [1, 1]]; +var GuardrailTopic = [3, n0, _GT, 0, [_n, _t, _a, _de], [0, 0, 0, 2]]; +var GuardrailTopicPolicyAssessment = [ + 3, + n0, + _GTPA, + 0, + [_top], + [() => GuardrailTopicList], +]; +var GuardrailTraceAssessment = [ + 3, + n0, + _GTA, + 0, + [_mO, _iAn, _oA, _aR], + [64 | 0, [() => GuardrailAssessmentMap, 0], [() => GuardrailAssessmentListMap, 0], 0], +]; +var GuardrailUsage = [ + 3, + n0, + _GU, + 0, + [_tPU, _cPU, _wPU, _sIPU, _sIPFU, _cGPU, _cPIU, _aRPU, _aRPu], + [1, 1, 1, 1, 1, 1, 1, 1, 1], +]; +var GuardrailWordPolicyAssessment = [ + 3, + n0, + _GWPA, + 0, + [_cW, _mWL], + [() => GuardrailCustomWordList, () => GuardrailManagedWordList], +]; +var ImageBlock = [3, n0, _IB, 0, [_f, _s], [0, () => ImageSource]]; +var InferenceConfiguration = [3, n0, _IC, 0, [_mT, _tem, _tPo, _sS], [1, 1, 1, 64 | 0]]; +var InternalServerException = [ + -3, + n0, + _ISE, + { + [_e]: _se, + [_hE]: 500, + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(InternalServerException, InternalServerException$1); +var InvokeModelRequest = [ + 3, + n0, + _IMR, + 0, + [_bo, _cT, _ac, _mI, _tr, _gI, _gV, _pCL, _sTe], + [ + [() => Body, 16], + [ + 0, + { + [_hH]: _CT_, + }, + ], + [ + 0, + { + [_hH]: _A, + }, + ], + [0, 1], + [ + 0, + { + [_hH]: _XABT, + }, + ], + [ + 0, + { + [_hH]: _XABG, + }, + ], + [ + 0, + { + [_hH]: _XABG_, + }, + ], + [ + 0, + { + [_hH]: _XABPL, + }, + ], + [ + 0, + { + [_hH]: _XABST, + }, + ], + ], +]; +var InvokeModelResponse = [ + 3, + n0, + _IMRn, + 0, + [_bo, _cT, _pCL, _sTe], + [ + [() => Body, 16], + [ + 0, + { + [_hH]: _CT_, + }, + ], + [ + 0, + { + [_hH]: _XABPL, + }, + ], + [ + 0, + { + [_hH]: _XABST, + }, + ], + ], +]; +var InvokeModelTokensRequest = [3, n0, _IMTR, 0, [_bo], [[() => Body, 0]]]; +var InvokeModelWithBidirectionalStreamRequest = [ + 3, + n0, + _IMWBSR, + 0, + [_mI, _bo], + [ + [0, 1], + [() => InvokeModelWithBidirectionalStreamInput, 16], + ], +]; +var InvokeModelWithBidirectionalStreamResponse = [ + 3, + n0, + _IMWBSRn, + 0, + [_bo], + [[() => InvokeModelWithBidirectionalStreamOutput, 16]], +]; +var InvokeModelWithResponseStreamRequest = [ + 3, + n0, + _IMWRSR, + 0, + [_bo, _cT, _ac, _mI, _tr, _gI, _gV, _pCL, _sTe], + [ + [() => Body, 16], + [ + 0, + { + [_hH]: _CT_, + }, + ], + [ + 0, + { + [_hH]: _XABA, + }, + ], + [0, 1], + [ + 0, + { + [_hH]: _XABT, + }, + ], + [ + 0, + { + [_hH]: _XABG, + }, + ], + [ + 0, + { + [_hH]: _XABG_, + }, + ], + [ + 0, + { + [_hH]: _XABPL, + }, + ], + [ + 0, + { + [_hH]: _XABST, + }, + ], + ], +]; +var InvokeModelWithResponseStreamResponse = [ + 3, + n0, + _IMWRSRn, + 0, + [_bo, _cT, _pCL, _sTe], + [ + [() => ResponseStream, 16], + [ + 0, + { + [_hH]: _XABCT, + }, + ], + [ + 0, + { + [_hH]: _XABPL, + }, + ], + [ + 0, + { + [_hH]: _XABST, + }, + ], + ], +]; +var ListAsyncInvokesRequest = [ + 3, + n0, + _LAIR, + 0, + [_sTA, _sTB, _sE, _mR, _nT, _sB, _sO], + [ + [ + 5, + { + [_hQ]: _sTA, + }, + ], + [ + 5, + { + [_hQ]: _sTB, + }, + ], + [ + 0, + { + [_hQ]: _sE, + }, + ], + [ + 1, + { + [_hQ]: _mR, + }, + ], + [ + 0, + { + [_hQ]: _nT, + }, + ], + [ + 0, + { + [_hQ]: _sB, + }, + ], + [ + 0, + { + [_hQ]: _sO, + }, + ], + ], +]; +var ListAsyncInvokesResponse = [ + 3, + n0, + _LAIRi, + 0, + [_nT, _aIS], + [0, [() => AsyncInvokeSummaries, 0]], +]; +var Message = [3, n0, _M, 0, [_ro, _co], [0, [() => ContentBlocks, 0]]]; +var MessageStartEvent = [3, n0, _MSE, 0, [_ro], [0]]; +var MessageStopEvent = [3, n0, _MSEe, 0, [_sR, _aMRFd], [0, 15]]; +var ModelErrorException = [ + -3, + n0, + _MEE, + { + [_e]: _c, + [_hE]: 424, + }, + [_m, _oSC, _rN], + [0, 1, 0], +]; +schema.TypeRegistry.for(n0).registerError(ModelErrorException, ModelErrorException$1); +var ModelNotReadyException = [ + -3, + n0, + _MNRE, + { + [_e]: _c, + [_hE]: 429, + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(ModelNotReadyException, ModelNotReadyException$1); +var ModelStreamErrorException = [ + -3, + n0, + _MSEE, + { + [_e]: _c, + [_hE]: 424, + }, + [_m, _oSC, _oM], + [0, 1, 0], +]; +schema.TypeRegistry.for(n0).registerError(ModelStreamErrorException, ModelStreamErrorException$1); +var ModelTimeoutException = [ + -3, + n0, + _MTE, + { + [_e]: _c, + [_hE]: 408, + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(ModelTimeoutException, ModelTimeoutException$1); +var PayloadPart = [3, n0, _PP, 8, [_b], [[() => PartBody, 0]]]; +var PerformanceConfiguration = [3, n0, _PC, 0, [_la], [0]]; +var PromptRouterTrace = [3, n0, _PRT, 0, [_iMI], [0]]; +var ReasoningTextBlock = [3, n0, _RTB, 8, [_te, _si], [0, 0]]; +var ResourceNotFoundException = [ + -3, + n0, + _RNFE, + { + [_e]: _c, + [_hE]: 404, + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(ResourceNotFoundException, ResourceNotFoundException$1); +var S3Location = [3, n0, _SL, 0, [_ur, _bO], [0, 0]]; +var SearchResultBlock = [ + 3, + n0, + _SRB, + 0, + [_s, _ti, _co, _ci], + [0, 0, () => SearchResultContentBlocks, () => CitationsConfig], +]; +var SearchResultContentBlock = [3, n0, _SRCB, 0, [_te], [0]]; +var SearchResultLocation = [3, n0, _SRL, 0, [_sRI, _sta, _end], [1, 1, 1]]; +var ServiceQuotaExceededException = [ + -3, + n0, + _SQEE, + { + [_e]: _c, + [_hE]: 400, + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(ServiceQuotaExceededException, ServiceQuotaExceededException$1); +var ServiceTier = [3, n0, _ST, 0, [_t], [0]]; +var ServiceUnavailableException = [ + -3, + n0, + _SUE, + { + [_e]: _se, + [_hE]: 503, + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(ServiceUnavailableException, ServiceUnavailableException$1); +var SpecificToolChoice = [3, n0, _STC, 0, [_n], [0]]; +var StartAsyncInvokeRequest = [ + 3, + n0, + _SAIR, + 0, + [_cRT, _mI, _mIo, _oDC, _ta], + [[0, 4], 0, [() => ModelInputPayload, 0], () => AsyncInvokeOutputDataConfig, () => TagList], +]; +var StartAsyncInvokeResponse = [3, n0, _SAIRt, 0, [_iA], [0]]; +var SystemTool = [3, n0, _STy, 0, [_n], [0]]; +var Tag = [3, n0, _T, 0, [_k, _v], [0, 0]]; +var ThrottlingException = [ + -3, + n0, + _TE, + { + [_e]: _c, + [_hE]: 429, + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(ThrottlingException, ThrottlingException$1); +var TokenUsage = [3, n0, _TU, 0, [_iT, _oT, _tT, _cRIT, _cWIT], [1, 1, 1, 1, 1]]; +var ToolConfiguration = [3, n0, _TC, 0, [_too, _tCo], [() => Tools, () => ToolChoice]]; +var ToolResultBlock = [ + 3, + n0, + _TRB, + 0, + [_tUI, _co, _st, _t], + [0, () => ToolResultContentBlocks, 0, 0], +]; +var ToolResultBlockStart = [3, n0, _TRBS, 0, [_tUI, _t, _st], [0, 0, 0]]; +var ToolSpecification = [3, n0, _TS, 0, [_n, _des, _iS], [0, 0, () => ToolInputSchema]]; +var ToolUseBlock = [3, n0, _TUB, 0, [_tUI, _n, _i, _t], [0, 0, 15, 0]]; +var ToolUseBlockDelta = [3, n0, _TUBD, 0, [_i], [0]]; +var ToolUseBlockStart = [3, n0, _TUBS, 0, [_tUI, _n, _t], [0, 0, 0]]; +var ValidationException = [ + -3, + n0, + _VE, + { + [_e]: _c, + [_hE]: 400, + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(ValidationException, ValidationException$1); +var VideoBlock = [3, n0, _VB, 0, [_f, _s], [0, () => VideoSource]]; +var WebLocation = [3, n0, _WL, 0, [_url, _do], [0, 0]]; +var BedrockRuntimeServiceException = [-3, _sm, "BedrockRuntimeServiceException", 0, [], []]; +schema.TypeRegistry.for(_sm).registerError(BedrockRuntimeServiceException, BedrockRuntimeServiceException$1); +var AsyncInvokeSummaries = [1, n0, _AISs, 0, [() => AsyncInvokeSummary, 0]]; +var CitationGeneratedContentList = [1, n0, _CGCL, 0, () => CitationGeneratedContent]; +var Citations = [1, n0, _Ci, 0, () => Citation]; +var CitationSourceContentList = [1, n0, _CSCL, 0, () => CitationSourceContent]; +var CitationSourceContentListDelta = [1, n0, _CSCLD, 0, () => CitationSourceContentDelta]; +var ContentBlocks = [1, n0, _CB, 0, [() => ContentBlock, 0]]; +var DocumentContentBlocks = [1, n0, _DCB, 0, () => DocumentContentBlock]; +var GuardrailAssessmentList = [1, n0, _GAL, 0, [() => GuardrailAssessment, 0]]; +var GuardrailAutomatedReasoningDifferenceScenarioList = [ + 1, + n0, + _GARDSL, + 0, + [() => GuardrailAutomatedReasoningScenario, 0], +]; +var GuardrailAutomatedReasoningFindingList = [ + 1, + n0, + _GARFL, + 0, + [() => GuardrailAutomatedReasoningFinding, 0], +]; +var GuardrailAutomatedReasoningInputTextReferenceList = [ + 1, + n0, + _GARITRL, + 0, + [() => GuardrailAutomatedReasoningInputTextReference, 0], +]; +var GuardrailAutomatedReasoningRuleList = [ + 1, + n0, + _GARRL, + 0, + () => GuardrailAutomatedReasoningRule, +]; +var GuardrailAutomatedReasoningStatementList = [ + 1, + n0, + _GARSL, + 0, + [() => GuardrailAutomatedReasoningStatement, 0], +]; +var GuardrailAutomatedReasoningTranslationList = [ + 1, + n0, + _GARTL, + 0, + [() => GuardrailAutomatedReasoningTranslation, 0], +]; +var GuardrailAutomatedReasoningTranslationOptionList = [ + 1, + n0, + _GARTOL, + 0, + [() => GuardrailAutomatedReasoningTranslationOption, 0], +]; +var GuardrailContentBlockList = [1, n0, _GCBL, 0, [() => GuardrailContentBlock, 0]]; +var GuardrailContentFilterList = [1, n0, _GCFL, 0, () => GuardrailContentFilter]; +var GuardrailContextualGroundingFilters = [ + 1, + n0, + _GCGFu, + 0, + () => GuardrailContextualGroundingFilter, +]; +var GuardrailCustomWordList = [1, n0, _GCWL, 0, () => GuardrailCustomWord]; +var GuardrailManagedWordList = [1, n0, _GMWL, 0, () => GuardrailManagedWord]; +var GuardrailOutputContentList = [1, n0, _GOCL, 0, () => GuardrailOutputContent]; +var GuardrailPiiEntityFilterList = [1, n0, _GPEFL, 0, () => GuardrailPiiEntityFilter]; +var GuardrailRegexFilterList = [1, n0, _GRFL, 0, () => GuardrailRegexFilter]; +var GuardrailTopicList = [1, n0, _GTL, 0, () => GuardrailTopic]; +var Messages = [1, n0, _Me, 0, [() => Message, 0]]; +var SearchResultContentBlocks = [1, n0, _SRCBe, 0, () => SearchResultContentBlock]; +var SystemContentBlocks = [1, n0, _SCB, 0, [() => SystemContentBlock, 0]]; +var TagList = [1, n0, _TL, 0, () => Tag]; +var ToolResultBlocksDelta = [1, n0, _TRBD, 0, () => ToolResultBlockDelta]; +var ToolResultContentBlocks = [1, n0, _TRCB, 0, () => ToolResultContentBlock]; +var Tools = [1, n0, _To, 0, () => Tool]; +var GuardrailAssessmentListMap = [2, n0, _GALM, 0, [0, 0], [() => GuardrailAssessmentList, 0]]; +var GuardrailAssessmentMap = [2, n0, _GAM, 0, [0, 0], [() => GuardrailAssessment, 0]]; +var PromptVariableMap = [2, n0, _PVM, 8, 0, () => PromptVariableValues]; +var RequestMetadata = [2, n0, _RM, 8, 0, 0]; +var AsyncInvokeOutputDataConfig = [ + 3, + n0, + _AIODC, + 0, + [_sODC], + [() => AsyncInvokeS3OutputDataConfig], +]; +var CitationGeneratedContent = [3, n0, _CGC, 0, [_te], [0]]; +var CitationLocation = [ + 3, + n0, + _CL, + 0, + [_w, _dC, _dP, _dCo, _sRL], + [ + () => WebLocation, + () => DocumentCharLocation, + () => DocumentPageLocation, + () => DocumentChunkLocation, + () => SearchResultLocation, + ], +]; +var CitationSourceContent = [3, n0, _CSC, 0, [_te], [0]]; +var ContentBlock = [ + 3, + n0, + _CBo, + 0, + [_te, _ima, _doc, _vi, _tU, _tR, _gCua, _cPa, _rC, _cC, _sRe], + [ + 0, + () => ImageBlock, + () => DocumentBlock, + () => VideoBlock, + () => ToolUseBlock, + () => ToolResultBlock, + [() => GuardrailConverseContentBlock, 0], + () => CachePointBlock, + [() => ReasoningContentBlock, 0], + () => CitationsContentBlock, + () => SearchResultBlock, + ], +]; +var ContentBlockDelta = [ + 3, + n0, + _CBD, + 0, + [_te, _tU, _tR, _rC, _cit], + [ + 0, + () => ToolUseBlockDelta, + () => ToolResultBlocksDelta, + [() => ReasoningContentBlockDelta, 0], + () => CitationsDelta, + ], +]; +var ContentBlockStart = [ + 3, + n0, + _CBS, + 0, + [_tU, _tR], + [() => ToolUseBlockStart, () => ToolResultBlockStart], +]; +var ConverseOutput = [3, n0, _CO, 0, [_m], [[() => Message, 0]]]; +var ConverseStreamOutput = [ + 3, + n0, + _CSO, + { + [_stre]: 1, + }, + [_mS, _cBS, _cBD, _cBSo, _mSe, _meta, _iSE, _mSEE, _vE, _tE, _sUE], + [ + () => MessageStartEvent, + () => ContentBlockStartEvent, + [() => ContentBlockDeltaEvent, 0], + () => ContentBlockStopEvent, + () => MessageStopEvent, + [() => ConverseStreamMetadataEvent, 0], + [() => InternalServerException, 0], + [() => ModelStreamErrorException, 0], + [() => ValidationException, 0], + [() => ThrottlingException, 0], + [() => ServiceUnavailableException, 0], + ], +]; +var CountTokensInput = [ + 3, + n0, + _CTI, + 0, + [_iMn, _conv], + [ + [() => InvokeModelTokensRequest, 0], + [() => ConverseTokensRequest, 0], + ], +]; +var DocumentContentBlock = [3, n0, _DCBo, 0, [_te], [0]]; +var DocumentSource = [ + 3, + n0, + _DS, + 0, + [_b, _sL, _te, _co], + [21, () => S3Location, 0, () => DocumentContentBlocks], +]; +var GuardrailAutomatedReasoningFinding = [ + 3, + n0, + _GARF, + 0, + [_va, _in, _sa, _imp, _tA, _tCoo, _nTo], + [ + [() => GuardrailAutomatedReasoningValidFinding, 0], + [() => GuardrailAutomatedReasoningInvalidFinding, 0], + [() => GuardrailAutomatedReasoningSatisfiableFinding, 0], + [() => GuardrailAutomatedReasoningImpossibleFinding, 0], + [() => GuardrailAutomatedReasoningTranslationAmbiguousFinding, 0], + () => GuardrailAutomatedReasoningTooComplexFinding, + () => GuardrailAutomatedReasoningNoTranslationsFinding, + ], +]; +var GuardrailContentBlock = [ + 3, + n0, + _GCB, + 0, + [_te, _ima], + [() => GuardrailTextBlock, [() => GuardrailImageBlock, 0]], +]; +var GuardrailConverseContentBlock = [ + 3, + n0, + _GCCB, + 0, + [_te, _ima], + [() => GuardrailConverseTextBlock, [() => GuardrailConverseImageBlock, 0]], +]; +var GuardrailConverseImageSource = [3, n0, _GCIS, 8, [_b], [21]]; +var GuardrailImageSource = [3, n0, _GIS, 8, [_b], [21]]; +var ImageSource = [3, n0, _IS, 0, [_b, _sL], [21, () => S3Location]]; +var InvokeModelWithBidirectionalStreamInput = [ + 3, + n0, + _IMWBSI, + { + [_stre]: 1, + }, + [_ch], + [[() => BidirectionalInputPayloadPart, 0]], +]; +var InvokeModelWithBidirectionalStreamOutput = [ + 3, + n0, + _IMWBSO, + { + [_stre]: 1, + }, + [_ch, _iSE, _mSEE, _vE, _tE, _mTE, _sUE], + [ + [() => BidirectionalOutputPayloadPart, 0], + [() => InternalServerException, 0], + [() => ModelStreamErrorException, 0], + [() => ValidationException, 0], + [() => ThrottlingException, 0], + [() => ModelTimeoutException, 0], + [() => ServiceUnavailableException, 0], + ], +]; +var PromptVariableValues = [3, n0, _PVV, 0, [_te], [0]]; +var ReasoningContentBlock = [ + 3, + n0, + _RCB, + 8, + [_rT, _rCe], + [[() => ReasoningTextBlock, 0], 21], +]; +var ReasoningContentBlockDelta = [3, n0, _RCBD, 8, [_te, _rCe, _si], [0, 21, 0]]; +var ResponseStream = [ + 3, + n0, + _RS, + { + [_stre]: 1, + }, + [_ch, _iSE, _mSEE, _vE, _tE, _mTE, _sUE], + [ + [() => PayloadPart, 0], + [() => InternalServerException, 0], + [() => ModelStreamErrorException, 0], + [() => ValidationException, 0], + [() => ThrottlingException, 0], + [() => ModelTimeoutException, 0], + [() => ServiceUnavailableException, 0], + ], +]; +var SystemContentBlock = [ + 3, + n0, + _SCBy, + 0, + [_te, _gCua, _cPa], + [0, [() => GuardrailConverseContentBlock, 0], () => CachePointBlock], +]; +var Tool = [ + 3, + n0, + _Too, + 0, + [_tS, _sTy, _cPa], + [() => ToolSpecification, () => SystemTool, () => CachePointBlock], +]; +var ToolChoice = [ + 3, + n0, + _TCo, + 0, + [_au, _an, _tool], + [() => AutoToolChoice, () => AnyToolChoice, () => SpecificToolChoice], +]; +var ToolInputSchema = [3, n0, _TIS, 0, [_j], [15]]; +var ToolResultBlockDelta = [3, n0, _TRBDo, 0, [_te], [0]]; +var ToolResultContentBlock = [ + 3, + n0, + _TRCBo, + 0, + [_j, _te, _ima, _doc, _vi, _sRe], + [15, 0, () => ImageBlock, () => DocumentBlock, () => VideoBlock, () => SearchResultBlock], +]; +var VideoSource = [3, n0, _VS, 0, [_b, _sL], [21, () => S3Location]]; +var ApplyGuardrail = [ + 9, + n0, + _AG, + { + [_h]: ["POST", "/guardrail/{guardrailIdentifier}/version/{guardrailVersion}/apply", 200], + }, + () => ApplyGuardrailRequest, + () => ApplyGuardrailResponse, +]; +var Converse = [ + 9, + n0, + _Co, + { + [_h]: ["POST", "/model/{modelId}/converse", 200], + }, + () => ConverseRequest, + () => ConverseResponse, +]; +var ConverseStream = [ + 9, + n0, + _CS, + { + [_h]: ["POST", "/model/{modelId}/converse-stream", 200], + }, + () => ConverseStreamRequest, + () => ConverseStreamResponse, +]; +var CountTokens = [ + 9, + n0, + _CTo, + { + [_h]: ["POST", "/model/{modelId}/count-tokens", 200], + }, + () => CountTokensRequest, + () => CountTokensResponse, +]; +var GetAsyncInvoke = [ + 9, + n0, + _GAI, + { + [_h]: ["GET", "/async-invoke/{invocationArn}", 200], + }, + () => GetAsyncInvokeRequest, + () => GetAsyncInvokeResponse, +]; +var InvokeModel = [ + 9, + n0, + _IM, + { + [_h]: ["POST", "/model/{modelId}/invoke", 200], + }, + () => InvokeModelRequest, + () => InvokeModelResponse, +]; +var InvokeModelWithBidirectionalStream = [ + 9, + n0, + _IMWBS, + { + [_h]: ["POST", "/model/{modelId}/invoke-with-bidirectional-stream", 200], + }, + () => InvokeModelWithBidirectionalStreamRequest, + () => InvokeModelWithBidirectionalStreamResponse, +]; +var InvokeModelWithResponseStream = [ + 9, + n0, + _IMWRS, + { + [_h]: ["POST", "/model/{modelId}/invoke-with-response-stream", 200], + }, + () => InvokeModelWithResponseStreamRequest, + () => InvokeModelWithResponseStreamResponse, +]; +var ListAsyncInvokes = [ + 9, + n0, + _LAI, + { + [_h]: ["GET", "/async-invoke", 200], + }, + () => ListAsyncInvokesRequest, + () => ListAsyncInvokesResponse, +]; +var StartAsyncInvoke = [ + 9, + n0, + _SAI, + { + [_h]: ["POST", "/async-invoke", 200], + }, + () => StartAsyncInvokeRequest, + () => StartAsyncInvokeResponse, +]; + +class ApplyGuardrailCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockFrontendService", "ApplyGuardrail", {}) + .n("BedrockRuntimeClient", "ApplyGuardrailCommand") + .sc(ApplyGuardrail) + .build() { +} + +class ConverseCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockFrontendService", "Converse", {}) + .n("BedrockRuntimeClient", "ConverseCommand") + .sc(Converse) + .build() { +} + +class ConverseStreamCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockFrontendService", "ConverseStream", { + eventStream: { + output: true, + }, +}) + .n("BedrockRuntimeClient", "ConverseStreamCommand") + .sc(ConverseStream) + .build() { +} + +class CountTokensCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockFrontendService", "CountTokens", {}) + .n("BedrockRuntimeClient", "CountTokensCommand") + .sc(CountTokens) + .build() { +} + +class GetAsyncInvokeCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockFrontendService", "GetAsyncInvoke", {}) + .n("BedrockRuntimeClient", "GetAsyncInvokeCommand") + .sc(GetAsyncInvoke) + .build() { +} + +class InvokeModelCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockFrontendService", "InvokeModel", {}) + .n("BedrockRuntimeClient", "InvokeModelCommand") + .sc(InvokeModel) + .build() { +} + +class InvokeModelWithBidirectionalStreamCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + middlewareEventstream.getEventStreamPlugin(config), + middlewareWebsocket.getWebSocketPlugin(config, { + headerPrefix: "x-amz-bedrock-", + }), + ]; +}) + .s("AmazonBedrockFrontendService", "InvokeModelWithBidirectionalStream", { + eventStream: { + input: true, + output: true, + }, +}) + .n("BedrockRuntimeClient", "InvokeModelWithBidirectionalStreamCommand") + .sc(InvokeModelWithBidirectionalStream) + .build() { +} + +class InvokeModelWithResponseStreamCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockFrontendService", "InvokeModelWithResponseStream", { + eventStream: { + output: true, + }, +}) + .n("BedrockRuntimeClient", "InvokeModelWithResponseStreamCommand") + .sc(InvokeModelWithResponseStream) + .build() { +} + +class ListAsyncInvokesCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockFrontendService", "ListAsyncInvokes", {}) + .n("BedrockRuntimeClient", "ListAsyncInvokesCommand") + .sc(ListAsyncInvokes) + .build() { +} + +class StartAsyncInvokeCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockFrontendService", "StartAsyncInvoke", {}) + .n("BedrockRuntimeClient", "StartAsyncInvokeCommand") + .sc(StartAsyncInvoke) + .build() { +} + +const commands = { + ApplyGuardrailCommand, + ConverseCommand, + ConverseStreamCommand, + CountTokensCommand, + GetAsyncInvokeCommand, + InvokeModelCommand, + InvokeModelWithBidirectionalStreamCommand, + InvokeModelWithResponseStreamCommand, + ListAsyncInvokesCommand, + StartAsyncInvokeCommand, +}; +class BedrockRuntime extends BedrockRuntimeClient { +} +smithyClient.createAggregatedClient(commands, BedrockRuntime); + +const paginateListAsyncInvokes = core.createPaginator(BedrockRuntimeClient, ListAsyncInvokesCommand, "nextToken", "nextToken", "maxResults"); + +const AsyncInvokeStatus = { + COMPLETED: "Completed", + FAILED: "Failed", + IN_PROGRESS: "InProgress", +}; +const SortAsyncInvocationBy = { + SUBMISSION_TIME: "SubmissionTime", +}; +const SortOrder = { + ASCENDING: "Ascending", + DESCENDING: "Descending", +}; +const GuardrailImageFormat = { + JPEG: "jpeg", + PNG: "png", +}; +const GuardrailContentQualifier = { + GROUNDING_SOURCE: "grounding_source", + GUARD_CONTENT: "guard_content", + QUERY: "query", +}; +const GuardrailOutputScope = { + FULL: "FULL", + INTERVENTIONS: "INTERVENTIONS", +}; +const GuardrailContentSource = { + INPUT: "INPUT", + OUTPUT: "OUTPUT", +}; +const GuardrailAction = { + GUARDRAIL_INTERVENED: "GUARDRAIL_INTERVENED", + NONE: "NONE", +}; +const GuardrailAutomatedReasoningLogicWarningType = { + ALWAYS_FALSE: "ALWAYS_FALSE", + ALWAYS_TRUE: "ALWAYS_TRUE", +}; +const GuardrailContentPolicyAction = { + BLOCKED: "BLOCKED", + NONE: "NONE", +}; +const GuardrailContentFilterConfidence = { + HIGH: "HIGH", + LOW: "LOW", + MEDIUM: "MEDIUM", + NONE: "NONE", +}; +const GuardrailContentFilterStrength = { + HIGH: "HIGH", + LOW: "LOW", + MEDIUM: "MEDIUM", + NONE: "NONE", +}; +const GuardrailContentFilterType = { + HATE: "HATE", + INSULTS: "INSULTS", + MISCONDUCT: "MISCONDUCT", + PROMPT_ATTACK: "PROMPT_ATTACK", + SEXUAL: "SEXUAL", + VIOLENCE: "VIOLENCE", +}; +const GuardrailContextualGroundingPolicyAction = { + BLOCKED: "BLOCKED", + NONE: "NONE", +}; +const GuardrailContextualGroundingFilterType = { + GROUNDING: "GROUNDING", + RELEVANCE: "RELEVANCE", +}; +const GuardrailSensitiveInformationPolicyAction = { + ANONYMIZED: "ANONYMIZED", + BLOCKED: "BLOCKED", + NONE: "NONE", +}; +const GuardrailPiiEntityType = { + ADDRESS: "ADDRESS", + AGE: "AGE", + AWS_ACCESS_KEY: "AWS_ACCESS_KEY", + AWS_SECRET_KEY: "AWS_SECRET_KEY", + CA_HEALTH_NUMBER: "CA_HEALTH_NUMBER", + CA_SOCIAL_INSURANCE_NUMBER: "CA_SOCIAL_INSURANCE_NUMBER", + CREDIT_DEBIT_CARD_CVV: "CREDIT_DEBIT_CARD_CVV", + CREDIT_DEBIT_CARD_EXPIRY: "CREDIT_DEBIT_CARD_EXPIRY", + CREDIT_DEBIT_CARD_NUMBER: "CREDIT_DEBIT_CARD_NUMBER", + DRIVER_ID: "DRIVER_ID", + EMAIL: "EMAIL", + INTERNATIONAL_BANK_ACCOUNT_NUMBER: "INTERNATIONAL_BANK_ACCOUNT_NUMBER", + IP_ADDRESS: "IP_ADDRESS", + LICENSE_PLATE: "LICENSE_PLATE", + MAC_ADDRESS: "MAC_ADDRESS", + NAME: "NAME", + PASSWORD: "PASSWORD", + PHONE: "PHONE", + PIN: "PIN", + SWIFT_CODE: "SWIFT_CODE", + UK_NATIONAL_HEALTH_SERVICE_NUMBER: "UK_NATIONAL_HEALTH_SERVICE_NUMBER", + UK_NATIONAL_INSURANCE_NUMBER: "UK_NATIONAL_INSURANCE_NUMBER", + UK_UNIQUE_TAXPAYER_REFERENCE_NUMBER: "UK_UNIQUE_TAXPAYER_REFERENCE_NUMBER", + URL: "URL", + USERNAME: "USERNAME", + US_BANK_ACCOUNT_NUMBER: "US_BANK_ACCOUNT_NUMBER", + US_BANK_ROUTING_NUMBER: "US_BANK_ROUTING_NUMBER", + US_INDIVIDUAL_TAX_IDENTIFICATION_NUMBER: "US_INDIVIDUAL_TAX_IDENTIFICATION_NUMBER", + US_PASSPORT_NUMBER: "US_PASSPORT_NUMBER", + US_SOCIAL_SECURITY_NUMBER: "US_SOCIAL_SECURITY_NUMBER", + VEHICLE_IDENTIFICATION_NUMBER: "VEHICLE_IDENTIFICATION_NUMBER", +}; +const GuardrailTopicPolicyAction = { + BLOCKED: "BLOCKED", + NONE: "NONE", +}; +const GuardrailTopicType = { + DENY: "DENY", +}; +const GuardrailWordPolicyAction = { + BLOCKED: "BLOCKED", + NONE: "NONE", +}; +const GuardrailManagedWordType = { + PROFANITY: "PROFANITY", +}; +const GuardrailTrace = { + DISABLED: "disabled", + ENABLED: "enabled", + ENABLED_FULL: "enabled_full", +}; +const CachePointType = { + DEFAULT: "default", +}; +const DocumentFormat = { + CSV: "csv", + DOC: "doc", + DOCX: "docx", + HTML: "html", + MD: "md", + PDF: "pdf", + TXT: "txt", + XLS: "xls", + XLSX: "xlsx", +}; +const GuardrailConverseImageFormat = { + JPEG: "jpeg", + PNG: "png", +}; +const GuardrailConverseContentQualifier = { + GROUNDING_SOURCE: "grounding_source", + GUARD_CONTENT: "guard_content", + QUERY: "query", +}; +const ImageFormat = { + GIF: "gif", + JPEG: "jpeg", + PNG: "png", + WEBP: "webp", +}; +const VideoFormat = { + FLV: "flv", + MKV: "mkv", + MOV: "mov", + MP4: "mp4", + MPEG: "mpeg", + MPG: "mpg", + THREE_GP: "three_gp", + WEBM: "webm", + WMV: "wmv", +}; +const ToolResultStatus = { + ERROR: "error", + SUCCESS: "success", +}; +const ToolUseType = { + SERVER_TOOL_USE: "server_tool_use", +}; +const ConversationRole = { + ASSISTANT: "assistant", + USER: "user", +}; +const PerformanceConfigLatency = { + OPTIMIZED: "optimized", + STANDARD: "standard", +}; +const ServiceTierType = { + DEFAULT: "default", + FLEX: "flex", + PRIORITY: "priority", +}; +const StopReason = { + CONTENT_FILTERED: "content_filtered", + END_TURN: "end_turn", + GUARDRAIL_INTERVENED: "guardrail_intervened", + MAX_TOKENS: "max_tokens", + MODEL_CONTEXT_WINDOW_EXCEEDED: "model_context_window_exceeded", + STOP_SEQUENCE: "stop_sequence", + TOOL_USE: "tool_use", +}; +const GuardrailStreamProcessingMode = { + ASYNC: "async", + SYNC: "sync", +}; +const Trace = { + DISABLED: "DISABLED", + ENABLED: "ENABLED", + ENABLED_FULL: "ENABLED_FULL", +}; + +Object.defineProperty(exports, "$Command", { + enumerable: true, + get: function () { return smithyClient.Command; } +}); +Object.defineProperty(exports, "__Client", { + enumerable: true, + get: function () { return smithyClient.Client; } +}); +exports.AccessDeniedException = AccessDeniedException$1; +exports.ApplyGuardrailCommand = ApplyGuardrailCommand; +exports.AsyncInvokeStatus = AsyncInvokeStatus; +exports.BedrockRuntime = BedrockRuntime; +exports.BedrockRuntimeClient = BedrockRuntimeClient; +exports.BedrockRuntimeServiceException = BedrockRuntimeServiceException$1; +exports.CachePointType = CachePointType; +exports.ConflictException = ConflictException$1; +exports.ConversationRole = ConversationRole; +exports.ConverseCommand = ConverseCommand; +exports.ConverseStreamCommand = ConverseStreamCommand; +exports.CountTokensCommand = CountTokensCommand; +exports.DocumentFormat = DocumentFormat; +exports.GetAsyncInvokeCommand = GetAsyncInvokeCommand; +exports.GuardrailAction = GuardrailAction; +exports.GuardrailAutomatedReasoningLogicWarningType = GuardrailAutomatedReasoningLogicWarningType; +exports.GuardrailContentFilterConfidence = GuardrailContentFilterConfidence; +exports.GuardrailContentFilterStrength = GuardrailContentFilterStrength; +exports.GuardrailContentFilterType = GuardrailContentFilterType; +exports.GuardrailContentPolicyAction = GuardrailContentPolicyAction; +exports.GuardrailContentQualifier = GuardrailContentQualifier; +exports.GuardrailContentSource = GuardrailContentSource; +exports.GuardrailContextualGroundingFilterType = GuardrailContextualGroundingFilterType; +exports.GuardrailContextualGroundingPolicyAction = GuardrailContextualGroundingPolicyAction; +exports.GuardrailConverseContentQualifier = GuardrailConverseContentQualifier; +exports.GuardrailConverseImageFormat = GuardrailConverseImageFormat; +exports.GuardrailImageFormat = GuardrailImageFormat; +exports.GuardrailManagedWordType = GuardrailManagedWordType; +exports.GuardrailOutputScope = GuardrailOutputScope; +exports.GuardrailPiiEntityType = GuardrailPiiEntityType; +exports.GuardrailSensitiveInformationPolicyAction = GuardrailSensitiveInformationPolicyAction; +exports.GuardrailStreamProcessingMode = GuardrailStreamProcessingMode; +exports.GuardrailTopicPolicyAction = GuardrailTopicPolicyAction; +exports.GuardrailTopicType = GuardrailTopicType; +exports.GuardrailTrace = GuardrailTrace; +exports.GuardrailWordPolicyAction = GuardrailWordPolicyAction; +exports.ImageFormat = ImageFormat; +exports.InternalServerException = InternalServerException$1; +exports.InvokeModelCommand = InvokeModelCommand; +exports.InvokeModelWithBidirectionalStreamCommand = InvokeModelWithBidirectionalStreamCommand; +exports.InvokeModelWithResponseStreamCommand = InvokeModelWithResponseStreamCommand; +exports.ListAsyncInvokesCommand = ListAsyncInvokesCommand; +exports.ModelErrorException = ModelErrorException$1; +exports.ModelNotReadyException = ModelNotReadyException$1; +exports.ModelStreamErrorException = ModelStreamErrorException$1; +exports.ModelTimeoutException = ModelTimeoutException$1; +exports.PerformanceConfigLatency = PerformanceConfigLatency; +exports.ResourceNotFoundException = ResourceNotFoundException$1; +exports.ServiceQuotaExceededException = ServiceQuotaExceededException$1; +exports.ServiceTierType = ServiceTierType; +exports.ServiceUnavailableException = ServiceUnavailableException$1; +exports.SortAsyncInvocationBy = SortAsyncInvocationBy; +exports.SortOrder = SortOrder; +exports.StartAsyncInvokeCommand = StartAsyncInvokeCommand; +exports.StopReason = StopReason; +exports.ThrottlingException = ThrottlingException$1; +exports.ToolResultStatus = ToolResultStatus; +exports.ToolUseType = ToolUseType; +exports.Trace = Trace; +exports.ValidationException = ValidationException$1; +exports.VideoFormat = VideoFormat; +exports.paginateListAsyncInvokes = paginateListAsyncInvokes; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/runtimeConfig.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/runtimeConfig.js new file mode 100644 index 00000000..ea534e25 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/runtimeConfig.js @@ -0,0 +1,83 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getRuntimeConfig = void 0; +const tslib_1 = require("tslib"); +const package_json_1 = tslib_1.__importDefault(require("../package.json")); +const core_1 = require("@aws-sdk/core"); +const credential_provider_node_1 = require("@aws-sdk/credential-provider-node"); +const eventstream_handler_node_1 = require("@aws-sdk/eventstream-handler-node"); +const token_providers_1 = require("@aws-sdk/token-providers"); +const util_user_agent_node_1 = require("@aws-sdk/util-user-agent-node"); +const config_resolver_1 = require("@smithy/config-resolver"); +const core_2 = require("@smithy/core"); +const eventstream_serde_node_1 = require("@smithy/eventstream-serde-node"); +const hash_node_1 = require("@smithy/hash-node"); +const middleware_retry_1 = require("@smithy/middleware-retry"); +const node_config_provider_1 = require("@smithy/node-config-provider"); +const node_http_handler_1 = require("@smithy/node-http-handler"); +const util_body_length_node_1 = require("@smithy/util-body-length-node"); +const util_retry_1 = require("@smithy/util-retry"); +const runtimeConfig_shared_1 = require("./runtimeConfig.shared"); +const smithy_client_1 = require("@smithy/smithy-client"); +const util_defaults_mode_node_1 = require("@smithy/util-defaults-mode-node"); +const smithy_client_2 = require("@smithy/smithy-client"); +const getRuntimeConfig = (config) => { + (0, smithy_client_2.emitWarningIfUnsupportedVersion)(process.version); + const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config); + const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode); + const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config); + (0, core_1.emitWarningIfUnsupportedVersion)(process.version); + const loaderConfig = { + profile: config?.profile, + logger: clientSharedValues.logger, + signingName: "bedrock", + }; + return { + ...clientSharedValues, + ...config, + runtime: "node", + defaultsMode, + authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), + bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, + credentialDefaultProvider: config?.credentialDefaultProvider ?? credential_provider_node_1.defaultProvider, + defaultUserAgentProvider: config?.defaultUserAgentProvider ?? + (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), + eventStreamPayloadHandlerProvider: config?.eventStreamPayloadHandlerProvider ?? eventstream_handler_node_1.eventStreamPayloadHandlerProvider, + eventStreamSerdeProvider: config?.eventStreamSerdeProvider ?? eventstream_serde_node_1.eventStreamSerdeProvider, + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new core_1.AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#httpBearerAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#httpBearerAuth") || + (async (idProps) => { + try { + return await (0, token_providers_1.fromEnvSigningName)({ signingName: "bedrock" })(); + } + catch (error) { + return await (0, token_providers_1.nodeProvider)(idProps)(idProps); + } + }), + signer: new core_2.HttpBearerAuthSigner(), + }, + ], + maxAttempts: config?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), + region: config?.region ?? + (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), + requestHandler: node_http_handler_1.NodeHttp2Handler.create(config?.requestHandler ?? (async () => ({ ...(await defaultConfigProvider()), disableConcurrentStreams: true }))), + retryMode: config?.retryMode ?? + (0, node_config_provider_1.loadConfig)({ + ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS, + default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE, + }, config), + sha256: config?.sha256 ?? hash_node_1.Hash.bind(null, "sha256"), + streamCollector: config?.streamCollector ?? node_http_handler_1.streamCollector, + useDualstackEndpoint: config?.useDualstackEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), + }; +}; +exports.getRuntimeConfig = getRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/runtimeConfig.shared.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/runtimeConfig.shared.js new file mode 100644 index 00000000..3f4816c4 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/runtimeConfig.shared.js @@ -0,0 +1,42 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getRuntimeConfig = void 0; +const core_1 = require("@aws-sdk/core"); +const protocols_1 = require("@aws-sdk/core/protocols"); +const core_2 = require("@smithy/core"); +const smithy_client_1 = require("@smithy/smithy-client"); +const url_parser_1 = require("@smithy/url-parser"); +const util_base64_1 = require("@smithy/util-base64"); +const util_utf8_1 = require("@smithy/util-utf8"); +const httpAuthSchemeProvider_1 = require("./auth/httpAuthSchemeProvider"); +const endpointResolver_1 = require("./endpoint/endpointResolver"); +const getRuntimeConfig = (config) => { + return { + apiVersion: "2023-09-30", + base64Decoder: config?.base64Decoder ?? util_base64_1.fromBase64, + base64Encoder: config?.base64Encoder ?? util_base64_1.toBase64, + disableHostPrefix: config?.disableHostPrefix ?? false, + endpointProvider: config?.endpointProvider ?? endpointResolver_1.defaultEndpointResolver, + extensions: config?.extensions ?? [], + httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultBedrockRuntimeHttpAuthSchemeProvider, + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new core_1.AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#httpBearerAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#httpBearerAuth"), + signer: new core_2.HttpBearerAuthSigner(), + }, + ], + logger: config?.logger ?? new smithy_client_1.NoOpLogger(), + protocol: config?.protocol ?? new protocols_1.AwsRestJsonProtocol({ defaultNamespace: "com.amazonaws.bedrockruntime" }), + serviceId: config?.serviceId ?? "Bedrock Runtime", + urlParser: config?.urlParser ?? url_parser_1.parseUrl, + utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, + utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, + }; +}; +exports.getRuntimeConfig = getRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/eventstream-serde-node/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/eventstream-serde-node/dist-cjs/index.js new file mode 100644 index 00000000..cd52cf1a --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/eventstream-serde-node/dist-cjs/index.js @@ -0,0 +1,53 @@ +'use strict'; + +var eventstreamSerdeUniversal = require('@smithy/eventstream-serde-universal'); +var stream = require('stream'); + +async function* readabletoIterable(readStream) { + let streamEnded = false; + let generationEnded = false; + const records = new Array(); + readStream.on("error", (err) => { + if (!streamEnded) { + streamEnded = true; + } + if (err) { + throw err; + } + }); + readStream.on("data", (data) => { + records.push(data); + }); + readStream.on("end", () => { + streamEnded = true; + }); + while (!generationEnded) { + const value = await new Promise((resolve) => setTimeout(() => resolve(records.shift()), 0)); + if (value) { + yield value; + } + generationEnded = streamEnded && records.length === 0; + } +} + +class EventStreamMarshaller { + universalMarshaller; + constructor({ utf8Encoder, utf8Decoder }) { + this.universalMarshaller = new eventstreamSerdeUniversal.EventStreamMarshaller({ + utf8Decoder, + utf8Encoder, + }); + } + deserialize(body, deserializer) { + const bodyIterable = typeof body[Symbol.asyncIterator] === "function" ? body : readabletoIterable(body); + return this.universalMarshaller.deserialize(bodyIterable, deserializer); + } + serialize(input, serializer) { + return stream.Readable.from(this.universalMarshaller.serialize(input, serializer)); + } +} + +const eventStreamSerdeProvider = (options) => new EventStreamMarshaller(options); + +exports.EventStreamMarshaller = EventStreamMarshaller; +exports.eventStreamSerdeProvider = eventStreamSerdeProvider; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/eventstream-serde-node/node_modules/@smithy/eventstream-serde-universal/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/eventstream-serde-node/node_modules/@smithy/eventstream-serde-universal/dist-cjs/index.js new file mode 100644 index 00000000..cd84e7bd --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/eventstream-serde-node/node_modules/@smithy/eventstream-serde-universal/dist-cjs/index.js @@ -0,0 +1,132 @@ +'use strict'; + +var eventstreamCodec = require('@smithy/eventstream-codec'); + +function getChunkedStream(source) { + let currentMessageTotalLength = 0; + let currentMessagePendingLength = 0; + let currentMessage = null; + let messageLengthBuffer = null; + const allocateMessage = (size) => { + if (typeof size !== "number") { + throw new Error("Attempted to allocate an event message where size was not a number: " + size); + } + currentMessageTotalLength = size; + currentMessagePendingLength = 4; + currentMessage = new Uint8Array(size); + const currentMessageView = new DataView(currentMessage.buffer); + currentMessageView.setUint32(0, size, false); + }; + const iterator = async function* () { + const sourceIterator = source[Symbol.asyncIterator](); + while (true) { + const { value, done } = await sourceIterator.next(); + if (done) { + if (!currentMessageTotalLength) { + return; + } + else if (currentMessageTotalLength === currentMessagePendingLength) { + yield currentMessage; + } + else { + throw new Error("Truncated event message received."); + } + return; + } + const chunkLength = value.length; + let currentOffset = 0; + while (currentOffset < chunkLength) { + if (!currentMessage) { + const bytesRemaining = chunkLength - currentOffset; + if (!messageLengthBuffer) { + messageLengthBuffer = new Uint8Array(4); + } + const numBytesForTotal = Math.min(4 - currentMessagePendingLength, bytesRemaining); + messageLengthBuffer.set(value.slice(currentOffset, currentOffset + numBytesForTotal), currentMessagePendingLength); + currentMessagePendingLength += numBytesForTotal; + currentOffset += numBytesForTotal; + if (currentMessagePendingLength < 4) { + break; + } + allocateMessage(new DataView(messageLengthBuffer.buffer).getUint32(0, false)); + messageLengthBuffer = null; + } + const numBytesToWrite = Math.min(currentMessageTotalLength - currentMessagePendingLength, chunkLength - currentOffset); + currentMessage.set(value.slice(currentOffset, currentOffset + numBytesToWrite), currentMessagePendingLength); + currentMessagePendingLength += numBytesToWrite; + currentOffset += numBytesToWrite; + if (currentMessageTotalLength && currentMessageTotalLength === currentMessagePendingLength) { + yield currentMessage; + currentMessage = null; + currentMessageTotalLength = 0; + currentMessagePendingLength = 0; + } + } + } + }; + return { + [Symbol.asyncIterator]: iterator, + }; +} + +function getMessageUnmarshaller(deserializer, toUtf8) { + return async function (message) { + const { value: messageType } = message.headers[":message-type"]; + if (messageType === "error") { + const unmodeledError = new Error(message.headers[":error-message"].value || "UnknownError"); + unmodeledError.name = message.headers[":error-code"].value; + throw unmodeledError; + } + else if (messageType === "exception") { + const code = message.headers[":exception-type"].value; + const exception = { [code]: message }; + const deserializedException = await deserializer(exception); + if (deserializedException.$unknown) { + const error = new Error(toUtf8(message.body)); + error.name = code; + throw error; + } + throw deserializedException[code]; + } + else if (messageType === "event") { + const event = { + [message.headers[":event-type"].value]: message, + }; + const deserialized = await deserializer(event); + if (deserialized.$unknown) + return; + return deserialized; + } + else { + throw Error(`Unrecognizable event type: ${message.headers[":event-type"].value}`); + } + }; +} + +class EventStreamMarshaller { + eventStreamCodec; + utfEncoder; + constructor({ utf8Encoder, utf8Decoder }) { + this.eventStreamCodec = new eventstreamCodec.EventStreamCodec(utf8Encoder, utf8Decoder); + this.utfEncoder = utf8Encoder; + } + deserialize(body, deserializer) { + const inputStream = getChunkedStream(body); + return new eventstreamCodec.SmithyMessageDecoderStream({ + messageStream: new eventstreamCodec.MessageDecoderStream({ inputStream, decoder: this.eventStreamCodec }), + deserializer: getMessageUnmarshaller(deserializer, this.utfEncoder), + }); + } + serialize(inputStream, serializer) { + return new eventstreamCodec.MessageEncoderStream({ + messageStream: new eventstreamCodec.SmithyMessageEncoderStream({ inputStream, serializer }), + encoder: this.eventStreamCodec, + includeEndFrame: true, + }); + } +} + +const eventStreamSerdeProvider = (options) => new EventStreamMarshaller(options); + +exports.EventStreamMarshaller = EventStreamMarshaller; +exports.eventStreamSerdeProvider = eventStreamSerdeProvider; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/protocol-http/dist-cjs/index.js new file mode 100644 index 00000000..52303c3b --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/protocol-http/dist-cjs/index.js @@ -0,0 +1,169 @@ +'use strict'; + +var types = require('@smithy/types'); + +const getHttpHandlerExtensionConfiguration = (runtimeConfig) => { + return { + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); + }, + }; +}; +const resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler(), + }; +}; + +class Field { + name; + kind; + values; + constructor({ name, kind = types.FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; + } + add(value) { + this.values.push(value); + } + set(values) { + this.values = values; + } + remove(value) { + this.values = this.values.filter((v) => v !== value); + } + toString() { + return this.values.map((v) => (v.includes(",") || v.includes(" ") ? `"${v}"` : v)).join(", "); + } + get() { + return this.values; + } +} + +class Fields { + entries = {}; + encoding; + constructor({ fields = [], encoding = "utf-8" }) { + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + setField(field) { + this.entries[field.name.toLowerCase()] = field; + } + getField(name) { + return this.entries[name.toLowerCase()]; + } + removeField(name) { + delete this.entries[name.toLowerCase()]; + } + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } +} + +class HttpRequest { + method; + protocol; + hostname; + port; + path; + query; + headers; + username; + password; + fragment; + body; + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol + ? options.protocol.slice(-1) !== ":" + ? `${options.protocol}:` + : options.protocol + : "https:"; + this.path = options.path ? (options.path.charAt(0) !== "/" ? `/${options.path}` : options.path) : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + static clone(request) { + const cloned = new HttpRequest({ + ...request, + headers: { ...request.headers }, + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); + } + return cloned; + } + static isInstance(request) { + if (!request) { + return false; + } + const req = request; + return ("method" in req && + "protocol" in req && + "hostname" in req && + "path" in req && + typeof req["query"] === "object" && + typeof req["headers"] === "object"); + } + clone() { + return HttpRequest.clone(this); + } +} +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param, + }; + }, {}); +} + +class HttpResponse { + statusCode; + reason; + headers; + body; + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) + return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + } +} + +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} + +exports.Field = Field; +exports.Fields = Fields; +exports.HttpRequest = HttpRequest; +exports.HttpResponse = HttpResponse; +exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration; +exports.isValidHostname = isValidHostname; +exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/smithy-client/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/smithy-client/dist-cjs/index.js new file mode 100644 index 00000000..9f589873 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/smithy-client/dist-cjs/index.js @@ -0,0 +1,589 @@ +'use strict'; + +var middlewareStack = require('@smithy/middleware-stack'); +var protocols = require('@smithy/core/protocols'); +var types = require('@smithy/types'); +var schema = require('@smithy/core/schema'); +var serde = require('@smithy/core/serde'); + +class Client { + config; + middlewareStack = middlewareStack.constructStack(); + initConfig; + handlers; + constructor(config) { + this.config = config; + } + send(command, optionsOrCb, cb) { + const options = typeof optionsOrCb !== "function" ? optionsOrCb : undefined; + const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb; + const useHandlerCache = options === undefined && this.config.cacheMiddleware === true; + let handler; + if (useHandlerCache) { + if (!this.handlers) { + this.handlers = new WeakMap(); + } + const handlers = this.handlers; + if (handlers.has(command.constructor)) { + handler = handlers.get(command.constructor); + } + else { + handler = command.resolveMiddleware(this.middlewareStack, this.config, options); + handlers.set(command.constructor, handler); + } + } + else { + delete this.handlers; + handler = command.resolveMiddleware(this.middlewareStack, this.config, options); + } + if (callback) { + handler(command) + .then((result) => callback(null, result.output), (err) => callback(err)) + .catch(() => { }); + } + else { + return handler(command).then((result) => result.output); + } + } + destroy() { + this.config?.requestHandler?.destroy?.(); + delete this.handlers; + } +} + +const SENSITIVE_STRING$1 = "***SensitiveInformation***"; +function schemaLogFilter(schema$1, data) { + if (data == null) { + return data; + } + const ns = schema.NormalizedSchema.of(schema$1); + if (ns.getMergedTraits().sensitive) { + return SENSITIVE_STRING$1; + } + if (ns.isListSchema()) { + const isSensitive = !!ns.getValueSchema().getMergedTraits().sensitive; + if (isSensitive) { + return SENSITIVE_STRING$1; + } + } + else if (ns.isMapSchema()) { + const isSensitive = !!ns.getKeySchema().getMergedTraits().sensitive || !!ns.getValueSchema().getMergedTraits().sensitive; + if (isSensitive) { + return SENSITIVE_STRING$1; + } + } + else if (ns.isStructSchema() && typeof data === "object") { + const object = data; + const newObject = {}; + for (const [member, memberNs] of ns.structIterator()) { + if (object[member] != null) { + newObject[member] = schemaLogFilter(memberNs, object[member]); + } + } + return newObject; + } + return data; +} + +class Command { + middlewareStack = middlewareStack.constructStack(); + schema; + static classBuilder() { + return new ClassBuilder(); + } + resolveMiddlewareWithContext(clientStack, configuration, options, { middlewareFn, clientName, commandName, inputFilterSensitiveLog, outputFilterSensitiveLog, smithyContext, additionalContext, CommandCtor, }) { + for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options)) { + this.middlewareStack.use(mw); + } + const stack = clientStack.concat(this.middlewareStack); + const { logger } = configuration; + const handlerExecutionContext = { + logger, + clientName, + commandName, + inputFilterSensitiveLog, + outputFilterSensitiveLog, + [types.SMITHY_CONTEXT_KEY]: { + commandInstance: this, + ...smithyContext, + }, + ...additionalContext, + }; + const { requestHandler } = configuration; + return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); + } +} +class ClassBuilder { + _init = () => { }; + _ep = {}; + _middlewareFn = () => []; + _commandName = ""; + _clientName = ""; + _additionalContext = {}; + _smithyContext = {}; + _inputFilterSensitiveLog = undefined; + _outputFilterSensitiveLog = undefined; + _serializer = null; + _deserializer = null; + _operationSchema; + init(cb) { + this._init = cb; + } + ep(endpointParameterInstructions) { + this._ep = endpointParameterInstructions; + return this; + } + m(middlewareSupplier) { + this._middlewareFn = middlewareSupplier; + return this; + } + s(service, operation, smithyContext = {}) { + this._smithyContext = { + service, + operation, + ...smithyContext, + }; + return this; + } + c(additionalContext = {}) { + this._additionalContext = additionalContext; + return this; + } + n(clientName, commandName) { + this._clientName = clientName; + this._commandName = commandName; + return this; + } + f(inputFilter = (_) => _, outputFilter = (_) => _) { + this._inputFilterSensitiveLog = inputFilter; + this._outputFilterSensitiveLog = outputFilter; + return this; + } + ser(serializer) { + this._serializer = serializer; + return this; + } + de(deserializer) { + this._deserializer = deserializer; + return this; + } + sc(operation) { + this._operationSchema = operation; + this._smithyContext.operationSchema = operation; + return this; + } + build() { + const closure = this; + let CommandRef; + return (CommandRef = class extends Command { + input; + static getEndpointParameterInstructions() { + return closure._ep; + } + constructor(...[input]) { + super(); + this.input = input ?? {}; + closure._init(this); + this.schema = closure._operationSchema; + } + resolveMiddleware(stack, configuration, options) { + const op = closure._operationSchema; + const input = op?.[4] ?? op?.input; + const output = op?.[5] ?? op?.output; + return this.resolveMiddlewareWithContext(stack, configuration, options, { + CommandCtor: CommandRef, + middlewareFn: closure._middlewareFn, + clientName: closure._clientName, + commandName: closure._commandName, + inputFilterSensitiveLog: closure._inputFilterSensitiveLog ?? (op ? schemaLogFilter.bind(null, input) : (_) => _), + outputFilterSensitiveLog: closure._outputFilterSensitiveLog ?? (op ? schemaLogFilter.bind(null, output) : (_) => _), + smithyContext: closure._smithyContext, + additionalContext: closure._additionalContext, + }); + } + serialize = closure._serializer; + deserialize = closure._deserializer; + }); + } +} + +const SENSITIVE_STRING = "***SensitiveInformation***"; + +const createAggregatedClient = (commands, Client) => { + for (const command of Object.keys(commands)) { + const CommandCtor = commands[command]; + const methodImpl = async function (args, optionsOrCb, cb) { + const command = new CommandCtor(args); + if (typeof optionsOrCb === "function") { + this.send(command, optionsOrCb); + } + else if (typeof cb === "function") { + if (typeof optionsOrCb !== "object") + throw new Error(`Expected http options but got ${typeof optionsOrCb}`); + this.send(command, optionsOrCb || {}, cb); + } + else { + return this.send(command, optionsOrCb); + } + }; + const methodName = (command[0].toLowerCase() + command.slice(1)).replace(/Command$/, ""); + Client.prototype[methodName] = methodImpl; + } +}; + +class ServiceException extends Error { + $fault; + $response; + $retryable; + $metadata; + constructor(options) { + super(options.message); + Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype); + this.name = options.name; + this.$fault = options.$fault; + this.$metadata = options.$metadata; + } + static isInstance(value) { + if (!value) + return false; + const candidate = value; + return (ServiceException.prototype.isPrototypeOf(candidate) || + (Boolean(candidate.$fault) && + Boolean(candidate.$metadata) && + (candidate.$fault === "client" || candidate.$fault === "server"))); + } + static [Symbol.hasInstance](instance) { + if (!instance) + return false; + const candidate = instance; + if (this === ServiceException) { + return ServiceException.isInstance(instance); + } + if (ServiceException.isInstance(instance)) { + if (candidate.name && this.name) { + return this.prototype.isPrototypeOf(instance) || candidate.name === this.name; + } + return this.prototype.isPrototypeOf(instance); + } + return false; + } +} +const decorateServiceException = (exception, additions = {}) => { + Object.entries(additions) + .filter(([, v]) => v !== undefined) + .forEach(([k, v]) => { + if (exception[k] == undefined || exception[k] === "") { + exception[k] = v; + } + }); + const message = exception.message || exception.Message || "UnknownError"; + exception.message = message; + delete exception.Message; + return exception; +}; + +const throwDefaultError = ({ output, parsedBody, exceptionCtor, errorCode }) => { + const $metadata = deserializeMetadata(output); + const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : undefined; + const response = new exceptionCtor({ + name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || "UnknownError", + $fault: "client", + $metadata, + }); + throw decorateServiceException(response, parsedBody); +}; +const withBaseException = (ExceptionCtor) => { + return ({ output, parsedBody, errorCode }) => { + throwDefaultError({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode }); + }; +}; +const deserializeMetadata = (output) => ({ + httpStatusCode: output.statusCode, + requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], + extendedRequestId: output.headers["x-amz-id-2"], + cfId: output.headers["x-amz-cf-id"], +}); + +const loadConfigsForDefaultMode = (mode) => { + switch (mode) { + case "standard": + return { + retryMode: "standard", + connectionTimeout: 3100, + }; + case "in-region": + return { + retryMode: "standard", + connectionTimeout: 1100, + }; + case "cross-region": + return { + retryMode: "standard", + connectionTimeout: 3100, + }; + case "mobile": + return { + retryMode: "standard", + connectionTimeout: 30000, + }; + default: + return {}; + } +}; + +let warningEmitted = false; +const emitWarningIfUnsupportedVersion = (version) => { + if (version && !warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 16) { + warningEmitted = true; + } +}; + +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + for (const id in types.AlgorithmId) { + const algorithmId = types.AlgorithmId[id]; + if (runtimeConfig[algorithmId] === undefined) { + continue; + } + checksumAlgorithms.push({ + algorithmId: () => algorithmId, + checksumConstructor: () => runtimeConfig[algorithmId], + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getRetryConfiguration = (runtimeConfig) => { + return { + setRetryStrategy(retryStrategy) { + runtimeConfig.retryStrategy = retryStrategy; + }, + retryStrategy() { + return runtimeConfig.retryStrategy; + }, + }; +}; +const resolveRetryRuntimeConfig = (retryStrategyConfiguration) => { + const runtimeConfig = {}; + runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy(); + return runtimeConfig; +}; + +const getDefaultExtensionConfiguration = (runtimeConfig) => { + return Object.assign(getChecksumConfiguration(runtimeConfig), getRetryConfiguration(runtimeConfig)); +}; +const getDefaultClientConfiguration = getDefaultExtensionConfiguration; +const resolveDefaultRuntimeConfig = (config) => { + return Object.assign(resolveChecksumRuntimeConfig(config), resolveRetryRuntimeConfig(config)); +}; + +const getArrayIfSingleItem = (mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray]; + +const getValueFromTextNode = (obj) => { + const textNodeName = "#text"; + for (const key in obj) { + if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== undefined) { + obj[key] = obj[key][textNodeName]; + } + else if (typeof obj[key] === "object" && obj[key] !== null) { + obj[key] = getValueFromTextNode(obj[key]); + } + } + return obj; +}; + +const isSerializableHeaderValue = (value) => { + return value != null; +}; + +class NoOpLogger { + trace() { } + debug() { } + info() { } + warn() { } + error() { } +} + +function map(arg0, arg1, arg2) { + let target; + let filter; + let instructions; + if (typeof arg1 === "undefined" && typeof arg2 === "undefined") { + target = {}; + instructions = arg0; + } + else { + target = arg0; + if (typeof arg1 === "function") { + filter = arg1; + instructions = arg2; + return mapWithFilter(target, filter, instructions); + } + else { + instructions = arg1; + } + } + for (const key of Object.keys(instructions)) { + if (!Array.isArray(instructions[key])) { + target[key] = instructions[key]; + continue; + } + applyInstruction(target, null, instructions, key); + } + return target; +} +const convertMap = (target) => { + const output = {}; + for (const [k, v] of Object.entries(target || {})) { + output[k] = [, v]; + } + return output; +}; +const take = (source, instructions) => { + const out = {}; + for (const key in instructions) { + applyInstruction(out, source, instructions, key); + } + return out; +}; +const mapWithFilter = (target, filter, instructions) => { + return map(target, Object.entries(instructions).reduce((_instructions, [key, value]) => { + if (Array.isArray(value)) { + _instructions[key] = value; + } + else { + if (typeof value === "function") { + _instructions[key] = [filter, value()]; + } + else { + _instructions[key] = [filter, value]; + } + } + return _instructions; + }, {})); +}; +const applyInstruction = (target, source, instructions, targetKey) => { + if (source !== null) { + let instruction = instructions[targetKey]; + if (typeof instruction === "function") { + instruction = [, instruction]; + } + const [filter = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction; + if ((typeof filter === "function" && filter(source[sourceKey])) || (typeof filter !== "function" && !!filter)) { + target[targetKey] = valueFn(source[sourceKey]); + } + return; + } + let [filter, value] = instructions[targetKey]; + if (typeof value === "function") { + let _value; + const defaultFilterPassed = filter === undefined && (_value = value()) != null; + const customFilterPassed = (typeof filter === "function" && !!filter(void 0)) || (typeof filter !== "function" && !!filter); + if (defaultFilterPassed) { + target[targetKey] = _value; + } + else if (customFilterPassed) { + target[targetKey] = value(); + } + } + else { + const defaultFilterPassed = filter === undefined && value != null; + const customFilterPassed = (typeof filter === "function" && !!filter(value)) || (typeof filter !== "function" && !!filter); + if (defaultFilterPassed || customFilterPassed) { + target[targetKey] = value; + } + } +}; +const nonNullish = (_) => _ != null; +const pass = (_) => _; + +const serializeFloat = (value) => { + if (value !== value) { + return "NaN"; + } + switch (value) { + case Infinity: + return "Infinity"; + case -Infinity: + return "-Infinity"; + default: + return value; + } +}; +const serializeDateTime = (date) => date.toISOString().replace(".000Z", "Z"); + +const _json = (obj) => { + if (obj == null) { + return {}; + } + if (Array.isArray(obj)) { + return obj.filter((_) => _ != null).map(_json); + } + if (typeof obj === "object") { + const target = {}; + for (const key of Object.keys(obj)) { + if (obj[key] == null) { + continue; + } + target[key] = _json(obj[key]); + } + return target; + } + return obj; +}; + +Object.defineProperty(exports, "collectBody", { + enumerable: true, + get: function () { return protocols.collectBody; } +}); +Object.defineProperty(exports, "extendedEncodeURIComponent", { + enumerable: true, + get: function () { return protocols.extendedEncodeURIComponent; } +}); +Object.defineProperty(exports, "resolvedPath", { + enumerable: true, + get: function () { return protocols.resolvedPath; } +}); +exports.Client = Client; +exports.Command = Command; +exports.NoOpLogger = NoOpLogger; +exports.SENSITIVE_STRING = SENSITIVE_STRING; +exports.ServiceException = ServiceException; +exports._json = _json; +exports.convertMap = convertMap; +exports.createAggregatedClient = createAggregatedClient; +exports.decorateServiceException = decorateServiceException; +exports.emitWarningIfUnsupportedVersion = emitWarningIfUnsupportedVersion; +exports.getArrayIfSingleItem = getArrayIfSingleItem; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.getDefaultExtensionConfiguration = getDefaultExtensionConfiguration; +exports.getValueFromTextNode = getValueFromTextNode; +exports.isSerializableHeaderValue = isSerializableHeaderValue; +exports.loadConfigsForDefaultMode = loadConfigsForDefaultMode; +exports.map = map; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; +exports.serializeDateTime = serializeDateTime; +exports.serializeFloat = serializeFloat; +exports.take = take; +exports.throwDefaultError = throwDefaultError; +exports.withBaseException = withBaseException; +Object.keys(serde).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return serde[k]; } + }); +}); diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-cjs/index.js new file mode 100644 index 00000000..be6d0e1a --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-cjs/index.js @@ -0,0 +1,91 @@ +'use strict'; + +exports.HttpAuthLocation = void 0; +(function (HttpAuthLocation) { + HttpAuthLocation["HEADER"] = "header"; + HttpAuthLocation["QUERY"] = "query"; +})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); + +exports.HttpApiKeyAuthLocation = void 0; +(function (HttpApiKeyAuthLocation) { + HttpApiKeyAuthLocation["HEADER"] = "header"; + HttpApiKeyAuthLocation["QUERY"] = "query"; +})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); + +exports.EndpointURLScheme = void 0; +(function (EndpointURLScheme) { + EndpointURLScheme["HTTP"] = "http"; + EndpointURLScheme["HTTPS"] = "https"; +})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); + +exports.AlgorithmId = void 0; +(function (AlgorithmId) { + AlgorithmId["MD5"] = "md5"; + AlgorithmId["CRC32"] = "crc32"; + AlgorithmId["CRC32C"] = "crc32c"; + AlgorithmId["SHA1"] = "sha1"; + AlgorithmId["SHA256"] = "sha256"; +})(exports.AlgorithmId || (exports.AlgorithmId = {})); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.SHA256, + checksumConstructor: () => runtimeConfig.sha256, + }); + } + if (runtimeConfig.md5 != undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.MD5, + checksumConstructor: () => runtimeConfig.md5, + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getDefaultClientConfiguration = (runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}; +const resolveDefaultRuntimeConfig = (config) => { + return resolveChecksumRuntimeConfig(config); +}; + +exports.FieldPosition = void 0; +(function (FieldPosition) { + FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; + FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; +})(exports.FieldPosition || (exports.FieldPosition = {})); + +const SMITHY_CONTEXT_KEY = "__smithy_context"; + +exports.IniSectionType = void 0; +(function (IniSectionType) { + IniSectionType["PROFILE"] = "profile"; + IniSectionType["SSO_SESSION"] = "sso-session"; + IniSectionType["SERVICES"] = "services"; +})(exports.IniSectionType || (exports.IniSectionType = {})); + +exports.RequestHandlerProtocol = void 0; +(function (RequestHandlerProtocol) { + RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; +})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); + +exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js new file mode 100644 index 00000000..b06a7b87 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromBase64 = void 0; +const util_buffer_from_1 = require("@smithy/util-buffer-from"); +const BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; +const fromBase64 = (input) => { + if ((input.length * 3) % 4 !== 0) { + throw new TypeError(`Incorrect padding on base64 string.`); + } + if (!BASE64_REGEX.exec(input)) { + throw new TypeError(`Invalid base64 string.`); + } + const buffer = (0, util_buffer_from_1.fromString)(input, "base64"); + return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); +}; +exports.fromBase64 = fromBase64; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/dist-cjs/index.js new file mode 100644 index 00000000..c095e288 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/dist-cjs/index.js @@ -0,0 +1,19 @@ +'use strict'; + +var fromBase64 = require('./fromBase64'); +var toBase64 = require('./toBase64'); + + + +Object.keys(fromBase64).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return fromBase64[k]; } + }); +}); +Object.keys(toBase64).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return toBase64[k]; } + }); +}); diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/dist-cjs/toBase64.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/dist-cjs/toBase64.js new file mode 100644 index 00000000..0590ce3f --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/dist-cjs/toBase64.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.toBase64 = void 0; +const util_buffer_from_1 = require("@smithy/util-buffer-from"); +const util_utf8_1 = require("@smithy/util-utf8"); +const toBase64 = (_input) => { + let input; + if (typeof _input === "string") { + input = (0, util_utf8_1.fromUtf8)(_input); + } + else { + input = _input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); + } + return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64"); +}; +exports.toBase64 = toBase64; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js new file mode 100644 index 00000000..b577c9ca --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js @@ -0,0 +1,20 @@ +'use strict'; + +var isArrayBuffer = require('@smithy/is-array-buffer'); +var buffer = require('buffer'); + +const fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => { + if (!isArrayBuffer.isArrayBuffer(input)) { + throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); + } + return buffer.Buffer.from(input, offset, length); +}; +const fromString = (input, encoding) => { + if (typeof input !== "string") { + throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); + } + return encoding ? buffer.Buffer.from(input, encoding) : buffer.Buffer.from(input); +}; + +exports.fromArrayBuffer = fromArrayBuffer; +exports.fromString = fromString; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js new file mode 100644 index 00000000..3238bb77 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js @@ -0,0 +1,6 @@ +'use strict'; + +const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) || + Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; + +exports.isArrayBuffer = isArrayBuffer; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/auth/httpAuthSchemeProvider.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/auth/httpAuthSchemeProvider.js new file mode 100644 index 00000000..64710468 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/auth/httpAuthSchemeProvider.js @@ -0,0 +1,64 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.resolveHttpAuthSchemeConfig = exports.defaultBedrockHttpAuthSchemeProvider = exports.defaultBedrockHttpAuthSchemeParametersProvider = void 0; +const core_1 = require("@aws-sdk/core"); +const core_2 = require("@smithy/core"); +const util_middleware_1 = require("@smithy/util-middleware"); +const defaultBedrockHttpAuthSchemeParametersProvider = async (config, context, input) => { + return { + operation: (0, util_middleware_1.getSmithyContext)(context).operation, + region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || + (() => { + throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); + })(), + }; +}; +exports.defaultBedrockHttpAuthSchemeParametersProvider = defaultBedrockHttpAuthSchemeParametersProvider; +function createAwsAuthSigv4HttpAuthOption(authParameters) { + return { + schemeId: "aws.auth#sigv4", + signingProperties: { + name: "bedrock", + region: authParameters.region, + }, + propertiesExtractor: (config, context) => ({ + signingProperties: { + config, + context, + }, + }), + }; +} +function createSmithyApiHttpBearerAuthHttpAuthOption(authParameters) { + return { + schemeId: "smithy.api#httpBearerAuth", + propertiesExtractor: ({ profile, filepath, configFilepath, ignoreCache }, context) => ({ + identityProperties: { + profile, + filepath, + configFilepath, + ignoreCache, + }, + }), + }; +} +const defaultBedrockHttpAuthSchemeProvider = (authParameters) => { + const options = []; + switch (authParameters.operation) { + default: { + options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); + options.push(createSmithyApiHttpBearerAuthHttpAuthOption(authParameters)); + } + } + return options; +}; +exports.defaultBedrockHttpAuthSchemeProvider = defaultBedrockHttpAuthSchemeProvider; +const resolveHttpAuthSchemeConfig = (config) => { + const token = (0, core_2.memoizeIdentityProvider)(config.token, core_2.isIdentityExpired, core_2.doesIdentityRequireRefresh); + const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config); + return Object.assign(config_0, { + authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), + token, + }); +}; +exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/endpoint/endpointResolver.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/endpoint/endpointResolver.js new file mode 100644 index 00000000..7258a356 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/endpoint/endpointResolver.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defaultEndpointResolver = void 0; +const util_endpoints_1 = require("@aws-sdk/util-endpoints"); +const util_endpoints_2 = require("@smithy/util-endpoints"); +const ruleset_1 = require("./ruleset"); +const cache = new util_endpoints_2.EndpointCache({ + size: 50, + params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"], +}); +const defaultEndpointResolver = (endpointParams, context = {}) => { + return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { + endpointParams: endpointParams, + logger: context.logger, + })); +}; +exports.defaultEndpointResolver = defaultEndpointResolver; +util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/endpoint/ruleset.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/endpoint/ruleset.js new file mode 100644 index 00000000..a0506167 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/endpoint/ruleset.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ruleSet = void 0; +const s = "required", t = "fn", u = "argv", v = "ref"; +const a = true, b = "isSet", c = "booleanEquals", d = "error", e = "endpoint", f = "tree", g = "PartitionResult", h = { [s]: false, "type": "string" }, i = { [s]: true, "default": false, "type": "boolean" }, j = { [v]: "Endpoint" }, k = { [t]: c, [u]: [{ [v]: "UseFIPS" }, true] }, l = { [t]: c, [u]: [{ [v]: "UseDualStack" }, true] }, m = {}, n = { [t]: "getAttr", [u]: [{ [v]: g }, "supportsFIPS"] }, o = { [t]: c, [u]: [true, { [t]: "getAttr", [u]: [{ [v]: g }, "supportsDualStack"] }] }, p = [k], q = [l], r = [{ [v]: "Region" }]; +const _data = { version: "1.0", parameters: { Region: h, UseDualStack: i, UseFIPS: i, Endpoint: h }, rules: [{ conditions: [{ [t]: b, [u]: [j] }], rules: [{ conditions: p, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d }, { rules: [{ conditions: q, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d }, { endpoint: { url: j, properties: m, headers: m }, type: e }], type: f }], type: f }, { rules: [{ conditions: [{ [t]: b, [u]: r }], rules: [{ conditions: [{ [t]: "aws.partition", [u]: r, assign: g }], rules: [{ conditions: [k, l], rules: [{ conditions: [{ [t]: c, [u]: [a, n] }, o], rules: [{ rules: [{ endpoint: { url: "https://bedrock-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: m, headers: m }, type: e }], type: f }], type: f }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d }], type: f }, { conditions: p, rules: [{ conditions: [{ [t]: c, [u]: [n, a] }], rules: [{ rules: [{ endpoint: { url: "https://bedrock-fips.{Region}.{PartitionResult#dnsSuffix}", properties: m, headers: m }, type: e }], type: f }], type: f }, { error: "FIPS is enabled but this partition does not support FIPS", type: d }], type: f }, { conditions: q, rules: [{ conditions: [o], rules: [{ rules: [{ endpoint: { url: "https://bedrock.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: m, headers: m }, type: e }], type: f }], type: f }, { error: "DualStack is enabled but this partition does not support DualStack", type: d }], type: f }, { rules: [{ endpoint: { url: "https://bedrock.{Region}.{PartitionResult#dnsSuffix}", properties: m, headers: m }, type: e }], type: f }], type: f }], type: f }, { error: "Invalid Configuration: Missing Region", type: d }], type: f }] }; +exports.ruleSet = _data; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/index.js new file mode 100644 index 00000000..543c5f12 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/index.js @@ -0,0 +1,8222 @@ +'use strict'; + +var middlewareHostHeader = require('@aws-sdk/middleware-host-header'); +var middlewareLogger = require('@aws-sdk/middleware-logger'); +var middlewareRecursionDetection = require('@aws-sdk/middleware-recursion-detection'); +var middlewareUserAgent = require('@aws-sdk/middleware-user-agent'); +var configResolver = require('@smithy/config-resolver'); +var core = require('@smithy/core'); +var schema = require('@smithy/core/schema'); +var middlewareContentLength = require('@smithy/middleware-content-length'); +var middlewareEndpoint = require('@smithy/middleware-endpoint'); +var middlewareRetry = require('@smithy/middleware-retry'); +var smithyClient = require('@smithy/smithy-client'); +var httpAuthSchemeProvider = require('./auth/httpAuthSchemeProvider'); +var runtimeConfig = require('./runtimeConfig'); +var regionConfigResolver = require('@aws-sdk/region-config-resolver'); +var protocolHttp = require('@smithy/protocol-http'); + +const resolveClientEndpointParameters = (options) => { + return Object.assign(options, { + useDualstackEndpoint: options.useDualstackEndpoint ?? false, + useFipsEndpoint: options.useFipsEndpoint ?? false, + defaultSigningName: "bedrock", + }); +}; +const commonParams = { + UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, + Endpoint: { type: "builtInParams", name: "endpoint" }, + Region: { type: "builtInParams", name: "region" }, + UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, +}; + +const getHttpAuthExtensionConfiguration = (runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + let _token = runtimeConfig.token; + return { + setHttpAuthScheme(httpAuthScheme) { + const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } + else { + _httpAuthSchemes.splice(index, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; + }, + setToken(token) { + _token = token; + }, + token() { + return _token; + }, + }; +}; +const resolveHttpAuthRuntimeConfig = (config) => { + return { + httpAuthSchemes: config.httpAuthSchemes(), + httpAuthSchemeProvider: config.httpAuthSchemeProvider(), + credentials: config.credentials(), + token: config.token(), + }; +}; + +const resolveRuntimeExtensions = (runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign(regionConfigResolver.getAwsRegionExtensionConfiguration(runtimeConfig), smithyClient.getDefaultExtensionConfiguration(runtimeConfig), protocolHttp.getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig)); + extensions.forEach((extension) => extension.configure(extensionConfiguration)); + return Object.assign(runtimeConfig, regionConfigResolver.resolveAwsRegionExtensionConfiguration(extensionConfiguration), smithyClient.resolveDefaultRuntimeConfig(extensionConfiguration), protocolHttp.resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration)); +}; + +class BedrockClient extends smithyClient.Client { + config; + constructor(...[configuration]) { + const _config_0 = runtimeConfig.getRuntimeConfig(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = resolveClientEndpointParameters(_config_0); + const _config_2 = middlewareUserAgent.resolveUserAgentConfig(_config_1); + const _config_3 = middlewareRetry.resolveRetryConfig(_config_2); + const _config_4 = configResolver.resolveRegionConfig(_config_3); + const _config_5 = middlewareHostHeader.resolveHostHeaderConfig(_config_4); + const _config_6 = middlewareEndpoint.resolveEndpointConfig(_config_5); + const _config_7 = httpAuthSchemeProvider.resolveHttpAuthSchemeConfig(_config_6); + const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); + this.config = _config_8; + this.middlewareStack.use(schema.getSchemaSerdePlugin(this.config)); + this.middlewareStack.use(middlewareUserAgent.getUserAgentPlugin(this.config)); + this.middlewareStack.use(middlewareRetry.getRetryPlugin(this.config)); + this.middlewareStack.use(middlewareContentLength.getContentLengthPlugin(this.config)); + this.middlewareStack.use(middlewareHostHeader.getHostHeaderPlugin(this.config)); + this.middlewareStack.use(middlewareLogger.getLoggerPlugin(this.config)); + this.middlewareStack.use(middlewareRecursionDetection.getRecursionDetectionPlugin(this.config)); + this.middlewareStack.use(core.getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { + httpAuthSchemeParametersProvider: httpAuthSchemeProvider.defaultBedrockHttpAuthSchemeParametersProvider, + identityProviderConfigProvider: async (config) => new core.DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config.credentials, + "smithy.api#httpBearerAuth": config.token, + }), + })); + this.middlewareStack.use(core.getHttpSigningPlugin(this.config)); + } + destroy() { + super.destroy(); + } +} + +let BedrockServiceException$1 = class BedrockServiceException extends smithyClient.ServiceException { + constructor(options) { + super(options); + Object.setPrototypeOf(this, BedrockServiceException.prototype); + } +}; + +let AccessDeniedException$1 = class AccessDeniedException extends BedrockServiceException$1 { + name = "AccessDeniedException"; + $fault = "client"; + constructor(opts) { + super({ + name: "AccessDeniedException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, AccessDeniedException.prototype); + } +}; +let InternalServerException$1 = class InternalServerException extends BedrockServiceException$1 { + name = "InternalServerException"; + $fault = "server"; + constructor(opts) { + super({ + name: "InternalServerException", + $fault: "server", + ...opts, + }); + Object.setPrototypeOf(this, InternalServerException.prototype); + } +}; +let ResourceNotFoundException$1 = class ResourceNotFoundException extends BedrockServiceException$1 { + name = "ResourceNotFoundException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ResourceNotFoundException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ResourceNotFoundException.prototype); + } +}; +let ThrottlingException$1 = class ThrottlingException extends BedrockServiceException$1 { + name = "ThrottlingException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ThrottlingException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ThrottlingException.prototype); + } +}; +let ValidationException$1 = class ValidationException extends BedrockServiceException$1 { + name = "ValidationException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ValidationException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ValidationException.prototype); + } +}; +let ConflictException$1 = class ConflictException extends BedrockServiceException$1 { + name = "ConflictException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ConflictException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ConflictException.prototype); + } +}; +let ServiceQuotaExceededException$1 = class ServiceQuotaExceededException extends BedrockServiceException$1 { + name = "ServiceQuotaExceededException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ServiceQuotaExceededException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ServiceQuotaExceededException.prototype); + } +}; +let TooManyTagsException$1 = class TooManyTagsException extends BedrockServiceException$1 { + name = "TooManyTagsException"; + $fault = "client"; + resourceName; + constructor(opts) { + super({ + name: "TooManyTagsException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, TooManyTagsException.prototype); + this.resourceName = opts.resourceName; + } +}; +let ResourceInUseException$1 = class ResourceInUseException extends BedrockServiceException$1 { + name = "ResourceInUseException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ResourceInUseException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ResourceInUseException.prototype); + } +}; +let ServiceUnavailableException$1 = class ServiceUnavailableException extends BedrockServiceException$1 { + name = "ServiceUnavailableException"; + $fault = "server"; + constructor(opts) { + super({ + name: "ServiceUnavailableException", + $fault: "server", + ...opts, + }); + Object.setPrototypeOf(this, ServiceUnavailableException.prototype); + } +}; + +const _AA = "AgreementAvailability"; +const _ADE = "AccessDeniedException"; +const _AEC = "AutomatedEvaluationConfig"; +const _AECM = "AutomatedEvaluationCustomMetrics"; +const _AECMC = "AutomatedEvaluationCustomMetricConfig"; +const _AECMS = "AutomatedEvaluationCustomMetricSource"; +const _ARCDSL = "AutomatedReasoningCheckDifferenceScenarioList"; +const _ARCF = "AutomatedReasoningCheckFinding"; +const _ARCFL = "AutomatedReasoningCheckFindingList"; +const _ARCIF = "AutomatedReasoningCheckImpossibleFinding"; +const _ARCIFu = "AutomatedReasoningCheckInvalidFinding"; +const _ARCITR = "AutomatedReasoningCheckInputTextReference"; +const _ARCITRL = "AutomatedReasoningCheckInputTextReferenceList"; +const _ARCLW = "AutomatedReasoningCheckLogicWarning"; +const _ARCNTF = "AutomatedReasoningCheckNoTranslationsFinding"; +const _ARCR = "AutomatedReasoningCheckRule"; +const _ARCRL = "AutomatedReasoningCheckRuleList"; +const _ARCS = "AutomatedReasoningCheckScenario"; +const _ARCSF = "AutomatedReasoningCheckSatisfiableFinding"; +const _ARCT = "AutomatedReasoningCheckTranslation"; +const _ARCTAF = "AutomatedReasoningCheckTranslationAmbiguousFinding"; +const _ARCTCF = "AutomatedReasoningCheckTooComplexFinding"; +const _ARCTL = "AutomatedReasoningCheckTranslationList"; +const _ARCTO = "AutomatedReasoningCheckTranslationOption"; +const _ARCTOL = "AutomatedReasoningCheckTranslationOptionList"; +const _ARCVF = "AutomatedReasoningCheckValidFinding"; +const _ARLS = "AutomatedReasoningLogicStatement"; +const _ARLSC = "AutomatedReasoningLogicStatementContent"; +const _ARLSL = "AutomatedReasoningLogicStatementList"; +const _ARNLSC = "AutomatedReasoningNaturalLanguageStatementContent"; +const _ARPA = "AutomatedReasoningPolicyAnnotation"; +const _ARPAFNL = "AutomatedReasoningPolicyAnnotationFeedbackNaturalLanguage"; +const _ARPAIC = "AutomatedReasoningPolicyAnnotationIngestContent"; +const _ARPAL = "AutomatedReasoningPolicyAnnotationList"; +const _ARPARA = "AutomatedReasoningPolicyAddRuleAnnotation"; +const _ARPARFNLA = "AutomatedReasoningPolicyAddRuleFromNaturalLanguageAnnotation"; +const _ARPARM = "AutomatedReasoningPolicyAddRuleMutation"; +const _ARPARNL = "AutomatedReasoningPolicyAnnotationRuleNaturalLanguage"; +const _ARPATA = "AutomatedReasoningPolicyAddTypeAnnotation"; +const _ARPATM = "AutomatedReasoningPolicyAddTypeMutation"; +const _ARPATV = "AutomatedReasoningPolicyAddTypeValue"; +const _ARPAVA = "AutomatedReasoningPolicyAddVariableAnnotation"; +const _ARPAVM = "AutomatedReasoningPolicyAddVariableMutation"; +const _ARPBDB = "AutomatedReasoningPolicyBuildDocumentBlob"; +const _ARPBDD = "AutomatedReasoningPolicyBuildDocumentDescription"; +const _ARPBDN = "AutomatedReasoningPolicyBuildDocumentName"; +const _ARPBL = "AutomatedReasoningPolicyBuildLog"; +const _ARPBLE = "AutomatedReasoningPolicyBuildLogEntry"; +const _ARPBLEL = "AutomatedReasoningPolicyBuildLogEntryList"; +const _ARPBRA = "AutomatedReasoningPolicyBuildResultAssets"; +const _ARPBS = "AutomatedReasoningPolicyBuildStep"; +const _ARPBSC = "AutomatedReasoningPolicyBuildStepContext"; +const _ARPBSL = "AutomatedReasoningPolicyBuildStepList"; +const _ARPBSM = "AutomatedReasoningPolicyBuildStepMessage"; +const _ARPBSML = "AutomatedReasoningPolicyBuildStepMessageList"; +const _ARPBWD = "AutomatedReasoningPolicyBuildWorkflowDocument"; +const _ARPBWDL = "AutomatedReasoningPolicyBuildWorkflowDocumentList"; +const _ARPBWRC = "AutomatedReasoningPolicyBuildWorkflowRepairContent"; +const _ARPBWS = "AutomatedReasoningPolicyBuildWorkflowSource"; +const _ARPBWSu = "AutomatedReasoningPolicyBuildWorkflowSummary"; +const _ARPBWSut = "AutomatedReasoningPolicyBuildWorkflowSummaries"; +const _ARPD = "AutomatedReasoningPolicyDescription"; +const _ARPDE = "AutomatedReasoningPolicyDefinitionElement"; +const _ARPDQR = "AutomatedReasoningPolicyDefinitionQualityReport"; +const _ARPDR = "AutomatedReasoningPolicyDefinitionRule"; +const _ARPDRA = "AutomatedReasoningPolicyDeleteRuleAnnotation"; +const _ARPDRAE = "AutomatedReasoningPolicyDefinitionRuleAlternateExpression"; +const _ARPDRE = "AutomatedReasoningPolicyDefinitionRuleExpression"; +const _ARPDRL = "AutomatedReasoningPolicyDefinitionRuleList"; +const _ARPDRM = "AutomatedReasoningPolicyDeleteRuleMutation"; +const _ARPDRS = "AutomatedReasoningPolicyDisjointRuleSet"; +const _ARPDRSL = "AutomatedReasoningPolicyDisjointRuleSetList"; +const _ARPDT = "AutomatedReasoningPolicyDefinitionType"; +const _ARPDTA = "AutomatedReasoningPolicyDeleteTypeAnnotation"; +const _ARPDTD = "AutomatedReasoningPolicyDefinitionTypeDescription"; +const _ARPDTL = "AutomatedReasoningPolicyDefinitionTypeList"; +const _ARPDTM = "AutomatedReasoningPolicyDeleteTypeMutation"; +const _ARPDTN = "AutomatedReasoningPolicyDefinitionTypeName"; +const _ARPDTNL = "AutomatedReasoningPolicyDefinitionTypeNameList"; +const _ARPDTV = "AutomatedReasoningPolicyDefinitionTypeValue"; +const _ARPDTVD = "AutomatedReasoningPolicyDefinitionTypeValueDescription"; +const _ARPDTVL = "AutomatedReasoningPolicyDefinitionTypeValueList"; +const _ARPDTVP = "AutomatedReasoningPolicyDefinitionTypeValuePair"; +const _ARPDTVPL = "AutomatedReasoningPolicyDefinitionTypeValuePairList"; +const _ARPDTVu = "AutomatedReasoningPolicyDeleteTypeValue"; +const _ARPDV = "AutomatedReasoningPolicyDefinitionVariable"; +const _ARPDVA = "AutomatedReasoningPolicyDeleteVariableAnnotation"; +const _ARPDVD = "AutomatedReasoningPolicyDefinitionVariableDescription"; +const _ARPDVL = "AutomatedReasoningPolicyDefinitionVariableList"; +const _ARPDVM = "AutomatedReasoningPolicyDeleteVariableMutation"; +const _ARPDVN = "AutomatedReasoningPolicyDefinitionVariableName"; +const _ARPDVNL = "AutomatedReasoningPolicyDefinitionVariableNameList"; +const _ARPDu = "AutomatedReasoningPolicyDefinition"; +const _ARPGTC = "AutomatedReasoningPolicyGeneratedTestCase"; +const _ARPGTCL = "AutomatedReasoningPolicyGeneratedTestCaseList"; +const _ARPGTCu = "AutomatedReasoningPolicyGeneratedTestCases"; +const _ARPICA = "AutomatedReasoningPolicyIngestContentAnnotation"; +const _ARPM = "AutomatedReasoningPolicyMutation"; +const _ARPN = "AutomatedReasoningPolicyName"; +const _ARPP = "AutomatedReasoningPolicyPlanning"; +const _ARPS = "AutomatedReasoningPolicyScenario"; +const _ARPSAE = "AutomatedReasoningPolicyScenarioAlternateExpression"; +const _ARPSE = "AutomatedReasoningPolicyScenarioExpression"; +const _ARPSu = "AutomatedReasoningPolicySummary"; +const _ARPSut = "AutomatedReasoningPolicySummaries"; +const _ARPTC = "AutomatedReasoningPolicyTestCase"; +const _ARPTCL = "AutomatedReasoningPolicyTestCaseList"; +const _ARPTGC = "AutomatedReasoningPolicyTestGuardContent"; +const _ARPTL = "AutomatedReasoningPolicyTestList"; +const _ARPTQC = "AutomatedReasoningPolicyTestQueryContent"; +const _ARPTR = "AutomatedReasoningPolicyTestResult"; +const _ARPTVA = "AutomatedReasoningPolicyTypeValueAnnotation"; +const _ARPTVAL = "AutomatedReasoningPolicyTypeValueAnnotationList"; +const _ARPUFRFA = "AutomatedReasoningPolicyUpdateFromRuleFeedbackAnnotation"; +const _ARPUFSFA = "AutomatedReasoningPolicyUpdateFromScenarioFeedbackAnnotation"; +const _ARPURA = "AutomatedReasoningPolicyUpdateRuleAnnotation"; +const _ARPURM = "AutomatedReasoningPolicyUpdateRuleMutation"; +const _ARPUTA = "AutomatedReasoningPolicyUpdateTypeAnnotation"; +const _ARPUTM = "AutomatedReasoningPolicyUpdateTypeMutation"; +const _ARPUTV = "AutomatedReasoningPolicyUpdateTypeValue"; +const _ARPUVA = "AutomatedReasoningPolicyUpdateVariableAnnotation"; +const _ARPUVM = "AutomatedReasoningPolicyUpdateVariableMutation"; +const _ARPWTC = "AutomatedReasoningPolicyWorkflowTypeContent"; +const _BCB = "ByteContentBlob"; +const _BCD = "ByteContentDoc"; +const _BDEJ = "BatchDeleteEvaluationJob"; +const _BDEJE = "BatchDeleteEvaluationJobError"; +const _BDEJEa = "BatchDeleteEvaluationJobErrors"; +const _BDEJI = "BatchDeleteEvaluationJobItem"; +const _BDEJIa = "BatchDeleteEvaluationJobItems"; +const _BDEJR = "BatchDeleteEvaluationJobRequest"; +const _BDEJRa = "BatchDeleteEvaluationJobResponse"; +const _BEM = "BedrockEvaluatorModel"; +const _BEMe = "BedrockEvaluatorModels"; +const _CARP = "CreateAutomatedReasoningPolicy"; +const _CARPBW = "CancelAutomatedReasoningPolicyBuildWorkflow"; +const _CARPBWR = "CancelAutomatedReasoningPolicyBuildWorkflowRequest"; +const _CARPBWRa = "CancelAutomatedReasoningPolicyBuildWorkflowResponse"; +const _CARPR = "CreateAutomatedReasoningPolicyRequest"; +const _CARPRr = "CreateAutomatedReasoningPolicyResponse"; +const _CARPTC = "CreateAutomatedReasoningPolicyTestCase"; +const _CARPTCR = "CreateAutomatedReasoningPolicyTestCaseRequest"; +const _CARPTCRr = "CreateAutomatedReasoningPolicyTestCaseResponse"; +const _CARPV = "CreateAutomatedReasoningPolicyVersion"; +const _CARPVR = "CreateAutomatedReasoningPolicyVersionRequest"; +const _CARPVRr = "CreateAutomatedReasoningPolicyVersionResponse"; +const _CC = "CustomizationConfig"; +const _CCM = "CreateCustomModel"; +const _CCMD = "CreateCustomModelDeployment"; +const _CCMDR = "CreateCustomModelDeploymentRequest"; +const _CCMDRr = "CreateCustomModelDeploymentResponse"; +const _CCMR = "CreateCustomModelRequest"; +const _CCMRr = "CreateCustomModelResponse"; +const _CE = "ConflictException"; +const _CEJ = "CreateEvaluationJob"; +const _CEJR = "CreateEvaluationJobRequest"; +const _CEJRr = "CreateEvaluationJobResponse"; +const _CFMA = "CreateFoundationModelAgreement"; +const _CFMAR = "CreateFoundationModelAgreementRequest"; +const _CFMARr = "CreateFoundationModelAgreementResponse"; +const _CG = "CreateGuardrail"; +const _CGR = "CreateGuardrailRequest"; +const _CGRr = "CreateGuardrailResponse"; +const _CGV = "CreateGuardrailVersion"; +const _CGVR = "CreateGuardrailVersionRequest"; +const _CGVRr = "CreateGuardrailVersionResponse"; +const _CIP = "CreateInferenceProfile"; +const _CIPR = "CreateInferenceProfileRequest"; +const _CIPRr = "CreateInferenceProfileResponse"; +const _CMBEM = "CustomMetricBedrockEvaluatorModel"; +const _CMBEMu = "CustomMetricBedrockEvaluatorModels"; +const _CMCJ = "CreateModelCopyJob"; +const _CMCJR = "CreateModelCopyJobRequest"; +const _CMCJRr = "CreateModelCopyJobResponse"; +const _CMCJRre = "CreateModelCustomizationJobRequest"; +const _CMCJRrea = "CreateModelCustomizationJobResponse"; +const _CMCJr = "CreateModelCustomizationJob"; +const _CMD = "CustomMetricDefinition"; +const _CMDS = "CustomModelDeploymentSummary"; +const _CMDSL = "CustomModelDeploymentSummaryList"; +const _CMEMC = "CustomMetricEvaluatorModelConfig"; +const _CMIJ = "CreateModelImportJob"; +const _CMIJR = "CreateModelImportJobRequest"; +const _CMIJRr = "CreateModelImportJobResponse"; +const _CMIJRre = "CreateModelInvocationJobRequest"; +const _CMIJRrea = "CreateModelInvocationJobResponse"; +const _CMIJr = "CreateModelInvocationJob"; +const _CMME = "CreateMarketplaceModelEndpoint"; +const _CMMER = "CreateMarketplaceModelEndpointRequest"; +const _CMMERr = "CreateMarketplaceModelEndpointResponse"; +const _CMS = "CustomModelSummary"; +const _CMSL = "CustomModelSummaryList"; +const _CMU = "CustomModelUnits"; +const _CPMT = "CreateProvisionedModelThroughput"; +const _CPMTR = "CreateProvisionedModelThroughputRequest"; +const _CPMTRr = "CreateProvisionedModelThroughputResponse"; +const _CPR = "CreatePromptRouter"; +const _CPRR = "CreatePromptRouterRequest"; +const _CPRRr = "CreatePromptRouterResponse"; +const _CWC = "CloudWatchConfig"; +const _DARP = "DeleteAutomatedReasoningPolicy"; +const _DARPBW = "DeleteAutomatedReasoningPolicyBuildWorkflow"; +const _DARPBWR = "DeleteAutomatedReasoningPolicyBuildWorkflowRequest"; +const _DARPBWRe = "DeleteAutomatedReasoningPolicyBuildWorkflowResponse"; +const _DARPR = "DeleteAutomatedReasoningPolicyRequest"; +const _DARPRe = "DeleteAutomatedReasoningPolicyResponse"; +const _DARPTC = "DeleteAutomatedReasoningPolicyTestCase"; +const _DARPTCR = "DeleteAutomatedReasoningPolicyTestCaseRequest"; +const _DARPTCRe = "DeleteAutomatedReasoningPolicyTestCaseResponse"; +const _DC = "DistillationConfig"; +const _DCM = "DeleteCustomModel"; +const _DCMD = "DeleteCustomModelDeployment"; +const _DCMDR = "DeleteCustomModelDeploymentRequest"; +const _DCMDRe = "DeleteCustomModelDeploymentResponse"; +const _DCMR = "DeleteCustomModelRequest"; +const _DCMRe = "DeleteCustomModelResponse"; +const _DFMA = "DeleteFoundationModelAgreement"; +const _DFMAR = "DeleteFoundationModelAgreementRequest"; +const _DFMARe = "DeleteFoundationModelAgreementResponse"; +const _DG = "DeleteGuardrail"; +const _DGR = "DeleteGuardrailRequest"; +const _DGRe = "DeleteGuardrailResponse"; +const _DIM = "DeleteImportedModel"; +const _DIMR = "DeleteImportedModelRequest"; +const _DIMRe = "DeleteImportedModelResponse"; +const _DIP = "DeleteInferenceProfile"; +const _DIPR = "DeleteInferenceProfileRequest"; +const _DIPRe = "DeleteInferenceProfileResponse"; +const _DMILC = "DeleteModelInvocationLoggingConfiguration"; +const _DMILCR = "DeleteModelInvocationLoggingConfigurationRequest"; +const _DMILCRe = "DeleteModelInvocationLoggingConfigurationResponse"; +const _DMME = "DeleteMarketplaceModelEndpoint"; +const _DMMER = "DeleteMarketplaceModelEndpointRequest"; +const _DMMERe = "DeleteMarketplaceModelEndpointResponse"; +const _DMMERer = "DeregisterMarketplaceModelEndpointRequest"; +const _DMMERere = "DeregisterMarketplaceModelEndpointResponse"; +const _DMMEe = "DeregisterMarketplaceModelEndpoint"; +const _DPD = "DataProcessingDetails"; +const _DPMT = "DeleteProvisionedModelThroughput"; +const _DPMTR = "DeleteProvisionedModelThroughputRequest"; +const _DPMTRe = "DeleteProvisionedModelThroughputResponse"; +const _DPR = "DimensionalPriceRate"; +const _DPRR = "DeletePromptRouterRequest"; +const _DPRRe = "DeletePromptRouterResponse"; +const _DPRe = "DeletePromptRouter"; +const _EARPV = "ExportAutomatedReasoningPolicyVersion"; +const _EARPVR = "ExportAutomatedReasoningPolicyVersionRequest"; +const _EARPVRx = "ExportAutomatedReasoningPolicyVersionResponse"; +const _EBM = "EvaluationBedrockModel"; +const _EC = "EndpointConfig"; +const _ECv = "EvaluationConfig"; +const _ED = "EvaluationDataset"; +const _EDL = "EvaluationDatasetLocation"; +const _EDMC = "EvaluationDatasetMetricConfig"; +const _EDMCv = "EvaluationDatasetMetricConfigs"; +const _EDN = "EvaluationDatasetName"; +const _EIC = "EvaluationInferenceConfig"; +const _EICS = "EvaluationInferenceConfigSummary"; +const _EJD = "EvaluationJobDescription"; +const _EJI = "EvaluationJobIdentifier"; +const _EJIv = "EvaluationJobIdentifiers"; +const _EMC = "EvaluationModelConfigs"; +const _EMCS = "EvaluationModelConfigSummary"; +const _EMCv = "EvaluationModelConfig"; +const _EMCva = "EvaluatorModelConfig"; +const _EMD = "EvaluationMetricDescription"; +const _EMIP = "EvaluationModelInferenceParams"; +const _EMN = "EvaluationMetricName"; +const _EMNv = "EvaluationMetricNames"; +const _EODC = "EvaluationOutputDataConfig"; +const _EPIS = "EvaluationPrecomputedInferenceSource"; +const _EPRAGSC = "EvaluationPrecomputedRetrieveAndGenerateSourceConfig"; +const _EPRSC = "EvaluationPrecomputedRetrieveSourceConfig"; +const _EPRSCv = "EvaluationPrecomputedRagSourceConfig"; +const _ERCS = "EvaluationRagConfigSummary"; +const _ES = "EvaluationSummary"; +const _ESGC = "ExternalSourcesGenerationConfiguration"; +const _ESRAGC = "ExternalSourcesRetrieveAndGenerateConfiguration"; +const _ESv = "EvaluationSummaries"; +const _ESx = "ExternalSource"; +const _ESxt = "ExternalSources"; +const _FA = "FilterAttribute"; +const _FFR = "FieldForReranking"; +const _FFRi = "FieldsForReranking"; +const _FMD = "FoundationModelDetails"; +const _FML = "FoundationModelLifecycle"; +const _FMS = "FoundationModelSummary"; +const _FMSL = "FoundationModelSummaryList"; +const _GARP = "GuardrailAutomatedReasoningPolicy"; +const _GARPA = "GetAutomatedReasoningPolicyAnnotations"; +const _GARPAR = "GetAutomatedReasoningPolicyAnnotationsRequest"; +const _GARPARe = "GetAutomatedReasoningPolicyAnnotationsResponse"; +const _GARPBW = "GetAutomatedReasoningPolicyBuildWorkflow"; +const _GARPBWR = "GetAutomatedReasoningPolicyBuildWorkflowRequest"; +const _GARPBWRA = "GetAutomatedReasoningPolicyBuildWorkflowResultAssets"; +const _GARPBWRAR = "GetAutomatedReasoningPolicyBuildWorkflowResultAssetsRequest"; +const _GARPBWRARe = "GetAutomatedReasoningPolicyBuildWorkflowResultAssetsResponse"; +const _GARPBWRe = "GetAutomatedReasoningPolicyBuildWorkflowResponse"; +const _GARPC = "GuardrailAutomatedReasoningPolicyConfig"; +const _GARPNS = "GetAutomatedReasoningPolicyNextScenario"; +const _GARPNSR = "GetAutomatedReasoningPolicyNextScenarioRequest"; +const _GARPNSRe = "GetAutomatedReasoningPolicyNextScenarioResponse"; +const _GARPR = "GetAutomatedReasoningPolicyRequest"; +const _GARPRe = "GetAutomatedReasoningPolicyResponse"; +const _GARPTC = "GetAutomatedReasoningPolicyTestCase"; +const _GARPTCR = "GetAutomatedReasoningPolicyTestCaseRequest"; +const _GARPTCRe = "GetAutomatedReasoningPolicyTestCaseResponse"; +const _GARPTR = "GetAutomatedReasoningPolicyTestResult"; +const _GARPTRR = "GetAutomatedReasoningPolicyTestResultRequest"; +const _GARPTRRe = "GetAutomatedReasoningPolicyTestResultResponse"; +const _GARPe = "GetAutomatedReasoningPolicy"; +const _GBM = "GuardrailBlockedMessaging"; +const _GC = "GenerationConfiguration"; +const _GCF = "GuardrailContentFilter"; +const _GCFA = "GuardrailContentFilterAction"; +const _GCFC = "GuardrailContentFilterConfig"; +const _GCFCu = "GuardrailContentFiltersConfig"; +const _GCFT = "GuardrailContentFiltersTier"; +const _GCFTC = "GuardrailContentFiltersTierConfig"; +const _GCFTN = "GuardrailContentFiltersTierName"; +const _GCFu = "GuardrailContentFilters"; +const _GCGA = "GuardrailContextualGroundingAction"; +const _GCGF = "GuardrailContextualGroundingFilter"; +const _GCGFC = "GuardrailContextualGroundingFilterConfig"; +const _GCGFCu = "GuardrailContextualGroundingFiltersConfig"; +const _GCGFu = "GuardrailContextualGroundingFilters"; +const _GCGP = "GuardrailContextualGroundingPolicy"; +const _GCGPC = "GuardrailContextualGroundingPolicyConfig"; +const _GCM = "GetCustomModel"; +const _GCMD = "GetCustomModelDeployment"; +const _GCMDR = "GetCustomModelDeploymentRequest"; +const _GCMDRe = "GetCustomModelDeploymentResponse"; +const _GCMR = "GetCustomModelRequest"; +const _GCMRe = "GetCustomModelResponse"; +const _GCP = "GuardrailContentPolicy"; +const _GCPC = "GuardrailContentPolicyConfig"; +const _GCRC = "GuardrailCrossRegionConfig"; +const _GCRD = "GuardrailCrossRegionDetails"; +const _GCu = "GuardrailConfiguration"; +const _GD = "GuardrailDescription"; +const _GEJ = "GetEvaluationJob"; +const _GEJR = "GetEvaluationJobRequest"; +const _GEJRe = "GetEvaluationJobResponse"; +const _GFM = "GetFoundationModel"; +const _GFMA = "GetFoundationModelAvailability"; +const _GFMAR = "GetFoundationModelAvailabilityRequest"; +const _GFMARe = "GetFoundationModelAvailabilityResponse"; +const _GFMR = "GetFoundationModelRequest"; +const _GFMRe = "GetFoundationModelResponse"; +const _GFR = "GuardrailFailureRecommendation"; +const _GFRu = "GuardrailFailureRecommendations"; +const _GG = "GetGuardrail"; +const _GGR = "GetGuardrailRequest"; +const _GGRe = "GetGuardrailResponse"; +const _GIM = "GetImportedModel"; +const _GIMR = "GetImportedModelRequest"; +const _GIMRe = "GetImportedModelResponse"; +const _GIP = "GetInferenceProfile"; +const _GIPR = "GetInferenceProfileRequest"; +const _GIPRe = "GetInferenceProfileResponse"; +const _GM = "GuardrailModality"; +const _GMCJ = "GetModelCopyJob"; +const _GMCJR = "GetModelCopyJobRequest"; +const _GMCJRe = "GetModelCopyJobResponse"; +const _GMCJRet = "GetModelCustomizationJobRequest"; +const _GMCJReto = "GetModelCustomizationJobResponse"; +const _GMCJe = "GetModelCustomizationJob"; +const _GMIJ = "GetModelImportJob"; +const _GMIJR = "GetModelImportJobRequest"; +const _GMIJRe = "GetModelImportJobResponse"; +const _GMIJRet = "GetModelInvocationJobRequest"; +const _GMIJReto = "GetModelInvocationJobResponse"; +const _GMIJe = "GetModelInvocationJob"; +const _GMILC = "GetModelInvocationLoggingConfiguration"; +const _GMILCR = "GetModelInvocationLoggingConfigurationRequest"; +const _GMILCRe = "GetModelInvocationLoggingConfigurationResponse"; +const _GMME = "GetMarketplaceModelEndpoint"; +const _GMMER = "GetMarketplaceModelEndpointRequest"; +const _GMMERe = "GetMarketplaceModelEndpointResponse"; +const _GMW = "GuardrailManagedWords"; +const _GMWC = "GuardrailManagedWordsConfig"; +const _GMWL = "GuardrailManagedWordLists"; +const _GMWLC = "GuardrailManagedWordListsConfig"; +const _GMu = "GuardrailModalities"; +const _GN = "GuardrailName"; +const _GPE = "GuardrailPiiEntity"; +const _GPEC = "GuardrailPiiEntityConfig"; +const _GPECu = "GuardrailPiiEntitiesConfig"; +const _GPEu = "GuardrailPiiEntities"; +const _GPMT = "GetProvisionedModelThroughput"; +const _GPMTR = "GetProvisionedModelThroughputRequest"; +const _GPMTRe = "GetProvisionedModelThroughputResponse"; +const _GPR = "GetPromptRouter"; +const _GPRR = "GetPromptRouterRequest"; +const _GPRRe = "GetPromptRouterResponse"; +const _GR = "GuardrailRegex"; +const _GRC = "GuardrailRegexConfig"; +const _GRCu = "GuardrailRegexesConfig"; +const _GRu = "GuardrailRegexes"; +const _GS = "GuardrailSummary"; +const _GSIP = "GuardrailSensitiveInformationPolicy"; +const _GSIPC = "GuardrailSensitiveInformationPolicyConfig"; +const _GSR = "GuardrailStatusReason"; +const _GSRu = "GuardrailStatusReasons"; +const _GSu = "GuardrailSummaries"; +const _GT = "GuardrailTopic"; +const _GTA = "GuardrailTopicAction"; +const _GTC = "GuardrailTopicConfig"; +const _GTCu = "GuardrailTopicsConfig"; +const _GTD = "GuardrailTopicDefinition"; +const _GTE = "GuardrailTopicExample"; +const _GTEu = "GuardrailTopicExamples"; +const _GTN = "GuardrailTopicName"; +const _GTP = "GuardrailTopicPolicy"; +const _GTPC = "GuardrailTopicPolicyConfig"; +const _GTT = "GuardrailTopicsTier"; +const _GTTC = "GuardrailTopicsTierConfig"; +const _GTTN = "GuardrailTopicsTierName"; +const _GTu = "GuardrailTopics"; +const _GUCFMA = "GetUseCaseForModelAccess"; +const _GUCFMAR = "GetUseCaseForModelAccessRequest"; +const _GUCFMARe = "GetUseCaseForModelAccessResponse"; +const _GW = "GuardrailWord"; +const _GWA = "GuardrailWordAction"; +const _GWC = "GuardrailWordConfig"; +const _GWCu = "GuardrailWordsConfig"; +const _GWP = "GuardrailWordPolicy"; +const _GWPC = "GuardrailWordPolicyConfig"; +const _GWu = "GuardrailWords"; +const _HEC = "HumanEvaluationConfig"; +const _HECM = "HumanEvaluationCustomMetric"; +const _HECMu = "HumanEvaluationCustomMetrics"; +const _HTI = "HumanTaskInstructions"; +const _HWC = "HumanWorkflowConfig"; +const _I = "Identifier"; +const _IFC = "ImplicitFilterConfiguration"; +const _ILC = "InvocationLogsConfig"; +const _ILS = "InvocationLogSource"; +const _IMS = "ImportedModelSummary"; +const _IMSL = "ImportedModelSummaryList"; +const _IPD = "InferenceProfileDescription"; +const _IPM = "InferenceProfileModel"; +const _IPMS = "InferenceProfileModelSource"; +const _IPMn = "InferenceProfileModels"; +const _IPS = "InferenceProfileSummary"; +const _IPSn = "InferenceProfileSummaries"; +const _ISE = "InternalServerException"; +const _KBC = "KnowledgeBaseConfig"; +const _KBRAGC = "KnowledgeBaseRetrieveAndGenerateConfiguration"; +const _KBRC = "KnowledgeBaseRetrievalConfiguration"; +const _KBVSC = "KnowledgeBaseVectorSearchConfiguration"; +const _KIC = "KbInferenceConfig"; +const _LARP = "ListAutomatedReasoningPolicies"; +const _LARPBW = "ListAutomatedReasoningPolicyBuildWorkflows"; +const _LARPBWR = "ListAutomatedReasoningPolicyBuildWorkflowsRequest"; +const _LARPBWRi = "ListAutomatedReasoningPolicyBuildWorkflowsResponse"; +const _LARPR = "ListAutomatedReasoningPoliciesRequest"; +const _LARPRi = "ListAutomatedReasoningPoliciesResponse"; +const _LARPTC = "ListAutomatedReasoningPolicyTestCases"; +const _LARPTCR = "ListAutomatedReasoningPolicyTestCasesRequest"; +const _LARPTCRi = "ListAutomatedReasoningPolicyTestCasesResponse"; +const _LARPTR = "ListAutomatedReasoningPolicyTestResults"; +const _LARPTRR = "ListAutomatedReasoningPolicyTestResultsRequest"; +const _LARPTRRi = "ListAutomatedReasoningPolicyTestResultsResponse"; +const _LC = "LoggingConfig"; +const _LCM = "ListCustomModels"; +const _LCMD = "ListCustomModelDeployments"; +const _LCMDR = "ListCustomModelDeploymentsRequest"; +const _LCMDRi = "ListCustomModelDeploymentsResponse"; +const _LCMR = "ListCustomModelsRequest"; +const _LCMRi = "ListCustomModelsResponse"; +const _LEJ = "ListEvaluationJobs"; +const _LEJR = "ListEvaluationJobsRequest"; +const _LEJRi = "ListEvaluationJobsResponse"; +const _LFM = "ListFoundationModels"; +const _LFMAO = "ListFoundationModelAgreementOffers"; +const _LFMAOR = "ListFoundationModelAgreementOffersRequest"; +const _LFMAORi = "ListFoundationModelAgreementOffersResponse"; +const _LFMR = "ListFoundationModelsRequest"; +const _LFMRi = "ListFoundationModelsResponse"; +const _LG = "ListGuardrails"; +const _LGR = "ListGuardrailsRequest"; +const _LGRi = "ListGuardrailsResponse"; +const _LIM = "ListImportedModels"; +const _LIMR = "ListImportedModelsRequest"; +const _LIMRi = "ListImportedModelsResponse"; +const _LIP = "ListInferenceProfiles"; +const _LIPR = "ListInferenceProfilesRequest"; +const _LIPRi = "ListInferenceProfilesResponse"; +const _LMCJ = "ListModelCopyJobs"; +const _LMCJR = "ListModelCopyJobsRequest"; +const _LMCJRi = "ListModelCopyJobsResponse"; +const _LMCJRis = "ListModelCustomizationJobsRequest"; +const _LMCJRist = "ListModelCustomizationJobsResponse"; +const _LMCJi = "ListModelCustomizationJobs"; +const _LMIJ = "ListModelImportJobs"; +const _LMIJR = "ListModelImportJobsRequest"; +const _LMIJRi = "ListModelImportJobsResponse"; +const _LMIJRis = "ListModelInvocationJobsRequest"; +const _LMIJRist = "ListModelInvocationJobsResponse"; +const _LMIJi = "ListModelInvocationJobs"; +const _LMME = "ListMarketplaceModelEndpoints"; +const _LMMER = "ListMarketplaceModelEndpointsRequest"; +const _LMMERi = "ListMarketplaceModelEndpointsResponse"; +const _LPMT = "ListProvisionedModelThroughputs"; +const _LPMTR = "ListProvisionedModelThroughputsRequest"; +const _LPMTRi = "ListProvisionedModelThroughputsResponse"; +const _LPR = "ListPromptRouters"; +const _LPRR = "ListPromptRoutersRequest"; +const _LPRRi = "ListPromptRoutersResponse"; +const _LT = "LegalTerm"; +const _LTFR = "ListTagsForResource"; +const _LTFRR = "ListTagsForResourceRequest"; +const _LTFRRi = "ListTagsForResourceResponse"; +const _M = "Message"; +const _MAS = "MetadataAttributeSchema"; +const _MASL = "MetadataAttributeSchemaList"; +const _MCFR = "MetadataConfigurationForReranking"; +const _MCJS = "ModelCopyJobSummary"; +const _MCJSo = "ModelCustomizationJobSummary"; +const _MCJSod = "ModelCopyJobSummaries"; +const _MCJSode = "ModelCustomizationJobSummaries"; +const _MDS = "ModelDataSource"; +const _MIJIDC = "ModelInvocationJobInputDataConfig"; +const _MIJODC = "ModelInvocationJobOutputDataConfig"; +const _MIJS = "ModelImportJobSummary"; +const _MIJSIDC = "ModelInvocationJobS3InputDataConfig"; +const _MIJSODC = "ModelInvocationJobS3OutputDataConfig"; +const _MIJSo = "ModelInvocationJobSummary"; +const _MIJSod = "ModelImportJobSummaries"; +const _MIJSode = "ModelInvocationJobSummaries"; +const _MME = "MarketplaceModelEndpoint"; +const _MMES = "MarketplaceModelEndpointSummary"; +const _MMESa = "MarketplaceModelEndpointSummaries"; +const _MN = "MetricName"; +const _O = "Offer"; +const _OC = "OrchestrationConfiguration"; +const _ODC = "OutputDataConfig"; +const _Of = "Offers"; +const _PC = "PerformanceConfiguration"; +const _PMILC = "PutModelInvocationLoggingConfiguration"; +const _PMILCR = "PutModelInvocationLoggingConfigurationRequest"; +const _PMILCRu = "PutModelInvocationLoggingConfigurationResponse"; +const _PMS = "ProvisionedModelSummary"; +const _PMSr = "ProvisionedModelSummaries"; +const _PRD = "PromptRouterDescription"; +const _PRS = "PromptRouterSummary"; +const _PRSr = "PromptRouterSummaries"; +const _PRTM = "PromptRouterTargetModel"; +const _PRTMr = "PromptRouterTargetModels"; +const _PT = "PricingTerm"; +const _PTr = "PromptTemplate"; +const _PUCFMA = "PutUseCaseForModelAccess"; +const _PUCFMAR = "PutUseCaseForModelAccessRequest"; +const _PUCFMARu = "PutUseCaseForModelAccessResponse"; +const _QTC = "QueryTransformationConfiguration"; +const _RAGC = "RetrieveAndGenerateConfiguration"; +const _RAGCo = "RAGConfig"; +const _RC = "RetrieveConfig"; +const _RCa = "RagConfigs"; +const _RCat = "RateCard"; +const _RCo = "RoutingCriteria"; +const _RF = "RetrievalFilter"; +const _RFL = "RetrievalFilterList"; +const _RIUE = "ResourceInUseException"; +const _RMBF = "RequestMetadataBaseFilters"; +const _RMF = "RequestMetadataFilters"; +const _RMFL = "RequestMetadataFiltersList"; +const _RMM = "RequestMetadataMap"; +const _RMME = "RegisterMarketplaceModelEndpoint"; +const _RMMER = "RegisterMarketplaceModelEndpointRequest"; +const _RMMERe = "RegisterMarketplaceModelEndpointResponse"; +const _RMSMC = "RerankingMetadataSelectiveModeConfiguration"; +const _RNFE = "ResourceNotFoundException"; +const _RS = "RatingScale"; +const _RSI = "RatingScaleItem"; +const _RSIV = "RatingScaleItemValue"; +const _SARPBW = "StartAutomatedReasoningPolicyBuildWorkflow"; +const _SARPBWR = "StartAutomatedReasoningPolicyBuildWorkflowRequest"; +const _SARPBWRt = "StartAutomatedReasoningPolicyBuildWorkflowResponse"; +const _SARPTW = "StartAutomatedReasoningPolicyTestWorkflow"; +const _SARPTWR = "StartAutomatedReasoningPolicyTestWorkflowRequest"; +const _SARPTWRt = "StartAutomatedReasoningPolicyTestWorkflowResponse"; +const _SC = "S3Config"; +const _SD = "StatusDetails"; +const _SDS = "S3DataSource"; +const _SEJ = "StopEvaluationJob"; +const _SEJR = "StopEvaluationJobRequest"; +const _SEJRt = "StopEvaluationJobResponse"; +const _SMCJ = "StopModelCustomizationJob"; +const _SMCJR = "StopModelCustomizationJobRequest"; +const _SMCJRt = "StopModelCustomizationJobResponse"; +const _SME = "SageMakerEndpoint"; +const _SMIJ = "StopModelInvocationJob"; +const _SMIJR = "StopModelInvocationJobRequest"; +const _SMIJRt = "StopModelInvocationJobResponse"; +const _SOD = "S3ObjectDoc"; +const _SQEE = "ServiceQuotaExceededException"; +const _ST = "SupportTerm"; +const _SUE = "ServiceUnavailableException"; +const _T = "Tag"; +const _TD = "TermDetails"; +const _TDC = "TrainingDataConfig"; +const _TDr = "TrainingDetails"; +const _TE = "ThrottlingException"; +const _TIC = "TextInferenceConfig"; +const _TL = "TagList"; +const _TM = "TrainingMetrics"; +const _TMC = "TeacherModelConfig"; +const _TMTE = "TooManyTagsException"; +const _TPT = "TextPromptTemplate"; +const _TR = "TagResource"; +const _TRR = "TagResourceRequest"; +const _TRRa = "TagResourceResponse"; +const _UARP = "UpdateAutomatedReasoningPolicy"; +const _UARPA = "UpdateAutomatedReasoningPolicyAnnotations"; +const _UARPAR = "UpdateAutomatedReasoningPolicyAnnotationsRequest"; +const _UARPARp = "UpdateAutomatedReasoningPolicyAnnotationsResponse"; +const _UARPR = "UpdateAutomatedReasoningPolicyRequest"; +const _UARPRp = "UpdateAutomatedReasoningPolicyResponse"; +const _UARPTC = "UpdateAutomatedReasoningPolicyTestCase"; +const _UARPTCR = "UpdateAutomatedReasoningPolicyTestCaseRequest"; +const _UARPTCRp = "UpdateAutomatedReasoningPolicyTestCaseResponse"; +const _UG = "UpdateGuardrail"; +const _UGR = "UpdateGuardrailRequest"; +const _UGRp = "UpdateGuardrailResponse"; +const _UMME = "UpdateMarketplaceModelEndpoint"; +const _UMMER = "UpdateMarketplaceModelEndpointRequest"; +const _UMMERp = "UpdateMarketplaceModelEndpointResponse"; +const _UPMT = "UpdateProvisionedModelThroughput"; +const _UPMTR = "UpdateProvisionedModelThroughputRequest"; +const _UPMTRp = "UpdateProvisionedModelThroughputResponse"; +const _UR = "UntagResource"; +const _URR = "UntagResourceRequest"; +const _URRn = "UntagResourceResponse"; +const _V = "Validator"; +const _VC = "VpcConfig"; +const _VD = "ValidationDetails"; +const _VDC = "ValidationDataConfig"; +const _VE = "ValidationException"; +const _VM = "ValidatorMetric"; +const _VMa = "ValidationMetrics"; +const _VSBRC = "VectorSearchBedrockRerankingConfiguration"; +const _VSBRMC = "VectorSearchBedrockRerankingModelConfiguration"; +const _VSRC = "VectorSearchRerankingConfiguration"; +const _VT = "ValidityTerm"; +const _Va = "Validators"; +const _a = "annotation"; +const _aA = "agreementAvailability"; +const _aAn = "andAll"; +const _aD = "agreementDuration"; +const _aE = "alternateExpression"; +const _aEc = "acceptEula"; +const _aMRF = "additionalModelRequestFields"; +const _aR = "addRule"; +const _aRFNL = "addRuleFromNaturalLanguage"; +const _aRP = "automatedReasoningPolicy"; +const _aRPBWS = "automatedReasoningPolicyBuildWorkflowSummaries"; +const _aRPC = "automatedReasoningPolicyConfig"; +const _aRPS = "automatedReasoningPolicySummaries"; +const _aS = "authorizationStatus"; +const _aSH = "annotationSetHash"; +const _aT = "applicationType"; +const _aTE = "applicationTypeEquals"; +const _aTFR = "aggregatedTestFindingsResult"; +const _aTV = "addTypeValue"; +const _aTd = "addType"; +const _aTs = "assetType"; +const _aV = "addVariable"; +const _ac = "action"; +const _an = "annotations"; +const _ar = "arn"; +const _au = "automated"; +const _bC = "byteContent"; +const _bCT = "byCustomizationType"; +const _bEM = "bedrockEvaluatorModels"; +const _bIM = "blockedInputMessaging"; +const _bIT = "byInferenceType"; +const _bKBI = "bedrockKnowledgeBaseIdentifiers"; +const _bL = "buildLog"; +const _bM = "bedrockModel"; +const _bMA = "baseModelArn"; +const _bMAE = "baseModelArnEquals"; +const _bMI = "baseModelIdentifier"; +const _bMIe = "bedrockModelIdentifiers"; +const _bMN = "baseModelName"; +const _bN = "bucketName"; +const _bOM = "blockedOutputsMessaging"; +const _bOMy = "byOutputModality"; +const _bP = "byProvider"; +const _bRC = "bedrockRerankingConfiguration"; +const _bS = "buildSteps"; +const _bWA = "buildWorkflowAssets"; +const _bWI = "buildWorkflowId"; +const _bWT = "buildWorkflowType"; +const _c = "client"; +const _cA = "createdAt"; +const _cAr = "createdAfter"; +const _cB = "createdBefore"; +const _cC = "customizationConfig"; +const _cD = "commitmentDuration"; +const _cEKI = "customerEncryptionKeyId"; +const _cET = "commitmentExpirationTime"; +const _cF = "copyFrom"; +const _cFS = "claimsFalseScenario"; +const _cGP = "contextualGroundingPolicy"; +const _cGPC = "contextualGroundingPolicyConfig"; +const _cM = "customMetrics"; +const _cMA = "customModelArn"; +const _cMC = "customMetricConfig"; +const _cMD = "customMetricDefinition"; +const _cMDA = "customModelDeploymentArn"; +const _cMDI = "customModelDeploymentIdentifier"; +const _cMDN = "customModelDeploymentName"; +const _cMEMI = "customMetricsEvaluatorModelIdentifiers"; +const _cMKKI = "customModelKmsKeyId"; +const _cMN = "customModelName"; +const _cMT = "customModelTags"; +const _cMU = "customModelUnits"; +const _cMUPMC = "customModelUnitsPerModelCopy"; +const _cMUV = "customModelUnitsVersion"; +const _cP = "contentPolicy"; +const _cPC = "contentPolicyConfig"; +const _cR = "contradictingRules"; +const _cRC = "crossRegionConfig"; +const _cRD = "crossRegionDetails"; +const _cRT = "clientRequestToken"; +const _cRo = "conflictingRules"; +const _cS = "customizationsSupported"; +const _cT = "confidenceThreshold"; +const _cTA = "creationTimeAfter"; +const _cTB = "creationTimeBefore"; +const _cTS = "claimsTrueScenario"; +const _cTo = "contentType"; +const _cTr = "creationTime"; +const _cTu = "customizationType"; +const _cWC = "cloudWatchConfig"; +const _cl = "claims"; +const _co = "confidence"; +const _cod = "code"; +const _con = "context"; +const _cont = "content"; +const _d = "description"; +const _dC = "distillationConfig"; +const _dCT = "documentContentType"; +const _dD = "documentDescription"; +const _dH = "definitionHash"; +const _dL = "datasetLocation"; +const _dMA = "desiredModelArn"; +const _dMC = "datasetMetricConfigs"; +const _dMI = "desiredModelId"; +const _dMU = "desiredModelUnits"; +const _dN = "documentName"; +const _dPD = "dataProcessingDetails"; +const _dPMN = "desiredProvisionedModelName"; +const _dR = "deleteRule"; +const _dRS = "disjointRuleSets"; +const _dS = "differenceScenarios"; +const _dT = "deleteType"; +const _dTV = "deleteTypeValue"; +const _dV = "deleteVariable"; +const _da = "data"; +const _dat = "dataset"; +const _de = "definition"; +const _di = "dimension"; +const _do = "document"; +const _doc = "documents"; +const _e = "error"; +const _eA = "endpointArn"; +const _eAFR = "expectedAggregatedFindingsResult"; +const _eAn = "entitlementAvailability"; +const _eC = "evaluationConfig"; +const _eCn = "endpointConfig"; +const _eDDE = "embeddingDataDeliveryEnabled"; +const _eI = "endpointIdentifier"; +const _eJ = "evaluationJobs"; +const _eM = "errorMessage"; +const _eMC = "evaluatorModelConfig"; +const _eMI = "evaluatorModelIdentifiers"; +const _eN = "endpointName"; +const _eR = "expectedResult"; +const _eRx = "executionRole"; +const _eS = "endpointStatus"; +const _eSC = "externalSourcesConfiguration"; +const _eSM = "endpointStatusMessage"; +const _eT = "endTime"; +const _eTT = "evaluationTaskTypes"; +const _en = "entries"; +const _ena = "enabled"; +const _eq = "equals"; +const _er = "errors"; +const _ex = "expression"; +const _exa = "examples"; +const _f = "feedback"; +const _fC = "filtersConfig"; +const _fD = "formData"; +const _fDA = "flowDefinitionArn"; +const _fM = "fallbackModel"; +const _fMA = "foundationModelArn"; +const _fMAE = "foundationModelArnEquals"; +const _fMa = "failureMessage"; +const _fMai = "failureMessages"; +const _fN = "fieldName"; +const _fR = "failureRecommendations"; +const _fTE = "fieldsToExclude"; +const _fTI = "fieldsToInclude"; +const _fV = "floatValue"; +const _fi = "filters"; +const _fil = "filter"; +const _fo = "force"; +const _g = "guardrails"; +const _gA = "guardrailArn"; +const _gC = "guardContent"; +const _gCe = "generationConfiguration"; +const _gCu = "guardrailConfiguration"; +const _gI = "guardrailId"; +const _gIu = "guardrailIdentifier"; +const _gPA = "guardrailProfileArn"; +const _gPI = "guardrailProfileIdentifier"; +const _gPIu = "guardrailProfileId"; +const _gT = "greaterThan"; +const _gTC = "generatedTestCases"; +const _gTOE = "greaterThanOrEquals"; +const _gV = "guardrailVersion"; +const _h = "human"; +const _hE = "httpError"; +const _hH = "httpHeader"; +const _hP = "hyperParameters"; +const _hQ = "httpQuery"; +const _hWC = "humanWorkflowConfig"; +const _ht = "http"; +const _i = "id"; +const _iA = "inputAction"; +const _iC = "inferenceConfig"; +const _iCS = "inferenceConfigSummary"; +const _iCn = "ingestContent"; +const _iDC = "inputDataConfig"; +const _iDDE = "imageDataDeliveryEnabled"; +const _iE = "inputEnabled"; +const _iFC = "implicitFilterConfiguration"; +const _iIC = "initialInstanceCount"; +const _iJS = "invocationJobSummaries"; +const _iLC = "invocationLogsConfig"; +const _iLS = "invocationLogSource"; +const _iM = "inputModalities"; +const _iMA = "importedModelArn"; +const _iMKKA = "importedModelKmsKeyArn"; +const _iMKKI = "importedModelKmsKeyId"; +const _iMN = "importedModelName"; +const _iMT = "importedModelTags"; +const _iO = "isOwned"; +const _iP = "inferenceParams"; +const _iPA = "inferenceProfileArn"; +const _iPI = "inferenceProfileIdentifier"; +const _iPIn = "inferenceProfileId"; +const _iPN = "inferenceProfileName"; +const _iPS = "inferenceProfileSummaries"; +const _iS = "instructSupported"; +const _iSI = "inferenceSourceIdentifier"; +const _iSn = "inputStrength"; +const _iT = "instanceType"; +const _iTS = "inferenceTypesSupported"; +const _iTd = "idempotencyToken"; +const _id = "identifier"; +const _im = "impossible"; +const _in = "instructions"; +const _in_ = "in"; +const _inv = "invalid"; +const _jA = "jobArn"; +const _jD = "jobDescription"; +const _jET = "jobExpirationTime"; +const _jI = "jobIdentifier"; +const _jIo = "jobIdentifiers"; +const _jN = "jobName"; +const _jS = "jobStatus"; +const _jSo = "jobSummaries"; +const _jT = "jobTags"; +const _jTo = "jobType"; +const _k = "key"; +const _kBC = "knowledgeBaseConfiguration"; +const _kBCn = "knowledgeBaseConfig"; +const _kBI = "knowledgeBaseId"; +const _kBRC = "knowledgeBaseRetrievalConfiguration"; +const _kEK = "kmsEncryptionKey"; +const _kIC = "kbInferenceConfig"; +const _kKA = "kmsKeyArn"; +const _kKI = "kmsKeyId"; +const _kP = "keyPrefix"; +const _l = "logic"; +const _lC = "loggingConfig"; +const _lCi = "listContains"; +const _lDDSC = "largeDataDeliveryS3Config"; +const _lGN = "logGroupName"; +const _lMT = "lastModifiedTime"; +const _lT = "legalTerm"; +const _lTOE = "lessThanOrEquals"; +const _lTe = "lessThan"; +const _lUA = "lastUpdatedAt"; +const _lUASH = "lastUpdatedAnnotationSetHash"; +const _lUDH = "lastUpdatedDefinitionHash"; +const _lW = "logicWarning"; +const _la = "latency"; +const _m = "message"; +const _mA = "modelArn"; +const _mAE = "modelArnEquals"; +const _mAe = "metadataAttributes"; +const _mAo = "modelArchitecture"; +const _mC = "modelConfiguration"; +const _mCJS = "modelCopyJobSummaries"; +const _mCJSo = "modelCustomizationJobSummaries"; +const _mCS = "modelConfigSummary"; +const _mCe = "metadataConfiguration"; +const _mD = "modelDetails"; +const _mDN = "modelDeploymentName"; +const _mDS = "modelDataSource"; +const _mDSo = "modelDeploymentSummaries"; +const _mI = "modelIdentifier"; +const _mIJS = "modelImportJobSummaries"; +const _mIo = "modelId"; +const _mIod = "modelIdentifiers"; +const _mKKA = "modelKmsKeyArn"; +const _mKKI = "modelKmsKeyId"; +const _mL = "modelLifecycle"; +const _mME = "marketplaceModelEndpoint"; +const _mMEa = "marketplaceModelEndpoints"; +const _mN = "modelName"; +const _mNe = "metricNames"; +const _mR = "maxResults"; +const _mRLFI = "maxResponseLengthForInference"; +const _mS = "modelSource"; +const _mSC = "modelSourceConfig"; +const _mSE = "modelSourceEquals"; +const _mSI = "modelSourceIdentifier"; +const _mSo = "modelStatus"; +const _mSod = "modelSummaries"; +const _mT = "messageType"; +const _mTa = "maxTokens"; +const _mTo = "modelTags"; +const _mU = "modelUnits"; +const _mWL = "managedWordLists"; +const _mWLC = "managedWordListsConfig"; +const _me = "messages"; +const _mo = "models"; +const _mu = "mutation"; +const _n = "name"; +const _nC = "nameContains"; +const _nE = "notEquals"; +const _nI = "notIn"; +const _nL = "naturalLanguage"; +const _nN = "newName"; +const _nOR = "numberOfResults"; +const _nORR = "numberOfRerankedResults"; +const _nT = "nextToken"; +const _nTo = "noTranslations"; +const _nV = "newValue"; +const _o = "options"; +const _oA = "outputAction"; +const _oAI = "ownerAccountId"; +const _oAr = "orAll"; +const _oC = "orchestrationConfiguration"; +const _oDC = "outputDataConfig"; +const _oE = "outputEnabled"; +const _oI = "offerId"; +const _oM = "outputModalities"; +const _oMA = "outputModelArn"; +const _oMKKA = "outputModelKmsKeyArn"; +const _oMN = "outputModelName"; +const _oMNC = "outputModelNameContains"; +const _oS = "outputStrength"; +const _oST = "overrideSearchType"; +const _oT = "offerToken"; +const _oTf = "offerType"; +const _of = "offers"; +const _p = "premises"; +const _pA = "policyArn"; +const _pC = "performanceConfig"; +const _pD = "policyDefinition"; +const _pDR = "policyDefinitionRule"; +const _pDT = "policyDefinitionType"; +const _pDV = "policyDefinitionVariable"; +const _pE = "priorElement"; +const _pEC = "piiEntitiesConfig"; +const _pEi = "piiEntities"; +const _pI = "policyId"; +const _pIS = "precomputedInferenceSource"; +const _pISI = "precomputedInferenceSourceIdentifiers"; +const _pMA = "provisionedModelArn"; +const _pMI = "provisionedModelId"; +const _pMN = "provisionedModelName"; +const _pMS = "provisionedModelSummaries"; +const _pN = "providerName"; +const _pRA = "promptRouterArn"; +const _pRAo = "policyRepairAssets"; +const _pRN = "promptRouterName"; +const _pRS = "promptRouterSummaries"; +const _pRSC = "precomputedRagSourceConfig"; +const _pRSI = "precomputedRagSourceIdentifiers"; +const _pT = "promptTemplate"; +const _pVA = "policyVersionArn"; +const _pa = "pattern"; +const _pl = "planning"; +const _po = "policies"; +const _pr = "price"; +const _qC = "queryContent"; +const _qR = "qualityReport"; +const _qTC = "queryTransformationConfiguration"; +const _r = "rule"; +const _rA = "roleArn"; +const _rAGC = "retrieveAndGenerateConfig"; +const _rAGSC = "retrieveAndGenerateSourceConfig"; +const _rARN = "resourceARN"; +const _rAe = "regionAvailability"; +const _rC = "ruleCount"; +const _rCS = "ragConfigSummary"; +const _rCa = "rateCard"; +const _rCag = "ragConfigs"; +const _rCe = "regexesConfig"; +const _rCer = "rerankingConfiguration"; +const _rCet = "retrievalConfiguration"; +const _rCetr = "retrieveConfig"; +const _rCo = "routingCriteria"; +const _rI = "ruleId"; +const _rIa = "ragIdentifiers"; +const _rIu = "ruleIds"; +const _rM = "ratingMethod"; +const _rMF = "requestMetadataFilters"; +const _rN = "resourceName"; +const _rPD = "refundPolicyDescription"; +const _rQD = "responseQualityDifference"; +const _rS = "ratingScale"; +const _rSC = "retrieveSourceConfig"; +const _rSI = "ragSourceIdentifier"; +const _rSS = "responseStreamingSupported"; +const _re = "regexes"; +const _ru = "rules"; +const _s = "status"; +const _sAE = "sourceAccountEquals"; +const _sAI = "sourceAccountId"; +const _sB = "sortBy"; +const _sBO = "s3BucketOwner"; +const _sC = "s3Config"; +const _sCo = "sourceContent"; +const _sCt = "stringContains"; +const _sD = "statusDetails"; +const _sDS = "s3DataSource"; +const _sE = "scenarioExpression"; +const _sEKI = "s3EncryptionKeyId"; +const _sEt = "statusEquals"; +const _sGI = "securityGroupIds"; +const _sI = "subnetIds"; +const _sIDC = "s3InputDataConfig"; +const _sIF = "s3InputFormat"; +const _sIP = "sensitiveInformationPolicy"; +const _sIPC = "sensitiveInformationPolicyConfig"; +const _sL = "s3Location"; +const _sM = "statusMessage"; +const _sMA = "sourceModelArn"; +const _sMAE = "sourceModelArnEquals"; +const _sMC = "selectiveModeConfiguration"; +const _sMN = "sourceModelName"; +const _sMa = "sageMaker"; +const _sMe = "selectionMode"; +const _sO = "sortOrder"; +const _sODC = "s3OutputDataConfig"; +const _sR = "supportingRules"; +const _sRt = "statusReasons"; +const _sS = "stopSequences"; +const _sT = "sourceType"; +const _sTA = "submitTimeAfter"; +const _sTB = "submitTimeBefore"; +const _sTu = "submitTime"; +const _sTup = "supportTerm"; +const _sU = "s3Uri"; +const _sV = "stringValue"; +const _sW = "startsWith"; +const _sa = "satisfiable"; +const _sc = "scenario"; +const _se = "server"; +const _sm = "smithy.ts.sdk.synthetic.com.amazonaws.bedrock"; +const _so = "sources"; +const _st = "statements"; +const _t = "translation"; +const _tA = "translationAmbiguous"; +const _tC = "typeCount"; +const _tCI = "testCaseId"; +const _tCIe = "testCaseIds"; +const _tCe = "testCase"; +const _tCes = "testCases"; +const _tCi = "tierConfig"; +const _tCo = "topicsConfig"; +const _tCoo = "tooComplex"; +const _tD = "termDetails"; +const _tDC = "trainingDataConfig"; +const _tDDE = "textDataDeliveryEnabled"; +const _tDIH = "timeoutDurationInHours"; +const _tDr = "trainingDetails"; +const _tE = "typeEquals"; +const _tF = "testFindings"; +const _tIC = "textInferenceConfig"; +const _tK = "tagKeys"; +const _tL = "trainingLoss"; +const _tM = "trainingMetrics"; +const _tMA = "targetModelArn"; +const _tMC = "teacherModelConfig"; +const _tMI = "teacherModelIdentifier"; +const _tMKKA = "targetModelKmsKeyArn"; +const _tMN = "targetModelName"; +const _tMNC = "targetModelNameContains"; +const _tMT = "targetModelTags"; +const _tN = "typeName"; +const _tNi = "tierName"; +const _tP = "topicPolicy"; +const _tPC = "topicPolicyConfig"; +const _tPT = "textPromptTemplate"; +const _tPo = "topP"; +const _tR = "testResult"; +const _tRR = "testRunResult"; +const _tRS = "testRunStatus"; +const _tRe = "testResults"; +const _tT = "taskType"; +const _ta = "tags"; +const _te = "text"; +const _tem = "temperature"; +const _th = "threshold"; +const _ti = "tier"; +const _to = "topics"; +const _tr = "translations"; +const _ty = "type"; +const _typ = "types"; +const _u = "unit"; +const _uA = "updatedAt"; +const _uBPT = "usageBasedPricingTerm"; +const _uC = "untranslatedClaims"; +const _uFRF = "updateFromRulesFeedback"; +const _uFSF = "updateFromScenarioFeedback"; +const _uP = "untranslatedPremises"; +const _uPR = "usePromptResponse"; +const _uR = "updateRule"; +const _uT = "unusedTypes"; +const _uTV = "unusedTypeValues"; +const _uTVp = "updateTypeValue"; +const _uTp = "updateType"; +const _uV = "unusedVariables"; +const _uVp = "updateVariable"; +const _ur = "url"; +const _uri = "uri"; +const _v = "values"; +const _vC = "variableCount"; +const _vCp = "vpcConfig"; +const _vD = "validationDetails"; +const _vDC = "validationDataConfig"; +const _vDDE = "videoDataDeliveryEnabled"; +const _vL = "validationLoss"; +const _vM = "validationMetrics"; +const _vN = "valueName"; +const _vSC = "vectorSearchConfiguration"; +const _vT = "validityTerm"; +const _va = "value"; +const _val = "validators"; +const _vali = "valid"; +const _var = "variable"; +const _vari = "variables"; +const _ve = "version"; +const _vp = "vpc"; +const _w = "words"; +const _wC = "workflowContent"; +const _wCo = "wordsConfig"; +const _wP = "wordPolicy"; +const _wPC = "wordPolicyConfig"; +const _xact = "x-amz-client-token"; +const n0 = "com.amazonaws.bedrock"; +var AutomatedReasoningLogicStatementContent = [0, n0, _ARLSC, 8, 0]; +var AutomatedReasoningNaturalLanguageStatementContent = [0, n0, _ARNLSC, 8, 0]; +var AutomatedReasoningPolicyAnnotationFeedbackNaturalLanguage = [0, n0, _ARPAFNL, 8, 0]; +var AutomatedReasoningPolicyAnnotationIngestContent = [0, n0, _ARPAIC, 8, 0]; +var AutomatedReasoningPolicyAnnotationRuleNaturalLanguage = [0, n0, _ARPARNL, 8, 0]; +var AutomatedReasoningPolicyBuildDocumentBlob = [0, n0, _ARPBDB, 8, 21]; +var AutomatedReasoningPolicyBuildDocumentDescription = [0, n0, _ARPBDD, 8, 0]; +var AutomatedReasoningPolicyBuildDocumentName = [0, n0, _ARPBDN, 8, 0]; +var AutomatedReasoningPolicyDefinitionRuleAlternateExpression = [0, n0, _ARPDRAE, 8, 0]; +var AutomatedReasoningPolicyDefinitionRuleExpression = [0, n0, _ARPDRE, 8, 0]; +var AutomatedReasoningPolicyDefinitionTypeDescription = [0, n0, _ARPDTD, 8, 0]; +var AutomatedReasoningPolicyDefinitionTypeName = [0, n0, _ARPDTN, 8, 0]; +var AutomatedReasoningPolicyDefinitionTypeValueDescription = [0, n0, _ARPDTVD, 8, 0]; +var AutomatedReasoningPolicyDefinitionVariableDescription = [0, n0, _ARPDVD, 8, 0]; +var AutomatedReasoningPolicyDefinitionVariableName = [0, n0, _ARPDVN, 8, 0]; +var AutomatedReasoningPolicyDescription = [0, n0, _ARPD, 8, 0]; +var AutomatedReasoningPolicyName = [0, n0, _ARPN, 8, 0]; +var AutomatedReasoningPolicyScenarioAlternateExpression = [0, n0, _ARPSAE, 8, 0]; +var AutomatedReasoningPolicyScenarioExpression = [0, n0, _ARPSE, 8, 0]; +var AutomatedReasoningPolicyTestGuardContent = [0, n0, _ARPTGC, 8, 0]; +var AutomatedReasoningPolicyTestQueryContent = [0, n0, _ARPTQC, 8, 0]; +var ByteContentBlob = [0, n0, _BCB, 8, 21]; +var EvaluationDatasetName = [0, n0, _EDN, 8, 0]; +var EvaluationJobDescription = [0, n0, _EJD, 8, 0]; +var EvaluationJobIdentifier = [0, n0, _EJI, 8, 0]; +var EvaluationMetricDescription = [0, n0, _EMD, 8, 0]; +var EvaluationMetricName = [0, n0, _EMN, 8, 0]; +var EvaluationModelInferenceParams = [0, n0, _EMIP, 8, 0]; +var GuardrailBlockedMessaging = [0, n0, _GBM, 8, 0]; +var GuardrailContentFilterAction$1 = [0, n0, _GCFA, 8, 0]; +var GuardrailContentFiltersTierName$1 = [0, n0, _GCFTN, 8, 0]; +var GuardrailContextualGroundingAction$1 = [0, n0, _GCGA, 8, 0]; +var GuardrailDescription = [0, n0, _GD, 8, 0]; +var GuardrailFailureRecommendation = [0, n0, _GFR, 8, 0]; +var GuardrailModality$1 = [0, n0, _GM, 8, 0]; +var GuardrailName = [0, n0, _GN, 8, 0]; +var GuardrailStatusReason = [0, n0, _GSR, 8, 0]; +var GuardrailTopicAction$1 = [0, n0, _GTA, 8, 0]; +var GuardrailTopicDefinition = [0, n0, _GTD, 8, 0]; +var GuardrailTopicExample = [0, n0, _GTE, 8, 0]; +var GuardrailTopicName = [0, n0, _GTN, 8, 0]; +var GuardrailTopicsTierName$1 = [0, n0, _GTTN, 8, 0]; +var GuardrailWordAction$1 = [0, n0, _GWA, 8, 0]; +var HumanTaskInstructions = [0, n0, _HTI, 8, 0]; +var Identifier = [0, n0, _I, 8, 0]; +var InferenceProfileDescription = [0, n0, _IPD, 8, 0]; +var Message = [0, n0, _M, 8, 0]; +var MetricName = [0, n0, _MN, 8, 0]; +var PromptRouterDescription = [0, n0, _PRD, 8, 0]; +var TextPromptTemplate = [0, n0, _TPT, 8, 0]; +var AccessDeniedException = [ + -3, + n0, + _ADE, + { + [_e]: _c, + [_hE]: 403, + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(AccessDeniedException, AccessDeniedException$1); +var AgreementAvailability = [3, n0, _AA, 0, [_s, _eM], [0, 0]]; +var AutomatedEvaluationConfig = [ + 3, + n0, + _AEC, + 0, + [_dMC, _eMC, _cMC], + [ + [() => EvaluationDatasetMetricConfigs, 0], + () => EvaluatorModelConfig, + [() => AutomatedEvaluationCustomMetricConfig, 0], + ], +]; +var AutomatedEvaluationCustomMetricConfig = [ + 3, + n0, + _AECMC, + 0, + [_cM, _eMC], + [[() => AutomatedEvaluationCustomMetrics, 0], () => CustomMetricEvaluatorModelConfig], +]; +var AutomatedReasoningCheckImpossibleFinding = [ + 3, + n0, + _ARCIF, + 0, + [_t, _cR, _lW], + [ + [() => AutomatedReasoningCheckTranslation, 0], + () => AutomatedReasoningCheckRuleList, + [() => AutomatedReasoningCheckLogicWarning, 0], + ], +]; +var AutomatedReasoningCheckInputTextReference = [ + 3, + n0, + _ARCITR, + 0, + [_te], + [[() => AutomatedReasoningNaturalLanguageStatementContent, 0]], +]; +var AutomatedReasoningCheckInvalidFinding = [ + 3, + n0, + _ARCIFu, + 0, + [_t, _cR, _lW], + [ + [() => AutomatedReasoningCheckTranslation, 0], + () => AutomatedReasoningCheckRuleList, + [() => AutomatedReasoningCheckLogicWarning, 0], + ], +]; +var AutomatedReasoningCheckLogicWarning = [ + 3, + n0, + _ARCLW, + 0, + [_ty, _p, _cl], + [0, [() => AutomatedReasoningLogicStatementList, 0], [() => AutomatedReasoningLogicStatementList, 0]], +]; +var AutomatedReasoningCheckNoTranslationsFinding = [3, n0, _ARCNTF, 0, [], []]; +var AutomatedReasoningCheckRule = [3, n0, _ARCR, 0, [_i, _pVA], [0, 0]]; +var AutomatedReasoningCheckSatisfiableFinding = [ + 3, + n0, + _ARCSF, + 0, + [_t, _cTS, _cFS, _lW], + [ + [() => AutomatedReasoningCheckTranslation, 0], + [() => AutomatedReasoningCheckScenario, 0], + [() => AutomatedReasoningCheckScenario, 0], + [() => AutomatedReasoningCheckLogicWarning, 0], + ], +]; +var AutomatedReasoningCheckScenario = [ + 3, + n0, + _ARCS, + 0, + [_st], + [[() => AutomatedReasoningLogicStatementList, 0]], +]; +var AutomatedReasoningCheckTooComplexFinding = [3, n0, _ARCTCF, 0, [], []]; +var AutomatedReasoningCheckTranslation = [ + 3, + n0, + _ARCT, + 0, + [_p, _cl, _uP, _uC, _co], + [ + [() => AutomatedReasoningLogicStatementList, 0], + [() => AutomatedReasoningLogicStatementList, 0], + [() => AutomatedReasoningCheckInputTextReferenceList, 0], + [() => AutomatedReasoningCheckInputTextReferenceList, 0], + 1, + ], +]; +var AutomatedReasoningCheckTranslationAmbiguousFinding = [ + 3, + n0, + _ARCTAF, + 0, + [_o, _dS], + [ + [() => AutomatedReasoningCheckTranslationOptionList, 0], + [() => AutomatedReasoningCheckDifferenceScenarioList, 0], + ], +]; +var AutomatedReasoningCheckTranslationOption = [ + 3, + n0, + _ARCTO, + 0, + [_tr], + [[() => AutomatedReasoningCheckTranslationList, 0]], +]; +var AutomatedReasoningCheckValidFinding = [ + 3, + n0, + _ARCVF, + 0, + [_t, _cTS, _sR, _lW], + [ + [() => AutomatedReasoningCheckTranslation, 0], + [() => AutomatedReasoningCheckScenario, 0], + () => AutomatedReasoningCheckRuleList, + [() => AutomatedReasoningCheckLogicWarning, 0], + ], +]; +var AutomatedReasoningLogicStatement = [ + 3, + n0, + _ARLS, + 0, + [_l, _nL], + [ + [() => AutomatedReasoningLogicStatementContent, 0], + [() => AutomatedReasoningNaturalLanguageStatementContent, 0], + ], +]; +var AutomatedReasoningPolicyAddRuleAnnotation = [ + 3, + n0, + _ARPARA, + 0, + [_ex], + [[() => AutomatedReasoningPolicyDefinitionRuleExpression, 0]], +]; +var AutomatedReasoningPolicyAddRuleFromNaturalLanguageAnnotation = [ + 3, + n0, + _ARPARFNLA, + 0, + [_nL], + [[() => AutomatedReasoningPolicyAnnotationRuleNaturalLanguage, 0]], +]; +var AutomatedReasoningPolicyAddRuleMutation = [ + 3, + n0, + _ARPARM, + 0, + [_r], + [[() => AutomatedReasoningPolicyDefinitionRule, 0]], +]; +var AutomatedReasoningPolicyAddTypeAnnotation = [ + 3, + n0, + _ARPATA, + 0, + [_n, _d, _v], + [ + [() => AutomatedReasoningPolicyDefinitionTypeName, 0], + [() => AutomatedReasoningPolicyDefinitionTypeDescription, 0], + [() => AutomatedReasoningPolicyDefinitionTypeValueList, 0], + ], +]; +var AutomatedReasoningPolicyAddTypeMutation = [ + 3, + n0, + _ARPATM, + 0, + [_ty], + [[() => AutomatedReasoningPolicyDefinitionType, 0]], +]; +var AutomatedReasoningPolicyAddTypeValue = [ + 3, + n0, + _ARPATV, + 0, + [_va, _d], + [0, [() => AutomatedReasoningPolicyDefinitionTypeValueDescription, 0]], +]; +var AutomatedReasoningPolicyAddVariableAnnotation = [ + 3, + n0, + _ARPAVA, + 0, + [_n, _ty, _d], + [ + [() => AutomatedReasoningPolicyDefinitionVariableName, 0], + [() => AutomatedReasoningPolicyDefinitionTypeName, 0], + [() => AutomatedReasoningPolicyDefinitionVariableDescription, 0], + ], +]; +var AutomatedReasoningPolicyAddVariableMutation = [ + 3, + n0, + _ARPAVM, + 0, + [_var], + [[() => AutomatedReasoningPolicyDefinitionVariable, 0]], +]; +var AutomatedReasoningPolicyBuildLog = [ + 3, + n0, + _ARPBL, + 0, + [_en], + [[() => AutomatedReasoningPolicyBuildLogEntryList, 0]], +]; +var AutomatedReasoningPolicyBuildLogEntry = [ + 3, + n0, + _ARPBLE, + 0, + [_a, _s, _bS], + [[() => AutomatedReasoningPolicyAnnotation, 0], 0, [() => AutomatedReasoningPolicyBuildStepList, 0]], +]; +var AutomatedReasoningPolicyBuildStep = [ + 3, + n0, + _ARPBS, + 0, + [_con, _pE, _me], + [ + [() => AutomatedReasoningPolicyBuildStepContext, 0], + [() => AutomatedReasoningPolicyDefinitionElement, 0], + () => AutomatedReasoningPolicyBuildStepMessageList, + ], +]; +var AutomatedReasoningPolicyBuildStepMessage = [3, n0, _ARPBSM, 0, [_m, _mT], [0, 0]]; +var AutomatedReasoningPolicyBuildWorkflowDocument = [ + 3, + n0, + _ARPBWD, + 0, + [_do, _dCT, _dN, _dD], + [ + [() => AutomatedReasoningPolicyBuildDocumentBlob, 0], + 0, + [() => AutomatedReasoningPolicyBuildDocumentName, 0], + [() => AutomatedReasoningPolicyBuildDocumentDescription, 0], + ], +]; +var AutomatedReasoningPolicyBuildWorkflowRepairContent = [ + 3, + n0, + _ARPBWRC, + 0, + [_an], + [[() => AutomatedReasoningPolicyAnnotationList, 0]], +]; +var AutomatedReasoningPolicyBuildWorkflowSource = [ + 3, + n0, + _ARPBWS, + 0, + [_pD, _wC], + [ + [() => AutomatedReasoningPolicyDefinition, 0], + [() => AutomatedReasoningPolicyWorkflowTypeContent, 0], + ], +]; +var AutomatedReasoningPolicyBuildWorkflowSummary = [ + 3, + n0, + _ARPBWSu, + 0, + [_pA, _bWI, _s, _bWT, _cA, _uA], + [0, 0, 0, 0, 5, 5], +]; +var AutomatedReasoningPolicyDefinition = [ + 3, + n0, + _ARPDu, + 0, + [_ve, _typ, _ru, _vari], + [ + 0, + [() => AutomatedReasoningPolicyDefinitionTypeList, 0], + [() => AutomatedReasoningPolicyDefinitionRuleList, 0], + [() => AutomatedReasoningPolicyDefinitionVariableList, 0], + ], +]; +var AutomatedReasoningPolicyDefinitionQualityReport = [ + 3, + n0, + _ARPDQR, + 0, + [_tC, _vC, _rC, _uT, _uTV, _uV, _cRo, _dRS], + [ + 1, + 1, + 1, + [() => AutomatedReasoningPolicyDefinitionTypeNameList, 0], + [() => AutomatedReasoningPolicyDefinitionTypeValuePairList, 0], + [() => AutomatedReasoningPolicyDefinitionVariableNameList, 0], + 64 | 0, + [() => AutomatedReasoningPolicyDisjointRuleSetList, 0], + ], +]; +var AutomatedReasoningPolicyDefinitionRule = [ + 3, + n0, + _ARPDR, + 0, + [_i, _ex, _aE], + [ + 0, + [() => AutomatedReasoningPolicyDefinitionRuleExpression, 0], + [() => AutomatedReasoningPolicyDefinitionRuleAlternateExpression, 0], + ], +]; +var AutomatedReasoningPolicyDefinitionType = [ + 3, + n0, + _ARPDT, + 0, + [_n, _d, _v], + [ + [() => AutomatedReasoningPolicyDefinitionTypeName, 0], + [() => AutomatedReasoningPolicyDefinitionTypeDescription, 0], + [() => AutomatedReasoningPolicyDefinitionTypeValueList, 0], + ], +]; +var AutomatedReasoningPolicyDefinitionTypeValue = [ + 3, + n0, + _ARPDTV, + 0, + [_va, _d], + [0, [() => AutomatedReasoningPolicyDefinitionTypeValueDescription, 0]], +]; +var AutomatedReasoningPolicyDefinitionTypeValuePair = [ + 3, + n0, + _ARPDTVP, + 0, + [_tN, _vN], + [[() => AutomatedReasoningPolicyDefinitionTypeName, 0], 0], +]; +var AutomatedReasoningPolicyDefinitionVariable = [ + 3, + n0, + _ARPDV, + 0, + [_n, _ty, _d], + [ + [() => AutomatedReasoningPolicyDefinitionVariableName, 0], + [() => AutomatedReasoningPolicyDefinitionTypeName, 0], + [() => AutomatedReasoningPolicyDefinitionVariableDescription, 0], + ], +]; +var AutomatedReasoningPolicyDeleteRuleAnnotation = [3, n0, _ARPDRA, 0, [_rI], [0]]; +var AutomatedReasoningPolicyDeleteRuleMutation = [3, n0, _ARPDRM, 0, [_i], [0]]; +var AutomatedReasoningPolicyDeleteTypeAnnotation = [ + 3, + n0, + _ARPDTA, + 0, + [_n], + [[() => AutomatedReasoningPolicyDefinitionTypeName, 0]], +]; +var AutomatedReasoningPolicyDeleteTypeMutation = [ + 3, + n0, + _ARPDTM, + 0, + [_n], + [[() => AutomatedReasoningPolicyDefinitionTypeName, 0]], +]; +var AutomatedReasoningPolicyDeleteTypeValue = [3, n0, _ARPDTVu, 0, [_va], [0]]; +var AutomatedReasoningPolicyDeleteVariableAnnotation = [ + 3, + n0, + _ARPDVA, + 0, + [_n], + [[() => AutomatedReasoningPolicyDefinitionVariableName, 0]], +]; +var AutomatedReasoningPolicyDeleteVariableMutation = [ + 3, + n0, + _ARPDVM, + 0, + [_n], + [[() => AutomatedReasoningPolicyDefinitionVariableName, 0]], +]; +var AutomatedReasoningPolicyDisjointRuleSet = [ + 3, + n0, + _ARPDRS, + 0, + [_vari, _ru], + [[() => AutomatedReasoningPolicyDefinitionVariableNameList, 0], 64 | 0], +]; +var AutomatedReasoningPolicyGeneratedTestCase = [ + 3, + n0, + _ARPGTC, + 0, + [_qC, _gC, _eAFR], + [[() => AutomatedReasoningPolicyTestQueryContent, 0], [() => AutomatedReasoningPolicyTestGuardContent, 0], 0], +]; +var AutomatedReasoningPolicyGeneratedTestCases = [ + 3, + n0, + _ARPGTCu, + 0, + [_gTC], + [[() => AutomatedReasoningPolicyGeneratedTestCaseList, 0]], +]; +var AutomatedReasoningPolicyIngestContentAnnotation = [ + 3, + n0, + _ARPICA, + 0, + [_cont], + [[() => AutomatedReasoningPolicyAnnotationIngestContent, 0]], +]; +var AutomatedReasoningPolicyPlanning = [3, n0, _ARPP, 0, [], []]; +var AutomatedReasoningPolicyScenario = [ + 3, + n0, + _ARPS, + 0, + [_ex, _aE, _rIu, _eR], + [ + [() => AutomatedReasoningPolicyScenarioExpression, 0], + [() => AutomatedReasoningPolicyScenarioAlternateExpression, 0], + 64 | 0, + 0, + ], +]; +var AutomatedReasoningPolicySummary = [ + 3, + n0, + _ARPSu, + 0, + [_pA, _n, _d, _ve, _pI, _cA, _uA], + [0, [() => AutomatedReasoningPolicyName, 0], [() => AutomatedReasoningPolicyDescription, 0], 0, 0, 5, 5], +]; +var AutomatedReasoningPolicyTestCase = [ + 3, + n0, + _ARPTC, + 0, + [_tCI, _gC, _qC, _eAFR, _cA, _uA, _cT], + [ + 0, + [() => AutomatedReasoningPolicyTestGuardContent, 0], + [() => AutomatedReasoningPolicyTestQueryContent, 0], + 0, + 5, + 5, + 1, + ], +]; +var AutomatedReasoningPolicyTestResult = [ + 3, + n0, + _ARPTR, + 0, + [_tCe, _pA, _tRS, _tF, _tRR, _aTFR, _uA], + [[() => AutomatedReasoningPolicyTestCase, 0], 0, 0, [() => AutomatedReasoningCheckFindingList, 0], 0, 0, 5], +]; +var AutomatedReasoningPolicyUpdateFromRuleFeedbackAnnotation = [ + 3, + n0, + _ARPUFRFA, + 0, + [_rIu, _f], + [64 | 0, [() => AutomatedReasoningPolicyAnnotationFeedbackNaturalLanguage, 0]], +]; +var AutomatedReasoningPolicyUpdateFromScenarioFeedbackAnnotation = [ + 3, + n0, + _ARPUFSFA, + 0, + [_rIu, _sE, _f], + [ + 64 | 0, + [() => AutomatedReasoningPolicyScenarioExpression, 0], + [() => AutomatedReasoningPolicyAnnotationFeedbackNaturalLanguage, 0], + ], +]; +var AutomatedReasoningPolicyUpdateRuleAnnotation = [ + 3, + n0, + _ARPURA, + 0, + [_rI, _ex], + [0, [() => AutomatedReasoningPolicyDefinitionRuleExpression, 0]], +]; +var AutomatedReasoningPolicyUpdateRuleMutation = [ + 3, + n0, + _ARPURM, + 0, + [_r], + [[() => AutomatedReasoningPolicyDefinitionRule, 0]], +]; +var AutomatedReasoningPolicyUpdateTypeAnnotation = [ + 3, + n0, + _ARPUTA, + 0, + [_n, _nN, _d, _v], + [ + [() => AutomatedReasoningPolicyDefinitionTypeName, 0], + [() => AutomatedReasoningPolicyDefinitionTypeName, 0], + [() => AutomatedReasoningPolicyDefinitionTypeDescription, 0], + [() => AutomatedReasoningPolicyTypeValueAnnotationList, 0], + ], +]; +var AutomatedReasoningPolicyUpdateTypeMutation = [ + 3, + n0, + _ARPUTM, + 0, + [_ty], + [[() => AutomatedReasoningPolicyDefinitionType, 0]], +]; +var AutomatedReasoningPolicyUpdateTypeValue = [ + 3, + n0, + _ARPUTV, + 0, + [_va, _nV, _d], + [0, 0, [() => AutomatedReasoningPolicyDefinitionTypeValueDescription, 0]], +]; +var AutomatedReasoningPolicyUpdateVariableAnnotation = [ + 3, + n0, + _ARPUVA, + 0, + [_n, _nN, _d], + [ + [() => AutomatedReasoningPolicyDefinitionVariableName, 0], + [() => AutomatedReasoningPolicyDefinitionVariableName, 0], + [() => AutomatedReasoningPolicyDefinitionVariableDescription, 0], + ], +]; +var AutomatedReasoningPolicyUpdateVariableMutation = [ + 3, + n0, + _ARPUVM, + 0, + [_var], + [[() => AutomatedReasoningPolicyDefinitionVariable, 0]], +]; +var BatchDeleteEvaluationJobError = [ + 3, + n0, + _BDEJE, + 0, + [_jI, _cod, _m], + [[() => EvaluationJobIdentifier, 0], 0, 0], +]; +var BatchDeleteEvaluationJobItem = [ + 3, + n0, + _BDEJI, + 0, + [_jI, _jS], + [[() => EvaluationJobIdentifier, 0], 0], +]; +var BatchDeleteEvaluationJobRequest = [ + 3, + n0, + _BDEJR, + 0, + [_jIo], + [[() => EvaluationJobIdentifiers, 0]], +]; +var BatchDeleteEvaluationJobResponse = [ + 3, + n0, + _BDEJRa, + 0, + [_er, _eJ], + [ + [() => BatchDeleteEvaluationJobErrors, 0], + [() => BatchDeleteEvaluationJobItems, 0], + ], +]; +var BedrockEvaluatorModel = [3, n0, _BEM, 0, [_mI], [0]]; +var ByteContentDoc = [ + 3, + n0, + _BCD, + 0, + [_id, _cTo, _da], + [[() => Identifier, 0], 0, [() => ByteContentBlob, 0]], +]; +var CancelAutomatedReasoningPolicyBuildWorkflowRequest = [ + 3, + n0, + _CARPBWR, + 0, + [_pA, _bWI], + [ + [0, 1], + [0, 1], + ], +]; +var CancelAutomatedReasoningPolicyBuildWorkflowResponse = [3, n0, _CARPBWRa, 0, [], []]; +var CloudWatchConfig = [3, n0, _CWC, 0, [_lGN, _rA, _lDDSC], [0, 0, () => S3Config]]; +var ConflictException = [ + -3, + n0, + _CE, + { + [_e]: _c, + [_hE]: 400, + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(ConflictException, ConflictException$1); +var CreateAutomatedReasoningPolicyRequest = [ + 3, + n0, + _CARPR, + 0, + [_n, _d, _cRT, _pD, _kKI, _ta], + [ + [() => AutomatedReasoningPolicyName, 0], + [() => AutomatedReasoningPolicyDescription, 0], + [0, 4], + [() => AutomatedReasoningPolicyDefinition, 0], + 0, + () => TagList, + ], +]; +var CreateAutomatedReasoningPolicyResponse = [ + 3, + n0, + _CARPRr, + 0, + [_pA, _ve, _n, _d, _dH, _cA, _uA], + [0, 0, [() => AutomatedReasoningPolicyName, 0], [() => AutomatedReasoningPolicyDescription, 0], 0, 5, 5], +]; +var CreateAutomatedReasoningPolicyTestCaseRequest = [ + 3, + n0, + _CARPTCR, + 0, + [_pA, _gC, _qC, _eAFR, _cRT, _cT], + [ + [0, 1], + [() => AutomatedReasoningPolicyTestGuardContent, 0], + [() => AutomatedReasoningPolicyTestQueryContent, 0], + 0, + [0, 4], + 1, + ], +]; +var CreateAutomatedReasoningPolicyTestCaseResponse = [ + 3, + n0, + _CARPTCRr, + 0, + [_pA, _tCI], + [0, 0], +]; +var CreateAutomatedReasoningPolicyVersionRequest = [ + 3, + n0, + _CARPVR, + 0, + [_pA, _cRT, _lUDH, _ta], + [[0, 1], [0, 4], 0, () => TagList], +]; +var CreateAutomatedReasoningPolicyVersionResponse = [ + 3, + n0, + _CARPVRr, + 0, + [_pA, _ve, _n, _d, _dH, _cA], + [0, 0, [() => AutomatedReasoningPolicyName, 0], [() => AutomatedReasoningPolicyDescription, 0], 0, 5], +]; +var CreateCustomModelDeploymentRequest = [ + 3, + n0, + _CCMDR, + 0, + [_mDN, _mA, _d, _ta, _cRT], + [0, 0, 0, () => TagList, [0, 4]], +]; +var CreateCustomModelDeploymentResponse = [3, n0, _CCMDRr, 0, [_cMDA], [0]]; +var CreateCustomModelRequest = [ + 3, + n0, + _CCMR, + 0, + [_mN, _mSC, _mKKA, _rA, _mTo, _cRT], + [0, () => ModelDataSource, 0, 0, () => TagList, [0, 4]], +]; +var CreateCustomModelResponse = [3, n0, _CCMRr, 0, [_mA], [0]]; +var CreateEvaluationJobRequest = [ + 3, + n0, + _CEJR, + 0, + [_jN, _jD, _cRT, _rA, _cEKI, _jT, _aT, _eC, _iC, _oDC], + [ + 0, + [() => EvaluationJobDescription, 0], + [0, 4], + 0, + 0, + () => TagList, + 0, + [() => EvaluationConfig, 0], + [() => EvaluationInferenceConfig, 0], + () => EvaluationOutputDataConfig, + ], +]; +var CreateEvaluationJobResponse = [3, n0, _CEJRr, 0, [_jA], [0]]; +var CreateFoundationModelAgreementRequest = [3, n0, _CFMAR, 0, [_oT, _mIo], [0, 0]]; +var CreateFoundationModelAgreementResponse = [3, n0, _CFMARr, 0, [_mIo], [0]]; +var CreateGuardrailRequest = [ + 3, + n0, + _CGR, + 0, + [_n, _d, _tPC, _cPC, _wPC, _sIPC, _cGPC, _aRPC, _cRC, _bIM, _bOM, _kKI, _ta, _cRT], + [ + [() => GuardrailName, 0], + [() => GuardrailDescription, 0], + [() => GuardrailTopicPolicyConfig, 0], + [() => GuardrailContentPolicyConfig, 0], + [() => GuardrailWordPolicyConfig, 0], + () => GuardrailSensitiveInformationPolicyConfig, + [() => GuardrailContextualGroundingPolicyConfig, 0], + () => GuardrailAutomatedReasoningPolicyConfig, + () => GuardrailCrossRegionConfig, + [() => GuardrailBlockedMessaging, 0], + [() => GuardrailBlockedMessaging, 0], + 0, + () => TagList, + [0, 4], + ], +]; +var CreateGuardrailResponse = [3, n0, _CGRr, 0, [_gI, _gA, _ve, _cA], [0, 0, 0, 5]]; +var CreateGuardrailVersionRequest = [ + 3, + n0, + _CGVR, + 0, + [_gIu, _d, _cRT], + [ + [0, 1], + [() => GuardrailDescription, 0], + [0, 4], + ], +]; +var CreateGuardrailVersionResponse = [3, n0, _CGVRr, 0, [_gI, _ve], [0, 0]]; +var CreateInferenceProfileRequest = [ + 3, + n0, + _CIPR, + 0, + [_iPN, _d, _cRT, _mS, _ta], + [0, [() => InferenceProfileDescription, 0], [0, 4], () => InferenceProfileModelSource, () => TagList], +]; +var CreateInferenceProfileResponse = [3, n0, _CIPRr, 0, [_iPA, _s], [0, 0]]; +var CreateMarketplaceModelEndpointRequest = [ + 3, + n0, + _CMMER, + 0, + [_mSI, _eCn, _aEc, _eN, _cRT, _ta], + [0, () => EndpointConfig, 2, 0, [0, 4], () => TagList], +]; +var CreateMarketplaceModelEndpointResponse = [ + 3, + n0, + _CMMERr, + 0, + [_mME], + [() => MarketplaceModelEndpoint], +]; +var CreateModelCopyJobRequest = [ + 3, + n0, + _CMCJR, + 0, + [_sMA, _tMN, _mKKI, _tMT, _cRT], + [0, 0, 0, () => TagList, [0, 4]], +]; +var CreateModelCopyJobResponse = [3, n0, _CMCJRr, 0, [_jA], [0]]; +var CreateModelCustomizationJobRequest = [ + 3, + n0, + _CMCJRre, + 0, + [_jN, _cMN, _rA, _cRT, _bMI, _cTu, _cMKKI, _jT, _cMT, _tDC, _vDC, _oDC, _hP, _vCp, _cC], + [ + 0, + 0, + 0, + [0, 4], + 0, + 0, + 0, + () => TagList, + () => TagList, + [() => TrainingDataConfig, 0], + () => ValidationDataConfig, + () => OutputDataConfig, + 128 | 0, + () => VpcConfig, + () => CustomizationConfig, + ], +]; +var CreateModelCustomizationJobResponse = [3, n0, _CMCJRrea, 0, [_jA], [0]]; +var CreateModelImportJobRequest = [ + 3, + n0, + _CMIJR, + 0, + [_jN, _iMN, _rA, _mDS, _jT, _iMT, _cRT, _vCp, _iMKKI], + [0, 0, 0, () => ModelDataSource, () => TagList, () => TagList, 0, () => VpcConfig, 0], +]; +var CreateModelImportJobResponse = [3, n0, _CMIJRr, 0, [_jA], [0]]; +var CreateModelInvocationJobRequest = [ + 3, + n0, + _CMIJRre, + 0, + [_jN, _rA, _cRT, _mIo, _iDC, _oDC, _vCp, _tDIH, _ta], + [ + 0, + 0, + [0, 4], + 0, + () => ModelInvocationJobInputDataConfig, + () => ModelInvocationJobOutputDataConfig, + () => VpcConfig, + 1, + () => TagList, + ], +]; +var CreateModelInvocationJobResponse = [3, n0, _CMIJRrea, 0, [_jA], [0]]; +var CreatePromptRouterRequest = [ + 3, + n0, + _CPRR, + 0, + [_cRT, _pRN, _mo, _d, _rCo, _fM, _ta], + [ + [0, 4], + 0, + () => PromptRouterTargetModels, + [() => PromptRouterDescription, 0], + () => RoutingCriteria, + () => PromptRouterTargetModel, + () => TagList, + ], +]; +var CreatePromptRouterResponse = [3, n0, _CPRRr, 0, [_pRA], [0]]; +var CreateProvisionedModelThroughputRequest = [ + 3, + n0, + _CPMTR, + 0, + [_cRT, _mU, _pMN, _mIo, _cD, _ta], + [[0, 4], 1, 0, 0, 0, () => TagList], +]; +var CreateProvisionedModelThroughputResponse = [3, n0, _CPMTRr, 0, [_pMA], [0]]; +var CustomMetricBedrockEvaluatorModel = [3, n0, _CMBEM, 0, [_mI], [0]]; +var CustomMetricDefinition = [ + 3, + n0, + _CMD, + 8, + [_n, _in, _rS], + [[() => MetricName, 0], 0, () => RatingScale], +]; +var CustomMetricEvaluatorModelConfig = [ + 3, + n0, + _CMEMC, + 0, + [_bEM], + [() => CustomMetricBedrockEvaluatorModels], +]; +var CustomModelDeploymentSummary = [ + 3, + n0, + _CMDS, + 0, + [_cMDA, _cMDN, _mA, _cA, _s, _lUA, _fMa], + [0, 0, 0, 5, 0, 5, 0], +]; +var CustomModelSummary = [ + 3, + n0, + _CMS, + 0, + [_mA, _mN, _cTr, _bMA, _bMN, _cTu, _oAI, _mSo], + [0, 0, 5, 0, 0, 0, 0, 0], +]; +var CustomModelUnits = [3, n0, _CMU, 0, [_cMUPMC, _cMUV], [1, 0]]; +var DataProcessingDetails = [3, n0, _DPD, 0, [_s, _cTr, _lMT], [0, 5, 5]]; +var DeleteAutomatedReasoningPolicyBuildWorkflowRequest = [ + 3, + n0, + _DARPBWR, + 0, + [_pA, _bWI, _lUA], + [ + [0, 1], + [0, 1], + [ + 5, + { + [_hQ]: _uA, + }, + ], + ], +]; +var DeleteAutomatedReasoningPolicyBuildWorkflowResponse = [3, n0, _DARPBWRe, 0, [], []]; +var DeleteAutomatedReasoningPolicyRequest = [ + 3, + n0, + _DARPR, + 0, + [_pA, _fo], + [ + [0, 1], + [ + 2, + { + [_hQ]: _fo, + }, + ], + ], +]; +var DeleteAutomatedReasoningPolicyResponse = [3, n0, _DARPRe, 0, [], []]; +var DeleteAutomatedReasoningPolicyTestCaseRequest = [ + 3, + n0, + _DARPTCR, + 0, + [_pA, _tCI, _lUA], + [ + [0, 1], + [0, 1], + [ + 5, + { + [_hQ]: _uA, + }, + ], + ], +]; +var DeleteAutomatedReasoningPolicyTestCaseResponse = [3, n0, _DARPTCRe, 0, [], []]; +var DeleteCustomModelDeploymentRequest = [3, n0, _DCMDR, 0, [_cMDI], [[0, 1]]]; +var DeleteCustomModelDeploymentResponse = [3, n0, _DCMDRe, 0, [], []]; +var DeleteCustomModelRequest = [3, n0, _DCMR, 0, [_mI], [[0, 1]]]; +var DeleteCustomModelResponse = [3, n0, _DCMRe, 0, [], []]; +var DeleteFoundationModelAgreementRequest = [3, n0, _DFMAR, 0, [_mIo], [0]]; +var DeleteFoundationModelAgreementResponse = [3, n0, _DFMARe, 0, [], []]; +var DeleteGuardrailRequest = [ + 3, + n0, + _DGR, + 0, + [_gIu, _gV], + [ + [0, 1], + [ + 0, + { + [_hQ]: _gV, + }, + ], + ], +]; +var DeleteGuardrailResponse = [3, n0, _DGRe, 0, [], []]; +var DeleteImportedModelRequest = [3, n0, _DIMR, 0, [_mI], [[0, 1]]]; +var DeleteImportedModelResponse = [3, n0, _DIMRe, 0, [], []]; +var DeleteInferenceProfileRequest = [3, n0, _DIPR, 0, [_iPI], [[0, 1]]]; +var DeleteInferenceProfileResponse = [3, n0, _DIPRe, 0, [], []]; +var DeleteMarketplaceModelEndpointRequest = [3, n0, _DMMER, 0, [_eA], [[0, 1]]]; +var DeleteMarketplaceModelEndpointResponse = [3, n0, _DMMERe, 0, [], []]; +var DeleteModelInvocationLoggingConfigurationRequest = [3, n0, _DMILCR, 0, [], []]; +var DeleteModelInvocationLoggingConfigurationResponse = [3, n0, _DMILCRe, 0, [], []]; +var DeletePromptRouterRequest = [3, n0, _DPRR, 0, [_pRA], [[0, 1]]]; +var DeletePromptRouterResponse = [3, n0, _DPRRe, 0, [], []]; +var DeleteProvisionedModelThroughputRequest = [3, n0, _DPMTR, 0, [_pMI], [[0, 1]]]; +var DeleteProvisionedModelThroughputResponse = [3, n0, _DPMTRe, 0, [], []]; +var DeregisterMarketplaceModelEndpointRequest = [3, n0, _DMMERer, 0, [_eA], [[0, 1]]]; +var DeregisterMarketplaceModelEndpointResponse = [3, n0, _DMMERere, 0, [], []]; +var DimensionalPriceRate = [3, n0, _DPR, 0, [_di, _pr, _d, _u], [0, 0, 0, 0]]; +var DistillationConfig = [3, n0, _DC, 0, [_tMC], [() => TeacherModelConfig]]; +var EvaluationBedrockModel = [ + 3, + n0, + _EBM, + 0, + [_mI, _iP, _pC], + [0, [() => EvaluationModelInferenceParams, 0], () => PerformanceConfiguration], +]; +var EvaluationDataset = [ + 3, + n0, + _ED, + 0, + [_n, _dL], + [[() => EvaluationDatasetName, 0], () => EvaluationDatasetLocation], +]; +var EvaluationDatasetMetricConfig = [ + 3, + n0, + _EDMC, + 0, + [_tT, _dat, _mNe], + [0, [() => EvaluationDataset, 0], [() => EvaluationMetricNames, 0]], +]; +var EvaluationInferenceConfigSummary = [ + 3, + n0, + _EICS, + 0, + [_mCS, _rCS], + [() => EvaluationModelConfigSummary, () => EvaluationRagConfigSummary], +]; +var EvaluationModelConfigSummary = [3, n0, _EMCS, 0, [_bMIe, _pISI], [64 | 0, 64 | 0]]; +var EvaluationOutputDataConfig = [3, n0, _EODC, 0, [_sU], [0]]; +var EvaluationPrecomputedInferenceSource = [3, n0, _EPIS, 0, [_iSI], [0]]; +var EvaluationPrecomputedRetrieveAndGenerateSourceConfig = [ + 3, + n0, + _EPRAGSC, + 0, + [_rSI], + [0], +]; +var EvaluationPrecomputedRetrieveSourceConfig = [3, n0, _EPRSC, 0, [_rSI], [0]]; +var EvaluationRagConfigSummary = [3, n0, _ERCS, 0, [_bKBI, _pRSI], [64 | 0, 64 | 0]]; +var EvaluationSummary = [ + 3, + n0, + _ES, + 0, + [_jA, _jN, _s, _cTr, _jTo, _eTT, _mIod, _rIa, _eMI, _cMEMI, _iCS, _aT], + [0, 0, 0, 5, 0, 64 | 0, 64 | 0, 64 | 0, 64 | 0, 64 | 0, () => EvaluationInferenceConfigSummary, 0], +]; +var ExportAutomatedReasoningPolicyVersionRequest = [3, n0, _EARPVR, 0, [_pA], [[0, 1]]]; +var ExportAutomatedReasoningPolicyVersionResponse = [ + 3, + n0, + _EARPVRx, + 0, + [_pD], + [[() => AutomatedReasoningPolicyDefinition, 16]], +]; +var ExternalSource = [ + 3, + n0, + _ESx, + 0, + [_sT, _sL, _bC], + [0, () => S3ObjectDoc, [() => ByteContentDoc, 0]], +]; +var ExternalSourcesGenerationConfiguration = [ + 3, + n0, + _ESGC, + 0, + [_pT, _gCu, _kIC, _aMRF], + [[() => PromptTemplate, 0], () => GuardrailConfiguration, () => KbInferenceConfig, 128 | 15], +]; +var ExternalSourcesRetrieveAndGenerateConfiguration = [ + 3, + n0, + _ESRAGC, + 0, + [_mA, _so, _gCe], + [0, [() => ExternalSources, 0], [() => ExternalSourcesGenerationConfiguration, 0]], +]; +var FieldForReranking = [3, n0, _FFR, 0, [_fN], [0]]; +var FilterAttribute = [3, n0, _FA, 0, [_k, _va], [0, 15]]; +var FoundationModelDetails = [ + 3, + n0, + _FMD, + 0, + [_mA, _mIo, _mN, _pN, _iM, _oM, _rSS, _cS, _iTS, _mL], + [0, 0, 0, 0, 64 | 0, 64 | 0, 2, 64 | 0, 64 | 0, () => FoundationModelLifecycle], +]; +var FoundationModelLifecycle = [3, n0, _FML, 0, [_s], [0]]; +var FoundationModelSummary = [ + 3, + n0, + _FMS, + 0, + [_mA, _mIo, _mN, _pN, _iM, _oM, _rSS, _cS, _iTS, _mL], + [0, 0, 0, 0, 64 | 0, 64 | 0, 2, 64 | 0, 64 | 0, () => FoundationModelLifecycle], +]; +var GenerationConfiguration = [ + 3, + n0, + _GC, + 0, + [_pT, _gCu, _kIC, _aMRF], + [[() => PromptTemplate, 0], () => GuardrailConfiguration, () => KbInferenceConfig, 128 | 15], +]; +var GetAutomatedReasoningPolicyAnnotationsRequest = [ + 3, + n0, + _GARPAR, + 0, + [_pA, _bWI], + [ + [0, 1], + [0, 1], + ], +]; +var GetAutomatedReasoningPolicyAnnotationsResponse = [ + 3, + n0, + _GARPARe, + 0, + [_pA, _n, _bWI, _an, _aSH, _uA], + [0, [() => AutomatedReasoningPolicyName, 0], 0, [() => AutomatedReasoningPolicyAnnotationList, 0], 0, 5], +]; +var GetAutomatedReasoningPolicyBuildWorkflowRequest = [ + 3, + n0, + _GARPBWR, + 0, + [_pA, _bWI], + [ + [0, 1], + [0, 1], + ], +]; +var GetAutomatedReasoningPolicyBuildWorkflowResponse = [ + 3, + n0, + _GARPBWRe, + 0, + [_pA, _bWI, _s, _bWT, _dN, _dCT, _dD, _cA, _uA], + [ + 0, + 0, + 0, + 0, + [() => AutomatedReasoningPolicyBuildDocumentName, 0], + 0, + [() => AutomatedReasoningPolicyBuildDocumentDescription, 0], + 5, + 5, + ], +]; +var GetAutomatedReasoningPolicyBuildWorkflowResultAssetsRequest = [ + 3, + n0, + _GARPBWRAR, + 0, + [_pA, _bWI, _aTs], + [ + [0, 1], + [0, 1], + [ + 0, + { + [_hQ]: _aTs, + }, + ], + ], +]; +var GetAutomatedReasoningPolicyBuildWorkflowResultAssetsResponse = [ + 3, + n0, + _GARPBWRARe, + 0, + [_pA, _bWI, _bWA], + [0, 0, [() => AutomatedReasoningPolicyBuildResultAssets, 0]], +]; +var GetAutomatedReasoningPolicyNextScenarioRequest = [ + 3, + n0, + _GARPNSR, + 0, + [_pA, _bWI], + [ + [0, 1], + [0, 1], + ], +]; +var GetAutomatedReasoningPolicyNextScenarioResponse = [ + 3, + n0, + _GARPNSRe, + 0, + [_pA, _sc], + [0, [() => AutomatedReasoningPolicyScenario, 0]], +]; +var GetAutomatedReasoningPolicyRequest = [3, n0, _GARPR, 0, [_pA], [[0, 1]]]; +var GetAutomatedReasoningPolicyResponse = [ + 3, + n0, + _GARPRe, + 0, + [_pA, _n, _ve, _pI, _d, _dH, _kKA, _cA, _uA], + [0, [() => AutomatedReasoningPolicyName, 0], 0, 0, [() => AutomatedReasoningPolicyDescription, 0], 0, 0, 5, 5], +]; +var GetAutomatedReasoningPolicyTestCaseRequest = [ + 3, + n0, + _GARPTCR, + 0, + [_pA, _tCI], + [ + [0, 1], + [0, 1], + ], +]; +var GetAutomatedReasoningPolicyTestCaseResponse = [ + 3, + n0, + _GARPTCRe, + 0, + [_pA, _tCe], + [0, [() => AutomatedReasoningPolicyTestCase, 0]], +]; +var GetAutomatedReasoningPolicyTestResultRequest = [ + 3, + n0, + _GARPTRR, + 0, + [_pA, _bWI, _tCI], + [ + [0, 1], + [0, 1], + [0, 1], + ], +]; +var GetAutomatedReasoningPolicyTestResultResponse = [ + 3, + n0, + _GARPTRRe, + 0, + [_tR], + [[() => AutomatedReasoningPolicyTestResult, 0]], +]; +var GetCustomModelDeploymentRequest = [3, n0, _GCMDR, 0, [_cMDI], [[0, 1]]]; +var GetCustomModelDeploymentResponse = [ + 3, + n0, + _GCMDRe, + 0, + [_cMDA, _mDN, _mA, _cA, _s, _d, _fMa, _lUA], + [0, 0, 0, 5, 0, 0, 0, 5], +]; +var GetCustomModelRequest = [3, n0, _GCMR, 0, [_mI], [[0, 1]]]; +var GetCustomModelResponse = [ + 3, + n0, + _GCMRe, + 0, + [_mA, _mN, _jN, _jA, _bMA, _cTu, _mKKA, _hP, _tDC, _vDC, _oDC, _tM, _vM, _cTr, _cC, _mSo, _fMa], + [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 128 | 0, + [() => TrainingDataConfig, 0], + () => ValidationDataConfig, + () => OutputDataConfig, + () => TrainingMetrics, + () => ValidationMetrics, + 5, + () => CustomizationConfig, + 0, + 0, + ], +]; +var GetEvaluationJobRequest = [ + 3, + n0, + _GEJR, + 0, + [_jI], + [[() => EvaluationJobIdentifier, 1]], +]; +var GetEvaluationJobResponse = [ + 3, + n0, + _GEJRe, + 0, + [_jN, _s, _jA, _jD, _rA, _cEKI, _jTo, _aT, _eC, _iC, _oDC, _cTr, _lMT, _fMai], + [ + 0, + 0, + 0, + [() => EvaluationJobDescription, 0], + 0, + 0, + 0, + 0, + [() => EvaluationConfig, 0], + [() => EvaluationInferenceConfig, 0], + () => EvaluationOutputDataConfig, + 5, + 5, + 64 | 0, + ], +]; +var GetFoundationModelAvailabilityRequest = [3, n0, _GFMAR, 0, [_mIo], [[0, 1]]]; +var GetFoundationModelAvailabilityResponse = [ + 3, + n0, + _GFMARe, + 0, + [_mIo, _aA, _aS, _eAn, _rAe], + [0, () => AgreementAvailability, 0, 0, 0], +]; +var GetFoundationModelRequest = [3, n0, _GFMR, 0, [_mI], [[0, 1]]]; +var GetFoundationModelResponse = [ + 3, + n0, + _GFMRe, + 0, + [_mD], + [() => FoundationModelDetails], +]; +var GetGuardrailRequest = [ + 3, + n0, + _GGR, + 0, + [_gIu, _gV], + [ + [0, 1], + [ + 0, + { + [_hQ]: _gV, + }, + ], + ], +]; +var GetGuardrailResponse = [ + 3, + n0, + _GGRe, + 0, + [_n, _d, _gI, _gA, _ve, _s, _tP, _cP, _wP, _sIP, _cGP, _aRP, _cRD, _cA, _uA, _sRt, _fR, _bIM, _bOM, _kKA], + [ + [() => GuardrailName, 0], + [() => GuardrailDescription, 0], + 0, + 0, + 0, + 0, + [() => GuardrailTopicPolicy, 0], + [() => GuardrailContentPolicy, 0], + [() => GuardrailWordPolicy, 0], + () => GuardrailSensitiveInformationPolicy, + [() => GuardrailContextualGroundingPolicy, 0], + () => GuardrailAutomatedReasoningPolicy, + () => GuardrailCrossRegionDetails, + 5, + 5, + [() => GuardrailStatusReasons, 0], + [() => GuardrailFailureRecommendations, 0], + [() => GuardrailBlockedMessaging, 0], + [() => GuardrailBlockedMessaging, 0], + 0, + ], +]; +var GetImportedModelRequest = [3, n0, _GIMR, 0, [_mI], [[0, 1]]]; +var GetImportedModelResponse = [ + 3, + n0, + _GIMRe, + 0, + [_mA, _mN, _jN, _jA, _mDS, _cTr, _mAo, _mKKA, _iS, _cMU], + [0, 0, 0, 0, () => ModelDataSource, 5, 0, 0, 2, () => CustomModelUnits], +]; +var GetInferenceProfileRequest = [3, n0, _GIPR, 0, [_iPI], [[0, 1]]]; +var GetInferenceProfileResponse = [ + 3, + n0, + _GIPRe, + 0, + [_iPN, _d, _cA, _uA, _iPA, _mo, _iPIn, _s, _ty], + [0, [() => InferenceProfileDescription, 0], 5, 5, 0, () => InferenceProfileModels, 0, 0, 0], +]; +var GetMarketplaceModelEndpointRequest = [3, n0, _GMMER, 0, [_eA], [[0, 1]]]; +var GetMarketplaceModelEndpointResponse = [ + 3, + n0, + _GMMERe, + 0, + [_mME], + [() => MarketplaceModelEndpoint], +]; +var GetModelCopyJobRequest = [3, n0, _GMCJR, 0, [_jA], [[0, 1]]]; +var GetModelCopyJobResponse = [ + 3, + n0, + _GMCJRe, + 0, + [_jA, _s, _cTr, _tMA, _tMN, _sAI, _sMA, _tMKKA, _tMT, _fMa, _sMN], + [0, 0, 5, 0, 0, 0, 0, 0, () => TagList, 0, 0], +]; +var GetModelCustomizationJobRequest = [3, n0, _GMCJRet, 0, [_jI], [[0, 1]]]; +var GetModelCustomizationJobResponse = [ + 3, + n0, + _GMCJReto, + 0, + [ + _jA, + _jN, + _oMN, + _oMA, + _cRT, + _rA, + _s, + _sD, + _fMa, + _cTr, + _lMT, + _eT, + _bMA, + _hP, + _tDC, + _vDC, + _oDC, + _cTu, + _oMKKA, + _tM, + _vM, + _vCp, + _cC, + ], + [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + () => StatusDetails, + 0, + 5, + 5, + 5, + 0, + 128 | 0, + [() => TrainingDataConfig, 0], + () => ValidationDataConfig, + () => OutputDataConfig, + 0, + 0, + () => TrainingMetrics, + () => ValidationMetrics, + () => VpcConfig, + () => CustomizationConfig, + ], +]; +var GetModelImportJobRequest = [3, n0, _GMIJR, 0, [_jI], [[0, 1]]]; +var GetModelImportJobResponse = [ + 3, + n0, + _GMIJRe, + 0, + [_jA, _jN, _iMN, _iMA, _rA, _mDS, _s, _fMa, _cTr, _lMT, _eT, _vCp, _iMKKA], + [0, 0, 0, 0, 0, () => ModelDataSource, 0, 0, 5, 5, 5, () => VpcConfig, 0], +]; +var GetModelInvocationJobRequest = [3, n0, _GMIJRet, 0, [_jI], [[0, 1]]]; +var GetModelInvocationJobResponse = [ + 3, + n0, + _GMIJReto, + 0, + [_jA, _jN, _mIo, _cRT, _rA, _s, _m, _sTu, _lMT, _eT, _iDC, _oDC, _vCp, _tDIH, _jET], + [ + 0, + 0, + 0, + 0, + 0, + 0, + [() => Message, 0], + 5, + 5, + 5, + () => ModelInvocationJobInputDataConfig, + () => ModelInvocationJobOutputDataConfig, + () => VpcConfig, + 1, + 5, + ], +]; +var GetModelInvocationLoggingConfigurationRequest = [3, n0, _GMILCR, 0, [], []]; +var GetModelInvocationLoggingConfigurationResponse = [ + 3, + n0, + _GMILCRe, + 0, + [_lC], + [() => LoggingConfig], +]; +var GetPromptRouterRequest = [3, n0, _GPRR, 0, [_pRA], [[0, 1]]]; +var GetPromptRouterResponse = [ + 3, + n0, + _GPRRe, + 0, + [_pRN, _rCo, _d, _cA, _uA, _pRA, _mo, _fM, _s, _ty], + [ + 0, + () => RoutingCriteria, + [() => PromptRouterDescription, 0], + 5, + 5, + 0, + () => PromptRouterTargetModels, + () => PromptRouterTargetModel, + 0, + 0, + ], +]; +var GetProvisionedModelThroughputRequest = [3, n0, _GPMTR, 0, [_pMI], [[0, 1]]]; +var GetProvisionedModelThroughputResponse = [ + 3, + n0, + _GPMTRe, + 0, + [_mU, _dMU, _pMN, _pMA, _mA, _dMA, _fMA, _s, _cTr, _lMT, _fMa, _cD, _cET], + [1, 1, 0, 0, 0, 0, 0, 0, 5, 5, 0, 0, 5], +]; +var GetUseCaseForModelAccessRequest = [3, n0, _GUCFMAR, 0, [], []]; +var GetUseCaseForModelAccessResponse = [3, n0, _GUCFMARe, 0, [_fD], [21]]; +var GuardrailAutomatedReasoningPolicy = [3, n0, _GARP, 0, [_po, _cT], [64 | 0, 1]]; +var GuardrailAutomatedReasoningPolicyConfig = [3, n0, _GARPC, 0, [_po, _cT], [64 | 0, 1]]; +var GuardrailConfiguration = [3, n0, _GCu, 0, [_gI, _gV], [0, 0]]; +var GuardrailContentFilter = [ + 3, + n0, + _GCF, + 0, + [_ty, _iSn, _oS, _iM, _oM, _iA, _oA, _iE, _oE], + [ + 0, + 0, + 0, + [() => GuardrailModalities, 0], + [() => GuardrailModalities, 0], + [() => GuardrailContentFilterAction$1, 0], + [() => GuardrailContentFilterAction$1, 0], + 2, + 2, + ], +]; +var GuardrailContentFilterConfig = [ + 3, + n0, + _GCFC, + 0, + [_ty, _iSn, _oS, _iM, _oM, _iA, _oA, _iE, _oE], + [ + 0, + 0, + 0, + [() => GuardrailModalities, 0], + [() => GuardrailModalities, 0], + [() => GuardrailContentFilterAction$1, 0], + [() => GuardrailContentFilterAction$1, 0], + 2, + 2, + ], +]; +var GuardrailContentFiltersTier = [ + 3, + n0, + _GCFT, + 0, + [_tNi], + [[() => GuardrailContentFiltersTierName$1, 0]], +]; +var GuardrailContentFiltersTierConfig = [ + 3, + n0, + _GCFTC, + 0, + [_tNi], + [[() => GuardrailContentFiltersTierName$1, 0]], +]; +var GuardrailContentPolicy = [ + 3, + n0, + _GCP, + 0, + [_fi, _ti], + [ + [() => GuardrailContentFilters, 0], + [() => GuardrailContentFiltersTier, 0], + ], +]; +var GuardrailContentPolicyConfig = [ + 3, + n0, + _GCPC, + 0, + [_fC, _tCi], + [ + [() => GuardrailContentFiltersConfig, 0], + [() => GuardrailContentFiltersTierConfig, 0], + ], +]; +var GuardrailContextualGroundingFilter = [ + 3, + n0, + _GCGF, + 0, + [_ty, _th, _ac, _ena], + [0, 1, [() => GuardrailContextualGroundingAction$1, 0], 2], +]; +var GuardrailContextualGroundingFilterConfig = [ + 3, + n0, + _GCGFC, + 0, + [_ty, _th, _ac, _ena], + [0, 1, [() => GuardrailContextualGroundingAction$1, 0], 2], +]; +var GuardrailContextualGroundingPolicy = [ + 3, + n0, + _GCGP, + 0, + [_fi], + [[() => GuardrailContextualGroundingFilters, 0]], +]; +var GuardrailContextualGroundingPolicyConfig = [ + 3, + n0, + _GCGPC, + 0, + [_fC], + [[() => GuardrailContextualGroundingFiltersConfig, 0]], +]; +var GuardrailCrossRegionConfig = [3, n0, _GCRC, 0, [_gPI], [0]]; +var GuardrailCrossRegionDetails = [3, n0, _GCRD, 0, [_gPIu, _gPA], [0, 0]]; +var GuardrailManagedWords = [ + 3, + n0, + _GMW, + 0, + [_ty, _iA, _oA, _iE, _oE], + [0, [() => GuardrailWordAction$1, 0], [() => GuardrailWordAction$1, 0], 2, 2], +]; +var GuardrailManagedWordsConfig = [ + 3, + n0, + _GMWC, + 0, + [_ty, _iA, _oA, _iE, _oE], + [0, [() => GuardrailWordAction$1, 0], [() => GuardrailWordAction$1, 0], 2, 2], +]; +var GuardrailPiiEntity = [ + 3, + n0, + _GPE, + 0, + [_ty, _ac, _iA, _oA, _iE, _oE], + [0, 0, 0, 0, 2, 2], +]; +var GuardrailPiiEntityConfig = [ + 3, + n0, + _GPEC, + 0, + [_ty, _ac, _iA, _oA, _iE, _oE], + [0, 0, 0, 0, 2, 2], +]; +var GuardrailRegex = [ + 3, + n0, + _GR, + 0, + [_n, _d, _pa, _ac, _iA, _oA, _iE, _oE], + [0, 0, 0, 0, 0, 0, 2, 2], +]; +var GuardrailRegexConfig = [ + 3, + n0, + _GRC, + 0, + [_n, _d, _pa, _ac, _iA, _oA, _iE, _oE], + [0, 0, 0, 0, 0, 0, 2, 2], +]; +var GuardrailSensitiveInformationPolicy = [ + 3, + n0, + _GSIP, + 0, + [_pEi, _re], + [() => GuardrailPiiEntities, () => GuardrailRegexes], +]; +var GuardrailSensitiveInformationPolicyConfig = [ + 3, + n0, + _GSIPC, + 0, + [_pEC, _rCe], + [() => GuardrailPiiEntitiesConfig, () => GuardrailRegexesConfig], +]; +var GuardrailSummary = [ + 3, + n0, + _GS, + 0, + [_i, _ar, _s, _n, _d, _ve, _cA, _uA, _cRD], + [0, 0, 0, [() => GuardrailName, 0], [() => GuardrailDescription, 0], 0, 5, 5, () => GuardrailCrossRegionDetails], +]; +var GuardrailTopic = [ + 3, + n0, + _GT, + 0, + [_n, _de, _exa, _ty, _iA, _oA, _iE, _oE], + [ + [() => GuardrailTopicName, 0], + [() => GuardrailTopicDefinition, 0], + [() => GuardrailTopicExamples, 0], + 0, + [() => GuardrailTopicAction$1, 0], + [() => GuardrailTopicAction$1, 0], + 2, + 2, + ], +]; +var GuardrailTopicConfig = [ + 3, + n0, + _GTC, + 0, + [_n, _de, _exa, _ty, _iA, _oA, _iE, _oE], + [ + [() => GuardrailTopicName, 0], + [() => GuardrailTopicDefinition, 0], + [() => GuardrailTopicExamples, 0], + 0, + [() => GuardrailTopicAction$1, 0], + [() => GuardrailTopicAction$1, 0], + 2, + 2, + ], +]; +var GuardrailTopicPolicy = [ + 3, + n0, + _GTP, + 0, + [_to, _ti], + [ + [() => GuardrailTopics, 0], + [() => GuardrailTopicsTier, 0], + ], +]; +var GuardrailTopicPolicyConfig = [ + 3, + n0, + _GTPC, + 0, + [_tCo, _tCi], + [ + [() => GuardrailTopicsConfig, 0], + [() => GuardrailTopicsTierConfig, 0], + ], +]; +var GuardrailTopicsTier = [3, n0, _GTT, 0, [_tNi], [[() => GuardrailTopicsTierName$1, 0]]]; +var GuardrailTopicsTierConfig = [ + 3, + n0, + _GTTC, + 0, + [_tNi], + [[() => GuardrailTopicsTierName$1, 0]], +]; +var GuardrailWord = [ + 3, + n0, + _GW, + 0, + [_te, _iA, _oA, _iE, _oE], + [0, [() => GuardrailWordAction$1, 0], [() => GuardrailWordAction$1, 0], 2, 2], +]; +var GuardrailWordConfig = [ + 3, + n0, + _GWC, + 0, + [_te, _iA, _oA, _iE, _oE], + [0, [() => GuardrailWordAction$1, 0], [() => GuardrailWordAction$1, 0], 2, 2], +]; +var GuardrailWordPolicy = [ + 3, + n0, + _GWP, + 0, + [_w, _mWL], + [ + [() => GuardrailWords, 0], + [() => GuardrailManagedWordLists, 0], + ], +]; +var GuardrailWordPolicyConfig = [ + 3, + n0, + _GWPC, + 0, + [_wCo, _mWLC], + [ + [() => GuardrailWordsConfig, 0], + [() => GuardrailManagedWordListsConfig, 0], + ], +]; +var HumanEvaluationConfig = [ + 3, + n0, + _HEC, + 0, + [_hWC, _cM, _dMC], + [ + [() => HumanWorkflowConfig, 0], + [() => HumanEvaluationCustomMetrics, 0], + [() => EvaluationDatasetMetricConfigs, 0], + ], +]; +var HumanEvaluationCustomMetric = [ + 3, + n0, + _HECM, + 0, + [_n, _d, _rM], + [[() => EvaluationMetricName, 0], [() => EvaluationMetricDescription, 0], 0], +]; +var HumanWorkflowConfig = [ + 3, + n0, + _HWC, + 0, + [_fDA, _in], + [0, [() => HumanTaskInstructions, 0]], +]; +var ImplicitFilterConfiguration = [ + 3, + n0, + _IFC, + 0, + [_mAe, _mA], + [[() => MetadataAttributeSchemaList, 0], 0], +]; +var ImportedModelSummary = [3, n0, _IMS, 0, [_mA, _mN, _cTr, _iS, _mAo], [0, 0, 5, 2, 0]]; +var InferenceProfileModel = [3, n0, _IPM, 0, [_mA], [0]]; +var InferenceProfileSummary = [ + 3, + n0, + _IPS, + 0, + [_iPN, _d, _cA, _uA, _iPA, _mo, _iPIn, _s, _ty], + [0, [() => InferenceProfileDescription, 0], 5, 5, 0, () => InferenceProfileModels, 0, 0, 0], +]; +var InternalServerException = [ + -3, + n0, + _ISE, + { + [_e]: _se, + [_hE]: 500, + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(InternalServerException, InternalServerException$1); +var InvocationLogsConfig = [ + 3, + n0, + _ILC, + 0, + [_uPR, _iLS, _rMF], + [2, () => InvocationLogSource, [() => RequestMetadataFilters, 0]], +]; +var KbInferenceConfig = [3, n0, _KIC, 0, [_tIC], [() => TextInferenceConfig]]; +var KnowledgeBaseRetrievalConfiguration = [ + 3, + n0, + _KBRC, + 0, + [_vSC], + [[() => KnowledgeBaseVectorSearchConfiguration, 0]], +]; +var KnowledgeBaseRetrieveAndGenerateConfiguration = [ + 3, + n0, + _KBRAGC, + 0, + [_kBI, _mA, _rCet, _gCe, _oC], + [ + 0, + 0, + [() => KnowledgeBaseRetrievalConfiguration, 0], + [() => GenerationConfiguration, 0], + () => OrchestrationConfiguration, + ], +]; +var KnowledgeBaseVectorSearchConfiguration = [ + 3, + n0, + _KBVSC, + 0, + [_nOR, _oST, _fil, _iFC, _rCer], + [ + 1, + 0, + [() => RetrievalFilter, 0], + [() => ImplicitFilterConfiguration, 0], + [() => VectorSearchRerankingConfiguration, 0], + ], +]; +var LegalTerm = [3, n0, _LT, 0, [_ur], [0]]; +var ListAutomatedReasoningPoliciesRequest = [ + 3, + n0, + _LARPR, + 0, + [_pA, _nT, _mR], + [ + [ + 0, + { + [_hQ]: _pA, + }, + ], + [ + 0, + { + [_hQ]: _nT, + }, + ], + [ + 1, + { + [_hQ]: _mR, + }, + ], + ], +]; +var ListAutomatedReasoningPoliciesResponse = [ + 3, + n0, + _LARPRi, + 0, + [_aRPS, _nT], + [[() => AutomatedReasoningPolicySummaries, 0], 0], +]; +var ListAutomatedReasoningPolicyBuildWorkflowsRequest = [ + 3, + n0, + _LARPBWR, + 0, + [_pA, _nT, _mR], + [ + [0, 1], + [ + 0, + { + [_hQ]: _nT, + }, + ], + [ + 1, + { + [_hQ]: _mR, + }, + ], + ], +]; +var ListAutomatedReasoningPolicyBuildWorkflowsResponse = [ + 3, + n0, + _LARPBWRi, + 0, + [_aRPBWS, _nT], + [() => AutomatedReasoningPolicyBuildWorkflowSummaries, 0], +]; +var ListAutomatedReasoningPolicyTestCasesRequest = [ + 3, + n0, + _LARPTCR, + 0, + [_pA, _nT, _mR], + [ + [0, 1], + [ + 0, + { + [_hQ]: _nT, + }, + ], + [ + 1, + { + [_hQ]: _mR, + }, + ], + ], +]; +var ListAutomatedReasoningPolicyTestCasesResponse = [ + 3, + n0, + _LARPTCRi, + 0, + [_tCes, _nT], + [[() => AutomatedReasoningPolicyTestCaseList, 0], 0], +]; +var ListAutomatedReasoningPolicyTestResultsRequest = [ + 3, + n0, + _LARPTRR, + 0, + [_pA, _bWI, _nT, _mR], + [ + [0, 1], + [0, 1], + [ + 0, + { + [_hQ]: _nT, + }, + ], + [ + 1, + { + [_hQ]: _mR, + }, + ], + ], +]; +var ListAutomatedReasoningPolicyTestResultsResponse = [ + 3, + n0, + _LARPTRRi, + 0, + [_tRe, _nT], + [[() => AutomatedReasoningPolicyTestList, 0], 0], +]; +var ListCustomModelDeploymentsRequest = [ + 3, + n0, + _LCMDR, + 0, + [_cB, _cAr, _nC, _mR, _nT, _sB, _sO, _sEt, _mAE], + [ + [ + 5, + { + [_hQ]: _cB, + }, + ], + [ + 5, + { + [_hQ]: _cAr, + }, + ], + [ + 0, + { + [_hQ]: _nC, + }, + ], + [ + 1, + { + [_hQ]: _mR, + }, + ], + [ + 0, + { + [_hQ]: _nT, + }, + ], + [ + 0, + { + [_hQ]: _sB, + }, + ], + [ + 0, + { + [_hQ]: _sO, + }, + ], + [ + 0, + { + [_hQ]: _sEt, + }, + ], + [ + 0, + { + [_hQ]: _mAE, + }, + ], + ], +]; +var ListCustomModelDeploymentsResponse = [ + 3, + n0, + _LCMDRi, + 0, + [_nT, _mDSo], + [0, () => CustomModelDeploymentSummaryList], +]; +var ListCustomModelsRequest = [ + 3, + n0, + _LCMR, + 0, + [_cTB, _cTA, _nC, _bMAE, _fMAE, _mR, _nT, _sB, _sO, _iO, _mSo], + [ + [ + 5, + { + [_hQ]: _cTB, + }, + ], + [ + 5, + { + [_hQ]: _cTA, + }, + ], + [ + 0, + { + [_hQ]: _nC, + }, + ], + [ + 0, + { + [_hQ]: _bMAE, + }, + ], + [ + 0, + { + [_hQ]: _fMAE, + }, + ], + [ + 1, + { + [_hQ]: _mR, + }, + ], + [ + 0, + { + [_hQ]: _nT, + }, + ], + [ + 0, + { + [_hQ]: _sB, + }, + ], + [ + 0, + { + [_hQ]: _sO, + }, + ], + [ + 2, + { + [_hQ]: _iO, + }, + ], + [ + 0, + { + [_hQ]: _mSo, + }, + ], + ], +]; +var ListCustomModelsResponse = [ + 3, + n0, + _LCMRi, + 0, + [_nT, _mSod], + [0, () => CustomModelSummaryList], +]; +var ListEvaluationJobsRequest = [ + 3, + n0, + _LEJR, + 0, + [_cTA, _cTB, _sEt, _aTE, _nC, _mR, _nT, _sB, _sO], + [ + [ + 5, + { + [_hQ]: _cTA, + }, + ], + [ + 5, + { + [_hQ]: _cTB, + }, + ], + [ + 0, + { + [_hQ]: _sEt, + }, + ], + [ + 0, + { + [_hQ]: _aTE, + }, + ], + [ + 0, + { + [_hQ]: _nC, + }, + ], + [ + 1, + { + [_hQ]: _mR, + }, + ], + [ + 0, + { + [_hQ]: _nT, + }, + ], + [ + 0, + { + [_hQ]: _sB, + }, + ], + [ + 0, + { + [_hQ]: _sO, + }, + ], + ], +]; +var ListEvaluationJobsResponse = [ + 3, + n0, + _LEJRi, + 0, + [_nT, _jSo], + [0, () => EvaluationSummaries], +]; +var ListFoundationModelAgreementOffersRequest = [ + 3, + n0, + _LFMAOR, + 0, + [_mIo, _oTf], + [ + [0, 1], + [ + 0, + { + [_hQ]: _oTf, + }, + ], + ], +]; +var ListFoundationModelAgreementOffersResponse = [ + 3, + n0, + _LFMAORi, + 0, + [_mIo, _of], + [0, () => Offers], +]; +var ListFoundationModelsRequest = [ + 3, + n0, + _LFMR, + 0, + [_bP, _bCT, _bOMy, _bIT], + [ + [ + 0, + { + [_hQ]: _bP, + }, + ], + [ + 0, + { + [_hQ]: _bCT, + }, + ], + [ + 0, + { + [_hQ]: _bOMy, + }, + ], + [ + 0, + { + [_hQ]: _bIT, + }, + ], + ], +]; +var ListFoundationModelsResponse = [ + 3, + n0, + _LFMRi, + 0, + [_mSod], + [() => FoundationModelSummaryList], +]; +var ListGuardrailsRequest = [ + 3, + n0, + _LGR, + 0, + [_gIu, _mR, _nT], + [ + [ + 0, + { + [_hQ]: _gIu, + }, + ], + [ + 1, + { + [_hQ]: _mR, + }, + ], + [ + 0, + { + [_hQ]: _nT, + }, + ], + ], +]; +var ListGuardrailsResponse = [ + 3, + n0, + _LGRi, + 0, + [_g, _nT], + [[() => GuardrailSummaries, 0], 0], +]; +var ListImportedModelsRequest = [ + 3, + n0, + _LIMR, + 0, + [_cTB, _cTA, _nC, _mR, _nT, _sB, _sO], + [ + [ + 5, + { + [_hQ]: _cTB, + }, + ], + [ + 5, + { + [_hQ]: _cTA, + }, + ], + [ + 0, + { + [_hQ]: _nC, + }, + ], + [ + 1, + { + [_hQ]: _mR, + }, + ], + [ + 0, + { + [_hQ]: _nT, + }, + ], + [ + 0, + { + [_hQ]: _sB, + }, + ], + [ + 0, + { + [_hQ]: _sO, + }, + ], + ], +]; +var ListImportedModelsResponse = [ + 3, + n0, + _LIMRi, + 0, + [_nT, _mSod], + [0, () => ImportedModelSummaryList], +]; +var ListInferenceProfilesRequest = [ + 3, + n0, + _LIPR, + 0, + [_mR, _nT, _tE], + [ + [ + 1, + { + [_hQ]: _mR, + }, + ], + [ + 0, + { + [_hQ]: _nT, + }, + ], + [ + 0, + { + [_hQ]: _ty, + }, + ], + ], +]; +var ListInferenceProfilesResponse = [ + 3, + n0, + _LIPRi, + 0, + [_iPS, _nT], + [[() => InferenceProfileSummaries, 0], 0], +]; +var ListMarketplaceModelEndpointsRequest = [ + 3, + n0, + _LMMER, + 0, + [_mR, _nT, _mSE], + [ + [ + 1, + { + [_hQ]: _mR, + }, + ], + [ + 0, + { + [_hQ]: _nT, + }, + ], + [ + 0, + { + [_hQ]: _mSI, + }, + ], + ], +]; +var ListMarketplaceModelEndpointsResponse = [ + 3, + n0, + _LMMERi, + 0, + [_mMEa, _nT], + [() => MarketplaceModelEndpointSummaries, 0], +]; +var ListModelCopyJobsRequest = [ + 3, + n0, + _LMCJR, + 0, + [_cTA, _cTB, _sEt, _sAE, _sMAE, _tMNC, _mR, _nT, _sB, _sO], + [ + [ + 5, + { + [_hQ]: _cTA, + }, + ], + [ + 5, + { + [_hQ]: _cTB, + }, + ], + [ + 0, + { + [_hQ]: _sEt, + }, + ], + [ + 0, + { + [_hQ]: _sAE, + }, + ], + [ + 0, + { + [_hQ]: _sMAE, + }, + ], + [ + 0, + { + [_hQ]: _oMNC, + }, + ], + [ + 1, + { + [_hQ]: _mR, + }, + ], + [ + 0, + { + [_hQ]: _nT, + }, + ], + [ + 0, + { + [_hQ]: _sB, + }, + ], + [ + 0, + { + [_hQ]: _sO, + }, + ], + ], +]; +var ListModelCopyJobsResponse = [ + 3, + n0, + _LMCJRi, + 0, + [_nT, _mCJS], + [0, () => ModelCopyJobSummaries], +]; +var ListModelCustomizationJobsRequest = [ + 3, + n0, + _LMCJRis, + 0, + [_cTA, _cTB, _sEt, _nC, _mR, _nT, _sB, _sO], + [ + [ + 5, + { + [_hQ]: _cTA, + }, + ], + [ + 5, + { + [_hQ]: _cTB, + }, + ], + [ + 0, + { + [_hQ]: _sEt, + }, + ], + [ + 0, + { + [_hQ]: _nC, + }, + ], + [ + 1, + { + [_hQ]: _mR, + }, + ], + [ + 0, + { + [_hQ]: _nT, + }, + ], + [ + 0, + { + [_hQ]: _sB, + }, + ], + [ + 0, + { + [_hQ]: _sO, + }, + ], + ], +]; +var ListModelCustomizationJobsResponse = [ + 3, + n0, + _LMCJRist, + 0, + [_nT, _mCJSo], + [0, () => ModelCustomizationJobSummaries], +]; +var ListModelImportJobsRequest = [ + 3, + n0, + _LMIJR, + 0, + [_cTA, _cTB, _sEt, _nC, _mR, _nT, _sB, _sO], + [ + [ + 5, + { + [_hQ]: _cTA, + }, + ], + [ + 5, + { + [_hQ]: _cTB, + }, + ], + [ + 0, + { + [_hQ]: _sEt, + }, + ], + [ + 0, + { + [_hQ]: _nC, + }, + ], + [ + 1, + { + [_hQ]: _mR, + }, + ], + [ + 0, + { + [_hQ]: _nT, + }, + ], + [ + 0, + { + [_hQ]: _sB, + }, + ], + [ + 0, + { + [_hQ]: _sO, + }, + ], + ], +]; +var ListModelImportJobsResponse = [ + 3, + n0, + _LMIJRi, + 0, + [_nT, _mIJS], + [0, () => ModelImportJobSummaries], +]; +var ListModelInvocationJobsRequest = [ + 3, + n0, + _LMIJRis, + 0, + [_sTA, _sTB, _sEt, _nC, _mR, _nT, _sB, _sO], + [ + [ + 5, + { + [_hQ]: _sTA, + }, + ], + [ + 5, + { + [_hQ]: _sTB, + }, + ], + [ + 0, + { + [_hQ]: _sEt, + }, + ], + [ + 0, + { + [_hQ]: _nC, + }, + ], + [ + 1, + { + [_hQ]: _mR, + }, + ], + [ + 0, + { + [_hQ]: _nT, + }, + ], + [ + 0, + { + [_hQ]: _sB, + }, + ], + [ + 0, + { + [_hQ]: _sO, + }, + ], + ], +]; +var ListModelInvocationJobsResponse = [ + 3, + n0, + _LMIJRist, + 0, + [_nT, _iJS], + [0, [() => ModelInvocationJobSummaries, 0]], +]; +var ListPromptRoutersRequest = [ + 3, + n0, + _LPRR, + 0, + [_mR, _nT, _ty], + [ + [ + 1, + { + [_hQ]: _mR, + }, + ], + [ + 0, + { + [_hQ]: _nT, + }, + ], + [ + 0, + { + [_hQ]: _ty, + }, + ], + ], +]; +var ListPromptRoutersResponse = [ + 3, + n0, + _LPRRi, + 0, + [_pRS, _nT], + [[() => PromptRouterSummaries, 0], 0], +]; +var ListProvisionedModelThroughputsRequest = [ + 3, + n0, + _LPMTR, + 0, + [_cTA, _cTB, _sEt, _mAE, _nC, _mR, _nT, _sB, _sO], + [ + [ + 5, + { + [_hQ]: _cTA, + }, + ], + [ + 5, + { + [_hQ]: _cTB, + }, + ], + [ + 0, + { + [_hQ]: _sEt, + }, + ], + [ + 0, + { + [_hQ]: _mAE, + }, + ], + [ + 0, + { + [_hQ]: _nC, + }, + ], + [ + 1, + { + [_hQ]: _mR, + }, + ], + [ + 0, + { + [_hQ]: _nT, + }, + ], + [ + 0, + { + [_hQ]: _sB, + }, + ], + [ + 0, + { + [_hQ]: _sO, + }, + ], + ], +]; +var ListProvisionedModelThroughputsResponse = [ + 3, + n0, + _LPMTRi, + 0, + [_nT, _pMS], + [0, () => ProvisionedModelSummaries], +]; +var ListTagsForResourceRequest = [3, n0, _LTFRR, 0, [_rARN], [0]]; +var ListTagsForResourceResponse = [3, n0, _LTFRRi, 0, [_ta], [() => TagList]]; +var LoggingConfig = [ + 3, + n0, + _LC, + 0, + [_cWC, _sC, _tDDE, _iDDE, _eDDE, _vDDE], + [() => CloudWatchConfig, () => S3Config, 2, 2, 2, 2], +]; +var MarketplaceModelEndpoint = [ + 3, + n0, + _MME, + 0, + [_eA, _mSI, _s, _sM, _cA, _uA, _eCn, _eS, _eSM], + [0, 0, 0, 0, 5, 5, () => EndpointConfig, 0, 0], +]; +var MarketplaceModelEndpointSummary = [ + 3, + n0, + _MMES, + 0, + [_eA, _mSI, _s, _sM, _cA, _uA], + [0, 0, 0, 0, 5, 5], +]; +var MetadataAttributeSchema = [3, n0, _MAS, 8, [_k, _ty, _d], [0, 0, 0]]; +var MetadataConfigurationForReranking = [ + 3, + n0, + _MCFR, + 0, + [_sMe, _sMC], + [0, [() => RerankingMetadataSelectiveModeConfiguration, 0]], +]; +var ModelCopyJobSummary = [ + 3, + n0, + _MCJS, + 0, + [_jA, _s, _cTr, _tMA, _tMN, _sAI, _sMA, _tMKKA, _tMT, _fMa, _sMN], + [0, 0, 5, 0, 0, 0, 0, 0, () => TagList, 0, 0], +]; +var ModelCustomizationJobSummary = [ + 3, + n0, + _MCJSo, + 0, + [_jA, _bMA, _jN, _s, _sD, _lMT, _cTr, _eT, _cMA, _cMN, _cTu], + [0, 0, 0, 0, () => StatusDetails, 5, 5, 5, 0, 0, 0], +]; +var ModelImportJobSummary = [ + 3, + n0, + _MIJS, + 0, + [_jA, _jN, _s, _lMT, _cTr, _eT, _iMA, _iMN], + [0, 0, 0, 5, 5, 5, 0, 0], +]; +var ModelInvocationJobS3InputDataConfig = [ + 3, + n0, + _MIJSIDC, + 0, + [_sIF, _sU, _sBO], + [0, 0, 0], +]; +var ModelInvocationJobS3OutputDataConfig = [ + 3, + n0, + _MIJSODC, + 0, + [_sU, _sEKI, _sBO], + [0, 0, 0], +]; +var ModelInvocationJobSummary = [ + 3, + n0, + _MIJSo, + 0, + [_jA, _jN, _mIo, _cRT, _rA, _s, _m, _sTu, _lMT, _eT, _iDC, _oDC, _vCp, _tDIH, _jET], + [ + 0, + 0, + 0, + 0, + 0, + 0, + [() => Message, 0], + 5, + 5, + 5, + () => ModelInvocationJobInputDataConfig, + () => ModelInvocationJobOutputDataConfig, + () => VpcConfig, + 1, + 5, + ], +]; +var Offer = [3, n0, _O, 0, [_oI, _oT, _tD], [0, 0, () => TermDetails]]; +var OrchestrationConfiguration = [ + 3, + n0, + _OC, + 0, + [_qTC], + [() => QueryTransformationConfiguration], +]; +var OutputDataConfig = [3, n0, _ODC, 0, [_sU], [0]]; +var PerformanceConfiguration = [3, n0, _PC, 0, [_la], [0]]; +var PricingTerm = [3, n0, _PT, 0, [_rCa], [() => RateCard]]; +var PromptRouterSummary = [ + 3, + n0, + _PRS, + 0, + [_pRN, _rCo, _d, _cA, _uA, _pRA, _mo, _fM, _s, _ty], + [ + 0, + () => RoutingCriteria, + [() => PromptRouterDescription, 0], + 5, + 5, + 0, + () => PromptRouterTargetModels, + () => PromptRouterTargetModel, + 0, + 0, + ], +]; +var PromptRouterTargetModel = [3, n0, _PRTM, 0, [_mA], [0]]; +var PromptTemplate = [3, n0, _PTr, 0, [_tPT], [[() => TextPromptTemplate, 0]]]; +var ProvisionedModelSummary = [ + 3, + n0, + _PMS, + 0, + [_pMN, _pMA, _mA, _dMA, _fMA, _mU, _dMU, _s, _cD, _cET, _cTr, _lMT], + [0, 0, 0, 0, 0, 1, 1, 0, 0, 5, 5, 5], +]; +var PutModelInvocationLoggingConfigurationRequest = [ + 3, + n0, + _PMILCR, + 0, + [_lC], + [() => LoggingConfig], +]; +var PutModelInvocationLoggingConfigurationResponse = [3, n0, _PMILCRu, 0, [], []]; +var PutUseCaseForModelAccessRequest = [3, n0, _PUCFMAR, 0, [_fD], [21]]; +var PutUseCaseForModelAccessResponse = [3, n0, _PUCFMARu, 0, [], []]; +var QueryTransformationConfiguration = [3, n0, _QTC, 0, [_ty], [0]]; +var RatingScaleItem = [3, n0, _RSI, 0, [_de, _va], [0, () => RatingScaleItemValue]]; +var RegisterMarketplaceModelEndpointRequest = [ + 3, + n0, + _RMMER, + 0, + [_eI, _mSI], + [[0, 1], 0], +]; +var RegisterMarketplaceModelEndpointResponse = [ + 3, + n0, + _RMMERe, + 0, + [_mME], + [() => MarketplaceModelEndpoint], +]; +var RequestMetadataBaseFilters = [ + 3, + n0, + _RMBF, + 0, + [_eq, _nE], + [ + [() => RequestMetadataMap, 0], + [() => RequestMetadataMap, 0], + ], +]; +var ResourceInUseException = [ + -3, + n0, + _RIUE, + { + [_e]: _c, + [_hE]: 400, + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(ResourceInUseException, ResourceInUseException$1); +var ResourceNotFoundException = [ + -3, + n0, + _RNFE, + { + [_e]: _c, + [_hE]: 404, + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(ResourceNotFoundException, ResourceNotFoundException$1); +var RetrieveAndGenerateConfiguration = [ + 3, + n0, + _RAGC, + 0, + [_ty, _kBC, _eSC], + [ + 0, + [() => KnowledgeBaseRetrieveAndGenerateConfiguration, 0], + [() => ExternalSourcesRetrieveAndGenerateConfiguration, 0], + ], +]; +var RetrieveConfig = [ + 3, + n0, + _RC, + 0, + [_kBI, _kBRC], + [0, [() => KnowledgeBaseRetrievalConfiguration, 0]], +]; +var RoutingCriteria = [3, n0, _RCo, 0, [_rQD], [1]]; +var S3Config = [3, n0, _SC, 0, [_bN, _kP], [0, 0]]; +var S3DataSource = [3, n0, _SDS, 0, [_sU], [0]]; +var S3ObjectDoc = [3, n0, _SOD, 0, [_uri], [0]]; +var SageMakerEndpoint = [ + 3, + n0, + _SME, + 0, + [_iIC, _iT, _eRx, _kEK, _vp], + [1, 0, 0, 0, () => VpcConfig], +]; +var ServiceQuotaExceededException = [ + -3, + n0, + _SQEE, + { + [_e]: _c, + [_hE]: 400, + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(ServiceQuotaExceededException, ServiceQuotaExceededException$1); +var ServiceUnavailableException = [ + -3, + n0, + _SUE, + { + [_e]: _se, + [_hE]: 503, + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(ServiceUnavailableException, ServiceUnavailableException$1); +var StartAutomatedReasoningPolicyBuildWorkflowRequest = [ + 3, + n0, + _SARPBWR, + 0, + [_pA, _bWT, _cRT, _sCo], + [ + [0, 1], + [0, 1], + [ + 0, + { + [_hH]: _xact, + [_iTd]: 1, + }, + ], + [() => AutomatedReasoningPolicyBuildWorkflowSource, 16], + ], +]; +var StartAutomatedReasoningPolicyBuildWorkflowResponse = [ + 3, + n0, + _SARPBWRt, + 0, + [_pA, _bWI], + [0, 0], +]; +var StartAutomatedReasoningPolicyTestWorkflowRequest = [ + 3, + n0, + _SARPTWR, + 0, + [_pA, _bWI, _tCIe, _cRT], + [[0, 1], [0, 1], 64 | 0, [0, 4]], +]; +var StartAutomatedReasoningPolicyTestWorkflowResponse = [3, n0, _SARPTWRt, 0, [_pA], [0]]; +var StatusDetails = [ + 3, + n0, + _SD, + 0, + [_vD, _dPD, _tDr], + [() => ValidationDetails, () => DataProcessingDetails, () => TrainingDetails], +]; +var StopEvaluationJobRequest = [ + 3, + n0, + _SEJR, + 0, + [_jI], + [[() => EvaluationJobIdentifier, 1]], +]; +var StopEvaluationJobResponse = [3, n0, _SEJRt, 0, [], []]; +var StopModelCustomizationJobRequest = [3, n0, _SMCJR, 0, [_jI], [[0, 1]]]; +var StopModelCustomizationJobResponse = [3, n0, _SMCJRt, 0, [], []]; +var StopModelInvocationJobRequest = [3, n0, _SMIJR, 0, [_jI], [[0, 1]]]; +var StopModelInvocationJobResponse = [3, n0, _SMIJRt, 0, [], []]; +var SupportTerm = [3, n0, _ST, 0, [_rPD], [0]]; +var Tag = [3, n0, _T, 0, [_k, _va], [0, 0]]; +var TagResourceRequest = [3, n0, _TRR, 0, [_rARN, _ta], [0, () => TagList]]; +var TagResourceResponse = [3, n0, _TRRa, 0, [], []]; +var TeacherModelConfig = [3, n0, _TMC, 0, [_tMI, _mRLFI], [0, 1]]; +var TermDetails = [ + 3, + n0, + _TD, + 0, + [_uBPT, _lT, _sTup, _vT], + [() => PricingTerm, () => LegalTerm, () => SupportTerm, () => ValidityTerm], +]; +var TextInferenceConfig = [3, n0, _TIC, 0, [_tem, _tPo, _mTa, _sS], [1, 1, 1, 64 | 0]]; +var ThrottlingException = [ + -3, + n0, + _TE, + { + [_e]: _c, + [_hE]: 429, + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(ThrottlingException, ThrottlingException$1); +var TooManyTagsException = [ + -3, + n0, + _TMTE, + { + [_e]: _c, + [_hE]: 400, + }, + [_m, _rN], + [0, 0], +]; +schema.TypeRegistry.for(n0).registerError(TooManyTagsException, TooManyTagsException$1); +var TrainingDataConfig = [ + 3, + n0, + _TDC, + 0, + [_sU, _iLC], + [0, [() => InvocationLogsConfig, 0]], +]; +var TrainingDetails = [3, n0, _TDr, 0, [_s, _cTr, _lMT], [0, 5, 5]]; +var TrainingMetrics = [3, n0, _TM, 0, [_tL], [1]]; +var UntagResourceRequest = [3, n0, _URR, 0, [_rARN, _tK], [0, 64 | 0]]; +var UntagResourceResponse = [3, n0, _URRn, 0, [], []]; +var UpdateAutomatedReasoningPolicyAnnotationsRequest = [ + 3, + n0, + _UARPAR, + 0, + [_pA, _bWI, _an, _lUASH], + [[0, 1], [0, 1], [() => AutomatedReasoningPolicyAnnotationList, 0], 0], +]; +var UpdateAutomatedReasoningPolicyAnnotationsResponse = [ + 3, + n0, + _UARPARp, + 0, + [_pA, _bWI, _aSH, _uA], + [0, 0, 0, 5], +]; +var UpdateAutomatedReasoningPolicyRequest = [ + 3, + n0, + _UARPR, + 0, + [_pA, _pD, _n, _d], + [ + [0, 1], + [() => AutomatedReasoningPolicyDefinition, 0], + [() => AutomatedReasoningPolicyName, 0], + [() => AutomatedReasoningPolicyDescription, 0], + ], +]; +var UpdateAutomatedReasoningPolicyResponse = [ + 3, + n0, + _UARPRp, + 0, + [_pA, _n, _dH, _uA], + [0, [() => AutomatedReasoningPolicyName, 0], 0, 5], +]; +var UpdateAutomatedReasoningPolicyTestCaseRequest = [ + 3, + n0, + _UARPTCR, + 0, + [_pA, _tCI, _gC, _qC, _lUA, _eAFR, _cT, _cRT], + [ + [0, 1], + [0, 1], + [() => AutomatedReasoningPolicyTestGuardContent, 0], + [() => AutomatedReasoningPolicyTestQueryContent, 0], + 5, + 0, + 1, + [0, 4], + ], +]; +var UpdateAutomatedReasoningPolicyTestCaseResponse = [ + 3, + n0, + _UARPTCRp, + 0, + [_pA, _tCI], + [0, 0], +]; +var UpdateGuardrailRequest = [ + 3, + n0, + _UGR, + 0, + [_gIu, _n, _d, _tPC, _cPC, _wPC, _sIPC, _cGPC, _aRPC, _cRC, _bIM, _bOM, _kKI], + [ + [0, 1], + [() => GuardrailName, 0], + [() => GuardrailDescription, 0], + [() => GuardrailTopicPolicyConfig, 0], + [() => GuardrailContentPolicyConfig, 0], + [() => GuardrailWordPolicyConfig, 0], + () => GuardrailSensitiveInformationPolicyConfig, + [() => GuardrailContextualGroundingPolicyConfig, 0], + () => GuardrailAutomatedReasoningPolicyConfig, + () => GuardrailCrossRegionConfig, + [() => GuardrailBlockedMessaging, 0], + [() => GuardrailBlockedMessaging, 0], + 0, + ], +]; +var UpdateGuardrailResponse = [3, n0, _UGRp, 0, [_gI, _gA, _ve, _uA], [0, 0, 0, 5]]; +var UpdateMarketplaceModelEndpointRequest = [ + 3, + n0, + _UMMER, + 0, + [_eA, _eCn, _cRT], + [[0, 1], () => EndpointConfig, [0, 4]], +]; +var UpdateMarketplaceModelEndpointResponse = [ + 3, + n0, + _UMMERp, + 0, + [_mME], + [() => MarketplaceModelEndpoint], +]; +var UpdateProvisionedModelThroughputRequest = [ + 3, + n0, + _UPMTR, + 0, + [_pMI, _dPMN, _dMI], + [[0, 1], 0, 0], +]; +var UpdateProvisionedModelThroughputResponse = [3, n0, _UPMTRp, 0, [], []]; +var ValidationDataConfig = [3, n0, _VDC, 0, [_val], [() => Validators]]; +var ValidationDetails = [3, n0, _VD, 0, [_s, _cTr, _lMT], [0, 5, 5]]; +var ValidationException = [ + -3, + n0, + _VE, + { + [_e]: _c, + [_hE]: 400, + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(ValidationException, ValidationException$1); +var Validator = [3, n0, _V, 0, [_sU], [0]]; +var ValidatorMetric = [3, n0, _VM, 0, [_vL], [1]]; +var ValidityTerm = [3, n0, _VT, 0, [_aD], [0]]; +var VectorSearchBedrockRerankingConfiguration = [ + 3, + n0, + _VSBRC, + 0, + [_mC, _nORR, _mCe], + [() => VectorSearchBedrockRerankingModelConfiguration, 1, [() => MetadataConfigurationForReranking, 0]], +]; +var VectorSearchBedrockRerankingModelConfiguration = [ + 3, + n0, + _VSBRMC, + 0, + [_mA, _aMRF], + [0, 128 | 15], +]; +var VectorSearchRerankingConfiguration = [ + 3, + n0, + _VSRC, + 0, + [_ty, _bRC], + [0, [() => VectorSearchBedrockRerankingConfiguration, 0]], +]; +var VpcConfig = [3, n0, _VC, 0, [_sI, _sGI], [64 | 0, 64 | 0]]; +var BedrockServiceException = [-3, _sm, "BedrockServiceException", 0, [], []]; +schema.TypeRegistry.for(_sm).registerError(BedrockServiceException, BedrockServiceException$1); +var AutomatedEvaluationCustomMetrics = [ + 1, + n0, + _AECM, + 0, + [() => AutomatedEvaluationCustomMetricSource, 0], +]; +var AutomatedReasoningCheckDifferenceScenarioList = [ + 1, + n0, + _ARCDSL, + 0, + [() => AutomatedReasoningCheckScenario, 0], +]; +var AutomatedReasoningCheckFindingList = [ + 1, + n0, + _ARCFL, + 0, + [() => AutomatedReasoningCheckFinding, 0], +]; +var AutomatedReasoningCheckInputTextReferenceList = [ + 1, + n0, + _ARCITRL, + 0, + [() => AutomatedReasoningCheckInputTextReference, 0], +]; +var AutomatedReasoningCheckRuleList = [1, n0, _ARCRL, 0, () => AutomatedReasoningCheckRule]; +var AutomatedReasoningCheckTranslationList = [ + 1, + n0, + _ARCTL, + 0, + [() => AutomatedReasoningCheckTranslation, 0], +]; +var AutomatedReasoningCheckTranslationOptionList = [ + 1, + n0, + _ARCTOL, + 0, + [() => AutomatedReasoningCheckTranslationOption, 0], +]; +var AutomatedReasoningLogicStatementList = [ + 1, + n0, + _ARLSL, + 0, + [() => AutomatedReasoningLogicStatement, 0], +]; +var AutomatedReasoningPolicyAnnotationList = [ + 1, + n0, + _ARPAL, + 0, + [() => AutomatedReasoningPolicyAnnotation, 0], +]; +var AutomatedReasoningPolicyBuildLogEntryList = [ + 1, + n0, + _ARPBLEL, + 0, + [() => AutomatedReasoningPolicyBuildLogEntry, 0], +]; +var AutomatedReasoningPolicyBuildStepList = [ + 1, + n0, + _ARPBSL, + 0, + [() => AutomatedReasoningPolicyBuildStep, 0], +]; +var AutomatedReasoningPolicyBuildStepMessageList = [ + 1, + n0, + _ARPBSML, + 0, + () => AutomatedReasoningPolicyBuildStepMessage, +]; +var AutomatedReasoningPolicyBuildWorkflowDocumentList = [ + 1, + n0, + _ARPBWDL, + 0, + [() => AutomatedReasoningPolicyBuildWorkflowDocument, 0], +]; +var AutomatedReasoningPolicyBuildWorkflowSummaries = [ + 1, + n0, + _ARPBWSut, + 0, + () => AutomatedReasoningPolicyBuildWorkflowSummary, +]; +var AutomatedReasoningPolicyDefinitionRuleList = [ + 1, + n0, + _ARPDRL, + 0, + [() => AutomatedReasoningPolicyDefinitionRule, 0], +]; +var AutomatedReasoningPolicyDefinitionTypeList = [ + 1, + n0, + _ARPDTL, + 0, + [() => AutomatedReasoningPolicyDefinitionType, 0], +]; +var AutomatedReasoningPolicyDefinitionTypeNameList = [ + 1, + n0, + _ARPDTNL, + 0, + [() => AutomatedReasoningPolicyDefinitionTypeName, 0], +]; +var AutomatedReasoningPolicyDefinitionTypeValueList = [ + 1, + n0, + _ARPDTVL, + 0, + [() => AutomatedReasoningPolicyDefinitionTypeValue, 0], +]; +var AutomatedReasoningPolicyDefinitionTypeValuePairList = [ + 1, + n0, + _ARPDTVPL, + 0, + [() => AutomatedReasoningPolicyDefinitionTypeValuePair, 0], +]; +var AutomatedReasoningPolicyDefinitionVariableList = [ + 1, + n0, + _ARPDVL, + 0, + [() => AutomatedReasoningPolicyDefinitionVariable, 0], +]; +var AutomatedReasoningPolicyDefinitionVariableNameList = [ + 1, + n0, + _ARPDVNL, + 0, + [() => AutomatedReasoningPolicyDefinitionVariableName, 0], +]; +var AutomatedReasoningPolicyDisjointRuleSetList = [ + 1, + n0, + _ARPDRSL, + 0, + [() => AutomatedReasoningPolicyDisjointRuleSet, 0], +]; +var AutomatedReasoningPolicyGeneratedTestCaseList = [ + 1, + n0, + _ARPGTCL, + 0, + [() => AutomatedReasoningPolicyGeneratedTestCase, 0], +]; +var AutomatedReasoningPolicySummaries = [ + 1, + n0, + _ARPSut, + 0, + [() => AutomatedReasoningPolicySummary, 0], +]; +var AutomatedReasoningPolicyTestCaseList = [ + 1, + n0, + _ARPTCL, + 0, + [() => AutomatedReasoningPolicyTestCase, 0], +]; +var AutomatedReasoningPolicyTestList = [ + 1, + n0, + _ARPTL, + 0, + [() => AutomatedReasoningPolicyTestResult, 0], +]; +var AutomatedReasoningPolicyTypeValueAnnotationList = [ + 1, + n0, + _ARPTVAL, + 0, + [() => AutomatedReasoningPolicyTypeValueAnnotation, 0], +]; +var BatchDeleteEvaluationJobErrors = [ + 1, + n0, + _BDEJEa, + 0, + [() => BatchDeleteEvaluationJobError, 0], +]; +var BatchDeleteEvaluationJobItems = [ + 1, + n0, + _BDEJIa, + 0, + [() => BatchDeleteEvaluationJobItem, 0], +]; +var BedrockEvaluatorModels = [1, n0, _BEMe, 0, () => BedrockEvaluatorModel]; +var CustomMetricBedrockEvaluatorModels = [ + 1, + n0, + _CMBEMu, + 0, + () => CustomMetricBedrockEvaluatorModel, +]; +var CustomModelDeploymentSummaryList = [1, n0, _CMDSL, 0, () => CustomModelDeploymentSummary]; +var CustomModelSummaryList = [1, n0, _CMSL, 0, () => CustomModelSummary]; +var EvaluationDatasetMetricConfigs = [ + 1, + n0, + _EDMCv, + 0, + [() => EvaluationDatasetMetricConfig, 0], +]; +var EvaluationJobIdentifiers = [1, n0, _EJIv, 0, [() => EvaluationJobIdentifier, 0]]; +var EvaluationMetricNames = [1, n0, _EMNv, 0, [() => EvaluationMetricName, 0]]; +var EvaluationModelConfigs = [1, n0, _EMC, 0, [() => EvaluationModelConfig, 0]]; +var EvaluationSummaries = [1, n0, _ESv, 0, () => EvaluationSummary]; +var ExternalSources = [1, n0, _ESxt, 0, [() => ExternalSource, 0]]; +var FieldsForReranking = [1, n0, _FFRi, 8, () => FieldForReranking]; +var FoundationModelSummaryList = [1, n0, _FMSL, 0, () => FoundationModelSummary]; +var GuardrailContentFilters = [1, n0, _GCFu, 0, [() => GuardrailContentFilter, 0]]; +var GuardrailContentFiltersConfig = [ + 1, + n0, + _GCFCu, + 0, + [() => GuardrailContentFilterConfig, 0], +]; +var GuardrailContextualGroundingFilters = [ + 1, + n0, + _GCGFu, + 0, + [() => GuardrailContextualGroundingFilter, 0], +]; +var GuardrailContextualGroundingFiltersConfig = [ + 1, + n0, + _GCGFCu, + 0, + [() => GuardrailContextualGroundingFilterConfig, 0], +]; +var GuardrailFailureRecommendations = [ + 1, + n0, + _GFRu, + 0, + [() => GuardrailFailureRecommendation, 0], +]; +var GuardrailManagedWordLists = [1, n0, _GMWL, 0, [() => GuardrailManagedWords, 0]]; +var GuardrailManagedWordListsConfig = [ + 1, + n0, + _GMWLC, + 0, + [() => GuardrailManagedWordsConfig, 0], +]; +var GuardrailModalities = [1, n0, _GMu, 0, [() => GuardrailModality$1, 0]]; +var GuardrailPiiEntities = [1, n0, _GPEu, 0, () => GuardrailPiiEntity]; +var GuardrailPiiEntitiesConfig = [1, n0, _GPECu, 0, () => GuardrailPiiEntityConfig]; +var GuardrailRegexes = [1, n0, _GRu, 0, () => GuardrailRegex]; +var GuardrailRegexesConfig = [1, n0, _GRCu, 0, () => GuardrailRegexConfig]; +var GuardrailStatusReasons = [1, n0, _GSRu, 0, [() => GuardrailStatusReason, 0]]; +var GuardrailSummaries = [1, n0, _GSu, 0, [() => GuardrailSummary, 0]]; +var GuardrailTopicExamples = [1, n0, _GTEu, 0, [() => GuardrailTopicExample, 0]]; +var GuardrailTopics = [1, n0, _GTu, 0, [() => GuardrailTopic, 0]]; +var GuardrailTopicsConfig = [1, n0, _GTCu, 0, [() => GuardrailTopicConfig, 0]]; +var GuardrailWords = [1, n0, _GWu, 0, [() => GuardrailWord, 0]]; +var GuardrailWordsConfig = [1, n0, _GWCu, 0, [() => GuardrailWordConfig, 0]]; +var HumanEvaluationCustomMetrics = [1, n0, _HECMu, 0, [() => HumanEvaluationCustomMetric, 0]]; +var ImportedModelSummaryList = [1, n0, _IMSL, 0, () => ImportedModelSummary]; +var InferenceProfileModels = [1, n0, _IPMn, 0, () => InferenceProfileModel]; +var InferenceProfileSummaries = [1, n0, _IPSn, 0, [() => InferenceProfileSummary, 0]]; +var MarketplaceModelEndpointSummaries = [ + 1, + n0, + _MMESa, + 0, + () => MarketplaceModelEndpointSummary, +]; +var MetadataAttributeSchemaList = [1, n0, _MASL, 0, [() => MetadataAttributeSchema, 0]]; +var ModelCopyJobSummaries = [1, n0, _MCJSod, 0, () => ModelCopyJobSummary]; +var ModelCustomizationJobSummaries = [1, n0, _MCJSode, 0, () => ModelCustomizationJobSummary]; +var ModelImportJobSummaries = [1, n0, _MIJSod, 0, () => ModelImportJobSummary]; +var ModelInvocationJobSummaries = [1, n0, _MIJSode, 0, [() => ModelInvocationJobSummary, 0]]; +var Offers = [1, n0, _Of, 0, () => Offer]; +var PromptRouterSummaries = [1, n0, _PRSr, 0, [() => PromptRouterSummary, 0]]; +var PromptRouterTargetModels = [1, n0, _PRTMr, 0, () => PromptRouterTargetModel]; +var ProvisionedModelSummaries = [1, n0, _PMSr, 0, () => ProvisionedModelSummary]; +var RagConfigs = [1, n0, _RCa, 0, [() => RAGConfig, 0]]; +var RateCard = [1, n0, _RCat, 0, () => DimensionalPriceRate]; +var RatingScale = [1, n0, _RS, 0, () => RatingScaleItem]; +var RequestMetadataFiltersList = [1, n0, _RMFL, 0, [() => RequestMetadataBaseFilters, 0]]; +var RetrievalFilterList = [1, n0, _RFL, 0, [() => RetrievalFilter, 0]]; +var TagList = [1, n0, _TL, 0, () => Tag]; +var ValidationMetrics = [1, n0, _VMa, 0, () => ValidatorMetric]; +var Validators = [1, n0, _Va, 0, () => Validator]; +var RequestMetadataMap = [2, n0, _RMM, 8, 0, 0]; +var AutomatedEvaluationCustomMetricSource = [ + 3, + n0, + _AECMS, + 0, + [_cMD], + [[() => CustomMetricDefinition, 0]], +]; +var AutomatedReasoningCheckFinding = [ + 3, + n0, + _ARCF, + 0, + [_vali, _inv, _sa, _im, _tA, _tCoo, _nTo], + [ + [() => AutomatedReasoningCheckValidFinding, 0], + [() => AutomatedReasoningCheckInvalidFinding, 0], + [() => AutomatedReasoningCheckSatisfiableFinding, 0], + [() => AutomatedReasoningCheckImpossibleFinding, 0], + [() => AutomatedReasoningCheckTranslationAmbiguousFinding, 0], + () => AutomatedReasoningCheckTooComplexFinding, + () => AutomatedReasoningCheckNoTranslationsFinding, + ], +]; +var AutomatedReasoningPolicyAnnotation = [ + 3, + n0, + _ARPA, + 0, + [_aTd, _uTp, _dT, _aV, _uVp, _dV, _aR, _uR, _dR, _aRFNL, _uFRF, _uFSF, _iCn], + [ + [() => AutomatedReasoningPolicyAddTypeAnnotation, 0], + [() => AutomatedReasoningPolicyUpdateTypeAnnotation, 0], + [() => AutomatedReasoningPolicyDeleteTypeAnnotation, 0], + [() => AutomatedReasoningPolicyAddVariableAnnotation, 0], + [() => AutomatedReasoningPolicyUpdateVariableAnnotation, 0], + [() => AutomatedReasoningPolicyDeleteVariableAnnotation, 0], + [() => AutomatedReasoningPolicyAddRuleAnnotation, 0], + [() => AutomatedReasoningPolicyUpdateRuleAnnotation, 0], + () => AutomatedReasoningPolicyDeleteRuleAnnotation, + [() => AutomatedReasoningPolicyAddRuleFromNaturalLanguageAnnotation, 0], + [() => AutomatedReasoningPolicyUpdateFromRuleFeedbackAnnotation, 0], + [() => AutomatedReasoningPolicyUpdateFromScenarioFeedbackAnnotation, 0], + [() => AutomatedReasoningPolicyIngestContentAnnotation, 0], + ], +]; +var AutomatedReasoningPolicyBuildResultAssets = [ + 3, + n0, + _ARPBRA, + 0, + [_pD, _qR, _bL, _gTC], + [ + [() => AutomatedReasoningPolicyDefinition, 0], + [() => AutomatedReasoningPolicyDefinitionQualityReport, 0], + [() => AutomatedReasoningPolicyBuildLog, 0], + [() => AutomatedReasoningPolicyGeneratedTestCases, 0], + ], +]; +var AutomatedReasoningPolicyBuildStepContext = [ + 3, + n0, + _ARPBSC, + 0, + [_pl, _mu], + [() => AutomatedReasoningPolicyPlanning, [() => AutomatedReasoningPolicyMutation, 0]], +]; +var AutomatedReasoningPolicyDefinitionElement = [ + 3, + n0, + _ARPDE, + 0, + [_pDV, _pDT, _pDR], + [ + [() => AutomatedReasoningPolicyDefinitionVariable, 0], + [() => AutomatedReasoningPolicyDefinitionType, 0], + [() => AutomatedReasoningPolicyDefinitionRule, 0], + ], +]; +var AutomatedReasoningPolicyMutation = [ + 3, + n0, + _ARPM, + 0, + [_aTd, _uTp, _dT, _aV, _uVp, _dV, _aR, _uR, _dR], + [ + [() => AutomatedReasoningPolicyAddTypeMutation, 0], + [() => AutomatedReasoningPolicyUpdateTypeMutation, 0], + [() => AutomatedReasoningPolicyDeleteTypeMutation, 0], + [() => AutomatedReasoningPolicyAddVariableMutation, 0], + [() => AutomatedReasoningPolicyUpdateVariableMutation, 0], + [() => AutomatedReasoningPolicyDeleteVariableMutation, 0], + [() => AutomatedReasoningPolicyAddRuleMutation, 0], + [() => AutomatedReasoningPolicyUpdateRuleMutation, 0], + () => AutomatedReasoningPolicyDeleteRuleMutation, + ], +]; +var AutomatedReasoningPolicyTypeValueAnnotation = [ + 3, + n0, + _ARPTVA, + 0, + [_aTV, _uTVp, _dTV], + [ + [() => AutomatedReasoningPolicyAddTypeValue, 0], + [() => AutomatedReasoningPolicyUpdateTypeValue, 0], + () => AutomatedReasoningPolicyDeleteTypeValue, + ], +]; +var AutomatedReasoningPolicyWorkflowTypeContent = [ + 3, + n0, + _ARPWTC, + 0, + [_doc, _pRAo], + [ + [() => AutomatedReasoningPolicyBuildWorkflowDocumentList, 0], + [() => AutomatedReasoningPolicyBuildWorkflowRepairContent, 0], + ], +]; +var CustomizationConfig = [3, n0, _CC, 0, [_dC], [() => DistillationConfig]]; +var EndpointConfig = [3, n0, _EC, 0, [_sMa], [() => SageMakerEndpoint]]; +var EvaluationConfig = [ + 3, + n0, + _ECv, + 0, + [_au, _h], + [ + [() => AutomatedEvaluationConfig, 0], + [() => HumanEvaluationConfig, 0], + ], +]; +var EvaluationDatasetLocation = [3, n0, _EDL, 0, [_sU], [0]]; +var EvaluationInferenceConfig = [ + 3, + n0, + _EIC, + 0, + [_mo, _rCag], + [ + [() => EvaluationModelConfigs, 0], + [() => RagConfigs, 0], + ], +]; +var EvaluationModelConfig = [ + 3, + n0, + _EMCv, + 0, + [_bM, _pIS], + [[() => EvaluationBedrockModel, 0], () => EvaluationPrecomputedInferenceSource], +]; +var EvaluationPrecomputedRagSourceConfig = [ + 3, + n0, + _EPRSCv, + 0, + [_rSC, _rAGSC], + [() => EvaluationPrecomputedRetrieveSourceConfig, () => EvaluationPrecomputedRetrieveAndGenerateSourceConfig], +]; +var EvaluatorModelConfig = [3, n0, _EMCva, 0, [_bEM], [() => BedrockEvaluatorModels]]; +var InferenceProfileModelSource = [3, n0, _IPMS, 0, [_cF], [0]]; +var InvocationLogSource = [3, n0, _ILS, 0, [_sU], [0]]; +var KnowledgeBaseConfig = [ + 3, + n0, + _KBC, + 0, + [_rCetr, _rAGC], + [ + [() => RetrieveConfig, 0], + [() => RetrieveAndGenerateConfiguration, 0], + ], +]; +var ModelDataSource = [3, n0, _MDS, 0, [_sDS], [() => S3DataSource]]; +var ModelInvocationJobInputDataConfig = [ + 3, + n0, + _MIJIDC, + 0, + [_sIDC], + [() => ModelInvocationJobS3InputDataConfig], +]; +var ModelInvocationJobOutputDataConfig = [ + 3, + n0, + _MIJODC, + 0, + [_sODC], + [() => ModelInvocationJobS3OutputDataConfig], +]; +var RAGConfig = [ + 3, + n0, + _RAGCo, + 0, + [_kBCn, _pRSC], + [[() => KnowledgeBaseConfig, 0], () => EvaluationPrecomputedRagSourceConfig], +]; +var RatingScaleItemValue = [3, n0, _RSIV, 0, [_sV, _fV], [0, 1]]; +var RequestMetadataFilters = [ + 3, + n0, + _RMF, + 0, + [_eq, _nE, _aAn, _oAr], + [ + [() => RequestMetadataMap, 0], + [() => RequestMetadataMap, 0], + [() => RequestMetadataFiltersList, 0], + [() => RequestMetadataFiltersList, 0], + ], +]; +var RerankingMetadataSelectiveModeConfiguration = [ + 3, + n0, + _RMSMC, + 0, + [_fTI, _fTE], + [ + [() => FieldsForReranking, 0], + [() => FieldsForReranking, 0], + ], +]; +var RetrievalFilter = [ + 3, + n0, + _RF, + 8, + [_eq, _nE, _gT, _gTOE, _lTe, _lTOE, _in_, _nI, _sW, _lCi, _sCt, _aAn, _oAr], + [ + () => FilterAttribute, + () => FilterAttribute, + () => FilterAttribute, + () => FilterAttribute, + () => FilterAttribute, + () => FilterAttribute, + () => FilterAttribute, + () => FilterAttribute, + () => FilterAttribute, + () => FilterAttribute, + () => FilterAttribute, + [() => RetrievalFilterList, 0], + [() => RetrievalFilterList, 0], + ], +]; +var BatchDeleteEvaluationJob = [ + 9, + n0, + _BDEJ, + { + [_ht]: ["POST", "/evaluation-jobs/batch-delete", 202], + }, + () => BatchDeleteEvaluationJobRequest, + () => BatchDeleteEvaluationJobResponse, +]; +var CancelAutomatedReasoningPolicyBuildWorkflow = [ + 9, + n0, + _CARPBW, + { + [_ht]: ["POST", "/automated-reasoning-policies/{policyArn}/build-workflows/{buildWorkflowId}/cancel", 202], + }, + () => CancelAutomatedReasoningPolicyBuildWorkflowRequest, + () => CancelAutomatedReasoningPolicyBuildWorkflowResponse, +]; +var CreateAutomatedReasoningPolicy = [ + 9, + n0, + _CARP, + { + [_ht]: ["POST", "/automated-reasoning-policies", 200], + }, + () => CreateAutomatedReasoningPolicyRequest, + () => CreateAutomatedReasoningPolicyResponse, +]; +var CreateAutomatedReasoningPolicyTestCase = [ + 9, + n0, + _CARPTC, + { + [_ht]: ["POST", "/automated-reasoning-policies/{policyArn}/test-cases", 200], + }, + () => CreateAutomatedReasoningPolicyTestCaseRequest, + () => CreateAutomatedReasoningPolicyTestCaseResponse, +]; +var CreateAutomatedReasoningPolicyVersion = [ + 9, + n0, + _CARPV, + { + [_ht]: ["POST", "/automated-reasoning-policies/{policyArn}/versions", 200], + }, + () => CreateAutomatedReasoningPolicyVersionRequest, + () => CreateAutomatedReasoningPolicyVersionResponse, +]; +var CreateCustomModel = [ + 9, + n0, + _CCM, + { + [_ht]: ["POST", "/custom-models/create-custom-model", 202], + }, + () => CreateCustomModelRequest, + () => CreateCustomModelResponse, +]; +var CreateCustomModelDeployment = [ + 9, + n0, + _CCMD, + { + [_ht]: ["POST", "/model-customization/custom-model-deployments", 202], + }, + () => CreateCustomModelDeploymentRequest, + () => CreateCustomModelDeploymentResponse, +]; +var CreateEvaluationJob = [ + 9, + n0, + _CEJ, + { + [_ht]: ["POST", "/evaluation-jobs", 202], + }, + () => CreateEvaluationJobRequest, + () => CreateEvaluationJobResponse, +]; +var CreateFoundationModelAgreement = [ + 9, + n0, + _CFMA, + { + [_ht]: ["POST", "/create-foundation-model-agreement", 202], + }, + () => CreateFoundationModelAgreementRequest, + () => CreateFoundationModelAgreementResponse, +]; +var CreateGuardrail = [ + 9, + n0, + _CG, + { + [_ht]: ["POST", "/guardrails", 202], + }, + () => CreateGuardrailRequest, + () => CreateGuardrailResponse, +]; +var CreateGuardrailVersion = [ + 9, + n0, + _CGV, + { + [_ht]: ["POST", "/guardrails/{guardrailIdentifier}", 202], + }, + () => CreateGuardrailVersionRequest, + () => CreateGuardrailVersionResponse, +]; +var CreateInferenceProfile = [ + 9, + n0, + _CIP, + { + [_ht]: ["POST", "/inference-profiles", 201], + }, + () => CreateInferenceProfileRequest, + () => CreateInferenceProfileResponse, +]; +var CreateMarketplaceModelEndpoint = [ + 9, + n0, + _CMME, + { + [_ht]: ["POST", "/marketplace-model/endpoints", 200], + }, + () => CreateMarketplaceModelEndpointRequest, + () => CreateMarketplaceModelEndpointResponse, +]; +var CreateModelCopyJob = [ + 9, + n0, + _CMCJ, + { + [_ht]: ["POST", "/model-copy-jobs", 201], + }, + () => CreateModelCopyJobRequest, + () => CreateModelCopyJobResponse, +]; +var CreateModelCustomizationJob = [ + 9, + n0, + _CMCJr, + { + [_ht]: ["POST", "/model-customization-jobs", 201], + }, + () => CreateModelCustomizationJobRequest, + () => CreateModelCustomizationJobResponse, +]; +var CreateModelImportJob = [ + 9, + n0, + _CMIJ, + { + [_ht]: ["POST", "/model-import-jobs", 201], + }, + () => CreateModelImportJobRequest, + () => CreateModelImportJobResponse, +]; +var CreateModelInvocationJob = [ + 9, + n0, + _CMIJr, + { + [_ht]: ["POST", "/model-invocation-job", 200], + }, + () => CreateModelInvocationJobRequest, + () => CreateModelInvocationJobResponse, +]; +var CreatePromptRouter = [ + 9, + n0, + _CPR, + { + [_ht]: ["POST", "/prompt-routers", 200], + }, + () => CreatePromptRouterRequest, + () => CreatePromptRouterResponse, +]; +var CreateProvisionedModelThroughput = [ + 9, + n0, + _CPMT, + { + [_ht]: ["POST", "/provisioned-model-throughput", 201], + }, + () => CreateProvisionedModelThroughputRequest, + () => CreateProvisionedModelThroughputResponse, +]; +var DeleteAutomatedReasoningPolicy = [ + 9, + n0, + _DARP, + { + [_ht]: ["DELETE", "/automated-reasoning-policies/{policyArn}", 202], + }, + () => DeleteAutomatedReasoningPolicyRequest, + () => DeleteAutomatedReasoningPolicyResponse, +]; +var DeleteAutomatedReasoningPolicyBuildWorkflow = [ + 9, + n0, + _DARPBW, + { + [_ht]: ["DELETE", "/automated-reasoning-policies/{policyArn}/build-workflows/{buildWorkflowId}", 202], + }, + () => DeleteAutomatedReasoningPolicyBuildWorkflowRequest, + () => DeleteAutomatedReasoningPolicyBuildWorkflowResponse, +]; +var DeleteAutomatedReasoningPolicyTestCase = [ + 9, + n0, + _DARPTC, + { + [_ht]: ["DELETE", "/automated-reasoning-policies/{policyArn}/test-cases/{testCaseId}", 202], + }, + () => DeleteAutomatedReasoningPolicyTestCaseRequest, + () => DeleteAutomatedReasoningPolicyTestCaseResponse, +]; +var DeleteCustomModel = [ + 9, + n0, + _DCM, + { + [_ht]: ["DELETE", "/custom-models/{modelIdentifier}", 200], + }, + () => DeleteCustomModelRequest, + () => DeleteCustomModelResponse, +]; +var DeleteCustomModelDeployment = [ + 9, + n0, + _DCMD, + { + [_ht]: ["DELETE", "/model-customization/custom-model-deployments/{customModelDeploymentIdentifier}", 200], + }, + () => DeleteCustomModelDeploymentRequest, + () => DeleteCustomModelDeploymentResponse, +]; +var DeleteFoundationModelAgreement = [ + 9, + n0, + _DFMA, + { + [_ht]: ["POST", "/delete-foundation-model-agreement", 202], + }, + () => DeleteFoundationModelAgreementRequest, + () => DeleteFoundationModelAgreementResponse, +]; +var DeleteGuardrail = [ + 9, + n0, + _DG, + { + [_ht]: ["DELETE", "/guardrails/{guardrailIdentifier}", 202], + }, + () => DeleteGuardrailRequest, + () => DeleteGuardrailResponse, +]; +var DeleteImportedModel = [ + 9, + n0, + _DIM, + { + [_ht]: ["DELETE", "/imported-models/{modelIdentifier}", 200], + }, + () => DeleteImportedModelRequest, + () => DeleteImportedModelResponse, +]; +var DeleteInferenceProfile = [ + 9, + n0, + _DIP, + { + [_ht]: ["DELETE", "/inference-profiles/{inferenceProfileIdentifier}", 200], + }, + () => DeleteInferenceProfileRequest, + () => DeleteInferenceProfileResponse, +]; +var DeleteMarketplaceModelEndpoint = [ + 9, + n0, + _DMME, + { + [_ht]: ["DELETE", "/marketplace-model/endpoints/{endpointArn}", 200], + }, + () => DeleteMarketplaceModelEndpointRequest, + () => DeleteMarketplaceModelEndpointResponse, +]; +var DeleteModelInvocationLoggingConfiguration = [ + 9, + n0, + _DMILC, + { + [_ht]: ["DELETE", "/logging/modelinvocations", 200], + }, + () => DeleteModelInvocationLoggingConfigurationRequest, + () => DeleteModelInvocationLoggingConfigurationResponse, +]; +var DeletePromptRouter = [ + 9, + n0, + _DPRe, + { + [_ht]: ["DELETE", "/prompt-routers/{promptRouterArn}", 200], + }, + () => DeletePromptRouterRequest, + () => DeletePromptRouterResponse, +]; +var DeleteProvisionedModelThroughput = [ + 9, + n0, + _DPMT, + { + [_ht]: ["DELETE", "/provisioned-model-throughput/{provisionedModelId}", 200], + }, + () => DeleteProvisionedModelThroughputRequest, + () => DeleteProvisionedModelThroughputResponse, +]; +var DeregisterMarketplaceModelEndpoint = [ + 9, + n0, + _DMMEe, + { + [_ht]: ["DELETE", "/marketplace-model/endpoints/{endpointArn}/registration", 200], + }, + () => DeregisterMarketplaceModelEndpointRequest, + () => DeregisterMarketplaceModelEndpointResponse, +]; +var ExportAutomatedReasoningPolicyVersion = [ + 9, + n0, + _EARPV, + { + [_ht]: ["GET", "/automated-reasoning-policies/{policyArn}/export", 200], + }, + () => ExportAutomatedReasoningPolicyVersionRequest, + () => ExportAutomatedReasoningPolicyVersionResponse, +]; +var GetAutomatedReasoningPolicy = [ + 9, + n0, + _GARPe, + { + [_ht]: ["GET", "/automated-reasoning-policies/{policyArn}", 200], + }, + () => GetAutomatedReasoningPolicyRequest, + () => GetAutomatedReasoningPolicyResponse, +]; +var GetAutomatedReasoningPolicyAnnotations = [ + 9, + n0, + _GARPA, + { + [_ht]: ["GET", "/automated-reasoning-policies/{policyArn}/build-workflows/{buildWorkflowId}/annotations", 200], + }, + () => GetAutomatedReasoningPolicyAnnotationsRequest, + () => GetAutomatedReasoningPolicyAnnotationsResponse, +]; +var GetAutomatedReasoningPolicyBuildWorkflow = [ + 9, + n0, + _GARPBW, + { + [_ht]: ["GET", "/automated-reasoning-policies/{policyArn}/build-workflows/{buildWorkflowId}", 200], + }, + () => GetAutomatedReasoningPolicyBuildWorkflowRequest, + () => GetAutomatedReasoningPolicyBuildWorkflowResponse, +]; +var GetAutomatedReasoningPolicyBuildWorkflowResultAssets = [ + 9, + n0, + _GARPBWRA, + { + [_ht]: ["GET", "/automated-reasoning-policies/{policyArn}/build-workflows/{buildWorkflowId}/result-assets", 200], + }, + () => GetAutomatedReasoningPolicyBuildWorkflowResultAssetsRequest, + () => GetAutomatedReasoningPolicyBuildWorkflowResultAssetsResponse, +]; +var GetAutomatedReasoningPolicyNextScenario = [ + 9, + n0, + _GARPNS, + { + [_ht]: ["GET", "/automated-reasoning-policies/{policyArn}/build-workflows/{buildWorkflowId}/scenarios", 200], + }, + () => GetAutomatedReasoningPolicyNextScenarioRequest, + () => GetAutomatedReasoningPolicyNextScenarioResponse, +]; +var GetAutomatedReasoningPolicyTestCase = [ + 9, + n0, + _GARPTC, + { + [_ht]: ["GET", "/automated-reasoning-policies/{policyArn}/test-cases/{testCaseId}", 200], + }, + () => GetAutomatedReasoningPolicyTestCaseRequest, + () => GetAutomatedReasoningPolicyTestCaseResponse, +]; +var GetAutomatedReasoningPolicyTestResult = [ + 9, + n0, + _GARPTR, + { + [_ht]: [ + "GET", + "/automated-reasoning-policies/{policyArn}/build-workflows/{buildWorkflowId}/test-cases/{testCaseId}/test-results", + 200, + ], + }, + () => GetAutomatedReasoningPolicyTestResultRequest, + () => GetAutomatedReasoningPolicyTestResultResponse, +]; +var GetCustomModel = [ + 9, + n0, + _GCM, + { + [_ht]: ["GET", "/custom-models/{modelIdentifier}", 200], + }, + () => GetCustomModelRequest, + () => GetCustomModelResponse, +]; +var GetCustomModelDeployment = [ + 9, + n0, + _GCMD, + { + [_ht]: ["GET", "/model-customization/custom-model-deployments/{customModelDeploymentIdentifier}", 200], + }, + () => GetCustomModelDeploymentRequest, + () => GetCustomModelDeploymentResponse, +]; +var GetEvaluationJob = [ + 9, + n0, + _GEJ, + { + [_ht]: ["GET", "/evaluation-jobs/{jobIdentifier}", 200], + }, + () => GetEvaluationJobRequest, + () => GetEvaluationJobResponse, +]; +var GetFoundationModel = [ + 9, + n0, + _GFM, + { + [_ht]: ["GET", "/foundation-models/{modelIdentifier}", 200], + }, + () => GetFoundationModelRequest, + () => GetFoundationModelResponse, +]; +var GetFoundationModelAvailability = [ + 9, + n0, + _GFMA, + { + [_ht]: ["GET", "/foundation-model-availability/{modelId}", 200], + }, + () => GetFoundationModelAvailabilityRequest, + () => GetFoundationModelAvailabilityResponse, +]; +var GetGuardrail = [ + 9, + n0, + _GG, + { + [_ht]: ["GET", "/guardrails/{guardrailIdentifier}", 200], + }, + () => GetGuardrailRequest, + () => GetGuardrailResponse, +]; +var GetImportedModel = [ + 9, + n0, + _GIM, + { + [_ht]: ["GET", "/imported-models/{modelIdentifier}", 200], + }, + () => GetImportedModelRequest, + () => GetImportedModelResponse, +]; +var GetInferenceProfile = [ + 9, + n0, + _GIP, + { + [_ht]: ["GET", "/inference-profiles/{inferenceProfileIdentifier}", 200], + }, + () => GetInferenceProfileRequest, + () => GetInferenceProfileResponse, +]; +var GetMarketplaceModelEndpoint = [ + 9, + n0, + _GMME, + { + [_ht]: ["GET", "/marketplace-model/endpoints/{endpointArn}", 200], + }, + () => GetMarketplaceModelEndpointRequest, + () => GetMarketplaceModelEndpointResponse, +]; +var GetModelCopyJob = [ + 9, + n0, + _GMCJ, + { + [_ht]: ["GET", "/model-copy-jobs/{jobArn}", 200], + }, + () => GetModelCopyJobRequest, + () => GetModelCopyJobResponse, +]; +var GetModelCustomizationJob = [ + 9, + n0, + _GMCJe, + { + [_ht]: ["GET", "/model-customization-jobs/{jobIdentifier}", 200], + }, + () => GetModelCustomizationJobRequest, + () => GetModelCustomizationJobResponse, +]; +var GetModelImportJob = [ + 9, + n0, + _GMIJ, + { + [_ht]: ["GET", "/model-import-jobs/{jobIdentifier}", 200], + }, + () => GetModelImportJobRequest, + () => GetModelImportJobResponse, +]; +var GetModelInvocationJob = [ + 9, + n0, + _GMIJe, + { + [_ht]: ["GET", "/model-invocation-job/{jobIdentifier}", 200], + }, + () => GetModelInvocationJobRequest, + () => GetModelInvocationJobResponse, +]; +var GetModelInvocationLoggingConfiguration = [ + 9, + n0, + _GMILC, + { + [_ht]: ["GET", "/logging/modelinvocations", 200], + }, + () => GetModelInvocationLoggingConfigurationRequest, + () => GetModelInvocationLoggingConfigurationResponse, +]; +var GetPromptRouter = [ + 9, + n0, + _GPR, + { + [_ht]: ["GET", "/prompt-routers/{promptRouterArn}", 200], + }, + () => GetPromptRouterRequest, + () => GetPromptRouterResponse, +]; +var GetProvisionedModelThroughput = [ + 9, + n0, + _GPMT, + { + [_ht]: ["GET", "/provisioned-model-throughput/{provisionedModelId}", 200], + }, + () => GetProvisionedModelThroughputRequest, + () => GetProvisionedModelThroughputResponse, +]; +var GetUseCaseForModelAccess = [ + 9, + n0, + _GUCFMA, + { + [_ht]: ["GET", "/use-case-for-model-access", 200], + }, + () => GetUseCaseForModelAccessRequest, + () => GetUseCaseForModelAccessResponse, +]; +var ListAutomatedReasoningPolicies = [ + 9, + n0, + _LARP, + { + [_ht]: ["GET", "/automated-reasoning-policies", 200], + }, + () => ListAutomatedReasoningPoliciesRequest, + () => ListAutomatedReasoningPoliciesResponse, +]; +var ListAutomatedReasoningPolicyBuildWorkflows = [ + 9, + n0, + _LARPBW, + { + [_ht]: ["GET", "/automated-reasoning-policies/{policyArn}/build-workflows", 200], + }, + () => ListAutomatedReasoningPolicyBuildWorkflowsRequest, + () => ListAutomatedReasoningPolicyBuildWorkflowsResponse, +]; +var ListAutomatedReasoningPolicyTestCases = [ + 9, + n0, + _LARPTC, + { + [_ht]: ["GET", "/automated-reasoning-policies/{policyArn}/test-cases", 200], + }, + () => ListAutomatedReasoningPolicyTestCasesRequest, + () => ListAutomatedReasoningPolicyTestCasesResponse, +]; +var ListAutomatedReasoningPolicyTestResults = [ + 9, + n0, + _LARPTR, + { + [_ht]: ["GET", "/automated-reasoning-policies/{policyArn}/build-workflows/{buildWorkflowId}/test-results", 200], + }, + () => ListAutomatedReasoningPolicyTestResultsRequest, + () => ListAutomatedReasoningPolicyTestResultsResponse, +]; +var ListCustomModelDeployments = [ + 9, + n0, + _LCMD, + { + [_ht]: ["GET", "/model-customization/custom-model-deployments", 200], + }, + () => ListCustomModelDeploymentsRequest, + () => ListCustomModelDeploymentsResponse, +]; +var ListCustomModels = [ + 9, + n0, + _LCM, + { + [_ht]: ["GET", "/custom-models", 200], + }, + () => ListCustomModelsRequest, + () => ListCustomModelsResponse, +]; +var ListEvaluationJobs = [ + 9, + n0, + _LEJ, + { + [_ht]: ["GET", "/evaluation-jobs", 200], + }, + () => ListEvaluationJobsRequest, + () => ListEvaluationJobsResponse, +]; +var ListFoundationModelAgreementOffers = [ + 9, + n0, + _LFMAO, + { + [_ht]: ["GET", "/list-foundation-model-agreement-offers/{modelId}", 200], + }, + () => ListFoundationModelAgreementOffersRequest, + () => ListFoundationModelAgreementOffersResponse, +]; +var ListFoundationModels = [ + 9, + n0, + _LFM, + { + [_ht]: ["GET", "/foundation-models", 200], + }, + () => ListFoundationModelsRequest, + () => ListFoundationModelsResponse, +]; +var ListGuardrails = [ + 9, + n0, + _LG, + { + [_ht]: ["GET", "/guardrails", 200], + }, + () => ListGuardrailsRequest, + () => ListGuardrailsResponse, +]; +var ListImportedModels = [ + 9, + n0, + _LIM, + { + [_ht]: ["GET", "/imported-models", 200], + }, + () => ListImportedModelsRequest, + () => ListImportedModelsResponse, +]; +var ListInferenceProfiles = [ + 9, + n0, + _LIP, + { + [_ht]: ["GET", "/inference-profiles", 200], + }, + () => ListInferenceProfilesRequest, + () => ListInferenceProfilesResponse, +]; +var ListMarketplaceModelEndpoints = [ + 9, + n0, + _LMME, + { + [_ht]: ["GET", "/marketplace-model/endpoints", 200], + }, + () => ListMarketplaceModelEndpointsRequest, + () => ListMarketplaceModelEndpointsResponse, +]; +var ListModelCopyJobs = [ + 9, + n0, + _LMCJ, + { + [_ht]: ["GET", "/model-copy-jobs", 200], + }, + () => ListModelCopyJobsRequest, + () => ListModelCopyJobsResponse, +]; +var ListModelCustomizationJobs = [ + 9, + n0, + _LMCJi, + { + [_ht]: ["GET", "/model-customization-jobs", 200], + }, + () => ListModelCustomizationJobsRequest, + () => ListModelCustomizationJobsResponse, +]; +var ListModelImportJobs = [ + 9, + n0, + _LMIJ, + { + [_ht]: ["GET", "/model-import-jobs", 200], + }, + () => ListModelImportJobsRequest, + () => ListModelImportJobsResponse, +]; +var ListModelInvocationJobs = [ + 9, + n0, + _LMIJi, + { + [_ht]: ["GET", "/model-invocation-jobs", 200], + }, + () => ListModelInvocationJobsRequest, + () => ListModelInvocationJobsResponse, +]; +var ListPromptRouters = [ + 9, + n0, + _LPR, + { + [_ht]: ["GET", "/prompt-routers", 200], + }, + () => ListPromptRoutersRequest, + () => ListPromptRoutersResponse, +]; +var ListProvisionedModelThroughputs = [ + 9, + n0, + _LPMT, + { + [_ht]: ["GET", "/provisioned-model-throughputs", 200], + }, + () => ListProvisionedModelThroughputsRequest, + () => ListProvisionedModelThroughputsResponse, +]; +var ListTagsForResource = [ + 9, + n0, + _LTFR, + { + [_ht]: ["POST", "/listTagsForResource", 200], + }, + () => ListTagsForResourceRequest, + () => ListTagsForResourceResponse, +]; +var PutModelInvocationLoggingConfiguration = [ + 9, + n0, + _PMILC, + { + [_ht]: ["PUT", "/logging/modelinvocations", 200], + }, + () => PutModelInvocationLoggingConfigurationRequest, + () => PutModelInvocationLoggingConfigurationResponse, +]; +var PutUseCaseForModelAccess = [ + 9, + n0, + _PUCFMA, + { + [_ht]: ["POST", "/use-case-for-model-access", 201], + }, + () => PutUseCaseForModelAccessRequest, + () => PutUseCaseForModelAccessResponse, +]; +var RegisterMarketplaceModelEndpoint = [ + 9, + n0, + _RMME, + { + [_ht]: ["POST", "/marketplace-model/endpoints/{endpointIdentifier}/registration", 200], + }, + () => RegisterMarketplaceModelEndpointRequest, + () => RegisterMarketplaceModelEndpointResponse, +]; +var StartAutomatedReasoningPolicyBuildWorkflow = [ + 9, + n0, + _SARPBW, + { + [_ht]: ["POST", "/automated-reasoning-policies/{policyArn}/build-workflows/{buildWorkflowType}/start", 200], + }, + () => StartAutomatedReasoningPolicyBuildWorkflowRequest, + () => StartAutomatedReasoningPolicyBuildWorkflowResponse, +]; +var StartAutomatedReasoningPolicyTestWorkflow = [ + 9, + n0, + _SARPTW, + { + [_ht]: ["POST", "/automated-reasoning-policies/{policyArn}/build-workflows/{buildWorkflowId}/test-workflows", 200], + }, + () => StartAutomatedReasoningPolicyTestWorkflowRequest, + () => StartAutomatedReasoningPolicyTestWorkflowResponse, +]; +var StopEvaluationJob = [ + 9, + n0, + _SEJ, + { + [_ht]: ["POST", "/evaluation-job/{jobIdentifier}/stop", 200], + }, + () => StopEvaluationJobRequest, + () => StopEvaluationJobResponse, +]; +var StopModelCustomizationJob = [ + 9, + n0, + _SMCJ, + { + [_ht]: ["POST", "/model-customization-jobs/{jobIdentifier}/stop", 200], + }, + () => StopModelCustomizationJobRequest, + () => StopModelCustomizationJobResponse, +]; +var StopModelInvocationJob = [ + 9, + n0, + _SMIJ, + { + [_ht]: ["POST", "/model-invocation-job/{jobIdentifier}/stop", 200], + }, + () => StopModelInvocationJobRequest, + () => StopModelInvocationJobResponse, +]; +var TagResource = [ + 9, + n0, + _TR, + { + [_ht]: ["POST", "/tagResource", 200], + }, + () => TagResourceRequest, + () => TagResourceResponse, +]; +var UntagResource = [ + 9, + n0, + _UR, + { + [_ht]: ["POST", "/untagResource", 200], + }, + () => UntagResourceRequest, + () => UntagResourceResponse, +]; +var UpdateAutomatedReasoningPolicy = [ + 9, + n0, + _UARP, + { + [_ht]: ["PATCH", "/automated-reasoning-policies/{policyArn}", 200], + }, + () => UpdateAutomatedReasoningPolicyRequest, + () => UpdateAutomatedReasoningPolicyResponse, +]; +var UpdateAutomatedReasoningPolicyAnnotations = [ + 9, + n0, + _UARPA, + { + [_ht]: ["PATCH", "/automated-reasoning-policies/{policyArn}/build-workflows/{buildWorkflowId}/annotations", 200], + }, + () => UpdateAutomatedReasoningPolicyAnnotationsRequest, + () => UpdateAutomatedReasoningPolicyAnnotationsResponse, +]; +var UpdateAutomatedReasoningPolicyTestCase = [ + 9, + n0, + _UARPTC, + { + [_ht]: ["PATCH", "/automated-reasoning-policies/{policyArn}/test-cases/{testCaseId}", 200], + }, + () => UpdateAutomatedReasoningPolicyTestCaseRequest, + () => UpdateAutomatedReasoningPolicyTestCaseResponse, +]; +var UpdateGuardrail = [ + 9, + n0, + _UG, + { + [_ht]: ["PUT", "/guardrails/{guardrailIdentifier}", 202], + }, + () => UpdateGuardrailRequest, + () => UpdateGuardrailResponse, +]; +var UpdateMarketplaceModelEndpoint = [ + 9, + n0, + _UMME, + { + [_ht]: ["PATCH", "/marketplace-model/endpoints/{endpointArn}", 200], + }, + () => UpdateMarketplaceModelEndpointRequest, + () => UpdateMarketplaceModelEndpointResponse, +]; +var UpdateProvisionedModelThroughput = [ + 9, + n0, + _UPMT, + { + [_ht]: ["PATCH", "/provisioned-model-throughput/{provisionedModelId}", 200], + }, + () => UpdateProvisionedModelThroughputRequest, + () => UpdateProvisionedModelThroughputResponse, +]; + +class BatchDeleteEvaluationJobCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "BatchDeleteEvaluationJob", {}) + .n("BedrockClient", "BatchDeleteEvaluationJobCommand") + .sc(BatchDeleteEvaluationJob) + .build() { +} + +class CancelAutomatedReasoningPolicyBuildWorkflowCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "CancelAutomatedReasoningPolicyBuildWorkflow", {}) + .n("BedrockClient", "CancelAutomatedReasoningPolicyBuildWorkflowCommand") + .sc(CancelAutomatedReasoningPolicyBuildWorkflow) + .build() { +} + +class CreateAutomatedReasoningPolicyCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "CreateAutomatedReasoningPolicy", {}) + .n("BedrockClient", "CreateAutomatedReasoningPolicyCommand") + .sc(CreateAutomatedReasoningPolicy) + .build() { +} + +class CreateAutomatedReasoningPolicyTestCaseCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "CreateAutomatedReasoningPolicyTestCase", {}) + .n("BedrockClient", "CreateAutomatedReasoningPolicyTestCaseCommand") + .sc(CreateAutomatedReasoningPolicyTestCase) + .build() { +} + +class CreateAutomatedReasoningPolicyVersionCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "CreateAutomatedReasoningPolicyVersion", {}) + .n("BedrockClient", "CreateAutomatedReasoningPolicyVersionCommand") + .sc(CreateAutomatedReasoningPolicyVersion) + .build() { +} + +class CreateCustomModelCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "CreateCustomModel", {}) + .n("BedrockClient", "CreateCustomModelCommand") + .sc(CreateCustomModel) + .build() { +} + +class CreateCustomModelDeploymentCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "CreateCustomModelDeployment", {}) + .n("BedrockClient", "CreateCustomModelDeploymentCommand") + .sc(CreateCustomModelDeployment) + .build() { +} + +class CreateEvaluationJobCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "CreateEvaluationJob", {}) + .n("BedrockClient", "CreateEvaluationJobCommand") + .sc(CreateEvaluationJob) + .build() { +} + +class CreateFoundationModelAgreementCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "CreateFoundationModelAgreement", {}) + .n("BedrockClient", "CreateFoundationModelAgreementCommand") + .sc(CreateFoundationModelAgreement) + .build() { +} + +class CreateGuardrailCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "CreateGuardrail", {}) + .n("BedrockClient", "CreateGuardrailCommand") + .sc(CreateGuardrail) + .build() { +} + +class CreateGuardrailVersionCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "CreateGuardrailVersion", {}) + .n("BedrockClient", "CreateGuardrailVersionCommand") + .sc(CreateGuardrailVersion) + .build() { +} + +class CreateInferenceProfileCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "CreateInferenceProfile", {}) + .n("BedrockClient", "CreateInferenceProfileCommand") + .sc(CreateInferenceProfile) + .build() { +} + +class CreateMarketplaceModelEndpointCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "CreateMarketplaceModelEndpoint", {}) + .n("BedrockClient", "CreateMarketplaceModelEndpointCommand") + .sc(CreateMarketplaceModelEndpoint) + .build() { +} + +class CreateModelCopyJobCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "CreateModelCopyJob", {}) + .n("BedrockClient", "CreateModelCopyJobCommand") + .sc(CreateModelCopyJob) + .build() { +} + +class CreateModelCustomizationJobCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "CreateModelCustomizationJob", {}) + .n("BedrockClient", "CreateModelCustomizationJobCommand") + .sc(CreateModelCustomizationJob) + .build() { +} + +class CreateModelImportJobCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "CreateModelImportJob", {}) + .n("BedrockClient", "CreateModelImportJobCommand") + .sc(CreateModelImportJob) + .build() { +} + +class CreateModelInvocationJobCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "CreateModelInvocationJob", {}) + .n("BedrockClient", "CreateModelInvocationJobCommand") + .sc(CreateModelInvocationJob) + .build() { +} + +class CreatePromptRouterCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "CreatePromptRouter", {}) + .n("BedrockClient", "CreatePromptRouterCommand") + .sc(CreatePromptRouter) + .build() { +} + +class CreateProvisionedModelThroughputCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "CreateProvisionedModelThroughput", {}) + .n("BedrockClient", "CreateProvisionedModelThroughputCommand") + .sc(CreateProvisionedModelThroughput) + .build() { +} + +class DeleteAutomatedReasoningPolicyBuildWorkflowCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "DeleteAutomatedReasoningPolicyBuildWorkflow", {}) + .n("BedrockClient", "DeleteAutomatedReasoningPolicyBuildWorkflowCommand") + .sc(DeleteAutomatedReasoningPolicyBuildWorkflow) + .build() { +} + +class DeleteAutomatedReasoningPolicyCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "DeleteAutomatedReasoningPolicy", {}) + .n("BedrockClient", "DeleteAutomatedReasoningPolicyCommand") + .sc(DeleteAutomatedReasoningPolicy) + .build() { +} + +class DeleteAutomatedReasoningPolicyTestCaseCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "DeleteAutomatedReasoningPolicyTestCase", {}) + .n("BedrockClient", "DeleteAutomatedReasoningPolicyTestCaseCommand") + .sc(DeleteAutomatedReasoningPolicyTestCase) + .build() { +} + +class DeleteCustomModelCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "DeleteCustomModel", {}) + .n("BedrockClient", "DeleteCustomModelCommand") + .sc(DeleteCustomModel) + .build() { +} + +class DeleteCustomModelDeploymentCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "DeleteCustomModelDeployment", {}) + .n("BedrockClient", "DeleteCustomModelDeploymentCommand") + .sc(DeleteCustomModelDeployment) + .build() { +} + +class DeleteFoundationModelAgreementCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "DeleteFoundationModelAgreement", {}) + .n("BedrockClient", "DeleteFoundationModelAgreementCommand") + .sc(DeleteFoundationModelAgreement) + .build() { +} + +class DeleteGuardrailCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "DeleteGuardrail", {}) + .n("BedrockClient", "DeleteGuardrailCommand") + .sc(DeleteGuardrail) + .build() { +} + +class DeleteImportedModelCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "DeleteImportedModel", {}) + .n("BedrockClient", "DeleteImportedModelCommand") + .sc(DeleteImportedModel) + .build() { +} + +class DeleteInferenceProfileCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "DeleteInferenceProfile", {}) + .n("BedrockClient", "DeleteInferenceProfileCommand") + .sc(DeleteInferenceProfile) + .build() { +} + +class DeleteMarketplaceModelEndpointCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "DeleteMarketplaceModelEndpoint", {}) + .n("BedrockClient", "DeleteMarketplaceModelEndpointCommand") + .sc(DeleteMarketplaceModelEndpoint) + .build() { +} + +class DeleteModelInvocationLoggingConfigurationCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "DeleteModelInvocationLoggingConfiguration", {}) + .n("BedrockClient", "DeleteModelInvocationLoggingConfigurationCommand") + .sc(DeleteModelInvocationLoggingConfiguration) + .build() { +} + +class DeletePromptRouterCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "DeletePromptRouter", {}) + .n("BedrockClient", "DeletePromptRouterCommand") + .sc(DeletePromptRouter) + .build() { +} + +class DeleteProvisionedModelThroughputCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "DeleteProvisionedModelThroughput", {}) + .n("BedrockClient", "DeleteProvisionedModelThroughputCommand") + .sc(DeleteProvisionedModelThroughput) + .build() { +} + +class DeregisterMarketplaceModelEndpointCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "DeregisterMarketplaceModelEndpoint", {}) + .n("BedrockClient", "DeregisterMarketplaceModelEndpointCommand") + .sc(DeregisterMarketplaceModelEndpoint) + .build() { +} + +class ExportAutomatedReasoningPolicyVersionCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "ExportAutomatedReasoningPolicyVersion", {}) + .n("BedrockClient", "ExportAutomatedReasoningPolicyVersionCommand") + .sc(ExportAutomatedReasoningPolicyVersion) + .build() { +} + +class GetAutomatedReasoningPolicyAnnotationsCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "GetAutomatedReasoningPolicyAnnotations", {}) + .n("BedrockClient", "GetAutomatedReasoningPolicyAnnotationsCommand") + .sc(GetAutomatedReasoningPolicyAnnotations) + .build() { +} + +class GetAutomatedReasoningPolicyBuildWorkflowCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "GetAutomatedReasoningPolicyBuildWorkflow", {}) + .n("BedrockClient", "GetAutomatedReasoningPolicyBuildWorkflowCommand") + .sc(GetAutomatedReasoningPolicyBuildWorkflow) + .build() { +} + +class GetAutomatedReasoningPolicyBuildWorkflowResultAssetsCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "GetAutomatedReasoningPolicyBuildWorkflowResultAssets", {}) + .n("BedrockClient", "GetAutomatedReasoningPolicyBuildWorkflowResultAssetsCommand") + .sc(GetAutomatedReasoningPolicyBuildWorkflowResultAssets) + .build() { +} + +class GetAutomatedReasoningPolicyCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "GetAutomatedReasoningPolicy", {}) + .n("BedrockClient", "GetAutomatedReasoningPolicyCommand") + .sc(GetAutomatedReasoningPolicy) + .build() { +} + +class GetAutomatedReasoningPolicyNextScenarioCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "GetAutomatedReasoningPolicyNextScenario", {}) + .n("BedrockClient", "GetAutomatedReasoningPolicyNextScenarioCommand") + .sc(GetAutomatedReasoningPolicyNextScenario) + .build() { +} + +class GetAutomatedReasoningPolicyTestCaseCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "GetAutomatedReasoningPolicyTestCase", {}) + .n("BedrockClient", "GetAutomatedReasoningPolicyTestCaseCommand") + .sc(GetAutomatedReasoningPolicyTestCase) + .build() { +} + +class GetAutomatedReasoningPolicyTestResultCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "GetAutomatedReasoningPolicyTestResult", {}) + .n("BedrockClient", "GetAutomatedReasoningPolicyTestResultCommand") + .sc(GetAutomatedReasoningPolicyTestResult) + .build() { +} + +class GetCustomModelCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "GetCustomModel", {}) + .n("BedrockClient", "GetCustomModelCommand") + .sc(GetCustomModel) + .build() { +} + +class GetCustomModelDeploymentCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "GetCustomModelDeployment", {}) + .n("BedrockClient", "GetCustomModelDeploymentCommand") + .sc(GetCustomModelDeployment) + .build() { +} + +class GetEvaluationJobCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "GetEvaluationJob", {}) + .n("BedrockClient", "GetEvaluationJobCommand") + .sc(GetEvaluationJob) + .build() { +} + +class GetFoundationModelAvailabilityCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "GetFoundationModelAvailability", {}) + .n("BedrockClient", "GetFoundationModelAvailabilityCommand") + .sc(GetFoundationModelAvailability) + .build() { +} + +class GetFoundationModelCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "GetFoundationModel", {}) + .n("BedrockClient", "GetFoundationModelCommand") + .sc(GetFoundationModel) + .build() { +} + +class GetGuardrailCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "GetGuardrail", {}) + .n("BedrockClient", "GetGuardrailCommand") + .sc(GetGuardrail) + .build() { +} + +class GetImportedModelCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "GetImportedModel", {}) + .n("BedrockClient", "GetImportedModelCommand") + .sc(GetImportedModel) + .build() { +} + +class GetInferenceProfileCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "GetInferenceProfile", {}) + .n("BedrockClient", "GetInferenceProfileCommand") + .sc(GetInferenceProfile) + .build() { +} + +class GetMarketplaceModelEndpointCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "GetMarketplaceModelEndpoint", {}) + .n("BedrockClient", "GetMarketplaceModelEndpointCommand") + .sc(GetMarketplaceModelEndpoint) + .build() { +} + +class GetModelCopyJobCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "GetModelCopyJob", {}) + .n("BedrockClient", "GetModelCopyJobCommand") + .sc(GetModelCopyJob) + .build() { +} + +class GetModelCustomizationJobCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "GetModelCustomizationJob", {}) + .n("BedrockClient", "GetModelCustomizationJobCommand") + .sc(GetModelCustomizationJob) + .build() { +} + +class GetModelImportJobCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "GetModelImportJob", {}) + .n("BedrockClient", "GetModelImportJobCommand") + .sc(GetModelImportJob) + .build() { +} + +class GetModelInvocationJobCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "GetModelInvocationJob", {}) + .n("BedrockClient", "GetModelInvocationJobCommand") + .sc(GetModelInvocationJob) + .build() { +} + +class GetModelInvocationLoggingConfigurationCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "GetModelInvocationLoggingConfiguration", {}) + .n("BedrockClient", "GetModelInvocationLoggingConfigurationCommand") + .sc(GetModelInvocationLoggingConfiguration) + .build() { +} + +class GetPromptRouterCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "GetPromptRouter", {}) + .n("BedrockClient", "GetPromptRouterCommand") + .sc(GetPromptRouter) + .build() { +} + +class GetProvisionedModelThroughputCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "GetProvisionedModelThroughput", {}) + .n("BedrockClient", "GetProvisionedModelThroughputCommand") + .sc(GetProvisionedModelThroughput) + .build() { +} + +class GetUseCaseForModelAccessCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "GetUseCaseForModelAccess", {}) + .n("BedrockClient", "GetUseCaseForModelAccessCommand") + .sc(GetUseCaseForModelAccess) + .build() { +} + +class ListAutomatedReasoningPoliciesCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "ListAutomatedReasoningPolicies", {}) + .n("BedrockClient", "ListAutomatedReasoningPoliciesCommand") + .sc(ListAutomatedReasoningPolicies) + .build() { +} + +class ListAutomatedReasoningPolicyBuildWorkflowsCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "ListAutomatedReasoningPolicyBuildWorkflows", {}) + .n("BedrockClient", "ListAutomatedReasoningPolicyBuildWorkflowsCommand") + .sc(ListAutomatedReasoningPolicyBuildWorkflows) + .build() { +} + +class ListAutomatedReasoningPolicyTestCasesCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "ListAutomatedReasoningPolicyTestCases", {}) + .n("BedrockClient", "ListAutomatedReasoningPolicyTestCasesCommand") + .sc(ListAutomatedReasoningPolicyTestCases) + .build() { +} + +class ListAutomatedReasoningPolicyTestResultsCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "ListAutomatedReasoningPolicyTestResults", {}) + .n("BedrockClient", "ListAutomatedReasoningPolicyTestResultsCommand") + .sc(ListAutomatedReasoningPolicyTestResults) + .build() { +} + +class ListCustomModelDeploymentsCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "ListCustomModelDeployments", {}) + .n("BedrockClient", "ListCustomModelDeploymentsCommand") + .sc(ListCustomModelDeployments) + .build() { +} + +class ListCustomModelsCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "ListCustomModels", {}) + .n("BedrockClient", "ListCustomModelsCommand") + .sc(ListCustomModels) + .build() { +} + +class ListEvaluationJobsCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "ListEvaluationJobs", {}) + .n("BedrockClient", "ListEvaluationJobsCommand") + .sc(ListEvaluationJobs) + .build() { +} + +class ListFoundationModelAgreementOffersCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "ListFoundationModelAgreementOffers", {}) + .n("BedrockClient", "ListFoundationModelAgreementOffersCommand") + .sc(ListFoundationModelAgreementOffers) + .build() { +} + +class ListFoundationModelsCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "ListFoundationModels", {}) + .n("BedrockClient", "ListFoundationModelsCommand") + .sc(ListFoundationModels) + .build() { +} + +class ListGuardrailsCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "ListGuardrails", {}) + .n("BedrockClient", "ListGuardrailsCommand") + .sc(ListGuardrails) + .build() { +} + +class ListImportedModelsCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "ListImportedModels", {}) + .n("BedrockClient", "ListImportedModelsCommand") + .sc(ListImportedModels) + .build() { +} + +class ListInferenceProfilesCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "ListInferenceProfiles", {}) + .n("BedrockClient", "ListInferenceProfilesCommand") + .sc(ListInferenceProfiles) + .build() { +} + +class ListMarketplaceModelEndpointsCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "ListMarketplaceModelEndpoints", {}) + .n("BedrockClient", "ListMarketplaceModelEndpointsCommand") + .sc(ListMarketplaceModelEndpoints) + .build() { +} + +class ListModelCopyJobsCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "ListModelCopyJobs", {}) + .n("BedrockClient", "ListModelCopyJobsCommand") + .sc(ListModelCopyJobs) + .build() { +} + +class ListModelCustomizationJobsCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "ListModelCustomizationJobs", {}) + .n("BedrockClient", "ListModelCustomizationJobsCommand") + .sc(ListModelCustomizationJobs) + .build() { +} + +class ListModelImportJobsCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "ListModelImportJobs", {}) + .n("BedrockClient", "ListModelImportJobsCommand") + .sc(ListModelImportJobs) + .build() { +} + +class ListModelInvocationJobsCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "ListModelInvocationJobs", {}) + .n("BedrockClient", "ListModelInvocationJobsCommand") + .sc(ListModelInvocationJobs) + .build() { +} + +class ListPromptRoutersCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "ListPromptRouters", {}) + .n("BedrockClient", "ListPromptRoutersCommand") + .sc(ListPromptRouters) + .build() { +} + +class ListProvisionedModelThroughputsCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "ListProvisionedModelThroughputs", {}) + .n("BedrockClient", "ListProvisionedModelThroughputsCommand") + .sc(ListProvisionedModelThroughputs) + .build() { +} + +class ListTagsForResourceCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "ListTagsForResource", {}) + .n("BedrockClient", "ListTagsForResourceCommand") + .sc(ListTagsForResource) + .build() { +} + +class PutModelInvocationLoggingConfigurationCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "PutModelInvocationLoggingConfiguration", {}) + .n("BedrockClient", "PutModelInvocationLoggingConfigurationCommand") + .sc(PutModelInvocationLoggingConfiguration) + .build() { +} + +class PutUseCaseForModelAccessCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "PutUseCaseForModelAccess", {}) + .n("BedrockClient", "PutUseCaseForModelAccessCommand") + .sc(PutUseCaseForModelAccess) + .build() { +} + +class RegisterMarketplaceModelEndpointCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "RegisterMarketplaceModelEndpoint", {}) + .n("BedrockClient", "RegisterMarketplaceModelEndpointCommand") + .sc(RegisterMarketplaceModelEndpoint) + .build() { +} + +class StartAutomatedReasoningPolicyBuildWorkflowCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "StartAutomatedReasoningPolicyBuildWorkflow", {}) + .n("BedrockClient", "StartAutomatedReasoningPolicyBuildWorkflowCommand") + .sc(StartAutomatedReasoningPolicyBuildWorkflow) + .build() { +} + +class StartAutomatedReasoningPolicyTestWorkflowCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "StartAutomatedReasoningPolicyTestWorkflow", {}) + .n("BedrockClient", "StartAutomatedReasoningPolicyTestWorkflowCommand") + .sc(StartAutomatedReasoningPolicyTestWorkflow) + .build() { +} + +class StopEvaluationJobCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "StopEvaluationJob", {}) + .n("BedrockClient", "StopEvaluationJobCommand") + .sc(StopEvaluationJob) + .build() { +} + +class StopModelCustomizationJobCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "StopModelCustomizationJob", {}) + .n("BedrockClient", "StopModelCustomizationJobCommand") + .sc(StopModelCustomizationJob) + .build() { +} + +class StopModelInvocationJobCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "StopModelInvocationJob", {}) + .n("BedrockClient", "StopModelInvocationJobCommand") + .sc(StopModelInvocationJob) + .build() { +} + +class TagResourceCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "TagResource", {}) + .n("BedrockClient", "TagResourceCommand") + .sc(TagResource) + .build() { +} + +class UntagResourceCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "UntagResource", {}) + .n("BedrockClient", "UntagResourceCommand") + .sc(UntagResource) + .build() { +} + +class UpdateAutomatedReasoningPolicyAnnotationsCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "UpdateAutomatedReasoningPolicyAnnotations", {}) + .n("BedrockClient", "UpdateAutomatedReasoningPolicyAnnotationsCommand") + .sc(UpdateAutomatedReasoningPolicyAnnotations) + .build() { +} + +class UpdateAutomatedReasoningPolicyCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "UpdateAutomatedReasoningPolicy", {}) + .n("BedrockClient", "UpdateAutomatedReasoningPolicyCommand") + .sc(UpdateAutomatedReasoningPolicy) + .build() { +} + +class UpdateAutomatedReasoningPolicyTestCaseCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "UpdateAutomatedReasoningPolicyTestCase", {}) + .n("BedrockClient", "UpdateAutomatedReasoningPolicyTestCaseCommand") + .sc(UpdateAutomatedReasoningPolicyTestCase) + .build() { +} + +class UpdateGuardrailCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "UpdateGuardrail", {}) + .n("BedrockClient", "UpdateGuardrailCommand") + .sc(UpdateGuardrail) + .build() { +} + +class UpdateMarketplaceModelEndpointCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "UpdateMarketplaceModelEndpoint", {}) + .n("BedrockClient", "UpdateMarketplaceModelEndpointCommand") + .sc(UpdateMarketplaceModelEndpoint) + .build() { +} + +class UpdateProvisionedModelThroughputCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AmazonBedrockControlPlaneService", "UpdateProvisionedModelThroughput", {}) + .n("BedrockClient", "UpdateProvisionedModelThroughputCommand") + .sc(UpdateProvisionedModelThroughput) + .build() { +} + +const commands = { + BatchDeleteEvaluationJobCommand, + CancelAutomatedReasoningPolicyBuildWorkflowCommand, + CreateAutomatedReasoningPolicyCommand, + CreateAutomatedReasoningPolicyTestCaseCommand, + CreateAutomatedReasoningPolicyVersionCommand, + CreateCustomModelCommand, + CreateCustomModelDeploymentCommand, + CreateEvaluationJobCommand, + CreateFoundationModelAgreementCommand, + CreateGuardrailCommand, + CreateGuardrailVersionCommand, + CreateInferenceProfileCommand, + CreateMarketplaceModelEndpointCommand, + CreateModelCopyJobCommand, + CreateModelCustomizationJobCommand, + CreateModelImportJobCommand, + CreateModelInvocationJobCommand, + CreatePromptRouterCommand, + CreateProvisionedModelThroughputCommand, + DeleteAutomatedReasoningPolicyCommand, + DeleteAutomatedReasoningPolicyBuildWorkflowCommand, + DeleteAutomatedReasoningPolicyTestCaseCommand, + DeleteCustomModelCommand, + DeleteCustomModelDeploymentCommand, + DeleteFoundationModelAgreementCommand, + DeleteGuardrailCommand, + DeleteImportedModelCommand, + DeleteInferenceProfileCommand, + DeleteMarketplaceModelEndpointCommand, + DeleteModelInvocationLoggingConfigurationCommand, + DeletePromptRouterCommand, + DeleteProvisionedModelThroughputCommand, + DeregisterMarketplaceModelEndpointCommand, + ExportAutomatedReasoningPolicyVersionCommand, + GetAutomatedReasoningPolicyCommand, + GetAutomatedReasoningPolicyAnnotationsCommand, + GetAutomatedReasoningPolicyBuildWorkflowCommand, + GetAutomatedReasoningPolicyBuildWorkflowResultAssetsCommand, + GetAutomatedReasoningPolicyNextScenarioCommand, + GetAutomatedReasoningPolicyTestCaseCommand, + GetAutomatedReasoningPolicyTestResultCommand, + GetCustomModelCommand, + GetCustomModelDeploymentCommand, + GetEvaluationJobCommand, + GetFoundationModelCommand, + GetFoundationModelAvailabilityCommand, + GetGuardrailCommand, + GetImportedModelCommand, + GetInferenceProfileCommand, + GetMarketplaceModelEndpointCommand, + GetModelCopyJobCommand, + GetModelCustomizationJobCommand, + GetModelImportJobCommand, + GetModelInvocationJobCommand, + GetModelInvocationLoggingConfigurationCommand, + GetPromptRouterCommand, + GetProvisionedModelThroughputCommand, + GetUseCaseForModelAccessCommand, + ListAutomatedReasoningPoliciesCommand, + ListAutomatedReasoningPolicyBuildWorkflowsCommand, + ListAutomatedReasoningPolicyTestCasesCommand, + ListAutomatedReasoningPolicyTestResultsCommand, + ListCustomModelDeploymentsCommand, + ListCustomModelsCommand, + ListEvaluationJobsCommand, + ListFoundationModelAgreementOffersCommand, + ListFoundationModelsCommand, + ListGuardrailsCommand, + ListImportedModelsCommand, + ListInferenceProfilesCommand, + ListMarketplaceModelEndpointsCommand, + ListModelCopyJobsCommand, + ListModelCustomizationJobsCommand, + ListModelImportJobsCommand, + ListModelInvocationJobsCommand, + ListPromptRoutersCommand, + ListProvisionedModelThroughputsCommand, + ListTagsForResourceCommand, + PutModelInvocationLoggingConfigurationCommand, + PutUseCaseForModelAccessCommand, + RegisterMarketplaceModelEndpointCommand, + StartAutomatedReasoningPolicyBuildWorkflowCommand, + StartAutomatedReasoningPolicyTestWorkflowCommand, + StopEvaluationJobCommand, + StopModelCustomizationJobCommand, + StopModelInvocationJobCommand, + TagResourceCommand, + UntagResourceCommand, + UpdateAutomatedReasoningPolicyCommand, + UpdateAutomatedReasoningPolicyAnnotationsCommand, + UpdateAutomatedReasoningPolicyTestCaseCommand, + UpdateGuardrailCommand, + UpdateMarketplaceModelEndpointCommand, + UpdateProvisionedModelThroughputCommand, +}; +class Bedrock extends BedrockClient { +} +smithyClient.createAggregatedClient(commands, Bedrock); + +const paginateListAutomatedReasoningPolicies = core.createPaginator(BedrockClient, ListAutomatedReasoningPoliciesCommand, "nextToken", "nextToken", "maxResults"); + +const paginateListAutomatedReasoningPolicyBuildWorkflows = core.createPaginator(BedrockClient, ListAutomatedReasoningPolicyBuildWorkflowsCommand, "nextToken", "nextToken", "maxResults"); + +const paginateListAutomatedReasoningPolicyTestCases = core.createPaginator(BedrockClient, ListAutomatedReasoningPolicyTestCasesCommand, "nextToken", "nextToken", "maxResults"); + +const paginateListAutomatedReasoningPolicyTestResults = core.createPaginator(BedrockClient, ListAutomatedReasoningPolicyTestResultsCommand, "nextToken", "nextToken", "maxResults"); + +const paginateListCustomModelDeployments = core.createPaginator(BedrockClient, ListCustomModelDeploymentsCommand, "nextToken", "nextToken", "maxResults"); + +const paginateListCustomModels = core.createPaginator(BedrockClient, ListCustomModelsCommand, "nextToken", "nextToken", "maxResults"); + +const paginateListEvaluationJobs = core.createPaginator(BedrockClient, ListEvaluationJobsCommand, "nextToken", "nextToken", "maxResults"); + +const paginateListGuardrails = core.createPaginator(BedrockClient, ListGuardrailsCommand, "nextToken", "nextToken", "maxResults"); + +const paginateListImportedModels = core.createPaginator(BedrockClient, ListImportedModelsCommand, "nextToken", "nextToken", "maxResults"); + +const paginateListInferenceProfiles = core.createPaginator(BedrockClient, ListInferenceProfilesCommand, "nextToken", "nextToken", "maxResults"); + +const paginateListMarketplaceModelEndpoints = core.createPaginator(BedrockClient, ListMarketplaceModelEndpointsCommand, "nextToken", "nextToken", "maxResults"); + +const paginateListModelCopyJobs = core.createPaginator(BedrockClient, ListModelCopyJobsCommand, "nextToken", "nextToken", "maxResults"); + +const paginateListModelCustomizationJobs = core.createPaginator(BedrockClient, ListModelCustomizationJobsCommand, "nextToken", "nextToken", "maxResults"); + +const paginateListModelImportJobs = core.createPaginator(BedrockClient, ListModelImportJobsCommand, "nextToken", "nextToken", "maxResults"); + +const paginateListModelInvocationJobs = core.createPaginator(BedrockClient, ListModelInvocationJobsCommand, "nextToken", "nextToken", "maxResults"); + +const paginateListPromptRouters = core.createPaginator(BedrockClient, ListPromptRoutersCommand, "nextToken", "nextToken", "maxResults"); + +const paginateListProvisionedModelThroughputs = core.createPaginator(BedrockClient, ListProvisionedModelThroughputsCommand, "nextToken", "nextToken", "maxResults"); + +const AgreementStatus = { + AVAILABLE: "AVAILABLE", + ERROR: "ERROR", + NOT_AVAILABLE: "NOT_AVAILABLE", + PENDING: "PENDING", +}; +const AutomatedReasoningCheckResult = { + IMPOSSIBLE: "IMPOSSIBLE", + INVALID: "INVALID", + NO_TRANSLATION: "NO_TRANSLATION", + SATISFIABLE: "SATISFIABLE", + TOO_COMPLEX: "TOO_COMPLEX", + TRANSLATION_AMBIGUOUS: "TRANSLATION_AMBIGUOUS", + VALID: "VALID", +}; +const AutomatedReasoningPolicyBuildWorkflowType = { + IMPORT_POLICY: "IMPORT_POLICY", + INGEST_CONTENT: "INGEST_CONTENT", + REFINE_POLICY: "REFINE_POLICY", +}; +const AutomatedReasoningPolicyBuildDocumentContentType = { + PDF: "pdf", + TEXT: "txt", +}; +const AutomatedReasoningPolicyBuildWorkflowStatus = { + BUILDING: "BUILDING", + CANCELLED: "CANCELLED", + CANCEL_REQUESTED: "CANCEL_REQUESTED", + COMPLETED: "COMPLETED", + FAILED: "FAILED", + PREPROCESSING: "PREPROCESSING", + SCHEDULED: "SCHEDULED", + TESTING: "TESTING", +}; +const AutomatedReasoningPolicyBuildResultAssetType = { + BUILD_LOG: "BUILD_LOG", + GENERATED_TEST_CASES: "GENERATED_TEST_CASES", + POLICY_DEFINITION: "POLICY_DEFINITION", + QUALITY_REPORT: "QUALITY_REPORT", +}; +const AutomatedReasoningPolicyBuildMessageType = { + ERROR: "ERROR", + INFO: "INFO", + WARNING: "WARNING", +}; +const AutomatedReasoningPolicyAnnotationStatus = { + APPLIED: "APPLIED", + FAILED: "FAILED", +}; +const AutomatedReasoningCheckLogicWarningType = { + ALWAYS_FALSE: "ALWAYS_FALSE", + ALWAYS_TRUE: "ALWAYS_TRUE", +}; +const AutomatedReasoningPolicyTestRunResult = { + FAILED: "FAILED", + PASSED: "PASSED", +}; +const AutomatedReasoningPolicyTestRunStatus = { + COMPLETED: "COMPLETED", + FAILED: "FAILED", + IN_PROGRESS: "IN_PROGRESS", + NOT_STARTED: "NOT_STARTED", + SCHEDULED: "SCHEDULED", +}; +const Status = { + INCOMPATIBLE_ENDPOINT: "INCOMPATIBLE_ENDPOINT", + REGISTERED: "REGISTERED", +}; +const CustomModelDeploymentStatus = { + ACTIVE: "Active", + CREATING: "Creating", + FAILED: "Failed", +}; +const SortModelsBy = { + CREATION_TIME: "CreationTime", +}; +const SortOrder = { + ASCENDING: "Ascending", + DESCENDING: "Descending", +}; +const CustomizationType = { + CONTINUED_PRE_TRAINING: "CONTINUED_PRE_TRAINING", + DISTILLATION: "DISTILLATION", + FINE_TUNING: "FINE_TUNING", + IMPORTED: "IMPORTED", +}; +const ModelStatus = { + ACTIVE: "Active", + CREATING: "Creating", + FAILED: "Failed", +}; +const EvaluationJobStatus = { + COMPLETED: "Completed", + DELETING: "Deleting", + FAILED: "Failed", + IN_PROGRESS: "InProgress", + STOPPED: "Stopped", + STOPPING: "Stopping", +}; +const ApplicationType = { + MODEL_EVALUATION: "ModelEvaluation", + RAG_EVALUATION: "RagEvaluation", +}; +const EvaluationTaskType = { + CLASSIFICATION: "Classification", + CUSTOM: "Custom", + GENERATION: "Generation", + QUESTION_AND_ANSWER: "QuestionAndAnswer", + SUMMARIZATION: "Summarization", +}; +const PerformanceConfigLatency = { + OPTIMIZED: "optimized", + STANDARD: "standard", +}; +const ExternalSourceType = { + BYTE_CONTENT: "BYTE_CONTENT", + S3: "S3", +}; +const QueryTransformationType = { + QUERY_DECOMPOSITION: "QUERY_DECOMPOSITION", +}; +const AttributeType = { + BOOLEAN: "BOOLEAN", + NUMBER: "NUMBER", + STRING: "STRING", + STRING_LIST: "STRING_LIST", +}; +const SearchType = { + HYBRID: "HYBRID", + SEMANTIC: "SEMANTIC", +}; +const RerankingMetadataSelectionMode = { + ALL: "ALL", + SELECTIVE: "SELECTIVE", +}; +const VectorSearchRerankingConfigurationType = { + BEDROCK_RERANKING_MODEL: "BEDROCK_RERANKING_MODEL", +}; +const RetrieveAndGenerateType = { + EXTERNAL_SOURCES: "EXTERNAL_SOURCES", + KNOWLEDGE_BASE: "KNOWLEDGE_BASE", +}; +const EvaluationJobType = { + AUTOMATED: "Automated", + HUMAN: "Human", +}; +const SortJobsBy = { + CREATION_TIME: "CreationTime", +}; +const GuardrailContentFilterAction = { + BLOCK: "BLOCK", + NONE: "NONE", +}; +const GuardrailModality = { + IMAGE: "IMAGE", + TEXT: "TEXT", +}; +const GuardrailFilterStrength = { + HIGH: "HIGH", + LOW: "LOW", + MEDIUM: "MEDIUM", + NONE: "NONE", +}; +const GuardrailContentFilterType = { + HATE: "HATE", + INSULTS: "INSULTS", + MISCONDUCT: "MISCONDUCT", + PROMPT_ATTACK: "PROMPT_ATTACK", + SEXUAL: "SEXUAL", + VIOLENCE: "VIOLENCE", +}; +const GuardrailContentFiltersTierName = { + CLASSIC: "CLASSIC", + STANDARD: "STANDARD", +}; +const GuardrailContextualGroundingAction = { + BLOCK: "BLOCK", + NONE: "NONE", +}; +const GuardrailContextualGroundingFilterType = { + GROUNDING: "GROUNDING", + RELEVANCE: "RELEVANCE", +}; +const GuardrailSensitiveInformationAction = { + ANONYMIZE: "ANONYMIZE", + BLOCK: "BLOCK", + NONE: "NONE", +}; +const GuardrailPiiEntityType = { + ADDRESS: "ADDRESS", + AGE: "AGE", + AWS_ACCESS_KEY: "AWS_ACCESS_KEY", + AWS_SECRET_KEY: "AWS_SECRET_KEY", + CA_HEALTH_NUMBER: "CA_HEALTH_NUMBER", + CA_SOCIAL_INSURANCE_NUMBER: "CA_SOCIAL_INSURANCE_NUMBER", + CREDIT_DEBIT_CARD_CVV: "CREDIT_DEBIT_CARD_CVV", + CREDIT_DEBIT_CARD_EXPIRY: "CREDIT_DEBIT_CARD_EXPIRY", + CREDIT_DEBIT_CARD_NUMBER: "CREDIT_DEBIT_CARD_NUMBER", + DRIVER_ID: "DRIVER_ID", + EMAIL: "EMAIL", + INTERNATIONAL_BANK_ACCOUNT_NUMBER: "INTERNATIONAL_BANK_ACCOUNT_NUMBER", + IP_ADDRESS: "IP_ADDRESS", + LICENSE_PLATE: "LICENSE_PLATE", + MAC_ADDRESS: "MAC_ADDRESS", + NAME: "NAME", + PASSWORD: "PASSWORD", + PHONE: "PHONE", + PIN: "PIN", + SWIFT_CODE: "SWIFT_CODE", + UK_NATIONAL_HEALTH_SERVICE_NUMBER: "UK_NATIONAL_HEALTH_SERVICE_NUMBER", + UK_NATIONAL_INSURANCE_NUMBER: "UK_NATIONAL_INSURANCE_NUMBER", + UK_UNIQUE_TAXPAYER_REFERENCE_NUMBER: "UK_UNIQUE_TAXPAYER_REFERENCE_NUMBER", + URL: "URL", + USERNAME: "USERNAME", + US_BANK_ACCOUNT_NUMBER: "US_BANK_ACCOUNT_NUMBER", + US_BANK_ROUTING_NUMBER: "US_BANK_ROUTING_NUMBER", + US_INDIVIDUAL_TAX_IDENTIFICATION_NUMBER: "US_INDIVIDUAL_TAX_IDENTIFICATION_NUMBER", + US_PASSPORT_NUMBER: "US_PASSPORT_NUMBER", + US_SOCIAL_SECURITY_NUMBER: "US_SOCIAL_SECURITY_NUMBER", + VEHICLE_IDENTIFICATION_NUMBER: "VEHICLE_IDENTIFICATION_NUMBER", +}; +const GuardrailTopicsTierName = { + CLASSIC: "CLASSIC", + STANDARD: "STANDARD", +}; +const GuardrailTopicAction = { + BLOCK: "BLOCK", + NONE: "NONE", +}; +const GuardrailTopicType = { + DENY: "DENY", +}; +const GuardrailWordAction = { + BLOCK: "BLOCK", + NONE: "NONE", +}; +const GuardrailManagedWordsType = { + PROFANITY: "PROFANITY", +}; +const GuardrailStatus = { + CREATING: "CREATING", + DELETING: "DELETING", + FAILED: "FAILED", + READY: "READY", + UPDATING: "UPDATING", + VERSIONING: "VERSIONING", +}; +const InferenceProfileStatus = { + ACTIVE: "ACTIVE", +}; +const InferenceProfileType = { + APPLICATION: "APPLICATION", + SYSTEM_DEFINED: "SYSTEM_DEFINED", +}; +const ModelCopyJobStatus = { + COMPLETED: "Completed", + FAILED: "Failed", + IN_PROGRESS: "InProgress", +}; +const ModelImportJobStatus = { + COMPLETED: "Completed", + FAILED: "Failed", + IN_PROGRESS: "InProgress", +}; +const S3InputFormat = { + JSONL: "JSONL", +}; +const ModelInvocationJobStatus = { + COMPLETED: "Completed", + EXPIRED: "Expired", + FAILED: "Failed", + IN_PROGRESS: "InProgress", + PARTIALLY_COMPLETED: "PartiallyCompleted", + SCHEDULED: "Scheduled", + STOPPED: "Stopped", + STOPPING: "Stopping", + SUBMITTED: "Submitted", + VALIDATING: "Validating", +}; +const ModelCustomization = { + CONTINUED_PRE_TRAINING: "CONTINUED_PRE_TRAINING", + DISTILLATION: "DISTILLATION", + FINE_TUNING: "FINE_TUNING", +}; +const InferenceType = { + ON_DEMAND: "ON_DEMAND", + PROVISIONED: "PROVISIONED", +}; +const ModelModality = { + EMBEDDING: "EMBEDDING", + IMAGE: "IMAGE", + TEXT: "TEXT", +}; +const FoundationModelLifecycleStatus = { + ACTIVE: "ACTIVE", + LEGACY: "LEGACY", +}; +const PromptRouterStatus = { + AVAILABLE: "AVAILABLE", +}; +const PromptRouterType = { + CUSTOM: "custom", + DEFAULT: "default", +}; +const CommitmentDuration = { + ONE_MONTH: "OneMonth", + SIX_MONTHS: "SixMonths", +}; +const ProvisionedModelStatus = { + CREATING: "Creating", + FAILED: "Failed", + IN_SERVICE: "InService", + UPDATING: "Updating", +}; +const SortByProvisionedModels = { + CREATION_TIME: "CreationTime", +}; +const AuthorizationStatus = { + AUTHORIZED: "AUTHORIZED", + NOT_AUTHORIZED: "NOT_AUTHORIZED", +}; +const EntitlementAvailability = { + AVAILABLE: "AVAILABLE", + NOT_AVAILABLE: "NOT_AVAILABLE", +}; +const RegionAvailability = { + AVAILABLE: "AVAILABLE", + NOT_AVAILABLE: "NOT_AVAILABLE", +}; +const OfferType = { + ALL: "ALL", + PUBLIC: "PUBLIC", +}; +const ModelCustomizationJobStatus = { + COMPLETED: "Completed", + FAILED: "Failed", + IN_PROGRESS: "InProgress", + STOPPED: "Stopped", + STOPPING: "Stopping", +}; +const JobStatusDetails = { + COMPLETED: "Completed", + FAILED: "Failed", + IN_PROGRESS: "InProgress", + NOT_STARTED: "NotStarted", + STOPPED: "Stopped", + STOPPING: "Stopping", +}; +const FineTuningJobStatus = { + COMPLETED: "Completed", + FAILED: "Failed", + IN_PROGRESS: "InProgress", + STOPPED: "Stopped", + STOPPING: "Stopping", +}; + +Object.defineProperty(exports, "$Command", { + enumerable: true, + get: function () { return smithyClient.Command; } +}); +Object.defineProperty(exports, "__Client", { + enumerable: true, + get: function () { return smithyClient.Client; } +}); +exports.AccessDeniedException = AccessDeniedException$1; +exports.AgreementStatus = AgreementStatus; +exports.ApplicationType = ApplicationType; +exports.AttributeType = AttributeType; +exports.AuthorizationStatus = AuthorizationStatus; +exports.AutomatedReasoningCheckLogicWarningType = AutomatedReasoningCheckLogicWarningType; +exports.AutomatedReasoningCheckResult = AutomatedReasoningCheckResult; +exports.AutomatedReasoningPolicyAnnotationStatus = AutomatedReasoningPolicyAnnotationStatus; +exports.AutomatedReasoningPolicyBuildDocumentContentType = AutomatedReasoningPolicyBuildDocumentContentType; +exports.AutomatedReasoningPolicyBuildMessageType = AutomatedReasoningPolicyBuildMessageType; +exports.AutomatedReasoningPolicyBuildResultAssetType = AutomatedReasoningPolicyBuildResultAssetType; +exports.AutomatedReasoningPolicyBuildWorkflowStatus = AutomatedReasoningPolicyBuildWorkflowStatus; +exports.AutomatedReasoningPolicyBuildWorkflowType = AutomatedReasoningPolicyBuildWorkflowType; +exports.AutomatedReasoningPolicyTestRunResult = AutomatedReasoningPolicyTestRunResult; +exports.AutomatedReasoningPolicyTestRunStatus = AutomatedReasoningPolicyTestRunStatus; +exports.BatchDeleteEvaluationJobCommand = BatchDeleteEvaluationJobCommand; +exports.Bedrock = Bedrock; +exports.BedrockClient = BedrockClient; +exports.BedrockServiceException = BedrockServiceException$1; +exports.CancelAutomatedReasoningPolicyBuildWorkflowCommand = CancelAutomatedReasoningPolicyBuildWorkflowCommand; +exports.CommitmentDuration = CommitmentDuration; +exports.ConflictException = ConflictException$1; +exports.CreateAutomatedReasoningPolicyCommand = CreateAutomatedReasoningPolicyCommand; +exports.CreateAutomatedReasoningPolicyTestCaseCommand = CreateAutomatedReasoningPolicyTestCaseCommand; +exports.CreateAutomatedReasoningPolicyVersionCommand = CreateAutomatedReasoningPolicyVersionCommand; +exports.CreateCustomModelCommand = CreateCustomModelCommand; +exports.CreateCustomModelDeploymentCommand = CreateCustomModelDeploymentCommand; +exports.CreateEvaluationJobCommand = CreateEvaluationJobCommand; +exports.CreateFoundationModelAgreementCommand = CreateFoundationModelAgreementCommand; +exports.CreateGuardrailCommand = CreateGuardrailCommand; +exports.CreateGuardrailVersionCommand = CreateGuardrailVersionCommand; +exports.CreateInferenceProfileCommand = CreateInferenceProfileCommand; +exports.CreateMarketplaceModelEndpointCommand = CreateMarketplaceModelEndpointCommand; +exports.CreateModelCopyJobCommand = CreateModelCopyJobCommand; +exports.CreateModelCustomizationJobCommand = CreateModelCustomizationJobCommand; +exports.CreateModelImportJobCommand = CreateModelImportJobCommand; +exports.CreateModelInvocationJobCommand = CreateModelInvocationJobCommand; +exports.CreatePromptRouterCommand = CreatePromptRouterCommand; +exports.CreateProvisionedModelThroughputCommand = CreateProvisionedModelThroughputCommand; +exports.CustomModelDeploymentStatus = CustomModelDeploymentStatus; +exports.CustomizationType = CustomizationType; +exports.DeleteAutomatedReasoningPolicyBuildWorkflowCommand = DeleteAutomatedReasoningPolicyBuildWorkflowCommand; +exports.DeleteAutomatedReasoningPolicyCommand = DeleteAutomatedReasoningPolicyCommand; +exports.DeleteAutomatedReasoningPolicyTestCaseCommand = DeleteAutomatedReasoningPolicyTestCaseCommand; +exports.DeleteCustomModelCommand = DeleteCustomModelCommand; +exports.DeleteCustomModelDeploymentCommand = DeleteCustomModelDeploymentCommand; +exports.DeleteFoundationModelAgreementCommand = DeleteFoundationModelAgreementCommand; +exports.DeleteGuardrailCommand = DeleteGuardrailCommand; +exports.DeleteImportedModelCommand = DeleteImportedModelCommand; +exports.DeleteInferenceProfileCommand = DeleteInferenceProfileCommand; +exports.DeleteMarketplaceModelEndpointCommand = DeleteMarketplaceModelEndpointCommand; +exports.DeleteModelInvocationLoggingConfigurationCommand = DeleteModelInvocationLoggingConfigurationCommand; +exports.DeletePromptRouterCommand = DeletePromptRouterCommand; +exports.DeleteProvisionedModelThroughputCommand = DeleteProvisionedModelThroughputCommand; +exports.DeregisterMarketplaceModelEndpointCommand = DeregisterMarketplaceModelEndpointCommand; +exports.EntitlementAvailability = EntitlementAvailability; +exports.EvaluationJobStatus = EvaluationJobStatus; +exports.EvaluationJobType = EvaluationJobType; +exports.EvaluationTaskType = EvaluationTaskType; +exports.ExportAutomatedReasoningPolicyVersionCommand = ExportAutomatedReasoningPolicyVersionCommand; +exports.ExternalSourceType = ExternalSourceType; +exports.FineTuningJobStatus = FineTuningJobStatus; +exports.FoundationModelLifecycleStatus = FoundationModelLifecycleStatus; +exports.GetAutomatedReasoningPolicyAnnotationsCommand = GetAutomatedReasoningPolicyAnnotationsCommand; +exports.GetAutomatedReasoningPolicyBuildWorkflowCommand = GetAutomatedReasoningPolicyBuildWorkflowCommand; +exports.GetAutomatedReasoningPolicyBuildWorkflowResultAssetsCommand = GetAutomatedReasoningPolicyBuildWorkflowResultAssetsCommand; +exports.GetAutomatedReasoningPolicyCommand = GetAutomatedReasoningPolicyCommand; +exports.GetAutomatedReasoningPolicyNextScenarioCommand = GetAutomatedReasoningPolicyNextScenarioCommand; +exports.GetAutomatedReasoningPolicyTestCaseCommand = GetAutomatedReasoningPolicyTestCaseCommand; +exports.GetAutomatedReasoningPolicyTestResultCommand = GetAutomatedReasoningPolicyTestResultCommand; +exports.GetCustomModelCommand = GetCustomModelCommand; +exports.GetCustomModelDeploymentCommand = GetCustomModelDeploymentCommand; +exports.GetEvaluationJobCommand = GetEvaluationJobCommand; +exports.GetFoundationModelAvailabilityCommand = GetFoundationModelAvailabilityCommand; +exports.GetFoundationModelCommand = GetFoundationModelCommand; +exports.GetGuardrailCommand = GetGuardrailCommand; +exports.GetImportedModelCommand = GetImportedModelCommand; +exports.GetInferenceProfileCommand = GetInferenceProfileCommand; +exports.GetMarketplaceModelEndpointCommand = GetMarketplaceModelEndpointCommand; +exports.GetModelCopyJobCommand = GetModelCopyJobCommand; +exports.GetModelCustomizationJobCommand = GetModelCustomizationJobCommand; +exports.GetModelImportJobCommand = GetModelImportJobCommand; +exports.GetModelInvocationJobCommand = GetModelInvocationJobCommand; +exports.GetModelInvocationLoggingConfigurationCommand = GetModelInvocationLoggingConfigurationCommand; +exports.GetPromptRouterCommand = GetPromptRouterCommand; +exports.GetProvisionedModelThroughputCommand = GetProvisionedModelThroughputCommand; +exports.GetUseCaseForModelAccessCommand = GetUseCaseForModelAccessCommand; +exports.GuardrailContentFilterAction = GuardrailContentFilterAction; +exports.GuardrailContentFilterType = GuardrailContentFilterType; +exports.GuardrailContentFiltersTierName = GuardrailContentFiltersTierName; +exports.GuardrailContextualGroundingAction = GuardrailContextualGroundingAction; +exports.GuardrailContextualGroundingFilterType = GuardrailContextualGroundingFilterType; +exports.GuardrailFilterStrength = GuardrailFilterStrength; +exports.GuardrailManagedWordsType = GuardrailManagedWordsType; +exports.GuardrailModality = GuardrailModality; +exports.GuardrailPiiEntityType = GuardrailPiiEntityType; +exports.GuardrailSensitiveInformationAction = GuardrailSensitiveInformationAction; +exports.GuardrailStatus = GuardrailStatus; +exports.GuardrailTopicAction = GuardrailTopicAction; +exports.GuardrailTopicType = GuardrailTopicType; +exports.GuardrailTopicsTierName = GuardrailTopicsTierName; +exports.GuardrailWordAction = GuardrailWordAction; +exports.InferenceProfileStatus = InferenceProfileStatus; +exports.InferenceProfileType = InferenceProfileType; +exports.InferenceType = InferenceType; +exports.InternalServerException = InternalServerException$1; +exports.JobStatusDetails = JobStatusDetails; +exports.ListAutomatedReasoningPoliciesCommand = ListAutomatedReasoningPoliciesCommand; +exports.ListAutomatedReasoningPolicyBuildWorkflowsCommand = ListAutomatedReasoningPolicyBuildWorkflowsCommand; +exports.ListAutomatedReasoningPolicyTestCasesCommand = ListAutomatedReasoningPolicyTestCasesCommand; +exports.ListAutomatedReasoningPolicyTestResultsCommand = ListAutomatedReasoningPolicyTestResultsCommand; +exports.ListCustomModelDeploymentsCommand = ListCustomModelDeploymentsCommand; +exports.ListCustomModelsCommand = ListCustomModelsCommand; +exports.ListEvaluationJobsCommand = ListEvaluationJobsCommand; +exports.ListFoundationModelAgreementOffersCommand = ListFoundationModelAgreementOffersCommand; +exports.ListFoundationModelsCommand = ListFoundationModelsCommand; +exports.ListGuardrailsCommand = ListGuardrailsCommand; +exports.ListImportedModelsCommand = ListImportedModelsCommand; +exports.ListInferenceProfilesCommand = ListInferenceProfilesCommand; +exports.ListMarketplaceModelEndpointsCommand = ListMarketplaceModelEndpointsCommand; +exports.ListModelCopyJobsCommand = ListModelCopyJobsCommand; +exports.ListModelCustomizationJobsCommand = ListModelCustomizationJobsCommand; +exports.ListModelImportJobsCommand = ListModelImportJobsCommand; +exports.ListModelInvocationJobsCommand = ListModelInvocationJobsCommand; +exports.ListPromptRoutersCommand = ListPromptRoutersCommand; +exports.ListProvisionedModelThroughputsCommand = ListProvisionedModelThroughputsCommand; +exports.ListTagsForResourceCommand = ListTagsForResourceCommand; +exports.ModelCopyJobStatus = ModelCopyJobStatus; +exports.ModelCustomization = ModelCustomization; +exports.ModelCustomizationJobStatus = ModelCustomizationJobStatus; +exports.ModelImportJobStatus = ModelImportJobStatus; +exports.ModelInvocationJobStatus = ModelInvocationJobStatus; +exports.ModelModality = ModelModality; +exports.ModelStatus = ModelStatus; +exports.OfferType = OfferType; +exports.PerformanceConfigLatency = PerformanceConfigLatency; +exports.PromptRouterStatus = PromptRouterStatus; +exports.PromptRouterType = PromptRouterType; +exports.ProvisionedModelStatus = ProvisionedModelStatus; +exports.PutModelInvocationLoggingConfigurationCommand = PutModelInvocationLoggingConfigurationCommand; +exports.PutUseCaseForModelAccessCommand = PutUseCaseForModelAccessCommand; +exports.QueryTransformationType = QueryTransformationType; +exports.RegionAvailability = RegionAvailability; +exports.RegisterMarketplaceModelEndpointCommand = RegisterMarketplaceModelEndpointCommand; +exports.RerankingMetadataSelectionMode = RerankingMetadataSelectionMode; +exports.ResourceInUseException = ResourceInUseException$1; +exports.ResourceNotFoundException = ResourceNotFoundException$1; +exports.RetrieveAndGenerateType = RetrieveAndGenerateType; +exports.S3InputFormat = S3InputFormat; +exports.SearchType = SearchType; +exports.ServiceQuotaExceededException = ServiceQuotaExceededException$1; +exports.ServiceUnavailableException = ServiceUnavailableException$1; +exports.SortByProvisionedModels = SortByProvisionedModels; +exports.SortJobsBy = SortJobsBy; +exports.SortModelsBy = SortModelsBy; +exports.SortOrder = SortOrder; +exports.StartAutomatedReasoningPolicyBuildWorkflowCommand = StartAutomatedReasoningPolicyBuildWorkflowCommand; +exports.StartAutomatedReasoningPolicyTestWorkflowCommand = StartAutomatedReasoningPolicyTestWorkflowCommand; +exports.Status = Status; +exports.StopEvaluationJobCommand = StopEvaluationJobCommand; +exports.StopModelCustomizationJobCommand = StopModelCustomizationJobCommand; +exports.StopModelInvocationJobCommand = StopModelInvocationJobCommand; +exports.TagResourceCommand = TagResourceCommand; +exports.ThrottlingException = ThrottlingException$1; +exports.TooManyTagsException = TooManyTagsException$1; +exports.UntagResourceCommand = UntagResourceCommand; +exports.UpdateAutomatedReasoningPolicyAnnotationsCommand = UpdateAutomatedReasoningPolicyAnnotationsCommand; +exports.UpdateAutomatedReasoningPolicyCommand = UpdateAutomatedReasoningPolicyCommand; +exports.UpdateAutomatedReasoningPolicyTestCaseCommand = UpdateAutomatedReasoningPolicyTestCaseCommand; +exports.UpdateGuardrailCommand = UpdateGuardrailCommand; +exports.UpdateMarketplaceModelEndpointCommand = UpdateMarketplaceModelEndpointCommand; +exports.UpdateProvisionedModelThroughputCommand = UpdateProvisionedModelThroughputCommand; +exports.ValidationException = ValidationException$1; +exports.VectorSearchRerankingConfigurationType = VectorSearchRerankingConfigurationType; +exports.paginateListAutomatedReasoningPolicies = paginateListAutomatedReasoningPolicies; +exports.paginateListAutomatedReasoningPolicyBuildWorkflows = paginateListAutomatedReasoningPolicyBuildWorkflows; +exports.paginateListAutomatedReasoningPolicyTestCases = paginateListAutomatedReasoningPolicyTestCases; +exports.paginateListAutomatedReasoningPolicyTestResults = paginateListAutomatedReasoningPolicyTestResults; +exports.paginateListCustomModelDeployments = paginateListCustomModelDeployments; +exports.paginateListCustomModels = paginateListCustomModels; +exports.paginateListEvaluationJobs = paginateListEvaluationJobs; +exports.paginateListGuardrails = paginateListGuardrails; +exports.paginateListImportedModels = paginateListImportedModels; +exports.paginateListInferenceProfiles = paginateListInferenceProfiles; +exports.paginateListMarketplaceModelEndpoints = paginateListMarketplaceModelEndpoints; +exports.paginateListModelCopyJobs = paginateListModelCopyJobs; +exports.paginateListModelCustomizationJobs = paginateListModelCustomizationJobs; +exports.paginateListModelImportJobs = paginateListModelImportJobs; +exports.paginateListModelInvocationJobs = paginateListModelInvocationJobs; +exports.paginateListPromptRouters = paginateListPromptRouters; +exports.paginateListProvisionedModelThroughputs = paginateListProvisionedModelThroughputs; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/runtimeConfig.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/runtimeConfig.js new file mode 100644 index 00000000..ee8b6f27 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/runtimeConfig.js @@ -0,0 +1,79 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getRuntimeConfig = void 0; +const tslib_1 = require("tslib"); +const package_json_1 = tslib_1.__importDefault(require("../package.json")); +const core_1 = require("@aws-sdk/core"); +const credential_provider_node_1 = require("@aws-sdk/credential-provider-node"); +const token_providers_1 = require("@aws-sdk/token-providers"); +const util_user_agent_node_1 = require("@aws-sdk/util-user-agent-node"); +const config_resolver_1 = require("@smithy/config-resolver"); +const core_2 = require("@smithy/core"); +const hash_node_1 = require("@smithy/hash-node"); +const middleware_retry_1 = require("@smithy/middleware-retry"); +const node_config_provider_1 = require("@smithy/node-config-provider"); +const node_http_handler_1 = require("@smithy/node-http-handler"); +const util_body_length_node_1 = require("@smithy/util-body-length-node"); +const util_retry_1 = require("@smithy/util-retry"); +const runtimeConfig_shared_1 = require("./runtimeConfig.shared"); +const smithy_client_1 = require("@smithy/smithy-client"); +const util_defaults_mode_node_1 = require("@smithy/util-defaults-mode-node"); +const smithy_client_2 = require("@smithy/smithy-client"); +const getRuntimeConfig = (config) => { + (0, smithy_client_2.emitWarningIfUnsupportedVersion)(process.version); + const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config); + const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode); + const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config); + (0, core_1.emitWarningIfUnsupportedVersion)(process.version); + const loaderConfig = { + profile: config?.profile, + logger: clientSharedValues.logger, + signingName: "bedrock", + }; + return { + ...clientSharedValues, + ...config, + runtime: "node", + defaultsMode, + authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), + bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, + credentialDefaultProvider: config?.credentialDefaultProvider ?? credential_provider_node_1.defaultProvider, + defaultUserAgentProvider: config?.defaultUserAgentProvider ?? + (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new core_1.AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#httpBearerAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#httpBearerAuth") || + (async (idProps) => { + try { + return await (0, token_providers_1.fromEnvSigningName)({ signingName: "bedrock" })(); + } + catch (error) { + return await (0, token_providers_1.nodeProvider)(idProps)(idProps); + } + }), + signer: new core_2.HttpBearerAuthSigner(), + }, + ], + maxAttempts: config?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), + region: config?.region ?? + (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), + requestHandler: node_http_handler_1.NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), + retryMode: config?.retryMode ?? + (0, node_config_provider_1.loadConfig)({ + ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS, + default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE, + }, config), + sha256: config?.sha256 ?? hash_node_1.Hash.bind(null, "sha256"), + streamCollector: config?.streamCollector ?? node_http_handler_1.streamCollector, + useDualstackEndpoint: config?.useDualstackEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), + }; +}; +exports.getRuntimeConfig = getRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/runtimeConfig.shared.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/runtimeConfig.shared.js new file mode 100644 index 00000000..cf4b9ba3 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/runtimeConfig.shared.js @@ -0,0 +1,42 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getRuntimeConfig = void 0; +const core_1 = require("@aws-sdk/core"); +const protocols_1 = require("@aws-sdk/core/protocols"); +const core_2 = require("@smithy/core"); +const smithy_client_1 = require("@smithy/smithy-client"); +const url_parser_1 = require("@smithy/url-parser"); +const util_base64_1 = require("@smithy/util-base64"); +const util_utf8_1 = require("@smithy/util-utf8"); +const httpAuthSchemeProvider_1 = require("./auth/httpAuthSchemeProvider"); +const endpointResolver_1 = require("./endpoint/endpointResolver"); +const getRuntimeConfig = (config) => { + return { + apiVersion: "2023-04-20", + base64Decoder: config?.base64Decoder ?? util_base64_1.fromBase64, + base64Encoder: config?.base64Encoder ?? util_base64_1.toBase64, + disableHostPrefix: config?.disableHostPrefix ?? false, + endpointProvider: config?.endpointProvider ?? endpointResolver_1.defaultEndpointResolver, + extensions: config?.extensions ?? [], + httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultBedrockHttpAuthSchemeProvider, + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new core_1.AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#httpBearerAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#httpBearerAuth"), + signer: new core_2.HttpBearerAuthSigner(), + }, + ], + logger: config?.logger ?? new smithy_client_1.NoOpLogger(), + protocol: config?.protocol ?? new protocols_1.AwsRestJsonProtocol({ defaultNamespace: "com.amazonaws.bedrock" }), + serviceId: config?.serviceId ?? "Bedrock", + urlParser: config?.urlParser ?? url_parser_1.parseUrl, + utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, + utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, + }; +}; +exports.getRuntimeConfig = getRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/protocol-http/dist-cjs/index.js new file mode 100644 index 00000000..52303c3b --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/protocol-http/dist-cjs/index.js @@ -0,0 +1,169 @@ +'use strict'; + +var types = require('@smithy/types'); + +const getHttpHandlerExtensionConfiguration = (runtimeConfig) => { + return { + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); + }, + }; +}; +const resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler(), + }; +}; + +class Field { + name; + kind; + values; + constructor({ name, kind = types.FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; + } + add(value) { + this.values.push(value); + } + set(values) { + this.values = values; + } + remove(value) { + this.values = this.values.filter((v) => v !== value); + } + toString() { + return this.values.map((v) => (v.includes(",") || v.includes(" ") ? `"${v}"` : v)).join(", "); + } + get() { + return this.values; + } +} + +class Fields { + entries = {}; + encoding; + constructor({ fields = [], encoding = "utf-8" }) { + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + setField(field) { + this.entries[field.name.toLowerCase()] = field; + } + getField(name) { + return this.entries[name.toLowerCase()]; + } + removeField(name) { + delete this.entries[name.toLowerCase()]; + } + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } +} + +class HttpRequest { + method; + protocol; + hostname; + port; + path; + query; + headers; + username; + password; + fragment; + body; + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol + ? options.protocol.slice(-1) !== ":" + ? `${options.protocol}:` + : options.protocol + : "https:"; + this.path = options.path ? (options.path.charAt(0) !== "/" ? `/${options.path}` : options.path) : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + static clone(request) { + const cloned = new HttpRequest({ + ...request, + headers: { ...request.headers }, + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); + } + return cloned; + } + static isInstance(request) { + if (!request) { + return false; + } + const req = request; + return ("method" in req && + "protocol" in req && + "hostname" in req && + "path" in req && + typeof req["query"] === "object" && + typeof req["headers"] === "object"); + } + clone() { + return HttpRequest.clone(this); + } +} +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param, + }; + }, {}); +} + +class HttpResponse { + statusCode; + reason; + headers; + body; + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) + return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + } +} + +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} + +exports.Field = Field; +exports.Fields = Fields; +exports.HttpRequest = HttpRequest; +exports.HttpResponse = HttpResponse; +exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration; +exports.isValidHostname = isValidHostname; +exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/smithy-client/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/smithy-client/dist-cjs/index.js new file mode 100644 index 00000000..9f589873 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/smithy-client/dist-cjs/index.js @@ -0,0 +1,589 @@ +'use strict'; + +var middlewareStack = require('@smithy/middleware-stack'); +var protocols = require('@smithy/core/protocols'); +var types = require('@smithy/types'); +var schema = require('@smithy/core/schema'); +var serde = require('@smithy/core/serde'); + +class Client { + config; + middlewareStack = middlewareStack.constructStack(); + initConfig; + handlers; + constructor(config) { + this.config = config; + } + send(command, optionsOrCb, cb) { + const options = typeof optionsOrCb !== "function" ? optionsOrCb : undefined; + const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb; + const useHandlerCache = options === undefined && this.config.cacheMiddleware === true; + let handler; + if (useHandlerCache) { + if (!this.handlers) { + this.handlers = new WeakMap(); + } + const handlers = this.handlers; + if (handlers.has(command.constructor)) { + handler = handlers.get(command.constructor); + } + else { + handler = command.resolveMiddleware(this.middlewareStack, this.config, options); + handlers.set(command.constructor, handler); + } + } + else { + delete this.handlers; + handler = command.resolveMiddleware(this.middlewareStack, this.config, options); + } + if (callback) { + handler(command) + .then((result) => callback(null, result.output), (err) => callback(err)) + .catch(() => { }); + } + else { + return handler(command).then((result) => result.output); + } + } + destroy() { + this.config?.requestHandler?.destroy?.(); + delete this.handlers; + } +} + +const SENSITIVE_STRING$1 = "***SensitiveInformation***"; +function schemaLogFilter(schema$1, data) { + if (data == null) { + return data; + } + const ns = schema.NormalizedSchema.of(schema$1); + if (ns.getMergedTraits().sensitive) { + return SENSITIVE_STRING$1; + } + if (ns.isListSchema()) { + const isSensitive = !!ns.getValueSchema().getMergedTraits().sensitive; + if (isSensitive) { + return SENSITIVE_STRING$1; + } + } + else if (ns.isMapSchema()) { + const isSensitive = !!ns.getKeySchema().getMergedTraits().sensitive || !!ns.getValueSchema().getMergedTraits().sensitive; + if (isSensitive) { + return SENSITIVE_STRING$1; + } + } + else if (ns.isStructSchema() && typeof data === "object") { + const object = data; + const newObject = {}; + for (const [member, memberNs] of ns.structIterator()) { + if (object[member] != null) { + newObject[member] = schemaLogFilter(memberNs, object[member]); + } + } + return newObject; + } + return data; +} + +class Command { + middlewareStack = middlewareStack.constructStack(); + schema; + static classBuilder() { + return new ClassBuilder(); + } + resolveMiddlewareWithContext(clientStack, configuration, options, { middlewareFn, clientName, commandName, inputFilterSensitiveLog, outputFilterSensitiveLog, smithyContext, additionalContext, CommandCtor, }) { + for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options)) { + this.middlewareStack.use(mw); + } + const stack = clientStack.concat(this.middlewareStack); + const { logger } = configuration; + const handlerExecutionContext = { + logger, + clientName, + commandName, + inputFilterSensitiveLog, + outputFilterSensitiveLog, + [types.SMITHY_CONTEXT_KEY]: { + commandInstance: this, + ...smithyContext, + }, + ...additionalContext, + }; + const { requestHandler } = configuration; + return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); + } +} +class ClassBuilder { + _init = () => { }; + _ep = {}; + _middlewareFn = () => []; + _commandName = ""; + _clientName = ""; + _additionalContext = {}; + _smithyContext = {}; + _inputFilterSensitiveLog = undefined; + _outputFilterSensitiveLog = undefined; + _serializer = null; + _deserializer = null; + _operationSchema; + init(cb) { + this._init = cb; + } + ep(endpointParameterInstructions) { + this._ep = endpointParameterInstructions; + return this; + } + m(middlewareSupplier) { + this._middlewareFn = middlewareSupplier; + return this; + } + s(service, operation, smithyContext = {}) { + this._smithyContext = { + service, + operation, + ...smithyContext, + }; + return this; + } + c(additionalContext = {}) { + this._additionalContext = additionalContext; + return this; + } + n(clientName, commandName) { + this._clientName = clientName; + this._commandName = commandName; + return this; + } + f(inputFilter = (_) => _, outputFilter = (_) => _) { + this._inputFilterSensitiveLog = inputFilter; + this._outputFilterSensitiveLog = outputFilter; + return this; + } + ser(serializer) { + this._serializer = serializer; + return this; + } + de(deserializer) { + this._deserializer = deserializer; + return this; + } + sc(operation) { + this._operationSchema = operation; + this._smithyContext.operationSchema = operation; + return this; + } + build() { + const closure = this; + let CommandRef; + return (CommandRef = class extends Command { + input; + static getEndpointParameterInstructions() { + return closure._ep; + } + constructor(...[input]) { + super(); + this.input = input ?? {}; + closure._init(this); + this.schema = closure._operationSchema; + } + resolveMiddleware(stack, configuration, options) { + const op = closure._operationSchema; + const input = op?.[4] ?? op?.input; + const output = op?.[5] ?? op?.output; + return this.resolveMiddlewareWithContext(stack, configuration, options, { + CommandCtor: CommandRef, + middlewareFn: closure._middlewareFn, + clientName: closure._clientName, + commandName: closure._commandName, + inputFilterSensitiveLog: closure._inputFilterSensitiveLog ?? (op ? schemaLogFilter.bind(null, input) : (_) => _), + outputFilterSensitiveLog: closure._outputFilterSensitiveLog ?? (op ? schemaLogFilter.bind(null, output) : (_) => _), + smithyContext: closure._smithyContext, + additionalContext: closure._additionalContext, + }); + } + serialize = closure._serializer; + deserialize = closure._deserializer; + }); + } +} + +const SENSITIVE_STRING = "***SensitiveInformation***"; + +const createAggregatedClient = (commands, Client) => { + for (const command of Object.keys(commands)) { + const CommandCtor = commands[command]; + const methodImpl = async function (args, optionsOrCb, cb) { + const command = new CommandCtor(args); + if (typeof optionsOrCb === "function") { + this.send(command, optionsOrCb); + } + else if (typeof cb === "function") { + if (typeof optionsOrCb !== "object") + throw new Error(`Expected http options but got ${typeof optionsOrCb}`); + this.send(command, optionsOrCb || {}, cb); + } + else { + return this.send(command, optionsOrCb); + } + }; + const methodName = (command[0].toLowerCase() + command.slice(1)).replace(/Command$/, ""); + Client.prototype[methodName] = methodImpl; + } +}; + +class ServiceException extends Error { + $fault; + $response; + $retryable; + $metadata; + constructor(options) { + super(options.message); + Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype); + this.name = options.name; + this.$fault = options.$fault; + this.$metadata = options.$metadata; + } + static isInstance(value) { + if (!value) + return false; + const candidate = value; + return (ServiceException.prototype.isPrototypeOf(candidate) || + (Boolean(candidate.$fault) && + Boolean(candidate.$metadata) && + (candidate.$fault === "client" || candidate.$fault === "server"))); + } + static [Symbol.hasInstance](instance) { + if (!instance) + return false; + const candidate = instance; + if (this === ServiceException) { + return ServiceException.isInstance(instance); + } + if (ServiceException.isInstance(instance)) { + if (candidate.name && this.name) { + return this.prototype.isPrototypeOf(instance) || candidate.name === this.name; + } + return this.prototype.isPrototypeOf(instance); + } + return false; + } +} +const decorateServiceException = (exception, additions = {}) => { + Object.entries(additions) + .filter(([, v]) => v !== undefined) + .forEach(([k, v]) => { + if (exception[k] == undefined || exception[k] === "") { + exception[k] = v; + } + }); + const message = exception.message || exception.Message || "UnknownError"; + exception.message = message; + delete exception.Message; + return exception; +}; + +const throwDefaultError = ({ output, parsedBody, exceptionCtor, errorCode }) => { + const $metadata = deserializeMetadata(output); + const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : undefined; + const response = new exceptionCtor({ + name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || "UnknownError", + $fault: "client", + $metadata, + }); + throw decorateServiceException(response, parsedBody); +}; +const withBaseException = (ExceptionCtor) => { + return ({ output, parsedBody, errorCode }) => { + throwDefaultError({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode }); + }; +}; +const deserializeMetadata = (output) => ({ + httpStatusCode: output.statusCode, + requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], + extendedRequestId: output.headers["x-amz-id-2"], + cfId: output.headers["x-amz-cf-id"], +}); + +const loadConfigsForDefaultMode = (mode) => { + switch (mode) { + case "standard": + return { + retryMode: "standard", + connectionTimeout: 3100, + }; + case "in-region": + return { + retryMode: "standard", + connectionTimeout: 1100, + }; + case "cross-region": + return { + retryMode: "standard", + connectionTimeout: 3100, + }; + case "mobile": + return { + retryMode: "standard", + connectionTimeout: 30000, + }; + default: + return {}; + } +}; + +let warningEmitted = false; +const emitWarningIfUnsupportedVersion = (version) => { + if (version && !warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 16) { + warningEmitted = true; + } +}; + +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + for (const id in types.AlgorithmId) { + const algorithmId = types.AlgorithmId[id]; + if (runtimeConfig[algorithmId] === undefined) { + continue; + } + checksumAlgorithms.push({ + algorithmId: () => algorithmId, + checksumConstructor: () => runtimeConfig[algorithmId], + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getRetryConfiguration = (runtimeConfig) => { + return { + setRetryStrategy(retryStrategy) { + runtimeConfig.retryStrategy = retryStrategy; + }, + retryStrategy() { + return runtimeConfig.retryStrategy; + }, + }; +}; +const resolveRetryRuntimeConfig = (retryStrategyConfiguration) => { + const runtimeConfig = {}; + runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy(); + return runtimeConfig; +}; + +const getDefaultExtensionConfiguration = (runtimeConfig) => { + return Object.assign(getChecksumConfiguration(runtimeConfig), getRetryConfiguration(runtimeConfig)); +}; +const getDefaultClientConfiguration = getDefaultExtensionConfiguration; +const resolveDefaultRuntimeConfig = (config) => { + return Object.assign(resolveChecksumRuntimeConfig(config), resolveRetryRuntimeConfig(config)); +}; + +const getArrayIfSingleItem = (mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray]; + +const getValueFromTextNode = (obj) => { + const textNodeName = "#text"; + for (const key in obj) { + if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== undefined) { + obj[key] = obj[key][textNodeName]; + } + else if (typeof obj[key] === "object" && obj[key] !== null) { + obj[key] = getValueFromTextNode(obj[key]); + } + } + return obj; +}; + +const isSerializableHeaderValue = (value) => { + return value != null; +}; + +class NoOpLogger { + trace() { } + debug() { } + info() { } + warn() { } + error() { } +} + +function map(arg0, arg1, arg2) { + let target; + let filter; + let instructions; + if (typeof arg1 === "undefined" && typeof arg2 === "undefined") { + target = {}; + instructions = arg0; + } + else { + target = arg0; + if (typeof arg1 === "function") { + filter = arg1; + instructions = arg2; + return mapWithFilter(target, filter, instructions); + } + else { + instructions = arg1; + } + } + for (const key of Object.keys(instructions)) { + if (!Array.isArray(instructions[key])) { + target[key] = instructions[key]; + continue; + } + applyInstruction(target, null, instructions, key); + } + return target; +} +const convertMap = (target) => { + const output = {}; + for (const [k, v] of Object.entries(target || {})) { + output[k] = [, v]; + } + return output; +}; +const take = (source, instructions) => { + const out = {}; + for (const key in instructions) { + applyInstruction(out, source, instructions, key); + } + return out; +}; +const mapWithFilter = (target, filter, instructions) => { + return map(target, Object.entries(instructions).reduce((_instructions, [key, value]) => { + if (Array.isArray(value)) { + _instructions[key] = value; + } + else { + if (typeof value === "function") { + _instructions[key] = [filter, value()]; + } + else { + _instructions[key] = [filter, value]; + } + } + return _instructions; + }, {})); +}; +const applyInstruction = (target, source, instructions, targetKey) => { + if (source !== null) { + let instruction = instructions[targetKey]; + if (typeof instruction === "function") { + instruction = [, instruction]; + } + const [filter = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction; + if ((typeof filter === "function" && filter(source[sourceKey])) || (typeof filter !== "function" && !!filter)) { + target[targetKey] = valueFn(source[sourceKey]); + } + return; + } + let [filter, value] = instructions[targetKey]; + if (typeof value === "function") { + let _value; + const defaultFilterPassed = filter === undefined && (_value = value()) != null; + const customFilterPassed = (typeof filter === "function" && !!filter(void 0)) || (typeof filter !== "function" && !!filter); + if (defaultFilterPassed) { + target[targetKey] = _value; + } + else if (customFilterPassed) { + target[targetKey] = value(); + } + } + else { + const defaultFilterPassed = filter === undefined && value != null; + const customFilterPassed = (typeof filter === "function" && !!filter(value)) || (typeof filter !== "function" && !!filter); + if (defaultFilterPassed || customFilterPassed) { + target[targetKey] = value; + } + } +}; +const nonNullish = (_) => _ != null; +const pass = (_) => _; + +const serializeFloat = (value) => { + if (value !== value) { + return "NaN"; + } + switch (value) { + case Infinity: + return "Infinity"; + case -Infinity: + return "-Infinity"; + default: + return value; + } +}; +const serializeDateTime = (date) => date.toISOString().replace(".000Z", "Z"); + +const _json = (obj) => { + if (obj == null) { + return {}; + } + if (Array.isArray(obj)) { + return obj.filter((_) => _ != null).map(_json); + } + if (typeof obj === "object") { + const target = {}; + for (const key of Object.keys(obj)) { + if (obj[key] == null) { + continue; + } + target[key] = _json(obj[key]); + } + return target; + } + return obj; +}; + +Object.defineProperty(exports, "collectBody", { + enumerable: true, + get: function () { return protocols.collectBody; } +}); +Object.defineProperty(exports, "extendedEncodeURIComponent", { + enumerable: true, + get: function () { return protocols.extendedEncodeURIComponent; } +}); +Object.defineProperty(exports, "resolvedPath", { + enumerable: true, + get: function () { return protocols.resolvedPath; } +}); +exports.Client = Client; +exports.Command = Command; +exports.NoOpLogger = NoOpLogger; +exports.SENSITIVE_STRING = SENSITIVE_STRING; +exports.ServiceException = ServiceException; +exports._json = _json; +exports.convertMap = convertMap; +exports.createAggregatedClient = createAggregatedClient; +exports.decorateServiceException = decorateServiceException; +exports.emitWarningIfUnsupportedVersion = emitWarningIfUnsupportedVersion; +exports.getArrayIfSingleItem = getArrayIfSingleItem; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.getDefaultExtensionConfiguration = getDefaultExtensionConfiguration; +exports.getValueFromTextNode = getValueFromTextNode; +exports.isSerializableHeaderValue = isSerializableHeaderValue; +exports.loadConfigsForDefaultMode = loadConfigsForDefaultMode; +exports.map = map; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; +exports.serializeDateTime = serializeDateTime; +exports.serializeFloat = serializeFloat; +exports.take = take; +exports.throwDefaultError = throwDefaultError; +exports.withBaseException = withBaseException; +Object.keys(serde).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return serde[k]; } + }); +}); diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-cjs/index.js new file mode 100644 index 00000000..be6d0e1a --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-cjs/index.js @@ -0,0 +1,91 @@ +'use strict'; + +exports.HttpAuthLocation = void 0; +(function (HttpAuthLocation) { + HttpAuthLocation["HEADER"] = "header"; + HttpAuthLocation["QUERY"] = "query"; +})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); + +exports.HttpApiKeyAuthLocation = void 0; +(function (HttpApiKeyAuthLocation) { + HttpApiKeyAuthLocation["HEADER"] = "header"; + HttpApiKeyAuthLocation["QUERY"] = "query"; +})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); + +exports.EndpointURLScheme = void 0; +(function (EndpointURLScheme) { + EndpointURLScheme["HTTP"] = "http"; + EndpointURLScheme["HTTPS"] = "https"; +})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); + +exports.AlgorithmId = void 0; +(function (AlgorithmId) { + AlgorithmId["MD5"] = "md5"; + AlgorithmId["CRC32"] = "crc32"; + AlgorithmId["CRC32C"] = "crc32c"; + AlgorithmId["SHA1"] = "sha1"; + AlgorithmId["SHA256"] = "sha256"; +})(exports.AlgorithmId || (exports.AlgorithmId = {})); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.SHA256, + checksumConstructor: () => runtimeConfig.sha256, + }); + } + if (runtimeConfig.md5 != undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.MD5, + checksumConstructor: () => runtimeConfig.md5, + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getDefaultClientConfiguration = (runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}; +const resolveDefaultRuntimeConfig = (config) => { + return resolveChecksumRuntimeConfig(config); +}; + +exports.FieldPosition = void 0; +(function (FieldPosition) { + FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; + FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; +})(exports.FieldPosition || (exports.FieldPosition = {})); + +const SMITHY_CONTEXT_KEY = "__smithy_context"; + +exports.IniSectionType = void 0; +(function (IniSectionType) { + IniSectionType["PROFILE"] = "profile"; + IniSectionType["SSO_SESSION"] = "sso-session"; + IniSectionType["SERVICES"] = "services"; +})(exports.IniSectionType || (exports.IniSectionType = {})); + +exports.RequestHandlerProtocol = void 0; +(function (RequestHandlerProtocol) { + RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; +})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); + +exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js new file mode 100644 index 00000000..b06a7b87 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromBase64 = void 0; +const util_buffer_from_1 = require("@smithy/util-buffer-from"); +const BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; +const fromBase64 = (input) => { + if ((input.length * 3) % 4 !== 0) { + throw new TypeError(`Incorrect padding on base64 string.`); + } + if (!BASE64_REGEX.exec(input)) { + throw new TypeError(`Invalid base64 string.`); + } + const buffer = (0, util_buffer_from_1.fromString)(input, "base64"); + return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); +}; +exports.fromBase64 = fromBase64; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/dist-cjs/index.js new file mode 100644 index 00000000..c095e288 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/dist-cjs/index.js @@ -0,0 +1,19 @@ +'use strict'; + +var fromBase64 = require('./fromBase64'); +var toBase64 = require('./toBase64'); + + + +Object.keys(fromBase64).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return fromBase64[k]; } + }); +}); +Object.keys(toBase64).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return toBase64[k]; } + }); +}); diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/dist-cjs/toBase64.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/dist-cjs/toBase64.js new file mode 100644 index 00000000..0590ce3f --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/dist-cjs/toBase64.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.toBase64 = void 0; +const util_buffer_from_1 = require("@smithy/util-buffer-from"); +const util_utf8_1 = require("@smithy/util-utf8"); +const toBase64 = (_input) => { + let input; + if (typeof _input === "string") { + input = (0, util_utf8_1.fromUtf8)(_input); + } + else { + input = _input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); + } + return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64"); +}; +exports.toBase64 = toBase64; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js new file mode 100644 index 00000000..b577c9ca --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js @@ -0,0 +1,20 @@ +'use strict'; + +var isArrayBuffer = require('@smithy/is-array-buffer'); +var buffer = require('buffer'); + +const fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => { + if (!isArrayBuffer.isArrayBuffer(input)) { + throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); + } + return buffer.Buffer.from(input, offset, length); +}; +const fromString = (input, encoding) => { + if (typeof input !== "string") { + throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); + } + return encoding ? buffer.Buffer.from(input, encoding) : buffer.Buffer.from(input); +}; + +exports.fromArrayBuffer = fromArrayBuffer; +exports.fromString = fromString; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js new file mode 100644 index 00000000..3238bb77 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js @@ -0,0 +1,6 @@ +'use strict'; + +const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) || + Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; + +exports.isArrayBuffer = isArrayBuffer; diff --git a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/auth/httpAuthSchemeProvider.js b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/auth/httpAuthSchemeProvider.js new file mode 100644 index 00000000..5f7bb744 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/auth/httpAuthSchemeProvider.js @@ -0,0 +1,68 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.resolveHttpAuthSchemeConfig = exports.defaultCognitoIdentityHttpAuthSchemeProvider = exports.defaultCognitoIdentityHttpAuthSchemeParametersProvider = void 0; +const core_1 = require("@aws-sdk/core"); +const util_middleware_1 = require("@smithy/util-middleware"); +const defaultCognitoIdentityHttpAuthSchemeParametersProvider = async (config, context, input) => { + return { + operation: (0, util_middleware_1.getSmithyContext)(context).operation, + region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || + (() => { + throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); + })(), + }; +}; +exports.defaultCognitoIdentityHttpAuthSchemeParametersProvider = defaultCognitoIdentityHttpAuthSchemeParametersProvider; +function createAwsAuthSigv4HttpAuthOption(authParameters) { + return { + schemeId: "aws.auth#sigv4", + signingProperties: { + name: "cognito-identity", + region: authParameters.region, + }, + propertiesExtractor: (config, context) => ({ + signingProperties: { + config, + context, + }, + }), + }; +} +function createSmithyApiNoAuthHttpAuthOption(authParameters) { + return { + schemeId: "smithy.api#noAuth", + }; +} +const defaultCognitoIdentityHttpAuthSchemeProvider = (authParameters) => { + const options = []; + switch (authParameters.operation) { + case "GetCredentialsForIdentity": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + case "GetId": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + case "GetOpenIdToken": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + case "UnlinkIdentity": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + default: { + options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); + } + } + return options; +}; +exports.defaultCognitoIdentityHttpAuthSchemeProvider = defaultCognitoIdentityHttpAuthSchemeProvider; +const resolveHttpAuthSchemeConfig = (config) => { + const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config); + return Object.assign(config_0, { + authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), + }); +}; +exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/endpoint/endpointResolver.js b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/endpoint/endpointResolver.js new file mode 100644 index 00000000..7258a356 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/endpoint/endpointResolver.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defaultEndpointResolver = void 0; +const util_endpoints_1 = require("@aws-sdk/util-endpoints"); +const util_endpoints_2 = require("@smithy/util-endpoints"); +const ruleset_1 = require("./ruleset"); +const cache = new util_endpoints_2.EndpointCache({ + size: 50, + params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"], +}); +const defaultEndpointResolver = (endpointParams, context = {}) => { + return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { + endpointParams: endpointParams, + logger: context.logger, + })); +}; +exports.defaultEndpointResolver = defaultEndpointResolver; +util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; diff --git a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/endpoint/ruleset.js b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/endpoint/ruleset.js new file mode 100644 index 00000000..e1510fa2 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/endpoint/ruleset.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ruleSet = void 0; +const w = "required", x = "fn", y = "argv", z = "ref"; +const a = true, b = "isSet", c = "booleanEquals", d = "error", e = "endpoint", f = "tree", g = "PartitionResult", h = "getAttr", i = "stringEquals", j = { [w]: false, "type": "string" }, k = { [w]: true, "default": false, "type": "boolean" }, l = { [z]: "Endpoint" }, m = { [x]: c, [y]: [{ [z]: "UseFIPS" }, true] }, n = { [x]: c, [y]: [{ [z]: "UseDualStack" }, true] }, o = {}, p = { [z]: "Region" }, q = { [x]: h, [y]: [{ [z]: g }, "supportsFIPS"] }, r = { [z]: g }, s = { [x]: c, [y]: [true, { [x]: h, [y]: [r, "supportsDualStack"] }] }, t = [m], u = [n], v = [p]; +const _data = { version: "1.0", parameters: { Region: j, UseDualStack: k, UseFIPS: k, Endpoint: j }, rules: [{ conditions: [{ [x]: b, [y]: [l] }], rules: [{ conditions: t, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d }, { conditions: u, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d }, { endpoint: { url: l, properties: o, headers: o }, type: e }], type: f }, { conditions: [{ [x]: b, [y]: v }], rules: [{ conditions: [{ [x]: "aws.partition", [y]: v, assign: g }], rules: [{ conditions: [m, n], rules: [{ conditions: [{ [x]: c, [y]: [a, q] }, s], rules: [{ conditions: [{ [x]: i, [y]: [p, "us-east-1"] }], endpoint: { url: "https://cognito-identity-fips.us-east-1.amazonaws.com", properties: o, headers: o }, type: e }, { conditions: [{ [x]: i, [y]: [p, "us-east-2"] }], endpoint: { url: "https://cognito-identity-fips.us-east-2.amazonaws.com", properties: o, headers: o }, type: e }, { conditions: [{ [x]: i, [y]: [p, "us-west-1"] }], endpoint: { url: "https://cognito-identity-fips.us-west-1.amazonaws.com", properties: o, headers: o }, type: e }, { conditions: [{ [x]: i, [y]: [p, "us-west-2"] }], endpoint: { url: "https://cognito-identity-fips.us-west-2.amazonaws.com", properties: o, headers: o }, type: e }, { endpoint: { url: "https://cognito-identity-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: o, headers: o }, type: e }], type: f }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d }], type: f }, { conditions: t, rules: [{ conditions: [{ [x]: c, [y]: [q, a] }], rules: [{ endpoint: { url: "https://cognito-identity-fips.{Region}.{PartitionResult#dnsSuffix}", properties: o, headers: o }, type: e }], type: f }, { error: "FIPS is enabled but this partition does not support FIPS", type: d }], type: f }, { conditions: u, rules: [{ conditions: [s], rules: [{ conditions: [{ [x]: i, [y]: ["aws", { [x]: h, [y]: [r, "name"] }] }], endpoint: { url: "https://cognito-identity.{Region}.amazonaws.com", properties: o, headers: o }, type: e }, { endpoint: { url: "https://cognito-identity.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: o, headers: o }, type: e }], type: f }, { error: "DualStack is enabled but this partition does not support DualStack", type: d }], type: f }, { endpoint: { url: "https://cognito-identity.{Region}.{PartitionResult#dnsSuffix}", properties: o, headers: o }, type: e }], type: f }], type: f }, { error: "Invalid Configuration: Missing Region", type: d }] }; +exports.ruleSet = _data; diff --git a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/index.js new file mode 100644 index 00000000..dd92a297 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/index.js @@ -0,0 +1,1266 @@ +'use strict'; + +var middlewareHostHeader = require('@aws-sdk/middleware-host-header'); +var middlewareLogger = require('@aws-sdk/middleware-logger'); +var middlewareRecursionDetection = require('@aws-sdk/middleware-recursion-detection'); +var middlewareUserAgent = require('@aws-sdk/middleware-user-agent'); +var configResolver = require('@smithy/config-resolver'); +var core = require('@smithy/core'); +var schema = require('@smithy/core/schema'); +var middlewareContentLength = require('@smithy/middleware-content-length'); +var middlewareEndpoint = require('@smithy/middleware-endpoint'); +var middlewareRetry = require('@smithy/middleware-retry'); +var smithyClient = require('@smithy/smithy-client'); +var httpAuthSchemeProvider = require('./auth/httpAuthSchemeProvider'); +var runtimeConfig = require('./runtimeConfig'); +var regionConfigResolver = require('@aws-sdk/region-config-resolver'); +var protocolHttp = require('@smithy/protocol-http'); + +const resolveClientEndpointParameters = (options) => { + return Object.assign(options, { + useDualstackEndpoint: options.useDualstackEndpoint ?? false, + useFipsEndpoint: options.useFipsEndpoint ?? false, + defaultSigningName: "cognito-identity", + }); +}; +const commonParams = { + UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, + Endpoint: { type: "builtInParams", name: "endpoint" }, + Region: { type: "builtInParams", name: "region" }, + UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, +}; + +const getHttpAuthExtensionConfiguration = (runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + return { + setHttpAuthScheme(httpAuthScheme) { + const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } + else { + _httpAuthSchemes.splice(index, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; + }, + }; +}; +const resolveHttpAuthRuntimeConfig = (config) => { + return { + httpAuthSchemes: config.httpAuthSchemes(), + httpAuthSchemeProvider: config.httpAuthSchemeProvider(), + credentials: config.credentials(), + }; +}; + +const resolveRuntimeExtensions = (runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign(regionConfigResolver.getAwsRegionExtensionConfiguration(runtimeConfig), smithyClient.getDefaultExtensionConfiguration(runtimeConfig), protocolHttp.getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig)); + extensions.forEach((extension) => extension.configure(extensionConfiguration)); + return Object.assign(runtimeConfig, regionConfigResolver.resolveAwsRegionExtensionConfiguration(extensionConfiguration), smithyClient.resolveDefaultRuntimeConfig(extensionConfiguration), protocolHttp.resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration)); +}; + +class CognitoIdentityClient extends smithyClient.Client { + config; + constructor(...[configuration]) { + const _config_0 = runtimeConfig.getRuntimeConfig(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = resolveClientEndpointParameters(_config_0); + const _config_2 = middlewareUserAgent.resolveUserAgentConfig(_config_1); + const _config_3 = middlewareRetry.resolveRetryConfig(_config_2); + const _config_4 = configResolver.resolveRegionConfig(_config_3); + const _config_5 = middlewareHostHeader.resolveHostHeaderConfig(_config_4); + const _config_6 = middlewareEndpoint.resolveEndpointConfig(_config_5); + const _config_7 = httpAuthSchemeProvider.resolveHttpAuthSchemeConfig(_config_6); + const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); + this.config = _config_8; + this.middlewareStack.use(schema.getSchemaSerdePlugin(this.config)); + this.middlewareStack.use(middlewareUserAgent.getUserAgentPlugin(this.config)); + this.middlewareStack.use(middlewareRetry.getRetryPlugin(this.config)); + this.middlewareStack.use(middlewareContentLength.getContentLengthPlugin(this.config)); + this.middlewareStack.use(middlewareHostHeader.getHostHeaderPlugin(this.config)); + this.middlewareStack.use(middlewareLogger.getLoggerPlugin(this.config)); + this.middlewareStack.use(middlewareRecursionDetection.getRecursionDetectionPlugin(this.config)); + this.middlewareStack.use(core.getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { + httpAuthSchemeParametersProvider: httpAuthSchemeProvider.defaultCognitoIdentityHttpAuthSchemeParametersProvider, + identityProviderConfigProvider: async (config) => new core.DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config.credentials, + }), + })); + this.middlewareStack.use(core.getHttpSigningPlugin(this.config)); + } + destroy() { + super.destroy(); + } +} + +let CognitoIdentityServiceException$1 = class CognitoIdentityServiceException extends smithyClient.ServiceException { + constructor(options) { + super(options); + Object.setPrototypeOf(this, CognitoIdentityServiceException.prototype); + } +}; + +let InternalErrorException$1 = class InternalErrorException extends CognitoIdentityServiceException$1 { + name = "InternalErrorException"; + $fault = "server"; + constructor(opts) { + super({ + name: "InternalErrorException", + $fault: "server", + ...opts, + }); + Object.setPrototypeOf(this, InternalErrorException.prototype); + } +}; +let InvalidParameterException$1 = class InvalidParameterException extends CognitoIdentityServiceException$1 { + name = "InvalidParameterException"; + $fault = "client"; + constructor(opts) { + super({ + name: "InvalidParameterException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, InvalidParameterException.prototype); + } +}; +let LimitExceededException$1 = class LimitExceededException extends CognitoIdentityServiceException$1 { + name = "LimitExceededException"; + $fault = "client"; + constructor(opts) { + super({ + name: "LimitExceededException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, LimitExceededException.prototype); + } +}; +let NotAuthorizedException$1 = class NotAuthorizedException extends CognitoIdentityServiceException$1 { + name = "NotAuthorizedException"; + $fault = "client"; + constructor(opts) { + super({ + name: "NotAuthorizedException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, NotAuthorizedException.prototype); + } +}; +let ResourceConflictException$1 = class ResourceConflictException extends CognitoIdentityServiceException$1 { + name = "ResourceConflictException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ResourceConflictException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ResourceConflictException.prototype); + } +}; +let TooManyRequestsException$1 = class TooManyRequestsException extends CognitoIdentityServiceException$1 { + name = "TooManyRequestsException"; + $fault = "client"; + constructor(opts) { + super({ + name: "TooManyRequestsException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, TooManyRequestsException.prototype); + } +}; +let ResourceNotFoundException$1 = class ResourceNotFoundException extends CognitoIdentityServiceException$1 { + name = "ResourceNotFoundException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ResourceNotFoundException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ResourceNotFoundException.prototype); + } +}; +let ExternalServiceException$1 = class ExternalServiceException extends CognitoIdentityServiceException$1 { + name = "ExternalServiceException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ExternalServiceException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ExternalServiceException.prototype); + } +}; +let InvalidIdentityPoolConfigurationException$1 = class InvalidIdentityPoolConfigurationException extends CognitoIdentityServiceException$1 { + name = "InvalidIdentityPoolConfigurationException"; + $fault = "client"; + constructor(opts) { + super({ + name: "InvalidIdentityPoolConfigurationException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, InvalidIdentityPoolConfigurationException.prototype); + } +}; +let DeveloperUserAlreadyRegisteredException$1 = class DeveloperUserAlreadyRegisteredException extends CognitoIdentityServiceException$1 { + name = "DeveloperUserAlreadyRegisteredException"; + $fault = "client"; + constructor(opts) { + super({ + name: "DeveloperUserAlreadyRegisteredException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, DeveloperUserAlreadyRegisteredException.prototype); + } +}; +let ConcurrentModificationException$1 = class ConcurrentModificationException extends CognitoIdentityServiceException$1 { + name = "ConcurrentModificationException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ConcurrentModificationException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ConcurrentModificationException.prototype); + } +}; + +const _ACF = "AllowClassicFlow"; +const _AI = "AccountId"; +const _AKI = "AccessKeyId"; +const _ARR = "AmbiguousRoleResolution"; +const _AUI = "AllowUnauthenticatedIdentities"; +const _C = "Credentials"; +const _CD = "CreationDate"; +const _CI = "ClientId"; +const _CIP = "CognitoIdentityProvider"; +const _CIPI = "CreateIdentityPoolInput"; +const _CIPL = "CognitoIdentityProviderList"; +const _CIPo = "CognitoIdentityProviders"; +const _CIPr = "CreateIdentityPool"; +const _CME = "ConcurrentModificationException"; +const _CRA = "CustomRoleArn"; +const _Cl = "Claim"; +const _DI = "DeleteIdentities"; +const _DII = "DeleteIdentitiesInput"; +const _DIIe = "DescribeIdentityInput"; +const _DIP = "DeleteIdentityPool"; +const _DIPI = "DeleteIdentityPoolInput"; +const _DIPIe = "DescribeIdentityPoolInput"; +const _DIPe = "DescribeIdentityPool"; +const _DIR = "DeleteIdentitiesResponse"; +const _DIe = "DescribeIdentity"; +const _DPN = "DeveloperProviderName"; +const _DUARE = "DeveloperUserAlreadyRegisteredException"; +const _DUI = "DeveloperUserIdentifier"; +const _DUIL = "DeveloperUserIdentifierList"; +const _DUIe = "DestinationUserIdentifier"; +const _E = "Expiration"; +const _EC = "ErrorCode"; +const _ESE = "ExternalServiceException"; +const _GCFI = "GetCredentialsForIdentity"; +const _GCFII = "GetCredentialsForIdentityInput"; +const _GCFIR = "GetCredentialsForIdentityResponse"; +const _GI = "GetId"; +const _GII = "GetIdInput"; +const _GIPR = "GetIdentityPoolRoles"; +const _GIPRI = "GetIdentityPoolRolesInput"; +const _GIPRR = "GetIdentityPoolRolesResponse"; +const _GIR = "GetIdResponse"; +const _GOIT = "GetOpenIdToken"; +const _GOITFDI = "GetOpenIdTokenForDeveloperIdentity"; +const _GOITFDII = "GetOpenIdTokenForDeveloperIdentityInput"; +const _GOITFDIR = "GetOpenIdTokenForDeveloperIdentityResponse"; +const _GOITI = "GetOpenIdTokenInput"; +const _GOITR = "GetOpenIdTokenResponse"; +const _GPTAM = "GetPrincipalTagAttributeMap"; +const _GPTAMI = "GetPrincipalTagAttributeMapInput"; +const _GPTAMR = "GetPrincipalTagAttributeMapResponse"; +const _HD = "HideDisabled"; +const _I = "Identities"; +const _ID = "IdentityDescription"; +const _IEE = "InternalErrorException"; +const _II = "IdentityId"; +const _IIPCE = "InvalidIdentityPoolConfigurationException"; +const _IITD = "IdentityIdsToDelete"; +const _IL = "IdentitiesList"; +const _IP = "IdentityPool"; +const _IPE = "InvalidParameterException"; +const _IPI = "IdentityPoolId"; +const _IPL = "IdentityPoolsList"; +const _IPN = "IdentityPoolName"; +const _IPNd = "IdentityProviderName"; +const _IPSD = "IdentityPoolShortDescription"; +const _IPT = "IdentityProviderToken"; +const _IPTd = "IdentityPoolTags"; +const _IPd = "IdentityPools"; +const _L = "Logins"; +const _LDI = "LookupDeveloperIdentity"; +const _LDII = "LookupDeveloperIdentityInput"; +const _LDIR = "LookupDeveloperIdentityResponse"; +const _LEE = "LimitExceededException"; +const _LI = "ListIdentities"; +const _LII = "ListIdentitiesInput"; +const _LIP = "ListIdentityPools"; +const _LIPI = "ListIdentityPoolsInput"; +const _LIPR = "ListIdentityPoolsResponse"; +const _LIR = "ListIdentitiesResponse"; +const _LM = "LoginsMap"; +const _LMD = "LastModifiedDate"; +const _LTFR = "ListTagsForResource"; +const _LTFRI = "ListTagsForResourceInput"; +const _LTFRR = "ListTagsForResourceResponse"; +const _LTR = "LoginsToRemove"; +const _MDI = "MergeDeveloperIdentities"; +const _MDII = "MergeDeveloperIdentitiesInput"; +const _MDIR = "MergeDeveloperIdentitiesResponse"; +const _MR = "MaxResults"; +const _MRL = "MappingRulesList"; +const _MRa = "MappingRule"; +const _MT = "MatchType"; +const _NAE = "NotAuthorizedException"; +const _NT = "NextToken"; +const _OICPARN = "OpenIdConnectProviderARNs"; +const _OIDCT = "OIDCToken"; +const _PN = "ProviderName"; +const _PT = "PrincipalTags"; +const _R = "Roles"; +const _RA = "ResourceArn"; +const _RARN = "RoleARN"; +const _RC = "RulesConfiguration"; +const _RCE = "ResourceConflictException"; +const _RCT = "RulesConfigurationType"; +const _RM = "RoleMappings"; +const _RMM = "RoleMappingMap"; +const _RMo = "RoleMapping"; +const _RNFE = "ResourceNotFoundException"; +const _Ru = "Rules"; +const _SIPR = "SetIdentityPoolRoles"; +const _SIPRI = "SetIdentityPoolRolesInput"; +const _SK = "SecretKey"; +const _SKS = "SecretKeyString"; +const _SLP = "SupportedLoginProviders"; +const _SPARN = "SamlProviderARNs"; +const _SPTAM = "SetPrincipalTagAttributeMap"; +const _SPTAMI = "SetPrincipalTagAttributeMapInput"; +const _SPTAMR = "SetPrincipalTagAttributeMapResponse"; +const _SSTC = "ServerSideTokenCheck"; +const _ST = "SessionToken"; +const _SUI = "SourceUserIdentifier"; +const _T = "Token"; +const _TD = "TokenDuration"; +const _TK = "TagKeys"; +const _TMRE = "TooManyRequestsException"; +const _TR = "TagResource"; +const _TRI = "TagResourceInput"; +const _TRR = "TagResourceResponse"; +const _Ta = "Tags"; +const _Ty = "Type"; +const _UD = "UseDefaults"; +const _UDI = "UnlinkDeveloperIdentity"; +const _UDII = "UnlinkDeveloperIdentityInput"; +const _UI = "UnlinkIdentity"; +const _UII = "UnprocessedIdentityIds"; +const _UIIL = "UnprocessedIdentityIdList"; +const _UIIn = "UnlinkIdentityInput"; +const _UIInp = "UnprocessedIdentityId"; +const _UIP = "UpdateIdentityPool"; +const _UR = "UntagResource"; +const _URI = "UntagResourceInput"; +const _URR = "UntagResourceResponse"; +const _V = "Value"; +const _c = "client"; +const _e = "error"; +const _hE = "httpError"; +const _m = "message"; +const _s = "server"; +const _sm = "smithy.ts.sdk.synthetic.com.amazonaws.cognitoidentity"; +const n0 = "com.amazonaws.cognitoidentity"; +var IdentityProviderToken = [0, n0, _IPT, 8, 0]; +var OIDCToken = [0, n0, _OIDCT, 8, 0]; +var SecretKeyString = [0, n0, _SKS, 8, 0]; +var CognitoIdentityProvider = [3, n0, _CIP, 0, [_PN, _CI, _SSTC], [0, 0, 2]]; +var ConcurrentModificationException = [ + -3, + n0, + _CME, + { + [_e]: _c, + [_hE]: 400, + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(ConcurrentModificationException, ConcurrentModificationException$1); +var CreateIdentityPoolInput = [ + 3, + n0, + _CIPI, + 0, + [_IPN, _AUI, _ACF, _SLP, _DPN, _OICPARN, _CIPo, _SPARN, _IPTd], + [0, 2, 2, 128 | 0, 0, 64 | 0, () => CognitoIdentityProviderList, 64 | 0, 128 | 0], +]; +var Credentials = [ + 3, + n0, + _C, + 0, + [_AKI, _SK, _ST, _E], + [0, [() => SecretKeyString, 0], 0, 4], +]; +var DeleteIdentitiesInput = [3, n0, _DII, 0, [_IITD], [64 | 0]]; +var DeleteIdentitiesResponse = [ + 3, + n0, + _DIR, + 0, + [_UII], + [() => UnprocessedIdentityIdList], +]; +var DeleteIdentityPoolInput = [3, n0, _DIPI, 0, [_IPI], [0]]; +var DescribeIdentityInput = [3, n0, _DIIe, 0, [_II], [0]]; +var DescribeIdentityPoolInput = [3, n0, _DIPIe, 0, [_IPI], [0]]; +var DeveloperUserAlreadyRegisteredException = [ + -3, + n0, + _DUARE, + { + [_e]: _c, + [_hE]: 400, + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(DeveloperUserAlreadyRegisteredException, DeveloperUserAlreadyRegisteredException$1); +var ExternalServiceException = [ + -3, + n0, + _ESE, + { + [_e]: _c, + [_hE]: 400, + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(ExternalServiceException, ExternalServiceException$1); +var GetCredentialsForIdentityInput = [ + 3, + n0, + _GCFII, + 0, + [_II, _L, _CRA], + [0, [() => LoginsMap, 0], 0], +]; +var GetCredentialsForIdentityResponse = [ + 3, + n0, + _GCFIR, + 0, + [_II, _C], + [0, [() => Credentials, 0]], +]; +var GetIdentityPoolRolesInput = [3, n0, _GIPRI, 0, [_IPI], [0]]; +var GetIdentityPoolRolesResponse = [ + 3, + n0, + _GIPRR, + 0, + [_IPI, _R, _RM], + [0, 128 | 0, () => RoleMappingMap], +]; +var GetIdInput = [3, n0, _GII, 0, [_AI, _IPI, _L], [0, 0, [() => LoginsMap, 0]]]; +var GetIdResponse = [3, n0, _GIR, 0, [_II], [0]]; +var GetOpenIdTokenForDeveloperIdentityInput = [ + 3, + n0, + _GOITFDII, + 0, + [_IPI, _II, _L, _PT, _TD], + [0, 0, [() => LoginsMap, 0], 128 | 0, 1], +]; +var GetOpenIdTokenForDeveloperIdentityResponse = [ + 3, + n0, + _GOITFDIR, + 0, + [_II, _T], + [0, [() => OIDCToken, 0]], +]; +var GetOpenIdTokenInput = [3, n0, _GOITI, 0, [_II, _L], [0, [() => LoginsMap, 0]]]; +var GetOpenIdTokenResponse = [3, n0, _GOITR, 0, [_II, _T], [0, [() => OIDCToken, 0]]]; +var GetPrincipalTagAttributeMapInput = [3, n0, _GPTAMI, 0, [_IPI, _IPNd], [0, 0]]; +var GetPrincipalTagAttributeMapResponse = [ + 3, + n0, + _GPTAMR, + 0, + [_IPI, _IPNd, _UD, _PT], + [0, 0, 2, 128 | 0], +]; +var IdentityDescription = [3, n0, _ID, 0, [_II, _L, _CD, _LMD], [0, 64 | 0, 4, 4]]; +var IdentityPool = [ + 3, + n0, + _IP, + 0, + [_IPI, _IPN, _AUI, _ACF, _SLP, _DPN, _OICPARN, _CIPo, _SPARN, _IPTd], + [0, 0, 2, 2, 128 | 0, 0, 64 | 0, () => CognitoIdentityProviderList, 64 | 0, 128 | 0], +]; +var IdentityPoolShortDescription = [3, n0, _IPSD, 0, [_IPI, _IPN], [0, 0]]; +var InternalErrorException = [ + -3, + n0, + _IEE, + { + [_e]: _s, + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(InternalErrorException, InternalErrorException$1); +var InvalidIdentityPoolConfigurationException = [ + -3, + n0, + _IIPCE, + { + [_e]: _c, + [_hE]: 400, + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(InvalidIdentityPoolConfigurationException, InvalidIdentityPoolConfigurationException$1); +var InvalidParameterException = [ + -3, + n0, + _IPE, + { + [_e]: _c, + [_hE]: 400, + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(InvalidParameterException, InvalidParameterException$1); +var LimitExceededException = [ + -3, + n0, + _LEE, + { + [_e]: _c, + [_hE]: 400, + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(LimitExceededException, LimitExceededException$1); +var ListIdentitiesInput = [3, n0, _LII, 0, [_IPI, _MR, _NT, _HD], [0, 1, 0, 2]]; +var ListIdentitiesResponse = [ + 3, + n0, + _LIR, + 0, + [_IPI, _I, _NT], + [0, () => IdentitiesList, 0], +]; +var ListIdentityPoolsInput = [3, n0, _LIPI, 0, [_MR, _NT], [1, 0]]; +var ListIdentityPoolsResponse = [ + 3, + n0, + _LIPR, + 0, + [_IPd, _NT], + [() => IdentityPoolsList, 0], +]; +var ListTagsForResourceInput = [3, n0, _LTFRI, 0, [_RA], [0]]; +var ListTagsForResourceResponse = [3, n0, _LTFRR, 0, [_Ta], [128 | 0]]; +var LookupDeveloperIdentityInput = [ + 3, + n0, + _LDII, + 0, + [_IPI, _II, _DUI, _MR, _NT], + [0, 0, 0, 1, 0], +]; +var LookupDeveloperIdentityResponse = [ + 3, + n0, + _LDIR, + 0, + [_II, _DUIL, _NT], + [0, 64 | 0, 0], +]; +var MappingRule = [3, n0, _MRa, 0, [_Cl, _MT, _V, _RARN], [0, 0, 0, 0]]; +var MergeDeveloperIdentitiesInput = [ + 3, + n0, + _MDII, + 0, + [_SUI, _DUIe, _DPN, _IPI], + [0, 0, 0, 0], +]; +var MergeDeveloperIdentitiesResponse = [3, n0, _MDIR, 0, [_II], [0]]; +var NotAuthorizedException = [ + -3, + n0, + _NAE, + { + [_e]: _c, + [_hE]: 403, + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(NotAuthorizedException, NotAuthorizedException$1); +var ResourceConflictException = [ + -3, + n0, + _RCE, + { + [_e]: _c, + [_hE]: 409, + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(ResourceConflictException, ResourceConflictException$1); +var ResourceNotFoundException = [ + -3, + n0, + _RNFE, + { + [_e]: _c, + [_hE]: 404, + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(ResourceNotFoundException, ResourceNotFoundException$1); +var RoleMapping = [ + 3, + n0, + _RMo, + 0, + [_Ty, _ARR, _RC], + [0, 0, () => RulesConfigurationType], +]; +var RulesConfigurationType = [3, n0, _RCT, 0, [_Ru], [() => MappingRulesList]]; +var SetIdentityPoolRolesInput = [ + 3, + n0, + _SIPRI, + 0, + [_IPI, _R, _RM], + [0, 128 | 0, () => RoleMappingMap], +]; +var SetPrincipalTagAttributeMapInput = [ + 3, + n0, + _SPTAMI, + 0, + [_IPI, _IPNd, _UD, _PT], + [0, 0, 2, 128 | 0], +]; +var SetPrincipalTagAttributeMapResponse = [ + 3, + n0, + _SPTAMR, + 0, + [_IPI, _IPNd, _UD, _PT], + [0, 0, 2, 128 | 0], +]; +var TagResourceInput = [3, n0, _TRI, 0, [_RA, _Ta], [0, 128 | 0]]; +var TagResourceResponse = [3, n0, _TRR, 0, [], []]; +var TooManyRequestsException = [ + -3, + n0, + _TMRE, + { + [_e]: _c, + [_hE]: 429, + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(TooManyRequestsException, TooManyRequestsException$1); +var UnlinkDeveloperIdentityInput = [ + 3, + n0, + _UDII, + 0, + [_II, _IPI, _DPN, _DUI], + [0, 0, 0, 0], +]; +var UnlinkIdentityInput = [ + 3, + n0, + _UIIn, + 0, + [_II, _L, _LTR], + [0, [() => LoginsMap, 0], 64 | 0], +]; +var UnprocessedIdentityId = [3, n0, _UIInp, 0, [_II, _EC], [0, 0]]; +var UntagResourceInput = [3, n0, _URI, 0, [_RA, _TK], [0, 64 | 0]]; +var UntagResourceResponse = [3, n0, _URR, 0, [], []]; +var __Unit = "unit"; +var CognitoIdentityServiceException = [-3, _sm, "CognitoIdentityServiceException", 0, [], []]; +schema.TypeRegistry.for(_sm).registerError(CognitoIdentityServiceException, CognitoIdentityServiceException$1); +var CognitoIdentityProviderList = [1, n0, _CIPL, 0, () => CognitoIdentityProvider]; +var IdentitiesList = [1, n0, _IL, 0, () => IdentityDescription]; +var IdentityPoolsList = [1, n0, _IPL, 0, () => IdentityPoolShortDescription]; +var MappingRulesList = [1, n0, _MRL, 0, () => MappingRule]; +var UnprocessedIdentityIdList = [1, n0, _UIIL, 0, () => UnprocessedIdentityId]; +var LoginsMap = [2, n0, _LM, 0, [0, 0], [() => IdentityProviderToken, 0]]; +var RoleMappingMap = [2, n0, _RMM, 0, 0, () => RoleMapping]; +var CreateIdentityPool = [ + 9, + n0, + _CIPr, + 0, + () => CreateIdentityPoolInput, + () => IdentityPool, +]; +var DeleteIdentities = [ + 9, + n0, + _DI, + 0, + () => DeleteIdentitiesInput, + () => DeleteIdentitiesResponse, +]; +var DeleteIdentityPool = [9, n0, _DIP, 0, () => DeleteIdentityPoolInput, () => __Unit]; +var DescribeIdentity = [ + 9, + n0, + _DIe, + 0, + () => DescribeIdentityInput, + () => IdentityDescription, +]; +var DescribeIdentityPool = [ + 9, + n0, + _DIPe, + 0, + () => DescribeIdentityPoolInput, + () => IdentityPool, +]; +var GetCredentialsForIdentity = [ + 9, + n0, + _GCFI, + 0, + () => GetCredentialsForIdentityInput, + () => GetCredentialsForIdentityResponse, +]; +var GetId = [9, n0, _GI, 0, () => GetIdInput, () => GetIdResponse]; +var GetIdentityPoolRoles = [ + 9, + n0, + _GIPR, + 0, + () => GetIdentityPoolRolesInput, + () => GetIdentityPoolRolesResponse, +]; +var GetOpenIdToken = [ + 9, + n0, + _GOIT, + 0, + () => GetOpenIdTokenInput, + () => GetOpenIdTokenResponse, +]; +var GetOpenIdTokenForDeveloperIdentity = [ + 9, + n0, + _GOITFDI, + 0, + () => GetOpenIdTokenForDeveloperIdentityInput, + () => GetOpenIdTokenForDeveloperIdentityResponse, +]; +var GetPrincipalTagAttributeMap = [ + 9, + n0, + _GPTAM, + 0, + () => GetPrincipalTagAttributeMapInput, + () => GetPrincipalTagAttributeMapResponse, +]; +var ListIdentities = [ + 9, + n0, + _LI, + 0, + () => ListIdentitiesInput, + () => ListIdentitiesResponse, +]; +var ListIdentityPools = [ + 9, + n0, + _LIP, + 0, + () => ListIdentityPoolsInput, + () => ListIdentityPoolsResponse, +]; +var ListTagsForResource = [ + 9, + n0, + _LTFR, + 0, + () => ListTagsForResourceInput, + () => ListTagsForResourceResponse, +]; +var LookupDeveloperIdentity = [ + 9, + n0, + _LDI, + 0, + () => LookupDeveloperIdentityInput, + () => LookupDeveloperIdentityResponse, +]; +var MergeDeveloperIdentities = [ + 9, + n0, + _MDI, + 0, + () => MergeDeveloperIdentitiesInput, + () => MergeDeveloperIdentitiesResponse, +]; +var SetIdentityPoolRoles = [ + 9, + n0, + _SIPR, + 0, + () => SetIdentityPoolRolesInput, + () => __Unit, +]; +var SetPrincipalTagAttributeMap = [ + 9, + n0, + _SPTAM, + 0, + () => SetPrincipalTagAttributeMapInput, + () => SetPrincipalTagAttributeMapResponse, +]; +var TagResource = [9, n0, _TR, 0, () => TagResourceInput, () => TagResourceResponse]; +var UnlinkDeveloperIdentity = [ + 9, + n0, + _UDI, + 0, + () => UnlinkDeveloperIdentityInput, + () => __Unit, +]; +var UnlinkIdentity = [9, n0, _UI, 0, () => UnlinkIdentityInput, () => __Unit]; +var UntagResource = [ + 9, + n0, + _UR, + 0, + () => UntagResourceInput, + () => UntagResourceResponse, +]; +var UpdateIdentityPool = [9, n0, _UIP, 0, () => IdentityPool, () => IdentityPool]; + +class CreateIdentityPoolCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSCognitoIdentityService", "CreateIdentityPool", {}) + .n("CognitoIdentityClient", "CreateIdentityPoolCommand") + .sc(CreateIdentityPool) + .build() { +} + +class DeleteIdentitiesCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSCognitoIdentityService", "DeleteIdentities", {}) + .n("CognitoIdentityClient", "DeleteIdentitiesCommand") + .sc(DeleteIdentities) + .build() { +} + +class DeleteIdentityPoolCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSCognitoIdentityService", "DeleteIdentityPool", {}) + .n("CognitoIdentityClient", "DeleteIdentityPoolCommand") + .sc(DeleteIdentityPool) + .build() { +} + +class DescribeIdentityCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSCognitoIdentityService", "DescribeIdentity", {}) + .n("CognitoIdentityClient", "DescribeIdentityCommand") + .sc(DescribeIdentity) + .build() { +} + +class DescribeIdentityPoolCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSCognitoIdentityService", "DescribeIdentityPool", {}) + .n("CognitoIdentityClient", "DescribeIdentityPoolCommand") + .sc(DescribeIdentityPool) + .build() { +} + +class GetCredentialsForIdentityCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSCognitoIdentityService", "GetCredentialsForIdentity", {}) + .n("CognitoIdentityClient", "GetCredentialsForIdentityCommand") + .sc(GetCredentialsForIdentity) + .build() { +} + +class GetIdCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSCognitoIdentityService", "GetId", {}) + .n("CognitoIdentityClient", "GetIdCommand") + .sc(GetId) + .build() { +} + +class GetIdentityPoolRolesCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSCognitoIdentityService", "GetIdentityPoolRoles", {}) + .n("CognitoIdentityClient", "GetIdentityPoolRolesCommand") + .sc(GetIdentityPoolRoles) + .build() { +} + +class GetOpenIdTokenCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSCognitoIdentityService", "GetOpenIdToken", {}) + .n("CognitoIdentityClient", "GetOpenIdTokenCommand") + .sc(GetOpenIdToken) + .build() { +} + +class GetOpenIdTokenForDeveloperIdentityCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSCognitoIdentityService", "GetOpenIdTokenForDeveloperIdentity", {}) + .n("CognitoIdentityClient", "GetOpenIdTokenForDeveloperIdentityCommand") + .sc(GetOpenIdTokenForDeveloperIdentity) + .build() { +} + +class GetPrincipalTagAttributeMapCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSCognitoIdentityService", "GetPrincipalTagAttributeMap", {}) + .n("CognitoIdentityClient", "GetPrincipalTagAttributeMapCommand") + .sc(GetPrincipalTagAttributeMap) + .build() { +} + +class ListIdentitiesCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSCognitoIdentityService", "ListIdentities", {}) + .n("CognitoIdentityClient", "ListIdentitiesCommand") + .sc(ListIdentities) + .build() { +} + +class ListIdentityPoolsCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSCognitoIdentityService", "ListIdentityPools", {}) + .n("CognitoIdentityClient", "ListIdentityPoolsCommand") + .sc(ListIdentityPools) + .build() { +} + +class ListTagsForResourceCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSCognitoIdentityService", "ListTagsForResource", {}) + .n("CognitoIdentityClient", "ListTagsForResourceCommand") + .sc(ListTagsForResource) + .build() { +} + +class LookupDeveloperIdentityCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSCognitoIdentityService", "LookupDeveloperIdentity", {}) + .n("CognitoIdentityClient", "LookupDeveloperIdentityCommand") + .sc(LookupDeveloperIdentity) + .build() { +} + +class MergeDeveloperIdentitiesCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSCognitoIdentityService", "MergeDeveloperIdentities", {}) + .n("CognitoIdentityClient", "MergeDeveloperIdentitiesCommand") + .sc(MergeDeveloperIdentities) + .build() { +} + +class SetIdentityPoolRolesCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSCognitoIdentityService", "SetIdentityPoolRoles", {}) + .n("CognitoIdentityClient", "SetIdentityPoolRolesCommand") + .sc(SetIdentityPoolRoles) + .build() { +} + +class SetPrincipalTagAttributeMapCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSCognitoIdentityService", "SetPrincipalTagAttributeMap", {}) + .n("CognitoIdentityClient", "SetPrincipalTagAttributeMapCommand") + .sc(SetPrincipalTagAttributeMap) + .build() { +} + +class TagResourceCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSCognitoIdentityService", "TagResource", {}) + .n("CognitoIdentityClient", "TagResourceCommand") + .sc(TagResource) + .build() { +} + +class UnlinkDeveloperIdentityCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSCognitoIdentityService", "UnlinkDeveloperIdentity", {}) + .n("CognitoIdentityClient", "UnlinkDeveloperIdentityCommand") + .sc(UnlinkDeveloperIdentity) + .build() { +} + +class UnlinkIdentityCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSCognitoIdentityService", "UnlinkIdentity", {}) + .n("CognitoIdentityClient", "UnlinkIdentityCommand") + .sc(UnlinkIdentity) + .build() { +} + +class UntagResourceCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSCognitoIdentityService", "UntagResource", {}) + .n("CognitoIdentityClient", "UntagResourceCommand") + .sc(UntagResource) + .build() { +} + +class UpdateIdentityPoolCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSCognitoIdentityService", "UpdateIdentityPool", {}) + .n("CognitoIdentityClient", "UpdateIdentityPoolCommand") + .sc(UpdateIdentityPool) + .build() { +} + +const commands = { + CreateIdentityPoolCommand, + DeleteIdentitiesCommand, + DeleteIdentityPoolCommand, + DescribeIdentityCommand, + DescribeIdentityPoolCommand, + GetCredentialsForIdentityCommand, + GetIdCommand, + GetIdentityPoolRolesCommand, + GetOpenIdTokenCommand, + GetOpenIdTokenForDeveloperIdentityCommand, + GetPrincipalTagAttributeMapCommand, + ListIdentitiesCommand, + ListIdentityPoolsCommand, + ListTagsForResourceCommand, + LookupDeveloperIdentityCommand, + MergeDeveloperIdentitiesCommand, + SetIdentityPoolRolesCommand, + SetPrincipalTagAttributeMapCommand, + TagResourceCommand, + UnlinkDeveloperIdentityCommand, + UnlinkIdentityCommand, + UntagResourceCommand, + UpdateIdentityPoolCommand, +}; +class CognitoIdentity extends CognitoIdentityClient { +} +smithyClient.createAggregatedClient(commands, CognitoIdentity); + +const paginateListIdentityPools = core.createPaginator(CognitoIdentityClient, ListIdentityPoolsCommand, "NextToken", "NextToken", "MaxResults"); + +const AmbiguousRoleResolutionType = { + AUTHENTICATED_ROLE: "AuthenticatedRole", + DENY: "Deny", +}; +const ErrorCode = { + ACCESS_DENIED: "AccessDenied", + INTERNAL_SERVER_ERROR: "InternalServerError", +}; +const MappingRuleMatchType = { + CONTAINS: "Contains", + EQUALS: "Equals", + NOT_EQUAL: "NotEqual", + STARTS_WITH: "StartsWith", +}; +const RoleMappingType = { + RULES: "Rules", + TOKEN: "Token", +}; + +Object.defineProperty(exports, "$Command", { + enumerable: true, + get: function () { return smithyClient.Command; } +}); +Object.defineProperty(exports, "__Client", { + enumerable: true, + get: function () { return smithyClient.Client; } +}); +exports.AmbiguousRoleResolutionType = AmbiguousRoleResolutionType; +exports.CognitoIdentity = CognitoIdentity; +exports.CognitoIdentityClient = CognitoIdentityClient; +exports.CognitoIdentityServiceException = CognitoIdentityServiceException$1; +exports.ConcurrentModificationException = ConcurrentModificationException$1; +exports.CreateIdentityPoolCommand = CreateIdentityPoolCommand; +exports.DeleteIdentitiesCommand = DeleteIdentitiesCommand; +exports.DeleteIdentityPoolCommand = DeleteIdentityPoolCommand; +exports.DescribeIdentityCommand = DescribeIdentityCommand; +exports.DescribeIdentityPoolCommand = DescribeIdentityPoolCommand; +exports.DeveloperUserAlreadyRegisteredException = DeveloperUserAlreadyRegisteredException$1; +exports.ErrorCode = ErrorCode; +exports.ExternalServiceException = ExternalServiceException$1; +exports.GetCredentialsForIdentityCommand = GetCredentialsForIdentityCommand; +exports.GetIdCommand = GetIdCommand; +exports.GetIdentityPoolRolesCommand = GetIdentityPoolRolesCommand; +exports.GetOpenIdTokenCommand = GetOpenIdTokenCommand; +exports.GetOpenIdTokenForDeveloperIdentityCommand = GetOpenIdTokenForDeveloperIdentityCommand; +exports.GetPrincipalTagAttributeMapCommand = GetPrincipalTagAttributeMapCommand; +exports.InternalErrorException = InternalErrorException$1; +exports.InvalidIdentityPoolConfigurationException = InvalidIdentityPoolConfigurationException$1; +exports.InvalidParameterException = InvalidParameterException$1; +exports.LimitExceededException = LimitExceededException$1; +exports.ListIdentitiesCommand = ListIdentitiesCommand; +exports.ListIdentityPoolsCommand = ListIdentityPoolsCommand; +exports.ListTagsForResourceCommand = ListTagsForResourceCommand; +exports.LookupDeveloperIdentityCommand = LookupDeveloperIdentityCommand; +exports.MappingRuleMatchType = MappingRuleMatchType; +exports.MergeDeveloperIdentitiesCommand = MergeDeveloperIdentitiesCommand; +exports.NotAuthorizedException = NotAuthorizedException$1; +exports.ResourceConflictException = ResourceConflictException$1; +exports.ResourceNotFoundException = ResourceNotFoundException$1; +exports.RoleMappingType = RoleMappingType; +exports.SetIdentityPoolRolesCommand = SetIdentityPoolRolesCommand; +exports.SetPrincipalTagAttributeMapCommand = SetPrincipalTagAttributeMapCommand; +exports.TagResourceCommand = TagResourceCommand; +exports.TooManyRequestsException = TooManyRequestsException$1; +exports.UnlinkDeveloperIdentityCommand = UnlinkDeveloperIdentityCommand; +exports.UnlinkIdentityCommand = UnlinkIdentityCommand; +exports.UntagResourceCommand = UntagResourceCommand; +exports.UpdateIdentityPoolCommand = UpdateIdentityPoolCommand; +exports.paginateListIdentityPools = paginateListIdentityPools; diff --git a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/runtimeConfig.js b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/runtimeConfig.js new file mode 100644 index 00000000..d4031116 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/runtimeConfig.js @@ -0,0 +1,56 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getRuntimeConfig = void 0; +const tslib_1 = require("tslib"); +const package_json_1 = tslib_1.__importDefault(require("../package.json")); +const core_1 = require("@aws-sdk/core"); +const credential_provider_node_1 = require("@aws-sdk/credential-provider-node"); +const util_user_agent_node_1 = require("@aws-sdk/util-user-agent-node"); +const config_resolver_1 = require("@smithy/config-resolver"); +const hash_node_1 = require("@smithy/hash-node"); +const middleware_retry_1 = require("@smithy/middleware-retry"); +const node_config_provider_1 = require("@smithy/node-config-provider"); +const node_http_handler_1 = require("@smithy/node-http-handler"); +const util_body_length_node_1 = require("@smithy/util-body-length-node"); +const util_retry_1 = require("@smithy/util-retry"); +const runtimeConfig_shared_1 = require("./runtimeConfig.shared"); +const smithy_client_1 = require("@smithy/smithy-client"); +const util_defaults_mode_node_1 = require("@smithy/util-defaults-mode-node"); +const smithy_client_2 = require("@smithy/smithy-client"); +const getRuntimeConfig = (config) => { + (0, smithy_client_2.emitWarningIfUnsupportedVersion)(process.version); + const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config); + const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode); + const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config); + (0, core_1.emitWarningIfUnsupportedVersion)(process.version); + const loaderConfig = { + profile: config?.profile, + logger: clientSharedValues.logger, + }; + return { + ...clientSharedValues, + ...config, + runtime: "node", + defaultsMode, + authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), + bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, + credentialDefaultProvider: config?.credentialDefaultProvider ?? credential_provider_node_1.defaultProvider, + defaultUserAgentProvider: config?.defaultUserAgentProvider ?? + (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), + maxAttempts: config?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), + region: config?.region ?? + (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), + requestHandler: node_http_handler_1.NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), + retryMode: config?.retryMode ?? + (0, node_config_provider_1.loadConfig)({ + ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS, + default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE, + }, config), + sha256: config?.sha256 ?? hash_node_1.Hash.bind(null, "sha256"), + streamCollector: config?.streamCollector ?? node_http_handler_1.streamCollector, + useDualstackEndpoint: config?.useDualstackEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), + }; +}; +exports.getRuntimeConfig = getRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/runtimeConfig.shared.js b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/runtimeConfig.shared.js new file mode 100644 index 00000000..e58de461 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/runtimeConfig.shared.js @@ -0,0 +1,47 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getRuntimeConfig = void 0; +const core_1 = require("@aws-sdk/core"); +const protocols_1 = require("@aws-sdk/core/protocols"); +const core_2 = require("@smithy/core"); +const smithy_client_1 = require("@smithy/smithy-client"); +const url_parser_1 = require("@smithy/url-parser"); +const util_base64_1 = require("@smithy/util-base64"); +const util_utf8_1 = require("@smithy/util-utf8"); +const httpAuthSchemeProvider_1 = require("./auth/httpAuthSchemeProvider"); +const endpointResolver_1 = require("./endpoint/endpointResolver"); +const getRuntimeConfig = (config) => { + return { + apiVersion: "2014-06-30", + base64Decoder: config?.base64Decoder ?? util_base64_1.fromBase64, + base64Encoder: config?.base64Encoder ?? util_base64_1.toBase64, + disableHostPrefix: config?.disableHostPrefix ?? false, + endpointProvider: config?.endpointProvider ?? endpointResolver_1.defaultEndpointResolver, + extensions: config?.extensions ?? [], + httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultCognitoIdentityHttpAuthSchemeProvider, + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new core_1.AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new core_2.NoAuthSigner(), + }, + ], + logger: config?.logger ?? new smithy_client_1.NoOpLogger(), + protocol: config?.protocol ?? + new protocols_1.AwsJson1_1Protocol({ + defaultNamespace: "com.amazonaws.cognitoidentity", + serviceTarget: "AWSCognitoIdentityService", + awsQueryCompatible: false, + }), + serviceId: config?.serviceId ?? "Cognito Identity", + urlParser: config?.urlParser ?? url_parser_1.parseUrl, + utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, + utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, + }; +}; +exports.getRuntimeConfig = getRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/protocol-http/dist-cjs/index.js new file mode 100644 index 00000000..52303c3b --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/protocol-http/dist-cjs/index.js @@ -0,0 +1,169 @@ +'use strict'; + +var types = require('@smithy/types'); + +const getHttpHandlerExtensionConfiguration = (runtimeConfig) => { + return { + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); + }, + }; +}; +const resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler(), + }; +}; + +class Field { + name; + kind; + values; + constructor({ name, kind = types.FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; + } + add(value) { + this.values.push(value); + } + set(values) { + this.values = values; + } + remove(value) { + this.values = this.values.filter((v) => v !== value); + } + toString() { + return this.values.map((v) => (v.includes(",") || v.includes(" ") ? `"${v}"` : v)).join(", "); + } + get() { + return this.values; + } +} + +class Fields { + entries = {}; + encoding; + constructor({ fields = [], encoding = "utf-8" }) { + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + setField(field) { + this.entries[field.name.toLowerCase()] = field; + } + getField(name) { + return this.entries[name.toLowerCase()]; + } + removeField(name) { + delete this.entries[name.toLowerCase()]; + } + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } +} + +class HttpRequest { + method; + protocol; + hostname; + port; + path; + query; + headers; + username; + password; + fragment; + body; + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol + ? options.protocol.slice(-1) !== ":" + ? `${options.protocol}:` + : options.protocol + : "https:"; + this.path = options.path ? (options.path.charAt(0) !== "/" ? `/${options.path}` : options.path) : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + static clone(request) { + const cloned = new HttpRequest({ + ...request, + headers: { ...request.headers }, + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); + } + return cloned; + } + static isInstance(request) { + if (!request) { + return false; + } + const req = request; + return ("method" in req && + "protocol" in req && + "hostname" in req && + "path" in req && + typeof req["query"] === "object" && + typeof req["headers"] === "object"); + } + clone() { + return HttpRequest.clone(this); + } +} +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param, + }; + }, {}); +} + +class HttpResponse { + statusCode; + reason; + headers; + body; + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) + return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + } +} + +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} + +exports.Field = Field; +exports.Fields = Fields; +exports.HttpRequest = HttpRequest; +exports.HttpResponse = HttpResponse; +exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration; +exports.isValidHostname = isValidHostname; +exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/smithy-client/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/smithy-client/dist-cjs/index.js new file mode 100644 index 00000000..9f589873 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/smithy-client/dist-cjs/index.js @@ -0,0 +1,589 @@ +'use strict'; + +var middlewareStack = require('@smithy/middleware-stack'); +var protocols = require('@smithy/core/protocols'); +var types = require('@smithy/types'); +var schema = require('@smithy/core/schema'); +var serde = require('@smithy/core/serde'); + +class Client { + config; + middlewareStack = middlewareStack.constructStack(); + initConfig; + handlers; + constructor(config) { + this.config = config; + } + send(command, optionsOrCb, cb) { + const options = typeof optionsOrCb !== "function" ? optionsOrCb : undefined; + const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb; + const useHandlerCache = options === undefined && this.config.cacheMiddleware === true; + let handler; + if (useHandlerCache) { + if (!this.handlers) { + this.handlers = new WeakMap(); + } + const handlers = this.handlers; + if (handlers.has(command.constructor)) { + handler = handlers.get(command.constructor); + } + else { + handler = command.resolveMiddleware(this.middlewareStack, this.config, options); + handlers.set(command.constructor, handler); + } + } + else { + delete this.handlers; + handler = command.resolveMiddleware(this.middlewareStack, this.config, options); + } + if (callback) { + handler(command) + .then((result) => callback(null, result.output), (err) => callback(err)) + .catch(() => { }); + } + else { + return handler(command).then((result) => result.output); + } + } + destroy() { + this.config?.requestHandler?.destroy?.(); + delete this.handlers; + } +} + +const SENSITIVE_STRING$1 = "***SensitiveInformation***"; +function schemaLogFilter(schema$1, data) { + if (data == null) { + return data; + } + const ns = schema.NormalizedSchema.of(schema$1); + if (ns.getMergedTraits().sensitive) { + return SENSITIVE_STRING$1; + } + if (ns.isListSchema()) { + const isSensitive = !!ns.getValueSchema().getMergedTraits().sensitive; + if (isSensitive) { + return SENSITIVE_STRING$1; + } + } + else if (ns.isMapSchema()) { + const isSensitive = !!ns.getKeySchema().getMergedTraits().sensitive || !!ns.getValueSchema().getMergedTraits().sensitive; + if (isSensitive) { + return SENSITIVE_STRING$1; + } + } + else if (ns.isStructSchema() && typeof data === "object") { + const object = data; + const newObject = {}; + for (const [member, memberNs] of ns.structIterator()) { + if (object[member] != null) { + newObject[member] = schemaLogFilter(memberNs, object[member]); + } + } + return newObject; + } + return data; +} + +class Command { + middlewareStack = middlewareStack.constructStack(); + schema; + static classBuilder() { + return new ClassBuilder(); + } + resolveMiddlewareWithContext(clientStack, configuration, options, { middlewareFn, clientName, commandName, inputFilterSensitiveLog, outputFilterSensitiveLog, smithyContext, additionalContext, CommandCtor, }) { + for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options)) { + this.middlewareStack.use(mw); + } + const stack = clientStack.concat(this.middlewareStack); + const { logger } = configuration; + const handlerExecutionContext = { + logger, + clientName, + commandName, + inputFilterSensitiveLog, + outputFilterSensitiveLog, + [types.SMITHY_CONTEXT_KEY]: { + commandInstance: this, + ...smithyContext, + }, + ...additionalContext, + }; + const { requestHandler } = configuration; + return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); + } +} +class ClassBuilder { + _init = () => { }; + _ep = {}; + _middlewareFn = () => []; + _commandName = ""; + _clientName = ""; + _additionalContext = {}; + _smithyContext = {}; + _inputFilterSensitiveLog = undefined; + _outputFilterSensitiveLog = undefined; + _serializer = null; + _deserializer = null; + _operationSchema; + init(cb) { + this._init = cb; + } + ep(endpointParameterInstructions) { + this._ep = endpointParameterInstructions; + return this; + } + m(middlewareSupplier) { + this._middlewareFn = middlewareSupplier; + return this; + } + s(service, operation, smithyContext = {}) { + this._smithyContext = { + service, + operation, + ...smithyContext, + }; + return this; + } + c(additionalContext = {}) { + this._additionalContext = additionalContext; + return this; + } + n(clientName, commandName) { + this._clientName = clientName; + this._commandName = commandName; + return this; + } + f(inputFilter = (_) => _, outputFilter = (_) => _) { + this._inputFilterSensitiveLog = inputFilter; + this._outputFilterSensitiveLog = outputFilter; + return this; + } + ser(serializer) { + this._serializer = serializer; + return this; + } + de(deserializer) { + this._deserializer = deserializer; + return this; + } + sc(operation) { + this._operationSchema = operation; + this._smithyContext.operationSchema = operation; + return this; + } + build() { + const closure = this; + let CommandRef; + return (CommandRef = class extends Command { + input; + static getEndpointParameterInstructions() { + return closure._ep; + } + constructor(...[input]) { + super(); + this.input = input ?? {}; + closure._init(this); + this.schema = closure._operationSchema; + } + resolveMiddleware(stack, configuration, options) { + const op = closure._operationSchema; + const input = op?.[4] ?? op?.input; + const output = op?.[5] ?? op?.output; + return this.resolveMiddlewareWithContext(stack, configuration, options, { + CommandCtor: CommandRef, + middlewareFn: closure._middlewareFn, + clientName: closure._clientName, + commandName: closure._commandName, + inputFilterSensitiveLog: closure._inputFilterSensitiveLog ?? (op ? schemaLogFilter.bind(null, input) : (_) => _), + outputFilterSensitiveLog: closure._outputFilterSensitiveLog ?? (op ? schemaLogFilter.bind(null, output) : (_) => _), + smithyContext: closure._smithyContext, + additionalContext: closure._additionalContext, + }); + } + serialize = closure._serializer; + deserialize = closure._deserializer; + }); + } +} + +const SENSITIVE_STRING = "***SensitiveInformation***"; + +const createAggregatedClient = (commands, Client) => { + for (const command of Object.keys(commands)) { + const CommandCtor = commands[command]; + const methodImpl = async function (args, optionsOrCb, cb) { + const command = new CommandCtor(args); + if (typeof optionsOrCb === "function") { + this.send(command, optionsOrCb); + } + else if (typeof cb === "function") { + if (typeof optionsOrCb !== "object") + throw new Error(`Expected http options but got ${typeof optionsOrCb}`); + this.send(command, optionsOrCb || {}, cb); + } + else { + return this.send(command, optionsOrCb); + } + }; + const methodName = (command[0].toLowerCase() + command.slice(1)).replace(/Command$/, ""); + Client.prototype[methodName] = methodImpl; + } +}; + +class ServiceException extends Error { + $fault; + $response; + $retryable; + $metadata; + constructor(options) { + super(options.message); + Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype); + this.name = options.name; + this.$fault = options.$fault; + this.$metadata = options.$metadata; + } + static isInstance(value) { + if (!value) + return false; + const candidate = value; + return (ServiceException.prototype.isPrototypeOf(candidate) || + (Boolean(candidate.$fault) && + Boolean(candidate.$metadata) && + (candidate.$fault === "client" || candidate.$fault === "server"))); + } + static [Symbol.hasInstance](instance) { + if (!instance) + return false; + const candidate = instance; + if (this === ServiceException) { + return ServiceException.isInstance(instance); + } + if (ServiceException.isInstance(instance)) { + if (candidate.name && this.name) { + return this.prototype.isPrototypeOf(instance) || candidate.name === this.name; + } + return this.prototype.isPrototypeOf(instance); + } + return false; + } +} +const decorateServiceException = (exception, additions = {}) => { + Object.entries(additions) + .filter(([, v]) => v !== undefined) + .forEach(([k, v]) => { + if (exception[k] == undefined || exception[k] === "") { + exception[k] = v; + } + }); + const message = exception.message || exception.Message || "UnknownError"; + exception.message = message; + delete exception.Message; + return exception; +}; + +const throwDefaultError = ({ output, parsedBody, exceptionCtor, errorCode }) => { + const $metadata = deserializeMetadata(output); + const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : undefined; + const response = new exceptionCtor({ + name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || "UnknownError", + $fault: "client", + $metadata, + }); + throw decorateServiceException(response, parsedBody); +}; +const withBaseException = (ExceptionCtor) => { + return ({ output, parsedBody, errorCode }) => { + throwDefaultError({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode }); + }; +}; +const deserializeMetadata = (output) => ({ + httpStatusCode: output.statusCode, + requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], + extendedRequestId: output.headers["x-amz-id-2"], + cfId: output.headers["x-amz-cf-id"], +}); + +const loadConfigsForDefaultMode = (mode) => { + switch (mode) { + case "standard": + return { + retryMode: "standard", + connectionTimeout: 3100, + }; + case "in-region": + return { + retryMode: "standard", + connectionTimeout: 1100, + }; + case "cross-region": + return { + retryMode: "standard", + connectionTimeout: 3100, + }; + case "mobile": + return { + retryMode: "standard", + connectionTimeout: 30000, + }; + default: + return {}; + } +}; + +let warningEmitted = false; +const emitWarningIfUnsupportedVersion = (version) => { + if (version && !warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 16) { + warningEmitted = true; + } +}; + +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + for (const id in types.AlgorithmId) { + const algorithmId = types.AlgorithmId[id]; + if (runtimeConfig[algorithmId] === undefined) { + continue; + } + checksumAlgorithms.push({ + algorithmId: () => algorithmId, + checksumConstructor: () => runtimeConfig[algorithmId], + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getRetryConfiguration = (runtimeConfig) => { + return { + setRetryStrategy(retryStrategy) { + runtimeConfig.retryStrategy = retryStrategy; + }, + retryStrategy() { + return runtimeConfig.retryStrategy; + }, + }; +}; +const resolveRetryRuntimeConfig = (retryStrategyConfiguration) => { + const runtimeConfig = {}; + runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy(); + return runtimeConfig; +}; + +const getDefaultExtensionConfiguration = (runtimeConfig) => { + return Object.assign(getChecksumConfiguration(runtimeConfig), getRetryConfiguration(runtimeConfig)); +}; +const getDefaultClientConfiguration = getDefaultExtensionConfiguration; +const resolveDefaultRuntimeConfig = (config) => { + return Object.assign(resolveChecksumRuntimeConfig(config), resolveRetryRuntimeConfig(config)); +}; + +const getArrayIfSingleItem = (mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray]; + +const getValueFromTextNode = (obj) => { + const textNodeName = "#text"; + for (const key in obj) { + if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== undefined) { + obj[key] = obj[key][textNodeName]; + } + else if (typeof obj[key] === "object" && obj[key] !== null) { + obj[key] = getValueFromTextNode(obj[key]); + } + } + return obj; +}; + +const isSerializableHeaderValue = (value) => { + return value != null; +}; + +class NoOpLogger { + trace() { } + debug() { } + info() { } + warn() { } + error() { } +} + +function map(arg0, arg1, arg2) { + let target; + let filter; + let instructions; + if (typeof arg1 === "undefined" && typeof arg2 === "undefined") { + target = {}; + instructions = arg0; + } + else { + target = arg0; + if (typeof arg1 === "function") { + filter = arg1; + instructions = arg2; + return mapWithFilter(target, filter, instructions); + } + else { + instructions = arg1; + } + } + for (const key of Object.keys(instructions)) { + if (!Array.isArray(instructions[key])) { + target[key] = instructions[key]; + continue; + } + applyInstruction(target, null, instructions, key); + } + return target; +} +const convertMap = (target) => { + const output = {}; + for (const [k, v] of Object.entries(target || {})) { + output[k] = [, v]; + } + return output; +}; +const take = (source, instructions) => { + const out = {}; + for (const key in instructions) { + applyInstruction(out, source, instructions, key); + } + return out; +}; +const mapWithFilter = (target, filter, instructions) => { + return map(target, Object.entries(instructions).reduce((_instructions, [key, value]) => { + if (Array.isArray(value)) { + _instructions[key] = value; + } + else { + if (typeof value === "function") { + _instructions[key] = [filter, value()]; + } + else { + _instructions[key] = [filter, value]; + } + } + return _instructions; + }, {})); +}; +const applyInstruction = (target, source, instructions, targetKey) => { + if (source !== null) { + let instruction = instructions[targetKey]; + if (typeof instruction === "function") { + instruction = [, instruction]; + } + const [filter = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction; + if ((typeof filter === "function" && filter(source[sourceKey])) || (typeof filter !== "function" && !!filter)) { + target[targetKey] = valueFn(source[sourceKey]); + } + return; + } + let [filter, value] = instructions[targetKey]; + if (typeof value === "function") { + let _value; + const defaultFilterPassed = filter === undefined && (_value = value()) != null; + const customFilterPassed = (typeof filter === "function" && !!filter(void 0)) || (typeof filter !== "function" && !!filter); + if (defaultFilterPassed) { + target[targetKey] = _value; + } + else if (customFilterPassed) { + target[targetKey] = value(); + } + } + else { + const defaultFilterPassed = filter === undefined && value != null; + const customFilterPassed = (typeof filter === "function" && !!filter(value)) || (typeof filter !== "function" && !!filter); + if (defaultFilterPassed || customFilterPassed) { + target[targetKey] = value; + } + } +}; +const nonNullish = (_) => _ != null; +const pass = (_) => _; + +const serializeFloat = (value) => { + if (value !== value) { + return "NaN"; + } + switch (value) { + case Infinity: + return "Infinity"; + case -Infinity: + return "-Infinity"; + default: + return value; + } +}; +const serializeDateTime = (date) => date.toISOString().replace(".000Z", "Z"); + +const _json = (obj) => { + if (obj == null) { + return {}; + } + if (Array.isArray(obj)) { + return obj.filter((_) => _ != null).map(_json); + } + if (typeof obj === "object") { + const target = {}; + for (const key of Object.keys(obj)) { + if (obj[key] == null) { + continue; + } + target[key] = _json(obj[key]); + } + return target; + } + return obj; +}; + +Object.defineProperty(exports, "collectBody", { + enumerable: true, + get: function () { return protocols.collectBody; } +}); +Object.defineProperty(exports, "extendedEncodeURIComponent", { + enumerable: true, + get: function () { return protocols.extendedEncodeURIComponent; } +}); +Object.defineProperty(exports, "resolvedPath", { + enumerable: true, + get: function () { return protocols.resolvedPath; } +}); +exports.Client = Client; +exports.Command = Command; +exports.NoOpLogger = NoOpLogger; +exports.SENSITIVE_STRING = SENSITIVE_STRING; +exports.ServiceException = ServiceException; +exports._json = _json; +exports.convertMap = convertMap; +exports.createAggregatedClient = createAggregatedClient; +exports.decorateServiceException = decorateServiceException; +exports.emitWarningIfUnsupportedVersion = emitWarningIfUnsupportedVersion; +exports.getArrayIfSingleItem = getArrayIfSingleItem; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.getDefaultExtensionConfiguration = getDefaultExtensionConfiguration; +exports.getValueFromTextNode = getValueFromTextNode; +exports.isSerializableHeaderValue = isSerializableHeaderValue; +exports.loadConfigsForDefaultMode = loadConfigsForDefaultMode; +exports.map = map; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; +exports.serializeDateTime = serializeDateTime; +exports.serializeFloat = serializeFloat; +exports.take = take; +exports.throwDefaultError = throwDefaultError; +exports.withBaseException = withBaseException; +Object.keys(serde).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return serde[k]; } + }); +}); diff --git a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/types/dist-cjs/index.js new file mode 100644 index 00000000..be6d0e1a --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/types/dist-cjs/index.js @@ -0,0 +1,91 @@ +'use strict'; + +exports.HttpAuthLocation = void 0; +(function (HttpAuthLocation) { + HttpAuthLocation["HEADER"] = "header"; + HttpAuthLocation["QUERY"] = "query"; +})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); + +exports.HttpApiKeyAuthLocation = void 0; +(function (HttpApiKeyAuthLocation) { + HttpApiKeyAuthLocation["HEADER"] = "header"; + HttpApiKeyAuthLocation["QUERY"] = "query"; +})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); + +exports.EndpointURLScheme = void 0; +(function (EndpointURLScheme) { + EndpointURLScheme["HTTP"] = "http"; + EndpointURLScheme["HTTPS"] = "https"; +})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); + +exports.AlgorithmId = void 0; +(function (AlgorithmId) { + AlgorithmId["MD5"] = "md5"; + AlgorithmId["CRC32"] = "crc32"; + AlgorithmId["CRC32C"] = "crc32c"; + AlgorithmId["SHA1"] = "sha1"; + AlgorithmId["SHA256"] = "sha256"; +})(exports.AlgorithmId || (exports.AlgorithmId = {})); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.SHA256, + checksumConstructor: () => runtimeConfig.sha256, + }); + } + if (runtimeConfig.md5 != undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.MD5, + checksumConstructor: () => runtimeConfig.md5, + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getDefaultClientConfiguration = (runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}; +const resolveDefaultRuntimeConfig = (config) => { + return resolveChecksumRuntimeConfig(config); +}; + +exports.FieldPosition = void 0; +(function (FieldPosition) { + FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; + FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; +})(exports.FieldPosition || (exports.FieldPosition = {})); + +const SMITHY_CONTEXT_KEY = "__smithy_context"; + +exports.IniSectionType = void 0; +(function (IniSectionType) { + IniSectionType["PROFILE"] = "profile"; + IniSectionType["SSO_SESSION"] = "sso-session"; + IniSectionType["SERVICES"] = "services"; +})(exports.IniSectionType || (exports.IniSectionType = {})); + +exports.RequestHandlerProtocol = void 0; +(function (RequestHandlerProtocol) { + RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; +})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); + +exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js new file mode 100644 index 00000000..b06a7b87 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromBase64 = void 0; +const util_buffer_from_1 = require("@smithy/util-buffer-from"); +const BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; +const fromBase64 = (input) => { + if ((input.length * 3) % 4 !== 0) { + throw new TypeError(`Incorrect padding on base64 string.`); + } + if (!BASE64_REGEX.exec(input)) { + throw new TypeError(`Invalid base64 string.`); + } + const buffer = (0, util_buffer_from_1.fromString)(input, "base64"); + return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); +}; +exports.fromBase64 = fromBase64; diff --git a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/dist-cjs/index.js new file mode 100644 index 00000000..c095e288 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/dist-cjs/index.js @@ -0,0 +1,19 @@ +'use strict'; + +var fromBase64 = require('./fromBase64'); +var toBase64 = require('./toBase64'); + + + +Object.keys(fromBase64).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return fromBase64[k]; } + }); +}); +Object.keys(toBase64).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return toBase64[k]; } + }); +}); diff --git a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/dist-cjs/toBase64.js b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/dist-cjs/toBase64.js new file mode 100644 index 00000000..0590ce3f --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/dist-cjs/toBase64.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.toBase64 = void 0; +const util_buffer_from_1 = require("@smithy/util-buffer-from"); +const util_utf8_1 = require("@smithy/util-utf8"); +const toBase64 = (_input) => { + let input; + if (typeof _input === "string") { + input = (0, util_utf8_1.fromUtf8)(_input); + } + else { + input = _input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); + } + return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64"); +}; +exports.toBase64 = toBase64; diff --git a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js new file mode 100644 index 00000000..b577c9ca --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js @@ -0,0 +1,20 @@ +'use strict'; + +var isArrayBuffer = require('@smithy/is-array-buffer'); +var buffer = require('buffer'); + +const fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => { + if (!isArrayBuffer.isArrayBuffer(input)) { + throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); + } + return buffer.Buffer.from(input, offset, length); +}; +const fromString = (input, encoding) => { + if (typeof input !== "string") { + throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); + } + return encoding ? buffer.Buffer.from(input, encoding) : buffer.Buffer.from(input); +}; + +exports.fromArrayBuffer = fromArrayBuffer; +exports.fromString = fromString; diff --git a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js new file mode 100644 index 00000000..3238bb77 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js @@ -0,0 +1,6 @@ +'use strict'; + +const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) || + Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; + +exports.isArrayBuffer = isArrayBuffer; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/auth/httpAuthSchemeProvider.js b/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/auth/httpAuthSchemeProvider.js new file mode 100644 index 00000000..2c256eea --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/auth/httpAuthSchemeProvider.js @@ -0,0 +1,68 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.resolveHttpAuthSchemeConfig = exports.defaultSSOHttpAuthSchemeProvider = exports.defaultSSOHttpAuthSchemeParametersProvider = void 0; +const core_1 = require("@aws-sdk/core"); +const util_middleware_1 = require("@smithy/util-middleware"); +const defaultSSOHttpAuthSchemeParametersProvider = async (config, context, input) => { + return { + operation: (0, util_middleware_1.getSmithyContext)(context).operation, + region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || + (() => { + throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); + })(), + }; +}; +exports.defaultSSOHttpAuthSchemeParametersProvider = defaultSSOHttpAuthSchemeParametersProvider; +function createAwsAuthSigv4HttpAuthOption(authParameters) { + return { + schemeId: "aws.auth#sigv4", + signingProperties: { + name: "awsssoportal", + region: authParameters.region, + }, + propertiesExtractor: (config, context) => ({ + signingProperties: { + config, + context, + }, + }), + }; +} +function createSmithyApiNoAuthHttpAuthOption(authParameters) { + return { + schemeId: "smithy.api#noAuth", + }; +} +const defaultSSOHttpAuthSchemeProvider = (authParameters) => { + const options = []; + switch (authParameters.operation) { + case "GetRoleCredentials": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + case "ListAccountRoles": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + case "ListAccounts": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + case "Logout": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + default: { + options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); + } + } + return options; +}; +exports.defaultSSOHttpAuthSchemeProvider = defaultSSOHttpAuthSchemeProvider; +const resolveHttpAuthSchemeConfig = (config) => { + const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config); + return Object.assign(config_0, { + authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), + }); +}; +exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/endpoint/endpointResolver.js b/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/endpoint/endpointResolver.js new file mode 100644 index 00000000..7258a356 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/endpoint/endpointResolver.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defaultEndpointResolver = void 0; +const util_endpoints_1 = require("@aws-sdk/util-endpoints"); +const util_endpoints_2 = require("@smithy/util-endpoints"); +const ruleset_1 = require("./ruleset"); +const cache = new util_endpoints_2.EndpointCache({ + size: 50, + params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"], +}); +const defaultEndpointResolver = (endpointParams, context = {}) => { + return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { + endpointParams: endpointParams, + logger: context.logger, + })); +}; +exports.defaultEndpointResolver = defaultEndpointResolver; +util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/endpoint/ruleset.js b/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/endpoint/ruleset.js new file mode 100644 index 00000000..28d8f332 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/endpoint/ruleset.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ruleSet = void 0; +const u = "required", v = "fn", w = "argv", x = "ref"; +const a = true, b = "isSet", c = "booleanEquals", d = "error", e = "endpoint", f = "tree", g = "PartitionResult", h = "getAttr", i = { [u]: false, "type": "string" }, j = { [u]: true, "default": false, "type": "boolean" }, k = { [x]: "Endpoint" }, l = { [v]: c, [w]: [{ [x]: "UseFIPS" }, true] }, m = { [v]: c, [w]: [{ [x]: "UseDualStack" }, true] }, n = {}, o = { [v]: h, [w]: [{ [x]: g }, "supportsFIPS"] }, p = { [x]: g }, q = { [v]: c, [w]: [true, { [v]: h, [w]: [p, "supportsDualStack"] }] }, r = [l], s = [m], t = [{ [x]: "Region" }]; +const _data = { version: "1.0", parameters: { Region: i, UseDualStack: j, UseFIPS: j, Endpoint: i }, rules: [{ conditions: [{ [v]: b, [w]: [k] }], rules: [{ conditions: r, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d }, { conditions: s, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d }, { endpoint: { url: k, properties: n, headers: n }, type: e }], type: f }, { conditions: [{ [v]: b, [w]: t }], rules: [{ conditions: [{ [v]: "aws.partition", [w]: t, assign: g }], rules: [{ conditions: [l, m], rules: [{ conditions: [{ [v]: c, [w]: [a, o] }, q], rules: [{ endpoint: { url: "https://portal.sso-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d }], type: f }, { conditions: r, rules: [{ conditions: [{ [v]: c, [w]: [o, a] }], rules: [{ conditions: [{ [v]: "stringEquals", [w]: [{ [v]: h, [w]: [p, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://portal.sso.{Region}.amazonaws.com", properties: n, headers: n }, type: e }, { endpoint: { url: "https://portal.sso-fips.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "FIPS is enabled but this partition does not support FIPS", type: d }], type: f }, { conditions: s, rules: [{ conditions: [q], rules: [{ endpoint: { url: "https://portal.sso.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "DualStack is enabled but this partition does not support DualStack", type: d }], type: f }, { endpoint: { url: "https://portal.sso.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }], type: f }, { error: "Invalid Configuration: Missing Region", type: d }] }; +exports.ruleSet = _data; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/index.js new file mode 100644 index 00000000..e03d1267 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/index.js @@ -0,0 +1,514 @@ +'use strict'; + +var middlewareHostHeader = require('@aws-sdk/middleware-host-header'); +var middlewareLogger = require('@aws-sdk/middleware-logger'); +var middlewareRecursionDetection = require('@aws-sdk/middleware-recursion-detection'); +var middlewareUserAgent = require('@aws-sdk/middleware-user-agent'); +var configResolver = require('@smithy/config-resolver'); +var core = require('@smithy/core'); +var schema = require('@smithy/core/schema'); +var middlewareContentLength = require('@smithy/middleware-content-length'); +var middlewareEndpoint = require('@smithy/middleware-endpoint'); +var middlewareRetry = require('@smithy/middleware-retry'); +var smithyClient = require('@smithy/smithy-client'); +var httpAuthSchemeProvider = require('./auth/httpAuthSchemeProvider'); +var runtimeConfig = require('./runtimeConfig'); +var regionConfigResolver = require('@aws-sdk/region-config-resolver'); +var protocolHttp = require('@smithy/protocol-http'); + +const resolveClientEndpointParameters = (options) => { + return Object.assign(options, { + useDualstackEndpoint: options.useDualstackEndpoint ?? false, + useFipsEndpoint: options.useFipsEndpoint ?? false, + defaultSigningName: "awsssoportal", + }); +}; +const commonParams = { + UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, + Endpoint: { type: "builtInParams", name: "endpoint" }, + Region: { type: "builtInParams", name: "region" }, + UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, +}; + +const getHttpAuthExtensionConfiguration = (runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + return { + setHttpAuthScheme(httpAuthScheme) { + const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } + else { + _httpAuthSchemes.splice(index, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; + }, + }; +}; +const resolveHttpAuthRuntimeConfig = (config) => { + return { + httpAuthSchemes: config.httpAuthSchemes(), + httpAuthSchemeProvider: config.httpAuthSchemeProvider(), + credentials: config.credentials(), + }; +}; + +const resolveRuntimeExtensions = (runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign(regionConfigResolver.getAwsRegionExtensionConfiguration(runtimeConfig), smithyClient.getDefaultExtensionConfiguration(runtimeConfig), protocolHttp.getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig)); + extensions.forEach((extension) => extension.configure(extensionConfiguration)); + return Object.assign(runtimeConfig, regionConfigResolver.resolveAwsRegionExtensionConfiguration(extensionConfiguration), smithyClient.resolveDefaultRuntimeConfig(extensionConfiguration), protocolHttp.resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration)); +}; + +class SSOClient extends smithyClient.Client { + config; + constructor(...[configuration]) { + const _config_0 = runtimeConfig.getRuntimeConfig(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = resolveClientEndpointParameters(_config_0); + const _config_2 = middlewareUserAgent.resolveUserAgentConfig(_config_1); + const _config_3 = middlewareRetry.resolveRetryConfig(_config_2); + const _config_4 = configResolver.resolveRegionConfig(_config_3); + const _config_5 = middlewareHostHeader.resolveHostHeaderConfig(_config_4); + const _config_6 = middlewareEndpoint.resolveEndpointConfig(_config_5); + const _config_7 = httpAuthSchemeProvider.resolveHttpAuthSchemeConfig(_config_6); + const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); + this.config = _config_8; + this.middlewareStack.use(schema.getSchemaSerdePlugin(this.config)); + this.middlewareStack.use(middlewareUserAgent.getUserAgentPlugin(this.config)); + this.middlewareStack.use(middlewareRetry.getRetryPlugin(this.config)); + this.middlewareStack.use(middlewareContentLength.getContentLengthPlugin(this.config)); + this.middlewareStack.use(middlewareHostHeader.getHostHeaderPlugin(this.config)); + this.middlewareStack.use(middlewareLogger.getLoggerPlugin(this.config)); + this.middlewareStack.use(middlewareRecursionDetection.getRecursionDetectionPlugin(this.config)); + this.middlewareStack.use(core.getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { + httpAuthSchemeParametersProvider: httpAuthSchemeProvider.defaultSSOHttpAuthSchemeParametersProvider, + identityProviderConfigProvider: async (config) => new core.DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config.credentials, + }), + })); + this.middlewareStack.use(core.getHttpSigningPlugin(this.config)); + } + destroy() { + super.destroy(); + } +} + +let SSOServiceException$1 = class SSOServiceException extends smithyClient.ServiceException { + constructor(options) { + super(options); + Object.setPrototypeOf(this, SSOServiceException.prototype); + } +}; + +let InvalidRequestException$1 = class InvalidRequestException extends SSOServiceException$1 { + name = "InvalidRequestException"; + $fault = "client"; + constructor(opts) { + super({ + name: "InvalidRequestException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, InvalidRequestException.prototype); + } +}; +let ResourceNotFoundException$1 = class ResourceNotFoundException extends SSOServiceException$1 { + name = "ResourceNotFoundException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ResourceNotFoundException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ResourceNotFoundException.prototype); + } +}; +let TooManyRequestsException$1 = class TooManyRequestsException extends SSOServiceException$1 { + name = "TooManyRequestsException"; + $fault = "client"; + constructor(opts) { + super({ + name: "TooManyRequestsException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, TooManyRequestsException.prototype); + } +}; +let UnauthorizedException$1 = class UnauthorizedException extends SSOServiceException$1 { + name = "UnauthorizedException"; + $fault = "client"; + constructor(opts) { + super({ + name: "UnauthorizedException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, UnauthorizedException.prototype); + } +}; + +const _AI = "AccountInfo"; +const _ALT = "AccountListType"; +const _ATT = "AccessTokenType"; +const _GRC = "GetRoleCredentials"; +const _GRCR = "GetRoleCredentialsRequest"; +const _GRCRe = "GetRoleCredentialsResponse"; +const _IRE = "InvalidRequestException"; +const _L = "Logout"; +const _LA = "ListAccounts"; +const _LAR = "ListAccountsRequest"; +const _LARR = "ListAccountRolesRequest"; +const _LARRi = "ListAccountRolesResponse"; +const _LARi = "ListAccountsResponse"; +const _LARis = "ListAccountRoles"; +const _LR = "LogoutRequest"; +const _RC = "RoleCredentials"; +const _RI = "RoleInfo"; +const _RLT = "RoleListType"; +const _RNFE = "ResourceNotFoundException"; +const _SAKT = "SecretAccessKeyType"; +const _STT = "SessionTokenType"; +const _TMRE = "TooManyRequestsException"; +const _UE = "UnauthorizedException"; +const _aI = "accountId"; +const _aKI = "accessKeyId"; +const _aL = "accountList"; +const _aN = "accountName"; +const _aT = "accessToken"; +const _ai = "account_id"; +const _c = "client"; +const _e = "error"; +const _eA = "emailAddress"; +const _ex = "expiration"; +const _h = "http"; +const _hE = "httpError"; +const _hH = "httpHeader"; +const _hQ = "httpQuery"; +const _m = "message"; +const _mR = "maxResults"; +const _mr = "max_result"; +const _nT = "nextToken"; +const _nt = "next_token"; +const _rC = "roleCredentials"; +const _rL = "roleList"; +const _rN = "roleName"; +const _rn = "role_name"; +const _s = "smithy.ts.sdk.synthetic.com.amazonaws.sso"; +const _sAK = "secretAccessKey"; +const _sT = "sessionToken"; +const _xasbt = "x-amz-sso_bearer_token"; +const n0 = "com.amazonaws.sso"; +var AccessTokenType = [0, n0, _ATT, 8, 0]; +var SecretAccessKeyType = [0, n0, _SAKT, 8, 0]; +var SessionTokenType = [0, n0, _STT, 8, 0]; +var AccountInfo = [3, n0, _AI, 0, [_aI, _aN, _eA], [0, 0, 0]]; +var GetRoleCredentialsRequest = [ + 3, + n0, + _GRCR, + 0, + [_rN, _aI, _aT], + [ + [ + 0, + { + [_hQ]: _rn, + }, + ], + [ + 0, + { + [_hQ]: _ai, + }, + ], + [ + () => AccessTokenType, + { + [_hH]: _xasbt, + }, + ], + ], +]; +var GetRoleCredentialsResponse = [3, n0, _GRCRe, 0, [_rC], [[() => RoleCredentials, 0]]]; +var InvalidRequestException = [ + -3, + n0, + _IRE, + { + [_e]: _c, + [_hE]: 400, + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(InvalidRequestException, InvalidRequestException$1); +var ListAccountRolesRequest = [ + 3, + n0, + _LARR, + 0, + [_nT, _mR, _aT, _aI], + [ + [ + 0, + { + [_hQ]: _nt, + }, + ], + [ + 1, + { + [_hQ]: _mr, + }, + ], + [ + () => AccessTokenType, + { + [_hH]: _xasbt, + }, + ], + [ + 0, + { + [_hQ]: _ai, + }, + ], + ], +]; +var ListAccountRolesResponse = [3, n0, _LARRi, 0, [_nT, _rL], [0, () => RoleListType]]; +var ListAccountsRequest = [ + 3, + n0, + _LAR, + 0, + [_nT, _mR, _aT], + [ + [ + 0, + { + [_hQ]: _nt, + }, + ], + [ + 1, + { + [_hQ]: _mr, + }, + ], + [ + () => AccessTokenType, + { + [_hH]: _xasbt, + }, + ], + ], +]; +var ListAccountsResponse = [3, n0, _LARi, 0, [_nT, _aL], [0, () => AccountListType]]; +var LogoutRequest = [ + 3, + n0, + _LR, + 0, + [_aT], + [ + [ + () => AccessTokenType, + { + [_hH]: _xasbt, + }, + ], + ], +]; +var ResourceNotFoundException = [ + -3, + n0, + _RNFE, + { + [_e]: _c, + [_hE]: 404, + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(ResourceNotFoundException, ResourceNotFoundException$1); +var RoleCredentials = [ + 3, + n0, + _RC, + 0, + [_aKI, _sAK, _sT, _ex], + [0, [() => SecretAccessKeyType, 0], [() => SessionTokenType, 0], 1], +]; +var RoleInfo = [3, n0, _RI, 0, [_rN, _aI], [0, 0]]; +var TooManyRequestsException = [ + -3, + n0, + _TMRE, + { + [_e]: _c, + [_hE]: 429, + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(TooManyRequestsException, TooManyRequestsException$1); +var UnauthorizedException = [ + -3, + n0, + _UE, + { + [_e]: _c, + [_hE]: 401, + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(UnauthorizedException, UnauthorizedException$1); +var __Unit = "unit"; +var SSOServiceException = [-3, _s, "SSOServiceException", 0, [], []]; +schema.TypeRegistry.for(_s).registerError(SSOServiceException, SSOServiceException$1); +var AccountListType = [1, n0, _ALT, 0, () => AccountInfo]; +var RoleListType = [1, n0, _RLT, 0, () => RoleInfo]; +var GetRoleCredentials = [ + 9, + n0, + _GRC, + { + [_h]: ["GET", "/federation/credentials", 200], + }, + () => GetRoleCredentialsRequest, + () => GetRoleCredentialsResponse, +]; +var ListAccountRoles = [ + 9, + n0, + _LARis, + { + [_h]: ["GET", "/assignment/roles", 200], + }, + () => ListAccountRolesRequest, + () => ListAccountRolesResponse, +]; +var ListAccounts = [ + 9, + n0, + _LA, + { + [_h]: ["GET", "/assignment/accounts", 200], + }, + () => ListAccountsRequest, + () => ListAccountsResponse, +]; +var Logout = [ + 9, + n0, + _L, + { + [_h]: ["POST", "/logout", 200], + }, + () => LogoutRequest, + () => __Unit, +]; + +class GetRoleCredentialsCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("SWBPortalService", "GetRoleCredentials", {}) + .n("SSOClient", "GetRoleCredentialsCommand") + .sc(GetRoleCredentials) + .build() { +} + +class ListAccountRolesCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("SWBPortalService", "ListAccountRoles", {}) + .n("SSOClient", "ListAccountRolesCommand") + .sc(ListAccountRoles) + .build() { +} + +class ListAccountsCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("SWBPortalService", "ListAccounts", {}) + .n("SSOClient", "ListAccountsCommand") + .sc(ListAccounts) + .build() { +} + +class LogoutCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("SWBPortalService", "Logout", {}) + .n("SSOClient", "LogoutCommand") + .sc(Logout) + .build() { +} + +const commands = { + GetRoleCredentialsCommand, + ListAccountRolesCommand, + ListAccountsCommand, + LogoutCommand, +}; +class SSO extends SSOClient { +} +smithyClient.createAggregatedClient(commands, SSO); + +const paginateListAccountRoles = core.createPaginator(SSOClient, ListAccountRolesCommand, "nextToken", "nextToken", "maxResults"); + +const paginateListAccounts = core.createPaginator(SSOClient, ListAccountsCommand, "nextToken", "nextToken", "maxResults"); + +Object.defineProperty(exports, "$Command", { + enumerable: true, + get: function () { return smithyClient.Command; } +}); +Object.defineProperty(exports, "__Client", { + enumerable: true, + get: function () { return smithyClient.Client; } +}); +exports.GetRoleCredentialsCommand = GetRoleCredentialsCommand; +exports.InvalidRequestException = InvalidRequestException$1; +exports.ListAccountRolesCommand = ListAccountRolesCommand; +exports.ListAccountsCommand = ListAccountsCommand; +exports.LogoutCommand = LogoutCommand; +exports.ResourceNotFoundException = ResourceNotFoundException$1; +exports.SSO = SSO; +exports.SSOClient = SSOClient; +exports.SSOServiceException = SSOServiceException$1; +exports.TooManyRequestsException = TooManyRequestsException$1; +exports.UnauthorizedException = UnauthorizedException$1; +exports.paginateListAccountRoles = paginateListAccountRoles; +exports.paginateListAccounts = paginateListAccounts; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/runtimeConfig.js b/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/runtimeConfig.js new file mode 100644 index 00000000..ecc8dd2f --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/runtimeConfig.js @@ -0,0 +1,54 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getRuntimeConfig = void 0; +const tslib_1 = require("tslib"); +const package_json_1 = tslib_1.__importDefault(require("../package.json")); +const core_1 = require("@aws-sdk/core"); +const util_user_agent_node_1 = require("@aws-sdk/util-user-agent-node"); +const config_resolver_1 = require("@smithy/config-resolver"); +const hash_node_1 = require("@smithy/hash-node"); +const middleware_retry_1 = require("@smithy/middleware-retry"); +const node_config_provider_1 = require("@smithy/node-config-provider"); +const node_http_handler_1 = require("@smithy/node-http-handler"); +const util_body_length_node_1 = require("@smithy/util-body-length-node"); +const util_retry_1 = require("@smithy/util-retry"); +const runtimeConfig_shared_1 = require("./runtimeConfig.shared"); +const smithy_client_1 = require("@smithy/smithy-client"); +const util_defaults_mode_node_1 = require("@smithy/util-defaults-mode-node"); +const smithy_client_2 = require("@smithy/smithy-client"); +const getRuntimeConfig = (config) => { + (0, smithy_client_2.emitWarningIfUnsupportedVersion)(process.version); + const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config); + const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode); + const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config); + (0, core_1.emitWarningIfUnsupportedVersion)(process.version); + const loaderConfig = { + profile: config?.profile, + logger: clientSharedValues.logger, + }; + return { + ...clientSharedValues, + ...config, + runtime: "node", + defaultsMode, + authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), + bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, + defaultUserAgentProvider: config?.defaultUserAgentProvider ?? + (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), + maxAttempts: config?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), + region: config?.region ?? + (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), + requestHandler: node_http_handler_1.NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), + retryMode: config?.retryMode ?? + (0, node_config_provider_1.loadConfig)({ + ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS, + default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE, + }, config), + sha256: config?.sha256 ?? hash_node_1.Hash.bind(null, "sha256"), + streamCollector: config?.streamCollector ?? node_http_handler_1.streamCollector, + useDualstackEndpoint: config?.useDualstackEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), + }; +}; +exports.getRuntimeConfig = getRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/runtimeConfig.shared.js b/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/runtimeConfig.shared.js new file mode 100644 index 00000000..4f73148f --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/runtimeConfig.shared.js @@ -0,0 +1,42 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getRuntimeConfig = void 0; +const core_1 = require("@aws-sdk/core"); +const protocols_1 = require("@aws-sdk/core/protocols"); +const core_2 = require("@smithy/core"); +const smithy_client_1 = require("@smithy/smithy-client"); +const url_parser_1 = require("@smithy/url-parser"); +const util_base64_1 = require("@smithy/util-base64"); +const util_utf8_1 = require("@smithy/util-utf8"); +const httpAuthSchemeProvider_1 = require("./auth/httpAuthSchemeProvider"); +const endpointResolver_1 = require("./endpoint/endpointResolver"); +const getRuntimeConfig = (config) => { + return { + apiVersion: "2019-06-10", + base64Decoder: config?.base64Decoder ?? util_base64_1.fromBase64, + base64Encoder: config?.base64Encoder ?? util_base64_1.toBase64, + disableHostPrefix: config?.disableHostPrefix ?? false, + endpointProvider: config?.endpointProvider ?? endpointResolver_1.defaultEndpointResolver, + extensions: config?.extensions ?? [], + httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSSOHttpAuthSchemeProvider, + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new core_1.AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new core_2.NoAuthSigner(), + }, + ], + logger: config?.logger ?? new smithy_client_1.NoOpLogger(), + protocol: config?.protocol ?? new protocols_1.AwsRestJsonProtocol({ defaultNamespace: "com.amazonaws.sso" }), + serviceId: config?.serviceId ?? "SSO", + urlParser: config?.urlParser ?? url_parser_1.parseUrl, + utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, + utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, + }; +}; +exports.getRuntimeConfig = getRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/protocol-http/dist-cjs/index.js new file mode 100644 index 00000000..52303c3b --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/protocol-http/dist-cjs/index.js @@ -0,0 +1,169 @@ +'use strict'; + +var types = require('@smithy/types'); + +const getHttpHandlerExtensionConfiguration = (runtimeConfig) => { + return { + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); + }, + }; +}; +const resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler(), + }; +}; + +class Field { + name; + kind; + values; + constructor({ name, kind = types.FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; + } + add(value) { + this.values.push(value); + } + set(values) { + this.values = values; + } + remove(value) { + this.values = this.values.filter((v) => v !== value); + } + toString() { + return this.values.map((v) => (v.includes(",") || v.includes(" ") ? `"${v}"` : v)).join(", "); + } + get() { + return this.values; + } +} + +class Fields { + entries = {}; + encoding; + constructor({ fields = [], encoding = "utf-8" }) { + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + setField(field) { + this.entries[field.name.toLowerCase()] = field; + } + getField(name) { + return this.entries[name.toLowerCase()]; + } + removeField(name) { + delete this.entries[name.toLowerCase()]; + } + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } +} + +class HttpRequest { + method; + protocol; + hostname; + port; + path; + query; + headers; + username; + password; + fragment; + body; + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol + ? options.protocol.slice(-1) !== ":" + ? `${options.protocol}:` + : options.protocol + : "https:"; + this.path = options.path ? (options.path.charAt(0) !== "/" ? `/${options.path}` : options.path) : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + static clone(request) { + const cloned = new HttpRequest({ + ...request, + headers: { ...request.headers }, + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); + } + return cloned; + } + static isInstance(request) { + if (!request) { + return false; + } + const req = request; + return ("method" in req && + "protocol" in req && + "hostname" in req && + "path" in req && + typeof req["query"] === "object" && + typeof req["headers"] === "object"); + } + clone() { + return HttpRequest.clone(this); + } +} +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param, + }; + }, {}); +} + +class HttpResponse { + statusCode; + reason; + headers; + body; + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) + return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + } +} + +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} + +exports.Field = Field; +exports.Fields = Fields; +exports.HttpRequest = HttpRequest; +exports.HttpResponse = HttpResponse; +exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration; +exports.isValidHostname = isValidHostname; +exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/smithy-client/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/smithy-client/dist-cjs/index.js new file mode 100644 index 00000000..9f589873 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/smithy-client/dist-cjs/index.js @@ -0,0 +1,589 @@ +'use strict'; + +var middlewareStack = require('@smithy/middleware-stack'); +var protocols = require('@smithy/core/protocols'); +var types = require('@smithy/types'); +var schema = require('@smithy/core/schema'); +var serde = require('@smithy/core/serde'); + +class Client { + config; + middlewareStack = middlewareStack.constructStack(); + initConfig; + handlers; + constructor(config) { + this.config = config; + } + send(command, optionsOrCb, cb) { + const options = typeof optionsOrCb !== "function" ? optionsOrCb : undefined; + const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb; + const useHandlerCache = options === undefined && this.config.cacheMiddleware === true; + let handler; + if (useHandlerCache) { + if (!this.handlers) { + this.handlers = new WeakMap(); + } + const handlers = this.handlers; + if (handlers.has(command.constructor)) { + handler = handlers.get(command.constructor); + } + else { + handler = command.resolveMiddleware(this.middlewareStack, this.config, options); + handlers.set(command.constructor, handler); + } + } + else { + delete this.handlers; + handler = command.resolveMiddleware(this.middlewareStack, this.config, options); + } + if (callback) { + handler(command) + .then((result) => callback(null, result.output), (err) => callback(err)) + .catch(() => { }); + } + else { + return handler(command).then((result) => result.output); + } + } + destroy() { + this.config?.requestHandler?.destroy?.(); + delete this.handlers; + } +} + +const SENSITIVE_STRING$1 = "***SensitiveInformation***"; +function schemaLogFilter(schema$1, data) { + if (data == null) { + return data; + } + const ns = schema.NormalizedSchema.of(schema$1); + if (ns.getMergedTraits().sensitive) { + return SENSITIVE_STRING$1; + } + if (ns.isListSchema()) { + const isSensitive = !!ns.getValueSchema().getMergedTraits().sensitive; + if (isSensitive) { + return SENSITIVE_STRING$1; + } + } + else if (ns.isMapSchema()) { + const isSensitive = !!ns.getKeySchema().getMergedTraits().sensitive || !!ns.getValueSchema().getMergedTraits().sensitive; + if (isSensitive) { + return SENSITIVE_STRING$1; + } + } + else if (ns.isStructSchema() && typeof data === "object") { + const object = data; + const newObject = {}; + for (const [member, memberNs] of ns.structIterator()) { + if (object[member] != null) { + newObject[member] = schemaLogFilter(memberNs, object[member]); + } + } + return newObject; + } + return data; +} + +class Command { + middlewareStack = middlewareStack.constructStack(); + schema; + static classBuilder() { + return new ClassBuilder(); + } + resolveMiddlewareWithContext(clientStack, configuration, options, { middlewareFn, clientName, commandName, inputFilterSensitiveLog, outputFilterSensitiveLog, smithyContext, additionalContext, CommandCtor, }) { + for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options)) { + this.middlewareStack.use(mw); + } + const stack = clientStack.concat(this.middlewareStack); + const { logger } = configuration; + const handlerExecutionContext = { + logger, + clientName, + commandName, + inputFilterSensitiveLog, + outputFilterSensitiveLog, + [types.SMITHY_CONTEXT_KEY]: { + commandInstance: this, + ...smithyContext, + }, + ...additionalContext, + }; + const { requestHandler } = configuration; + return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); + } +} +class ClassBuilder { + _init = () => { }; + _ep = {}; + _middlewareFn = () => []; + _commandName = ""; + _clientName = ""; + _additionalContext = {}; + _smithyContext = {}; + _inputFilterSensitiveLog = undefined; + _outputFilterSensitiveLog = undefined; + _serializer = null; + _deserializer = null; + _operationSchema; + init(cb) { + this._init = cb; + } + ep(endpointParameterInstructions) { + this._ep = endpointParameterInstructions; + return this; + } + m(middlewareSupplier) { + this._middlewareFn = middlewareSupplier; + return this; + } + s(service, operation, smithyContext = {}) { + this._smithyContext = { + service, + operation, + ...smithyContext, + }; + return this; + } + c(additionalContext = {}) { + this._additionalContext = additionalContext; + return this; + } + n(clientName, commandName) { + this._clientName = clientName; + this._commandName = commandName; + return this; + } + f(inputFilter = (_) => _, outputFilter = (_) => _) { + this._inputFilterSensitiveLog = inputFilter; + this._outputFilterSensitiveLog = outputFilter; + return this; + } + ser(serializer) { + this._serializer = serializer; + return this; + } + de(deserializer) { + this._deserializer = deserializer; + return this; + } + sc(operation) { + this._operationSchema = operation; + this._smithyContext.operationSchema = operation; + return this; + } + build() { + const closure = this; + let CommandRef; + return (CommandRef = class extends Command { + input; + static getEndpointParameterInstructions() { + return closure._ep; + } + constructor(...[input]) { + super(); + this.input = input ?? {}; + closure._init(this); + this.schema = closure._operationSchema; + } + resolveMiddleware(stack, configuration, options) { + const op = closure._operationSchema; + const input = op?.[4] ?? op?.input; + const output = op?.[5] ?? op?.output; + return this.resolveMiddlewareWithContext(stack, configuration, options, { + CommandCtor: CommandRef, + middlewareFn: closure._middlewareFn, + clientName: closure._clientName, + commandName: closure._commandName, + inputFilterSensitiveLog: closure._inputFilterSensitiveLog ?? (op ? schemaLogFilter.bind(null, input) : (_) => _), + outputFilterSensitiveLog: closure._outputFilterSensitiveLog ?? (op ? schemaLogFilter.bind(null, output) : (_) => _), + smithyContext: closure._smithyContext, + additionalContext: closure._additionalContext, + }); + } + serialize = closure._serializer; + deserialize = closure._deserializer; + }); + } +} + +const SENSITIVE_STRING = "***SensitiveInformation***"; + +const createAggregatedClient = (commands, Client) => { + for (const command of Object.keys(commands)) { + const CommandCtor = commands[command]; + const methodImpl = async function (args, optionsOrCb, cb) { + const command = new CommandCtor(args); + if (typeof optionsOrCb === "function") { + this.send(command, optionsOrCb); + } + else if (typeof cb === "function") { + if (typeof optionsOrCb !== "object") + throw new Error(`Expected http options but got ${typeof optionsOrCb}`); + this.send(command, optionsOrCb || {}, cb); + } + else { + return this.send(command, optionsOrCb); + } + }; + const methodName = (command[0].toLowerCase() + command.slice(1)).replace(/Command$/, ""); + Client.prototype[methodName] = methodImpl; + } +}; + +class ServiceException extends Error { + $fault; + $response; + $retryable; + $metadata; + constructor(options) { + super(options.message); + Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype); + this.name = options.name; + this.$fault = options.$fault; + this.$metadata = options.$metadata; + } + static isInstance(value) { + if (!value) + return false; + const candidate = value; + return (ServiceException.prototype.isPrototypeOf(candidate) || + (Boolean(candidate.$fault) && + Boolean(candidate.$metadata) && + (candidate.$fault === "client" || candidate.$fault === "server"))); + } + static [Symbol.hasInstance](instance) { + if (!instance) + return false; + const candidate = instance; + if (this === ServiceException) { + return ServiceException.isInstance(instance); + } + if (ServiceException.isInstance(instance)) { + if (candidate.name && this.name) { + return this.prototype.isPrototypeOf(instance) || candidate.name === this.name; + } + return this.prototype.isPrototypeOf(instance); + } + return false; + } +} +const decorateServiceException = (exception, additions = {}) => { + Object.entries(additions) + .filter(([, v]) => v !== undefined) + .forEach(([k, v]) => { + if (exception[k] == undefined || exception[k] === "") { + exception[k] = v; + } + }); + const message = exception.message || exception.Message || "UnknownError"; + exception.message = message; + delete exception.Message; + return exception; +}; + +const throwDefaultError = ({ output, parsedBody, exceptionCtor, errorCode }) => { + const $metadata = deserializeMetadata(output); + const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : undefined; + const response = new exceptionCtor({ + name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || "UnknownError", + $fault: "client", + $metadata, + }); + throw decorateServiceException(response, parsedBody); +}; +const withBaseException = (ExceptionCtor) => { + return ({ output, parsedBody, errorCode }) => { + throwDefaultError({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode }); + }; +}; +const deserializeMetadata = (output) => ({ + httpStatusCode: output.statusCode, + requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], + extendedRequestId: output.headers["x-amz-id-2"], + cfId: output.headers["x-amz-cf-id"], +}); + +const loadConfigsForDefaultMode = (mode) => { + switch (mode) { + case "standard": + return { + retryMode: "standard", + connectionTimeout: 3100, + }; + case "in-region": + return { + retryMode: "standard", + connectionTimeout: 1100, + }; + case "cross-region": + return { + retryMode: "standard", + connectionTimeout: 3100, + }; + case "mobile": + return { + retryMode: "standard", + connectionTimeout: 30000, + }; + default: + return {}; + } +}; + +let warningEmitted = false; +const emitWarningIfUnsupportedVersion = (version) => { + if (version && !warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 16) { + warningEmitted = true; + } +}; + +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + for (const id in types.AlgorithmId) { + const algorithmId = types.AlgorithmId[id]; + if (runtimeConfig[algorithmId] === undefined) { + continue; + } + checksumAlgorithms.push({ + algorithmId: () => algorithmId, + checksumConstructor: () => runtimeConfig[algorithmId], + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getRetryConfiguration = (runtimeConfig) => { + return { + setRetryStrategy(retryStrategy) { + runtimeConfig.retryStrategy = retryStrategy; + }, + retryStrategy() { + return runtimeConfig.retryStrategy; + }, + }; +}; +const resolveRetryRuntimeConfig = (retryStrategyConfiguration) => { + const runtimeConfig = {}; + runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy(); + return runtimeConfig; +}; + +const getDefaultExtensionConfiguration = (runtimeConfig) => { + return Object.assign(getChecksumConfiguration(runtimeConfig), getRetryConfiguration(runtimeConfig)); +}; +const getDefaultClientConfiguration = getDefaultExtensionConfiguration; +const resolveDefaultRuntimeConfig = (config) => { + return Object.assign(resolveChecksumRuntimeConfig(config), resolveRetryRuntimeConfig(config)); +}; + +const getArrayIfSingleItem = (mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray]; + +const getValueFromTextNode = (obj) => { + const textNodeName = "#text"; + for (const key in obj) { + if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== undefined) { + obj[key] = obj[key][textNodeName]; + } + else if (typeof obj[key] === "object" && obj[key] !== null) { + obj[key] = getValueFromTextNode(obj[key]); + } + } + return obj; +}; + +const isSerializableHeaderValue = (value) => { + return value != null; +}; + +class NoOpLogger { + trace() { } + debug() { } + info() { } + warn() { } + error() { } +} + +function map(arg0, arg1, arg2) { + let target; + let filter; + let instructions; + if (typeof arg1 === "undefined" && typeof arg2 === "undefined") { + target = {}; + instructions = arg0; + } + else { + target = arg0; + if (typeof arg1 === "function") { + filter = arg1; + instructions = arg2; + return mapWithFilter(target, filter, instructions); + } + else { + instructions = arg1; + } + } + for (const key of Object.keys(instructions)) { + if (!Array.isArray(instructions[key])) { + target[key] = instructions[key]; + continue; + } + applyInstruction(target, null, instructions, key); + } + return target; +} +const convertMap = (target) => { + const output = {}; + for (const [k, v] of Object.entries(target || {})) { + output[k] = [, v]; + } + return output; +}; +const take = (source, instructions) => { + const out = {}; + for (const key in instructions) { + applyInstruction(out, source, instructions, key); + } + return out; +}; +const mapWithFilter = (target, filter, instructions) => { + return map(target, Object.entries(instructions).reduce((_instructions, [key, value]) => { + if (Array.isArray(value)) { + _instructions[key] = value; + } + else { + if (typeof value === "function") { + _instructions[key] = [filter, value()]; + } + else { + _instructions[key] = [filter, value]; + } + } + return _instructions; + }, {})); +}; +const applyInstruction = (target, source, instructions, targetKey) => { + if (source !== null) { + let instruction = instructions[targetKey]; + if (typeof instruction === "function") { + instruction = [, instruction]; + } + const [filter = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction; + if ((typeof filter === "function" && filter(source[sourceKey])) || (typeof filter !== "function" && !!filter)) { + target[targetKey] = valueFn(source[sourceKey]); + } + return; + } + let [filter, value] = instructions[targetKey]; + if (typeof value === "function") { + let _value; + const defaultFilterPassed = filter === undefined && (_value = value()) != null; + const customFilterPassed = (typeof filter === "function" && !!filter(void 0)) || (typeof filter !== "function" && !!filter); + if (defaultFilterPassed) { + target[targetKey] = _value; + } + else if (customFilterPassed) { + target[targetKey] = value(); + } + } + else { + const defaultFilterPassed = filter === undefined && value != null; + const customFilterPassed = (typeof filter === "function" && !!filter(value)) || (typeof filter !== "function" && !!filter); + if (defaultFilterPassed || customFilterPassed) { + target[targetKey] = value; + } + } +}; +const nonNullish = (_) => _ != null; +const pass = (_) => _; + +const serializeFloat = (value) => { + if (value !== value) { + return "NaN"; + } + switch (value) { + case Infinity: + return "Infinity"; + case -Infinity: + return "-Infinity"; + default: + return value; + } +}; +const serializeDateTime = (date) => date.toISOString().replace(".000Z", "Z"); + +const _json = (obj) => { + if (obj == null) { + return {}; + } + if (Array.isArray(obj)) { + return obj.filter((_) => _ != null).map(_json); + } + if (typeof obj === "object") { + const target = {}; + for (const key of Object.keys(obj)) { + if (obj[key] == null) { + continue; + } + target[key] = _json(obj[key]); + } + return target; + } + return obj; +}; + +Object.defineProperty(exports, "collectBody", { + enumerable: true, + get: function () { return protocols.collectBody; } +}); +Object.defineProperty(exports, "extendedEncodeURIComponent", { + enumerable: true, + get: function () { return protocols.extendedEncodeURIComponent; } +}); +Object.defineProperty(exports, "resolvedPath", { + enumerable: true, + get: function () { return protocols.resolvedPath; } +}); +exports.Client = Client; +exports.Command = Command; +exports.NoOpLogger = NoOpLogger; +exports.SENSITIVE_STRING = SENSITIVE_STRING; +exports.ServiceException = ServiceException; +exports._json = _json; +exports.convertMap = convertMap; +exports.createAggregatedClient = createAggregatedClient; +exports.decorateServiceException = decorateServiceException; +exports.emitWarningIfUnsupportedVersion = emitWarningIfUnsupportedVersion; +exports.getArrayIfSingleItem = getArrayIfSingleItem; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.getDefaultExtensionConfiguration = getDefaultExtensionConfiguration; +exports.getValueFromTextNode = getValueFromTextNode; +exports.isSerializableHeaderValue = isSerializableHeaderValue; +exports.loadConfigsForDefaultMode = loadConfigsForDefaultMode; +exports.map = map; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; +exports.serializeDateTime = serializeDateTime; +exports.serializeFloat = serializeFloat; +exports.take = take; +exports.throwDefaultError = throwDefaultError; +exports.withBaseException = withBaseException; +Object.keys(serde).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return serde[k]; } + }); +}); diff --git a/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/types/dist-cjs/index.js new file mode 100644 index 00000000..be6d0e1a --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/types/dist-cjs/index.js @@ -0,0 +1,91 @@ +'use strict'; + +exports.HttpAuthLocation = void 0; +(function (HttpAuthLocation) { + HttpAuthLocation["HEADER"] = "header"; + HttpAuthLocation["QUERY"] = "query"; +})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); + +exports.HttpApiKeyAuthLocation = void 0; +(function (HttpApiKeyAuthLocation) { + HttpApiKeyAuthLocation["HEADER"] = "header"; + HttpApiKeyAuthLocation["QUERY"] = "query"; +})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); + +exports.EndpointURLScheme = void 0; +(function (EndpointURLScheme) { + EndpointURLScheme["HTTP"] = "http"; + EndpointURLScheme["HTTPS"] = "https"; +})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); + +exports.AlgorithmId = void 0; +(function (AlgorithmId) { + AlgorithmId["MD5"] = "md5"; + AlgorithmId["CRC32"] = "crc32"; + AlgorithmId["CRC32C"] = "crc32c"; + AlgorithmId["SHA1"] = "sha1"; + AlgorithmId["SHA256"] = "sha256"; +})(exports.AlgorithmId || (exports.AlgorithmId = {})); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.SHA256, + checksumConstructor: () => runtimeConfig.sha256, + }); + } + if (runtimeConfig.md5 != undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.MD5, + checksumConstructor: () => runtimeConfig.md5, + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getDefaultClientConfiguration = (runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}; +const resolveDefaultRuntimeConfig = (config) => { + return resolveChecksumRuntimeConfig(config); +}; + +exports.FieldPosition = void 0; +(function (FieldPosition) { + FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; + FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; +})(exports.FieldPosition || (exports.FieldPosition = {})); + +const SMITHY_CONTEXT_KEY = "__smithy_context"; + +exports.IniSectionType = void 0; +(function (IniSectionType) { + IniSectionType["PROFILE"] = "profile"; + IniSectionType["SSO_SESSION"] = "sso-session"; + IniSectionType["SERVICES"] = "services"; +})(exports.IniSectionType || (exports.IniSectionType = {})); + +exports.RequestHandlerProtocol = void 0; +(function (RequestHandlerProtocol) { + RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; +})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); + +exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js b/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js new file mode 100644 index 00000000..b06a7b87 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromBase64 = void 0; +const util_buffer_from_1 = require("@smithy/util-buffer-from"); +const BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; +const fromBase64 = (input) => { + if ((input.length * 3) % 4 !== 0) { + throw new TypeError(`Incorrect padding on base64 string.`); + } + if (!BASE64_REGEX.exec(input)) { + throw new TypeError(`Invalid base64 string.`); + } + const buffer = (0, util_buffer_from_1.fromString)(input, "base64"); + return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); +}; +exports.fromBase64 = fromBase64; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/dist-cjs/index.js new file mode 100644 index 00000000..c095e288 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/dist-cjs/index.js @@ -0,0 +1,19 @@ +'use strict'; + +var fromBase64 = require('./fromBase64'); +var toBase64 = require('./toBase64'); + + + +Object.keys(fromBase64).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return fromBase64[k]; } + }); +}); +Object.keys(toBase64).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return toBase64[k]; } + }); +}); diff --git a/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/dist-cjs/toBase64.js b/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/dist-cjs/toBase64.js new file mode 100644 index 00000000..0590ce3f --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/dist-cjs/toBase64.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.toBase64 = void 0; +const util_buffer_from_1 = require("@smithy/util-buffer-from"); +const util_utf8_1 = require("@smithy/util-utf8"); +const toBase64 = (_input) => { + let input; + if (typeof _input === "string") { + input = (0, util_utf8_1.fromUtf8)(_input); + } + else { + input = _input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); + } + return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64"); +}; +exports.toBase64 = toBase64; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js new file mode 100644 index 00000000..b577c9ca --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js @@ -0,0 +1,20 @@ +'use strict'; + +var isArrayBuffer = require('@smithy/is-array-buffer'); +var buffer = require('buffer'); + +const fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => { + if (!isArrayBuffer.isArrayBuffer(input)) { + throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); + } + return buffer.Buffer.from(input, offset, length); +}; +const fromString = (input, encoding) => { + if (typeof input !== "string") { + throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); + } + return encoding ? buffer.Buffer.from(input, encoding) : buffer.Buffer.from(input); +}; + +exports.fromArrayBuffer = fromArrayBuffer; +exports.fromString = fromString; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js new file mode 100644 index 00000000..3238bb77 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js @@ -0,0 +1,6 @@ +'use strict'; + +const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) || + Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; + +exports.isArrayBuffer = isArrayBuffer; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/STSClient.js b/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/STSClient.js new file mode 100644 index 00000000..879af8b9 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/STSClient.js @@ -0,0 +1,54 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.STSClient = exports.__Client = void 0; +const middleware_host_header_1 = require("@aws-sdk/middleware-host-header"); +const middleware_logger_1 = require("@aws-sdk/middleware-logger"); +const middleware_recursion_detection_1 = require("@aws-sdk/middleware-recursion-detection"); +const middleware_user_agent_1 = require("@aws-sdk/middleware-user-agent"); +const config_resolver_1 = require("@smithy/config-resolver"); +const core_1 = require("@smithy/core"); +const schema_1 = require("@smithy/core/schema"); +const middleware_content_length_1 = require("@smithy/middleware-content-length"); +const middleware_endpoint_1 = require("@smithy/middleware-endpoint"); +const middleware_retry_1 = require("@smithy/middleware-retry"); +const smithy_client_1 = require("@smithy/smithy-client"); +Object.defineProperty(exports, "__Client", { enumerable: true, get: function () { return smithy_client_1.Client; } }); +const httpAuthSchemeProvider_1 = require("./auth/httpAuthSchemeProvider"); +const EndpointParameters_1 = require("./endpoint/EndpointParameters"); +const runtimeConfig_1 = require("./runtimeConfig"); +const runtimeExtensions_1 = require("./runtimeExtensions"); +class STSClient extends smithy_client_1.Client { + config; + constructor(...[configuration]) { + const _config_0 = (0, runtimeConfig_1.getRuntimeConfig)(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = (0, EndpointParameters_1.resolveClientEndpointParameters)(_config_0); + const _config_2 = (0, middleware_user_agent_1.resolveUserAgentConfig)(_config_1); + const _config_3 = (0, middleware_retry_1.resolveRetryConfig)(_config_2); + const _config_4 = (0, config_resolver_1.resolveRegionConfig)(_config_3); + const _config_5 = (0, middleware_host_header_1.resolveHostHeaderConfig)(_config_4); + const _config_6 = (0, middleware_endpoint_1.resolveEndpointConfig)(_config_5); + const _config_7 = (0, httpAuthSchemeProvider_1.resolveHttpAuthSchemeConfig)(_config_6); + const _config_8 = (0, runtimeExtensions_1.resolveRuntimeExtensions)(_config_7, configuration?.extensions || []); + this.config = _config_8; + this.middlewareStack.use((0, schema_1.getSchemaSerdePlugin)(this.config)); + this.middlewareStack.use((0, middleware_user_agent_1.getUserAgentPlugin)(this.config)); + this.middlewareStack.use((0, middleware_retry_1.getRetryPlugin)(this.config)); + this.middlewareStack.use((0, middleware_content_length_1.getContentLengthPlugin)(this.config)); + this.middlewareStack.use((0, middleware_host_header_1.getHostHeaderPlugin)(this.config)); + this.middlewareStack.use((0, middleware_logger_1.getLoggerPlugin)(this.config)); + this.middlewareStack.use((0, middleware_recursion_detection_1.getRecursionDetectionPlugin)(this.config)); + this.middlewareStack.use((0, core_1.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, { + httpAuthSchemeParametersProvider: httpAuthSchemeProvider_1.defaultSTSHttpAuthSchemeParametersProvider, + identityProviderConfigProvider: async (config) => new core_1.DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config.credentials, + }), + })); + this.middlewareStack.use((0, core_1.getHttpSigningPlugin)(this.config)); + } + destroy() { + super.destroy(); + } +} +exports.STSClient = STSClient; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/auth/httpAuthExtensionConfiguration.js b/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/auth/httpAuthExtensionConfiguration.js new file mode 100644 index 00000000..239095e0 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/auth/httpAuthExtensionConfiguration.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.resolveHttpAuthRuntimeConfig = exports.getHttpAuthExtensionConfiguration = void 0; +const getHttpAuthExtensionConfiguration = (runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + return { + setHttpAuthScheme(httpAuthScheme) { + const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } + else { + _httpAuthSchemes.splice(index, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; + }, + }; +}; +exports.getHttpAuthExtensionConfiguration = getHttpAuthExtensionConfiguration; +const resolveHttpAuthRuntimeConfig = (config) => { + return { + httpAuthSchemes: config.httpAuthSchemes(), + httpAuthSchemeProvider: config.httpAuthSchemeProvider(), + credentials: config.credentials(), + }; +}; +exports.resolveHttpAuthRuntimeConfig = resolveHttpAuthRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/auth/httpAuthSchemeProvider.js b/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/auth/httpAuthSchemeProvider.js new file mode 100644 index 00000000..d5cb1131 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/auth/httpAuthSchemeProvider.js @@ -0,0 +1,66 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.resolveHttpAuthSchemeConfig = exports.resolveStsAuthConfig = exports.defaultSTSHttpAuthSchemeProvider = exports.defaultSTSHttpAuthSchemeParametersProvider = void 0; +const core_1 = require("@aws-sdk/core"); +const util_middleware_1 = require("@smithy/util-middleware"); +const STSClient_1 = require("../STSClient"); +const defaultSTSHttpAuthSchemeParametersProvider = async (config, context, input) => { + return { + operation: (0, util_middleware_1.getSmithyContext)(context).operation, + region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || + (() => { + throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); + })(), + }; +}; +exports.defaultSTSHttpAuthSchemeParametersProvider = defaultSTSHttpAuthSchemeParametersProvider; +function createAwsAuthSigv4HttpAuthOption(authParameters) { + return { + schemeId: "aws.auth#sigv4", + signingProperties: { + name: "sts", + region: authParameters.region, + }, + propertiesExtractor: (config, context) => ({ + signingProperties: { + config, + context, + }, + }), + }; +} +function createSmithyApiNoAuthHttpAuthOption(authParameters) { + return { + schemeId: "smithy.api#noAuth", + }; +} +const defaultSTSHttpAuthSchemeProvider = (authParameters) => { + const options = []; + switch (authParameters.operation) { + case "AssumeRoleWithSAML": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + case "AssumeRoleWithWebIdentity": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + default: { + options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); + } + } + return options; +}; +exports.defaultSTSHttpAuthSchemeProvider = defaultSTSHttpAuthSchemeProvider; +const resolveStsAuthConfig = (input) => Object.assign(input, { + stsClientCtor: STSClient_1.STSClient, +}); +exports.resolveStsAuthConfig = resolveStsAuthConfig; +const resolveHttpAuthSchemeConfig = (config) => { + const config_0 = (0, exports.resolveStsAuthConfig)(config); + const config_1 = (0, core_1.resolveAwsSdkSigV4Config)(config_0); + return Object.assign(config_1, { + authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), + }); +}; +exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/endpoint/EndpointParameters.js b/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/endpoint/EndpointParameters.js new file mode 100644 index 00000000..3aec6a5e --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/endpoint/EndpointParameters.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.commonParams = exports.resolveClientEndpointParameters = void 0; +const resolveClientEndpointParameters = (options) => { + return Object.assign(options, { + useDualstackEndpoint: options.useDualstackEndpoint ?? false, + useFipsEndpoint: options.useFipsEndpoint ?? false, + useGlobalEndpoint: options.useGlobalEndpoint ?? false, + defaultSigningName: "sts", + }); +}; +exports.resolveClientEndpointParameters = resolveClientEndpointParameters; +exports.commonParams = { + UseGlobalEndpoint: { type: "builtInParams", name: "useGlobalEndpoint" }, + UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, + Endpoint: { type: "builtInParams", name: "endpoint" }, + Region: { type: "builtInParams", name: "region" }, + UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, +}; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/endpoint/endpointResolver.js b/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/endpoint/endpointResolver.js new file mode 100644 index 00000000..6bfb6e90 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/endpoint/endpointResolver.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defaultEndpointResolver = void 0; +const util_endpoints_1 = require("@aws-sdk/util-endpoints"); +const util_endpoints_2 = require("@smithy/util-endpoints"); +const ruleset_1 = require("./ruleset"); +const cache = new util_endpoints_2.EndpointCache({ + size: 50, + params: ["Endpoint", "Region", "UseDualStack", "UseFIPS", "UseGlobalEndpoint"], +}); +const defaultEndpointResolver = (endpointParams, context = {}) => { + return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { + endpointParams: endpointParams, + logger: context.logger, + })); +}; +exports.defaultEndpointResolver = defaultEndpointResolver; +util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/endpoint/ruleset.js b/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/endpoint/ruleset.js new file mode 100644 index 00000000..a5e5cf2a --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/endpoint/ruleset.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ruleSet = void 0; +const F = "required", G = "type", H = "fn", I = "argv", J = "ref"; +const a = false, b = true, c = "booleanEquals", d = "stringEquals", e = "sigv4", f = "sts", g = "us-east-1", h = "endpoint", i = "https://sts.{Region}.{PartitionResult#dnsSuffix}", j = "tree", k = "error", l = "getAttr", m = { [F]: false, [G]: "string" }, n = { [F]: true, "default": false, [G]: "boolean" }, o = { [J]: "Endpoint" }, p = { [H]: "isSet", [I]: [{ [J]: "Region" }] }, q = { [J]: "Region" }, r = { [H]: "aws.partition", [I]: [q], "assign": "PartitionResult" }, s = { [J]: "UseFIPS" }, t = { [J]: "UseDualStack" }, u = { "url": "https://sts.amazonaws.com", "properties": { "authSchemes": [{ "name": e, "signingName": f, "signingRegion": g }] }, "headers": {} }, v = {}, w = { "conditions": [{ [H]: d, [I]: [q, "aws-global"] }], [h]: u, [G]: h }, x = { [H]: c, [I]: [s, true] }, y = { [H]: c, [I]: [t, true] }, z = { [H]: l, [I]: [{ [J]: "PartitionResult" }, "supportsFIPS"] }, A = { [J]: "PartitionResult" }, B = { [H]: c, [I]: [true, { [H]: l, [I]: [A, "supportsDualStack"] }] }, C = [{ [H]: "isSet", [I]: [o] }], D = [x], E = [y]; +const _data = { version: "1.0", parameters: { Region: m, UseDualStack: n, UseFIPS: n, Endpoint: m, UseGlobalEndpoint: n }, rules: [{ conditions: [{ [H]: c, [I]: [{ [J]: "UseGlobalEndpoint" }, b] }, { [H]: "not", [I]: C }, p, r, { [H]: c, [I]: [s, a] }, { [H]: c, [I]: [t, a] }], rules: [{ conditions: [{ [H]: d, [I]: [q, "ap-northeast-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "ap-south-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "ap-southeast-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "ap-southeast-2"] }], endpoint: u, [G]: h }, w, { conditions: [{ [H]: d, [I]: [q, "ca-central-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-central-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-north-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-west-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-west-2"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-west-3"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "sa-east-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, g] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "us-east-2"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "us-west-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "us-west-2"] }], endpoint: u, [G]: h }, { endpoint: { url: i, properties: { authSchemes: [{ name: e, signingName: f, signingRegion: "{Region}" }] }, headers: v }, [G]: h }], [G]: j }, { conditions: C, rules: [{ conditions: D, error: "Invalid Configuration: FIPS and custom endpoint are not supported", [G]: k }, { conditions: E, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", [G]: k }, { endpoint: { url: o, properties: v, headers: v }, [G]: h }], [G]: j }, { conditions: [p], rules: [{ conditions: [r], rules: [{ conditions: [x, y], rules: [{ conditions: [{ [H]: c, [I]: [b, z] }, B], rules: [{ endpoint: { url: "https://sts-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: v, headers: v }, [G]: h }], [G]: j }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", [G]: k }], [G]: j }, { conditions: D, rules: [{ conditions: [{ [H]: c, [I]: [z, b] }], rules: [{ conditions: [{ [H]: d, [I]: [{ [H]: l, [I]: [A, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://sts.{Region}.amazonaws.com", properties: v, headers: v }, [G]: h }, { endpoint: { url: "https://sts-fips.{Region}.{PartitionResult#dnsSuffix}", properties: v, headers: v }, [G]: h }], [G]: j }, { error: "FIPS is enabled but this partition does not support FIPS", [G]: k }], [G]: j }, { conditions: E, rules: [{ conditions: [B], rules: [{ endpoint: { url: "https://sts.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: v, headers: v }, [G]: h }], [G]: j }, { error: "DualStack is enabled but this partition does not support DualStack", [G]: k }], [G]: j }, w, { endpoint: { url: i, properties: v, headers: v }, [G]: h }], [G]: j }], [G]: j }, { error: "Invalid Configuration: Missing Region", [G]: k }] }; +exports.ruleSet = _data; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/index.js new file mode 100644 index 00000000..62b019bc --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/index.js @@ -0,0 +1,947 @@ +'use strict'; + +var STSClient = require('./STSClient'); +var smithyClient = require('@smithy/smithy-client'); +var middlewareEndpoint = require('@smithy/middleware-endpoint'); +var EndpointParameters = require('./endpoint/EndpointParameters'); +var schema = require('@smithy/core/schema'); +var client = require('@aws-sdk/core/client'); +var regionConfigResolver = require('@aws-sdk/region-config-resolver'); + +let STSServiceException$1 = class STSServiceException extends smithyClient.ServiceException { + constructor(options) { + super(options); + Object.setPrototypeOf(this, STSServiceException.prototype); + } +}; + +let ExpiredTokenException$1 = class ExpiredTokenException extends STSServiceException$1 { + name = "ExpiredTokenException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ExpiredTokenException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ExpiredTokenException.prototype); + } +}; +let MalformedPolicyDocumentException$1 = class MalformedPolicyDocumentException extends STSServiceException$1 { + name = "MalformedPolicyDocumentException"; + $fault = "client"; + constructor(opts) { + super({ + name: "MalformedPolicyDocumentException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, MalformedPolicyDocumentException.prototype); + } +}; +let PackedPolicyTooLargeException$1 = class PackedPolicyTooLargeException extends STSServiceException$1 { + name = "PackedPolicyTooLargeException"; + $fault = "client"; + constructor(opts) { + super({ + name: "PackedPolicyTooLargeException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, PackedPolicyTooLargeException.prototype); + } +}; +let RegionDisabledException$1 = class RegionDisabledException extends STSServiceException$1 { + name = "RegionDisabledException"; + $fault = "client"; + constructor(opts) { + super({ + name: "RegionDisabledException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, RegionDisabledException.prototype); + } +}; +let IDPRejectedClaimException$1 = class IDPRejectedClaimException extends STSServiceException$1 { + name = "IDPRejectedClaimException"; + $fault = "client"; + constructor(opts) { + super({ + name: "IDPRejectedClaimException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, IDPRejectedClaimException.prototype); + } +}; +let InvalidIdentityTokenException$1 = class InvalidIdentityTokenException extends STSServiceException$1 { + name = "InvalidIdentityTokenException"; + $fault = "client"; + constructor(opts) { + super({ + name: "InvalidIdentityTokenException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, InvalidIdentityTokenException.prototype); + } +}; +let IDPCommunicationErrorException$1 = class IDPCommunicationErrorException extends STSServiceException$1 { + name = "IDPCommunicationErrorException"; + $fault = "client"; + constructor(opts) { + super({ + name: "IDPCommunicationErrorException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, IDPCommunicationErrorException.prototype); + } +}; +let InvalidAuthorizationMessageException$1 = class InvalidAuthorizationMessageException extends STSServiceException$1 { + name = "InvalidAuthorizationMessageException"; + $fault = "client"; + constructor(opts) { + super({ + name: "InvalidAuthorizationMessageException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, InvalidAuthorizationMessageException.prototype); + } +}; +let ExpiredTradeInTokenException$1 = class ExpiredTradeInTokenException extends STSServiceException$1 { + name = "ExpiredTradeInTokenException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ExpiredTradeInTokenException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ExpiredTradeInTokenException.prototype); + } +}; +let JWTPayloadSizeExceededException$1 = class JWTPayloadSizeExceededException extends STSServiceException$1 { + name = "JWTPayloadSizeExceededException"; + $fault = "client"; + constructor(opts) { + super({ + name: "JWTPayloadSizeExceededException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, JWTPayloadSizeExceededException.prototype); + } +}; +let OutboundWebIdentityFederationDisabledException$1 = class OutboundWebIdentityFederationDisabledException extends STSServiceException$1 { + name = "OutboundWebIdentityFederationDisabledException"; + $fault = "client"; + constructor(opts) { + super({ + name: "OutboundWebIdentityFederationDisabledException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, OutboundWebIdentityFederationDisabledException.prototype); + } +}; +let SessionDurationEscalationException$1 = class SessionDurationEscalationException extends STSServiceException$1 { + name = "SessionDurationEscalationException"; + $fault = "client"; + constructor(opts) { + super({ + name: "SessionDurationEscalationException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, SessionDurationEscalationException.prototype); + } +}; + +const _A = "Arn"; +const _AKI = "AccessKeyId"; +const _AP = "AssumedPrincipal"; +const _AR = "AssumeRole"; +const _ARI = "AssumedRoleId"; +const _ARR = "AssumeRoleRequest"; +const _ARRs = "AssumeRoleResponse"; +const _ARRss = "AssumeRootRequest"; +const _ARRssu = "AssumeRootResponse"; +const _ARU = "AssumedRoleUser"; +const _ARWSAML = "AssumeRoleWithSAML"; +const _ARWSAMLR = "AssumeRoleWithSAMLRequest"; +const _ARWSAMLRs = "AssumeRoleWithSAMLResponse"; +const _ARWWI = "AssumeRoleWithWebIdentity"; +const _ARWWIR = "AssumeRoleWithWebIdentityRequest"; +const _ARWWIRs = "AssumeRoleWithWebIdentityResponse"; +const _ARs = "AssumeRoot"; +const _Ac = "Account"; +const _Au = "Audience"; +const _C = "Credentials"; +const _CA = "ContextAssertion"; +const _DAM = "DecodeAuthorizationMessage"; +const _DAMR = "DecodeAuthorizationMessageRequest"; +const _DAMRe = "DecodeAuthorizationMessageResponse"; +const _DM = "DecodedMessage"; +const _DS = "DurationSeconds"; +const _E = "Expiration"; +const _EI = "ExternalId"; +const _EM = "EncodedMessage"; +const _ETE = "ExpiredTokenException"; +const _ETITE = "ExpiredTradeInTokenException"; +const _FU = "FederatedUser"; +const _FUI = "FederatedUserId"; +const _GAKI = "GetAccessKeyInfo"; +const _GAKIR = "GetAccessKeyInfoRequest"; +const _GAKIRe = "GetAccessKeyInfoResponse"; +const _GCI = "GetCallerIdentity"; +const _GCIR = "GetCallerIdentityRequest"; +const _GCIRe = "GetCallerIdentityResponse"; +const _GDAT = "GetDelegatedAccessToken"; +const _GDATR = "GetDelegatedAccessTokenRequest"; +const _GDATRe = "GetDelegatedAccessTokenResponse"; +const _GFT = "GetFederationToken"; +const _GFTR = "GetFederationTokenRequest"; +const _GFTRe = "GetFederationTokenResponse"; +const _GST = "GetSessionToken"; +const _GSTR = "GetSessionTokenRequest"; +const _GSTRe = "GetSessionTokenResponse"; +const _GWIT = "GetWebIdentityToken"; +const _GWITR = "GetWebIdentityTokenRequest"; +const _GWITRe = "GetWebIdentityTokenResponse"; +const _I = "Issuer"; +const _IAME = "InvalidAuthorizationMessageException"; +const _IDPCEE = "IDPCommunicationErrorException"; +const _IDPRCE = "IDPRejectedClaimException"; +const _IITE = "InvalidIdentityTokenException"; +const _JWTPSEE = "JWTPayloadSizeExceededException"; +const _K = "Key"; +const _MPDE = "MalformedPolicyDocumentException"; +const _N = "Name"; +const _NQ = "NameQualifier"; +const _OWIFDE = "OutboundWebIdentityFederationDisabledException"; +const _P = "Policy"; +const _PA = "PolicyArns"; +const _PAr = "PrincipalArn"; +const _PAro = "ProviderArn"; +const _PC = "ProvidedContexts"; +const _PCLT = "ProvidedContextsListType"; +const _PCr = "ProvidedContext"; +const _PDT = "PolicyDescriptorType"; +const _PI = "ProviderId"; +const _PPS = "PackedPolicySize"; +const _PPTLE = "PackedPolicyTooLargeException"; +const _Pr = "Provider"; +const _RA = "RoleArn"; +const _RDE = "RegionDisabledException"; +const _RSN = "RoleSessionName"; +const _S = "Subject"; +const _SA = "SigningAlgorithm"; +const _SAK = "SecretAccessKey"; +const _SAMLA = "SAMLAssertion"; +const _SAMLAT = "SAMLAssertionType"; +const _SDEE = "SessionDurationEscalationException"; +const _SFWIT = "SubjectFromWebIdentityToken"; +const _SI = "SourceIdentity"; +const _SN = "SerialNumber"; +const _ST = "SubjectType"; +const _STe = "SessionToken"; +const _T = "Tags"; +const _TC = "TokenCode"; +const _TIT = "TradeInToken"; +const _TP = "TargetPrincipal"; +const _TPA = "TaskPolicyArn"; +const _TTK = "TransitiveTagKeys"; +const _Ta = "Tag"; +const _UI = "UserId"; +const _V = "Value"; +const _WIT = "WebIdentityToken"; +const _a = "arn"; +const _aKST = "accessKeySecretType"; +const _aQE = "awsQueryError"; +const _c = "client"; +const _cTT = "clientTokenType"; +const _e = "error"; +const _hE = "httpError"; +const _m = "message"; +const _pDLT = "policyDescriptorListType"; +const _s = "smithy.ts.sdk.synthetic.com.amazonaws.sts"; +const _tITT = "tradeInTokenType"; +const _tLT = "tagListType"; +const _wITT = "webIdentityTokenType"; +const n0 = "com.amazonaws.sts"; +var accessKeySecretType = [0, n0, _aKST, 8, 0]; +var clientTokenType = [0, n0, _cTT, 8, 0]; +var SAMLAssertionType = [0, n0, _SAMLAT, 8, 0]; +var tradeInTokenType = [0, n0, _tITT, 8, 0]; +var webIdentityTokenType = [0, n0, _wITT, 8, 0]; +var AssumedRoleUser = [3, n0, _ARU, 0, [_ARI, _A], [0, 0]]; +var AssumeRoleRequest = [ + 3, + n0, + _ARR, + 0, + [_RA, _RSN, _PA, _P, _DS, _T, _TTK, _EI, _SN, _TC, _SI, _PC], + [0, 0, () => policyDescriptorListType, 0, 1, () => tagListType, 64 | 0, 0, 0, 0, 0, () => ProvidedContextsListType], +]; +var AssumeRoleResponse = [ + 3, + n0, + _ARRs, + 0, + [_C, _ARU, _PPS, _SI], + [[() => Credentials, 0], () => AssumedRoleUser, 1, 0], +]; +var AssumeRoleWithSAMLRequest = [ + 3, + n0, + _ARWSAMLR, + 0, + [_RA, _PAr, _SAMLA, _PA, _P, _DS], + [0, 0, [() => SAMLAssertionType, 0], () => policyDescriptorListType, 0, 1], +]; +var AssumeRoleWithSAMLResponse = [ + 3, + n0, + _ARWSAMLRs, + 0, + [_C, _ARU, _PPS, _S, _ST, _I, _Au, _NQ, _SI], + [[() => Credentials, 0], () => AssumedRoleUser, 1, 0, 0, 0, 0, 0, 0], +]; +var AssumeRoleWithWebIdentityRequest = [ + 3, + n0, + _ARWWIR, + 0, + [_RA, _RSN, _WIT, _PI, _PA, _P, _DS], + [0, 0, [() => clientTokenType, 0], 0, () => policyDescriptorListType, 0, 1], +]; +var AssumeRoleWithWebIdentityResponse = [ + 3, + n0, + _ARWWIRs, + 0, + [_C, _SFWIT, _ARU, _PPS, _Pr, _Au, _SI], + [[() => Credentials, 0], 0, () => AssumedRoleUser, 1, 0, 0, 0], +]; +var AssumeRootRequest = [ + 3, + n0, + _ARRss, + 0, + [_TP, _TPA, _DS], + [0, () => PolicyDescriptorType, 1], +]; +var AssumeRootResponse = [3, n0, _ARRssu, 0, [_C, _SI], [[() => Credentials, 0], 0]]; +var Credentials = [ + 3, + n0, + _C, + 0, + [_AKI, _SAK, _STe, _E], + [0, [() => accessKeySecretType, 0], 0, 4], +]; +var DecodeAuthorizationMessageRequest = [3, n0, _DAMR, 0, [_EM], [0]]; +var DecodeAuthorizationMessageResponse = [3, n0, _DAMRe, 0, [_DM], [0]]; +var ExpiredTokenException = [ + -3, + n0, + _ETE, + { + [_e]: _c, + [_hE]: 400, + [_aQE]: [`ExpiredTokenException`, 400], + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(ExpiredTokenException, ExpiredTokenException$1); +var ExpiredTradeInTokenException = [ + -3, + n0, + _ETITE, + { + [_e]: _c, + [_hE]: 400, + [_aQE]: [`ExpiredTradeInTokenException`, 400], + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(ExpiredTradeInTokenException, ExpiredTradeInTokenException$1); +var FederatedUser = [3, n0, _FU, 0, [_FUI, _A], [0, 0]]; +var GetAccessKeyInfoRequest = [3, n0, _GAKIR, 0, [_AKI], [0]]; +var GetAccessKeyInfoResponse = [3, n0, _GAKIRe, 0, [_Ac], [0]]; +var GetCallerIdentityRequest = [3, n0, _GCIR, 0, [], []]; +var GetCallerIdentityResponse = [3, n0, _GCIRe, 0, [_UI, _Ac, _A], [0, 0, 0]]; +var GetDelegatedAccessTokenRequest = [ + 3, + n0, + _GDATR, + 0, + [_TIT], + [[() => tradeInTokenType, 0]], +]; +var GetDelegatedAccessTokenResponse = [ + 3, + n0, + _GDATRe, + 0, + [_C, _PPS, _AP], + [[() => Credentials, 0], 1, 0], +]; +var GetFederationTokenRequest = [ + 3, + n0, + _GFTR, + 0, + [_N, _P, _PA, _DS, _T], + [0, 0, () => policyDescriptorListType, 1, () => tagListType], +]; +var GetFederationTokenResponse = [ + 3, + n0, + _GFTRe, + 0, + [_C, _FU, _PPS], + [[() => Credentials, 0], () => FederatedUser, 1], +]; +var GetSessionTokenRequest = [3, n0, _GSTR, 0, [_DS, _SN, _TC], [1, 0, 0]]; +var GetSessionTokenResponse = [3, n0, _GSTRe, 0, [_C], [[() => Credentials, 0]]]; +var GetWebIdentityTokenRequest = [ + 3, + n0, + _GWITR, + 0, + [_Au, _DS, _SA, _T], + [64 | 0, 1, 0, () => tagListType], +]; +var GetWebIdentityTokenResponse = [ + 3, + n0, + _GWITRe, + 0, + [_WIT, _E], + [[() => webIdentityTokenType, 0], 4], +]; +var IDPCommunicationErrorException = [ + -3, + n0, + _IDPCEE, + { + [_e]: _c, + [_hE]: 400, + [_aQE]: [`IDPCommunicationError`, 400], + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(IDPCommunicationErrorException, IDPCommunicationErrorException$1); +var IDPRejectedClaimException = [ + -3, + n0, + _IDPRCE, + { + [_e]: _c, + [_hE]: 403, + [_aQE]: [`IDPRejectedClaim`, 403], + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(IDPRejectedClaimException, IDPRejectedClaimException$1); +var InvalidAuthorizationMessageException = [ + -3, + n0, + _IAME, + { + [_e]: _c, + [_hE]: 400, + [_aQE]: [`InvalidAuthorizationMessageException`, 400], + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(InvalidAuthorizationMessageException, InvalidAuthorizationMessageException$1); +var InvalidIdentityTokenException = [ + -3, + n0, + _IITE, + { + [_e]: _c, + [_hE]: 400, + [_aQE]: [`InvalidIdentityToken`, 400], + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(InvalidIdentityTokenException, InvalidIdentityTokenException$1); +var JWTPayloadSizeExceededException = [ + -3, + n0, + _JWTPSEE, + { + [_e]: _c, + [_hE]: 400, + [_aQE]: [`JWTPayloadSizeExceededException`, 400], + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(JWTPayloadSizeExceededException, JWTPayloadSizeExceededException$1); +var MalformedPolicyDocumentException = [ + -3, + n0, + _MPDE, + { + [_e]: _c, + [_hE]: 400, + [_aQE]: [`MalformedPolicyDocument`, 400], + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(MalformedPolicyDocumentException, MalformedPolicyDocumentException$1); +var OutboundWebIdentityFederationDisabledException = [ + -3, + n0, + _OWIFDE, + { + [_e]: _c, + [_hE]: 403, + [_aQE]: [`OutboundWebIdentityFederationDisabledException`, 403], + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(OutboundWebIdentityFederationDisabledException, OutboundWebIdentityFederationDisabledException$1); +var PackedPolicyTooLargeException = [ + -3, + n0, + _PPTLE, + { + [_e]: _c, + [_hE]: 400, + [_aQE]: [`PackedPolicyTooLarge`, 400], + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(PackedPolicyTooLargeException, PackedPolicyTooLargeException$1); +var PolicyDescriptorType = [3, n0, _PDT, 0, [_a], [0]]; +var ProvidedContext = [3, n0, _PCr, 0, [_PAro, _CA], [0, 0]]; +var RegionDisabledException = [ + -3, + n0, + _RDE, + { + [_e]: _c, + [_hE]: 403, + [_aQE]: [`RegionDisabledException`, 403], + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(RegionDisabledException, RegionDisabledException$1); +var SessionDurationEscalationException = [ + -3, + n0, + _SDEE, + { + [_e]: _c, + [_hE]: 403, + [_aQE]: [`SessionDurationEscalationException`, 403], + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(SessionDurationEscalationException, SessionDurationEscalationException$1); +var Tag = [3, n0, _Ta, 0, [_K, _V], [0, 0]]; +var STSServiceException = [-3, _s, "STSServiceException", 0, [], []]; +schema.TypeRegistry.for(_s).registerError(STSServiceException, STSServiceException$1); +var policyDescriptorListType = [1, n0, _pDLT, 0, () => PolicyDescriptorType]; +var ProvidedContextsListType = [1, n0, _PCLT, 0, () => ProvidedContext]; +var tagListType = [1, n0, _tLT, 0, () => Tag]; +var AssumeRole = [9, n0, _AR, 0, () => AssumeRoleRequest, () => AssumeRoleResponse]; +var AssumeRoleWithSAML = [ + 9, + n0, + _ARWSAML, + 0, + () => AssumeRoleWithSAMLRequest, + () => AssumeRoleWithSAMLResponse, +]; +var AssumeRoleWithWebIdentity = [ + 9, + n0, + _ARWWI, + 0, + () => AssumeRoleWithWebIdentityRequest, + () => AssumeRoleWithWebIdentityResponse, +]; +var AssumeRoot = [9, n0, _ARs, 0, () => AssumeRootRequest, () => AssumeRootResponse]; +var DecodeAuthorizationMessage = [ + 9, + n0, + _DAM, + 0, + () => DecodeAuthorizationMessageRequest, + () => DecodeAuthorizationMessageResponse, +]; +var GetAccessKeyInfo = [ + 9, + n0, + _GAKI, + 0, + () => GetAccessKeyInfoRequest, + () => GetAccessKeyInfoResponse, +]; +var GetCallerIdentity = [ + 9, + n0, + _GCI, + 0, + () => GetCallerIdentityRequest, + () => GetCallerIdentityResponse, +]; +var GetDelegatedAccessToken = [ + 9, + n0, + _GDAT, + 0, + () => GetDelegatedAccessTokenRequest, + () => GetDelegatedAccessTokenResponse, +]; +var GetFederationToken = [ + 9, + n0, + _GFT, + 0, + () => GetFederationTokenRequest, + () => GetFederationTokenResponse, +]; +var GetSessionToken = [ + 9, + n0, + _GST, + 0, + () => GetSessionTokenRequest, + () => GetSessionTokenResponse, +]; +var GetWebIdentityToken = [ + 9, + n0, + _GWIT, + 0, + () => GetWebIdentityTokenRequest, + () => GetWebIdentityTokenResponse, +]; + +class AssumeRoleCommand extends smithyClient.Command + .classBuilder() + .ep(EndpointParameters.commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSSecurityTokenServiceV20110615", "AssumeRole", {}) + .n("STSClient", "AssumeRoleCommand") + .sc(AssumeRole) + .build() { +} + +class AssumeRoleWithSAMLCommand extends smithyClient.Command + .classBuilder() + .ep(EndpointParameters.commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithSAML", {}) + .n("STSClient", "AssumeRoleWithSAMLCommand") + .sc(AssumeRoleWithSAML) + .build() { +} + +class AssumeRoleWithWebIdentityCommand extends smithyClient.Command + .classBuilder() + .ep(EndpointParameters.commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithWebIdentity", {}) + .n("STSClient", "AssumeRoleWithWebIdentityCommand") + .sc(AssumeRoleWithWebIdentity) + .build() { +} + +class AssumeRootCommand extends smithyClient.Command + .classBuilder() + .ep(EndpointParameters.commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSSecurityTokenServiceV20110615", "AssumeRoot", {}) + .n("STSClient", "AssumeRootCommand") + .sc(AssumeRoot) + .build() { +} + +class DecodeAuthorizationMessageCommand extends smithyClient.Command + .classBuilder() + .ep(EndpointParameters.commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSSecurityTokenServiceV20110615", "DecodeAuthorizationMessage", {}) + .n("STSClient", "DecodeAuthorizationMessageCommand") + .sc(DecodeAuthorizationMessage) + .build() { +} + +class GetAccessKeyInfoCommand extends smithyClient.Command + .classBuilder() + .ep(EndpointParameters.commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSSecurityTokenServiceV20110615", "GetAccessKeyInfo", {}) + .n("STSClient", "GetAccessKeyInfoCommand") + .sc(GetAccessKeyInfo) + .build() { +} + +class GetCallerIdentityCommand extends smithyClient.Command + .classBuilder() + .ep(EndpointParameters.commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSSecurityTokenServiceV20110615", "GetCallerIdentity", {}) + .n("STSClient", "GetCallerIdentityCommand") + .sc(GetCallerIdentity) + .build() { +} + +class GetDelegatedAccessTokenCommand extends smithyClient.Command + .classBuilder() + .ep(EndpointParameters.commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSSecurityTokenServiceV20110615", "GetDelegatedAccessToken", {}) + .n("STSClient", "GetDelegatedAccessTokenCommand") + .sc(GetDelegatedAccessToken) + .build() { +} + +class GetFederationTokenCommand extends smithyClient.Command + .classBuilder() + .ep(EndpointParameters.commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSSecurityTokenServiceV20110615", "GetFederationToken", {}) + .n("STSClient", "GetFederationTokenCommand") + .sc(GetFederationToken) + .build() { +} + +class GetSessionTokenCommand extends smithyClient.Command + .classBuilder() + .ep(EndpointParameters.commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSSecurityTokenServiceV20110615", "GetSessionToken", {}) + .n("STSClient", "GetSessionTokenCommand") + .sc(GetSessionToken) + .build() { +} + +class GetWebIdentityTokenCommand extends smithyClient.Command + .classBuilder() + .ep(EndpointParameters.commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSSecurityTokenServiceV20110615", "GetWebIdentityToken", {}) + .n("STSClient", "GetWebIdentityTokenCommand") + .sc(GetWebIdentityToken) + .build() { +} + +const commands = { + AssumeRoleCommand, + AssumeRoleWithSAMLCommand, + AssumeRoleWithWebIdentityCommand, + AssumeRootCommand, + DecodeAuthorizationMessageCommand, + GetAccessKeyInfoCommand, + GetCallerIdentityCommand, + GetDelegatedAccessTokenCommand, + GetFederationTokenCommand, + GetSessionTokenCommand, + GetWebIdentityTokenCommand, +}; +class STS extends STSClient.STSClient { +} +smithyClient.createAggregatedClient(commands, STS); + +const getAccountIdFromAssumedRoleUser = (assumedRoleUser) => { + if (typeof assumedRoleUser?.Arn === "string") { + const arnComponents = assumedRoleUser.Arn.split(":"); + if (arnComponents.length > 4 && arnComponents[4] !== "") { + return arnComponents[4]; + } + } + return undefined; +}; +const resolveRegion = async (_region, _parentRegion, credentialProviderLogger, loaderConfig = {}) => { + const region = typeof _region === "function" ? await _region() : _region; + const parentRegion = typeof _parentRegion === "function" ? await _parentRegion() : _parentRegion; + const stsDefaultRegion = await regionConfigResolver.stsRegionDefaultResolver(loaderConfig)(); + credentialProviderLogger?.debug?.("@aws-sdk/client-sts::resolveRegion", "accepting first of:", `${region} (credential provider clientConfig)`, `${parentRegion} (contextual client)`, `${stsDefaultRegion} (STS default: AWS_REGION, profile region, or us-east-1)`); + return region ?? parentRegion ?? stsDefaultRegion; +}; +const getDefaultRoleAssumer$1 = (stsOptions, STSClient) => { + let stsClient; + let closureSourceCreds; + return async (sourceCreds, params) => { + closureSourceCreds = sourceCreds; + if (!stsClient) { + const { logger = stsOptions?.parentClientConfig?.logger, profile = stsOptions?.parentClientConfig?.profile, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger, userAgentAppId = stsOptions?.parentClientConfig?.userAgentAppId, } = stsOptions; + const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger, { + logger, + profile, + }); + const isCompatibleRequestHandler = !isH2(requestHandler); + stsClient = new STSClient({ + ...stsOptions, + userAgentAppId, + profile, + credentialDefaultProvider: () => async () => closureSourceCreds, + region: resolvedRegion, + requestHandler: isCompatibleRequestHandler ? requestHandler : undefined, + logger: logger, + }); + } + const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleCommand(params)); + if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) { + throw new Error(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`); + } + const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser); + const credentials = { + accessKeyId: Credentials.AccessKeyId, + secretAccessKey: Credentials.SecretAccessKey, + sessionToken: Credentials.SessionToken, + expiration: Credentials.Expiration, + ...(Credentials.CredentialScope && { credentialScope: Credentials.CredentialScope }), + ...(accountId && { accountId }), + }; + client.setCredentialFeature(credentials, "CREDENTIALS_STS_ASSUME_ROLE", "i"); + return credentials; + }; +}; +const getDefaultRoleAssumerWithWebIdentity$1 = (stsOptions, STSClient) => { + let stsClient; + return async (params) => { + if (!stsClient) { + const { logger = stsOptions?.parentClientConfig?.logger, profile = stsOptions?.parentClientConfig?.profile, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger, userAgentAppId = stsOptions?.parentClientConfig?.userAgentAppId, } = stsOptions; + const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger, { + logger, + profile, + }); + const isCompatibleRequestHandler = !isH2(requestHandler); + stsClient = new STSClient({ + ...stsOptions, + userAgentAppId, + profile, + region: resolvedRegion, + requestHandler: isCompatibleRequestHandler ? requestHandler : undefined, + logger: logger, + }); + } + const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleWithWebIdentityCommand(params)); + if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) { + throw new Error(`Invalid response from STS.assumeRoleWithWebIdentity call with role ${params.RoleArn}`); + } + const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser); + const credentials = { + accessKeyId: Credentials.AccessKeyId, + secretAccessKey: Credentials.SecretAccessKey, + sessionToken: Credentials.SessionToken, + expiration: Credentials.Expiration, + ...(Credentials.CredentialScope && { credentialScope: Credentials.CredentialScope }), + ...(accountId && { accountId }), + }; + if (accountId) { + client.setCredentialFeature(credentials, "RESOLVED_ACCOUNT_ID", "T"); + } + client.setCredentialFeature(credentials, "CREDENTIALS_STS_ASSUME_ROLE_WEB_ID", "k"); + return credentials; + }; +}; +const isH2 = (requestHandler) => { + return requestHandler?.metadata?.handlerProtocol === "h2"; +}; + +const getCustomizableStsClientCtor = (baseCtor, customizations) => { + if (!customizations) + return baseCtor; + else + return class CustomizableSTSClient extends baseCtor { + constructor(config) { + super(config); + for (const customization of customizations) { + this.middlewareStack.use(customization); + } + } + }; +}; +const getDefaultRoleAssumer = (stsOptions = {}, stsPlugins) => getDefaultRoleAssumer$1(stsOptions, getCustomizableStsClientCtor(STSClient.STSClient, stsPlugins)); +const getDefaultRoleAssumerWithWebIdentity = (stsOptions = {}, stsPlugins) => getDefaultRoleAssumerWithWebIdentity$1(stsOptions, getCustomizableStsClientCtor(STSClient.STSClient, stsPlugins)); +const decorateDefaultCredentialProvider = (provider) => (input) => provider({ + roleAssumer: getDefaultRoleAssumer(input), + roleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity(input), + ...input, +}); + +Object.defineProperty(exports, "$Command", { + enumerable: true, + get: function () { return smithyClient.Command; } +}); +exports.AssumeRoleCommand = AssumeRoleCommand; +exports.AssumeRoleWithSAMLCommand = AssumeRoleWithSAMLCommand; +exports.AssumeRoleWithWebIdentityCommand = AssumeRoleWithWebIdentityCommand; +exports.AssumeRootCommand = AssumeRootCommand; +exports.DecodeAuthorizationMessageCommand = DecodeAuthorizationMessageCommand; +exports.ExpiredTokenException = ExpiredTokenException$1; +exports.ExpiredTradeInTokenException = ExpiredTradeInTokenException$1; +exports.GetAccessKeyInfoCommand = GetAccessKeyInfoCommand; +exports.GetCallerIdentityCommand = GetCallerIdentityCommand; +exports.GetDelegatedAccessTokenCommand = GetDelegatedAccessTokenCommand; +exports.GetFederationTokenCommand = GetFederationTokenCommand; +exports.GetSessionTokenCommand = GetSessionTokenCommand; +exports.GetWebIdentityTokenCommand = GetWebIdentityTokenCommand; +exports.IDPCommunicationErrorException = IDPCommunicationErrorException$1; +exports.IDPRejectedClaimException = IDPRejectedClaimException$1; +exports.InvalidAuthorizationMessageException = InvalidAuthorizationMessageException$1; +exports.InvalidIdentityTokenException = InvalidIdentityTokenException$1; +exports.JWTPayloadSizeExceededException = JWTPayloadSizeExceededException$1; +exports.MalformedPolicyDocumentException = MalformedPolicyDocumentException$1; +exports.OutboundWebIdentityFederationDisabledException = OutboundWebIdentityFederationDisabledException$1; +exports.PackedPolicyTooLargeException = PackedPolicyTooLargeException$1; +exports.RegionDisabledException = RegionDisabledException$1; +exports.STS = STS; +exports.STSServiceException = STSServiceException$1; +exports.SessionDurationEscalationException = SessionDurationEscalationException$1; +exports.decorateDefaultCredentialProvider = decorateDefaultCredentialProvider; +exports.getDefaultRoleAssumer = getDefaultRoleAssumer; +exports.getDefaultRoleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity; +Object.keys(STSClient).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return STSClient[k]; } + }); +}); diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/runtimeConfig.js b/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/runtimeConfig.js new file mode 100644 index 00000000..7d39d101 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/runtimeConfig.js @@ -0,0 +1,70 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getRuntimeConfig = void 0; +const tslib_1 = require("tslib"); +const package_json_1 = tslib_1.__importDefault(require("../package.json")); +const core_1 = require("@aws-sdk/core"); +const credential_provider_node_1 = require("@aws-sdk/credential-provider-node"); +const util_user_agent_node_1 = require("@aws-sdk/util-user-agent-node"); +const config_resolver_1 = require("@smithy/config-resolver"); +const core_2 = require("@smithy/core"); +const hash_node_1 = require("@smithy/hash-node"); +const middleware_retry_1 = require("@smithy/middleware-retry"); +const node_config_provider_1 = require("@smithy/node-config-provider"); +const node_http_handler_1 = require("@smithy/node-http-handler"); +const util_body_length_node_1 = require("@smithy/util-body-length-node"); +const util_retry_1 = require("@smithy/util-retry"); +const runtimeConfig_shared_1 = require("./runtimeConfig.shared"); +const smithy_client_1 = require("@smithy/smithy-client"); +const util_defaults_mode_node_1 = require("@smithy/util-defaults-mode-node"); +const smithy_client_2 = require("@smithy/smithy-client"); +const getRuntimeConfig = (config) => { + (0, smithy_client_2.emitWarningIfUnsupportedVersion)(process.version); + const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config); + const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode); + const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config); + (0, core_1.emitWarningIfUnsupportedVersion)(process.version); + const loaderConfig = { + profile: config?.profile, + logger: clientSharedValues.logger, + }; + return { + ...clientSharedValues, + ...config, + runtime: "node", + defaultsMode, + authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), + bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, + credentialDefaultProvider: config?.credentialDefaultProvider ?? credential_provider_node_1.defaultProvider, + defaultUserAgentProvider: config?.defaultUserAgentProvider ?? + (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4") || + (async (idProps) => await (0, credential_provider_node_1.defaultProvider)(idProps?.__config || {})()), + signer: new core_1.AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new core_2.NoAuthSigner(), + }, + ], + maxAttempts: config?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), + region: config?.region ?? + (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), + requestHandler: node_http_handler_1.NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), + retryMode: config?.retryMode ?? + (0, node_config_provider_1.loadConfig)({ + ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS, + default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE, + }, config), + sha256: config?.sha256 ?? hash_node_1.Hash.bind(null, "sha256"), + streamCollector: config?.streamCollector ?? node_http_handler_1.streamCollector, + useDualstackEndpoint: config?.useDualstackEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), + }; +}; +exports.getRuntimeConfig = getRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/runtimeConfig.shared.js b/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/runtimeConfig.shared.js new file mode 100644 index 00000000..5291d67e --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/runtimeConfig.shared.js @@ -0,0 +1,47 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getRuntimeConfig = void 0; +const core_1 = require("@aws-sdk/core"); +const protocols_1 = require("@aws-sdk/core/protocols"); +const core_2 = require("@smithy/core"); +const smithy_client_1 = require("@smithy/smithy-client"); +const url_parser_1 = require("@smithy/url-parser"); +const util_base64_1 = require("@smithy/util-base64"); +const util_utf8_1 = require("@smithy/util-utf8"); +const httpAuthSchemeProvider_1 = require("./auth/httpAuthSchemeProvider"); +const endpointResolver_1 = require("./endpoint/endpointResolver"); +const getRuntimeConfig = (config) => { + return { + apiVersion: "2011-06-15", + base64Decoder: config?.base64Decoder ?? util_base64_1.fromBase64, + base64Encoder: config?.base64Encoder ?? util_base64_1.toBase64, + disableHostPrefix: config?.disableHostPrefix ?? false, + endpointProvider: config?.endpointProvider ?? endpointResolver_1.defaultEndpointResolver, + extensions: config?.extensions ?? [], + httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSTSHttpAuthSchemeProvider, + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new core_1.AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new core_2.NoAuthSigner(), + }, + ], + logger: config?.logger ?? new smithy_client_1.NoOpLogger(), + protocol: config?.protocol ?? + new protocols_1.AwsQueryProtocol({ + defaultNamespace: "com.amazonaws.sts", + xmlNamespace: "https://sts.amazonaws.com/doc/2011-06-15/", + version: "2011-06-15", + }), + serviceId: config?.serviceId ?? "STS", + urlParser: config?.urlParser ?? url_parser_1.parseUrl, + utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, + utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, + }; +}; +exports.getRuntimeConfig = getRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/runtimeExtensions.js b/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/runtimeExtensions.js new file mode 100644 index 00000000..a50ebec3 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/runtimeExtensions.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.resolveRuntimeExtensions = void 0; +const region_config_resolver_1 = require("@aws-sdk/region-config-resolver"); +const protocol_http_1 = require("@smithy/protocol-http"); +const smithy_client_1 = require("@smithy/smithy-client"); +const httpAuthExtensionConfiguration_1 = require("./auth/httpAuthExtensionConfiguration"); +const resolveRuntimeExtensions = (runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign((0, region_config_resolver_1.getAwsRegionExtensionConfiguration)(runtimeConfig), (0, smithy_client_1.getDefaultExtensionConfiguration)(runtimeConfig), (0, protocol_http_1.getHttpHandlerExtensionConfiguration)(runtimeConfig), (0, httpAuthExtensionConfiguration_1.getHttpAuthExtensionConfiguration)(runtimeConfig)); + extensions.forEach((extension) => extension.configure(extensionConfiguration)); + return Object.assign(runtimeConfig, (0, region_config_resolver_1.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), (0, smithy_client_1.resolveDefaultRuntimeConfig)(extensionConfiguration), (0, protocol_http_1.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), (0, httpAuthExtensionConfiguration_1.resolveHttpAuthRuntimeConfig)(extensionConfiguration)); +}; +exports.resolveRuntimeExtensions = resolveRuntimeExtensions; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/protocol-http/dist-cjs/index.js new file mode 100644 index 00000000..52303c3b --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/protocol-http/dist-cjs/index.js @@ -0,0 +1,169 @@ +'use strict'; + +var types = require('@smithy/types'); + +const getHttpHandlerExtensionConfiguration = (runtimeConfig) => { + return { + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); + }, + }; +}; +const resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler(), + }; +}; + +class Field { + name; + kind; + values; + constructor({ name, kind = types.FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; + } + add(value) { + this.values.push(value); + } + set(values) { + this.values = values; + } + remove(value) { + this.values = this.values.filter((v) => v !== value); + } + toString() { + return this.values.map((v) => (v.includes(",") || v.includes(" ") ? `"${v}"` : v)).join(", "); + } + get() { + return this.values; + } +} + +class Fields { + entries = {}; + encoding; + constructor({ fields = [], encoding = "utf-8" }) { + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + setField(field) { + this.entries[field.name.toLowerCase()] = field; + } + getField(name) { + return this.entries[name.toLowerCase()]; + } + removeField(name) { + delete this.entries[name.toLowerCase()]; + } + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } +} + +class HttpRequest { + method; + protocol; + hostname; + port; + path; + query; + headers; + username; + password; + fragment; + body; + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol + ? options.protocol.slice(-1) !== ":" + ? `${options.protocol}:` + : options.protocol + : "https:"; + this.path = options.path ? (options.path.charAt(0) !== "/" ? `/${options.path}` : options.path) : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + static clone(request) { + const cloned = new HttpRequest({ + ...request, + headers: { ...request.headers }, + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); + } + return cloned; + } + static isInstance(request) { + if (!request) { + return false; + } + const req = request; + return ("method" in req && + "protocol" in req && + "hostname" in req && + "path" in req && + typeof req["query"] === "object" && + typeof req["headers"] === "object"); + } + clone() { + return HttpRequest.clone(this); + } +} +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param, + }; + }, {}); +} + +class HttpResponse { + statusCode; + reason; + headers; + body; + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) + return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + } +} + +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} + +exports.Field = Field; +exports.Fields = Fields; +exports.HttpRequest = HttpRequest; +exports.HttpResponse = HttpResponse; +exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration; +exports.isValidHostname = isValidHostname; +exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/smithy-client/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/smithy-client/dist-cjs/index.js new file mode 100644 index 00000000..9f589873 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/smithy-client/dist-cjs/index.js @@ -0,0 +1,589 @@ +'use strict'; + +var middlewareStack = require('@smithy/middleware-stack'); +var protocols = require('@smithy/core/protocols'); +var types = require('@smithy/types'); +var schema = require('@smithy/core/schema'); +var serde = require('@smithy/core/serde'); + +class Client { + config; + middlewareStack = middlewareStack.constructStack(); + initConfig; + handlers; + constructor(config) { + this.config = config; + } + send(command, optionsOrCb, cb) { + const options = typeof optionsOrCb !== "function" ? optionsOrCb : undefined; + const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb; + const useHandlerCache = options === undefined && this.config.cacheMiddleware === true; + let handler; + if (useHandlerCache) { + if (!this.handlers) { + this.handlers = new WeakMap(); + } + const handlers = this.handlers; + if (handlers.has(command.constructor)) { + handler = handlers.get(command.constructor); + } + else { + handler = command.resolveMiddleware(this.middlewareStack, this.config, options); + handlers.set(command.constructor, handler); + } + } + else { + delete this.handlers; + handler = command.resolveMiddleware(this.middlewareStack, this.config, options); + } + if (callback) { + handler(command) + .then((result) => callback(null, result.output), (err) => callback(err)) + .catch(() => { }); + } + else { + return handler(command).then((result) => result.output); + } + } + destroy() { + this.config?.requestHandler?.destroy?.(); + delete this.handlers; + } +} + +const SENSITIVE_STRING$1 = "***SensitiveInformation***"; +function schemaLogFilter(schema$1, data) { + if (data == null) { + return data; + } + const ns = schema.NormalizedSchema.of(schema$1); + if (ns.getMergedTraits().sensitive) { + return SENSITIVE_STRING$1; + } + if (ns.isListSchema()) { + const isSensitive = !!ns.getValueSchema().getMergedTraits().sensitive; + if (isSensitive) { + return SENSITIVE_STRING$1; + } + } + else if (ns.isMapSchema()) { + const isSensitive = !!ns.getKeySchema().getMergedTraits().sensitive || !!ns.getValueSchema().getMergedTraits().sensitive; + if (isSensitive) { + return SENSITIVE_STRING$1; + } + } + else if (ns.isStructSchema() && typeof data === "object") { + const object = data; + const newObject = {}; + for (const [member, memberNs] of ns.structIterator()) { + if (object[member] != null) { + newObject[member] = schemaLogFilter(memberNs, object[member]); + } + } + return newObject; + } + return data; +} + +class Command { + middlewareStack = middlewareStack.constructStack(); + schema; + static classBuilder() { + return new ClassBuilder(); + } + resolveMiddlewareWithContext(clientStack, configuration, options, { middlewareFn, clientName, commandName, inputFilterSensitiveLog, outputFilterSensitiveLog, smithyContext, additionalContext, CommandCtor, }) { + for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options)) { + this.middlewareStack.use(mw); + } + const stack = clientStack.concat(this.middlewareStack); + const { logger } = configuration; + const handlerExecutionContext = { + logger, + clientName, + commandName, + inputFilterSensitiveLog, + outputFilterSensitiveLog, + [types.SMITHY_CONTEXT_KEY]: { + commandInstance: this, + ...smithyContext, + }, + ...additionalContext, + }; + const { requestHandler } = configuration; + return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); + } +} +class ClassBuilder { + _init = () => { }; + _ep = {}; + _middlewareFn = () => []; + _commandName = ""; + _clientName = ""; + _additionalContext = {}; + _smithyContext = {}; + _inputFilterSensitiveLog = undefined; + _outputFilterSensitiveLog = undefined; + _serializer = null; + _deserializer = null; + _operationSchema; + init(cb) { + this._init = cb; + } + ep(endpointParameterInstructions) { + this._ep = endpointParameterInstructions; + return this; + } + m(middlewareSupplier) { + this._middlewareFn = middlewareSupplier; + return this; + } + s(service, operation, smithyContext = {}) { + this._smithyContext = { + service, + operation, + ...smithyContext, + }; + return this; + } + c(additionalContext = {}) { + this._additionalContext = additionalContext; + return this; + } + n(clientName, commandName) { + this._clientName = clientName; + this._commandName = commandName; + return this; + } + f(inputFilter = (_) => _, outputFilter = (_) => _) { + this._inputFilterSensitiveLog = inputFilter; + this._outputFilterSensitiveLog = outputFilter; + return this; + } + ser(serializer) { + this._serializer = serializer; + return this; + } + de(deserializer) { + this._deserializer = deserializer; + return this; + } + sc(operation) { + this._operationSchema = operation; + this._smithyContext.operationSchema = operation; + return this; + } + build() { + const closure = this; + let CommandRef; + return (CommandRef = class extends Command { + input; + static getEndpointParameterInstructions() { + return closure._ep; + } + constructor(...[input]) { + super(); + this.input = input ?? {}; + closure._init(this); + this.schema = closure._operationSchema; + } + resolveMiddleware(stack, configuration, options) { + const op = closure._operationSchema; + const input = op?.[4] ?? op?.input; + const output = op?.[5] ?? op?.output; + return this.resolveMiddlewareWithContext(stack, configuration, options, { + CommandCtor: CommandRef, + middlewareFn: closure._middlewareFn, + clientName: closure._clientName, + commandName: closure._commandName, + inputFilterSensitiveLog: closure._inputFilterSensitiveLog ?? (op ? schemaLogFilter.bind(null, input) : (_) => _), + outputFilterSensitiveLog: closure._outputFilterSensitiveLog ?? (op ? schemaLogFilter.bind(null, output) : (_) => _), + smithyContext: closure._smithyContext, + additionalContext: closure._additionalContext, + }); + } + serialize = closure._serializer; + deserialize = closure._deserializer; + }); + } +} + +const SENSITIVE_STRING = "***SensitiveInformation***"; + +const createAggregatedClient = (commands, Client) => { + for (const command of Object.keys(commands)) { + const CommandCtor = commands[command]; + const methodImpl = async function (args, optionsOrCb, cb) { + const command = new CommandCtor(args); + if (typeof optionsOrCb === "function") { + this.send(command, optionsOrCb); + } + else if (typeof cb === "function") { + if (typeof optionsOrCb !== "object") + throw new Error(`Expected http options but got ${typeof optionsOrCb}`); + this.send(command, optionsOrCb || {}, cb); + } + else { + return this.send(command, optionsOrCb); + } + }; + const methodName = (command[0].toLowerCase() + command.slice(1)).replace(/Command$/, ""); + Client.prototype[methodName] = methodImpl; + } +}; + +class ServiceException extends Error { + $fault; + $response; + $retryable; + $metadata; + constructor(options) { + super(options.message); + Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype); + this.name = options.name; + this.$fault = options.$fault; + this.$metadata = options.$metadata; + } + static isInstance(value) { + if (!value) + return false; + const candidate = value; + return (ServiceException.prototype.isPrototypeOf(candidate) || + (Boolean(candidate.$fault) && + Boolean(candidate.$metadata) && + (candidate.$fault === "client" || candidate.$fault === "server"))); + } + static [Symbol.hasInstance](instance) { + if (!instance) + return false; + const candidate = instance; + if (this === ServiceException) { + return ServiceException.isInstance(instance); + } + if (ServiceException.isInstance(instance)) { + if (candidate.name && this.name) { + return this.prototype.isPrototypeOf(instance) || candidate.name === this.name; + } + return this.prototype.isPrototypeOf(instance); + } + return false; + } +} +const decorateServiceException = (exception, additions = {}) => { + Object.entries(additions) + .filter(([, v]) => v !== undefined) + .forEach(([k, v]) => { + if (exception[k] == undefined || exception[k] === "") { + exception[k] = v; + } + }); + const message = exception.message || exception.Message || "UnknownError"; + exception.message = message; + delete exception.Message; + return exception; +}; + +const throwDefaultError = ({ output, parsedBody, exceptionCtor, errorCode }) => { + const $metadata = deserializeMetadata(output); + const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : undefined; + const response = new exceptionCtor({ + name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || "UnknownError", + $fault: "client", + $metadata, + }); + throw decorateServiceException(response, parsedBody); +}; +const withBaseException = (ExceptionCtor) => { + return ({ output, parsedBody, errorCode }) => { + throwDefaultError({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode }); + }; +}; +const deserializeMetadata = (output) => ({ + httpStatusCode: output.statusCode, + requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], + extendedRequestId: output.headers["x-amz-id-2"], + cfId: output.headers["x-amz-cf-id"], +}); + +const loadConfigsForDefaultMode = (mode) => { + switch (mode) { + case "standard": + return { + retryMode: "standard", + connectionTimeout: 3100, + }; + case "in-region": + return { + retryMode: "standard", + connectionTimeout: 1100, + }; + case "cross-region": + return { + retryMode: "standard", + connectionTimeout: 3100, + }; + case "mobile": + return { + retryMode: "standard", + connectionTimeout: 30000, + }; + default: + return {}; + } +}; + +let warningEmitted = false; +const emitWarningIfUnsupportedVersion = (version) => { + if (version && !warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 16) { + warningEmitted = true; + } +}; + +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + for (const id in types.AlgorithmId) { + const algorithmId = types.AlgorithmId[id]; + if (runtimeConfig[algorithmId] === undefined) { + continue; + } + checksumAlgorithms.push({ + algorithmId: () => algorithmId, + checksumConstructor: () => runtimeConfig[algorithmId], + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getRetryConfiguration = (runtimeConfig) => { + return { + setRetryStrategy(retryStrategy) { + runtimeConfig.retryStrategy = retryStrategy; + }, + retryStrategy() { + return runtimeConfig.retryStrategy; + }, + }; +}; +const resolveRetryRuntimeConfig = (retryStrategyConfiguration) => { + const runtimeConfig = {}; + runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy(); + return runtimeConfig; +}; + +const getDefaultExtensionConfiguration = (runtimeConfig) => { + return Object.assign(getChecksumConfiguration(runtimeConfig), getRetryConfiguration(runtimeConfig)); +}; +const getDefaultClientConfiguration = getDefaultExtensionConfiguration; +const resolveDefaultRuntimeConfig = (config) => { + return Object.assign(resolveChecksumRuntimeConfig(config), resolveRetryRuntimeConfig(config)); +}; + +const getArrayIfSingleItem = (mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray]; + +const getValueFromTextNode = (obj) => { + const textNodeName = "#text"; + for (const key in obj) { + if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== undefined) { + obj[key] = obj[key][textNodeName]; + } + else if (typeof obj[key] === "object" && obj[key] !== null) { + obj[key] = getValueFromTextNode(obj[key]); + } + } + return obj; +}; + +const isSerializableHeaderValue = (value) => { + return value != null; +}; + +class NoOpLogger { + trace() { } + debug() { } + info() { } + warn() { } + error() { } +} + +function map(arg0, arg1, arg2) { + let target; + let filter; + let instructions; + if (typeof arg1 === "undefined" && typeof arg2 === "undefined") { + target = {}; + instructions = arg0; + } + else { + target = arg0; + if (typeof arg1 === "function") { + filter = arg1; + instructions = arg2; + return mapWithFilter(target, filter, instructions); + } + else { + instructions = arg1; + } + } + for (const key of Object.keys(instructions)) { + if (!Array.isArray(instructions[key])) { + target[key] = instructions[key]; + continue; + } + applyInstruction(target, null, instructions, key); + } + return target; +} +const convertMap = (target) => { + const output = {}; + for (const [k, v] of Object.entries(target || {})) { + output[k] = [, v]; + } + return output; +}; +const take = (source, instructions) => { + const out = {}; + for (const key in instructions) { + applyInstruction(out, source, instructions, key); + } + return out; +}; +const mapWithFilter = (target, filter, instructions) => { + return map(target, Object.entries(instructions).reduce((_instructions, [key, value]) => { + if (Array.isArray(value)) { + _instructions[key] = value; + } + else { + if (typeof value === "function") { + _instructions[key] = [filter, value()]; + } + else { + _instructions[key] = [filter, value]; + } + } + return _instructions; + }, {})); +}; +const applyInstruction = (target, source, instructions, targetKey) => { + if (source !== null) { + let instruction = instructions[targetKey]; + if (typeof instruction === "function") { + instruction = [, instruction]; + } + const [filter = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction; + if ((typeof filter === "function" && filter(source[sourceKey])) || (typeof filter !== "function" && !!filter)) { + target[targetKey] = valueFn(source[sourceKey]); + } + return; + } + let [filter, value] = instructions[targetKey]; + if (typeof value === "function") { + let _value; + const defaultFilterPassed = filter === undefined && (_value = value()) != null; + const customFilterPassed = (typeof filter === "function" && !!filter(void 0)) || (typeof filter !== "function" && !!filter); + if (defaultFilterPassed) { + target[targetKey] = _value; + } + else if (customFilterPassed) { + target[targetKey] = value(); + } + } + else { + const defaultFilterPassed = filter === undefined && value != null; + const customFilterPassed = (typeof filter === "function" && !!filter(value)) || (typeof filter !== "function" && !!filter); + if (defaultFilterPassed || customFilterPassed) { + target[targetKey] = value; + } + } +}; +const nonNullish = (_) => _ != null; +const pass = (_) => _; + +const serializeFloat = (value) => { + if (value !== value) { + return "NaN"; + } + switch (value) { + case Infinity: + return "Infinity"; + case -Infinity: + return "-Infinity"; + default: + return value; + } +}; +const serializeDateTime = (date) => date.toISOString().replace(".000Z", "Z"); + +const _json = (obj) => { + if (obj == null) { + return {}; + } + if (Array.isArray(obj)) { + return obj.filter((_) => _ != null).map(_json); + } + if (typeof obj === "object") { + const target = {}; + for (const key of Object.keys(obj)) { + if (obj[key] == null) { + continue; + } + target[key] = _json(obj[key]); + } + return target; + } + return obj; +}; + +Object.defineProperty(exports, "collectBody", { + enumerable: true, + get: function () { return protocols.collectBody; } +}); +Object.defineProperty(exports, "extendedEncodeURIComponent", { + enumerable: true, + get: function () { return protocols.extendedEncodeURIComponent; } +}); +Object.defineProperty(exports, "resolvedPath", { + enumerable: true, + get: function () { return protocols.resolvedPath; } +}); +exports.Client = Client; +exports.Command = Command; +exports.NoOpLogger = NoOpLogger; +exports.SENSITIVE_STRING = SENSITIVE_STRING; +exports.ServiceException = ServiceException; +exports._json = _json; +exports.convertMap = convertMap; +exports.createAggregatedClient = createAggregatedClient; +exports.decorateServiceException = decorateServiceException; +exports.emitWarningIfUnsupportedVersion = emitWarningIfUnsupportedVersion; +exports.getArrayIfSingleItem = getArrayIfSingleItem; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.getDefaultExtensionConfiguration = getDefaultExtensionConfiguration; +exports.getValueFromTextNode = getValueFromTextNode; +exports.isSerializableHeaderValue = isSerializableHeaderValue; +exports.loadConfigsForDefaultMode = loadConfigsForDefaultMode; +exports.map = map; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; +exports.serializeDateTime = serializeDateTime; +exports.serializeFloat = serializeFloat; +exports.take = take; +exports.throwDefaultError = throwDefaultError; +exports.withBaseException = withBaseException; +Object.keys(serde).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return serde[k]; } + }); +}); diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-cjs/index.js new file mode 100644 index 00000000..be6d0e1a --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-cjs/index.js @@ -0,0 +1,91 @@ +'use strict'; + +exports.HttpAuthLocation = void 0; +(function (HttpAuthLocation) { + HttpAuthLocation["HEADER"] = "header"; + HttpAuthLocation["QUERY"] = "query"; +})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); + +exports.HttpApiKeyAuthLocation = void 0; +(function (HttpApiKeyAuthLocation) { + HttpApiKeyAuthLocation["HEADER"] = "header"; + HttpApiKeyAuthLocation["QUERY"] = "query"; +})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); + +exports.EndpointURLScheme = void 0; +(function (EndpointURLScheme) { + EndpointURLScheme["HTTP"] = "http"; + EndpointURLScheme["HTTPS"] = "https"; +})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); + +exports.AlgorithmId = void 0; +(function (AlgorithmId) { + AlgorithmId["MD5"] = "md5"; + AlgorithmId["CRC32"] = "crc32"; + AlgorithmId["CRC32C"] = "crc32c"; + AlgorithmId["SHA1"] = "sha1"; + AlgorithmId["SHA256"] = "sha256"; +})(exports.AlgorithmId || (exports.AlgorithmId = {})); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.SHA256, + checksumConstructor: () => runtimeConfig.sha256, + }); + } + if (runtimeConfig.md5 != undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.MD5, + checksumConstructor: () => runtimeConfig.md5, + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getDefaultClientConfiguration = (runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}; +const resolveDefaultRuntimeConfig = (config) => { + return resolveChecksumRuntimeConfig(config); +}; + +exports.FieldPosition = void 0; +(function (FieldPosition) { + FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; + FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; +})(exports.FieldPosition || (exports.FieldPosition = {})); + +const SMITHY_CONTEXT_KEY = "__smithy_context"; + +exports.IniSectionType = void 0; +(function (IniSectionType) { + IniSectionType["PROFILE"] = "profile"; + IniSectionType["SSO_SESSION"] = "sso-session"; + IniSectionType["SERVICES"] = "services"; +})(exports.IniSectionType || (exports.IniSectionType = {})); + +exports.RequestHandlerProtocol = void 0; +(function (RequestHandlerProtocol) { + RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; +})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); + +exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js b/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js new file mode 100644 index 00000000..b06a7b87 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromBase64 = void 0; +const util_buffer_from_1 = require("@smithy/util-buffer-from"); +const BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; +const fromBase64 = (input) => { + if ((input.length * 3) % 4 !== 0) { + throw new TypeError(`Incorrect padding on base64 string.`); + } + if (!BASE64_REGEX.exec(input)) { + throw new TypeError(`Invalid base64 string.`); + } + const buffer = (0, util_buffer_from_1.fromString)(input, "base64"); + return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); +}; +exports.fromBase64 = fromBase64; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/dist-cjs/index.js new file mode 100644 index 00000000..c095e288 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/dist-cjs/index.js @@ -0,0 +1,19 @@ +'use strict'; + +var fromBase64 = require('./fromBase64'); +var toBase64 = require('./toBase64'); + + + +Object.keys(fromBase64).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return fromBase64[k]; } + }); +}); +Object.keys(toBase64).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return toBase64[k]; } + }); +}); diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/dist-cjs/toBase64.js b/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/dist-cjs/toBase64.js new file mode 100644 index 00000000..0590ce3f --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/dist-cjs/toBase64.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.toBase64 = void 0; +const util_buffer_from_1 = require("@smithy/util-buffer-from"); +const util_utf8_1 = require("@smithy/util-utf8"); +const toBase64 = (_input) => { + let input; + if (typeof _input === "string") { + input = (0, util_utf8_1.fromUtf8)(_input); + } + else { + input = _input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); + } + return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64"); +}; +exports.toBase64 = toBase64; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js new file mode 100644 index 00000000..b577c9ca --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js @@ -0,0 +1,20 @@ +'use strict'; + +var isArrayBuffer = require('@smithy/is-array-buffer'); +var buffer = require('buffer'); + +const fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => { + if (!isArrayBuffer.isArrayBuffer(input)) { + throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); + } + return buffer.Buffer.from(input, offset, length); +}; +const fromString = (input, encoding) => { + if (typeof input !== "string") { + throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); + } + return encoding ? buffer.Buffer.from(input, encoding) : buffer.Buffer.from(input); +}; + +exports.fromArrayBuffer = fromArrayBuffer; +exports.fromString = fromString; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js new file mode 100644 index 00000000..3238bb77 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js @@ -0,0 +1,6 @@ +'use strict'; + +const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) || + Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; + +exports.isArrayBuffer = isArrayBuffer; diff --git a/claude-code-source/node_modules/@aws-sdk/core/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/core/dist-cjs/index.js new file mode 100644 index 00000000..6cda67ed --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/core/dist-cjs/index.js @@ -0,0 +1,2000 @@ +'use strict'; + +var protocolHttp = require('@smithy/protocol-http'); +var core = require('@smithy/core'); +var propertyProvider = require('@smithy/property-provider'); +var client = require('@aws-sdk/core/client'); +var signatureV4 = require('@smithy/signature-v4'); +var cbor = require('@smithy/core/cbor'); +var schema = require('@smithy/core/schema'); +var smithyClient = require('@smithy/smithy-client'); +var protocols = require('@smithy/core/protocols'); +var serde = require('@smithy/core/serde'); +var utilBase64 = require('@smithy/util-base64'); +var utilUtf8 = require('@smithy/util-utf8'); +var xmlBuilder = require('@aws-sdk/xml-builder'); + +const state = { + warningEmitted: false, +}; +const emitWarningIfUnsupportedVersion = (version) => { + if (version && !state.warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 18) { + state.warningEmitted = true; + process.emitWarning(`NodeDeprecationWarning: The AWS SDK for JavaScript (v3) will +no longer support Node.js 16.x on January 6, 2025. + +To continue receiving updates to AWS services, bug fixes, and security +updates please upgrade to a supported Node.js LTS version. + +More information can be found at: https://a.co/74kJMmI`); + } +}; + +function setCredentialFeature(credentials, feature, value) { + if (!credentials.$source) { + credentials.$source = {}; + } + credentials.$source[feature] = value; + return credentials; +} + +function setFeature(context, feature, value) { + if (!context.__aws_sdk_context) { + context.__aws_sdk_context = { + features: {}, + }; + } + else if (!context.__aws_sdk_context.features) { + context.__aws_sdk_context.features = {}; + } + context.__aws_sdk_context.features[feature] = value; +} + +function setTokenFeature(token, feature, value) { + if (!token.$source) { + token.$source = {}; + } + token.$source[feature] = value; + return token; +} + +const getDateHeader = (response) => protocolHttp.HttpResponse.isInstance(response) ? response.headers?.date ?? response.headers?.Date : undefined; + +const getSkewCorrectedDate = (systemClockOffset) => new Date(Date.now() + systemClockOffset); + +const isClockSkewed = (clockTime, systemClockOffset) => Math.abs(getSkewCorrectedDate(systemClockOffset).getTime() - clockTime) >= 300000; + +const getUpdatedSystemClockOffset = (clockTime, currentSystemClockOffset) => { + const clockTimeInMs = Date.parse(clockTime); + if (isClockSkewed(clockTimeInMs, currentSystemClockOffset)) { + return clockTimeInMs - Date.now(); + } + return currentSystemClockOffset; +}; + +const throwSigningPropertyError = (name, property) => { + if (!property) { + throw new Error(`Property \`${name}\` is not resolved for AWS SDK SigV4Auth`); + } + return property; +}; +const validateSigningProperties = async (signingProperties) => { + const context = throwSigningPropertyError("context", signingProperties.context); + const config = throwSigningPropertyError("config", signingProperties.config); + const authScheme = context.endpointV2?.properties?.authSchemes?.[0]; + const signerFunction = throwSigningPropertyError("signer", config.signer); + const signer = await signerFunction(authScheme); + const signingRegion = signingProperties?.signingRegion; + const signingRegionSet = signingProperties?.signingRegionSet; + const signingName = signingProperties?.signingName; + return { + config, + signer, + signingRegion, + signingRegionSet, + signingName, + }; +}; +class AwsSdkSigV4Signer { + async sign(httpRequest, identity, signingProperties) { + if (!protocolHttp.HttpRequest.isInstance(httpRequest)) { + throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); + } + const validatedProps = await validateSigningProperties(signingProperties); + const { config, signer } = validatedProps; + let { signingRegion, signingName } = validatedProps; + const handlerExecutionContext = signingProperties.context; + if (handlerExecutionContext?.authSchemes?.length ?? 0 > 1) { + const [first, second] = handlerExecutionContext.authSchemes; + if (first?.name === "sigv4a" && second?.name === "sigv4") { + signingRegion = second?.signingRegion ?? signingRegion; + signingName = second?.signingName ?? signingName; + } + } + const signedRequest = await signer.sign(httpRequest, { + signingDate: getSkewCorrectedDate(config.systemClockOffset), + signingRegion: signingRegion, + signingService: signingName, + }); + return signedRequest; + } + errorHandler(signingProperties) { + return (error) => { + const serverTime = error.ServerTime ?? getDateHeader(error.$response); + if (serverTime) { + const config = throwSigningPropertyError("config", signingProperties.config); + const initialSystemClockOffset = config.systemClockOffset; + config.systemClockOffset = getUpdatedSystemClockOffset(serverTime, config.systemClockOffset); + const clockSkewCorrected = config.systemClockOffset !== initialSystemClockOffset; + if (clockSkewCorrected && error.$metadata) { + error.$metadata.clockSkewCorrected = true; + } + } + throw error; + }; + } + successHandler(httpResponse, signingProperties) { + const dateHeader = getDateHeader(httpResponse); + if (dateHeader) { + const config = throwSigningPropertyError("config", signingProperties.config); + config.systemClockOffset = getUpdatedSystemClockOffset(dateHeader, config.systemClockOffset); + } + } +} +const AWSSDKSigV4Signer = AwsSdkSigV4Signer; + +class AwsSdkSigV4ASigner extends AwsSdkSigV4Signer { + async sign(httpRequest, identity, signingProperties) { + if (!protocolHttp.HttpRequest.isInstance(httpRequest)) { + throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); + } + const { config, signer, signingRegion, signingRegionSet, signingName } = await validateSigningProperties(signingProperties); + const configResolvedSigningRegionSet = await config.sigv4aSigningRegionSet?.(); + const multiRegionOverride = (configResolvedSigningRegionSet ?? + signingRegionSet ?? [signingRegion]).join(","); + const signedRequest = await signer.sign(httpRequest, { + signingDate: getSkewCorrectedDate(config.systemClockOffset), + signingRegion: multiRegionOverride, + signingService: signingName, + }); + return signedRequest; + } +} + +const getArrayForCommaSeparatedString = (str) => typeof str === "string" && str.length > 0 ? str.split(",").map((item) => item.trim()) : []; + +const getBearerTokenEnvKey = (signingName) => `AWS_BEARER_TOKEN_${signingName.replace(/[\s-]/g, "_").toUpperCase()}`; + +const NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY = "AWS_AUTH_SCHEME_PREFERENCE"; +const NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY = "auth_scheme_preference"; +const NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = { + environmentVariableSelector: (env, options) => { + if (options?.signingName) { + const bearerTokenKey = getBearerTokenEnvKey(options.signingName); + if (bearerTokenKey in env) + return ["httpBearerAuth"]; + } + if (!(NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY in env)) + return undefined; + return getArrayForCommaSeparatedString(env[NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY]); + }, + configFileSelector: (profile) => { + if (!(NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY in profile)) + return undefined; + return getArrayForCommaSeparatedString(profile[NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY]); + }, + default: [], +}; + +const resolveAwsSdkSigV4AConfig = (config) => { + config.sigv4aSigningRegionSet = core.normalizeProvider(config.sigv4aSigningRegionSet); + return config; +}; +const NODE_SIGV4A_CONFIG_OPTIONS = { + environmentVariableSelector(env) { + if (env.AWS_SIGV4A_SIGNING_REGION_SET) { + return env.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((_) => _.trim()); + } + throw new propertyProvider.ProviderError("AWS_SIGV4A_SIGNING_REGION_SET not set in env.", { + tryNextLink: true, + }); + }, + configFileSelector(profile) { + if (profile.sigv4a_signing_region_set) { + return (profile.sigv4a_signing_region_set ?? "").split(",").map((_) => _.trim()); + } + throw new propertyProvider.ProviderError("sigv4a_signing_region_set not set in profile.", { + tryNextLink: true, + }); + }, + default: undefined, +}; + +const resolveAwsSdkSigV4Config = (config) => { + let inputCredentials = config.credentials; + let isUserSupplied = !!config.credentials; + let resolvedCredentials = undefined; + Object.defineProperty(config, "credentials", { + set(credentials) { + if (credentials && credentials !== inputCredentials && credentials !== resolvedCredentials) { + isUserSupplied = true; + } + inputCredentials = credentials; + const memoizedProvider = normalizeCredentialProvider(config, { + credentials: inputCredentials, + credentialDefaultProvider: config.credentialDefaultProvider, + }); + const boundProvider = bindCallerConfig(config, memoizedProvider); + if (isUserSupplied && !boundProvider.attributed) { + resolvedCredentials = async (options) => boundProvider(options).then((creds) => client.setCredentialFeature(creds, "CREDENTIALS_CODE", "e")); + resolvedCredentials.memoized = boundProvider.memoized; + resolvedCredentials.configBound = boundProvider.configBound; + resolvedCredentials.attributed = true; + } + else { + resolvedCredentials = boundProvider; + } + }, + get() { + return resolvedCredentials; + }, + enumerable: true, + configurable: true, + }); + config.credentials = inputCredentials; + const { signingEscapePath = true, systemClockOffset = config.systemClockOffset || 0, sha256, } = config; + let signer; + if (config.signer) { + signer = core.normalizeProvider(config.signer); + } + else if (config.regionInfoProvider) { + signer = () => core.normalizeProvider(config.region)() + .then(async (region) => [ + (await config.regionInfoProvider(region, { + useFipsEndpoint: await config.useFipsEndpoint(), + useDualstackEndpoint: await config.useDualstackEndpoint(), + })) || {}, + region, + ]) + .then(([regionInfo, region]) => { + const { signingRegion, signingService } = regionInfo; + config.signingRegion = config.signingRegion || signingRegion || region; + config.signingName = config.signingName || signingService || config.serviceId; + const params = { + ...config, + credentials: config.credentials, + region: config.signingRegion, + service: config.signingName, + sha256, + uriEscapePath: signingEscapePath, + }; + const SignerCtor = config.signerConstructor || signatureV4.SignatureV4; + return new SignerCtor(params); + }); + } + else { + signer = async (authScheme) => { + authScheme = Object.assign({}, { + name: "sigv4", + signingName: config.signingName || config.defaultSigningName, + signingRegion: await core.normalizeProvider(config.region)(), + properties: {}, + }, authScheme); + const signingRegion = authScheme.signingRegion; + const signingService = authScheme.signingName; + config.signingRegion = config.signingRegion || signingRegion; + config.signingName = config.signingName || signingService || config.serviceId; + const params = { + ...config, + credentials: config.credentials, + region: config.signingRegion, + service: config.signingName, + sha256, + uriEscapePath: signingEscapePath, + }; + const SignerCtor = config.signerConstructor || signatureV4.SignatureV4; + return new SignerCtor(params); + }; + } + const resolvedConfig = Object.assign(config, { + systemClockOffset, + signingEscapePath, + signer, + }); + return resolvedConfig; +}; +const resolveAWSSDKSigV4Config = resolveAwsSdkSigV4Config; +function normalizeCredentialProvider(config, { credentials, credentialDefaultProvider, }) { + let credentialsProvider; + if (credentials) { + if (!credentials?.memoized) { + credentialsProvider = core.memoizeIdentityProvider(credentials, core.isIdentityExpired, core.doesIdentityRequireRefresh); + } + else { + credentialsProvider = credentials; + } + } + else { + if (credentialDefaultProvider) { + credentialsProvider = core.normalizeProvider(credentialDefaultProvider(Object.assign({}, config, { + parentClientConfig: config, + }))); + } + else { + credentialsProvider = async () => { + throw new Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured."); + }; + } + } + credentialsProvider.memoized = true; + return credentialsProvider; +} +function bindCallerConfig(config, credentialsProvider) { + if (credentialsProvider.configBound) { + return credentialsProvider; + } + const fn = async (options) => credentialsProvider({ ...options, callerClientConfig: config }); + fn.memoized = credentialsProvider.memoized; + fn.configBound = true; + return fn; +} + +class ProtocolLib { + queryCompat; + constructor(queryCompat = false) { + this.queryCompat = queryCompat; + } + resolveRestContentType(defaultContentType, inputSchema) { + const members = inputSchema.getMemberSchemas(); + const httpPayloadMember = Object.values(members).find((m) => { + return !!m.getMergedTraits().httpPayload; + }); + if (httpPayloadMember) { + const mediaType = httpPayloadMember.getMergedTraits().mediaType; + if (mediaType) { + return mediaType; + } + else if (httpPayloadMember.isStringSchema()) { + return "text/plain"; + } + else if (httpPayloadMember.isBlobSchema()) { + return "application/octet-stream"; + } + else { + return defaultContentType; + } + } + else if (!inputSchema.isUnitSchema()) { + const hasBody = Object.values(members).find((m) => { + const { httpQuery, httpQueryParams, httpHeader, httpLabel, httpPrefixHeaders } = m.getMergedTraits(); + const noPrefixHeaders = httpPrefixHeaders === void 0; + return !httpQuery && !httpQueryParams && !httpHeader && !httpLabel && noPrefixHeaders; + }); + if (hasBody) { + return defaultContentType; + } + } + } + async getErrorSchemaOrThrowBaseException(errorIdentifier, defaultNamespace, response, dataObject, metadata, getErrorSchema) { + let namespace = defaultNamespace; + let errorName = errorIdentifier; + if (errorIdentifier.includes("#")) { + [namespace, errorName] = errorIdentifier.split("#"); + } + const errorMetadata = { + $metadata: metadata, + $fault: response.statusCode < 500 ? "client" : "server", + }; + const registry = schema.TypeRegistry.for(namespace); + try { + const errorSchema = getErrorSchema?.(registry, errorName) ?? registry.getSchema(errorIdentifier); + return { errorSchema, errorMetadata }; + } + catch (e) { + dataObject.message = dataObject.message ?? dataObject.Message ?? "UnknownError"; + const synthetic = schema.TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace); + const baseExceptionSchema = synthetic.getBaseException(); + if (baseExceptionSchema) { + const ErrorCtor = synthetic.getErrorCtor(baseExceptionSchema) ?? Error; + throw this.decorateServiceException(Object.assign(new ErrorCtor({ name: errorName }), errorMetadata), dataObject); + } + throw this.decorateServiceException(Object.assign(new Error(errorName), errorMetadata), dataObject); + } + } + decorateServiceException(exception, additions = {}) { + if (this.queryCompat) { + const msg = exception.Message ?? additions.Message; + const error = smithyClient.decorateServiceException(exception, additions); + if (msg) { + error.Message = msg; + error.message = msg; + } + return error; + } + return smithyClient.decorateServiceException(exception, additions); + } + setQueryCompatError(output, response) { + const queryErrorHeader = response.headers?.["x-amzn-query-error"]; + if (output !== undefined && queryErrorHeader != null) { + const [Code, Type] = queryErrorHeader.split(";"); + const entries = Object.entries(output); + const Error = { + Code, + Type, + }; + Object.assign(output, Error); + for (const [k, v] of entries) { + Error[k] = v; + } + delete Error.__type; + output.Error = Error; + } + } + queryCompatOutput(queryCompatErrorData, errorData) { + if (queryCompatErrorData.Error) { + errorData.Error = queryCompatErrorData.Error; + } + if (queryCompatErrorData.Type) { + errorData.Type = queryCompatErrorData.Type; + } + if (queryCompatErrorData.Code) { + errorData.Code = queryCompatErrorData.Code; + } + } +} + +class AwsSmithyRpcV2CborProtocol extends cbor.SmithyRpcV2CborProtocol { + awsQueryCompatible; + mixin; + constructor({ defaultNamespace, awsQueryCompatible, }) { + super({ defaultNamespace }); + this.awsQueryCompatible = !!awsQueryCompatible; + this.mixin = new ProtocolLib(this.awsQueryCompatible); + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + if (this.awsQueryCompatible) { + request.headers["x-amzn-query-mode"] = "true"; + } + return request; + } + async handleError(operationSchema, context, response, dataObject, metadata) { + if (this.awsQueryCompatible) { + this.mixin.setQueryCompatError(dataObject, response); + } + const errorName = cbor.loadSmithyRpcV2CborErrorCode(response, dataObject) ?? "Unknown"; + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorName, this.options.defaultNamespace, response, dataObject, metadata); + const ns = schema.NormalizedSchema.of(errorSchema); + const message = dataObject.message ?? dataObject.Message ?? "Unknown"; + const ErrorCtor = schema.TypeRegistry.for(errorSchema[1]).getErrorCtor(errorSchema) ?? Error; + const exception = new ErrorCtor(message); + const output = {}; + for (const [name, member] of ns.structIterator()) { + output[name] = this.deserializer.readValue(member, dataObject[name]); + } + if (this.awsQueryCompatible) { + this.mixin.queryCompatOutput(dataObject, output); + } + throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message, + }, output), dataObject); + } +} + +const _toStr = (val) => { + if (val == null) { + return val; + } + if (typeof val === "number" || typeof val === "bigint") { + const warning = new Error(`Received number ${val} where a string was expected.`); + warning.name = "Warning"; + console.warn(warning); + return String(val); + } + if (typeof val === "boolean") { + const warning = new Error(`Received boolean ${val} where a string was expected.`); + warning.name = "Warning"; + console.warn(warning); + return String(val); + } + return val; +}; +const _toBool = (val) => { + if (val == null) { + return val; + } + if (typeof val === "string") { + const lowercase = val.toLowerCase(); + if (val !== "" && lowercase !== "false" && lowercase !== "true") { + const warning = new Error(`Received string "${val}" where a boolean was expected.`); + warning.name = "Warning"; + console.warn(warning); + } + return val !== "" && lowercase !== "false"; + } + return val; +}; +const _toNum = (val) => { + if (val == null) { + return val; + } + if (typeof val === "string") { + const num = Number(val); + if (num.toString() !== val) { + const warning = new Error(`Received string "${val}" where a number was expected.`); + warning.name = "Warning"; + console.warn(warning); + return val; + } + return num; + } + return val; +}; + +class SerdeContextConfig { + serdeContext; + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + } +} + +function jsonReviver(key, value, context) { + if (context?.source) { + const numericString = context.source; + if (typeof value === "number") { + if (value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER || numericString !== String(value)) { + const isFractional = numericString.includes("."); + if (isFractional) { + return new serde.NumericValue(numericString, "bigDecimal"); + } + else { + return BigInt(numericString); + } + } + } + } + return value; +} + +const collectBodyString = (streamBody, context) => smithyClient.collectBody(streamBody, context).then((body) => (context?.utf8Encoder ?? utilUtf8.toUtf8)(body)); + +const parseJsonBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { + if (encoded.length) { + try { + return JSON.parse(encoded); + } + catch (e) { + if (e?.name === "SyntaxError") { + Object.defineProperty(e, "$responseBodyText", { + value: encoded, + }); + } + throw e; + } + } + return {}; +}); +const parseJsonErrorBody = async (errorBody, context) => { + const value = await parseJsonBody(errorBody, context); + value.message = value.message ?? value.Message; + return value; +}; +const loadRestJsonErrorCode = (output, data) => { + const findKey = (object, key) => Object.keys(object).find((k) => k.toLowerCase() === key.toLowerCase()); + const sanitizeErrorCode = (rawValue) => { + let cleanValue = rawValue; + if (typeof cleanValue === "number") { + cleanValue = cleanValue.toString(); + } + if (cleanValue.indexOf(",") >= 0) { + cleanValue = cleanValue.split(",")[0]; + } + if (cleanValue.indexOf(":") >= 0) { + cleanValue = cleanValue.split(":")[0]; + } + if (cleanValue.indexOf("#") >= 0) { + cleanValue = cleanValue.split("#")[1]; + } + return cleanValue; + }; + const headerKey = findKey(output.headers, "x-amzn-errortype"); + if (headerKey !== undefined) { + return sanitizeErrorCode(output.headers[headerKey]); + } + if (data && typeof data === "object") { + const codeKey = findKey(data, "code"); + if (codeKey && data[codeKey] !== undefined) { + return sanitizeErrorCode(data[codeKey]); + } + if (data["__type"] !== undefined) { + return sanitizeErrorCode(data["__type"]); + } + } +}; + +class JsonShapeDeserializer extends SerdeContextConfig { + settings; + constructor(settings) { + super(); + this.settings = settings; + } + async read(schema, data) { + return this._read(schema, typeof data === "string" ? JSON.parse(data, jsonReviver) : await parseJsonBody(data, this.serdeContext)); + } + readObject(schema, data) { + return this._read(schema, data); + } + _read(schema$1, value) { + const isObject = value !== null && typeof value === "object"; + const ns = schema.NormalizedSchema.of(schema$1); + if (ns.isListSchema() && Array.isArray(value)) { + const listMember = ns.getValueSchema(); + const out = []; + const sparse = !!ns.getMergedTraits().sparse; + for (const item of value) { + if (sparse || item != null) { + out.push(this._read(listMember, item)); + } + } + return out; + } + else if (ns.isMapSchema() && isObject) { + const mapMember = ns.getValueSchema(); + const out = {}; + const sparse = !!ns.getMergedTraits().sparse; + for (const [_k, _v] of Object.entries(value)) { + if (sparse || _v != null) { + out[_k] = this._read(mapMember, _v); + } + } + return out; + } + else if (ns.isStructSchema() && isObject) { + const out = {}; + for (const [memberName, memberSchema] of ns.structIterator()) { + const fromKey = this.settings.jsonName ? memberSchema.getMergedTraits().jsonName ?? memberName : memberName; + const deserializedValue = this._read(memberSchema, value[fromKey]); + if (deserializedValue != null) { + out[memberName] = deserializedValue; + } + } + return out; + } + if (ns.isBlobSchema() && typeof value === "string") { + return utilBase64.fromBase64(value); + } + const mediaType = ns.getMergedTraits().mediaType; + if (ns.isStringSchema() && typeof value === "string" && mediaType) { + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + return serde.LazyJsonString.from(value); + } + } + if (ns.isTimestampSchema() && value != null) { + const format = protocols.determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: + return serde.parseRfc3339DateTimeWithOffset(value); + case 6: + return serde.parseRfc7231DateTime(value); + case 7: + return serde.parseEpochTimestamp(value); + default: + console.warn("Missing timestamp format, parsing value with Date constructor:", value); + return new Date(value); + } + } + if (ns.isBigIntegerSchema() && (typeof value === "number" || typeof value === "string")) { + return BigInt(value); + } + if (ns.isBigDecimalSchema() && value != undefined) { + if (value instanceof serde.NumericValue) { + return value; + } + const untyped = value; + if (untyped.type === "bigDecimal" && "string" in untyped) { + return new serde.NumericValue(untyped.string, untyped.type); + } + return new serde.NumericValue(String(value), "bigDecimal"); + } + if (ns.isNumericSchema() && typeof value === "string") { + switch (value) { + case "Infinity": + return Infinity; + case "-Infinity": + return -Infinity; + case "NaN": + return NaN; + } + } + if (ns.isDocumentSchema()) { + if (isObject) { + const out = Array.isArray(value) ? [] : {}; + for (const [k, v] of Object.entries(value)) { + if (v instanceof serde.NumericValue) { + out[k] = v; + } + else { + out[k] = this._read(ns, v); + } + } + return out; + } + else { + return structuredClone(value); + } + } + return value; + } +} + +const NUMERIC_CONTROL_CHAR = String.fromCharCode(925); +class JsonReplacer { + values = new Map(); + counter = 0; + stage = 0; + createReplacer() { + if (this.stage === 1) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer already created."); + } + if (this.stage === 2) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); + } + this.stage = 1; + return (key, value) => { + if (value instanceof serde.NumericValue) { + const v = `${NUMERIC_CONTROL_CHAR + "nv" + this.counter++}_` + value.string; + this.values.set(`"${v}"`, value.string); + return v; + } + if (typeof value === "bigint") { + const s = value.toString(); + const v = `${NUMERIC_CONTROL_CHAR + "b" + this.counter++}_` + s; + this.values.set(`"${v}"`, s); + return v; + } + return value; + }; + } + replaceInJson(json) { + if (this.stage === 0) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer not created yet."); + } + if (this.stage === 2) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); + } + this.stage = 2; + if (this.counter === 0) { + return json; + } + for (const [key, value] of this.values) { + json = json.replace(key, value); + } + return json; + } +} + +class JsonShapeSerializer extends SerdeContextConfig { + settings; + buffer; + rootSchema; + constructor(settings) { + super(); + this.settings = settings; + } + write(schema$1, value) { + this.rootSchema = schema.NormalizedSchema.of(schema$1); + this.buffer = this._write(this.rootSchema, value); + } + writeDiscriminatedDocument(schema$1, value) { + this.write(schema$1, value); + if (typeof this.buffer === "object") { + this.buffer.__type = schema.NormalizedSchema.of(schema$1).getName(true); + } + } + flush() { + const { rootSchema } = this; + this.rootSchema = undefined; + if (rootSchema?.isStructSchema() || rootSchema?.isDocumentSchema()) { + const replacer = new JsonReplacer(); + return replacer.replaceInJson(JSON.stringify(this.buffer, replacer.createReplacer(), 0)); + } + return this.buffer; + } + _write(schema$1, value, container) { + const isObject = value !== null && typeof value === "object"; + const ns = schema.NormalizedSchema.of(schema$1); + if (ns.isListSchema() && Array.isArray(value)) { + const listMember = ns.getValueSchema(); + const out = []; + const sparse = !!ns.getMergedTraits().sparse; + for (const item of value) { + if (sparse || item != null) { + out.push(this._write(listMember, item)); + } + } + return out; + } + else if (ns.isMapSchema() && isObject) { + const mapMember = ns.getValueSchema(); + const out = {}; + const sparse = !!ns.getMergedTraits().sparse; + for (const [_k, _v] of Object.entries(value)) { + if (sparse || _v != null) { + out[_k] = this._write(mapMember, _v); + } + } + return out; + } + else if (ns.isStructSchema() && isObject) { + const out = {}; + for (const [memberName, memberSchema] of ns.structIterator()) { + const targetKey = this.settings.jsonName ? memberSchema.getMergedTraits().jsonName ?? memberName : memberName; + const serializableValue = this._write(memberSchema, value[memberName], ns); + if (serializableValue !== undefined) { + out[targetKey] = serializableValue; + } + } + return out; + } + if (value === null && container?.isStructSchema()) { + return void 0; + } + if ((ns.isBlobSchema() && (value instanceof Uint8Array || typeof value === "string")) || + (ns.isDocumentSchema() && value instanceof Uint8Array)) { + if (ns === this.rootSchema) { + return value; + } + return (this.serdeContext?.base64Encoder ?? utilBase64.toBase64)(value); + } + if ((ns.isTimestampSchema() || ns.isDocumentSchema()) && value instanceof Date) { + const format = protocols.determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: + return value.toISOString().replace(".000Z", "Z"); + case 6: + return serde.dateToUtcString(value); + case 7: + return value.getTime() / 1000; + default: + console.warn("Missing timestamp format, using epoch seconds", value); + return value.getTime() / 1000; + } + } + if (ns.isNumericSchema() && typeof value === "number") { + if (Math.abs(value) === Infinity || isNaN(value)) { + return String(value); + } + } + if (ns.isStringSchema()) { + if (typeof value === "undefined" && ns.isIdempotencyToken()) { + return serde.generateIdempotencyToken(); + } + const mediaType = ns.getMergedTraits().mediaType; + if (value != null && mediaType) { + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + return serde.LazyJsonString.from(value); + } + } + } + if (ns.isDocumentSchema()) { + if (isObject) { + const out = Array.isArray(value) ? [] : {}; + for (const [k, v] of Object.entries(value)) { + if (v instanceof serde.NumericValue) { + out[k] = v; + } + else { + out[k] = this._write(ns, v); + } + } + return out; + } + else { + return structuredClone(value); + } + } + return value; + } +} + +class JsonCodec extends SerdeContextConfig { + settings; + constructor(settings) { + super(); + this.settings = settings; + } + createSerializer() { + const serializer = new JsonShapeSerializer(this.settings); + serializer.setSerdeContext(this.serdeContext); + return serializer; + } + createDeserializer() { + const deserializer = new JsonShapeDeserializer(this.settings); + deserializer.setSerdeContext(this.serdeContext); + return deserializer; + } +} + +class AwsJsonRpcProtocol extends protocols.RpcProtocol { + serializer; + deserializer; + serviceTarget; + codec; + mixin; + awsQueryCompatible; + constructor({ defaultNamespace, serviceTarget, awsQueryCompatible, }) { + super({ + defaultNamespace, + }); + this.serviceTarget = serviceTarget; + this.codec = new JsonCodec({ + timestampFormat: { + useTrait: true, + default: 7, + }, + jsonName: false, + }); + this.serializer = this.codec.createSerializer(); + this.deserializer = this.codec.createDeserializer(); + this.awsQueryCompatible = !!awsQueryCompatible; + this.mixin = new ProtocolLib(this.awsQueryCompatible); + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + if (!request.path.endsWith("/")) { + request.path += "/"; + } + Object.assign(request.headers, { + "content-type": `application/x-amz-json-${this.getJsonRpcVersion()}`, + "x-amz-target": `${this.serviceTarget}.${operationSchema.name}`, + }); + if (this.awsQueryCompatible) { + request.headers["x-amzn-query-mode"] = "true"; + } + if (schema.deref(operationSchema.input) === "unit" || !request.body) { + request.body = "{}"; + } + return request; + } + getPayloadCodec() { + return this.codec; + } + async handleError(operationSchema, context, response, dataObject, metadata) { + if (this.awsQueryCompatible) { + this.mixin.setQueryCompatError(dataObject, response); + } + const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown"; + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata); + const ns = schema.NormalizedSchema.of(errorSchema); + const message = dataObject.message ?? dataObject.Message ?? "Unknown"; + const ErrorCtor = schema.TypeRegistry.for(errorSchema[1]).getErrorCtor(errorSchema) ?? Error; + const exception = new ErrorCtor(message); + const output = {}; + for (const [name, member] of ns.structIterator()) { + const target = member.getMergedTraits().jsonName ?? name; + output[name] = this.codec.createDeserializer().readObject(member, dataObject[target]); + } + if (this.awsQueryCompatible) { + this.mixin.queryCompatOutput(dataObject, output); + } + throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message, + }, output), dataObject); + } +} + +class AwsJson1_0Protocol extends AwsJsonRpcProtocol { + constructor({ defaultNamespace, serviceTarget, awsQueryCompatible, }) { + super({ + defaultNamespace, + serviceTarget, + awsQueryCompatible, + }); + } + getShapeId() { + return "aws.protocols#awsJson1_0"; + } + getJsonRpcVersion() { + return "1.0"; + } + getDefaultContentType() { + return "application/x-amz-json-1.0"; + } +} + +class AwsJson1_1Protocol extends AwsJsonRpcProtocol { + constructor({ defaultNamespace, serviceTarget, awsQueryCompatible, }) { + super({ + defaultNamespace, + serviceTarget, + awsQueryCompatible, + }); + } + getShapeId() { + return "aws.protocols#awsJson1_1"; + } + getJsonRpcVersion() { + return "1.1"; + } + getDefaultContentType() { + return "application/x-amz-json-1.1"; + } +} + +class AwsRestJsonProtocol extends protocols.HttpBindingProtocol { + serializer; + deserializer; + codec; + mixin = new ProtocolLib(); + constructor({ defaultNamespace }) { + super({ + defaultNamespace, + }); + const settings = { + timestampFormat: { + useTrait: true, + default: 7, + }, + httpBindings: true, + jsonName: true, + }; + this.codec = new JsonCodec(settings); + this.serializer = new protocols.HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings); + this.deserializer = new protocols.HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings); + } + getShapeId() { + return "aws.protocols#restJson1"; + } + getPayloadCodec() { + return this.codec; + } + setSerdeContext(serdeContext) { + this.codec.setSerdeContext(serdeContext); + super.setSerdeContext(serdeContext); + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + const inputSchema = schema.NormalizedSchema.of(operationSchema.input); + if (!request.headers["content-type"]) { + const contentType = this.mixin.resolveRestContentType(this.getDefaultContentType(), inputSchema); + if (contentType) { + request.headers["content-type"] = contentType; + } + } + if (request.body == null && request.headers["content-type"] === this.getDefaultContentType()) { + request.body = "{}"; + } + return request; + } + async deserializeResponse(operationSchema, context, response) { + const output = await super.deserializeResponse(operationSchema, context, response); + const outputSchema = schema.NormalizedSchema.of(operationSchema.output); + for (const [name, member] of outputSchema.structIterator()) { + if (member.getMemberTraits().httpPayload && !(name in output)) { + output[name] = null; + } + } + return output; + } + async handleError(operationSchema, context, response, dataObject, metadata) { + const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown"; + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata); + const ns = schema.NormalizedSchema.of(errorSchema); + const message = dataObject.message ?? dataObject.Message ?? "Unknown"; + const ErrorCtor = schema.TypeRegistry.for(errorSchema[1]).getErrorCtor(errorSchema) ?? Error; + const exception = new ErrorCtor(message); + await this.deserializeHttpMessage(errorSchema, context, response, dataObject); + const output = {}; + for (const [name, member] of ns.structIterator()) { + const target = member.getMergedTraits().jsonName ?? name; + output[name] = this.codec.createDeserializer().readObject(member, dataObject[target]); + } + throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message, + }, output), dataObject); + } + getDefaultContentType() { + return "application/json"; + } +} + +const awsExpectUnion = (value) => { + if (value == null) { + return undefined; + } + if (typeof value === "object" && "__type" in value) { + delete value.__type; + } + return smithyClient.expectUnion(value); +}; + +class XmlShapeDeserializer extends SerdeContextConfig { + settings; + stringDeserializer; + constructor(settings) { + super(); + this.settings = settings; + this.stringDeserializer = new protocols.FromStringShapeDeserializer(settings); + } + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + this.stringDeserializer.setSerdeContext(serdeContext); + } + read(schema$1, bytes, key) { + const ns = schema.NormalizedSchema.of(schema$1); + const memberSchemas = ns.getMemberSchemas(); + const isEventPayload = ns.isStructSchema() && + ns.isMemberSchema() && + !!Object.values(memberSchemas).find((memberNs) => { + return !!memberNs.getMemberTraits().eventPayload; + }); + if (isEventPayload) { + const output = {}; + const memberName = Object.keys(memberSchemas)[0]; + const eventMemberSchema = memberSchemas[memberName]; + if (eventMemberSchema.isBlobSchema()) { + output[memberName] = bytes; + } + else { + output[memberName] = this.read(memberSchemas[memberName], bytes); + } + return output; + } + const xmlString = (this.serdeContext?.utf8Encoder ?? utilUtf8.toUtf8)(bytes); + const parsedObject = this.parseXml(xmlString); + return this.readSchema(schema$1, key ? parsedObject[key] : parsedObject); + } + readSchema(_schema, value) { + const ns = schema.NormalizedSchema.of(_schema); + if (ns.isUnitSchema()) { + return; + } + const traits = ns.getMergedTraits(); + if (ns.isListSchema() && !Array.isArray(value)) { + return this.readSchema(ns, [value]); + } + if (value == null) { + return value; + } + if (typeof value === "object") { + const sparse = !!traits.sparse; + const flat = !!traits.xmlFlattened; + if (ns.isListSchema()) { + const listValue = ns.getValueSchema(); + const buffer = []; + const sourceKey = listValue.getMergedTraits().xmlName ?? "member"; + const source = flat ? value : (value[0] ?? value)[sourceKey]; + const sourceArray = Array.isArray(source) ? source : [source]; + for (const v of sourceArray) { + if (v != null || sparse) { + buffer.push(this.readSchema(listValue, v)); + } + } + return buffer; + } + const buffer = {}; + if (ns.isMapSchema()) { + const keyNs = ns.getKeySchema(); + const memberNs = ns.getValueSchema(); + let entries; + if (flat) { + entries = Array.isArray(value) ? value : [value]; + } + else { + entries = Array.isArray(value.entry) ? value.entry : [value.entry]; + } + const keyProperty = keyNs.getMergedTraits().xmlName ?? "key"; + const valueProperty = memberNs.getMergedTraits().xmlName ?? "value"; + for (const entry of entries) { + const key = entry[keyProperty]; + const value = entry[valueProperty]; + if (value != null || sparse) { + buffer[key] = this.readSchema(memberNs, value); + } + } + return buffer; + } + if (ns.isStructSchema()) { + for (const [memberName, memberSchema] of ns.structIterator()) { + const memberTraits = memberSchema.getMergedTraits(); + const xmlObjectKey = !memberTraits.httpPayload + ? memberSchema.getMemberTraits().xmlName ?? memberName + : memberTraits.xmlName ?? memberSchema.getName(); + if (value[xmlObjectKey] != null) { + buffer[memberName] = this.readSchema(memberSchema, value[xmlObjectKey]); + } + } + return buffer; + } + if (ns.isDocumentSchema()) { + return value; + } + throw new Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${ns.getName(true)}`); + } + if (ns.isListSchema()) { + return []; + } + if (ns.isMapSchema() || ns.isStructSchema()) { + return {}; + } + return this.stringDeserializer.read(ns, value); + } + parseXml(xml) { + if (xml.length) { + let parsedObj; + try { + parsedObj = xmlBuilder.parseXML(xml); + } + catch (e) { + if (e && typeof e === "object") { + Object.defineProperty(e, "$responseBodyText", { + value: xml, + }); + } + throw e; + } + const textNodeName = "#text"; + const key = Object.keys(parsedObj)[0]; + const parsedObjToReturn = parsedObj[key]; + if (parsedObjToReturn[textNodeName]) { + parsedObjToReturn[key] = parsedObjToReturn[textNodeName]; + delete parsedObjToReturn[textNodeName]; + } + return smithyClient.getValueFromTextNode(parsedObjToReturn); + } + return {}; + } +} + +class QueryShapeSerializer extends SerdeContextConfig { + settings; + buffer; + constructor(settings) { + super(); + this.settings = settings; + } + write(schema$1, value, prefix = "") { + if (this.buffer === undefined) { + this.buffer = ""; + } + const ns = schema.NormalizedSchema.of(schema$1); + if (prefix && !prefix.endsWith(".")) { + prefix += "."; + } + if (ns.isBlobSchema()) { + if (typeof value === "string" || value instanceof Uint8Array) { + this.writeKey(prefix); + this.writeValue((this.serdeContext?.base64Encoder ?? utilBase64.toBase64)(value)); + } + } + else if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isStringSchema()) { + if (value != null) { + this.writeKey(prefix); + this.writeValue(String(value)); + } + else if (ns.isIdempotencyToken()) { + this.writeKey(prefix); + this.writeValue(serde.generateIdempotencyToken()); + } + } + else if (ns.isBigIntegerSchema()) { + if (value != null) { + this.writeKey(prefix); + this.writeValue(String(value)); + } + } + else if (ns.isBigDecimalSchema()) { + if (value != null) { + this.writeKey(prefix); + this.writeValue(value instanceof serde.NumericValue ? value.string : String(value)); + } + } + else if (ns.isTimestampSchema()) { + if (value instanceof Date) { + this.writeKey(prefix); + const format = protocols.determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: + this.writeValue(value.toISOString().replace(".000Z", "Z")); + break; + case 6: + this.writeValue(smithyClient.dateToUtcString(value)); + break; + case 7: + this.writeValue(String(value.getTime() / 1000)); + break; + } + } + } + else if (ns.isDocumentSchema()) { + throw new Error(`@aws-sdk/core/protocols - QuerySerializer unsupported document type ${ns.getName(true)}`); + } + else if (ns.isListSchema()) { + if (Array.isArray(value)) { + if (value.length === 0) { + if (this.settings.serializeEmptyLists) { + this.writeKey(prefix); + this.writeValue(""); + } + } + else { + const member = ns.getValueSchema(); + const flat = this.settings.flattenLists || ns.getMergedTraits().xmlFlattened; + let i = 1; + for (const item of value) { + if (item == null) { + continue; + } + const suffix = this.getKey("member", member.getMergedTraits().xmlName); + const key = flat ? `${prefix}${i}` : `${prefix}${suffix}.${i}`; + this.write(member, item, key); + ++i; + } + } + } + } + else if (ns.isMapSchema()) { + if (value && typeof value === "object") { + const keySchema = ns.getKeySchema(); + const memberSchema = ns.getValueSchema(); + const flat = ns.getMergedTraits().xmlFlattened; + let i = 1; + for (const [k, v] of Object.entries(value)) { + if (v == null) { + continue; + } + const keySuffix = this.getKey("key", keySchema.getMergedTraits().xmlName); + const key = flat ? `${prefix}${i}.${keySuffix}` : `${prefix}entry.${i}.${keySuffix}`; + const valueSuffix = this.getKey("value", memberSchema.getMergedTraits().xmlName); + const valueKey = flat ? `${prefix}${i}.${valueSuffix}` : `${prefix}entry.${i}.${valueSuffix}`; + this.write(keySchema, k, key); + this.write(memberSchema, v, valueKey); + ++i; + } + } + } + else if (ns.isStructSchema()) { + if (value && typeof value === "object") { + for (const [memberName, member] of ns.structIterator()) { + if (value[memberName] == null && !member.isIdempotencyToken()) { + continue; + } + const suffix = this.getKey(memberName, member.getMergedTraits().xmlName); + const key = `${prefix}${suffix}`; + this.write(member, value[memberName], key); + } + } + } + else if (ns.isUnitSchema()) ; + else { + throw new Error(`@aws-sdk/core/protocols - QuerySerializer unrecognized schema type ${ns.getName(true)}`); + } + } + flush() { + if (this.buffer === undefined) { + throw new Error("@aws-sdk/core/protocols - QuerySerializer cannot flush with nothing written to buffer."); + } + const str = this.buffer; + delete this.buffer; + return str; + } + getKey(memberName, xmlName) { + const key = xmlName ?? memberName; + if (this.settings.capitalizeKeys) { + return key[0].toUpperCase() + key.slice(1); + } + return key; + } + writeKey(key) { + if (key.endsWith(".")) { + key = key.slice(0, key.length - 1); + } + this.buffer += `&${protocols.extendedEncodeURIComponent(key)}=`; + } + writeValue(value) { + this.buffer += protocols.extendedEncodeURIComponent(value); + } +} + +class AwsQueryProtocol extends protocols.RpcProtocol { + options; + serializer; + deserializer; + mixin = new ProtocolLib(); + constructor(options) { + super({ + defaultNamespace: options.defaultNamespace, + }); + this.options = options; + const settings = { + timestampFormat: { + useTrait: true, + default: 5, + }, + httpBindings: false, + xmlNamespace: options.xmlNamespace, + serviceNamespace: options.defaultNamespace, + serializeEmptyLists: true, + }; + this.serializer = new QueryShapeSerializer(settings); + this.deserializer = new XmlShapeDeserializer(settings); + } + getShapeId() { + return "aws.protocols#awsQuery"; + } + setSerdeContext(serdeContext) { + this.serializer.setSerdeContext(serdeContext); + this.deserializer.setSerdeContext(serdeContext); + } + getPayloadCodec() { + throw new Error("AWSQuery protocol has no payload codec."); + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + if (!request.path.endsWith("/")) { + request.path += "/"; + } + Object.assign(request.headers, { + "content-type": `application/x-www-form-urlencoded`, + }); + if (schema.deref(operationSchema.input) === "unit" || !request.body) { + request.body = ""; + } + const action = operationSchema.name.split("#")[1] ?? operationSchema.name; + request.body = `Action=${action}&Version=${this.options.version}` + request.body; + if (request.body.endsWith("&")) { + request.body = request.body.slice(-1); + } + return request; + } + async deserializeResponse(operationSchema, context, response) { + const deserializer = this.deserializer; + const ns = schema.NormalizedSchema.of(operationSchema.output); + const dataObject = {}; + if (response.statusCode >= 300) { + const bytes = await protocols.collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(15, bytes)); + } + await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); + } + for (const header in response.headers) { + const value = response.headers[header]; + delete response.headers[header]; + response.headers[header.toLowerCase()] = value; + } + const shortName = operationSchema.name.split("#")[1] ?? operationSchema.name; + const awsQueryResultKey = ns.isStructSchema() && this.useNestedResult() ? shortName + "Result" : undefined; + const bytes = await protocols.collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(ns, bytes, awsQueryResultKey)); + } + const output = { + $metadata: this.deserializeMetadata(response), + ...dataObject, + }; + return output; + } + useNestedResult() { + return true; + } + async handleError(operationSchema, context, response, dataObject, metadata) { + const errorIdentifier = this.loadQueryErrorCode(response, dataObject) ?? "Unknown"; + const errorData = this.loadQueryError(dataObject); + const message = this.loadQueryErrorMessage(dataObject); + errorData.message = message; + errorData.Error = { + Type: errorData.Type, + Code: errorData.Code, + Message: message, + }; + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, errorData, metadata, (registry, errorName) => { + try { + return registry.getSchema(errorName); + } + catch (e) { + return registry.find((schema$1) => schema.NormalizedSchema.of(schema$1).getMergedTraits().awsQueryError?.[0] === errorName); + } + }); + const ns = schema.NormalizedSchema.of(errorSchema); + const ErrorCtor = schema.TypeRegistry.for(errorSchema[1]).getErrorCtor(errorSchema) ?? Error; + const exception = new ErrorCtor(message); + const output = { + Error: errorData.Error, + }; + for (const [name, member] of ns.structIterator()) { + const target = member.getMergedTraits().xmlName ?? name; + const value = errorData[target] ?? dataObject[target]; + output[name] = this.deserializer.readSchema(member, value); + } + throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message, + }, output), dataObject); + } + loadQueryErrorCode(output, data) { + const code = (data.Errors?.[0]?.Error ?? data.Errors?.Error ?? data.Error)?.Code; + if (code !== undefined) { + return code; + } + if (output.statusCode == 404) { + return "NotFound"; + } + } + loadQueryError(data) { + return data.Errors?.[0]?.Error ?? data.Errors?.Error ?? data.Error; + } + loadQueryErrorMessage(data) { + const errorData = this.loadQueryError(data); + return errorData?.message ?? errorData?.Message ?? data.message ?? data.Message ?? "Unknown"; + } + getDefaultContentType() { + return "application/x-www-form-urlencoded"; + } +} + +class AwsEc2QueryProtocol extends AwsQueryProtocol { + options; + constructor(options) { + super(options); + this.options = options; + const ec2Settings = { + capitalizeKeys: true, + flattenLists: true, + serializeEmptyLists: false, + }; + Object.assign(this.serializer.settings, ec2Settings); + } + useNestedResult() { + return false; + } +} + +const parseXmlBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { + if (encoded.length) { + let parsedObj; + try { + parsedObj = xmlBuilder.parseXML(encoded); + } + catch (e) { + if (e && typeof e === "object") { + Object.defineProperty(e, "$responseBodyText", { + value: encoded, + }); + } + throw e; + } + const textNodeName = "#text"; + const key = Object.keys(parsedObj)[0]; + const parsedObjToReturn = parsedObj[key]; + if (parsedObjToReturn[textNodeName]) { + parsedObjToReturn[key] = parsedObjToReturn[textNodeName]; + delete parsedObjToReturn[textNodeName]; + } + return smithyClient.getValueFromTextNode(parsedObjToReturn); + } + return {}; +}); +const parseXmlErrorBody = async (errorBody, context) => { + const value = await parseXmlBody(errorBody, context); + if (value.Error) { + value.Error.message = value.Error.message ?? value.Error.Message; + } + return value; +}; +const loadRestXmlErrorCode = (output, data) => { + if (data?.Error?.Code !== undefined) { + return data.Error.Code; + } + if (data?.Code !== undefined) { + return data.Code; + } + if (output.statusCode == 404) { + return "NotFound"; + } +}; + +class XmlShapeSerializer extends SerdeContextConfig { + settings; + stringBuffer; + byteBuffer; + buffer; + constructor(settings) { + super(); + this.settings = settings; + } + write(schema$1, value) { + const ns = schema.NormalizedSchema.of(schema$1); + if (ns.isStringSchema() && typeof value === "string") { + this.stringBuffer = value; + } + else if (ns.isBlobSchema()) { + this.byteBuffer = + "byteLength" in value + ? value + : (this.serdeContext?.base64Decoder ?? utilBase64.fromBase64)(value); + } + else { + this.buffer = this.writeStruct(ns, value, undefined); + const traits = ns.getMergedTraits(); + if (traits.httpPayload && !traits.xmlName) { + this.buffer.withName(ns.getName()); + } + } + } + flush() { + if (this.byteBuffer !== undefined) { + const bytes = this.byteBuffer; + delete this.byteBuffer; + return bytes; + } + if (this.stringBuffer !== undefined) { + const str = this.stringBuffer; + delete this.stringBuffer; + return str; + } + const buffer = this.buffer; + if (this.settings.xmlNamespace) { + if (!buffer?.attributes?.["xmlns"]) { + buffer.addAttribute("xmlns", this.settings.xmlNamespace); + } + } + delete this.buffer; + return buffer.toString(); + } + writeStruct(ns, value, parentXmlns) { + const traits = ns.getMergedTraits(); + const name = ns.isMemberSchema() && !traits.httpPayload + ? ns.getMemberTraits().xmlName ?? ns.getMemberName() + : traits.xmlName ?? ns.getName(); + if (!name || !ns.isStructSchema()) { + throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${ns.getName(true)}.`); + } + const structXmlNode = xmlBuilder.XmlNode.of(name); + const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns); + for (const [memberName, memberSchema] of ns.structIterator()) { + const val = value[memberName]; + if (val != null || memberSchema.isIdempotencyToken()) { + if (memberSchema.getMergedTraits().xmlAttribute) { + structXmlNode.addAttribute(memberSchema.getMergedTraits().xmlName ?? memberName, this.writeSimple(memberSchema, val)); + continue; + } + if (memberSchema.isListSchema()) { + this.writeList(memberSchema, val, structXmlNode, xmlns); + } + else if (memberSchema.isMapSchema()) { + this.writeMap(memberSchema, val, structXmlNode, xmlns); + } + else if (memberSchema.isStructSchema()) { + structXmlNode.addChildNode(this.writeStruct(memberSchema, val, xmlns)); + } + else { + const memberNode = xmlBuilder.XmlNode.of(memberSchema.getMergedTraits().xmlName ?? memberSchema.getMemberName()); + this.writeSimpleInto(memberSchema, val, memberNode, xmlns); + structXmlNode.addChildNode(memberNode); + } + } + } + if (xmlns) { + structXmlNode.addAttribute(xmlnsAttr, xmlns); + } + return structXmlNode; + } + writeList(listMember, array, container, parentXmlns) { + if (!listMember.isMemberSchema()) { + throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member list: ${listMember.getName(true)}`); + } + const listTraits = listMember.getMergedTraits(); + const listValueSchema = listMember.getValueSchema(); + const listValueTraits = listValueSchema.getMergedTraits(); + const sparse = !!listValueTraits.sparse; + const flat = !!listTraits.xmlFlattened; + const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(listMember, parentXmlns); + const writeItem = (container, value) => { + if (listValueSchema.isListSchema()) { + this.writeList(listValueSchema, Array.isArray(value) ? value : [value], container, xmlns); + } + else if (listValueSchema.isMapSchema()) { + this.writeMap(listValueSchema, value, container, xmlns); + } + else if (listValueSchema.isStructSchema()) { + const struct = this.writeStruct(listValueSchema, value, xmlns); + container.addChildNode(struct.withName(flat ? listTraits.xmlName ?? listMember.getMemberName() : listValueTraits.xmlName ?? "member")); + } + else { + const listItemNode = xmlBuilder.XmlNode.of(flat ? listTraits.xmlName ?? listMember.getMemberName() : listValueTraits.xmlName ?? "member"); + this.writeSimpleInto(listValueSchema, value, listItemNode, xmlns); + container.addChildNode(listItemNode); + } + }; + if (flat) { + for (const value of array) { + if (sparse || value != null) { + writeItem(container, value); + } + } + } + else { + const listNode = xmlBuilder.XmlNode.of(listTraits.xmlName ?? listMember.getMemberName()); + if (xmlns) { + listNode.addAttribute(xmlnsAttr, xmlns); + } + for (const value of array) { + if (sparse || value != null) { + writeItem(listNode, value); + } + } + container.addChildNode(listNode); + } + } + writeMap(mapMember, map, container, parentXmlns, containerIsMap = false) { + if (!mapMember.isMemberSchema()) { + throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member map: ${mapMember.getName(true)}`); + } + const mapTraits = mapMember.getMergedTraits(); + const mapKeySchema = mapMember.getKeySchema(); + const mapKeyTraits = mapKeySchema.getMergedTraits(); + const keyTag = mapKeyTraits.xmlName ?? "key"; + const mapValueSchema = mapMember.getValueSchema(); + const mapValueTraits = mapValueSchema.getMergedTraits(); + const valueTag = mapValueTraits.xmlName ?? "value"; + const sparse = !!mapValueTraits.sparse; + const flat = !!mapTraits.xmlFlattened; + const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(mapMember, parentXmlns); + const addKeyValue = (entry, key, val) => { + const keyNode = xmlBuilder.XmlNode.of(keyTag, key); + const [keyXmlnsAttr, keyXmlns] = this.getXmlnsAttribute(mapKeySchema, xmlns); + if (keyXmlns) { + keyNode.addAttribute(keyXmlnsAttr, keyXmlns); + } + entry.addChildNode(keyNode); + let valueNode = xmlBuilder.XmlNode.of(valueTag); + if (mapValueSchema.isListSchema()) { + this.writeList(mapValueSchema, val, valueNode, xmlns); + } + else if (mapValueSchema.isMapSchema()) { + this.writeMap(mapValueSchema, val, valueNode, xmlns, true); + } + else if (mapValueSchema.isStructSchema()) { + valueNode = this.writeStruct(mapValueSchema, val, xmlns); + } + else { + this.writeSimpleInto(mapValueSchema, val, valueNode, xmlns); + } + entry.addChildNode(valueNode); + }; + if (flat) { + for (const [key, val] of Object.entries(map)) { + if (sparse || val != null) { + const entry = xmlBuilder.XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName()); + addKeyValue(entry, key, val); + container.addChildNode(entry); + } + } + } + else { + let mapNode; + if (!containerIsMap) { + mapNode = xmlBuilder.XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName()); + if (xmlns) { + mapNode.addAttribute(xmlnsAttr, xmlns); + } + container.addChildNode(mapNode); + } + for (const [key, val] of Object.entries(map)) { + if (sparse || val != null) { + const entry = xmlBuilder.XmlNode.of("entry"); + addKeyValue(entry, key, val); + (containerIsMap ? container : mapNode).addChildNode(entry); + } + } + } + } + writeSimple(_schema, value) { + if (null === value) { + throw new Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value."); + } + const ns = schema.NormalizedSchema.of(_schema); + let nodeContents = null; + if (value && typeof value === "object") { + if (ns.isBlobSchema()) { + nodeContents = (this.serdeContext?.base64Encoder ?? utilBase64.toBase64)(value); + } + else if (ns.isTimestampSchema() && value instanceof Date) { + const format = protocols.determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: + nodeContents = value.toISOString().replace(".000Z", "Z"); + break; + case 6: + nodeContents = smithyClient.dateToUtcString(value); + break; + case 7: + nodeContents = String(value.getTime() / 1000); + break; + default: + console.warn("Missing timestamp format, using http date", value); + nodeContents = smithyClient.dateToUtcString(value); + break; + } + } + else if (ns.isBigDecimalSchema() && value) { + if (value instanceof serde.NumericValue) { + return value.string; + } + return String(value); + } + else if (ns.isMapSchema() || ns.isListSchema()) { + throw new Error("@aws-sdk/core/protocols - xml serializer, cannot call _write() on List/Map schema, call writeList or writeMap() instead."); + } + else { + throw new Error(`@aws-sdk/core/protocols - xml serializer, unhandled schema type for object value and schema: ${ns.getName(true)}`); + } + } + if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isBigIntegerSchema() || ns.isBigDecimalSchema()) { + nodeContents = String(value); + } + if (ns.isStringSchema()) { + if (value === undefined && ns.isIdempotencyToken()) { + nodeContents = serde.generateIdempotencyToken(); + } + else { + nodeContents = String(value); + } + } + if (nodeContents === null) { + throw new Error(`Unhandled schema-value pair ${ns.getName(true)}=${value}`); + } + return nodeContents; + } + writeSimpleInto(_schema, value, into, parentXmlns) { + const nodeContents = this.writeSimple(_schema, value); + const ns = schema.NormalizedSchema.of(_schema); + const content = new xmlBuilder.XmlText(nodeContents); + const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns); + if (xmlns) { + into.addAttribute(xmlnsAttr, xmlns); + } + into.addChildNode(content); + } + getXmlnsAttribute(ns, parentXmlns) { + const traits = ns.getMergedTraits(); + const [prefix, xmlns] = traits.xmlNamespace ?? []; + if (xmlns && xmlns !== parentXmlns) { + return [prefix ? `xmlns:${prefix}` : "xmlns", xmlns]; + } + return [void 0, void 0]; + } +} + +class XmlCodec extends SerdeContextConfig { + settings; + constructor(settings) { + super(); + this.settings = settings; + } + createSerializer() { + const serializer = new XmlShapeSerializer(this.settings); + serializer.setSerdeContext(this.serdeContext); + return serializer; + } + createDeserializer() { + const deserializer = new XmlShapeDeserializer(this.settings); + deserializer.setSerdeContext(this.serdeContext); + return deserializer; + } +} + +class AwsRestXmlProtocol extends protocols.HttpBindingProtocol { + codec; + serializer; + deserializer; + mixin = new ProtocolLib(); + constructor(options) { + super(options); + const settings = { + timestampFormat: { + useTrait: true, + default: 5, + }, + httpBindings: true, + xmlNamespace: options.xmlNamespace, + serviceNamespace: options.defaultNamespace, + }; + this.codec = new XmlCodec(settings); + this.serializer = new protocols.HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings); + this.deserializer = new protocols.HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings); + } + getPayloadCodec() { + return this.codec; + } + getShapeId() { + return "aws.protocols#restXml"; + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + const inputSchema = schema.NormalizedSchema.of(operationSchema.input); + if (!request.headers["content-type"]) { + const contentType = this.mixin.resolveRestContentType(this.getDefaultContentType(), inputSchema); + if (contentType) { + request.headers["content-type"] = contentType; + } + } + if (request.headers["content-type"] === this.getDefaultContentType()) { + if (typeof request.body === "string") { + request.body = '' + request.body; + } + } + return request; + } + async deserializeResponse(operationSchema, context, response) { + return super.deserializeResponse(operationSchema, context, response); + } + async handleError(operationSchema, context, response, dataObject, metadata) { + const errorIdentifier = loadRestXmlErrorCode(response, dataObject) ?? "Unknown"; + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata); + const ns = schema.NormalizedSchema.of(errorSchema); + const message = dataObject.Error?.message ?? dataObject.Error?.Message ?? dataObject.message ?? dataObject.Message ?? "Unknown"; + const ErrorCtor = schema.TypeRegistry.for(errorSchema[1]).getErrorCtor(errorSchema) ?? Error; + const exception = new ErrorCtor(message); + await this.deserializeHttpMessage(errorSchema, context, response, dataObject); + const output = {}; + for (const [name, member] of ns.structIterator()) { + const target = member.getMergedTraits().xmlName ?? name; + const value = dataObject.Error?.[target] ?? dataObject[target]; + output[name] = this.codec.createDeserializer().readSchema(member, value); + } + throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message, + }, output), dataObject); + } + getDefaultContentType() { + return "application/xml"; + } +} + +exports.AWSSDKSigV4Signer = AWSSDKSigV4Signer; +exports.AwsEc2QueryProtocol = AwsEc2QueryProtocol; +exports.AwsJson1_0Protocol = AwsJson1_0Protocol; +exports.AwsJson1_1Protocol = AwsJson1_1Protocol; +exports.AwsJsonRpcProtocol = AwsJsonRpcProtocol; +exports.AwsQueryProtocol = AwsQueryProtocol; +exports.AwsRestJsonProtocol = AwsRestJsonProtocol; +exports.AwsRestXmlProtocol = AwsRestXmlProtocol; +exports.AwsSdkSigV4ASigner = AwsSdkSigV4ASigner; +exports.AwsSdkSigV4Signer = AwsSdkSigV4Signer; +exports.AwsSmithyRpcV2CborProtocol = AwsSmithyRpcV2CborProtocol; +exports.JsonCodec = JsonCodec; +exports.JsonShapeDeserializer = JsonShapeDeserializer; +exports.JsonShapeSerializer = JsonShapeSerializer; +exports.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = NODE_AUTH_SCHEME_PREFERENCE_OPTIONS; +exports.NODE_SIGV4A_CONFIG_OPTIONS = NODE_SIGV4A_CONFIG_OPTIONS; +exports.XmlCodec = XmlCodec; +exports.XmlShapeDeserializer = XmlShapeDeserializer; +exports.XmlShapeSerializer = XmlShapeSerializer; +exports._toBool = _toBool; +exports._toNum = _toNum; +exports._toStr = _toStr; +exports.awsExpectUnion = awsExpectUnion; +exports.emitWarningIfUnsupportedVersion = emitWarningIfUnsupportedVersion; +exports.getBearerTokenEnvKey = getBearerTokenEnvKey; +exports.loadRestJsonErrorCode = loadRestJsonErrorCode; +exports.loadRestXmlErrorCode = loadRestXmlErrorCode; +exports.parseJsonBody = parseJsonBody; +exports.parseJsonErrorBody = parseJsonErrorBody; +exports.parseXmlBody = parseXmlBody; +exports.parseXmlErrorBody = parseXmlErrorBody; +exports.resolveAWSSDKSigV4Config = resolveAWSSDKSigV4Config; +exports.resolveAwsSdkSigV4AConfig = resolveAwsSdkSigV4AConfig; +exports.resolveAwsSdkSigV4Config = resolveAwsSdkSigV4Config; +exports.setCredentialFeature = setCredentialFeature; +exports.setFeature = setFeature; +exports.setTokenFeature = setTokenFeature; +exports.state = state; +exports.validateSigningProperties = validateSigningProperties; diff --git a/claude-code-source/node_modules/@aws-sdk/core/dist-cjs/submodules/client/index.js b/claude-code-source/node_modules/@aws-sdk/core/dist-cjs/submodules/client/index.js new file mode 100644 index 00000000..5c8510e6 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/core/dist-cjs/submodules/client/index.js @@ -0,0 +1,51 @@ +'use strict'; + +const state = { + warningEmitted: false, +}; +const emitWarningIfUnsupportedVersion = (version) => { + if (version && !state.warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 18) { + state.warningEmitted = true; + process.emitWarning(`NodeDeprecationWarning: The AWS SDK for JavaScript (v3) will +no longer support Node.js 16.x on January 6, 2025. + +To continue receiving updates to AWS services, bug fixes, and security +updates please upgrade to a supported Node.js LTS version. + +More information can be found at: https://a.co/74kJMmI`); + } +}; + +function setCredentialFeature(credentials, feature, value) { + if (!credentials.$source) { + credentials.$source = {}; + } + credentials.$source[feature] = value; + return credentials; +} + +function setFeature(context, feature, value) { + if (!context.__aws_sdk_context) { + context.__aws_sdk_context = { + features: {}, + }; + } + else if (!context.__aws_sdk_context.features) { + context.__aws_sdk_context.features = {}; + } + context.__aws_sdk_context.features[feature] = value; +} + +function setTokenFeature(token, feature, value) { + if (!token.$source) { + token.$source = {}; + } + token.$source[feature] = value; + return token; +} + +exports.emitWarningIfUnsupportedVersion = emitWarningIfUnsupportedVersion; +exports.setCredentialFeature = setCredentialFeature; +exports.setFeature = setFeature; +exports.setTokenFeature = setTokenFeature; +exports.state = state; diff --git a/claude-code-source/node_modules/@aws-sdk/core/dist-cjs/submodules/httpAuthSchemes/index.js b/claude-code-source/node_modules/@aws-sdk/core/dist-cjs/submodules/httpAuthSchemes/index.js new file mode 100644 index 00000000..229f37b0 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/core/dist-cjs/submodules/httpAuthSchemes/index.js @@ -0,0 +1,299 @@ +'use strict'; + +var protocolHttp = require('@smithy/protocol-http'); +var core = require('@smithy/core'); +var propertyProvider = require('@smithy/property-provider'); +var client = require('@aws-sdk/core/client'); +var signatureV4 = require('@smithy/signature-v4'); + +const getDateHeader = (response) => protocolHttp.HttpResponse.isInstance(response) ? response.headers?.date ?? response.headers?.Date : undefined; + +const getSkewCorrectedDate = (systemClockOffset) => new Date(Date.now() + systemClockOffset); + +const isClockSkewed = (clockTime, systemClockOffset) => Math.abs(getSkewCorrectedDate(systemClockOffset).getTime() - clockTime) >= 300000; + +const getUpdatedSystemClockOffset = (clockTime, currentSystemClockOffset) => { + const clockTimeInMs = Date.parse(clockTime); + if (isClockSkewed(clockTimeInMs, currentSystemClockOffset)) { + return clockTimeInMs - Date.now(); + } + return currentSystemClockOffset; +}; + +const throwSigningPropertyError = (name, property) => { + if (!property) { + throw new Error(`Property \`${name}\` is not resolved for AWS SDK SigV4Auth`); + } + return property; +}; +const validateSigningProperties = async (signingProperties) => { + const context = throwSigningPropertyError("context", signingProperties.context); + const config = throwSigningPropertyError("config", signingProperties.config); + const authScheme = context.endpointV2?.properties?.authSchemes?.[0]; + const signerFunction = throwSigningPropertyError("signer", config.signer); + const signer = await signerFunction(authScheme); + const signingRegion = signingProperties?.signingRegion; + const signingRegionSet = signingProperties?.signingRegionSet; + const signingName = signingProperties?.signingName; + return { + config, + signer, + signingRegion, + signingRegionSet, + signingName, + }; +}; +class AwsSdkSigV4Signer { + async sign(httpRequest, identity, signingProperties) { + if (!protocolHttp.HttpRequest.isInstance(httpRequest)) { + throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); + } + const validatedProps = await validateSigningProperties(signingProperties); + const { config, signer } = validatedProps; + let { signingRegion, signingName } = validatedProps; + const handlerExecutionContext = signingProperties.context; + if (handlerExecutionContext?.authSchemes?.length ?? 0 > 1) { + const [first, second] = handlerExecutionContext.authSchemes; + if (first?.name === "sigv4a" && second?.name === "sigv4") { + signingRegion = second?.signingRegion ?? signingRegion; + signingName = second?.signingName ?? signingName; + } + } + const signedRequest = await signer.sign(httpRequest, { + signingDate: getSkewCorrectedDate(config.systemClockOffset), + signingRegion: signingRegion, + signingService: signingName, + }); + return signedRequest; + } + errorHandler(signingProperties) { + return (error) => { + const serverTime = error.ServerTime ?? getDateHeader(error.$response); + if (serverTime) { + const config = throwSigningPropertyError("config", signingProperties.config); + const initialSystemClockOffset = config.systemClockOffset; + config.systemClockOffset = getUpdatedSystemClockOffset(serverTime, config.systemClockOffset); + const clockSkewCorrected = config.systemClockOffset !== initialSystemClockOffset; + if (clockSkewCorrected && error.$metadata) { + error.$metadata.clockSkewCorrected = true; + } + } + throw error; + }; + } + successHandler(httpResponse, signingProperties) { + const dateHeader = getDateHeader(httpResponse); + if (dateHeader) { + const config = throwSigningPropertyError("config", signingProperties.config); + config.systemClockOffset = getUpdatedSystemClockOffset(dateHeader, config.systemClockOffset); + } + } +} +const AWSSDKSigV4Signer = AwsSdkSigV4Signer; + +class AwsSdkSigV4ASigner extends AwsSdkSigV4Signer { + async sign(httpRequest, identity, signingProperties) { + if (!protocolHttp.HttpRequest.isInstance(httpRequest)) { + throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); + } + const { config, signer, signingRegion, signingRegionSet, signingName } = await validateSigningProperties(signingProperties); + const configResolvedSigningRegionSet = await config.sigv4aSigningRegionSet?.(); + const multiRegionOverride = (configResolvedSigningRegionSet ?? + signingRegionSet ?? [signingRegion]).join(","); + const signedRequest = await signer.sign(httpRequest, { + signingDate: getSkewCorrectedDate(config.systemClockOffset), + signingRegion: multiRegionOverride, + signingService: signingName, + }); + return signedRequest; + } +} + +const getArrayForCommaSeparatedString = (str) => typeof str === "string" && str.length > 0 ? str.split(",").map((item) => item.trim()) : []; + +const getBearerTokenEnvKey = (signingName) => `AWS_BEARER_TOKEN_${signingName.replace(/[\s-]/g, "_").toUpperCase()}`; + +const NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY = "AWS_AUTH_SCHEME_PREFERENCE"; +const NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY = "auth_scheme_preference"; +const NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = { + environmentVariableSelector: (env, options) => { + if (options?.signingName) { + const bearerTokenKey = getBearerTokenEnvKey(options.signingName); + if (bearerTokenKey in env) + return ["httpBearerAuth"]; + } + if (!(NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY in env)) + return undefined; + return getArrayForCommaSeparatedString(env[NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY]); + }, + configFileSelector: (profile) => { + if (!(NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY in profile)) + return undefined; + return getArrayForCommaSeparatedString(profile[NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY]); + }, + default: [], +}; + +const resolveAwsSdkSigV4AConfig = (config) => { + config.sigv4aSigningRegionSet = core.normalizeProvider(config.sigv4aSigningRegionSet); + return config; +}; +const NODE_SIGV4A_CONFIG_OPTIONS = { + environmentVariableSelector(env) { + if (env.AWS_SIGV4A_SIGNING_REGION_SET) { + return env.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((_) => _.trim()); + } + throw new propertyProvider.ProviderError("AWS_SIGV4A_SIGNING_REGION_SET not set in env.", { + tryNextLink: true, + }); + }, + configFileSelector(profile) { + if (profile.sigv4a_signing_region_set) { + return (profile.sigv4a_signing_region_set ?? "").split(",").map((_) => _.trim()); + } + throw new propertyProvider.ProviderError("sigv4a_signing_region_set not set in profile.", { + tryNextLink: true, + }); + }, + default: undefined, +}; + +const resolveAwsSdkSigV4Config = (config) => { + let inputCredentials = config.credentials; + let isUserSupplied = !!config.credentials; + let resolvedCredentials = undefined; + Object.defineProperty(config, "credentials", { + set(credentials) { + if (credentials && credentials !== inputCredentials && credentials !== resolvedCredentials) { + isUserSupplied = true; + } + inputCredentials = credentials; + const memoizedProvider = normalizeCredentialProvider(config, { + credentials: inputCredentials, + credentialDefaultProvider: config.credentialDefaultProvider, + }); + const boundProvider = bindCallerConfig(config, memoizedProvider); + if (isUserSupplied && !boundProvider.attributed) { + resolvedCredentials = async (options) => boundProvider(options).then((creds) => client.setCredentialFeature(creds, "CREDENTIALS_CODE", "e")); + resolvedCredentials.memoized = boundProvider.memoized; + resolvedCredentials.configBound = boundProvider.configBound; + resolvedCredentials.attributed = true; + } + else { + resolvedCredentials = boundProvider; + } + }, + get() { + return resolvedCredentials; + }, + enumerable: true, + configurable: true, + }); + config.credentials = inputCredentials; + const { signingEscapePath = true, systemClockOffset = config.systemClockOffset || 0, sha256, } = config; + let signer; + if (config.signer) { + signer = core.normalizeProvider(config.signer); + } + else if (config.regionInfoProvider) { + signer = () => core.normalizeProvider(config.region)() + .then(async (region) => [ + (await config.regionInfoProvider(region, { + useFipsEndpoint: await config.useFipsEndpoint(), + useDualstackEndpoint: await config.useDualstackEndpoint(), + })) || {}, + region, + ]) + .then(([regionInfo, region]) => { + const { signingRegion, signingService } = regionInfo; + config.signingRegion = config.signingRegion || signingRegion || region; + config.signingName = config.signingName || signingService || config.serviceId; + const params = { + ...config, + credentials: config.credentials, + region: config.signingRegion, + service: config.signingName, + sha256, + uriEscapePath: signingEscapePath, + }; + const SignerCtor = config.signerConstructor || signatureV4.SignatureV4; + return new SignerCtor(params); + }); + } + else { + signer = async (authScheme) => { + authScheme = Object.assign({}, { + name: "sigv4", + signingName: config.signingName || config.defaultSigningName, + signingRegion: await core.normalizeProvider(config.region)(), + properties: {}, + }, authScheme); + const signingRegion = authScheme.signingRegion; + const signingService = authScheme.signingName; + config.signingRegion = config.signingRegion || signingRegion; + config.signingName = config.signingName || signingService || config.serviceId; + const params = { + ...config, + credentials: config.credentials, + region: config.signingRegion, + service: config.signingName, + sha256, + uriEscapePath: signingEscapePath, + }; + const SignerCtor = config.signerConstructor || signatureV4.SignatureV4; + return new SignerCtor(params); + }; + } + const resolvedConfig = Object.assign(config, { + systemClockOffset, + signingEscapePath, + signer, + }); + return resolvedConfig; +}; +const resolveAWSSDKSigV4Config = resolveAwsSdkSigV4Config; +function normalizeCredentialProvider(config, { credentials, credentialDefaultProvider, }) { + let credentialsProvider; + if (credentials) { + if (!credentials?.memoized) { + credentialsProvider = core.memoizeIdentityProvider(credentials, core.isIdentityExpired, core.doesIdentityRequireRefresh); + } + else { + credentialsProvider = credentials; + } + } + else { + if (credentialDefaultProvider) { + credentialsProvider = core.normalizeProvider(credentialDefaultProvider(Object.assign({}, config, { + parentClientConfig: config, + }))); + } + else { + credentialsProvider = async () => { + throw new Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured."); + }; + } + } + credentialsProvider.memoized = true; + return credentialsProvider; +} +function bindCallerConfig(config, credentialsProvider) { + if (credentialsProvider.configBound) { + return credentialsProvider; + } + const fn = async (options) => credentialsProvider({ ...options, callerClientConfig: config }); + fn.memoized = credentialsProvider.memoized; + fn.configBound = true; + return fn; +} + +exports.AWSSDKSigV4Signer = AWSSDKSigV4Signer; +exports.AwsSdkSigV4ASigner = AwsSdkSigV4ASigner; +exports.AwsSdkSigV4Signer = AwsSdkSigV4Signer; +exports.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = NODE_AUTH_SCHEME_PREFERENCE_OPTIONS; +exports.NODE_SIGV4A_CONFIG_OPTIONS = NODE_SIGV4A_CONFIG_OPTIONS; +exports.getBearerTokenEnvKey = getBearerTokenEnvKey; +exports.resolveAWSSDKSigV4Config = resolveAWSSDKSigV4Config; +exports.resolveAwsSdkSigV4AConfig = resolveAwsSdkSigV4AConfig; +exports.resolveAwsSdkSigV4Config = resolveAwsSdkSigV4Config; +exports.validateSigningProperties = validateSigningProperties; diff --git a/claude-code-source/node_modules/@aws-sdk/core/dist-cjs/submodules/protocols/index.js b/claude-code-source/node_modules/@aws-sdk/core/dist-cjs/submodules/protocols/index.js new file mode 100644 index 00000000..c0e99791 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/core/dist-cjs/submodules/protocols/index.js @@ -0,0 +1,1655 @@ +'use strict'; + +var cbor = require('@smithy/core/cbor'); +var schema = require('@smithy/core/schema'); +var smithyClient = require('@smithy/smithy-client'); +var protocols = require('@smithy/core/protocols'); +var serde = require('@smithy/core/serde'); +var utilBase64 = require('@smithy/util-base64'); +var utilUtf8 = require('@smithy/util-utf8'); +var xmlBuilder = require('@aws-sdk/xml-builder'); + +class ProtocolLib { + queryCompat; + constructor(queryCompat = false) { + this.queryCompat = queryCompat; + } + resolveRestContentType(defaultContentType, inputSchema) { + const members = inputSchema.getMemberSchemas(); + const httpPayloadMember = Object.values(members).find((m) => { + return !!m.getMergedTraits().httpPayload; + }); + if (httpPayloadMember) { + const mediaType = httpPayloadMember.getMergedTraits().mediaType; + if (mediaType) { + return mediaType; + } + else if (httpPayloadMember.isStringSchema()) { + return "text/plain"; + } + else if (httpPayloadMember.isBlobSchema()) { + return "application/octet-stream"; + } + else { + return defaultContentType; + } + } + else if (!inputSchema.isUnitSchema()) { + const hasBody = Object.values(members).find((m) => { + const { httpQuery, httpQueryParams, httpHeader, httpLabel, httpPrefixHeaders } = m.getMergedTraits(); + const noPrefixHeaders = httpPrefixHeaders === void 0; + return !httpQuery && !httpQueryParams && !httpHeader && !httpLabel && noPrefixHeaders; + }); + if (hasBody) { + return defaultContentType; + } + } + } + async getErrorSchemaOrThrowBaseException(errorIdentifier, defaultNamespace, response, dataObject, metadata, getErrorSchema) { + let namespace = defaultNamespace; + let errorName = errorIdentifier; + if (errorIdentifier.includes("#")) { + [namespace, errorName] = errorIdentifier.split("#"); + } + const errorMetadata = { + $metadata: metadata, + $fault: response.statusCode < 500 ? "client" : "server", + }; + const registry = schema.TypeRegistry.for(namespace); + try { + const errorSchema = getErrorSchema?.(registry, errorName) ?? registry.getSchema(errorIdentifier); + return { errorSchema, errorMetadata }; + } + catch (e) { + dataObject.message = dataObject.message ?? dataObject.Message ?? "UnknownError"; + const synthetic = schema.TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace); + const baseExceptionSchema = synthetic.getBaseException(); + if (baseExceptionSchema) { + const ErrorCtor = synthetic.getErrorCtor(baseExceptionSchema) ?? Error; + throw this.decorateServiceException(Object.assign(new ErrorCtor({ name: errorName }), errorMetadata), dataObject); + } + throw this.decorateServiceException(Object.assign(new Error(errorName), errorMetadata), dataObject); + } + } + decorateServiceException(exception, additions = {}) { + if (this.queryCompat) { + const msg = exception.Message ?? additions.Message; + const error = smithyClient.decorateServiceException(exception, additions); + if (msg) { + error.Message = msg; + error.message = msg; + } + return error; + } + return smithyClient.decorateServiceException(exception, additions); + } + setQueryCompatError(output, response) { + const queryErrorHeader = response.headers?.["x-amzn-query-error"]; + if (output !== undefined && queryErrorHeader != null) { + const [Code, Type] = queryErrorHeader.split(";"); + const entries = Object.entries(output); + const Error = { + Code, + Type, + }; + Object.assign(output, Error); + for (const [k, v] of entries) { + Error[k] = v; + } + delete Error.__type; + output.Error = Error; + } + } + queryCompatOutput(queryCompatErrorData, errorData) { + if (queryCompatErrorData.Error) { + errorData.Error = queryCompatErrorData.Error; + } + if (queryCompatErrorData.Type) { + errorData.Type = queryCompatErrorData.Type; + } + if (queryCompatErrorData.Code) { + errorData.Code = queryCompatErrorData.Code; + } + } +} + +class AwsSmithyRpcV2CborProtocol extends cbor.SmithyRpcV2CborProtocol { + awsQueryCompatible; + mixin; + constructor({ defaultNamespace, awsQueryCompatible, }) { + super({ defaultNamespace }); + this.awsQueryCompatible = !!awsQueryCompatible; + this.mixin = new ProtocolLib(this.awsQueryCompatible); + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + if (this.awsQueryCompatible) { + request.headers["x-amzn-query-mode"] = "true"; + } + return request; + } + async handleError(operationSchema, context, response, dataObject, metadata) { + if (this.awsQueryCompatible) { + this.mixin.setQueryCompatError(dataObject, response); + } + const errorName = cbor.loadSmithyRpcV2CborErrorCode(response, dataObject) ?? "Unknown"; + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorName, this.options.defaultNamespace, response, dataObject, metadata); + const ns = schema.NormalizedSchema.of(errorSchema); + const message = dataObject.message ?? dataObject.Message ?? "Unknown"; + const ErrorCtor = schema.TypeRegistry.for(errorSchema[1]).getErrorCtor(errorSchema) ?? Error; + const exception = new ErrorCtor(message); + const output = {}; + for (const [name, member] of ns.structIterator()) { + output[name] = this.deserializer.readValue(member, dataObject[name]); + } + if (this.awsQueryCompatible) { + this.mixin.queryCompatOutput(dataObject, output); + } + throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message, + }, output), dataObject); + } +} + +const _toStr = (val) => { + if (val == null) { + return val; + } + if (typeof val === "number" || typeof val === "bigint") { + const warning = new Error(`Received number ${val} where a string was expected.`); + warning.name = "Warning"; + console.warn(warning); + return String(val); + } + if (typeof val === "boolean") { + const warning = new Error(`Received boolean ${val} where a string was expected.`); + warning.name = "Warning"; + console.warn(warning); + return String(val); + } + return val; +}; +const _toBool = (val) => { + if (val == null) { + return val; + } + if (typeof val === "string") { + const lowercase = val.toLowerCase(); + if (val !== "" && lowercase !== "false" && lowercase !== "true") { + const warning = new Error(`Received string "${val}" where a boolean was expected.`); + warning.name = "Warning"; + console.warn(warning); + } + return val !== "" && lowercase !== "false"; + } + return val; +}; +const _toNum = (val) => { + if (val == null) { + return val; + } + if (typeof val === "string") { + const num = Number(val); + if (num.toString() !== val) { + const warning = new Error(`Received string "${val}" where a number was expected.`); + warning.name = "Warning"; + console.warn(warning); + return val; + } + return num; + } + return val; +}; + +class SerdeContextConfig { + serdeContext; + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + } +} + +function jsonReviver(key, value, context) { + if (context?.source) { + const numericString = context.source; + if (typeof value === "number") { + if (value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER || numericString !== String(value)) { + const isFractional = numericString.includes("."); + if (isFractional) { + return new serde.NumericValue(numericString, "bigDecimal"); + } + else { + return BigInt(numericString); + } + } + } + } + return value; +} + +const collectBodyString = (streamBody, context) => smithyClient.collectBody(streamBody, context).then((body) => (context?.utf8Encoder ?? utilUtf8.toUtf8)(body)); + +const parseJsonBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { + if (encoded.length) { + try { + return JSON.parse(encoded); + } + catch (e) { + if (e?.name === "SyntaxError") { + Object.defineProperty(e, "$responseBodyText", { + value: encoded, + }); + } + throw e; + } + } + return {}; +}); +const parseJsonErrorBody = async (errorBody, context) => { + const value = await parseJsonBody(errorBody, context); + value.message = value.message ?? value.Message; + return value; +}; +const loadRestJsonErrorCode = (output, data) => { + const findKey = (object, key) => Object.keys(object).find((k) => k.toLowerCase() === key.toLowerCase()); + const sanitizeErrorCode = (rawValue) => { + let cleanValue = rawValue; + if (typeof cleanValue === "number") { + cleanValue = cleanValue.toString(); + } + if (cleanValue.indexOf(",") >= 0) { + cleanValue = cleanValue.split(",")[0]; + } + if (cleanValue.indexOf(":") >= 0) { + cleanValue = cleanValue.split(":")[0]; + } + if (cleanValue.indexOf("#") >= 0) { + cleanValue = cleanValue.split("#")[1]; + } + return cleanValue; + }; + const headerKey = findKey(output.headers, "x-amzn-errortype"); + if (headerKey !== undefined) { + return sanitizeErrorCode(output.headers[headerKey]); + } + if (data && typeof data === "object") { + const codeKey = findKey(data, "code"); + if (codeKey && data[codeKey] !== undefined) { + return sanitizeErrorCode(data[codeKey]); + } + if (data["__type"] !== undefined) { + return sanitizeErrorCode(data["__type"]); + } + } +}; + +class JsonShapeDeserializer extends SerdeContextConfig { + settings; + constructor(settings) { + super(); + this.settings = settings; + } + async read(schema, data) { + return this._read(schema, typeof data === "string" ? JSON.parse(data, jsonReviver) : await parseJsonBody(data, this.serdeContext)); + } + readObject(schema, data) { + return this._read(schema, data); + } + _read(schema$1, value) { + const isObject = value !== null && typeof value === "object"; + const ns = schema.NormalizedSchema.of(schema$1); + if (ns.isListSchema() && Array.isArray(value)) { + const listMember = ns.getValueSchema(); + const out = []; + const sparse = !!ns.getMergedTraits().sparse; + for (const item of value) { + if (sparse || item != null) { + out.push(this._read(listMember, item)); + } + } + return out; + } + else if (ns.isMapSchema() && isObject) { + const mapMember = ns.getValueSchema(); + const out = {}; + const sparse = !!ns.getMergedTraits().sparse; + for (const [_k, _v] of Object.entries(value)) { + if (sparse || _v != null) { + out[_k] = this._read(mapMember, _v); + } + } + return out; + } + else if (ns.isStructSchema() && isObject) { + const out = {}; + for (const [memberName, memberSchema] of ns.structIterator()) { + const fromKey = this.settings.jsonName ? memberSchema.getMergedTraits().jsonName ?? memberName : memberName; + const deserializedValue = this._read(memberSchema, value[fromKey]); + if (deserializedValue != null) { + out[memberName] = deserializedValue; + } + } + return out; + } + if (ns.isBlobSchema() && typeof value === "string") { + return utilBase64.fromBase64(value); + } + const mediaType = ns.getMergedTraits().mediaType; + if (ns.isStringSchema() && typeof value === "string" && mediaType) { + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + return serde.LazyJsonString.from(value); + } + } + if (ns.isTimestampSchema() && value != null) { + const format = protocols.determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: + return serde.parseRfc3339DateTimeWithOffset(value); + case 6: + return serde.parseRfc7231DateTime(value); + case 7: + return serde.parseEpochTimestamp(value); + default: + console.warn("Missing timestamp format, parsing value with Date constructor:", value); + return new Date(value); + } + } + if (ns.isBigIntegerSchema() && (typeof value === "number" || typeof value === "string")) { + return BigInt(value); + } + if (ns.isBigDecimalSchema() && value != undefined) { + if (value instanceof serde.NumericValue) { + return value; + } + const untyped = value; + if (untyped.type === "bigDecimal" && "string" in untyped) { + return new serde.NumericValue(untyped.string, untyped.type); + } + return new serde.NumericValue(String(value), "bigDecimal"); + } + if (ns.isNumericSchema() && typeof value === "string") { + switch (value) { + case "Infinity": + return Infinity; + case "-Infinity": + return -Infinity; + case "NaN": + return NaN; + } + } + if (ns.isDocumentSchema()) { + if (isObject) { + const out = Array.isArray(value) ? [] : {}; + for (const [k, v] of Object.entries(value)) { + if (v instanceof serde.NumericValue) { + out[k] = v; + } + else { + out[k] = this._read(ns, v); + } + } + return out; + } + else { + return structuredClone(value); + } + } + return value; + } +} + +const NUMERIC_CONTROL_CHAR = String.fromCharCode(925); +class JsonReplacer { + values = new Map(); + counter = 0; + stage = 0; + createReplacer() { + if (this.stage === 1) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer already created."); + } + if (this.stage === 2) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); + } + this.stage = 1; + return (key, value) => { + if (value instanceof serde.NumericValue) { + const v = `${NUMERIC_CONTROL_CHAR + "nv" + this.counter++}_` + value.string; + this.values.set(`"${v}"`, value.string); + return v; + } + if (typeof value === "bigint") { + const s = value.toString(); + const v = `${NUMERIC_CONTROL_CHAR + "b" + this.counter++}_` + s; + this.values.set(`"${v}"`, s); + return v; + } + return value; + }; + } + replaceInJson(json) { + if (this.stage === 0) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer not created yet."); + } + if (this.stage === 2) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); + } + this.stage = 2; + if (this.counter === 0) { + return json; + } + for (const [key, value] of this.values) { + json = json.replace(key, value); + } + return json; + } +} + +class JsonShapeSerializer extends SerdeContextConfig { + settings; + buffer; + rootSchema; + constructor(settings) { + super(); + this.settings = settings; + } + write(schema$1, value) { + this.rootSchema = schema.NormalizedSchema.of(schema$1); + this.buffer = this._write(this.rootSchema, value); + } + writeDiscriminatedDocument(schema$1, value) { + this.write(schema$1, value); + if (typeof this.buffer === "object") { + this.buffer.__type = schema.NormalizedSchema.of(schema$1).getName(true); + } + } + flush() { + const { rootSchema } = this; + this.rootSchema = undefined; + if (rootSchema?.isStructSchema() || rootSchema?.isDocumentSchema()) { + const replacer = new JsonReplacer(); + return replacer.replaceInJson(JSON.stringify(this.buffer, replacer.createReplacer(), 0)); + } + return this.buffer; + } + _write(schema$1, value, container) { + const isObject = value !== null && typeof value === "object"; + const ns = schema.NormalizedSchema.of(schema$1); + if (ns.isListSchema() && Array.isArray(value)) { + const listMember = ns.getValueSchema(); + const out = []; + const sparse = !!ns.getMergedTraits().sparse; + for (const item of value) { + if (sparse || item != null) { + out.push(this._write(listMember, item)); + } + } + return out; + } + else if (ns.isMapSchema() && isObject) { + const mapMember = ns.getValueSchema(); + const out = {}; + const sparse = !!ns.getMergedTraits().sparse; + for (const [_k, _v] of Object.entries(value)) { + if (sparse || _v != null) { + out[_k] = this._write(mapMember, _v); + } + } + return out; + } + else if (ns.isStructSchema() && isObject) { + const out = {}; + for (const [memberName, memberSchema] of ns.structIterator()) { + const targetKey = this.settings.jsonName ? memberSchema.getMergedTraits().jsonName ?? memberName : memberName; + const serializableValue = this._write(memberSchema, value[memberName], ns); + if (serializableValue !== undefined) { + out[targetKey] = serializableValue; + } + } + return out; + } + if (value === null && container?.isStructSchema()) { + return void 0; + } + if ((ns.isBlobSchema() && (value instanceof Uint8Array || typeof value === "string")) || + (ns.isDocumentSchema() && value instanceof Uint8Array)) { + if (ns === this.rootSchema) { + return value; + } + return (this.serdeContext?.base64Encoder ?? utilBase64.toBase64)(value); + } + if ((ns.isTimestampSchema() || ns.isDocumentSchema()) && value instanceof Date) { + const format = protocols.determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: + return value.toISOString().replace(".000Z", "Z"); + case 6: + return serde.dateToUtcString(value); + case 7: + return value.getTime() / 1000; + default: + console.warn("Missing timestamp format, using epoch seconds", value); + return value.getTime() / 1000; + } + } + if (ns.isNumericSchema() && typeof value === "number") { + if (Math.abs(value) === Infinity || isNaN(value)) { + return String(value); + } + } + if (ns.isStringSchema()) { + if (typeof value === "undefined" && ns.isIdempotencyToken()) { + return serde.generateIdempotencyToken(); + } + const mediaType = ns.getMergedTraits().mediaType; + if (value != null && mediaType) { + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + return serde.LazyJsonString.from(value); + } + } + } + if (ns.isDocumentSchema()) { + if (isObject) { + const out = Array.isArray(value) ? [] : {}; + for (const [k, v] of Object.entries(value)) { + if (v instanceof serde.NumericValue) { + out[k] = v; + } + else { + out[k] = this._write(ns, v); + } + } + return out; + } + else { + return structuredClone(value); + } + } + return value; + } +} + +class JsonCodec extends SerdeContextConfig { + settings; + constructor(settings) { + super(); + this.settings = settings; + } + createSerializer() { + const serializer = new JsonShapeSerializer(this.settings); + serializer.setSerdeContext(this.serdeContext); + return serializer; + } + createDeserializer() { + const deserializer = new JsonShapeDeserializer(this.settings); + deserializer.setSerdeContext(this.serdeContext); + return deserializer; + } +} + +class AwsJsonRpcProtocol extends protocols.RpcProtocol { + serializer; + deserializer; + serviceTarget; + codec; + mixin; + awsQueryCompatible; + constructor({ defaultNamespace, serviceTarget, awsQueryCompatible, }) { + super({ + defaultNamespace, + }); + this.serviceTarget = serviceTarget; + this.codec = new JsonCodec({ + timestampFormat: { + useTrait: true, + default: 7, + }, + jsonName: false, + }); + this.serializer = this.codec.createSerializer(); + this.deserializer = this.codec.createDeserializer(); + this.awsQueryCompatible = !!awsQueryCompatible; + this.mixin = new ProtocolLib(this.awsQueryCompatible); + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + if (!request.path.endsWith("/")) { + request.path += "/"; + } + Object.assign(request.headers, { + "content-type": `application/x-amz-json-${this.getJsonRpcVersion()}`, + "x-amz-target": `${this.serviceTarget}.${operationSchema.name}`, + }); + if (this.awsQueryCompatible) { + request.headers["x-amzn-query-mode"] = "true"; + } + if (schema.deref(operationSchema.input) === "unit" || !request.body) { + request.body = "{}"; + } + return request; + } + getPayloadCodec() { + return this.codec; + } + async handleError(operationSchema, context, response, dataObject, metadata) { + if (this.awsQueryCompatible) { + this.mixin.setQueryCompatError(dataObject, response); + } + const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown"; + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata); + const ns = schema.NormalizedSchema.of(errorSchema); + const message = dataObject.message ?? dataObject.Message ?? "Unknown"; + const ErrorCtor = schema.TypeRegistry.for(errorSchema[1]).getErrorCtor(errorSchema) ?? Error; + const exception = new ErrorCtor(message); + const output = {}; + for (const [name, member] of ns.structIterator()) { + const target = member.getMergedTraits().jsonName ?? name; + output[name] = this.codec.createDeserializer().readObject(member, dataObject[target]); + } + if (this.awsQueryCompatible) { + this.mixin.queryCompatOutput(dataObject, output); + } + throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message, + }, output), dataObject); + } +} + +class AwsJson1_0Protocol extends AwsJsonRpcProtocol { + constructor({ defaultNamespace, serviceTarget, awsQueryCompatible, }) { + super({ + defaultNamespace, + serviceTarget, + awsQueryCompatible, + }); + } + getShapeId() { + return "aws.protocols#awsJson1_0"; + } + getJsonRpcVersion() { + return "1.0"; + } + getDefaultContentType() { + return "application/x-amz-json-1.0"; + } +} + +class AwsJson1_1Protocol extends AwsJsonRpcProtocol { + constructor({ defaultNamespace, serviceTarget, awsQueryCompatible, }) { + super({ + defaultNamespace, + serviceTarget, + awsQueryCompatible, + }); + } + getShapeId() { + return "aws.protocols#awsJson1_1"; + } + getJsonRpcVersion() { + return "1.1"; + } + getDefaultContentType() { + return "application/x-amz-json-1.1"; + } +} + +class AwsRestJsonProtocol extends protocols.HttpBindingProtocol { + serializer; + deserializer; + codec; + mixin = new ProtocolLib(); + constructor({ defaultNamespace }) { + super({ + defaultNamespace, + }); + const settings = { + timestampFormat: { + useTrait: true, + default: 7, + }, + httpBindings: true, + jsonName: true, + }; + this.codec = new JsonCodec(settings); + this.serializer = new protocols.HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings); + this.deserializer = new protocols.HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings); + } + getShapeId() { + return "aws.protocols#restJson1"; + } + getPayloadCodec() { + return this.codec; + } + setSerdeContext(serdeContext) { + this.codec.setSerdeContext(serdeContext); + super.setSerdeContext(serdeContext); + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + const inputSchema = schema.NormalizedSchema.of(operationSchema.input); + if (!request.headers["content-type"]) { + const contentType = this.mixin.resolveRestContentType(this.getDefaultContentType(), inputSchema); + if (contentType) { + request.headers["content-type"] = contentType; + } + } + if (request.body == null && request.headers["content-type"] === this.getDefaultContentType()) { + request.body = "{}"; + } + return request; + } + async deserializeResponse(operationSchema, context, response) { + const output = await super.deserializeResponse(operationSchema, context, response); + const outputSchema = schema.NormalizedSchema.of(operationSchema.output); + for (const [name, member] of outputSchema.structIterator()) { + if (member.getMemberTraits().httpPayload && !(name in output)) { + output[name] = null; + } + } + return output; + } + async handleError(operationSchema, context, response, dataObject, metadata) { + const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown"; + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata); + const ns = schema.NormalizedSchema.of(errorSchema); + const message = dataObject.message ?? dataObject.Message ?? "Unknown"; + const ErrorCtor = schema.TypeRegistry.for(errorSchema[1]).getErrorCtor(errorSchema) ?? Error; + const exception = new ErrorCtor(message); + await this.deserializeHttpMessage(errorSchema, context, response, dataObject); + const output = {}; + for (const [name, member] of ns.structIterator()) { + const target = member.getMergedTraits().jsonName ?? name; + output[name] = this.codec.createDeserializer().readObject(member, dataObject[target]); + } + throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message, + }, output), dataObject); + } + getDefaultContentType() { + return "application/json"; + } +} + +const awsExpectUnion = (value) => { + if (value == null) { + return undefined; + } + if (typeof value === "object" && "__type" in value) { + delete value.__type; + } + return smithyClient.expectUnion(value); +}; + +class XmlShapeDeserializer extends SerdeContextConfig { + settings; + stringDeserializer; + constructor(settings) { + super(); + this.settings = settings; + this.stringDeserializer = new protocols.FromStringShapeDeserializer(settings); + } + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + this.stringDeserializer.setSerdeContext(serdeContext); + } + read(schema$1, bytes, key) { + const ns = schema.NormalizedSchema.of(schema$1); + const memberSchemas = ns.getMemberSchemas(); + const isEventPayload = ns.isStructSchema() && + ns.isMemberSchema() && + !!Object.values(memberSchemas).find((memberNs) => { + return !!memberNs.getMemberTraits().eventPayload; + }); + if (isEventPayload) { + const output = {}; + const memberName = Object.keys(memberSchemas)[0]; + const eventMemberSchema = memberSchemas[memberName]; + if (eventMemberSchema.isBlobSchema()) { + output[memberName] = bytes; + } + else { + output[memberName] = this.read(memberSchemas[memberName], bytes); + } + return output; + } + const xmlString = (this.serdeContext?.utf8Encoder ?? utilUtf8.toUtf8)(bytes); + const parsedObject = this.parseXml(xmlString); + return this.readSchema(schema$1, key ? parsedObject[key] : parsedObject); + } + readSchema(_schema, value) { + const ns = schema.NormalizedSchema.of(_schema); + if (ns.isUnitSchema()) { + return; + } + const traits = ns.getMergedTraits(); + if (ns.isListSchema() && !Array.isArray(value)) { + return this.readSchema(ns, [value]); + } + if (value == null) { + return value; + } + if (typeof value === "object") { + const sparse = !!traits.sparse; + const flat = !!traits.xmlFlattened; + if (ns.isListSchema()) { + const listValue = ns.getValueSchema(); + const buffer = []; + const sourceKey = listValue.getMergedTraits().xmlName ?? "member"; + const source = flat ? value : (value[0] ?? value)[sourceKey]; + const sourceArray = Array.isArray(source) ? source : [source]; + for (const v of sourceArray) { + if (v != null || sparse) { + buffer.push(this.readSchema(listValue, v)); + } + } + return buffer; + } + const buffer = {}; + if (ns.isMapSchema()) { + const keyNs = ns.getKeySchema(); + const memberNs = ns.getValueSchema(); + let entries; + if (flat) { + entries = Array.isArray(value) ? value : [value]; + } + else { + entries = Array.isArray(value.entry) ? value.entry : [value.entry]; + } + const keyProperty = keyNs.getMergedTraits().xmlName ?? "key"; + const valueProperty = memberNs.getMergedTraits().xmlName ?? "value"; + for (const entry of entries) { + const key = entry[keyProperty]; + const value = entry[valueProperty]; + if (value != null || sparse) { + buffer[key] = this.readSchema(memberNs, value); + } + } + return buffer; + } + if (ns.isStructSchema()) { + for (const [memberName, memberSchema] of ns.structIterator()) { + const memberTraits = memberSchema.getMergedTraits(); + const xmlObjectKey = !memberTraits.httpPayload + ? memberSchema.getMemberTraits().xmlName ?? memberName + : memberTraits.xmlName ?? memberSchema.getName(); + if (value[xmlObjectKey] != null) { + buffer[memberName] = this.readSchema(memberSchema, value[xmlObjectKey]); + } + } + return buffer; + } + if (ns.isDocumentSchema()) { + return value; + } + throw new Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${ns.getName(true)}`); + } + if (ns.isListSchema()) { + return []; + } + if (ns.isMapSchema() || ns.isStructSchema()) { + return {}; + } + return this.stringDeserializer.read(ns, value); + } + parseXml(xml) { + if (xml.length) { + let parsedObj; + try { + parsedObj = xmlBuilder.parseXML(xml); + } + catch (e) { + if (e && typeof e === "object") { + Object.defineProperty(e, "$responseBodyText", { + value: xml, + }); + } + throw e; + } + const textNodeName = "#text"; + const key = Object.keys(parsedObj)[0]; + const parsedObjToReturn = parsedObj[key]; + if (parsedObjToReturn[textNodeName]) { + parsedObjToReturn[key] = parsedObjToReturn[textNodeName]; + delete parsedObjToReturn[textNodeName]; + } + return smithyClient.getValueFromTextNode(parsedObjToReturn); + } + return {}; + } +} + +class QueryShapeSerializer extends SerdeContextConfig { + settings; + buffer; + constructor(settings) { + super(); + this.settings = settings; + } + write(schema$1, value, prefix = "") { + if (this.buffer === undefined) { + this.buffer = ""; + } + const ns = schema.NormalizedSchema.of(schema$1); + if (prefix && !prefix.endsWith(".")) { + prefix += "."; + } + if (ns.isBlobSchema()) { + if (typeof value === "string" || value instanceof Uint8Array) { + this.writeKey(prefix); + this.writeValue((this.serdeContext?.base64Encoder ?? utilBase64.toBase64)(value)); + } + } + else if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isStringSchema()) { + if (value != null) { + this.writeKey(prefix); + this.writeValue(String(value)); + } + else if (ns.isIdempotencyToken()) { + this.writeKey(prefix); + this.writeValue(serde.generateIdempotencyToken()); + } + } + else if (ns.isBigIntegerSchema()) { + if (value != null) { + this.writeKey(prefix); + this.writeValue(String(value)); + } + } + else if (ns.isBigDecimalSchema()) { + if (value != null) { + this.writeKey(prefix); + this.writeValue(value instanceof serde.NumericValue ? value.string : String(value)); + } + } + else if (ns.isTimestampSchema()) { + if (value instanceof Date) { + this.writeKey(prefix); + const format = protocols.determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: + this.writeValue(value.toISOString().replace(".000Z", "Z")); + break; + case 6: + this.writeValue(smithyClient.dateToUtcString(value)); + break; + case 7: + this.writeValue(String(value.getTime() / 1000)); + break; + } + } + } + else if (ns.isDocumentSchema()) { + throw new Error(`@aws-sdk/core/protocols - QuerySerializer unsupported document type ${ns.getName(true)}`); + } + else if (ns.isListSchema()) { + if (Array.isArray(value)) { + if (value.length === 0) { + if (this.settings.serializeEmptyLists) { + this.writeKey(prefix); + this.writeValue(""); + } + } + else { + const member = ns.getValueSchema(); + const flat = this.settings.flattenLists || ns.getMergedTraits().xmlFlattened; + let i = 1; + for (const item of value) { + if (item == null) { + continue; + } + const suffix = this.getKey("member", member.getMergedTraits().xmlName); + const key = flat ? `${prefix}${i}` : `${prefix}${suffix}.${i}`; + this.write(member, item, key); + ++i; + } + } + } + } + else if (ns.isMapSchema()) { + if (value && typeof value === "object") { + const keySchema = ns.getKeySchema(); + const memberSchema = ns.getValueSchema(); + const flat = ns.getMergedTraits().xmlFlattened; + let i = 1; + for (const [k, v] of Object.entries(value)) { + if (v == null) { + continue; + } + const keySuffix = this.getKey("key", keySchema.getMergedTraits().xmlName); + const key = flat ? `${prefix}${i}.${keySuffix}` : `${prefix}entry.${i}.${keySuffix}`; + const valueSuffix = this.getKey("value", memberSchema.getMergedTraits().xmlName); + const valueKey = flat ? `${prefix}${i}.${valueSuffix}` : `${prefix}entry.${i}.${valueSuffix}`; + this.write(keySchema, k, key); + this.write(memberSchema, v, valueKey); + ++i; + } + } + } + else if (ns.isStructSchema()) { + if (value && typeof value === "object") { + for (const [memberName, member] of ns.structIterator()) { + if (value[memberName] == null && !member.isIdempotencyToken()) { + continue; + } + const suffix = this.getKey(memberName, member.getMergedTraits().xmlName); + const key = `${prefix}${suffix}`; + this.write(member, value[memberName], key); + } + } + } + else if (ns.isUnitSchema()) ; + else { + throw new Error(`@aws-sdk/core/protocols - QuerySerializer unrecognized schema type ${ns.getName(true)}`); + } + } + flush() { + if (this.buffer === undefined) { + throw new Error("@aws-sdk/core/protocols - QuerySerializer cannot flush with nothing written to buffer."); + } + const str = this.buffer; + delete this.buffer; + return str; + } + getKey(memberName, xmlName) { + const key = xmlName ?? memberName; + if (this.settings.capitalizeKeys) { + return key[0].toUpperCase() + key.slice(1); + } + return key; + } + writeKey(key) { + if (key.endsWith(".")) { + key = key.slice(0, key.length - 1); + } + this.buffer += `&${protocols.extendedEncodeURIComponent(key)}=`; + } + writeValue(value) { + this.buffer += protocols.extendedEncodeURIComponent(value); + } +} + +class AwsQueryProtocol extends protocols.RpcProtocol { + options; + serializer; + deserializer; + mixin = new ProtocolLib(); + constructor(options) { + super({ + defaultNamespace: options.defaultNamespace, + }); + this.options = options; + const settings = { + timestampFormat: { + useTrait: true, + default: 5, + }, + httpBindings: false, + xmlNamespace: options.xmlNamespace, + serviceNamespace: options.defaultNamespace, + serializeEmptyLists: true, + }; + this.serializer = new QueryShapeSerializer(settings); + this.deserializer = new XmlShapeDeserializer(settings); + } + getShapeId() { + return "aws.protocols#awsQuery"; + } + setSerdeContext(serdeContext) { + this.serializer.setSerdeContext(serdeContext); + this.deserializer.setSerdeContext(serdeContext); + } + getPayloadCodec() { + throw new Error("AWSQuery protocol has no payload codec."); + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + if (!request.path.endsWith("/")) { + request.path += "/"; + } + Object.assign(request.headers, { + "content-type": `application/x-www-form-urlencoded`, + }); + if (schema.deref(operationSchema.input) === "unit" || !request.body) { + request.body = ""; + } + const action = operationSchema.name.split("#")[1] ?? operationSchema.name; + request.body = `Action=${action}&Version=${this.options.version}` + request.body; + if (request.body.endsWith("&")) { + request.body = request.body.slice(-1); + } + return request; + } + async deserializeResponse(operationSchema, context, response) { + const deserializer = this.deserializer; + const ns = schema.NormalizedSchema.of(operationSchema.output); + const dataObject = {}; + if (response.statusCode >= 300) { + const bytes = await protocols.collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(15, bytes)); + } + await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); + } + for (const header in response.headers) { + const value = response.headers[header]; + delete response.headers[header]; + response.headers[header.toLowerCase()] = value; + } + const shortName = operationSchema.name.split("#")[1] ?? operationSchema.name; + const awsQueryResultKey = ns.isStructSchema() && this.useNestedResult() ? shortName + "Result" : undefined; + const bytes = await protocols.collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(ns, bytes, awsQueryResultKey)); + } + const output = { + $metadata: this.deserializeMetadata(response), + ...dataObject, + }; + return output; + } + useNestedResult() { + return true; + } + async handleError(operationSchema, context, response, dataObject, metadata) { + const errorIdentifier = this.loadQueryErrorCode(response, dataObject) ?? "Unknown"; + const errorData = this.loadQueryError(dataObject); + const message = this.loadQueryErrorMessage(dataObject); + errorData.message = message; + errorData.Error = { + Type: errorData.Type, + Code: errorData.Code, + Message: message, + }; + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, errorData, metadata, (registry, errorName) => { + try { + return registry.getSchema(errorName); + } + catch (e) { + return registry.find((schema$1) => schema.NormalizedSchema.of(schema$1).getMergedTraits().awsQueryError?.[0] === errorName); + } + }); + const ns = schema.NormalizedSchema.of(errorSchema); + const ErrorCtor = schema.TypeRegistry.for(errorSchema[1]).getErrorCtor(errorSchema) ?? Error; + const exception = new ErrorCtor(message); + const output = { + Error: errorData.Error, + }; + for (const [name, member] of ns.structIterator()) { + const target = member.getMergedTraits().xmlName ?? name; + const value = errorData[target] ?? dataObject[target]; + output[name] = this.deserializer.readSchema(member, value); + } + throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message, + }, output), dataObject); + } + loadQueryErrorCode(output, data) { + const code = (data.Errors?.[0]?.Error ?? data.Errors?.Error ?? data.Error)?.Code; + if (code !== undefined) { + return code; + } + if (output.statusCode == 404) { + return "NotFound"; + } + } + loadQueryError(data) { + return data.Errors?.[0]?.Error ?? data.Errors?.Error ?? data.Error; + } + loadQueryErrorMessage(data) { + const errorData = this.loadQueryError(data); + return errorData?.message ?? errorData?.Message ?? data.message ?? data.Message ?? "Unknown"; + } + getDefaultContentType() { + return "application/x-www-form-urlencoded"; + } +} + +class AwsEc2QueryProtocol extends AwsQueryProtocol { + options; + constructor(options) { + super(options); + this.options = options; + const ec2Settings = { + capitalizeKeys: true, + flattenLists: true, + serializeEmptyLists: false, + }; + Object.assign(this.serializer.settings, ec2Settings); + } + useNestedResult() { + return false; + } +} + +const parseXmlBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { + if (encoded.length) { + let parsedObj; + try { + parsedObj = xmlBuilder.parseXML(encoded); + } + catch (e) { + if (e && typeof e === "object") { + Object.defineProperty(e, "$responseBodyText", { + value: encoded, + }); + } + throw e; + } + const textNodeName = "#text"; + const key = Object.keys(parsedObj)[0]; + const parsedObjToReturn = parsedObj[key]; + if (parsedObjToReturn[textNodeName]) { + parsedObjToReturn[key] = parsedObjToReturn[textNodeName]; + delete parsedObjToReturn[textNodeName]; + } + return smithyClient.getValueFromTextNode(parsedObjToReturn); + } + return {}; +}); +const parseXmlErrorBody = async (errorBody, context) => { + const value = await parseXmlBody(errorBody, context); + if (value.Error) { + value.Error.message = value.Error.message ?? value.Error.Message; + } + return value; +}; +const loadRestXmlErrorCode = (output, data) => { + if (data?.Error?.Code !== undefined) { + return data.Error.Code; + } + if (data?.Code !== undefined) { + return data.Code; + } + if (output.statusCode == 404) { + return "NotFound"; + } +}; + +class XmlShapeSerializer extends SerdeContextConfig { + settings; + stringBuffer; + byteBuffer; + buffer; + constructor(settings) { + super(); + this.settings = settings; + } + write(schema$1, value) { + const ns = schema.NormalizedSchema.of(schema$1); + if (ns.isStringSchema() && typeof value === "string") { + this.stringBuffer = value; + } + else if (ns.isBlobSchema()) { + this.byteBuffer = + "byteLength" in value + ? value + : (this.serdeContext?.base64Decoder ?? utilBase64.fromBase64)(value); + } + else { + this.buffer = this.writeStruct(ns, value, undefined); + const traits = ns.getMergedTraits(); + if (traits.httpPayload && !traits.xmlName) { + this.buffer.withName(ns.getName()); + } + } + } + flush() { + if (this.byteBuffer !== undefined) { + const bytes = this.byteBuffer; + delete this.byteBuffer; + return bytes; + } + if (this.stringBuffer !== undefined) { + const str = this.stringBuffer; + delete this.stringBuffer; + return str; + } + const buffer = this.buffer; + if (this.settings.xmlNamespace) { + if (!buffer?.attributes?.["xmlns"]) { + buffer.addAttribute("xmlns", this.settings.xmlNamespace); + } + } + delete this.buffer; + return buffer.toString(); + } + writeStruct(ns, value, parentXmlns) { + const traits = ns.getMergedTraits(); + const name = ns.isMemberSchema() && !traits.httpPayload + ? ns.getMemberTraits().xmlName ?? ns.getMemberName() + : traits.xmlName ?? ns.getName(); + if (!name || !ns.isStructSchema()) { + throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${ns.getName(true)}.`); + } + const structXmlNode = xmlBuilder.XmlNode.of(name); + const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns); + for (const [memberName, memberSchema] of ns.structIterator()) { + const val = value[memberName]; + if (val != null || memberSchema.isIdempotencyToken()) { + if (memberSchema.getMergedTraits().xmlAttribute) { + structXmlNode.addAttribute(memberSchema.getMergedTraits().xmlName ?? memberName, this.writeSimple(memberSchema, val)); + continue; + } + if (memberSchema.isListSchema()) { + this.writeList(memberSchema, val, structXmlNode, xmlns); + } + else if (memberSchema.isMapSchema()) { + this.writeMap(memberSchema, val, structXmlNode, xmlns); + } + else if (memberSchema.isStructSchema()) { + structXmlNode.addChildNode(this.writeStruct(memberSchema, val, xmlns)); + } + else { + const memberNode = xmlBuilder.XmlNode.of(memberSchema.getMergedTraits().xmlName ?? memberSchema.getMemberName()); + this.writeSimpleInto(memberSchema, val, memberNode, xmlns); + structXmlNode.addChildNode(memberNode); + } + } + } + if (xmlns) { + structXmlNode.addAttribute(xmlnsAttr, xmlns); + } + return structXmlNode; + } + writeList(listMember, array, container, parentXmlns) { + if (!listMember.isMemberSchema()) { + throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member list: ${listMember.getName(true)}`); + } + const listTraits = listMember.getMergedTraits(); + const listValueSchema = listMember.getValueSchema(); + const listValueTraits = listValueSchema.getMergedTraits(); + const sparse = !!listValueTraits.sparse; + const flat = !!listTraits.xmlFlattened; + const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(listMember, parentXmlns); + const writeItem = (container, value) => { + if (listValueSchema.isListSchema()) { + this.writeList(listValueSchema, Array.isArray(value) ? value : [value], container, xmlns); + } + else if (listValueSchema.isMapSchema()) { + this.writeMap(listValueSchema, value, container, xmlns); + } + else if (listValueSchema.isStructSchema()) { + const struct = this.writeStruct(listValueSchema, value, xmlns); + container.addChildNode(struct.withName(flat ? listTraits.xmlName ?? listMember.getMemberName() : listValueTraits.xmlName ?? "member")); + } + else { + const listItemNode = xmlBuilder.XmlNode.of(flat ? listTraits.xmlName ?? listMember.getMemberName() : listValueTraits.xmlName ?? "member"); + this.writeSimpleInto(listValueSchema, value, listItemNode, xmlns); + container.addChildNode(listItemNode); + } + }; + if (flat) { + for (const value of array) { + if (sparse || value != null) { + writeItem(container, value); + } + } + } + else { + const listNode = xmlBuilder.XmlNode.of(listTraits.xmlName ?? listMember.getMemberName()); + if (xmlns) { + listNode.addAttribute(xmlnsAttr, xmlns); + } + for (const value of array) { + if (sparse || value != null) { + writeItem(listNode, value); + } + } + container.addChildNode(listNode); + } + } + writeMap(mapMember, map, container, parentXmlns, containerIsMap = false) { + if (!mapMember.isMemberSchema()) { + throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member map: ${mapMember.getName(true)}`); + } + const mapTraits = mapMember.getMergedTraits(); + const mapKeySchema = mapMember.getKeySchema(); + const mapKeyTraits = mapKeySchema.getMergedTraits(); + const keyTag = mapKeyTraits.xmlName ?? "key"; + const mapValueSchema = mapMember.getValueSchema(); + const mapValueTraits = mapValueSchema.getMergedTraits(); + const valueTag = mapValueTraits.xmlName ?? "value"; + const sparse = !!mapValueTraits.sparse; + const flat = !!mapTraits.xmlFlattened; + const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(mapMember, parentXmlns); + const addKeyValue = (entry, key, val) => { + const keyNode = xmlBuilder.XmlNode.of(keyTag, key); + const [keyXmlnsAttr, keyXmlns] = this.getXmlnsAttribute(mapKeySchema, xmlns); + if (keyXmlns) { + keyNode.addAttribute(keyXmlnsAttr, keyXmlns); + } + entry.addChildNode(keyNode); + let valueNode = xmlBuilder.XmlNode.of(valueTag); + if (mapValueSchema.isListSchema()) { + this.writeList(mapValueSchema, val, valueNode, xmlns); + } + else if (mapValueSchema.isMapSchema()) { + this.writeMap(mapValueSchema, val, valueNode, xmlns, true); + } + else if (mapValueSchema.isStructSchema()) { + valueNode = this.writeStruct(mapValueSchema, val, xmlns); + } + else { + this.writeSimpleInto(mapValueSchema, val, valueNode, xmlns); + } + entry.addChildNode(valueNode); + }; + if (flat) { + for (const [key, val] of Object.entries(map)) { + if (sparse || val != null) { + const entry = xmlBuilder.XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName()); + addKeyValue(entry, key, val); + container.addChildNode(entry); + } + } + } + else { + let mapNode; + if (!containerIsMap) { + mapNode = xmlBuilder.XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName()); + if (xmlns) { + mapNode.addAttribute(xmlnsAttr, xmlns); + } + container.addChildNode(mapNode); + } + for (const [key, val] of Object.entries(map)) { + if (sparse || val != null) { + const entry = xmlBuilder.XmlNode.of("entry"); + addKeyValue(entry, key, val); + (containerIsMap ? container : mapNode).addChildNode(entry); + } + } + } + } + writeSimple(_schema, value) { + if (null === value) { + throw new Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value."); + } + const ns = schema.NormalizedSchema.of(_schema); + let nodeContents = null; + if (value && typeof value === "object") { + if (ns.isBlobSchema()) { + nodeContents = (this.serdeContext?.base64Encoder ?? utilBase64.toBase64)(value); + } + else if (ns.isTimestampSchema() && value instanceof Date) { + const format = protocols.determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: + nodeContents = value.toISOString().replace(".000Z", "Z"); + break; + case 6: + nodeContents = smithyClient.dateToUtcString(value); + break; + case 7: + nodeContents = String(value.getTime() / 1000); + break; + default: + console.warn("Missing timestamp format, using http date", value); + nodeContents = smithyClient.dateToUtcString(value); + break; + } + } + else if (ns.isBigDecimalSchema() && value) { + if (value instanceof serde.NumericValue) { + return value.string; + } + return String(value); + } + else if (ns.isMapSchema() || ns.isListSchema()) { + throw new Error("@aws-sdk/core/protocols - xml serializer, cannot call _write() on List/Map schema, call writeList or writeMap() instead."); + } + else { + throw new Error(`@aws-sdk/core/protocols - xml serializer, unhandled schema type for object value and schema: ${ns.getName(true)}`); + } + } + if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isBigIntegerSchema() || ns.isBigDecimalSchema()) { + nodeContents = String(value); + } + if (ns.isStringSchema()) { + if (value === undefined && ns.isIdempotencyToken()) { + nodeContents = serde.generateIdempotencyToken(); + } + else { + nodeContents = String(value); + } + } + if (nodeContents === null) { + throw new Error(`Unhandled schema-value pair ${ns.getName(true)}=${value}`); + } + return nodeContents; + } + writeSimpleInto(_schema, value, into, parentXmlns) { + const nodeContents = this.writeSimple(_schema, value); + const ns = schema.NormalizedSchema.of(_schema); + const content = new xmlBuilder.XmlText(nodeContents); + const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns); + if (xmlns) { + into.addAttribute(xmlnsAttr, xmlns); + } + into.addChildNode(content); + } + getXmlnsAttribute(ns, parentXmlns) { + const traits = ns.getMergedTraits(); + const [prefix, xmlns] = traits.xmlNamespace ?? []; + if (xmlns && xmlns !== parentXmlns) { + return [prefix ? `xmlns:${prefix}` : "xmlns", xmlns]; + } + return [void 0, void 0]; + } +} + +class XmlCodec extends SerdeContextConfig { + settings; + constructor(settings) { + super(); + this.settings = settings; + } + createSerializer() { + const serializer = new XmlShapeSerializer(this.settings); + serializer.setSerdeContext(this.serdeContext); + return serializer; + } + createDeserializer() { + const deserializer = new XmlShapeDeserializer(this.settings); + deserializer.setSerdeContext(this.serdeContext); + return deserializer; + } +} + +class AwsRestXmlProtocol extends protocols.HttpBindingProtocol { + codec; + serializer; + deserializer; + mixin = new ProtocolLib(); + constructor(options) { + super(options); + const settings = { + timestampFormat: { + useTrait: true, + default: 5, + }, + httpBindings: true, + xmlNamespace: options.xmlNamespace, + serviceNamespace: options.defaultNamespace, + }; + this.codec = new XmlCodec(settings); + this.serializer = new protocols.HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings); + this.deserializer = new protocols.HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings); + } + getPayloadCodec() { + return this.codec; + } + getShapeId() { + return "aws.protocols#restXml"; + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + const inputSchema = schema.NormalizedSchema.of(operationSchema.input); + if (!request.headers["content-type"]) { + const contentType = this.mixin.resolveRestContentType(this.getDefaultContentType(), inputSchema); + if (contentType) { + request.headers["content-type"] = contentType; + } + } + if (request.headers["content-type"] === this.getDefaultContentType()) { + if (typeof request.body === "string") { + request.body = '' + request.body; + } + } + return request; + } + async deserializeResponse(operationSchema, context, response) { + return super.deserializeResponse(operationSchema, context, response); + } + async handleError(operationSchema, context, response, dataObject, metadata) { + const errorIdentifier = loadRestXmlErrorCode(response, dataObject) ?? "Unknown"; + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata); + const ns = schema.NormalizedSchema.of(errorSchema); + const message = dataObject.Error?.message ?? dataObject.Error?.Message ?? dataObject.message ?? dataObject.Message ?? "Unknown"; + const ErrorCtor = schema.TypeRegistry.for(errorSchema[1]).getErrorCtor(errorSchema) ?? Error; + const exception = new ErrorCtor(message); + await this.deserializeHttpMessage(errorSchema, context, response, dataObject); + const output = {}; + for (const [name, member] of ns.structIterator()) { + const target = member.getMergedTraits().xmlName ?? name; + const value = dataObject.Error?.[target] ?? dataObject[target]; + output[name] = this.codec.createDeserializer().readSchema(member, value); + } + throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message, + }, output), dataObject); + } + getDefaultContentType() { + return "application/xml"; + } +} + +exports.AwsEc2QueryProtocol = AwsEc2QueryProtocol; +exports.AwsJson1_0Protocol = AwsJson1_0Protocol; +exports.AwsJson1_1Protocol = AwsJson1_1Protocol; +exports.AwsJsonRpcProtocol = AwsJsonRpcProtocol; +exports.AwsQueryProtocol = AwsQueryProtocol; +exports.AwsRestJsonProtocol = AwsRestJsonProtocol; +exports.AwsRestXmlProtocol = AwsRestXmlProtocol; +exports.AwsSmithyRpcV2CborProtocol = AwsSmithyRpcV2CborProtocol; +exports.JsonCodec = JsonCodec; +exports.JsonShapeDeserializer = JsonShapeDeserializer; +exports.JsonShapeSerializer = JsonShapeSerializer; +exports.XmlCodec = XmlCodec; +exports.XmlShapeDeserializer = XmlShapeDeserializer; +exports.XmlShapeSerializer = XmlShapeSerializer; +exports._toBool = _toBool; +exports._toNum = _toNum; +exports._toStr = _toStr; +exports.awsExpectUnion = awsExpectUnion; +exports.loadRestJsonErrorCode = loadRestJsonErrorCode; +exports.loadRestXmlErrorCode = loadRestXmlErrorCode; +exports.parseJsonBody = parseJsonBody; +exports.parseJsonErrorBody = parseJsonErrorBody; +exports.parseXmlBody = parseXmlBody; +exports.parseXmlErrorBody = parseXmlErrorBody; diff --git a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/protocol-http/dist-cjs/index.js new file mode 100644 index 00000000..52303c3b --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/protocol-http/dist-cjs/index.js @@ -0,0 +1,169 @@ +'use strict'; + +var types = require('@smithy/types'); + +const getHttpHandlerExtensionConfiguration = (runtimeConfig) => { + return { + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); + }, + }; +}; +const resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler(), + }; +}; + +class Field { + name; + kind; + values; + constructor({ name, kind = types.FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; + } + add(value) { + this.values.push(value); + } + set(values) { + this.values = values; + } + remove(value) { + this.values = this.values.filter((v) => v !== value); + } + toString() { + return this.values.map((v) => (v.includes(",") || v.includes(" ") ? `"${v}"` : v)).join(", "); + } + get() { + return this.values; + } +} + +class Fields { + entries = {}; + encoding; + constructor({ fields = [], encoding = "utf-8" }) { + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + setField(field) { + this.entries[field.name.toLowerCase()] = field; + } + getField(name) { + return this.entries[name.toLowerCase()]; + } + removeField(name) { + delete this.entries[name.toLowerCase()]; + } + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } +} + +class HttpRequest { + method; + protocol; + hostname; + port; + path; + query; + headers; + username; + password; + fragment; + body; + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol + ? options.protocol.slice(-1) !== ":" + ? `${options.protocol}:` + : options.protocol + : "https:"; + this.path = options.path ? (options.path.charAt(0) !== "/" ? `/${options.path}` : options.path) : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + static clone(request) { + const cloned = new HttpRequest({ + ...request, + headers: { ...request.headers }, + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); + } + return cloned; + } + static isInstance(request) { + if (!request) { + return false; + } + const req = request; + return ("method" in req && + "protocol" in req && + "hostname" in req && + "path" in req && + typeof req["query"] === "object" && + typeof req["headers"] === "object"); + } + clone() { + return HttpRequest.clone(this); + } +} +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param, + }; + }, {}); +} + +class HttpResponse { + statusCode; + reason; + headers; + body; + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) + return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + } +} + +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} + +exports.Field = Field; +exports.Fields = Fields; +exports.HttpRequest = HttpRequest; +exports.HttpResponse = HttpResponse; +exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration; +exports.isValidHostname = isValidHostname; +exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/dist-cjs/index.js new file mode 100644 index 00000000..362d7f30 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/dist-cjs/index.js @@ -0,0 +1,556 @@ +'use strict'; + +var utilHexEncoding = require('@smithy/util-hex-encoding'); +var utilUtf8 = require('@smithy/util-utf8'); +var isArrayBuffer = require('@smithy/is-array-buffer'); +var protocolHttp = require('@smithy/protocol-http'); +var utilMiddleware = require('@smithy/util-middleware'); +var utilUriEscape = require('@smithy/util-uri-escape'); + +const ALGORITHM_QUERY_PARAM = "X-Amz-Algorithm"; +const CREDENTIAL_QUERY_PARAM = "X-Amz-Credential"; +const AMZ_DATE_QUERY_PARAM = "X-Amz-Date"; +const SIGNED_HEADERS_QUERY_PARAM = "X-Amz-SignedHeaders"; +const EXPIRES_QUERY_PARAM = "X-Amz-Expires"; +const SIGNATURE_QUERY_PARAM = "X-Amz-Signature"; +const TOKEN_QUERY_PARAM = "X-Amz-Security-Token"; +const REGION_SET_PARAM = "X-Amz-Region-Set"; +const AUTH_HEADER = "authorization"; +const AMZ_DATE_HEADER = AMZ_DATE_QUERY_PARAM.toLowerCase(); +const DATE_HEADER = "date"; +const GENERATED_HEADERS = [AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER]; +const SIGNATURE_HEADER = SIGNATURE_QUERY_PARAM.toLowerCase(); +const SHA256_HEADER = "x-amz-content-sha256"; +const TOKEN_HEADER = TOKEN_QUERY_PARAM.toLowerCase(); +const HOST_HEADER = "host"; +const ALWAYS_UNSIGNABLE_HEADERS = { + authorization: true, + "cache-control": true, + connection: true, + expect: true, + from: true, + "keep-alive": true, + "max-forwards": true, + pragma: true, + referer: true, + te: true, + trailer: true, + "transfer-encoding": true, + upgrade: true, + "user-agent": true, + "x-amzn-trace-id": true, +}; +const PROXY_HEADER_PATTERN = /^proxy-/; +const SEC_HEADER_PATTERN = /^sec-/; +const UNSIGNABLE_PATTERNS = [/^proxy-/i, /^sec-/i]; +const ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256"; +const ALGORITHM_IDENTIFIER_V4A = "AWS4-ECDSA-P256-SHA256"; +const EVENT_ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256-PAYLOAD"; +const UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD"; +const MAX_CACHE_SIZE = 50; +const KEY_TYPE_IDENTIFIER = "aws4_request"; +const MAX_PRESIGNED_TTL = 60 * 60 * 24 * 7; + +const signingKeyCache = {}; +const cacheQueue = []; +const createScope = (shortDate, region, service) => `${shortDate}/${region}/${service}/${KEY_TYPE_IDENTIFIER}`; +const getSigningKey = async (sha256Constructor, credentials, shortDate, region, service) => { + const credsHash = await hmac(sha256Constructor, credentials.secretAccessKey, credentials.accessKeyId); + const cacheKey = `${shortDate}:${region}:${service}:${utilHexEncoding.toHex(credsHash)}:${credentials.sessionToken}`; + if (cacheKey in signingKeyCache) { + return signingKeyCache[cacheKey]; + } + cacheQueue.push(cacheKey); + while (cacheQueue.length > MAX_CACHE_SIZE) { + delete signingKeyCache[cacheQueue.shift()]; + } + let key = `AWS4${credentials.secretAccessKey}`; + for (const signable of [shortDate, region, service, KEY_TYPE_IDENTIFIER]) { + key = await hmac(sha256Constructor, key, signable); + } + return (signingKeyCache[cacheKey] = key); +}; +const clearCredentialCache = () => { + cacheQueue.length = 0; + Object.keys(signingKeyCache).forEach((cacheKey) => { + delete signingKeyCache[cacheKey]; + }); +}; +const hmac = (ctor, secret, data) => { + const hash = new ctor(secret); + hash.update(utilUtf8.toUint8Array(data)); + return hash.digest(); +}; + +const getCanonicalHeaders = ({ headers }, unsignableHeaders, signableHeaders) => { + const canonical = {}; + for (const headerName of Object.keys(headers).sort()) { + if (headers[headerName] == undefined) { + continue; + } + const canonicalHeaderName = headerName.toLowerCase(); + if (canonicalHeaderName in ALWAYS_UNSIGNABLE_HEADERS || + unsignableHeaders?.has(canonicalHeaderName) || + PROXY_HEADER_PATTERN.test(canonicalHeaderName) || + SEC_HEADER_PATTERN.test(canonicalHeaderName)) { + if (!signableHeaders || (signableHeaders && !signableHeaders.has(canonicalHeaderName))) { + continue; + } + } + canonical[canonicalHeaderName] = headers[headerName].trim().replace(/\s+/g, " "); + } + return canonical; +}; + +const getPayloadHash = async ({ headers, body }, hashConstructor) => { + for (const headerName of Object.keys(headers)) { + if (headerName.toLowerCase() === SHA256_HEADER) { + return headers[headerName]; + } + } + if (body == undefined) { + return "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; + } + else if (typeof body === "string" || ArrayBuffer.isView(body) || isArrayBuffer.isArrayBuffer(body)) { + const hashCtor = new hashConstructor(); + hashCtor.update(utilUtf8.toUint8Array(body)); + return utilHexEncoding.toHex(await hashCtor.digest()); + } + return UNSIGNED_PAYLOAD; +}; + +class HeaderFormatter { + format(headers) { + const chunks = []; + for (const headerName of Object.keys(headers)) { + const bytes = utilUtf8.fromUtf8(headerName); + chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName])); + } + const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0)); + let position = 0; + for (const chunk of chunks) { + out.set(chunk, position); + position += chunk.byteLength; + } + return out; + } + formatHeaderValue(header) { + switch (header.type) { + case "boolean": + return Uint8Array.from([header.value ? 0 : 1]); + case "byte": + return Uint8Array.from([2, header.value]); + case "short": + const shortView = new DataView(new ArrayBuffer(3)); + shortView.setUint8(0, 3); + shortView.setInt16(1, header.value, false); + return new Uint8Array(shortView.buffer); + case "integer": + const intView = new DataView(new ArrayBuffer(5)); + intView.setUint8(0, 4); + intView.setInt32(1, header.value, false); + return new Uint8Array(intView.buffer); + case "long": + const longBytes = new Uint8Array(9); + longBytes[0] = 5; + longBytes.set(header.value.bytes, 1); + return longBytes; + case "binary": + const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength)); + binView.setUint8(0, 6); + binView.setUint16(1, header.value.byteLength, false); + const binBytes = new Uint8Array(binView.buffer); + binBytes.set(header.value, 3); + return binBytes; + case "string": + const utf8Bytes = utilUtf8.fromUtf8(header.value); + const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength)); + strView.setUint8(0, 7); + strView.setUint16(1, utf8Bytes.byteLength, false); + const strBytes = new Uint8Array(strView.buffer); + strBytes.set(utf8Bytes, 3); + return strBytes; + case "timestamp": + const tsBytes = new Uint8Array(9); + tsBytes[0] = 8; + tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1); + return tsBytes; + case "uuid": + if (!UUID_PATTERN.test(header.value)) { + throw new Error(`Invalid UUID received: ${header.value}`); + } + const uuidBytes = new Uint8Array(17); + uuidBytes[0] = 9; + uuidBytes.set(utilHexEncoding.fromHex(header.value.replace(/\-/g, "")), 1); + return uuidBytes; + } + } +} +const UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; +class Int64 { + bytes; + constructor(bytes) { + this.bytes = bytes; + if (bytes.byteLength !== 8) { + throw new Error("Int64 buffers must be exactly 8 bytes"); + } + } + static fromNumber(number) { + if (number > 9_223_372_036_854_775_807 || number < -9223372036854776e3) { + throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`); + } + const bytes = new Uint8Array(8); + for (let i = 7, remaining = Math.abs(Math.round(number)); i > -1 && remaining > 0; i--, remaining /= 256) { + bytes[i] = remaining; + } + if (number < 0) { + negate(bytes); + } + return new Int64(bytes); + } + valueOf() { + const bytes = this.bytes.slice(0); + const negative = bytes[0] & 0b10000000; + if (negative) { + negate(bytes); + } + return parseInt(utilHexEncoding.toHex(bytes), 16) * (negative ? -1 : 1); + } + toString() { + return String(this.valueOf()); + } +} +function negate(bytes) { + for (let i = 0; i < 8; i++) { + bytes[i] ^= 0xff; + } + for (let i = 7; i > -1; i--) { + bytes[i]++; + if (bytes[i] !== 0) + break; + } +} + +const hasHeader = (soughtHeader, headers) => { + soughtHeader = soughtHeader.toLowerCase(); + for (const headerName of Object.keys(headers)) { + if (soughtHeader === headerName.toLowerCase()) { + return true; + } + } + return false; +}; + +const moveHeadersToQuery = (request, options = {}) => { + const { headers, query = {} } = protocolHttp.HttpRequest.clone(request); + for (const name of Object.keys(headers)) { + const lname = name.toLowerCase(); + if ((lname.slice(0, 6) === "x-amz-" && !options.unhoistableHeaders?.has(lname)) || + options.hoistableHeaders?.has(lname)) { + query[name] = headers[name]; + delete headers[name]; + } + } + return { + ...request, + headers, + query, + }; +}; + +const prepareRequest = (request) => { + request = protocolHttp.HttpRequest.clone(request); + for (const headerName of Object.keys(request.headers)) { + if (GENERATED_HEADERS.indexOf(headerName.toLowerCase()) > -1) { + delete request.headers[headerName]; + } + } + return request; +}; + +const getCanonicalQuery = ({ query = {} }) => { + const keys = []; + const serialized = {}; + for (const key of Object.keys(query)) { + if (key.toLowerCase() === SIGNATURE_HEADER) { + continue; + } + const encodedKey = utilUriEscape.escapeUri(key); + keys.push(encodedKey); + const value = query[key]; + if (typeof value === "string") { + serialized[encodedKey] = `${encodedKey}=${utilUriEscape.escapeUri(value)}`; + } + else if (Array.isArray(value)) { + serialized[encodedKey] = value + .slice(0) + .reduce((encoded, value) => encoded.concat([`${encodedKey}=${utilUriEscape.escapeUri(value)}`]), []) + .sort() + .join("&"); + } + } + return keys + .sort() + .map((key) => serialized[key]) + .filter((serialized) => serialized) + .join("&"); +}; + +const iso8601 = (time) => toDate(time) + .toISOString() + .replace(/\.\d{3}Z$/, "Z"); +const toDate = (time) => { + if (typeof time === "number") { + return new Date(time * 1000); + } + if (typeof time === "string") { + if (Number(time)) { + return new Date(Number(time) * 1000); + } + return new Date(time); + } + return time; +}; + +class SignatureV4Base { + service; + regionProvider; + credentialProvider; + sha256; + uriEscapePath; + applyChecksum; + constructor({ applyChecksum, credentials, region, service, sha256, uriEscapePath = true, }) { + this.service = service; + this.sha256 = sha256; + this.uriEscapePath = uriEscapePath; + this.applyChecksum = typeof applyChecksum === "boolean" ? applyChecksum : true; + this.regionProvider = utilMiddleware.normalizeProvider(region); + this.credentialProvider = utilMiddleware.normalizeProvider(credentials); + } + createCanonicalRequest(request, canonicalHeaders, payloadHash) { + const sortedHeaders = Object.keys(canonicalHeaders).sort(); + return `${request.method} +${this.getCanonicalPath(request)} +${getCanonicalQuery(request)} +${sortedHeaders.map((name) => `${name}:${canonicalHeaders[name]}`).join("\n")} + +${sortedHeaders.join(";")} +${payloadHash}`; + } + async createStringToSign(longDate, credentialScope, canonicalRequest, algorithmIdentifier) { + const hash = new this.sha256(); + hash.update(utilUtf8.toUint8Array(canonicalRequest)); + const hashedRequest = await hash.digest(); + return `${algorithmIdentifier} +${longDate} +${credentialScope} +${utilHexEncoding.toHex(hashedRequest)}`; + } + getCanonicalPath({ path }) { + if (this.uriEscapePath) { + const normalizedPathSegments = []; + for (const pathSegment of path.split("/")) { + if (pathSegment?.length === 0) + continue; + if (pathSegment === ".") + continue; + if (pathSegment === "..") { + normalizedPathSegments.pop(); + } + else { + normalizedPathSegments.push(pathSegment); + } + } + const normalizedPath = `${path?.startsWith("/") ? "/" : ""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length > 0 && path?.endsWith("/") ? "/" : ""}`; + const doubleEncoded = utilUriEscape.escapeUri(normalizedPath); + return doubleEncoded.replace(/%2F/g, "/"); + } + return path; + } + validateResolvedCredentials(credentials) { + if (typeof credentials !== "object" || + typeof credentials.accessKeyId !== "string" || + typeof credentials.secretAccessKey !== "string") { + throw new Error("Resolved credential object is not valid"); + } + } + formatDate(now) { + const longDate = iso8601(now).replace(/[\-:]/g, ""); + return { + longDate, + shortDate: longDate.slice(0, 8), + }; + } + getCanonicalHeaderList(headers) { + return Object.keys(headers).sort().join(";"); + } +} + +class SignatureV4 extends SignatureV4Base { + headerFormatter = new HeaderFormatter(); + constructor({ applyChecksum, credentials, region, service, sha256, uriEscapePath = true, }) { + super({ + applyChecksum, + credentials, + region, + service, + sha256, + uriEscapePath, + }); + } + async presign(originalRequest, options = {}) { + const { signingDate = new Date(), expiresIn = 3600, unsignableHeaders, unhoistableHeaders, signableHeaders, hoistableHeaders, signingRegion, signingService, } = options; + const credentials = await this.credentialProvider(); + this.validateResolvedCredentials(credentials); + const region = signingRegion ?? (await this.regionProvider()); + const { longDate, shortDate } = this.formatDate(signingDate); + if (expiresIn > MAX_PRESIGNED_TTL) { + return Promise.reject("Signature version 4 presigned URLs" + " must have an expiration date less than one week in" + " the future"); + } + const scope = createScope(shortDate, region, signingService ?? this.service); + const request = moveHeadersToQuery(prepareRequest(originalRequest), { unhoistableHeaders, hoistableHeaders }); + if (credentials.sessionToken) { + request.query[TOKEN_QUERY_PARAM] = credentials.sessionToken; + } + request.query[ALGORITHM_QUERY_PARAM] = ALGORITHM_IDENTIFIER; + request.query[CREDENTIAL_QUERY_PARAM] = `${credentials.accessKeyId}/${scope}`; + request.query[AMZ_DATE_QUERY_PARAM] = longDate; + request.query[EXPIRES_QUERY_PARAM] = expiresIn.toString(10); + const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders); + request.query[SIGNED_HEADERS_QUERY_PARAM] = this.getCanonicalHeaderList(canonicalHeaders); + request.query[SIGNATURE_QUERY_PARAM] = await this.getSignature(longDate, scope, this.getSigningKey(credentials, region, shortDate, signingService), this.createCanonicalRequest(request, canonicalHeaders, await getPayloadHash(originalRequest, this.sha256))); + return request; + } + async sign(toSign, options) { + if (typeof toSign === "string") { + return this.signString(toSign, options); + } + else if (toSign.headers && toSign.payload) { + return this.signEvent(toSign, options); + } + else if (toSign.message) { + return this.signMessage(toSign, options); + } + else { + return this.signRequest(toSign, options); + } + } + async signEvent({ headers, payload }, { signingDate = new Date(), priorSignature, signingRegion, signingService }) { + const region = signingRegion ?? (await this.regionProvider()); + const { shortDate, longDate } = this.formatDate(signingDate); + const scope = createScope(shortDate, region, signingService ?? this.service); + const hashedPayload = await getPayloadHash({ headers: {}, body: payload }, this.sha256); + const hash = new this.sha256(); + hash.update(headers); + const hashedHeaders = utilHexEncoding.toHex(await hash.digest()); + const stringToSign = [ + EVENT_ALGORITHM_IDENTIFIER, + longDate, + scope, + priorSignature, + hashedHeaders, + hashedPayload, + ].join("\n"); + return this.signString(stringToSign, { signingDate, signingRegion: region, signingService }); + } + async signMessage(signableMessage, { signingDate = new Date(), signingRegion, signingService }) { + const promise = this.signEvent({ + headers: this.headerFormatter.format(signableMessage.message.headers), + payload: signableMessage.message.body, + }, { + signingDate, + signingRegion, + signingService, + priorSignature: signableMessage.priorSignature, + }); + return promise.then((signature) => { + return { message: signableMessage.message, signature }; + }); + } + async signString(stringToSign, { signingDate = new Date(), signingRegion, signingService } = {}) { + const credentials = await this.credentialProvider(); + this.validateResolvedCredentials(credentials); + const region = signingRegion ?? (await this.regionProvider()); + const { shortDate } = this.formatDate(signingDate); + const hash = new this.sha256(await this.getSigningKey(credentials, region, shortDate, signingService)); + hash.update(utilUtf8.toUint8Array(stringToSign)); + return utilHexEncoding.toHex(await hash.digest()); + } + async signRequest(requestToSign, { signingDate = new Date(), signableHeaders, unsignableHeaders, signingRegion, signingService, } = {}) { + const credentials = await this.credentialProvider(); + this.validateResolvedCredentials(credentials); + const region = signingRegion ?? (await this.regionProvider()); + const request = prepareRequest(requestToSign); + const { longDate, shortDate } = this.formatDate(signingDate); + const scope = createScope(shortDate, region, signingService ?? this.service); + request.headers[AMZ_DATE_HEADER] = longDate; + if (credentials.sessionToken) { + request.headers[TOKEN_HEADER] = credentials.sessionToken; + } + const payloadHash = await getPayloadHash(request, this.sha256); + if (!hasHeader(SHA256_HEADER, request.headers) && this.applyChecksum) { + request.headers[SHA256_HEADER] = payloadHash; + } + const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders); + const signature = await this.getSignature(longDate, scope, this.getSigningKey(credentials, region, shortDate, signingService), this.createCanonicalRequest(request, canonicalHeaders, payloadHash)); + request.headers[AUTH_HEADER] = + `${ALGORITHM_IDENTIFIER} ` + + `Credential=${credentials.accessKeyId}/${scope}, ` + + `SignedHeaders=${this.getCanonicalHeaderList(canonicalHeaders)}, ` + + `Signature=${signature}`; + return request; + } + async getSignature(longDate, credentialScope, keyPromise, canonicalRequest) { + const stringToSign = await this.createStringToSign(longDate, credentialScope, canonicalRequest, ALGORITHM_IDENTIFIER); + const hash = new this.sha256(await keyPromise); + hash.update(utilUtf8.toUint8Array(stringToSign)); + return utilHexEncoding.toHex(await hash.digest()); + } + getSigningKey(credentials, region, shortDate, service) { + return getSigningKey(this.sha256, credentials, shortDate, region, service || this.service); + } +} + +const signatureV4aContainer = { + SignatureV4a: null, +}; + +exports.ALGORITHM_IDENTIFIER = ALGORITHM_IDENTIFIER; +exports.ALGORITHM_IDENTIFIER_V4A = ALGORITHM_IDENTIFIER_V4A; +exports.ALGORITHM_QUERY_PARAM = ALGORITHM_QUERY_PARAM; +exports.ALWAYS_UNSIGNABLE_HEADERS = ALWAYS_UNSIGNABLE_HEADERS; +exports.AMZ_DATE_HEADER = AMZ_DATE_HEADER; +exports.AMZ_DATE_QUERY_PARAM = AMZ_DATE_QUERY_PARAM; +exports.AUTH_HEADER = AUTH_HEADER; +exports.CREDENTIAL_QUERY_PARAM = CREDENTIAL_QUERY_PARAM; +exports.DATE_HEADER = DATE_HEADER; +exports.EVENT_ALGORITHM_IDENTIFIER = EVENT_ALGORITHM_IDENTIFIER; +exports.EXPIRES_QUERY_PARAM = EXPIRES_QUERY_PARAM; +exports.GENERATED_HEADERS = GENERATED_HEADERS; +exports.HOST_HEADER = HOST_HEADER; +exports.KEY_TYPE_IDENTIFIER = KEY_TYPE_IDENTIFIER; +exports.MAX_CACHE_SIZE = MAX_CACHE_SIZE; +exports.MAX_PRESIGNED_TTL = MAX_PRESIGNED_TTL; +exports.PROXY_HEADER_PATTERN = PROXY_HEADER_PATTERN; +exports.REGION_SET_PARAM = REGION_SET_PARAM; +exports.SEC_HEADER_PATTERN = SEC_HEADER_PATTERN; +exports.SHA256_HEADER = SHA256_HEADER; +exports.SIGNATURE_HEADER = SIGNATURE_HEADER; +exports.SIGNATURE_QUERY_PARAM = SIGNATURE_QUERY_PARAM; +exports.SIGNED_HEADERS_QUERY_PARAM = SIGNED_HEADERS_QUERY_PARAM; +exports.SignatureV4 = SignatureV4; +exports.SignatureV4Base = SignatureV4Base; +exports.TOKEN_HEADER = TOKEN_HEADER; +exports.TOKEN_QUERY_PARAM = TOKEN_QUERY_PARAM; +exports.UNSIGNABLE_PATTERNS = UNSIGNABLE_PATTERNS; +exports.UNSIGNED_PAYLOAD = UNSIGNED_PAYLOAD; +exports.clearCredentialCache = clearCredentialCache; +exports.createScope = createScope; +exports.getCanonicalHeaders = getCanonicalHeaders; +exports.getCanonicalQuery = getCanonicalQuery; +exports.getPayloadHash = getPayloadHash; +exports.getSigningKey = getSigningKey; +exports.hasHeader = hasHeader; +exports.moveHeadersToQuery = moveHeadersToQuery; +exports.prepareRequest = prepareRequest; +exports.signatureV4aContainer = signatureV4aContainer; diff --git a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/node_modules/@smithy/is-array-buffer/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/node_modules/@smithy/is-array-buffer/dist-cjs/index.js new file mode 100644 index 00000000..3238bb77 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/node_modules/@smithy/is-array-buffer/dist-cjs/index.js @@ -0,0 +1,6 @@ +'use strict'; + +const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) || + Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; + +exports.isArrayBuffer = isArrayBuffer; diff --git a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js new file mode 100644 index 00000000..6d1eb2d1 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js @@ -0,0 +1,38 @@ +'use strict'; + +const SHORT_TO_HEX = {}; +const HEX_TO_SHORT = {}; +for (let i = 0; i < 256; i++) { + let encodedByte = i.toString(16).toLowerCase(); + if (encodedByte.length === 1) { + encodedByte = `0${encodedByte}`; + } + SHORT_TO_HEX[i] = encodedByte; + HEX_TO_SHORT[encodedByte] = i; +} +function fromHex(encoded) { + if (encoded.length % 2 !== 0) { + throw new Error("Hex encoded strings must have an even number length"); + } + const out = new Uint8Array(encoded.length / 2); + for (let i = 0; i < encoded.length; i += 2) { + const encodedByte = encoded.slice(i, i + 2).toLowerCase(); + if (encodedByte in HEX_TO_SHORT) { + out[i / 2] = HEX_TO_SHORT[encodedByte]; + } + else { + throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); + } + } + return out; +} +function toHex(bytes) { + let out = ""; + for (let i = 0; i < bytes.byteLength; i++) { + out += SHORT_TO_HEX[bytes[i]]; + } + return out; +} + +exports.fromHex = fromHex; +exports.toHex = toHex; diff --git a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/node_modules/@smithy/util-uri-escape/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/node_modules/@smithy/util-uri-escape/dist-cjs/index.js new file mode 100644 index 00000000..11f942c3 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/node_modules/@smithy/util-uri-escape/dist-cjs/index.js @@ -0,0 +1,9 @@ +'use strict'; + +const escapeUri = (uri) => encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode); +const hexEncode = (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`; + +const escapeUriPath = (uri) => uri.split("/").map(escapeUri).join("/"); + +exports.escapeUri = escapeUri; +exports.escapeUriPath = escapeUriPath; diff --git a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/smithy-client/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/smithy-client/dist-cjs/index.js new file mode 100644 index 00000000..9f589873 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/smithy-client/dist-cjs/index.js @@ -0,0 +1,589 @@ +'use strict'; + +var middlewareStack = require('@smithy/middleware-stack'); +var protocols = require('@smithy/core/protocols'); +var types = require('@smithy/types'); +var schema = require('@smithy/core/schema'); +var serde = require('@smithy/core/serde'); + +class Client { + config; + middlewareStack = middlewareStack.constructStack(); + initConfig; + handlers; + constructor(config) { + this.config = config; + } + send(command, optionsOrCb, cb) { + const options = typeof optionsOrCb !== "function" ? optionsOrCb : undefined; + const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb; + const useHandlerCache = options === undefined && this.config.cacheMiddleware === true; + let handler; + if (useHandlerCache) { + if (!this.handlers) { + this.handlers = new WeakMap(); + } + const handlers = this.handlers; + if (handlers.has(command.constructor)) { + handler = handlers.get(command.constructor); + } + else { + handler = command.resolveMiddleware(this.middlewareStack, this.config, options); + handlers.set(command.constructor, handler); + } + } + else { + delete this.handlers; + handler = command.resolveMiddleware(this.middlewareStack, this.config, options); + } + if (callback) { + handler(command) + .then((result) => callback(null, result.output), (err) => callback(err)) + .catch(() => { }); + } + else { + return handler(command).then((result) => result.output); + } + } + destroy() { + this.config?.requestHandler?.destroy?.(); + delete this.handlers; + } +} + +const SENSITIVE_STRING$1 = "***SensitiveInformation***"; +function schemaLogFilter(schema$1, data) { + if (data == null) { + return data; + } + const ns = schema.NormalizedSchema.of(schema$1); + if (ns.getMergedTraits().sensitive) { + return SENSITIVE_STRING$1; + } + if (ns.isListSchema()) { + const isSensitive = !!ns.getValueSchema().getMergedTraits().sensitive; + if (isSensitive) { + return SENSITIVE_STRING$1; + } + } + else if (ns.isMapSchema()) { + const isSensitive = !!ns.getKeySchema().getMergedTraits().sensitive || !!ns.getValueSchema().getMergedTraits().sensitive; + if (isSensitive) { + return SENSITIVE_STRING$1; + } + } + else if (ns.isStructSchema() && typeof data === "object") { + const object = data; + const newObject = {}; + for (const [member, memberNs] of ns.structIterator()) { + if (object[member] != null) { + newObject[member] = schemaLogFilter(memberNs, object[member]); + } + } + return newObject; + } + return data; +} + +class Command { + middlewareStack = middlewareStack.constructStack(); + schema; + static classBuilder() { + return new ClassBuilder(); + } + resolveMiddlewareWithContext(clientStack, configuration, options, { middlewareFn, clientName, commandName, inputFilterSensitiveLog, outputFilterSensitiveLog, smithyContext, additionalContext, CommandCtor, }) { + for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options)) { + this.middlewareStack.use(mw); + } + const stack = clientStack.concat(this.middlewareStack); + const { logger } = configuration; + const handlerExecutionContext = { + logger, + clientName, + commandName, + inputFilterSensitiveLog, + outputFilterSensitiveLog, + [types.SMITHY_CONTEXT_KEY]: { + commandInstance: this, + ...smithyContext, + }, + ...additionalContext, + }; + const { requestHandler } = configuration; + return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); + } +} +class ClassBuilder { + _init = () => { }; + _ep = {}; + _middlewareFn = () => []; + _commandName = ""; + _clientName = ""; + _additionalContext = {}; + _smithyContext = {}; + _inputFilterSensitiveLog = undefined; + _outputFilterSensitiveLog = undefined; + _serializer = null; + _deserializer = null; + _operationSchema; + init(cb) { + this._init = cb; + } + ep(endpointParameterInstructions) { + this._ep = endpointParameterInstructions; + return this; + } + m(middlewareSupplier) { + this._middlewareFn = middlewareSupplier; + return this; + } + s(service, operation, smithyContext = {}) { + this._smithyContext = { + service, + operation, + ...smithyContext, + }; + return this; + } + c(additionalContext = {}) { + this._additionalContext = additionalContext; + return this; + } + n(clientName, commandName) { + this._clientName = clientName; + this._commandName = commandName; + return this; + } + f(inputFilter = (_) => _, outputFilter = (_) => _) { + this._inputFilterSensitiveLog = inputFilter; + this._outputFilterSensitiveLog = outputFilter; + return this; + } + ser(serializer) { + this._serializer = serializer; + return this; + } + de(deserializer) { + this._deserializer = deserializer; + return this; + } + sc(operation) { + this._operationSchema = operation; + this._smithyContext.operationSchema = operation; + return this; + } + build() { + const closure = this; + let CommandRef; + return (CommandRef = class extends Command { + input; + static getEndpointParameterInstructions() { + return closure._ep; + } + constructor(...[input]) { + super(); + this.input = input ?? {}; + closure._init(this); + this.schema = closure._operationSchema; + } + resolveMiddleware(stack, configuration, options) { + const op = closure._operationSchema; + const input = op?.[4] ?? op?.input; + const output = op?.[5] ?? op?.output; + return this.resolveMiddlewareWithContext(stack, configuration, options, { + CommandCtor: CommandRef, + middlewareFn: closure._middlewareFn, + clientName: closure._clientName, + commandName: closure._commandName, + inputFilterSensitiveLog: closure._inputFilterSensitiveLog ?? (op ? schemaLogFilter.bind(null, input) : (_) => _), + outputFilterSensitiveLog: closure._outputFilterSensitiveLog ?? (op ? schemaLogFilter.bind(null, output) : (_) => _), + smithyContext: closure._smithyContext, + additionalContext: closure._additionalContext, + }); + } + serialize = closure._serializer; + deserialize = closure._deserializer; + }); + } +} + +const SENSITIVE_STRING = "***SensitiveInformation***"; + +const createAggregatedClient = (commands, Client) => { + for (const command of Object.keys(commands)) { + const CommandCtor = commands[command]; + const methodImpl = async function (args, optionsOrCb, cb) { + const command = new CommandCtor(args); + if (typeof optionsOrCb === "function") { + this.send(command, optionsOrCb); + } + else if (typeof cb === "function") { + if (typeof optionsOrCb !== "object") + throw new Error(`Expected http options but got ${typeof optionsOrCb}`); + this.send(command, optionsOrCb || {}, cb); + } + else { + return this.send(command, optionsOrCb); + } + }; + const methodName = (command[0].toLowerCase() + command.slice(1)).replace(/Command$/, ""); + Client.prototype[methodName] = methodImpl; + } +}; + +class ServiceException extends Error { + $fault; + $response; + $retryable; + $metadata; + constructor(options) { + super(options.message); + Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype); + this.name = options.name; + this.$fault = options.$fault; + this.$metadata = options.$metadata; + } + static isInstance(value) { + if (!value) + return false; + const candidate = value; + return (ServiceException.prototype.isPrototypeOf(candidate) || + (Boolean(candidate.$fault) && + Boolean(candidate.$metadata) && + (candidate.$fault === "client" || candidate.$fault === "server"))); + } + static [Symbol.hasInstance](instance) { + if (!instance) + return false; + const candidate = instance; + if (this === ServiceException) { + return ServiceException.isInstance(instance); + } + if (ServiceException.isInstance(instance)) { + if (candidate.name && this.name) { + return this.prototype.isPrototypeOf(instance) || candidate.name === this.name; + } + return this.prototype.isPrototypeOf(instance); + } + return false; + } +} +const decorateServiceException = (exception, additions = {}) => { + Object.entries(additions) + .filter(([, v]) => v !== undefined) + .forEach(([k, v]) => { + if (exception[k] == undefined || exception[k] === "") { + exception[k] = v; + } + }); + const message = exception.message || exception.Message || "UnknownError"; + exception.message = message; + delete exception.Message; + return exception; +}; + +const throwDefaultError = ({ output, parsedBody, exceptionCtor, errorCode }) => { + const $metadata = deserializeMetadata(output); + const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : undefined; + const response = new exceptionCtor({ + name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || "UnknownError", + $fault: "client", + $metadata, + }); + throw decorateServiceException(response, parsedBody); +}; +const withBaseException = (ExceptionCtor) => { + return ({ output, parsedBody, errorCode }) => { + throwDefaultError({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode }); + }; +}; +const deserializeMetadata = (output) => ({ + httpStatusCode: output.statusCode, + requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], + extendedRequestId: output.headers["x-amz-id-2"], + cfId: output.headers["x-amz-cf-id"], +}); + +const loadConfigsForDefaultMode = (mode) => { + switch (mode) { + case "standard": + return { + retryMode: "standard", + connectionTimeout: 3100, + }; + case "in-region": + return { + retryMode: "standard", + connectionTimeout: 1100, + }; + case "cross-region": + return { + retryMode: "standard", + connectionTimeout: 3100, + }; + case "mobile": + return { + retryMode: "standard", + connectionTimeout: 30000, + }; + default: + return {}; + } +}; + +let warningEmitted = false; +const emitWarningIfUnsupportedVersion = (version) => { + if (version && !warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 16) { + warningEmitted = true; + } +}; + +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + for (const id in types.AlgorithmId) { + const algorithmId = types.AlgorithmId[id]; + if (runtimeConfig[algorithmId] === undefined) { + continue; + } + checksumAlgorithms.push({ + algorithmId: () => algorithmId, + checksumConstructor: () => runtimeConfig[algorithmId], + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getRetryConfiguration = (runtimeConfig) => { + return { + setRetryStrategy(retryStrategy) { + runtimeConfig.retryStrategy = retryStrategy; + }, + retryStrategy() { + return runtimeConfig.retryStrategy; + }, + }; +}; +const resolveRetryRuntimeConfig = (retryStrategyConfiguration) => { + const runtimeConfig = {}; + runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy(); + return runtimeConfig; +}; + +const getDefaultExtensionConfiguration = (runtimeConfig) => { + return Object.assign(getChecksumConfiguration(runtimeConfig), getRetryConfiguration(runtimeConfig)); +}; +const getDefaultClientConfiguration = getDefaultExtensionConfiguration; +const resolveDefaultRuntimeConfig = (config) => { + return Object.assign(resolveChecksumRuntimeConfig(config), resolveRetryRuntimeConfig(config)); +}; + +const getArrayIfSingleItem = (mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray]; + +const getValueFromTextNode = (obj) => { + const textNodeName = "#text"; + for (const key in obj) { + if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== undefined) { + obj[key] = obj[key][textNodeName]; + } + else if (typeof obj[key] === "object" && obj[key] !== null) { + obj[key] = getValueFromTextNode(obj[key]); + } + } + return obj; +}; + +const isSerializableHeaderValue = (value) => { + return value != null; +}; + +class NoOpLogger { + trace() { } + debug() { } + info() { } + warn() { } + error() { } +} + +function map(arg0, arg1, arg2) { + let target; + let filter; + let instructions; + if (typeof arg1 === "undefined" && typeof arg2 === "undefined") { + target = {}; + instructions = arg0; + } + else { + target = arg0; + if (typeof arg1 === "function") { + filter = arg1; + instructions = arg2; + return mapWithFilter(target, filter, instructions); + } + else { + instructions = arg1; + } + } + for (const key of Object.keys(instructions)) { + if (!Array.isArray(instructions[key])) { + target[key] = instructions[key]; + continue; + } + applyInstruction(target, null, instructions, key); + } + return target; +} +const convertMap = (target) => { + const output = {}; + for (const [k, v] of Object.entries(target || {})) { + output[k] = [, v]; + } + return output; +}; +const take = (source, instructions) => { + const out = {}; + for (const key in instructions) { + applyInstruction(out, source, instructions, key); + } + return out; +}; +const mapWithFilter = (target, filter, instructions) => { + return map(target, Object.entries(instructions).reduce((_instructions, [key, value]) => { + if (Array.isArray(value)) { + _instructions[key] = value; + } + else { + if (typeof value === "function") { + _instructions[key] = [filter, value()]; + } + else { + _instructions[key] = [filter, value]; + } + } + return _instructions; + }, {})); +}; +const applyInstruction = (target, source, instructions, targetKey) => { + if (source !== null) { + let instruction = instructions[targetKey]; + if (typeof instruction === "function") { + instruction = [, instruction]; + } + const [filter = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction; + if ((typeof filter === "function" && filter(source[sourceKey])) || (typeof filter !== "function" && !!filter)) { + target[targetKey] = valueFn(source[sourceKey]); + } + return; + } + let [filter, value] = instructions[targetKey]; + if (typeof value === "function") { + let _value; + const defaultFilterPassed = filter === undefined && (_value = value()) != null; + const customFilterPassed = (typeof filter === "function" && !!filter(void 0)) || (typeof filter !== "function" && !!filter); + if (defaultFilterPassed) { + target[targetKey] = _value; + } + else if (customFilterPassed) { + target[targetKey] = value(); + } + } + else { + const defaultFilterPassed = filter === undefined && value != null; + const customFilterPassed = (typeof filter === "function" && !!filter(value)) || (typeof filter !== "function" && !!filter); + if (defaultFilterPassed || customFilterPassed) { + target[targetKey] = value; + } + } +}; +const nonNullish = (_) => _ != null; +const pass = (_) => _; + +const serializeFloat = (value) => { + if (value !== value) { + return "NaN"; + } + switch (value) { + case Infinity: + return "Infinity"; + case -Infinity: + return "-Infinity"; + default: + return value; + } +}; +const serializeDateTime = (date) => date.toISOString().replace(".000Z", "Z"); + +const _json = (obj) => { + if (obj == null) { + return {}; + } + if (Array.isArray(obj)) { + return obj.filter((_) => _ != null).map(_json); + } + if (typeof obj === "object") { + const target = {}; + for (const key of Object.keys(obj)) { + if (obj[key] == null) { + continue; + } + target[key] = _json(obj[key]); + } + return target; + } + return obj; +}; + +Object.defineProperty(exports, "collectBody", { + enumerable: true, + get: function () { return protocols.collectBody; } +}); +Object.defineProperty(exports, "extendedEncodeURIComponent", { + enumerable: true, + get: function () { return protocols.extendedEncodeURIComponent; } +}); +Object.defineProperty(exports, "resolvedPath", { + enumerable: true, + get: function () { return protocols.resolvedPath; } +}); +exports.Client = Client; +exports.Command = Command; +exports.NoOpLogger = NoOpLogger; +exports.SENSITIVE_STRING = SENSITIVE_STRING; +exports.ServiceException = ServiceException; +exports._json = _json; +exports.convertMap = convertMap; +exports.createAggregatedClient = createAggregatedClient; +exports.decorateServiceException = decorateServiceException; +exports.emitWarningIfUnsupportedVersion = emitWarningIfUnsupportedVersion; +exports.getArrayIfSingleItem = getArrayIfSingleItem; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.getDefaultExtensionConfiguration = getDefaultExtensionConfiguration; +exports.getValueFromTextNode = getValueFromTextNode; +exports.isSerializableHeaderValue = isSerializableHeaderValue; +exports.loadConfigsForDefaultMode = loadConfigsForDefaultMode; +exports.map = map; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; +exports.serializeDateTime = serializeDateTime; +exports.serializeFloat = serializeFloat; +exports.take = take; +exports.throwDefaultError = throwDefaultError; +exports.withBaseException = withBaseException; +Object.keys(serde).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return serde[k]; } + }); +}); diff --git a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/types/dist-cjs/index.js new file mode 100644 index 00000000..be6d0e1a --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/types/dist-cjs/index.js @@ -0,0 +1,91 @@ +'use strict'; + +exports.HttpAuthLocation = void 0; +(function (HttpAuthLocation) { + HttpAuthLocation["HEADER"] = "header"; + HttpAuthLocation["QUERY"] = "query"; +})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); + +exports.HttpApiKeyAuthLocation = void 0; +(function (HttpApiKeyAuthLocation) { + HttpApiKeyAuthLocation["HEADER"] = "header"; + HttpApiKeyAuthLocation["QUERY"] = "query"; +})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); + +exports.EndpointURLScheme = void 0; +(function (EndpointURLScheme) { + EndpointURLScheme["HTTP"] = "http"; + EndpointURLScheme["HTTPS"] = "https"; +})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); + +exports.AlgorithmId = void 0; +(function (AlgorithmId) { + AlgorithmId["MD5"] = "md5"; + AlgorithmId["CRC32"] = "crc32"; + AlgorithmId["CRC32C"] = "crc32c"; + AlgorithmId["SHA1"] = "sha1"; + AlgorithmId["SHA256"] = "sha256"; +})(exports.AlgorithmId || (exports.AlgorithmId = {})); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.SHA256, + checksumConstructor: () => runtimeConfig.sha256, + }); + } + if (runtimeConfig.md5 != undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.MD5, + checksumConstructor: () => runtimeConfig.md5, + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getDefaultClientConfiguration = (runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}; +const resolveDefaultRuntimeConfig = (config) => { + return resolveChecksumRuntimeConfig(config); +}; + +exports.FieldPosition = void 0; +(function (FieldPosition) { + FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; + FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; +})(exports.FieldPosition || (exports.FieldPosition = {})); + +const SMITHY_CONTEXT_KEY = "__smithy_context"; + +exports.IniSectionType = void 0; +(function (IniSectionType) { + IniSectionType["PROFILE"] = "profile"; + IniSectionType["SSO_SESSION"] = "sso-session"; + IniSectionType["SERVICES"] = "services"; +})(exports.IniSectionType || (exports.IniSectionType = {})); + +exports.RequestHandlerProtocol = void 0; +(function (RequestHandlerProtocol) { + RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; +})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); + +exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js new file mode 100644 index 00000000..b06a7b87 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromBase64 = void 0; +const util_buffer_from_1 = require("@smithy/util-buffer-from"); +const BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; +const fromBase64 = (input) => { + if ((input.length * 3) % 4 !== 0) { + throw new TypeError(`Incorrect padding on base64 string.`); + } + if (!BASE64_REGEX.exec(input)) { + throw new TypeError(`Invalid base64 string.`); + } + const buffer = (0, util_buffer_from_1.fromString)(input, "base64"); + return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); +}; +exports.fromBase64 = fromBase64; diff --git a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/dist-cjs/index.js new file mode 100644 index 00000000..c095e288 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/dist-cjs/index.js @@ -0,0 +1,19 @@ +'use strict'; + +var fromBase64 = require('./fromBase64'); +var toBase64 = require('./toBase64'); + + + +Object.keys(fromBase64).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return fromBase64[k]; } + }); +}); +Object.keys(toBase64).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return toBase64[k]; } + }); +}); diff --git a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/dist-cjs/toBase64.js b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/dist-cjs/toBase64.js new file mode 100644 index 00000000..0590ce3f --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/dist-cjs/toBase64.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.toBase64 = void 0; +const util_buffer_from_1 = require("@smithy/util-buffer-from"); +const util_utf8_1 = require("@smithy/util-utf8"); +const toBase64 = (_input) => { + let input; + if (typeof _input === "string") { + input = (0, util_utf8_1.fromUtf8)(_input); + } + else { + input = _input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); + } + return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64"); +}; +exports.toBase64 = toBase64; diff --git a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js new file mode 100644 index 00000000..b577c9ca --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js @@ -0,0 +1,20 @@ +'use strict'; + +var isArrayBuffer = require('@smithy/is-array-buffer'); +var buffer = require('buffer'); + +const fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => { + if (!isArrayBuffer.isArrayBuffer(input)) { + throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); + } + return buffer.Buffer.from(input, offset, length); +}; +const fromString = (input, encoding) => { + if (typeof input !== "string") { + throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); + } + return encoding ? buffer.Buffer.from(input, encoding) : buffer.Buffer.from(input); +}; + +exports.fromArrayBuffer = fromArrayBuffer; +exports.fromString = fromString; diff --git a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js new file mode 100644 index 00000000..3238bb77 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js @@ -0,0 +1,6 @@ +'use strict'; + +const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) || + Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; + +exports.isArrayBuffer = isArrayBuffer; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-cjs/index.js new file mode 100644 index 00000000..536f926f --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-cjs/index.js @@ -0,0 +1,204 @@ +'use strict'; + +var propertyProvider = require('@smithy/property-provider'); + +function resolveLogins(logins) { + return Promise.all(Object.keys(logins).reduce((arr, name) => { + const tokenOrProvider = logins[name]; + if (typeof tokenOrProvider === "string") { + arr.push([name, tokenOrProvider]); + } + else { + arr.push(tokenOrProvider().then((token) => [name, token])); + } + return arr; + }, [])).then((resolvedPairs) => resolvedPairs.reduce((logins, [key, value]) => { + logins[key] = value; + return logins; + }, {})); +} + +function fromCognitoIdentity(parameters) { + return async (awsIdentityProperties) => { + parameters.logger?.debug("@aws-sdk/credential-provider-cognito-identity - fromCognitoIdentity"); + const { GetCredentialsForIdentityCommand, CognitoIdentityClient } = await Promise.resolve().then(function () { return require('./loadCognitoIdentity-BPNvueUJ.js'); }); + const fromConfigs = (property) => parameters.clientConfig?.[property] ?? + parameters.parentClientConfig?.[property] ?? + awsIdentityProperties?.callerClientConfig?.[property]; + const { Credentials: { AccessKeyId = throwOnMissingAccessKeyId(parameters.logger), Expiration, SecretKey = throwOnMissingSecretKey(parameters.logger), SessionToken, } = throwOnMissingCredentials(parameters.logger), } = await (parameters.client ?? + new CognitoIdentityClient(Object.assign({}, parameters.clientConfig ?? {}, { + region: fromConfigs("region"), + profile: fromConfigs("profile"), + userAgentAppId: fromConfigs("userAgentAppId"), + }))).send(new GetCredentialsForIdentityCommand({ + CustomRoleArn: parameters.customRoleArn, + IdentityId: parameters.identityId, + Logins: parameters.logins ? await resolveLogins(parameters.logins) : undefined, + })); + return { + identityId: parameters.identityId, + accessKeyId: AccessKeyId, + secretAccessKey: SecretKey, + sessionToken: SessionToken, + expiration: Expiration, + }; + }; +} +function throwOnMissingAccessKeyId(logger) { + throw new propertyProvider.CredentialsProviderError("Response from Amazon Cognito contained no access key ID", { logger }); +} +function throwOnMissingCredentials(logger) { + throw new propertyProvider.CredentialsProviderError("Response from Amazon Cognito contained no credentials", { logger }); +} +function throwOnMissingSecretKey(logger) { + throw new propertyProvider.CredentialsProviderError("Response from Amazon Cognito contained no secret key", { logger }); +} + +const STORE_NAME = "IdentityIds"; +class IndexedDbStorage { + dbName; + constructor(dbName = "aws:cognito-identity-ids") { + this.dbName = dbName; + } + getItem(key) { + return this.withObjectStore("readonly", (store) => { + const req = store.get(key); + return new Promise((resolve) => { + req.onerror = () => resolve(null); + req.onsuccess = () => resolve(req.result ? req.result.value : null); + }); + }).catch(() => null); + } + removeItem(key) { + return this.withObjectStore("readwrite", (store) => { + const req = store.delete(key); + return new Promise((resolve, reject) => { + req.onerror = () => reject(req.error); + req.onsuccess = () => resolve(); + }); + }); + } + setItem(id, value) { + return this.withObjectStore("readwrite", (store) => { + const req = store.put({ id, value }); + return new Promise((resolve, reject) => { + req.onerror = () => reject(req.error); + req.onsuccess = () => resolve(); + }); + }); + } + getDb() { + const openDbRequest = self.indexedDB.open(this.dbName, 1); + return new Promise((resolve, reject) => { + openDbRequest.onsuccess = () => { + resolve(openDbRequest.result); + }; + openDbRequest.onerror = () => { + reject(openDbRequest.error); + }; + openDbRequest.onblocked = () => { + reject(new Error("Unable to access DB")); + }; + openDbRequest.onupgradeneeded = () => { + const db = openDbRequest.result; + db.onerror = () => { + reject(new Error("Failed to create object store")); + }; + db.createObjectStore(STORE_NAME, { keyPath: "id" }); + }; + }); + } + withObjectStore(mode, action) { + return this.getDb().then((db) => { + const tx = db.transaction(STORE_NAME, mode); + tx.oncomplete = () => db.close(); + return new Promise((resolve, reject) => { + tx.onerror = () => reject(tx.error); + resolve(action(tx.objectStore(STORE_NAME))); + }).catch((err) => { + db.close(); + throw err; + }); + }); + } +} + +class InMemoryStorage { + store; + constructor(store = {}) { + this.store = store; + } + getItem(key) { + if (key in this.store) { + return this.store[key]; + } + return null; + } + removeItem(key) { + delete this.store[key]; + } + setItem(key, value) { + this.store[key] = value; + } +} + +const inMemoryStorage = new InMemoryStorage(); +function localStorage() { + if (typeof self === "object" && self.indexedDB) { + return new IndexedDbStorage(); + } + if (typeof window === "object" && window.localStorage) { + return window.localStorage; + } + return inMemoryStorage; +} + +function fromCognitoIdentityPool({ accountId, cache = localStorage(), client, clientConfig, customRoleArn, identityPoolId, logins, userIdentifier = !logins || Object.keys(logins).length === 0 ? "ANONYMOUS" : undefined, logger, parentClientConfig, }) { + logger?.debug("@aws-sdk/credential-provider-cognito-identity - fromCognitoIdentity"); + const cacheKey = userIdentifier + ? `aws:cognito-identity-credentials:${identityPoolId}:${userIdentifier}` + : undefined; + let provider = async (awsIdentityProperties) => { + const { GetIdCommand, CognitoIdentityClient } = await Promise.resolve().then(function () { return require('./loadCognitoIdentity-BPNvueUJ.js'); }); + const fromConfigs = (property) => clientConfig?.[property] ?? + parentClientConfig?.[property] ?? + awsIdentityProperties?.callerClientConfig?.[property]; + const _client = client ?? + new CognitoIdentityClient(Object.assign({}, clientConfig ?? {}, { + region: fromConfigs("region"), + profile: fromConfigs("profile"), + userAgentAppId: fromConfigs("userAgentAppId"), + })); + let identityId = (cacheKey && (await cache.getItem(cacheKey))); + if (!identityId) { + const { IdentityId = throwOnMissingId(logger) } = await _client.send(new GetIdCommand({ + AccountId: accountId, + IdentityPoolId: identityPoolId, + Logins: logins ? await resolveLogins(logins) : undefined, + })); + identityId = IdentityId; + if (cacheKey) { + Promise.resolve(cache.setItem(cacheKey, identityId)).catch(() => { }); + } + } + provider = fromCognitoIdentity({ + client: _client, + customRoleArn, + logins, + identityId, + }); + return provider(awsIdentityProperties); + }; + return (awsIdentityProperties) => provider(awsIdentityProperties).catch(async (err) => { + if (cacheKey) { + Promise.resolve(cache.removeItem(cacheKey)).catch(() => { }); + } + throw err; + }); +} +function throwOnMissingId(logger) { + throw new propertyProvider.CredentialsProviderError("Response from Amazon Cognito contained no identity ID", { logger }); +} + +exports.fromCognitoIdentity = fromCognitoIdentity; +exports.fromCognitoIdentityPool = fromCognitoIdentityPool; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-cjs/loadCognitoIdentity-BPNvueUJ.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-cjs/loadCognitoIdentity-BPNvueUJ.js new file mode 100644 index 00000000..0170766a --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-cjs/loadCognitoIdentity-BPNvueUJ.js @@ -0,0 +1,18 @@ +'use strict'; + +var clientCognitoIdentity = require('@aws-sdk/client-cognito-identity'); + + + +Object.defineProperty(exports, "CognitoIdentityClient", { + enumerable: true, + get: function () { return clientCognitoIdentity.CognitoIdentityClient; } +}); +Object.defineProperty(exports, "GetCredentialsForIdentityCommand", { + enumerable: true, + get: function () { return clientCognitoIdentity.GetCredentialsForIdentityCommand; } +}); +Object.defineProperty(exports, "GetIdCommand", { + enumerable: true, + get: function () { return clientCognitoIdentity.GetIdCommand; } +}); diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-env/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-env/dist-cjs/index.js new file mode 100644 index 00000000..74d76aac --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-provider-env/dist-cjs/index.js @@ -0,0 +1,41 @@ +'use strict'; + +var client = require('@aws-sdk/core/client'); +var propertyProvider = require('@smithy/property-provider'); + +const ENV_KEY = "AWS_ACCESS_KEY_ID"; +const ENV_SECRET = "AWS_SECRET_ACCESS_KEY"; +const ENV_SESSION = "AWS_SESSION_TOKEN"; +const ENV_EXPIRATION = "AWS_CREDENTIAL_EXPIRATION"; +const ENV_CREDENTIAL_SCOPE = "AWS_CREDENTIAL_SCOPE"; +const ENV_ACCOUNT_ID = "AWS_ACCOUNT_ID"; +const fromEnv = (init) => async () => { + init?.logger?.debug("@aws-sdk/credential-provider-env - fromEnv"); + const accessKeyId = process.env[ENV_KEY]; + const secretAccessKey = process.env[ENV_SECRET]; + const sessionToken = process.env[ENV_SESSION]; + const expiry = process.env[ENV_EXPIRATION]; + const credentialScope = process.env[ENV_CREDENTIAL_SCOPE]; + const accountId = process.env[ENV_ACCOUNT_ID]; + if (accessKeyId && secretAccessKey) { + const credentials = { + accessKeyId, + secretAccessKey, + ...(sessionToken && { sessionToken }), + ...(expiry && { expiration: new Date(expiry) }), + ...(credentialScope && { credentialScope }), + ...(accountId && { accountId }), + }; + client.setCredentialFeature(credentials, "CREDENTIALS_ENV_VARS", "g"); + return credentials; + } + throw new propertyProvider.CredentialsProviderError("Unable to find environment variable credentials.", { logger: init?.logger }); +}; + +exports.ENV_ACCOUNT_ID = ENV_ACCOUNT_ID; +exports.ENV_CREDENTIAL_SCOPE = ENV_CREDENTIAL_SCOPE; +exports.ENV_EXPIRATION = ENV_EXPIRATION; +exports.ENV_KEY = ENV_KEY; +exports.ENV_SECRET = ENV_SECRET; +exports.ENV_SESSION = ENV_SESSION; +exports.fromEnv = fromEnv; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/checkUrl.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/checkUrl.js new file mode 100644 index 00000000..c4adb5f9 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/checkUrl.js @@ -0,0 +1,46 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.checkUrl = void 0; +const property_provider_1 = require("@smithy/property-provider"); +const LOOPBACK_CIDR_IPv4 = "127.0.0.0/8"; +const LOOPBACK_CIDR_IPv6 = "::1/128"; +const ECS_CONTAINER_HOST = "169.254.170.2"; +const EKS_CONTAINER_HOST_IPv4 = "169.254.170.23"; +const EKS_CONTAINER_HOST_IPv6 = "[fd00:ec2::23]"; +const checkUrl = (url, logger) => { + if (url.protocol === "https:") { + return; + } + if (url.hostname === ECS_CONTAINER_HOST || + url.hostname === EKS_CONTAINER_HOST_IPv4 || + url.hostname === EKS_CONTAINER_HOST_IPv6) { + return; + } + if (url.hostname.includes("[")) { + if (url.hostname === "[::1]" || url.hostname === "[0000:0000:0000:0000:0000:0000:0000:0001]") { + return; + } + } + else { + if (url.hostname === "localhost") { + return; + } + const ipComponents = url.hostname.split("."); + const inRange = (component) => { + const num = parseInt(component, 10); + return 0 <= num && num <= 255; + }; + if (ipComponents[0] === "127" && + inRange(ipComponents[1]) && + inRange(ipComponents[2]) && + inRange(ipComponents[3]) && + ipComponents.length === 4) { + return; + } + } + throw new property_provider_1.CredentialsProviderError(`URL not accepted. It must either be HTTPS or match one of the following: + - loopback CIDR 127.0.0.0/8 or [::1/128] + - ECS container host 169.254.170.2 + - EKS container host 169.254.170.23 or [fd00:ec2::23]`, { logger }); +}; +exports.checkUrl = checkUrl; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/fromHttp.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/fromHttp.js new file mode 100644 index 00000000..ea602512 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/fromHttp.js @@ -0,0 +1,70 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromHttp = void 0; +const tslib_1 = require("tslib"); +const client_1 = require("@aws-sdk/core/client"); +const node_http_handler_1 = require("@smithy/node-http-handler"); +const property_provider_1 = require("@smithy/property-provider"); +const promises_1 = tslib_1.__importDefault(require("fs/promises")); +const checkUrl_1 = require("./checkUrl"); +const requestHelpers_1 = require("./requestHelpers"); +const retry_wrapper_1 = require("./retry-wrapper"); +const AWS_CONTAINER_CREDENTIALS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"; +const DEFAULT_LINK_LOCAL_HOST = "http://169.254.170.2"; +const AWS_CONTAINER_CREDENTIALS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI"; +const AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE = "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE"; +const AWS_CONTAINER_AUTHORIZATION_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN"; +const fromHttp = (options = {}) => { + options.logger?.debug("@aws-sdk/credential-provider-http - fromHttp"); + let host; + const relative = options.awsContainerCredentialsRelativeUri ?? process.env[AWS_CONTAINER_CREDENTIALS_RELATIVE_URI]; + const full = options.awsContainerCredentialsFullUri ?? process.env[AWS_CONTAINER_CREDENTIALS_FULL_URI]; + const token = options.awsContainerAuthorizationToken ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN]; + const tokenFile = options.awsContainerAuthorizationTokenFile ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE]; + const warn = options.logger?.constructor?.name === "NoOpLogger" || !options.logger?.warn + ? console.warn + : options.logger.warn.bind(options.logger); + if (relative && full) { + warn("@aws-sdk/credential-provider-http: " + + "you have set both awsContainerCredentialsRelativeUri and awsContainerCredentialsFullUri."); + warn("awsContainerCredentialsFullUri will take precedence."); + } + if (token && tokenFile) { + warn("@aws-sdk/credential-provider-http: " + + "you have set both awsContainerAuthorizationToken and awsContainerAuthorizationTokenFile."); + warn("awsContainerAuthorizationToken will take precedence."); + } + if (full) { + host = full; + } + else if (relative) { + host = `${DEFAULT_LINK_LOCAL_HOST}${relative}`; + } + else { + throw new property_provider_1.CredentialsProviderError(`No HTTP credential provider host provided. +Set AWS_CONTAINER_CREDENTIALS_FULL_URI or AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.`, { logger: options.logger }); + } + const url = new URL(host); + (0, checkUrl_1.checkUrl)(url, options.logger); + const requestHandler = node_http_handler_1.NodeHttpHandler.create({ + requestTimeout: options.timeout ?? 1000, + connectionTimeout: options.timeout ?? 1000, + }); + return (0, retry_wrapper_1.retryWrapper)(async () => { + const request = (0, requestHelpers_1.createGetRequest)(url); + if (token) { + request.headers.Authorization = token; + } + else if (tokenFile) { + request.headers.Authorization = (await promises_1.default.readFile(tokenFile)).toString(); + } + try { + const result = await requestHandler.handle(request); + return (0, requestHelpers_1.getCredentials)(result.response).then((creds) => (0, client_1.setCredentialFeature)(creds, "CREDENTIALS_HTTP", "z")); + } + catch (e) { + throw new property_provider_1.CredentialsProviderError(String(e), { logger: options.logger }); + } + }, options.maxRetries ?? 3, options.timeout ?? 1000); +}; +exports.fromHttp = fromHttp; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/requestHelpers.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/requestHelpers.js new file mode 100644 index 00000000..48159a32 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/requestHelpers.js @@ -0,0 +1,53 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createGetRequest = createGetRequest; +exports.getCredentials = getCredentials; +const property_provider_1 = require("@smithy/property-provider"); +const protocol_http_1 = require("@smithy/protocol-http"); +const smithy_client_1 = require("@smithy/smithy-client"); +const util_stream_1 = require("@smithy/util-stream"); +function createGetRequest(url) { + return new protocol_http_1.HttpRequest({ + protocol: url.protocol, + hostname: url.hostname, + port: Number(url.port), + path: url.pathname, + query: Array.from(url.searchParams.entries()).reduce((acc, [k, v]) => { + acc[k] = v; + return acc; + }, {}), + fragment: url.hash, + }); +} +async function getCredentials(response, logger) { + const stream = (0, util_stream_1.sdkStreamMixin)(response.body); + const str = await stream.transformToString(); + if (response.statusCode === 200) { + const parsed = JSON.parse(str); + if (typeof parsed.AccessKeyId !== "string" || + typeof parsed.SecretAccessKey !== "string" || + typeof parsed.Token !== "string" || + typeof parsed.Expiration !== "string") { + throw new property_provider_1.CredentialsProviderError("HTTP credential provider response not of the required format, an object matching: " + + "{ AccessKeyId: string, SecretAccessKey: string, Token: string, Expiration: string(rfc3339) }", { logger }); + } + return { + accessKeyId: parsed.AccessKeyId, + secretAccessKey: parsed.SecretAccessKey, + sessionToken: parsed.Token, + expiration: (0, smithy_client_1.parseRfc3339DateTime)(parsed.Expiration), + }; + } + if (response.statusCode >= 400 && response.statusCode < 500) { + let parsedBody = {}; + try { + parsedBody = JSON.parse(str); + } + catch (e) { } + throw Object.assign(new property_provider_1.CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger }), { + Code: parsedBody.Code, + Message: parsedBody.Message, + }); + } + throw new property_provider_1.CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger }); +} diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/retry-wrapper.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/retry-wrapper.js new file mode 100644 index 00000000..b99b2efa --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/retry-wrapper.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.retryWrapper = void 0; +const retryWrapper = (toRetry, maxRetries, delayMs) => { + return async () => { + for (let i = 0; i < maxRetries; ++i) { + try { + return await toRetry(); + } + catch (e) { + await new Promise((resolve) => setTimeout(resolve, delayMs)); + } + } + return await toRetry(); + }; +}; +exports.retryWrapper = retryWrapper; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/index.js new file mode 100644 index 00000000..0286ea03 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/index.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromHttp = void 0; +var fromHttp_1 = require("./fromHttp/fromHttp"); +Object.defineProperty(exports, "fromHttp", { enumerable: true, get: function () { return fromHttp_1.fromHttp; } }); diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/protocol-http/dist-cjs/index.js new file mode 100644 index 00000000..52303c3b --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/protocol-http/dist-cjs/index.js @@ -0,0 +1,169 @@ +'use strict'; + +var types = require('@smithy/types'); + +const getHttpHandlerExtensionConfiguration = (runtimeConfig) => { + return { + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); + }, + }; +}; +const resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler(), + }; +}; + +class Field { + name; + kind; + values; + constructor({ name, kind = types.FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; + } + add(value) { + this.values.push(value); + } + set(values) { + this.values = values; + } + remove(value) { + this.values = this.values.filter((v) => v !== value); + } + toString() { + return this.values.map((v) => (v.includes(",") || v.includes(" ") ? `"${v}"` : v)).join(", "); + } + get() { + return this.values; + } +} + +class Fields { + entries = {}; + encoding; + constructor({ fields = [], encoding = "utf-8" }) { + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + setField(field) { + this.entries[field.name.toLowerCase()] = field; + } + getField(name) { + return this.entries[name.toLowerCase()]; + } + removeField(name) { + delete this.entries[name.toLowerCase()]; + } + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } +} + +class HttpRequest { + method; + protocol; + hostname; + port; + path; + query; + headers; + username; + password; + fragment; + body; + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol + ? options.protocol.slice(-1) !== ":" + ? `${options.protocol}:` + : options.protocol + : "https:"; + this.path = options.path ? (options.path.charAt(0) !== "/" ? `/${options.path}` : options.path) : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + static clone(request) { + const cloned = new HttpRequest({ + ...request, + headers: { ...request.headers }, + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); + } + return cloned; + } + static isInstance(request) { + if (!request) { + return false; + } + const req = request; + return ("method" in req && + "protocol" in req && + "hostname" in req && + "path" in req && + typeof req["query"] === "object" && + typeof req["headers"] === "object"); + } + clone() { + return HttpRequest.clone(this); + } +} +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param, + }; + }, {}); +} + +class HttpResponse { + statusCode; + reason; + headers; + body; + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) + return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + } +} + +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} + +exports.Field = Field; +exports.Fields = Fields; +exports.HttpRequest = HttpRequest; +exports.HttpResponse = HttpResponse; +exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration; +exports.isValidHostname = isValidHostname; +exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/smithy-client/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/smithy-client/dist-cjs/index.js new file mode 100644 index 00000000..9f589873 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/smithy-client/dist-cjs/index.js @@ -0,0 +1,589 @@ +'use strict'; + +var middlewareStack = require('@smithy/middleware-stack'); +var protocols = require('@smithy/core/protocols'); +var types = require('@smithy/types'); +var schema = require('@smithy/core/schema'); +var serde = require('@smithy/core/serde'); + +class Client { + config; + middlewareStack = middlewareStack.constructStack(); + initConfig; + handlers; + constructor(config) { + this.config = config; + } + send(command, optionsOrCb, cb) { + const options = typeof optionsOrCb !== "function" ? optionsOrCb : undefined; + const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb; + const useHandlerCache = options === undefined && this.config.cacheMiddleware === true; + let handler; + if (useHandlerCache) { + if (!this.handlers) { + this.handlers = new WeakMap(); + } + const handlers = this.handlers; + if (handlers.has(command.constructor)) { + handler = handlers.get(command.constructor); + } + else { + handler = command.resolveMiddleware(this.middlewareStack, this.config, options); + handlers.set(command.constructor, handler); + } + } + else { + delete this.handlers; + handler = command.resolveMiddleware(this.middlewareStack, this.config, options); + } + if (callback) { + handler(command) + .then((result) => callback(null, result.output), (err) => callback(err)) + .catch(() => { }); + } + else { + return handler(command).then((result) => result.output); + } + } + destroy() { + this.config?.requestHandler?.destroy?.(); + delete this.handlers; + } +} + +const SENSITIVE_STRING$1 = "***SensitiveInformation***"; +function schemaLogFilter(schema$1, data) { + if (data == null) { + return data; + } + const ns = schema.NormalizedSchema.of(schema$1); + if (ns.getMergedTraits().sensitive) { + return SENSITIVE_STRING$1; + } + if (ns.isListSchema()) { + const isSensitive = !!ns.getValueSchema().getMergedTraits().sensitive; + if (isSensitive) { + return SENSITIVE_STRING$1; + } + } + else if (ns.isMapSchema()) { + const isSensitive = !!ns.getKeySchema().getMergedTraits().sensitive || !!ns.getValueSchema().getMergedTraits().sensitive; + if (isSensitive) { + return SENSITIVE_STRING$1; + } + } + else if (ns.isStructSchema() && typeof data === "object") { + const object = data; + const newObject = {}; + for (const [member, memberNs] of ns.structIterator()) { + if (object[member] != null) { + newObject[member] = schemaLogFilter(memberNs, object[member]); + } + } + return newObject; + } + return data; +} + +class Command { + middlewareStack = middlewareStack.constructStack(); + schema; + static classBuilder() { + return new ClassBuilder(); + } + resolveMiddlewareWithContext(clientStack, configuration, options, { middlewareFn, clientName, commandName, inputFilterSensitiveLog, outputFilterSensitiveLog, smithyContext, additionalContext, CommandCtor, }) { + for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options)) { + this.middlewareStack.use(mw); + } + const stack = clientStack.concat(this.middlewareStack); + const { logger } = configuration; + const handlerExecutionContext = { + logger, + clientName, + commandName, + inputFilterSensitiveLog, + outputFilterSensitiveLog, + [types.SMITHY_CONTEXT_KEY]: { + commandInstance: this, + ...smithyContext, + }, + ...additionalContext, + }; + const { requestHandler } = configuration; + return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); + } +} +class ClassBuilder { + _init = () => { }; + _ep = {}; + _middlewareFn = () => []; + _commandName = ""; + _clientName = ""; + _additionalContext = {}; + _smithyContext = {}; + _inputFilterSensitiveLog = undefined; + _outputFilterSensitiveLog = undefined; + _serializer = null; + _deserializer = null; + _operationSchema; + init(cb) { + this._init = cb; + } + ep(endpointParameterInstructions) { + this._ep = endpointParameterInstructions; + return this; + } + m(middlewareSupplier) { + this._middlewareFn = middlewareSupplier; + return this; + } + s(service, operation, smithyContext = {}) { + this._smithyContext = { + service, + operation, + ...smithyContext, + }; + return this; + } + c(additionalContext = {}) { + this._additionalContext = additionalContext; + return this; + } + n(clientName, commandName) { + this._clientName = clientName; + this._commandName = commandName; + return this; + } + f(inputFilter = (_) => _, outputFilter = (_) => _) { + this._inputFilterSensitiveLog = inputFilter; + this._outputFilterSensitiveLog = outputFilter; + return this; + } + ser(serializer) { + this._serializer = serializer; + return this; + } + de(deserializer) { + this._deserializer = deserializer; + return this; + } + sc(operation) { + this._operationSchema = operation; + this._smithyContext.operationSchema = operation; + return this; + } + build() { + const closure = this; + let CommandRef; + return (CommandRef = class extends Command { + input; + static getEndpointParameterInstructions() { + return closure._ep; + } + constructor(...[input]) { + super(); + this.input = input ?? {}; + closure._init(this); + this.schema = closure._operationSchema; + } + resolveMiddleware(stack, configuration, options) { + const op = closure._operationSchema; + const input = op?.[4] ?? op?.input; + const output = op?.[5] ?? op?.output; + return this.resolveMiddlewareWithContext(stack, configuration, options, { + CommandCtor: CommandRef, + middlewareFn: closure._middlewareFn, + clientName: closure._clientName, + commandName: closure._commandName, + inputFilterSensitiveLog: closure._inputFilterSensitiveLog ?? (op ? schemaLogFilter.bind(null, input) : (_) => _), + outputFilterSensitiveLog: closure._outputFilterSensitiveLog ?? (op ? schemaLogFilter.bind(null, output) : (_) => _), + smithyContext: closure._smithyContext, + additionalContext: closure._additionalContext, + }); + } + serialize = closure._serializer; + deserialize = closure._deserializer; + }); + } +} + +const SENSITIVE_STRING = "***SensitiveInformation***"; + +const createAggregatedClient = (commands, Client) => { + for (const command of Object.keys(commands)) { + const CommandCtor = commands[command]; + const methodImpl = async function (args, optionsOrCb, cb) { + const command = new CommandCtor(args); + if (typeof optionsOrCb === "function") { + this.send(command, optionsOrCb); + } + else if (typeof cb === "function") { + if (typeof optionsOrCb !== "object") + throw new Error(`Expected http options but got ${typeof optionsOrCb}`); + this.send(command, optionsOrCb || {}, cb); + } + else { + return this.send(command, optionsOrCb); + } + }; + const methodName = (command[0].toLowerCase() + command.slice(1)).replace(/Command$/, ""); + Client.prototype[methodName] = methodImpl; + } +}; + +class ServiceException extends Error { + $fault; + $response; + $retryable; + $metadata; + constructor(options) { + super(options.message); + Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype); + this.name = options.name; + this.$fault = options.$fault; + this.$metadata = options.$metadata; + } + static isInstance(value) { + if (!value) + return false; + const candidate = value; + return (ServiceException.prototype.isPrototypeOf(candidate) || + (Boolean(candidate.$fault) && + Boolean(candidate.$metadata) && + (candidate.$fault === "client" || candidate.$fault === "server"))); + } + static [Symbol.hasInstance](instance) { + if (!instance) + return false; + const candidate = instance; + if (this === ServiceException) { + return ServiceException.isInstance(instance); + } + if (ServiceException.isInstance(instance)) { + if (candidate.name && this.name) { + return this.prototype.isPrototypeOf(instance) || candidate.name === this.name; + } + return this.prototype.isPrototypeOf(instance); + } + return false; + } +} +const decorateServiceException = (exception, additions = {}) => { + Object.entries(additions) + .filter(([, v]) => v !== undefined) + .forEach(([k, v]) => { + if (exception[k] == undefined || exception[k] === "") { + exception[k] = v; + } + }); + const message = exception.message || exception.Message || "UnknownError"; + exception.message = message; + delete exception.Message; + return exception; +}; + +const throwDefaultError = ({ output, parsedBody, exceptionCtor, errorCode }) => { + const $metadata = deserializeMetadata(output); + const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : undefined; + const response = new exceptionCtor({ + name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || "UnknownError", + $fault: "client", + $metadata, + }); + throw decorateServiceException(response, parsedBody); +}; +const withBaseException = (ExceptionCtor) => { + return ({ output, parsedBody, errorCode }) => { + throwDefaultError({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode }); + }; +}; +const deserializeMetadata = (output) => ({ + httpStatusCode: output.statusCode, + requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], + extendedRequestId: output.headers["x-amz-id-2"], + cfId: output.headers["x-amz-cf-id"], +}); + +const loadConfigsForDefaultMode = (mode) => { + switch (mode) { + case "standard": + return { + retryMode: "standard", + connectionTimeout: 3100, + }; + case "in-region": + return { + retryMode: "standard", + connectionTimeout: 1100, + }; + case "cross-region": + return { + retryMode: "standard", + connectionTimeout: 3100, + }; + case "mobile": + return { + retryMode: "standard", + connectionTimeout: 30000, + }; + default: + return {}; + } +}; + +let warningEmitted = false; +const emitWarningIfUnsupportedVersion = (version) => { + if (version && !warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 16) { + warningEmitted = true; + } +}; + +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + for (const id in types.AlgorithmId) { + const algorithmId = types.AlgorithmId[id]; + if (runtimeConfig[algorithmId] === undefined) { + continue; + } + checksumAlgorithms.push({ + algorithmId: () => algorithmId, + checksumConstructor: () => runtimeConfig[algorithmId], + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getRetryConfiguration = (runtimeConfig) => { + return { + setRetryStrategy(retryStrategy) { + runtimeConfig.retryStrategy = retryStrategy; + }, + retryStrategy() { + return runtimeConfig.retryStrategy; + }, + }; +}; +const resolveRetryRuntimeConfig = (retryStrategyConfiguration) => { + const runtimeConfig = {}; + runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy(); + return runtimeConfig; +}; + +const getDefaultExtensionConfiguration = (runtimeConfig) => { + return Object.assign(getChecksumConfiguration(runtimeConfig), getRetryConfiguration(runtimeConfig)); +}; +const getDefaultClientConfiguration = getDefaultExtensionConfiguration; +const resolveDefaultRuntimeConfig = (config) => { + return Object.assign(resolveChecksumRuntimeConfig(config), resolveRetryRuntimeConfig(config)); +}; + +const getArrayIfSingleItem = (mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray]; + +const getValueFromTextNode = (obj) => { + const textNodeName = "#text"; + for (const key in obj) { + if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== undefined) { + obj[key] = obj[key][textNodeName]; + } + else if (typeof obj[key] === "object" && obj[key] !== null) { + obj[key] = getValueFromTextNode(obj[key]); + } + } + return obj; +}; + +const isSerializableHeaderValue = (value) => { + return value != null; +}; + +class NoOpLogger { + trace() { } + debug() { } + info() { } + warn() { } + error() { } +} + +function map(arg0, arg1, arg2) { + let target; + let filter; + let instructions; + if (typeof arg1 === "undefined" && typeof arg2 === "undefined") { + target = {}; + instructions = arg0; + } + else { + target = arg0; + if (typeof arg1 === "function") { + filter = arg1; + instructions = arg2; + return mapWithFilter(target, filter, instructions); + } + else { + instructions = arg1; + } + } + for (const key of Object.keys(instructions)) { + if (!Array.isArray(instructions[key])) { + target[key] = instructions[key]; + continue; + } + applyInstruction(target, null, instructions, key); + } + return target; +} +const convertMap = (target) => { + const output = {}; + for (const [k, v] of Object.entries(target || {})) { + output[k] = [, v]; + } + return output; +}; +const take = (source, instructions) => { + const out = {}; + for (const key in instructions) { + applyInstruction(out, source, instructions, key); + } + return out; +}; +const mapWithFilter = (target, filter, instructions) => { + return map(target, Object.entries(instructions).reduce((_instructions, [key, value]) => { + if (Array.isArray(value)) { + _instructions[key] = value; + } + else { + if (typeof value === "function") { + _instructions[key] = [filter, value()]; + } + else { + _instructions[key] = [filter, value]; + } + } + return _instructions; + }, {})); +}; +const applyInstruction = (target, source, instructions, targetKey) => { + if (source !== null) { + let instruction = instructions[targetKey]; + if (typeof instruction === "function") { + instruction = [, instruction]; + } + const [filter = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction; + if ((typeof filter === "function" && filter(source[sourceKey])) || (typeof filter !== "function" && !!filter)) { + target[targetKey] = valueFn(source[sourceKey]); + } + return; + } + let [filter, value] = instructions[targetKey]; + if (typeof value === "function") { + let _value; + const defaultFilterPassed = filter === undefined && (_value = value()) != null; + const customFilterPassed = (typeof filter === "function" && !!filter(void 0)) || (typeof filter !== "function" && !!filter); + if (defaultFilterPassed) { + target[targetKey] = _value; + } + else if (customFilterPassed) { + target[targetKey] = value(); + } + } + else { + const defaultFilterPassed = filter === undefined && value != null; + const customFilterPassed = (typeof filter === "function" && !!filter(value)) || (typeof filter !== "function" && !!filter); + if (defaultFilterPassed || customFilterPassed) { + target[targetKey] = value; + } + } +}; +const nonNullish = (_) => _ != null; +const pass = (_) => _; + +const serializeFloat = (value) => { + if (value !== value) { + return "NaN"; + } + switch (value) { + case Infinity: + return "Infinity"; + case -Infinity: + return "-Infinity"; + default: + return value; + } +}; +const serializeDateTime = (date) => date.toISOString().replace(".000Z", "Z"); + +const _json = (obj) => { + if (obj == null) { + return {}; + } + if (Array.isArray(obj)) { + return obj.filter((_) => _ != null).map(_json); + } + if (typeof obj === "object") { + const target = {}; + for (const key of Object.keys(obj)) { + if (obj[key] == null) { + continue; + } + target[key] = _json(obj[key]); + } + return target; + } + return obj; +}; + +Object.defineProperty(exports, "collectBody", { + enumerable: true, + get: function () { return protocols.collectBody; } +}); +Object.defineProperty(exports, "extendedEncodeURIComponent", { + enumerable: true, + get: function () { return protocols.extendedEncodeURIComponent; } +}); +Object.defineProperty(exports, "resolvedPath", { + enumerable: true, + get: function () { return protocols.resolvedPath; } +}); +exports.Client = Client; +exports.Command = Command; +exports.NoOpLogger = NoOpLogger; +exports.SENSITIVE_STRING = SENSITIVE_STRING; +exports.ServiceException = ServiceException; +exports._json = _json; +exports.convertMap = convertMap; +exports.createAggregatedClient = createAggregatedClient; +exports.decorateServiceException = decorateServiceException; +exports.emitWarningIfUnsupportedVersion = emitWarningIfUnsupportedVersion; +exports.getArrayIfSingleItem = getArrayIfSingleItem; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.getDefaultExtensionConfiguration = getDefaultExtensionConfiguration; +exports.getValueFromTextNode = getValueFromTextNode; +exports.isSerializableHeaderValue = isSerializableHeaderValue; +exports.loadConfigsForDefaultMode = loadConfigsForDefaultMode; +exports.map = map; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; +exports.serializeDateTime = serializeDateTime; +exports.serializeFloat = serializeFloat; +exports.take = take; +exports.throwDefaultError = throwDefaultError; +exports.withBaseException = withBaseException; +Object.keys(serde).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return serde[k]; } + }); +}); diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-cjs/index.js new file mode 100644 index 00000000..be6d0e1a --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-cjs/index.js @@ -0,0 +1,91 @@ +'use strict'; + +exports.HttpAuthLocation = void 0; +(function (HttpAuthLocation) { + HttpAuthLocation["HEADER"] = "header"; + HttpAuthLocation["QUERY"] = "query"; +})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); + +exports.HttpApiKeyAuthLocation = void 0; +(function (HttpApiKeyAuthLocation) { + HttpApiKeyAuthLocation["HEADER"] = "header"; + HttpApiKeyAuthLocation["QUERY"] = "query"; +})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); + +exports.EndpointURLScheme = void 0; +(function (EndpointURLScheme) { + EndpointURLScheme["HTTP"] = "http"; + EndpointURLScheme["HTTPS"] = "https"; +})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); + +exports.AlgorithmId = void 0; +(function (AlgorithmId) { + AlgorithmId["MD5"] = "md5"; + AlgorithmId["CRC32"] = "crc32"; + AlgorithmId["CRC32C"] = "crc32c"; + AlgorithmId["SHA1"] = "sha1"; + AlgorithmId["SHA256"] = "sha256"; +})(exports.AlgorithmId || (exports.AlgorithmId = {})); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.SHA256, + checksumConstructor: () => runtimeConfig.sha256, + }); + } + if (runtimeConfig.md5 != undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.MD5, + checksumConstructor: () => runtimeConfig.md5, + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getDefaultClientConfiguration = (runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}; +const resolveDefaultRuntimeConfig = (config) => { + return resolveChecksumRuntimeConfig(config); +}; + +exports.FieldPosition = void 0; +(function (FieldPosition) { + FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; + FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; +})(exports.FieldPosition || (exports.FieldPosition = {})); + +const SMITHY_CONTEXT_KEY = "__smithy_context"; + +exports.IniSectionType = void 0; +(function (IniSectionType) { + IniSectionType["PROFILE"] = "profile"; + IniSectionType["SSO_SESSION"] = "sso-session"; + IniSectionType["SERVICES"] = "services"; +})(exports.IniSectionType || (exports.IniSectionType = {})); + +exports.RequestHandlerProtocol = void 0; +(function (RequestHandlerProtocol) { + RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; +})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); + +exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-ini/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-ini/dist-cjs/index.js new file mode 100644 index 00000000..84cef661 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-provider-ini/dist-cjs/index.js @@ -0,0 +1,226 @@ +'use strict'; + +var sharedIniFileLoader = require('@smithy/shared-ini-file-loader'); +var propertyProvider = require('@smithy/property-provider'); +var client = require('@aws-sdk/core/client'); +var credentialProviderLogin = require('@aws-sdk/credential-provider-login'); + +const resolveCredentialSource = (credentialSource, profileName, logger) => { + const sourceProvidersMap = { + EcsContainer: async (options) => { + const { fromHttp } = await import('@aws-sdk/credential-provider-http'); + const { fromContainerMetadata } = await import('@smithy/credential-provider-imds'); + logger?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer"); + return async () => propertyProvider.chain(fromHttp(options ?? {}), fromContainerMetadata(options))().then(setNamedProvider); + }, + Ec2InstanceMetadata: async (options) => { + logger?.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata"); + const { fromInstanceMetadata } = await import('@smithy/credential-provider-imds'); + return async () => fromInstanceMetadata(options)().then(setNamedProvider); + }, + Environment: async (options) => { + logger?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment"); + const { fromEnv } = await import('@aws-sdk/credential-provider-env'); + return async () => fromEnv(options)().then(setNamedProvider); + }, + }; + if (credentialSource in sourceProvidersMap) { + return sourceProvidersMap[credentialSource]; + } + else { + throw new propertyProvider.CredentialsProviderError(`Unsupported credential source in profile ${profileName}. Got ${credentialSource}, ` + + `expected EcsContainer or Ec2InstanceMetadata or Environment.`, { logger }); + } +}; +const setNamedProvider = (creds) => client.setCredentialFeature(creds, "CREDENTIALS_PROFILE_NAMED_PROVIDER", "p"); + +const isAssumeRoleProfile = (arg, { profile = "default", logger } = {}) => { + return (Boolean(arg) && + typeof arg === "object" && + typeof arg.role_arn === "string" && + ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1 && + ["undefined", "string"].indexOf(typeof arg.external_id) > -1 && + ["undefined", "string"].indexOf(typeof arg.mfa_serial) > -1 && + (isAssumeRoleWithSourceProfile(arg, { profile, logger }) || isCredentialSourceProfile(arg, { profile, logger }))); +}; +const isAssumeRoleWithSourceProfile = (arg, { profile, logger }) => { + const withSourceProfile = typeof arg.source_profile === "string" && typeof arg.credential_source === "undefined"; + if (withSourceProfile) { + logger?.debug?.(` ${profile} isAssumeRoleWithSourceProfile source_profile=${arg.source_profile}`); + } + return withSourceProfile; +}; +const isCredentialSourceProfile = (arg, { profile, logger }) => { + const withProviderProfile = typeof arg.credential_source === "string" && typeof arg.source_profile === "undefined"; + if (withProviderProfile) { + logger?.debug?.(` ${profile} isCredentialSourceProfile credential_source=${arg.credential_source}`); + } + return withProviderProfile; +}; +const resolveAssumeRoleCredentials = async (profileName, profiles, options, visitedProfiles = {}, resolveProfileData) => { + options.logger?.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)"); + const profileData = profiles[profileName]; + const { source_profile, region } = profileData; + if (!options.roleAssumer) { + const { getDefaultRoleAssumer } = await import('@aws-sdk/nested-clients/sts'); + options.roleAssumer = getDefaultRoleAssumer({ + ...options.clientConfig, + credentialProviderLogger: options.logger, + parentClientConfig: { + ...options?.parentClientConfig, + region: region ?? options?.parentClientConfig?.region, + }, + }, options.clientPlugins); + } + if (source_profile && source_profile in visitedProfiles) { + throw new propertyProvider.CredentialsProviderError(`Detected a cycle attempting to resolve credentials for profile` + + ` ${sharedIniFileLoader.getProfileName(options)}. Profiles visited: ` + + Object.keys(visitedProfiles).join(", "), { logger: options.logger }); + } + options.logger?.debug(`@aws-sdk/credential-provider-ini - finding credential resolver using ${source_profile ? `source_profile=[${source_profile}]` : `profile=[${profileName}]`}`); + const sourceCredsProvider = source_profile + ? resolveProfileData(source_profile, profiles, options, { + ...visitedProfiles, + [source_profile]: true, + }, isCredentialSourceWithoutRoleArn(profiles[source_profile] ?? {})) + : (await resolveCredentialSource(profileData.credential_source, profileName, options.logger)(options))(); + if (isCredentialSourceWithoutRoleArn(profileData)) { + return sourceCredsProvider.then((creds) => client.setCredentialFeature(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o")); + } + else { + const params = { + RoleArn: profileData.role_arn, + RoleSessionName: profileData.role_session_name || `aws-sdk-js-${Date.now()}`, + ExternalId: profileData.external_id, + DurationSeconds: parseInt(profileData.duration_seconds || "3600", 10), + }; + const { mfa_serial } = profileData; + if (mfa_serial) { + if (!options.mfaCodeProvider) { + throw new propertyProvider.CredentialsProviderError(`Profile ${profileName} requires multi-factor authentication, but no MFA code callback was provided.`, { logger: options.logger, tryNextLink: false }); + } + params.SerialNumber = mfa_serial; + params.TokenCode = await options.mfaCodeProvider(mfa_serial); + } + const sourceCreds = await sourceCredsProvider; + return options.roleAssumer(sourceCreds, params).then((creds) => client.setCredentialFeature(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o")); + } +}; +const isCredentialSourceWithoutRoleArn = (section) => { + return !section.role_arn && !!section.credential_source; +}; + +const isLoginProfile = (data) => { + return Boolean(data && data.login_session); +}; +const resolveLoginCredentials = async (profileName, options) => { + const credentials = await credentialProviderLogin.fromLoginCredentials({ + ...options, + profile: profileName, + })(); + return client.setCredentialFeature(credentials, "CREDENTIALS_PROFILE_LOGIN", "AC"); +}; + +const isProcessProfile = (arg) => Boolean(arg) && typeof arg === "object" && typeof arg.credential_process === "string"; +const resolveProcessCredentials = async (options, profile) => import('@aws-sdk/credential-provider-process').then(({ fromProcess }) => fromProcess({ + ...options, + profile, +})().then((creds) => client.setCredentialFeature(creds, "CREDENTIALS_PROFILE_PROCESS", "v"))); + +const resolveSsoCredentials = async (profile, profileData, options = {}) => { + const { fromSSO } = await import('@aws-sdk/credential-provider-sso'); + return fromSSO({ + profile, + logger: options.logger, + parentClientConfig: options.parentClientConfig, + clientConfig: options.clientConfig, + })().then((creds) => { + if (profileData.sso_session) { + return client.setCredentialFeature(creds, "CREDENTIALS_PROFILE_SSO", "r"); + } + else { + return client.setCredentialFeature(creds, "CREDENTIALS_PROFILE_SSO_LEGACY", "t"); + } + }); +}; +const isSsoProfile = (arg) => arg && + (typeof arg.sso_start_url === "string" || + typeof arg.sso_account_id === "string" || + typeof arg.sso_session === "string" || + typeof arg.sso_region === "string" || + typeof arg.sso_role_name === "string"); + +const isStaticCredsProfile = (arg) => Boolean(arg) && + typeof arg === "object" && + typeof arg.aws_access_key_id === "string" && + typeof arg.aws_secret_access_key === "string" && + ["undefined", "string"].indexOf(typeof arg.aws_session_token) > -1 && + ["undefined", "string"].indexOf(typeof arg.aws_account_id) > -1; +const resolveStaticCredentials = async (profile, options) => { + options?.logger?.debug("@aws-sdk/credential-provider-ini - resolveStaticCredentials"); + const credentials = { + accessKeyId: profile.aws_access_key_id, + secretAccessKey: profile.aws_secret_access_key, + sessionToken: profile.aws_session_token, + ...(profile.aws_credential_scope && { credentialScope: profile.aws_credential_scope }), + ...(profile.aws_account_id && { accountId: profile.aws_account_id }), + }; + return client.setCredentialFeature(credentials, "CREDENTIALS_PROFILE", "n"); +}; + +const isWebIdentityProfile = (arg) => Boolean(arg) && + typeof arg === "object" && + typeof arg.web_identity_token_file === "string" && + typeof arg.role_arn === "string" && + ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1; +const resolveWebIdentityCredentials = async (profile, options) => import('@aws-sdk/credential-provider-web-identity').then(({ fromTokenFile }) => fromTokenFile({ + webIdentityTokenFile: profile.web_identity_token_file, + roleArn: profile.role_arn, + roleSessionName: profile.role_session_name, + roleAssumerWithWebIdentity: options.roleAssumerWithWebIdentity, + logger: options.logger, + parentClientConfig: options.parentClientConfig, +})().then((creds) => client.setCredentialFeature(creds, "CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN", "q"))); + +const resolveProfileData = async (profileName, profiles, options, visitedProfiles = {}, isAssumeRoleRecursiveCall = false) => { + const data = profiles[profileName]; + if (Object.keys(visitedProfiles).length > 0 && isStaticCredsProfile(data)) { + return resolveStaticCredentials(data, options); + } + if (isAssumeRoleRecursiveCall || isAssumeRoleProfile(data, { profile: profileName, logger: options.logger })) { + return resolveAssumeRoleCredentials(profileName, profiles, options, visitedProfiles, resolveProfileData); + } + if (isStaticCredsProfile(data)) { + return resolveStaticCredentials(data, options); + } + if (isWebIdentityProfile(data)) { + return resolveWebIdentityCredentials(data, options); + } + if (isProcessProfile(data)) { + return resolveProcessCredentials(options, profileName); + } + if (isSsoProfile(data)) { + return await resolveSsoCredentials(profileName, data, options); + } + if (isLoginProfile(data)) { + return resolveLoginCredentials(profileName, options); + } + throw new propertyProvider.CredentialsProviderError(`Could not resolve credentials using profile: [${profileName}] in configuration/credentials file(s).`, { logger: options.logger }); +}; + +const fromIni = (_init = {}) => async ({ callerClientConfig } = {}) => { + const init = { + ..._init, + parentClientConfig: { + ...callerClientConfig, + ..._init.parentClientConfig, + }, + }; + init.logger?.debug("@aws-sdk/credential-provider-ini - fromIni"); + const profiles = await sharedIniFileLoader.parseKnownFiles(init); + return resolveProfileData(sharedIniFileLoader.getProfileName({ + profile: _init.profile ?? callerClientConfig?.profile, + }), profiles, init); +}; + +exports.fromIni = fromIni; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-login/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-login/dist-cjs/index.js new file mode 100644 index 00000000..487bc23a --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-provider-login/dist-cjs/index.js @@ -0,0 +1,286 @@ +'use strict'; + +var client = require('@aws-sdk/core/client'); +var propertyProvider = require('@smithy/property-provider'); +var sharedIniFileLoader = require('@smithy/shared-ini-file-loader'); +var protocolHttp = require('@smithy/protocol-http'); +var node_crypto = require('node:crypto'); +var node_fs = require('node:fs'); +var node_os = require('node:os'); +var node_path = require('node:path'); + +class LoginCredentialsFetcher { + profileData; + init; + callerClientConfig; + static REFRESH_THRESHOLD = 5 * 60 * 1000; + constructor(profileData, init, callerClientConfig) { + this.profileData = profileData; + this.init = init; + this.callerClientConfig = callerClientConfig; + } + async loadCredentials() { + const token = await this.loadToken(); + if (!token) { + throw new propertyProvider.CredentialsProviderError(`Failed to load a token for session ${this.loginSession}, please re-authenticate using aws login`, { tryNextLink: false, logger: this.logger }); + } + const accessToken = token.accessToken; + const now = Date.now(); + const expiryTime = new Date(accessToken.expiresAt).getTime(); + const timeUntilExpiry = expiryTime - now; + if (timeUntilExpiry <= LoginCredentialsFetcher.REFRESH_THRESHOLD) { + return this.refresh(token); + } + return { + accessKeyId: accessToken.accessKeyId, + secretAccessKey: accessToken.secretAccessKey, + sessionToken: accessToken.sessionToken, + accountId: accessToken.accountId, + expiration: new Date(accessToken.expiresAt), + }; + } + get logger() { + return this.init?.logger; + } + get loginSession() { + return this.profileData.login_session; + } + async refresh(token) { + const { SigninClient, CreateOAuth2TokenCommand } = await import('@aws-sdk/nested-clients/signin'); + const { logger, userAgentAppId } = this.callerClientConfig ?? {}; + const isH2 = (requestHandler) => { + return requestHandler?.metadata?.handlerProtocol === "h2"; + }; + const requestHandler = isH2(this.callerClientConfig?.requestHandler) + ? undefined + : this.callerClientConfig?.requestHandler; + const region = this.profileData.region ?? (await this.callerClientConfig?.region?.()) ?? process.env.AWS_REGION; + const client = new SigninClient({ + credentials: { + accessKeyId: "", + secretAccessKey: "", + }, + region, + requestHandler, + logger, + userAgentAppId, + ...this.init?.clientConfig, + }); + this.createDPoPInterceptor(client.middlewareStack); + const commandInput = { + tokenInput: { + clientId: token.clientId, + refreshToken: token.refreshToken, + grantType: "refresh_token", + }, + }; + try { + const response = await client.send(new CreateOAuth2TokenCommand(commandInput)); + const { accessKeyId, secretAccessKey, sessionToken } = response.tokenOutput?.accessToken ?? {}; + const { refreshToken, expiresIn } = response.tokenOutput ?? {}; + if (!accessKeyId || !secretAccessKey || !sessionToken || !refreshToken) { + throw new propertyProvider.CredentialsProviderError("Token refresh response missing required fields", { + logger: this.logger, + tryNextLink: false, + }); + } + const expiresInMs = (expiresIn ?? 900) * 1000; + const expiration = new Date(Date.now() + expiresInMs); + const updatedToken = { + ...token, + accessToken: { + ...token.accessToken, + accessKeyId: accessKeyId, + secretAccessKey: secretAccessKey, + sessionToken: sessionToken, + expiresAt: expiration.toISOString(), + }, + refreshToken: refreshToken, + }; + await this.saveToken(updatedToken); + const newAccessToken = updatedToken.accessToken; + return { + accessKeyId: newAccessToken.accessKeyId, + secretAccessKey: newAccessToken.secretAccessKey, + sessionToken: newAccessToken.sessionToken, + accountId: newAccessToken.accountId, + expiration, + }; + } + catch (error) { + if (error.name === "AccessDeniedException") { + const errorType = error.error; + let message; + switch (errorType) { + case "TOKEN_EXPIRED": + message = "Your session has expired. Please reauthenticate."; + break; + case "USER_CREDENTIALS_CHANGED": + message = + "Unable to refresh credentials because of a change in your password. Please reauthenticate with your new password."; + break; + case "INSUFFICIENT_PERMISSIONS": + message = + "Unable to refresh credentials due to insufficient permissions. You may be missing permission for the 'CreateOAuth2Token' action."; + break; + default: + message = `Failed to refresh token: ${String(error)}. Please re-authenticate using \`aws login\``; + } + throw new propertyProvider.CredentialsProviderError(message, { logger: this.logger, tryNextLink: false }); + } + throw new propertyProvider.CredentialsProviderError(`Failed to refresh token: ${String(error)}. Please re-authenticate using aws login`, { logger: this.logger }); + } + } + async loadToken() { + const tokenFilePath = this.getTokenFilePath(); + try { + let tokenData; + try { + tokenData = await sharedIniFileLoader.readFile(tokenFilePath, { ignoreCache: this.init?.ignoreCache }); + } + catch { + tokenData = await node_fs.promises.readFile(tokenFilePath, "utf8"); + } + const token = JSON.parse(tokenData); + const missingFields = ["accessToken", "clientId", "refreshToken", "dpopKey"].filter((k) => !token[k]); + if (!token.accessToken?.accountId) { + missingFields.push("accountId"); + } + if (missingFields.length > 0) { + throw new propertyProvider.CredentialsProviderError(`Token validation failed, missing fields: ${missingFields.join(", ")}`, { + logger: this.logger, + tryNextLink: false, + }); + } + return token; + } + catch (error) { + throw new propertyProvider.CredentialsProviderError(`Failed to load token from ${tokenFilePath}: ${String(error)}`, { + logger: this.logger, + tryNextLink: false, + }); + } + } + async saveToken(token) { + const tokenFilePath = this.getTokenFilePath(); + const directory = node_path.dirname(tokenFilePath); + try { + await node_fs.promises.mkdir(directory, { recursive: true }); + } + catch (error) { + } + await node_fs.promises.writeFile(tokenFilePath, JSON.stringify(token, null, 2), "utf8"); + } + getTokenFilePath() { + const directory = process.env.AWS_LOGIN_CACHE_DIRECTORY ?? node_path.join(node_os.homedir(), ".aws", "login", "cache"); + const loginSessionBytes = Buffer.from(this.loginSession, "utf8"); + const loginSessionSha256 = node_crypto.createHash("sha256").update(loginSessionBytes).digest("hex"); + return node_path.join(directory, `${loginSessionSha256}.json`); + } + derToRawSignature(derSignature) { + let offset = 2; + if (derSignature[offset] !== 0x02) { + throw new Error("Invalid DER signature"); + } + offset++; + const rLength = derSignature[offset++]; + let r = derSignature.subarray(offset, offset + rLength); + offset += rLength; + if (derSignature[offset] !== 0x02) { + throw new Error("Invalid DER signature"); + } + offset++; + const sLength = derSignature[offset++]; + let s = derSignature.subarray(offset, offset + sLength); + r = r[0] === 0x00 ? r.subarray(1) : r; + s = s[0] === 0x00 ? s.subarray(1) : s; + const rPadded = Buffer.concat([Buffer.alloc(32 - r.length), r]); + const sPadded = Buffer.concat([Buffer.alloc(32 - s.length), s]); + return Buffer.concat([rPadded, sPadded]); + } + createDPoPInterceptor(middlewareStack) { + middlewareStack.add((next) => async (args) => { + if (protocolHttp.HttpRequest.isInstance(args.request)) { + const request = args.request; + const actualEndpoint = `${request.protocol}//${request.hostname}${request.port ? `:${request.port}` : ""}${request.path}`; + const dpop = await this.generateDpop(request.method, actualEndpoint); + request.headers = { + ...request.headers, + DPoP: dpop, + }; + } + return next(args); + }, { + step: "finalizeRequest", + name: "dpopInterceptor", + override: true, + }); + } + async generateDpop(method = "POST", endpoint) { + const token = await this.loadToken(); + try { + const privateKey = node_crypto.createPrivateKey({ + key: token.dpopKey, + format: "pem", + type: "sec1", + }); + const publicKey = node_crypto.createPublicKey(privateKey); + const publicDer = publicKey.export({ format: "der", type: "spki" }); + let pointStart = -1; + for (let i = 0; i < publicDer.length; i++) { + if (publicDer[i] === 0x04) { + pointStart = i; + break; + } + } + const x = publicDer.slice(pointStart + 1, pointStart + 33); + const y = publicDer.slice(pointStart + 33, pointStart + 65); + const header = { + alg: "ES256", + typ: "dpop+jwt", + jwk: { + kty: "EC", + crv: "P-256", + x: x.toString("base64url"), + y: y.toString("base64url"), + }, + }; + const payload = { + jti: crypto.randomUUID(), + htm: method, + htu: endpoint, + iat: Math.floor(Date.now() / 1000), + }; + const headerB64 = Buffer.from(JSON.stringify(header)).toString("base64url"); + const payloadB64 = Buffer.from(JSON.stringify(payload)).toString("base64url"); + const message = `${headerB64}.${payloadB64}`; + const asn1Signature = node_crypto.sign("sha256", Buffer.from(message), privateKey); + const rawSignature = this.derToRawSignature(asn1Signature); + const signatureB64 = rawSignature.toString("base64url"); + return `${message}.${signatureB64}`; + } + catch (error) { + throw new propertyProvider.CredentialsProviderError(`Failed to generate Dpop proof: ${error instanceof Error ? error.message : String(error)}`, { logger: this.logger, tryNextLink: false }); + } + } +} + +const fromLoginCredentials = (init) => async ({ callerClientConfig } = {}) => { + init?.logger?.debug?.("@aws-sdk/credential-providers - fromLoginCredentials"); + const profiles = await sharedIniFileLoader.parseKnownFiles(init || {}); + const profileName = sharedIniFileLoader.getProfileName({ + profile: init?.profile ?? callerClientConfig?.profile, + }); + const profile = profiles[profileName]; + if (!profile?.login_session) { + throw new propertyProvider.CredentialsProviderError(`Profile ${profileName} does not contain login_session.`, { + tryNextLink: true, + logger: init?.logger, + }); + } + const fetcher = new LoginCredentialsFetcher(profile, init, callerClientConfig); + const credentials = await fetcher.loadCredentials(); + return client.setCredentialFeature(credentials, "CREDENTIALS_LOGIN", "AD"); +}; + +exports.fromLoginCredentials = fromLoginCredentials; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-login/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-login/node_modules/@smithy/protocol-http/dist-cjs/index.js new file mode 100644 index 00000000..52303c3b --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-provider-login/node_modules/@smithy/protocol-http/dist-cjs/index.js @@ -0,0 +1,169 @@ +'use strict'; + +var types = require('@smithy/types'); + +const getHttpHandlerExtensionConfiguration = (runtimeConfig) => { + return { + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); + }, + }; +}; +const resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler(), + }; +}; + +class Field { + name; + kind; + values; + constructor({ name, kind = types.FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; + } + add(value) { + this.values.push(value); + } + set(values) { + this.values = values; + } + remove(value) { + this.values = this.values.filter((v) => v !== value); + } + toString() { + return this.values.map((v) => (v.includes(",") || v.includes(" ") ? `"${v}"` : v)).join(", "); + } + get() { + return this.values; + } +} + +class Fields { + entries = {}; + encoding; + constructor({ fields = [], encoding = "utf-8" }) { + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + setField(field) { + this.entries[field.name.toLowerCase()] = field; + } + getField(name) { + return this.entries[name.toLowerCase()]; + } + removeField(name) { + delete this.entries[name.toLowerCase()]; + } + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } +} + +class HttpRequest { + method; + protocol; + hostname; + port; + path; + query; + headers; + username; + password; + fragment; + body; + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol + ? options.protocol.slice(-1) !== ":" + ? `${options.protocol}:` + : options.protocol + : "https:"; + this.path = options.path ? (options.path.charAt(0) !== "/" ? `/${options.path}` : options.path) : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + static clone(request) { + const cloned = new HttpRequest({ + ...request, + headers: { ...request.headers }, + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); + } + return cloned; + } + static isInstance(request) { + if (!request) { + return false; + } + const req = request; + return ("method" in req && + "protocol" in req && + "hostname" in req && + "path" in req && + typeof req["query"] === "object" && + typeof req["headers"] === "object"); + } + clone() { + return HttpRequest.clone(this); + } +} +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param, + }; + }, {}); +} + +class HttpResponse { + statusCode; + reason; + headers; + body; + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) + return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + } +} + +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} + +exports.Field = Field; +exports.Fields = Fields; +exports.HttpRequest = HttpRequest; +exports.HttpResponse = HttpResponse; +exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration; +exports.isValidHostname = isValidHostname; +exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-login/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-login/node_modules/@smithy/types/dist-cjs/index.js new file mode 100644 index 00000000..be6d0e1a --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-provider-login/node_modules/@smithy/types/dist-cjs/index.js @@ -0,0 +1,91 @@ +'use strict'; + +exports.HttpAuthLocation = void 0; +(function (HttpAuthLocation) { + HttpAuthLocation["HEADER"] = "header"; + HttpAuthLocation["QUERY"] = "query"; +})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); + +exports.HttpApiKeyAuthLocation = void 0; +(function (HttpApiKeyAuthLocation) { + HttpApiKeyAuthLocation["HEADER"] = "header"; + HttpApiKeyAuthLocation["QUERY"] = "query"; +})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); + +exports.EndpointURLScheme = void 0; +(function (EndpointURLScheme) { + EndpointURLScheme["HTTP"] = "http"; + EndpointURLScheme["HTTPS"] = "https"; +})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); + +exports.AlgorithmId = void 0; +(function (AlgorithmId) { + AlgorithmId["MD5"] = "md5"; + AlgorithmId["CRC32"] = "crc32"; + AlgorithmId["CRC32C"] = "crc32c"; + AlgorithmId["SHA1"] = "sha1"; + AlgorithmId["SHA256"] = "sha256"; +})(exports.AlgorithmId || (exports.AlgorithmId = {})); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.SHA256, + checksumConstructor: () => runtimeConfig.sha256, + }); + } + if (runtimeConfig.md5 != undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.MD5, + checksumConstructor: () => runtimeConfig.md5, + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getDefaultClientConfiguration = (runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}; +const resolveDefaultRuntimeConfig = (config) => { + return resolveChecksumRuntimeConfig(config); +}; + +exports.FieldPosition = void 0; +(function (FieldPosition) { + FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; + FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; +})(exports.FieldPosition || (exports.FieldPosition = {})); + +const SMITHY_CONTEXT_KEY = "__smithy_context"; + +exports.IniSectionType = void 0; +(function (IniSectionType) { + IniSectionType["PROFILE"] = "profile"; + IniSectionType["SSO_SESSION"] = "sso-session"; + IniSectionType["SERVICES"] = "services"; +})(exports.IniSectionType || (exports.IniSectionType = {})); + +exports.RequestHandlerProtocol = void 0; +(function (RequestHandlerProtocol) { + RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; +})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); + +exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-node/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-node/dist-cjs/index.js new file mode 100644 index 00000000..64c1ae9d --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-provider-node/dist-cjs/index.js @@ -0,0 +1,150 @@ +'use strict'; + +var credentialProviderEnv = require('@aws-sdk/credential-provider-env'); +var propertyProvider = require('@smithy/property-provider'); +var sharedIniFileLoader = require('@smithy/shared-ini-file-loader'); + +const ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED"; +const remoteProvider = async (init) => { + const { ENV_CMDS_FULL_URI, ENV_CMDS_RELATIVE_URI, fromContainerMetadata, fromInstanceMetadata } = await import('@smithy/credential-provider-imds'); + if (process.env[ENV_CMDS_RELATIVE_URI] || process.env[ENV_CMDS_FULL_URI]) { + init.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromHttp/fromContainerMetadata"); + const { fromHttp } = await import('@aws-sdk/credential-provider-http'); + return propertyProvider.chain(fromHttp(init), fromContainerMetadata(init)); + } + if (process.env[ENV_IMDS_DISABLED] && process.env[ENV_IMDS_DISABLED] !== "false") { + return async () => { + throw new propertyProvider.CredentialsProviderError("EC2 Instance Metadata Service access disabled", { logger: init.logger }); + }; + } + init.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromInstanceMetadata"); + return fromInstanceMetadata(init); +}; + +function memoizeChain(providers, treatAsExpired) { + const chain = internalCreateChain(providers); + let activeLock; + let passiveLock; + let credentials; + const provider = async (options) => { + if (options?.forceRefresh) { + return await chain(options); + } + if (credentials?.expiration) { + if (credentials?.expiration?.getTime() < Date.now()) { + credentials = undefined; + } + } + if (activeLock) { + await activeLock; + } + else if (!credentials || treatAsExpired?.(credentials)) { + if (credentials) { + if (!passiveLock) { + passiveLock = chain(options).then((c) => { + credentials = c; + passiveLock = undefined; + }); + } + } + else { + activeLock = chain(options).then((c) => { + credentials = c; + activeLock = undefined; + }); + return provider(options); + } + } + return credentials; + }; + return provider; +} +const internalCreateChain = (providers) => async (awsIdentityProperties) => { + let lastProviderError; + for (const provider of providers) { + try { + return await provider(awsIdentityProperties); + } + catch (err) { + lastProviderError = err; + if (err?.tryNextLink) { + continue; + } + throw err; + } + } + throw lastProviderError; +}; + +let multipleCredentialSourceWarningEmitted = false; +const defaultProvider = (init = {}) => memoizeChain([ + async () => { + const profile = init.profile ?? process.env[sharedIniFileLoader.ENV_PROFILE]; + if (profile) { + const envStaticCredentialsAreSet = process.env[credentialProviderEnv.ENV_KEY] && process.env[credentialProviderEnv.ENV_SECRET]; + if (envStaticCredentialsAreSet) { + if (!multipleCredentialSourceWarningEmitted) { + const warnFn = init.logger?.warn && init.logger?.constructor?.name !== "NoOpLogger" + ? init.logger.warn.bind(init.logger) + : console.warn; + warnFn(`@aws-sdk/credential-provider-node - defaultProvider::fromEnv WARNING: + Multiple credential sources detected: + Both AWS_PROFILE and the pair AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY static credentials are set. + This SDK will proceed with the AWS_PROFILE value. + + However, a future version may change this behavior to prefer the ENV static credentials. + Please ensure that your environment only sets either the AWS_PROFILE or the + AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY pair. +`); + multipleCredentialSourceWarningEmitted = true; + } + } + throw new propertyProvider.CredentialsProviderError("AWS_PROFILE is set, skipping fromEnv provider.", { + logger: init.logger, + tryNextLink: true, + }); + } + init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromEnv"); + return credentialProviderEnv.fromEnv(init)(); + }, + async (awsIdentityProperties) => { + init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromSSO"); + const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init; + if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) { + throw new propertyProvider.CredentialsProviderError("Skipping SSO provider in default chain (inputs do not include SSO fields).", { logger: init.logger }); + } + const { fromSSO } = await import('@aws-sdk/credential-provider-sso'); + return fromSSO(init)(awsIdentityProperties); + }, + async (awsIdentityProperties) => { + init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromIni"); + const { fromIni } = await import('@aws-sdk/credential-provider-ini'); + return fromIni(init)(awsIdentityProperties); + }, + async (awsIdentityProperties) => { + init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromProcess"); + const { fromProcess } = await import('@aws-sdk/credential-provider-process'); + return fromProcess(init)(awsIdentityProperties); + }, + async (awsIdentityProperties) => { + init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromTokenFile"); + const { fromTokenFile } = await import('@aws-sdk/credential-provider-web-identity'); + return fromTokenFile(init)(awsIdentityProperties); + }, + async () => { + init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::remoteProvider"); + return (await remoteProvider(init))(); + }, + async () => { + throw new propertyProvider.CredentialsProviderError("Could not load credentials from any providers", { + tryNextLink: false, + logger: init.logger, + }); + }, +], credentialsTreatedAsExpired); +const credentialsWillNeedRefresh = (credentials) => credentials?.expiration !== undefined; +const credentialsTreatedAsExpired = (credentials) => credentials?.expiration !== undefined && credentials.expiration.getTime() - Date.now() < 300000; + +exports.credentialsTreatedAsExpired = credentialsTreatedAsExpired; +exports.credentialsWillNeedRefresh = credentialsWillNeedRefresh; +exports.defaultProvider = defaultProvider; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-process/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-process/dist-cjs/index.js new file mode 100644 index 00000000..911fd4c5 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-provider-process/dist-cjs/index.js @@ -0,0 +1,79 @@ +'use strict'; + +var sharedIniFileLoader = require('@smithy/shared-ini-file-loader'); +var propertyProvider = require('@smithy/property-provider'); +var child_process = require('child_process'); +var util = require('util'); +var client = require('@aws-sdk/core/client'); + +const getValidatedProcessCredentials = (profileName, data, profiles) => { + if (data.Version !== 1) { + throw Error(`Profile ${profileName} credential_process did not return Version 1.`); + } + if (data.AccessKeyId === undefined || data.SecretAccessKey === undefined) { + throw Error(`Profile ${profileName} credential_process returned invalid credentials.`); + } + if (data.Expiration) { + const currentTime = new Date(); + const expireTime = new Date(data.Expiration); + if (expireTime < currentTime) { + throw Error(`Profile ${profileName} credential_process returned expired credentials.`); + } + } + let accountId = data.AccountId; + if (!accountId && profiles?.[profileName]?.aws_account_id) { + accountId = profiles[profileName].aws_account_id; + } + const credentials = { + accessKeyId: data.AccessKeyId, + secretAccessKey: data.SecretAccessKey, + ...(data.SessionToken && { sessionToken: data.SessionToken }), + ...(data.Expiration && { expiration: new Date(data.Expiration) }), + ...(data.CredentialScope && { credentialScope: data.CredentialScope }), + ...(accountId && { accountId }), + }; + client.setCredentialFeature(credentials, "CREDENTIALS_PROCESS", "w"); + return credentials; +}; + +const resolveProcessCredentials = async (profileName, profiles, logger) => { + const profile = profiles[profileName]; + if (profiles[profileName]) { + const credentialProcess = profile["credential_process"]; + if (credentialProcess !== undefined) { + const execPromise = util.promisify(sharedIniFileLoader.externalDataInterceptor?.getTokenRecord?.().exec ?? child_process.exec); + try { + const { stdout } = await execPromise(credentialProcess); + let data; + try { + data = JSON.parse(stdout.trim()); + } + catch { + throw Error(`Profile ${profileName} credential_process returned invalid JSON.`); + } + return getValidatedProcessCredentials(profileName, data, profiles); + } + catch (error) { + throw new propertyProvider.CredentialsProviderError(error.message, { logger }); + } + } + else { + throw new propertyProvider.CredentialsProviderError(`Profile ${profileName} did not contain credential_process.`, { logger }); + } + } + else { + throw new propertyProvider.CredentialsProviderError(`Profile ${profileName} could not be found in shared credentials file.`, { + logger, + }); + } +}; + +const fromProcess = (init = {}) => async ({ callerClientConfig } = {}) => { + init.logger?.debug("@aws-sdk/credential-provider-process - fromProcess"); + const profiles = await sharedIniFileLoader.parseKnownFiles(init); + return resolveProcessCredentials(sharedIniFileLoader.getProfileName({ + profile: init.profile ?? callerClientConfig?.profile, + }), profiles, init.logger); +}; + +exports.fromProcess = fromProcess; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-sso/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-sso/dist-cjs/index.js new file mode 100644 index 00000000..f9f0324e --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-provider-sso/dist-cjs/index.js @@ -0,0 +1,190 @@ +'use strict'; + +var propertyProvider = require('@smithy/property-provider'); +var sharedIniFileLoader = require('@smithy/shared-ini-file-loader'); +var client = require('@aws-sdk/core/client'); +var tokenProviders = require('@aws-sdk/token-providers'); + +const isSsoProfile = (arg) => arg && + (typeof arg.sso_start_url === "string" || + typeof arg.sso_account_id === "string" || + typeof arg.sso_session === "string" || + typeof arg.sso_region === "string" || + typeof arg.sso_role_name === "string"); + +const SHOULD_FAIL_CREDENTIAL_CHAIN = false; +const resolveSSOCredentials = async ({ ssoStartUrl, ssoSession, ssoAccountId, ssoRegion, ssoRoleName, ssoClient, clientConfig, parentClientConfig, profile, filepath, configFilepath, ignoreCache, logger, }) => { + let token; + const refreshMessage = `To refresh this SSO session run aws sso login with the corresponding profile.`; + if (ssoSession) { + try { + const _token = await tokenProviders.fromSso({ + profile, + filepath, + configFilepath, + ignoreCache, + })(); + token = { + accessToken: _token.token, + expiresAt: new Date(_token.expiration).toISOString(), + }; + } + catch (e) { + throw new propertyProvider.CredentialsProviderError(e.message, { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger, + }); + } + } + else { + try { + token = await sharedIniFileLoader.getSSOTokenFromFile(ssoStartUrl); + } + catch (e) { + throw new propertyProvider.CredentialsProviderError(`The SSO session associated with this profile is invalid. ${refreshMessage}`, { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger, + }); + } + } + if (new Date(token.expiresAt).getTime() - Date.now() <= 0) { + throw new propertyProvider.CredentialsProviderError(`The SSO session associated with this profile has expired. ${refreshMessage}`, { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger, + }); + } + const { accessToken } = token; + const { SSOClient, GetRoleCredentialsCommand } = await Promise.resolve().then(function () { return require('./loadSso-CVy8iqsZ.js'); }); + const sso = ssoClient || + new SSOClient(Object.assign({}, clientConfig ?? {}, { + logger: clientConfig?.logger ?? parentClientConfig?.logger, + region: clientConfig?.region ?? ssoRegion, + userAgentAppId: clientConfig?.userAgentAppId ?? parentClientConfig?.userAgentAppId, + })); + let ssoResp; + try { + ssoResp = await sso.send(new GetRoleCredentialsCommand({ + accountId: ssoAccountId, + roleName: ssoRoleName, + accessToken, + })); + } + catch (e) { + throw new propertyProvider.CredentialsProviderError(e, { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger, + }); + } + const { roleCredentials: { accessKeyId, secretAccessKey, sessionToken, expiration, credentialScope, accountId } = {}, } = ssoResp; + if (!accessKeyId || !secretAccessKey || !sessionToken || !expiration) { + throw new propertyProvider.CredentialsProviderError("SSO returns an invalid temporary credential.", { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger, + }); + } + const credentials = { + accessKeyId, + secretAccessKey, + sessionToken, + expiration: new Date(expiration), + ...(credentialScope && { credentialScope }), + ...(accountId && { accountId }), + }; + if (ssoSession) { + client.setCredentialFeature(credentials, "CREDENTIALS_SSO", "s"); + } + else { + client.setCredentialFeature(credentials, "CREDENTIALS_SSO_LEGACY", "u"); + } + return credentials; +}; + +const validateSsoProfile = (profile, logger) => { + const { sso_start_url, sso_account_id, sso_region, sso_role_name } = profile; + if (!sso_start_url || !sso_account_id || !sso_region || !sso_role_name) { + throw new propertyProvider.CredentialsProviderError(`Profile is configured with invalid SSO credentials. Required parameters "sso_account_id", ` + + `"sso_region", "sso_role_name", "sso_start_url". Got ${Object.keys(profile).join(", ")}\nReference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`, { tryNextLink: false, logger }); + } + return profile; +}; + +const fromSSO = (init = {}) => async ({ callerClientConfig } = {}) => { + init.logger?.debug("@aws-sdk/credential-provider-sso - fromSSO"); + const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init; + const { ssoClient } = init; + const profileName = sharedIniFileLoader.getProfileName({ + profile: init.profile ?? callerClientConfig?.profile, + }); + if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) { + const profiles = await sharedIniFileLoader.parseKnownFiles(init); + const profile = profiles[profileName]; + if (!profile) { + throw new propertyProvider.CredentialsProviderError(`Profile ${profileName} was not found.`, { logger: init.logger }); + } + if (!isSsoProfile(profile)) { + throw new propertyProvider.CredentialsProviderError(`Profile ${profileName} is not configured with SSO credentials.`, { + logger: init.logger, + }); + } + if (profile?.sso_session) { + const ssoSessions = await sharedIniFileLoader.loadSsoSessionData(init); + const session = ssoSessions[profile.sso_session]; + const conflictMsg = ` configurations in profile ${profileName} and sso-session ${profile.sso_session}`; + if (ssoRegion && ssoRegion !== session.sso_region) { + throw new propertyProvider.CredentialsProviderError(`Conflicting SSO region` + conflictMsg, { + tryNextLink: false, + logger: init.logger, + }); + } + if (ssoStartUrl && ssoStartUrl !== session.sso_start_url) { + throw new propertyProvider.CredentialsProviderError(`Conflicting SSO start_url` + conflictMsg, { + tryNextLink: false, + logger: init.logger, + }); + } + profile.sso_region = session.sso_region; + profile.sso_start_url = session.sso_start_url; + } + const { sso_start_url, sso_account_id, sso_region, sso_role_name, sso_session } = validateSsoProfile(profile, init.logger); + return resolveSSOCredentials({ + ssoStartUrl: sso_start_url, + ssoSession: sso_session, + ssoAccountId: sso_account_id, + ssoRegion: sso_region, + ssoRoleName: sso_role_name, + ssoClient: ssoClient, + clientConfig: init.clientConfig, + parentClientConfig: init.parentClientConfig, + profile: profileName, + filepath: init.filepath, + configFilepath: init.configFilepath, + ignoreCache: init.ignoreCache, + logger: init.logger, + }); + } + else if (!ssoStartUrl || !ssoAccountId || !ssoRegion || !ssoRoleName) { + throw new propertyProvider.CredentialsProviderError("Incomplete configuration. The fromSSO() argument hash must include " + + '"ssoStartUrl", "ssoAccountId", "ssoRegion", "ssoRoleName"', { tryNextLink: false, logger: init.logger }); + } + else { + return resolveSSOCredentials({ + ssoStartUrl, + ssoSession, + ssoAccountId, + ssoRegion, + ssoRoleName, + ssoClient, + clientConfig: init.clientConfig, + parentClientConfig: init.parentClientConfig, + profile: profileName, + filepath: init.filepath, + configFilepath: init.configFilepath, + ignoreCache: init.ignoreCache, + logger: init.logger, + }); + } +}; + +exports.fromSSO = fromSSO; +exports.isSsoProfile = isSsoProfile; +exports.validateSsoProfile = validateSsoProfile; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-sso/dist-cjs/loadSso-CVy8iqsZ.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-sso/dist-cjs/loadSso-CVy8iqsZ.js new file mode 100644 index 00000000..93eb944f --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-provider-sso/dist-cjs/loadSso-CVy8iqsZ.js @@ -0,0 +1,14 @@ +'use strict'; + +var clientSso = require('@aws-sdk/client-sso'); + + + +Object.defineProperty(exports, "GetRoleCredentialsCommand", { + enumerable: true, + get: function () { return clientSso.GetRoleCredentialsCommand; } +}); +Object.defineProperty(exports, "SSOClient", { + enumerable: true, + get: function () { return clientSso.SSOClient; } +}); diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/fromTokenFile.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/fromTokenFile.js new file mode 100644 index 00000000..e541fdb1 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/fromTokenFile.js @@ -0,0 +1,34 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromTokenFile = void 0; +const client_1 = require("@aws-sdk/core/client"); +const property_provider_1 = require("@smithy/property-provider"); +const shared_ini_file_loader_1 = require("@smithy/shared-ini-file-loader"); +const fs_1 = require("fs"); +const fromWebToken_1 = require("./fromWebToken"); +const ENV_TOKEN_FILE = "AWS_WEB_IDENTITY_TOKEN_FILE"; +const ENV_ROLE_ARN = "AWS_ROLE_ARN"; +const ENV_ROLE_SESSION_NAME = "AWS_ROLE_SESSION_NAME"; +const fromTokenFile = (init = {}) => async (awsIdentityProperties) => { + init.logger?.debug("@aws-sdk/credential-provider-web-identity - fromTokenFile"); + const webIdentityTokenFile = init?.webIdentityTokenFile ?? process.env[ENV_TOKEN_FILE]; + const roleArn = init?.roleArn ?? process.env[ENV_ROLE_ARN]; + const roleSessionName = init?.roleSessionName ?? process.env[ENV_ROLE_SESSION_NAME]; + if (!webIdentityTokenFile || !roleArn) { + throw new property_provider_1.CredentialsProviderError("Web identity configuration not specified", { + logger: init.logger, + }); + } + const credentials = await (0, fromWebToken_1.fromWebToken)({ + ...init, + webIdentityToken: shared_ini_file_loader_1.externalDataInterceptor?.getTokenRecord?.()[webIdentityTokenFile] ?? + (0, fs_1.readFileSync)(webIdentityTokenFile, { encoding: "ascii" }), + roleArn, + roleSessionName, + })(awsIdentityProperties); + if (webIdentityTokenFile === process.env[ENV_TOKEN_FILE]) { + (0, client_1.setCredentialFeature)(credentials, "CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN", "h"); + } + return credentials; +}; +exports.fromTokenFile = fromTokenFile; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/fromWebToken.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/fromWebToken.js new file mode 100644 index 00000000..b92af292 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/fromWebToken.js @@ -0,0 +1,62 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromWebToken = void 0; +const fromWebToken = (init) => async (awsIdentityProperties) => { + init.logger?.debug("@aws-sdk/credential-provider-web-identity - fromWebToken"); + const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy, durationSeconds } = init; + let { roleAssumerWithWebIdentity } = init; + if (!roleAssumerWithWebIdentity) { + const { getDefaultRoleAssumerWithWebIdentity } = await Promise.resolve().then(() => __importStar(require("@aws-sdk/nested-clients/sts"))); + roleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity({ + ...init.clientConfig, + credentialProviderLogger: init.logger, + parentClientConfig: { + ...awsIdentityProperties?.callerClientConfig, + ...init.parentClientConfig, + }, + }, init.clientPlugins); + } + return roleAssumerWithWebIdentity({ + RoleArn: roleArn, + RoleSessionName: roleSessionName ?? `aws-sdk-js-session-${Date.now()}`, + WebIdentityToken: webIdentityToken, + ProviderId: providerId, + PolicyArns: policyArns, + Policy: policy, + DurationSeconds: durationSeconds, + }); +}; +exports.fromWebToken = fromWebToken; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/index.js new file mode 100644 index 00000000..7f405954 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/index.js @@ -0,0 +1,19 @@ +'use strict'; + +var fromTokenFile = require('./fromTokenFile'); +var fromWebToken = require('./fromWebToken'); + + + +Object.keys(fromTokenFile).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return fromTokenFile[k]; } + }); +}); +Object.keys(fromWebToken).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return fromWebToken[k]; } + }); +}); diff --git a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/createCredentialChain.js b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/createCredentialChain.js new file mode 100644 index 00000000..3488e1be --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/createCredentialChain.js @@ -0,0 +1,45 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.propertyProviderChain = exports.createCredentialChain = void 0; +const property_provider_1 = require("@smithy/property-provider"); +const createCredentialChain = (...credentialProviders) => { + let expireAfter = -1; + const baseFunction = async (awsIdentityProperties) => { + const credentials = await (0, exports.propertyProviderChain)(...credentialProviders)(awsIdentityProperties); + if (!credentials.expiration && expireAfter !== -1) { + credentials.expiration = new Date(Date.now() + expireAfter); + } + return credentials; + }; + const withOptions = Object.assign(baseFunction, { + expireAfter(milliseconds) { + if (milliseconds < 5 * 60_000) { + throw new Error("@aws-sdk/credential-providers - createCredentialChain(...).expireAfter(ms) may not be called with a duration lower than five minutes."); + } + expireAfter = milliseconds; + return withOptions; + }, + }); + return withOptions; +}; +exports.createCredentialChain = createCredentialChain; +const propertyProviderChain = (...providers) => async (awsIdentityProperties) => { + if (providers.length === 0) { + throw new property_provider_1.ProviderError("No providers in chain", { tryNextLink: false }); + } + let lastProviderError; + for (const provider of providers) { + try { + return await provider(awsIdentityProperties); + } + catch (err) { + lastProviderError = err; + if (err?.tryNextLink) { + continue; + } + throw err; + } + } + throw lastProviderError; +}; +exports.propertyProviderChain = propertyProviderChain; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromCognitoIdentity.js b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromCognitoIdentity.js new file mode 100644 index 00000000..9e56e01d --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromCognitoIdentity.js @@ -0,0 +1,8 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromCognitoIdentity = void 0; +const credential_provider_cognito_identity_1 = require("@aws-sdk/credential-provider-cognito-identity"); +const fromCognitoIdentity = (options) => (0, credential_provider_cognito_identity_1.fromCognitoIdentity)({ + ...options, +}); +exports.fromCognitoIdentity = fromCognitoIdentity; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromCognitoIdentityPool.js b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromCognitoIdentityPool.js new file mode 100644 index 00000000..ed20c1d8 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromCognitoIdentityPool.js @@ -0,0 +1,8 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromCognitoIdentityPool = void 0; +const credential_provider_cognito_identity_1 = require("@aws-sdk/credential-provider-cognito-identity"); +const fromCognitoIdentityPool = (options) => (0, credential_provider_cognito_identity_1.fromCognitoIdentityPool)({ + ...options, +}); +exports.fromCognitoIdentityPool = fromCognitoIdentityPool; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromContainerMetadata.js b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromContainerMetadata.js new file mode 100644 index 00000000..343bf80c --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromContainerMetadata.js @@ -0,0 +1,9 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromContainerMetadata = void 0; +const credential_provider_imds_1 = require("@smithy/credential-provider-imds"); +const fromContainerMetadata = (init) => { + init?.logger?.debug("@smithy/credential-provider-imds", "fromContainerMetadata"); + return (0, credential_provider_imds_1.fromContainerMetadata)(init); +}; +exports.fromContainerMetadata = fromContainerMetadata; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromEnv.js b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromEnv.js new file mode 100644 index 00000000..b3e82a6f --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromEnv.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromEnv = void 0; +const credential_provider_env_1 = require("@aws-sdk/credential-provider-env"); +const fromEnv = (init) => (0, credential_provider_env_1.fromEnv)(init); +exports.fromEnv = fromEnv; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromIni.js b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromIni.js new file mode 100644 index 00000000..139107ac --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromIni.js @@ -0,0 +1,8 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromIni = void 0; +const credential_provider_ini_1 = require("@aws-sdk/credential-provider-ini"); +const fromIni = (init = {}) => (0, credential_provider_ini_1.fromIni)({ + ...init, +}); +exports.fromIni = fromIni; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromInstanceMetadata.js b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromInstanceMetadata.js new file mode 100644 index 00000000..57f70d04 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromInstanceMetadata.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromInstanceMetadata = void 0; +const client_1 = require("@aws-sdk/core/client"); +const credential_provider_imds_1 = require("@smithy/credential-provider-imds"); +const fromInstanceMetadata = (init) => { + init?.logger?.debug("@smithy/credential-provider-imds", "fromInstanceMetadata"); + return async () => (0, credential_provider_imds_1.fromInstanceMetadata)(init)().then((creds) => (0, client_1.setCredentialFeature)(creds, "CREDENTIALS_IMDS", "0")); +}; +exports.fromInstanceMetadata = fromInstanceMetadata; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromLoginCredentials.js b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromLoginCredentials.js new file mode 100644 index 00000000..c0d1ad61 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromLoginCredentials.js @@ -0,0 +1,8 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromLoginCredentials = void 0; +const credential_provider_login_1 = require("@aws-sdk/credential-provider-login"); +const fromLoginCredentials = (init) => (0, credential_provider_login_1.fromLoginCredentials)({ + ...init, +}); +exports.fromLoginCredentials = fromLoginCredentials; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromNodeProviderChain.js b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromNodeProviderChain.js new file mode 100644 index 00000000..4082387a --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromNodeProviderChain.js @@ -0,0 +1,8 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromNodeProviderChain = void 0; +const credential_provider_node_1 = require("@aws-sdk/credential-provider-node"); +const fromNodeProviderChain = (init = {}) => (0, credential_provider_node_1.defaultProvider)({ + ...init, +}); +exports.fromNodeProviderChain = fromNodeProviderChain; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromProcess.js b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromProcess.js new file mode 100644 index 00000000..58a65abd --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromProcess.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromProcess = void 0; +const credential_provider_process_1 = require("@aws-sdk/credential-provider-process"); +const fromProcess = (init) => (0, credential_provider_process_1.fromProcess)(init); +exports.fromProcess = fromProcess; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromSSO.js b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromSSO.js new file mode 100644 index 00000000..7cf0fb4a --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromSSO.js @@ -0,0 +1,8 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromSSO = void 0; +const credential_provider_sso_1 = require("@aws-sdk/credential-provider-sso"); +const fromSSO = (init = {}) => { + return (0, credential_provider_sso_1.fromSSO)({ ...init }); +}; +exports.fromSSO = fromSSO; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromTemporaryCredentials.base.js b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromTemporaryCredentials.base.js new file mode 100644 index 00000000..0648aed3 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromTemporaryCredentials.base.js @@ -0,0 +1,155 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromTemporaryCredentials = void 0; +const core_1 = require("@smithy/core"); +const property_provider_1 = require("@smithy/property-provider"); +const ASSUME_ROLE_DEFAULT_REGION = "us-east-1"; +const fromTemporaryCredentials = (options, credentialDefaultProvider, regionProvider) => { + let stsClient; + return async (awsIdentityProperties = {}) => { + const { callerClientConfig } = awsIdentityProperties; + const profile = options.clientConfig?.profile ?? callerClientConfig?.profile; + const logger = options.logger ?? callerClientConfig?.logger; + logger?.debug("@aws-sdk/credential-providers - fromTemporaryCredentials (STS)"); + const params = { ...options.params, RoleSessionName: options.params.RoleSessionName ?? "aws-sdk-js-" + Date.now() }; + if (params?.SerialNumber) { + if (!options.mfaCodeProvider) { + throw new property_provider_1.CredentialsProviderError(`Temporary credential requires multi-factor authentication, but no MFA code callback was provided.`, { + tryNextLink: false, + logger, + }); + } + params.TokenCode = await options.mfaCodeProvider(params?.SerialNumber); + } + const { AssumeRoleCommand, STSClient } = await Promise.resolve().then(() => __importStar(require("./loadSts"))); + if (!stsClient) { + const defaultCredentialsOrError = typeof credentialDefaultProvider === "function" ? credentialDefaultProvider() : undefined; + const credentialSources = [ + options.masterCredentials, + options.clientConfig?.credentials, + void callerClientConfig?.credentials, + callerClientConfig?.credentialDefaultProvider?.(), + defaultCredentialsOrError, + ]; + let credentialSource = "STS client default credentials"; + if (credentialSources[0]) { + credentialSource = "options.masterCredentials"; + } + else if (credentialSources[1]) { + credentialSource = "options.clientConfig.credentials"; + } + else if (credentialSources[2]) { + credentialSource = "caller client's credentials"; + throw new Error("fromTemporaryCredentials recursion in callerClientConfig.credentials"); + } + else if (credentialSources[3]) { + credentialSource = "caller client's credentialDefaultProvider"; + } + else if (credentialSources[4]) { + credentialSource = "AWS SDK default credentials"; + } + const regionSources = [ + options.clientConfig?.region, + callerClientConfig?.region, + await regionProvider?.({ + profile, + }), + ASSUME_ROLE_DEFAULT_REGION, + ]; + let regionSource = "default partition's default region"; + if (regionSources[0]) { + regionSource = "options.clientConfig.region"; + } + else if (regionSources[1]) { + regionSource = "caller client's region"; + } + else if (regionSources[2]) { + regionSource = "file or env region"; + } + const requestHandlerSources = [ + filterRequestHandler(options.clientConfig?.requestHandler), + filterRequestHandler(callerClientConfig?.requestHandler), + ]; + let requestHandlerSource = "STS default requestHandler"; + if (requestHandlerSources[0]) { + requestHandlerSource = "options.clientConfig.requestHandler"; + } + else if (requestHandlerSources[1]) { + requestHandlerSource = "caller client's requestHandler"; + } + logger?.debug?.(`@aws-sdk/credential-providers - fromTemporaryCredentials STS client init with ` + + `${regionSource}=${await (0, core_1.normalizeProvider)(coalesce(regionSources))()}, ${credentialSource}, ${requestHandlerSource}.`); + stsClient = new STSClient({ + userAgentAppId: callerClientConfig?.userAgentAppId, + ...options.clientConfig, + credentials: coalesce(credentialSources), + logger, + profile, + region: coalesce(regionSources), + requestHandler: coalesce(requestHandlerSources), + }); + } + if (options.clientPlugins) { + for (const plugin of options.clientPlugins) { + stsClient.middlewareStack.use(plugin); + } + } + const { Credentials } = await stsClient.send(new AssumeRoleCommand(params)); + if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) { + throw new property_provider_1.CredentialsProviderError(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`, { + logger, + }); + } + return { + accessKeyId: Credentials.AccessKeyId, + secretAccessKey: Credentials.SecretAccessKey, + sessionToken: Credentials.SessionToken, + expiration: Credentials.Expiration, + credentialScope: Credentials.CredentialScope, + }; + }; +}; +exports.fromTemporaryCredentials = fromTemporaryCredentials; +const filterRequestHandler = (requestHandler) => { + return requestHandler?.metadata?.handlerProtocol === "h2" ? undefined : requestHandler; +}; +const coalesce = (args) => { + for (const item of args) { + if (item !== undefined) { + return item; + } + } +}; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromTemporaryCredentials.js b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromTemporaryCredentials.js new file mode 100644 index 00000000..5cc665e6 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromTemporaryCredentials.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromTemporaryCredentials = void 0; +const config_resolver_1 = require("@smithy/config-resolver"); +const node_config_provider_1 = require("@smithy/node-config-provider"); +const fromNodeProviderChain_1 = require("./fromNodeProviderChain"); +const fromTemporaryCredentials_base_1 = require("./fromTemporaryCredentials.base"); +const fromTemporaryCredentials = (options) => { + return (0, fromTemporaryCredentials_base_1.fromTemporaryCredentials)(options, fromNodeProviderChain_1.fromNodeProviderChain, async ({ profile = process.env.AWS_PROFILE }) => (0, node_config_provider_1.loadConfig)({ + environmentVariableSelector: (env) => env.AWS_REGION, + configFileSelector: (profileData) => { + return profileData.region; + }, + default: () => undefined, + }, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, profile })()); +}; +exports.fromTemporaryCredentials = fromTemporaryCredentials; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromTokenFile.js b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromTokenFile.js new file mode 100644 index 00000000..66164b31 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromTokenFile.js @@ -0,0 +1,8 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromTokenFile = void 0; +const credential_provider_web_identity_1 = require("@aws-sdk/credential-provider-web-identity"); +const fromTokenFile = (init = {}) => (0, credential_provider_web_identity_1.fromTokenFile)({ + ...init, +}); +exports.fromTokenFile = fromTokenFile; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromWebToken.js b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromWebToken.js new file mode 100644 index 00000000..729cc111 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromWebToken.js @@ -0,0 +1,8 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromWebToken = void 0; +const credential_provider_web_identity_1 = require("@aws-sdk/credential-provider-web-identity"); +const fromWebToken = (init) => (0, credential_provider_web_identity_1.fromWebToken)({ + ...init, +}); +exports.fromWebToken = fromWebToken; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/index.js new file mode 100644 index 00000000..a5a5f611 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/index.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromHttp = void 0; +const tslib_1 = require("tslib"); +tslib_1.__exportStar(require("./createCredentialChain"), exports); +tslib_1.__exportStar(require("./fromCognitoIdentity"), exports); +tslib_1.__exportStar(require("./fromCognitoIdentityPool"), exports); +tslib_1.__exportStar(require("./fromContainerMetadata"), exports); +tslib_1.__exportStar(require("./fromEnv"), exports); +var credential_provider_http_1 = require("@aws-sdk/credential-provider-http"); +Object.defineProperty(exports, "fromHttp", { enumerable: true, get: function () { return credential_provider_http_1.fromHttp; } }); +tslib_1.__exportStar(require("./fromIni"), exports); +tslib_1.__exportStar(require("./fromInstanceMetadata"), exports); +tslib_1.__exportStar(require("./fromLoginCredentials"), exports); +tslib_1.__exportStar(require("./fromNodeProviderChain"), exports); +tslib_1.__exportStar(require("./fromProcess"), exports); +tslib_1.__exportStar(require("./fromSSO"), exports); +tslib_1.__exportStar(require("./fromTemporaryCredentials"), exports); +tslib_1.__exportStar(require("./fromTokenFile"), exports); +tslib_1.__exportStar(require("./fromWebToken"), exports); diff --git a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/loadSts.js b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/loadSts.js new file mode 100644 index 00000000..67e912ca --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/loadSts.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.STSClient = exports.AssumeRoleCommand = void 0; +const sts_1 = require("@aws-sdk/nested-clients/sts"); +Object.defineProperty(exports, "AssumeRoleCommand", { enumerable: true, get: function () { return sts_1.AssumeRoleCommand; } }); +Object.defineProperty(exports, "STSClient", { enumerable: true, get: function () { return sts_1.STSClient; } }); diff --git a/claude-code-source/node_modules/@aws-sdk/eventstream-handler-node/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/eventstream-handler-node/dist-cjs/index.js new file mode 100644 index 00000000..464093ae --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/eventstream-handler-node/dist-cjs/index.js @@ -0,0 +1,108 @@ +'use strict'; + +var eventstreamCodec = require('@smithy/eventstream-codec'); +var stream = require('stream'); + +class EventSigningStream extends stream.Transform { + priorSignature; + messageSigner; + eventStreamCodec; + systemClockOffsetProvider; + constructor(options) { + super({ + autoDestroy: true, + readableObjectMode: true, + writableObjectMode: true, + ...options, + }); + this.priorSignature = options.priorSignature; + this.eventStreamCodec = options.eventStreamCodec; + this.messageSigner = options.messageSigner; + this.systemClockOffsetProvider = options.systemClockOffsetProvider; + } + async _transform(chunk, encoding, callback) { + try { + const now = new Date(Date.now() + (await this.systemClockOffsetProvider())); + const dateHeader = { + ":date": { type: "timestamp", value: now }, + }; + const signedMessage = await this.messageSigner.sign({ + message: { + body: chunk, + headers: dateHeader, + }, + priorSignature: this.priorSignature, + }, { + signingDate: now, + }); + this.priorSignature = signedMessage.signature; + const serializedSigned = this.eventStreamCodec.encode({ + headers: { + ...dateHeader, + ":chunk-signature": { + type: "binary", + value: getSignatureBinary(signedMessage.signature), + }, + }, + body: chunk, + }); + this.push(serializedSigned); + return callback(); + } + catch (err) { + callback(err); + } + } +} +function getSignatureBinary(signature) { + const buf = Buffer.from(signature, "hex"); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); +} + +class EventStreamPayloadHandler { + messageSigner; + eventStreamCodec; + systemClockOffsetProvider; + constructor(options) { + this.messageSigner = options.messageSigner; + this.eventStreamCodec = new eventstreamCodec.EventStreamCodec(options.utf8Encoder, options.utf8Decoder); + this.systemClockOffsetProvider = async () => options.systemClockOffset ?? 0; + } + async handle(next, args, context = {}) { + const request = args.request; + const { body: payload, query } = request; + if (!(payload instanceof stream.Readable)) { + throw new Error("Eventstream payload must be a Readable stream."); + } + const payloadStream = payload; + request.body = new stream.PassThrough({ + objectMode: true, + }); + const match = request.headers?.authorization?.match(/Signature=([\w]+)$/); + const priorSignature = match?.[1] ?? query?.["X-Amz-Signature"] ?? ""; + const signingStream = new EventSigningStream({ + priorSignature, + eventStreamCodec: this.eventStreamCodec, + messageSigner: await this.messageSigner(), + systemClockOffsetProvider: this.systemClockOffsetProvider, + }); + stream.pipeline(payloadStream, signingStream, request.body, (err) => { + if (err) { + throw err; + } + }); + let result; + try { + result = await next(args); + } + catch (e) { + request.body.end(); + throw e; + } + return result; + } +} + +const eventStreamPayloadHandlerProvider = (options) => new EventStreamPayloadHandler(options); + +exports.eventStreamPayloadHandlerProvider = eventStreamPayloadHandlerProvider; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-eventstream/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-eventstream/dist-cjs/index.js new file mode 100644 index 00000000..bb03bb05 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/middleware-eventstream/dist-cjs/index.js @@ -0,0 +1,65 @@ +'use strict'; + +var protocolHttp = require('@smithy/protocol-http'); + +function resolveEventStreamConfig(input) { + const eventSigner = input.signer; + const messageSigner = input.signer; + const newInput = Object.assign(input, { + eventSigner, + messageSigner, + }); + const eventStreamPayloadHandler = newInput.eventStreamPayloadHandlerProvider(newInput); + return Object.assign(newInput, { + eventStreamPayloadHandler, + }); +} + +const eventStreamHandlingMiddleware = (options) => (next, context) => async (args) => { + const { request } = args; + if (!protocolHttp.HttpRequest.isInstance(request)) + return next(args); + return options.eventStreamPayloadHandler.handle(next, args, context); +}; +const eventStreamHandlingMiddlewareOptions = { + tags: ["EVENT_STREAM", "SIGNATURE", "HANDLE"], + name: "eventStreamHandlingMiddleware", + relation: "after", + toMiddleware: "awsAuthMiddleware", + override: true, +}; + +const eventStreamHeaderMiddleware = (next) => async (args) => { + const { request } = args; + if (!protocolHttp.HttpRequest.isInstance(request)) + return next(args); + request.headers = { + ...request.headers, + "content-type": "application/vnd.amazon.eventstream", + "x-amz-content-sha256": "STREAMING-AWS4-HMAC-SHA256-EVENTS", + }; + return next({ + ...args, + request, + }); +}; +const eventStreamHeaderMiddlewareOptions = { + step: "build", + tags: ["EVENT_STREAM", "HEADER", "CONTENT_TYPE", "CONTENT_SHA256"], + name: "eventStreamHeaderMiddleware", + override: true, +}; + +const getEventStreamPlugin = (options) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(eventStreamHandlingMiddleware(options), eventStreamHandlingMiddlewareOptions); + clientStack.add(eventStreamHeaderMiddleware, eventStreamHeaderMiddlewareOptions); + }, +}); + +exports.eventStreamHandlingMiddleware = eventStreamHandlingMiddleware; +exports.eventStreamHandlingMiddlewareOptions = eventStreamHandlingMiddlewareOptions; +exports.eventStreamHeaderMiddleware = eventStreamHeaderMiddleware; +exports.eventStreamHeaderMiddlewareOptions = eventStreamHeaderMiddlewareOptions; +exports.getEventStreamPlugin = getEventStreamPlugin; +exports.resolveEventStreamConfig = resolveEventStreamConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-eventstream/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-eventstream/node_modules/@smithy/protocol-http/dist-cjs/index.js new file mode 100644 index 00000000..52303c3b --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/middleware-eventstream/node_modules/@smithy/protocol-http/dist-cjs/index.js @@ -0,0 +1,169 @@ +'use strict'; + +var types = require('@smithy/types'); + +const getHttpHandlerExtensionConfiguration = (runtimeConfig) => { + return { + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); + }, + }; +}; +const resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler(), + }; +}; + +class Field { + name; + kind; + values; + constructor({ name, kind = types.FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; + } + add(value) { + this.values.push(value); + } + set(values) { + this.values = values; + } + remove(value) { + this.values = this.values.filter((v) => v !== value); + } + toString() { + return this.values.map((v) => (v.includes(",") || v.includes(" ") ? `"${v}"` : v)).join(", "); + } + get() { + return this.values; + } +} + +class Fields { + entries = {}; + encoding; + constructor({ fields = [], encoding = "utf-8" }) { + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + setField(field) { + this.entries[field.name.toLowerCase()] = field; + } + getField(name) { + return this.entries[name.toLowerCase()]; + } + removeField(name) { + delete this.entries[name.toLowerCase()]; + } + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } +} + +class HttpRequest { + method; + protocol; + hostname; + port; + path; + query; + headers; + username; + password; + fragment; + body; + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol + ? options.protocol.slice(-1) !== ":" + ? `${options.protocol}:` + : options.protocol + : "https:"; + this.path = options.path ? (options.path.charAt(0) !== "/" ? `/${options.path}` : options.path) : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + static clone(request) { + const cloned = new HttpRequest({ + ...request, + headers: { ...request.headers }, + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); + } + return cloned; + } + static isInstance(request) { + if (!request) { + return false; + } + const req = request; + return ("method" in req && + "protocol" in req && + "hostname" in req && + "path" in req && + typeof req["query"] === "object" && + typeof req["headers"] === "object"); + } + clone() { + return HttpRequest.clone(this); + } +} +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param, + }; + }, {}); +} + +class HttpResponse { + statusCode; + reason; + headers; + body; + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) + return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + } +} + +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} + +exports.Field = Field; +exports.Fields = Fields; +exports.HttpRequest = HttpRequest; +exports.HttpResponse = HttpResponse; +exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration; +exports.isValidHostname = isValidHostname; +exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-eventstream/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-eventstream/node_modules/@smithy/types/dist-cjs/index.js new file mode 100644 index 00000000..be6d0e1a --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/middleware-eventstream/node_modules/@smithy/types/dist-cjs/index.js @@ -0,0 +1,91 @@ +'use strict'; + +exports.HttpAuthLocation = void 0; +(function (HttpAuthLocation) { + HttpAuthLocation["HEADER"] = "header"; + HttpAuthLocation["QUERY"] = "query"; +})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); + +exports.HttpApiKeyAuthLocation = void 0; +(function (HttpApiKeyAuthLocation) { + HttpApiKeyAuthLocation["HEADER"] = "header"; + HttpApiKeyAuthLocation["QUERY"] = "query"; +})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); + +exports.EndpointURLScheme = void 0; +(function (EndpointURLScheme) { + EndpointURLScheme["HTTP"] = "http"; + EndpointURLScheme["HTTPS"] = "https"; +})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); + +exports.AlgorithmId = void 0; +(function (AlgorithmId) { + AlgorithmId["MD5"] = "md5"; + AlgorithmId["CRC32"] = "crc32"; + AlgorithmId["CRC32C"] = "crc32c"; + AlgorithmId["SHA1"] = "sha1"; + AlgorithmId["SHA256"] = "sha256"; +})(exports.AlgorithmId || (exports.AlgorithmId = {})); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.SHA256, + checksumConstructor: () => runtimeConfig.sha256, + }); + } + if (runtimeConfig.md5 != undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.MD5, + checksumConstructor: () => runtimeConfig.md5, + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getDefaultClientConfiguration = (runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}; +const resolveDefaultRuntimeConfig = (config) => { + return resolveChecksumRuntimeConfig(config); +}; + +exports.FieldPosition = void 0; +(function (FieldPosition) { + FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; + FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; +})(exports.FieldPosition || (exports.FieldPosition = {})); + +const SMITHY_CONTEXT_KEY = "__smithy_context"; + +exports.IniSectionType = void 0; +(function (IniSectionType) { + IniSectionType["PROFILE"] = "profile"; + IniSectionType["SSO_SESSION"] = "sso-session"; + IniSectionType["SERVICES"] = "services"; +})(exports.IniSectionType || (exports.IniSectionType = {})); + +exports.RequestHandlerProtocol = void 0; +(function (RequestHandlerProtocol) { + RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; +})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); + +exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-host-header/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-host-header/dist-cjs/index.js new file mode 100644 index 00000000..2dc022c3 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/middleware-host-header/dist-cjs/index.js @@ -0,0 +1,41 @@ +'use strict'; + +var protocolHttp = require('@smithy/protocol-http'); + +function resolveHostHeaderConfig(input) { + return input; +} +const hostHeaderMiddleware = (options) => (next) => async (args) => { + if (!protocolHttp.HttpRequest.isInstance(args.request)) + return next(args); + const { request } = args; + const { handlerProtocol = "" } = options.requestHandler.metadata || {}; + if (handlerProtocol.indexOf("h2") >= 0 && !request.headers[":authority"]) { + delete request.headers["host"]; + request.headers[":authority"] = request.hostname + (request.port ? ":" + request.port : ""); + } + else if (!request.headers["host"]) { + let host = request.hostname; + if (request.port != null) + host += `:${request.port}`; + request.headers["host"] = host; + } + return next(args); +}; +const hostHeaderMiddlewareOptions = { + name: "hostHeaderMiddleware", + step: "build", + priority: "low", + tags: ["HOST"], + override: true, +}; +const getHostHeaderPlugin = (options) => ({ + applyToStack: (clientStack) => { + clientStack.add(hostHeaderMiddleware(options), hostHeaderMiddlewareOptions); + }, +}); + +exports.getHostHeaderPlugin = getHostHeaderPlugin; +exports.hostHeaderMiddleware = hostHeaderMiddleware; +exports.hostHeaderMiddlewareOptions = hostHeaderMiddlewareOptions; +exports.resolveHostHeaderConfig = resolveHostHeaderConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/protocol-http/dist-cjs/index.js new file mode 100644 index 00000000..52303c3b --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/protocol-http/dist-cjs/index.js @@ -0,0 +1,169 @@ +'use strict'; + +var types = require('@smithy/types'); + +const getHttpHandlerExtensionConfiguration = (runtimeConfig) => { + return { + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); + }, + }; +}; +const resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler(), + }; +}; + +class Field { + name; + kind; + values; + constructor({ name, kind = types.FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; + } + add(value) { + this.values.push(value); + } + set(values) { + this.values = values; + } + remove(value) { + this.values = this.values.filter((v) => v !== value); + } + toString() { + return this.values.map((v) => (v.includes(",") || v.includes(" ") ? `"${v}"` : v)).join(", "); + } + get() { + return this.values; + } +} + +class Fields { + entries = {}; + encoding; + constructor({ fields = [], encoding = "utf-8" }) { + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + setField(field) { + this.entries[field.name.toLowerCase()] = field; + } + getField(name) { + return this.entries[name.toLowerCase()]; + } + removeField(name) { + delete this.entries[name.toLowerCase()]; + } + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } +} + +class HttpRequest { + method; + protocol; + hostname; + port; + path; + query; + headers; + username; + password; + fragment; + body; + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol + ? options.protocol.slice(-1) !== ":" + ? `${options.protocol}:` + : options.protocol + : "https:"; + this.path = options.path ? (options.path.charAt(0) !== "/" ? `/${options.path}` : options.path) : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + static clone(request) { + const cloned = new HttpRequest({ + ...request, + headers: { ...request.headers }, + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); + } + return cloned; + } + static isInstance(request) { + if (!request) { + return false; + } + const req = request; + return ("method" in req && + "protocol" in req && + "hostname" in req && + "path" in req && + typeof req["query"] === "object" && + typeof req["headers"] === "object"); + } + clone() { + return HttpRequest.clone(this); + } +} +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param, + }; + }, {}); +} + +class HttpResponse { + statusCode; + reason; + headers; + body; + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) + return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + } +} + +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} + +exports.Field = Field; +exports.Fields = Fields; +exports.HttpRequest = HttpRequest; +exports.HttpResponse = HttpResponse; +exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration; +exports.isValidHostname = isValidHostname; +exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/types/dist-cjs/index.js new file mode 100644 index 00000000..be6d0e1a --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/types/dist-cjs/index.js @@ -0,0 +1,91 @@ +'use strict'; + +exports.HttpAuthLocation = void 0; +(function (HttpAuthLocation) { + HttpAuthLocation["HEADER"] = "header"; + HttpAuthLocation["QUERY"] = "query"; +})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); + +exports.HttpApiKeyAuthLocation = void 0; +(function (HttpApiKeyAuthLocation) { + HttpApiKeyAuthLocation["HEADER"] = "header"; + HttpApiKeyAuthLocation["QUERY"] = "query"; +})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); + +exports.EndpointURLScheme = void 0; +(function (EndpointURLScheme) { + EndpointURLScheme["HTTP"] = "http"; + EndpointURLScheme["HTTPS"] = "https"; +})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); + +exports.AlgorithmId = void 0; +(function (AlgorithmId) { + AlgorithmId["MD5"] = "md5"; + AlgorithmId["CRC32"] = "crc32"; + AlgorithmId["CRC32C"] = "crc32c"; + AlgorithmId["SHA1"] = "sha1"; + AlgorithmId["SHA256"] = "sha256"; +})(exports.AlgorithmId || (exports.AlgorithmId = {})); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.SHA256, + checksumConstructor: () => runtimeConfig.sha256, + }); + } + if (runtimeConfig.md5 != undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.MD5, + checksumConstructor: () => runtimeConfig.md5, + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getDefaultClientConfiguration = (runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}; +const resolveDefaultRuntimeConfig = (config) => { + return resolveChecksumRuntimeConfig(config); +}; + +exports.FieldPosition = void 0; +(function (FieldPosition) { + FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; + FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; +})(exports.FieldPosition || (exports.FieldPosition = {})); + +const SMITHY_CONTEXT_KEY = "__smithy_context"; + +exports.IniSectionType = void 0; +(function (IniSectionType) { + IniSectionType["PROFILE"] = "profile"; + IniSectionType["SSO_SESSION"] = "sso-session"; + IniSectionType["SERVICES"] = "services"; +})(exports.IniSectionType || (exports.IniSectionType = {})); + +exports.RequestHandlerProtocol = void 0; +(function (RequestHandlerProtocol) { + RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; +})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); + +exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-logger/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-logger/dist-cjs/index.js new file mode 100644 index 00000000..584a4faa --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/middleware-logger/dist-cjs/index.js @@ -0,0 +1,48 @@ +'use strict'; + +const loggerMiddleware = () => (next, context) => async (args) => { + try { + const response = await next(args); + const { clientName, commandName, logger, dynamoDbDocumentClientOptions = {} } = context; + const { overrideInputFilterSensitiveLog, overrideOutputFilterSensitiveLog } = dynamoDbDocumentClientOptions; + const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog; + const outputFilterSensitiveLog = overrideOutputFilterSensitiveLog ?? context.outputFilterSensitiveLog; + const { $metadata, ...outputWithoutMetadata } = response.output; + logger?.info?.({ + clientName, + commandName, + input: inputFilterSensitiveLog(args.input), + output: outputFilterSensitiveLog(outputWithoutMetadata), + metadata: $metadata, + }); + return response; + } + catch (error) { + const { clientName, commandName, logger, dynamoDbDocumentClientOptions = {} } = context; + const { overrideInputFilterSensitiveLog } = dynamoDbDocumentClientOptions; + const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog; + logger?.error?.({ + clientName, + commandName, + input: inputFilterSensitiveLog(args.input), + error, + metadata: error.$metadata, + }); + throw error; + } +}; +const loggerMiddlewareOptions = { + name: "loggerMiddleware", + tags: ["LOGGER"], + step: "initialize", + override: true, +}; +const getLoggerPlugin = (options) => ({ + applyToStack: (clientStack) => { + clientStack.add(loggerMiddleware(), loggerMiddlewareOptions); + }, +}); + +exports.getLoggerPlugin = getLoggerPlugin; +exports.loggerMiddleware = loggerMiddleware; +exports.loggerMiddlewareOptions = loggerMiddlewareOptions; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-recursion-detection/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-recursion-detection/dist-cjs/index.js new file mode 100644 index 00000000..eb8ff04c --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/middleware-recursion-detection/dist-cjs/index.js @@ -0,0 +1,25 @@ +'use strict'; + +var recursionDetectionMiddleware = require('./recursionDetectionMiddleware'); + +const recursionDetectionMiddlewareOptions = { + step: "build", + tags: ["RECURSION_DETECTION"], + name: "recursionDetectionMiddleware", + override: true, + priority: "low", +}; + +const getRecursionDetectionPlugin = (options) => ({ + applyToStack: (clientStack) => { + clientStack.add(recursionDetectionMiddleware.recursionDetectionMiddleware(), recursionDetectionMiddlewareOptions); + }, +}); + +exports.getRecursionDetectionPlugin = getRecursionDetectionPlugin; +Object.keys(recursionDetectionMiddleware).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return recursionDetectionMiddleware[k]; } + }); +}); diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-recursion-detection/dist-cjs/recursionDetectionMiddleware.js b/claude-code-source/node_modules/@aws-sdk/middleware-recursion-detection/dist-cjs/recursionDetectionMiddleware.js new file mode 100644 index 00000000..1300be08 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/middleware-recursion-detection/dist-cjs/recursionDetectionMiddleware.js @@ -0,0 +1,33 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.recursionDetectionMiddleware = void 0; +const lambda_invoke_store_1 = require("@aws/lambda-invoke-store"); +const protocol_http_1 = require("@smithy/protocol-http"); +const TRACE_ID_HEADER_NAME = "X-Amzn-Trace-Id"; +const ENV_LAMBDA_FUNCTION_NAME = "AWS_LAMBDA_FUNCTION_NAME"; +const ENV_TRACE_ID = "_X_AMZN_TRACE_ID"; +const recursionDetectionMiddleware = () => (next) => async (args) => { + const { request } = args; + if (!protocol_http_1.HttpRequest.isInstance(request)) { + return next(args); + } + const traceIdHeader = Object.keys(request.headers ?? {}).find((h) => h.toLowerCase() === TRACE_ID_HEADER_NAME.toLowerCase()) ?? + TRACE_ID_HEADER_NAME; + if (request.headers.hasOwnProperty(traceIdHeader)) { + return next(args); + } + const functionName = process.env[ENV_LAMBDA_FUNCTION_NAME]; + const traceIdFromEnv = process.env[ENV_TRACE_ID]; + const invokeStore = await lambda_invoke_store_1.InvokeStore.getInstanceAsync(); + const traceIdFromInvokeStore = invokeStore?.getXRayTraceId(); + const traceId = traceIdFromInvokeStore ?? traceIdFromEnv; + const nonEmptyString = (str) => typeof str === "string" && str.length > 0; + if (nonEmptyString(functionName) && nonEmptyString(traceId)) { + request.headers[TRACE_ID_HEADER_NAME] = traceId; + } + return next({ + ...args, + request, + }); +}; +exports.recursionDetectionMiddleware = recursionDetectionMiddleware; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/protocol-http/dist-cjs/index.js new file mode 100644 index 00000000..52303c3b --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/protocol-http/dist-cjs/index.js @@ -0,0 +1,169 @@ +'use strict'; + +var types = require('@smithy/types'); + +const getHttpHandlerExtensionConfiguration = (runtimeConfig) => { + return { + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); + }, + }; +}; +const resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler(), + }; +}; + +class Field { + name; + kind; + values; + constructor({ name, kind = types.FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; + } + add(value) { + this.values.push(value); + } + set(values) { + this.values = values; + } + remove(value) { + this.values = this.values.filter((v) => v !== value); + } + toString() { + return this.values.map((v) => (v.includes(",") || v.includes(" ") ? `"${v}"` : v)).join(", "); + } + get() { + return this.values; + } +} + +class Fields { + entries = {}; + encoding; + constructor({ fields = [], encoding = "utf-8" }) { + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + setField(field) { + this.entries[field.name.toLowerCase()] = field; + } + getField(name) { + return this.entries[name.toLowerCase()]; + } + removeField(name) { + delete this.entries[name.toLowerCase()]; + } + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } +} + +class HttpRequest { + method; + protocol; + hostname; + port; + path; + query; + headers; + username; + password; + fragment; + body; + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol + ? options.protocol.slice(-1) !== ":" + ? `${options.protocol}:` + : options.protocol + : "https:"; + this.path = options.path ? (options.path.charAt(0) !== "/" ? `/${options.path}` : options.path) : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + static clone(request) { + const cloned = new HttpRequest({ + ...request, + headers: { ...request.headers }, + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); + } + return cloned; + } + static isInstance(request) { + if (!request) { + return false; + } + const req = request; + return ("method" in req && + "protocol" in req && + "hostname" in req && + "path" in req && + typeof req["query"] === "object" && + typeof req["headers"] === "object"); + } + clone() { + return HttpRequest.clone(this); + } +} +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param, + }; + }, {}); +} + +class HttpResponse { + statusCode; + reason; + headers; + body; + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) + return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + } +} + +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} + +exports.Field = Field; +exports.Fields = Fields; +exports.HttpRequest = HttpRequest; +exports.HttpResponse = HttpResponse; +exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration; +exports.isValidHostname = isValidHostname; +exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/types/dist-cjs/index.js new file mode 100644 index 00000000..be6d0e1a --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/types/dist-cjs/index.js @@ -0,0 +1,91 @@ +'use strict'; + +exports.HttpAuthLocation = void 0; +(function (HttpAuthLocation) { + HttpAuthLocation["HEADER"] = "header"; + HttpAuthLocation["QUERY"] = "query"; +})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); + +exports.HttpApiKeyAuthLocation = void 0; +(function (HttpApiKeyAuthLocation) { + HttpApiKeyAuthLocation["HEADER"] = "header"; + HttpApiKeyAuthLocation["QUERY"] = "query"; +})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); + +exports.EndpointURLScheme = void 0; +(function (EndpointURLScheme) { + EndpointURLScheme["HTTP"] = "http"; + EndpointURLScheme["HTTPS"] = "https"; +})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); + +exports.AlgorithmId = void 0; +(function (AlgorithmId) { + AlgorithmId["MD5"] = "md5"; + AlgorithmId["CRC32"] = "crc32"; + AlgorithmId["CRC32C"] = "crc32c"; + AlgorithmId["SHA1"] = "sha1"; + AlgorithmId["SHA256"] = "sha256"; +})(exports.AlgorithmId || (exports.AlgorithmId = {})); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.SHA256, + checksumConstructor: () => runtimeConfig.sha256, + }); + } + if (runtimeConfig.md5 != undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.MD5, + checksumConstructor: () => runtimeConfig.md5, + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getDefaultClientConfiguration = (runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}; +const resolveDefaultRuntimeConfig = (config) => { + return resolveChecksumRuntimeConfig(config); +}; + +exports.FieldPosition = void 0; +(function (FieldPosition) { + FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; + FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; +})(exports.FieldPosition || (exports.FieldPosition = {})); + +const SMITHY_CONTEXT_KEY = "__smithy_context"; + +exports.IniSectionType = void 0; +(function (IniSectionType) { + IniSectionType["PROFILE"] = "profile"; + IniSectionType["SSO_SESSION"] = "sso-session"; + IniSectionType["SERVICES"] = "services"; +})(exports.IniSectionType || (exports.IniSectionType = {})); + +exports.RequestHandlerProtocol = void 0; +(function (RequestHandlerProtocol) { + RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; +})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); + +exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-user-agent/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-user-agent/dist-cjs/index.js new file mode 100644 index 00000000..d5c19882 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/middleware-user-agent/dist-cjs/index.js @@ -0,0 +1,194 @@ +'use strict'; + +var core = require('@smithy/core'); +var utilEndpoints = require('@aws-sdk/util-endpoints'); +var protocolHttp = require('@smithy/protocol-http'); +var core$1 = require('@aws-sdk/core'); + +const DEFAULT_UA_APP_ID = undefined; +function isValidUserAgentAppId(appId) { + if (appId === undefined) { + return true; + } + return typeof appId === "string" && appId.length <= 50; +} +function resolveUserAgentConfig(input) { + const normalizedAppIdProvider = core.normalizeProvider(input.userAgentAppId ?? DEFAULT_UA_APP_ID); + const { customUserAgent } = input; + return Object.assign(input, { + customUserAgent: typeof customUserAgent === "string" ? [[customUserAgent]] : customUserAgent, + userAgentAppId: async () => { + const appId = await normalizedAppIdProvider(); + if (!isValidUserAgentAppId(appId)) { + const logger = input.logger?.constructor?.name === "NoOpLogger" || !input.logger ? console : input.logger; + if (typeof appId !== "string") { + logger?.warn("userAgentAppId must be a string or undefined."); + } + else if (appId.length > 50) { + logger?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters."); + } + } + return appId; + }, + }); +} + +const ACCOUNT_ID_ENDPOINT_REGEX = /\d{12}\.ddb/; +async function checkFeatures(context, config, args) { + const request = args.request; + if (request?.headers?.["smithy-protocol"] === "rpc-v2-cbor") { + core$1.setFeature(context, "PROTOCOL_RPC_V2_CBOR", "M"); + } + if (typeof config.retryStrategy === "function") { + const retryStrategy = await config.retryStrategy(); + if (typeof retryStrategy.acquireInitialRetryToken === "function") { + if (retryStrategy.constructor?.name?.includes("Adaptive")) { + core$1.setFeature(context, "RETRY_MODE_ADAPTIVE", "F"); + } + else { + core$1.setFeature(context, "RETRY_MODE_STANDARD", "E"); + } + } + else { + core$1.setFeature(context, "RETRY_MODE_LEGACY", "D"); + } + } + if (typeof config.accountIdEndpointMode === "function") { + const endpointV2 = context.endpointV2; + if (String(endpointV2?.url?.hostname).match(ACCOUNT_ID_ENDPOINT_REGEX)) { + core$1.setFeature(context, "ACCOUNT_ID_ENDPOINT", "O"); + } + switch (await config.accountIdEndpointMode?.()) { + case "disabled": + core$1.setFeature(context, "ACCOUNT_ID_MODE_DISABLED", "Q"); + break; + case "preferred": + core$1.setFeature(context, "ACCOUNT_ID_MODE_PREFERRED", "P"); + break; + case "required": + core$1.setFeature(context, "ACCOUNT_ID_MODE_REQUIRED", "R"); + break; + } + } + const identity = context.__smithy_context?.selectedHttpAuthScheme?.identity; + if (identity?.$source) { + const credentials = identity; + if (credentials.accountId) { + core$1.setFeature(context, "RESOLVED_ACCOUNT_ID", "T"); + } + for (const [key, value] of Object.entries(credentials.$source ?? {})) { + core$1.setFeature(context, key, value); + } + } +} + +const USER_AGENT = "user-agent"; +const X_AMZ_USER_AGENT = "x-amz-user-agent"; +const SPACE = " "; +const UA_NAME_SEPARATOR = "/"; +const UA_NAME_ESCAPE_REGEX = /[^!$%&'*+\-.^_`|~\w]/g; +const UA_VALUE_ESCAPE_REGEX = /[^!$%&'*+\-.^_`|~\w#]/g; +const UA_ESCAPE_CHAR = "-"; + +const BYTE_LIMIT = 1024; +function encodeFeatures(features) { + let buffer = ""; + for (const key in features) { + const val = features[key]; + if (buffer.length + val.length + 1 <= BYTE_LIMIT) { + if (buffer.length) { + buffer += "," + val; + } + else { + buffer += val; + } + continue; + } + break; + } + return buffer; +} + +const userAgentMiddleware = (options) => (next, context) => async (args) => { + const { request } = args; + if (!protocolHttp.HttpRequest.isInstance(request)) { + return next(args); + } + const { headers } = request; + const userAgent = context?.userAgent?.map(escapeUserAgent) || []; + const defaultUserAgent = (await options.defaultUserAgentProvider()).map(escapeUserAgent); + await checkFeatures(context, options, args); + const awsContext = context; + defaultUserAgent.push(`m/${encodeFeatures(Object.assign({}, context.__smithy_context?.features, awsContext.__aws_sdk_context?.features))}`); + const customUserAgent = options?.customUserAgent?.map(escapeUserAgent) || []; + const appId = await options.userAgentAppId(); + if (appId) { + defaultUserAgent.push(escapeUserAgent([`app`, `${appId}`])); + } + const prefix = utilEndpoints.getUserAgentPrefix(); + const sdkUserAgentValue = (prefix ? [prefix] : []) + .concat([...defaultUserAgent, ...userAgent, ...customUserAgent]) + .join(SPACE); + const normalUAValue = [ + ...defaultUserAgent.filter((section) => section.startsWith("aws-sdk-")), + ...customUserAgent, + ].join(SPACE); + if (options.runtime !== "browser") { + if (normalUAValue) { + headers[X_AMZ_USER_AGENT] = headers[X_AMZ_USER_AGENT] + ? `${headers[USER_AGENT]} ${normalUAValue}` + : normalUAValue; + } + headers[USER_AGENT] = sdkUserAgentValue; + } + else { + headers[X_AMZ_USER_AGENT] = sdkUserAgentValue; + } + return next({ + ...args, + request, + }); +}; +const escapeUserAgent = (userAgentPair) => { + const name = userAgentPair[0] + .split(UA_NAME_SEPARATOR) + .map((part) => part.replace(UA_NAME_ESCAPE_REGEX, UA_ESCAPE_CHAR)) + .join(UA_NAME_SEPARATOR); + const version = userAgentPair[1]?.replace(UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR); + const prefixSeparatorIndex = name.indexOf(UA_NAME_SEPARATOR); + const prefix = name.substring(0, prefixSeparatorIndex); + let uaName = name.substring(prefixSeparatorIndex + 1); + if (prefix === "api") { + uaName = uaName.toLowerCase(); + } + return [prefix, uaName, version] + .filter((item) => item && item.length > 0) + .reduce((acc, item, index) => { + switch (index) { + case 0: + return item; + case 1: + return `${acc}/${item}`; + default: + return `${acc}#${item}`; + } + }, ""); +}; +const getUserAgentMiddlewareOptions = { + name: "getUserAgentMiddleware", + step: "build", + priority: "low", + tags: ["SET_USER_AGENT", "USER_AGENT"], + override: true, +}; +const getUserAgentPlugin = (config) => ({ + applyToStack: (clientStack) => { + clientStack.add(userAgentMiddleware(config), getUserAgentMiddlewareOptions); + }, +}); + +exports.DEFAULT_UA_APP_ID = DEFAULT_UA_APP_ID; +exports.getUserAgentMiddlewareOptions = getUserAgentMiddlewareOptions; +exports.getUserAgentPlugin = getUserAgentPlugin; +exports.resolveUserAgentConfig = resolveUserAgentConfig; +exports.userAgentMiddleware = userAgentMiddleware; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/protocol-http/dist-cjs/index.js new file mode 100644 index 00000000..52303c3b --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/protocol-http/dist-cjs/index.js @@ -0,0 +1,169 @@ +'use strict'; + +var types = require('@smithy/types'); + +const getHttpHandlerExtensionConfiguration = (runtimeConfig) => { + return { + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); + }, + }; +}; +const resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler(), + }; +}; + +class Field { + name; + kind; + values; + constructor({ name, kind = types.FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; + } + add(value) { + this.values.push(value); + } + set(values) { + this.values = values; + } + remove(value) { + this.values = this.values.filter((v) => v !== value); + } + toString() { + return this.values.map((v) => (v.includes(",") || v.includes(" ") ? `"${v}"` : v)).join(", "); + } + get() { + return this.values; + } +} + +class Fields { + entries = {}; + encoding; + constructor({ fields = [], encoding = "utf-8" }) { + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + setField(field) { + this.entries[field.name.toLowerCase()] = field; + } + getField(name) { + return this.entries[name.toLowerCase()]; + } + removeField(name) { + delete this.entries[name.toLowerCase()]; + } + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } +} + +class HttpRequest { + method; + protocol; + hostname; + port; + path; + query; + headers; + username; + password; + fragment; + body; + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol + ? options.protocol.slice(-1) !== ":" + ? `${options.protocol}:` + : options.protocol + : "https:"; + this.path = options.path ? (options.path.charAt(0) !== "/" ? `/${options.path}` : options.path) : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + static clone(request) { + const cloned = new HttpRequest({ + ...request, + headers: { ...request.headers }, + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); + } + return cloned; + } + static isInstance(request) { + if (!request) { + return false; + } + const req = request; + return ("method" in req && + "protocol" in req && + "hostname" in req && + "path" in req && + typeof req["query"] === "object" && + typeof req["headers"] === "object"); + } + clone() { + return HttpRequest.clone(this); + } +} +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param, + }; + }, {}); +} + +class HttpResponse { + statusCode; + reason; + headers; + body; + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) + return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + } +} + +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} + +exports.Field = Field; +exports.Fields = Fields; +exports.HttpRequest = HttpRequest; +exports.HttpResponse = HttpResponse; +exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration; +exports.isValidHostname = isValidHostname; +exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/types/dist-cjs/index.js new file mode 100644 index 00000000..be6d0e1a --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/types/dist-cjs/index.js @@ -0,0 +1,91 @@ +'use strict'; + +exports.HttpAuthLocation = void 0; +(function (HttpAuthLocation) { + HttpAuthLocation["HEADER"] = "header"; + HttpAuthLocation["QUERY"] = "query"; +})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); + +exports.HttpApiKeyAuthLocation = void 0; +(function (HttpApiKeyAuthLocation) { + HttpApiKeyAuthLocation["HEADER"] = "header"; + HttpApiKeyAuthLocation["QUERY"] = "query"; +})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); + +exports.EndpointURLScheme = void 0; +(function (EndpointURLScheme) { + EndpointURLScheme["HTTP"] = "http"; + EndpointURLScheme["HTTPS"] = "https"; +})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); + +exports.AlgorithmId = void 0; +(function (AlgorithmId) { + AlgorithmId["MD5"] = "md5"; + AlgorithmId["CRC32"] = "crc32"; + AlgorithmId["CRC32C"] = "crc32c"; + AlgorithmId["SHA1"] = "sha1"; + AlgorithmId["SHA256"] = "sha256"; +})(exports.AlgorithmId || (exports.AlgorithmId = {})); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.SHA256, + checksumConstructor: () => runtimeConfig.sha256, + }); + } + if (runtimeConfig.md5 != undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.MD5, + checksumConstructor: () => runtimeConfig.md5, + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getDefaultClientConfiguration = (runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}; +const resolveDefaultRuntimeConfig = (config) => { + return resolveChecksumRuntimeConfig(config); +}; + +exports.FieldPosition = void 0; +(function (FieldPosition) { + FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; + FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; +})(exports.FieldPosition || (exports.FieldPosition = {})); + +const SMITHY_CONTEXT_KEY = "__smithy_context"; + +exports.IniSectionType = void 0; +(function (IniSectionType) { + IniSectionType["PROFILE"] = "profile"; + IniSectionType["SSO_SESSION"] = "sso-session"; + IniSectionType["SERVICES"] = "services"; +})(exports.IniSectionType || (exports.IniSectionType = {})); + +exports.RequestHandlerProtocol = void 0; +(function (RequestHandlerProtocol) { + RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; +})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); + +exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/dist-cjs/index.js new file mode 100644 index 00000000..d287b222 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/dist-cjs/index.js @@ -0,0 +1,347 @@ +'use strict'; + +var eventstreamCodec = require('@smithy/eventstream-codec'); +var utilHexEncoding = require('@smithy/util-hex-encoding'); +var protocolHttp = require('@smithy/protocol-http'); +var utilFormatUrl = require('@aws-sdk/util-format-url'); +var eventstreamSerdeBrowser = require('@smithy/eventstream-serde-browser'); +var fetchHttpHandler = require('@smithy/fetch-http-handler'); + +const getEventSigningTransformStream = (initialSignature, messageSigner, eventStreamCodec, systemClockOffsetProvider) => { + let priorSignature = initialSignature; + const transformer = { + start() { }, + async transform(chunk, controller) { + try { + const now = new Date(Date.now() + (await systemClockOffsetProvider())); + const dateHeader = { + ":date": { type: "timestamp", value: now }, + }; + const signedMessage = await messageSigner.sign({ + message: { + body: chunk, + headers: dateHeader, + }, + priorSignature: priorSignature, + }, { + signingDate: now, + }); + priorSignature = signedMessage.signature; + const serializedSigned = eventStreamCodec.encode({ + headers: { + ...dateHeader, + ":chunk-signature": { + type: "binary", + value: utilHexEncoding.fromHex(signedMessage.signature), + }, + }, + body: chunk, + }); + controller.enqueue(serializedSigned); + } + catch (error) { + controller.error(error); + } + }, + }; + return new TransformStream({ ...transformer }); +}; + +class EventStreamPayloadHandler { + messageSigner; + eventStreamCodec; + systemClockOffsetProvider; + constructor(options) { + this.messageSigner = options.messageSigner; + this.eventStreamCodec = new eventstreamCodec.EventStreamCodec(options.utf8Encoder, options.utf8Decoder); + this.systemClockOffsetProvider = async () => options.systemClockOffset ?? 0; + } + async handle(next, args, context = {}) { + const request = args.request; + const { body: payload, headers, query } = request; + if (!(payload instanceof ReadableStream)) { + throw new Error("Eventstream payload must be a ReadableStream."); + } + const placeHolderStream = new TransformStream(); + request.body = placeHolderStream.readable; + let result; + try { + result = await next(args); + } + catch (e) { + request.body.cancel(); + throw e; + } + const match = (headers["authorization"] || "").match(/Signature=([\w]+)$/); + const priorSignature = (match || [])[1] || (query && query["X-Amz-Signature"]) || ""; + const signingStream = getEventSigningTransformStream(priorSignature, await this.messageSigner(), this.eventStreamCodec, this.systemClockOffsetProvider); + const signedPayload = payload.pipeThrough(signingStream); + signedPayload.pipeThrough(placeHolderStream); + return result; + } +} + +const eventStreamPayloadHandlerProvider = (options) => new EventStreamPayloadHandler(options); + +const injectSessionIdMiddleware = () => (next) => async (args) => { + const requestParams = { + ...args.input, + }; + const response = await next(args); + const output = response.output; + if (requestParams.SessionId && output.SessionId == null) { + output.SessionId = requestParams.SessionId; + } + return response; +}; +const injectSessionIdMiddlewareOptions = { + step: "initialize", + name: "injectSessionIdMiddleware", + tags: ["WEBSOCKET", "EVENT_STREAM"], + override: true, +}; + +const websocketEndpointMiddleware = (config, options) => (next) => (args) => { + const { request } = args; + if (protocolHttp.HttpRequest.isInstance(request) && + config.requestHandler.metadata?.handlerProtocol?.toLowerCase().includes("websocket")) { + request.protocol = "wss:"; + request.method = "GET"; + request.path = `${request.path}-websocket`; + const { headers } = request; + delete headers["content-type"]; + delete headers["x-amz-content-sha256"]; + for (const name of Object.keys(headers)) { + if (name.indexOf(options.headerPrefix) === 0) { + const chunkedName = name.replace(options.headerPrefix, ""); + request.query[chunkedName] = headers[name]; + } + } + if (headers["x-amz-user-agent"]) { + request.query["user-agent"] = headers["x-amz-user-agent"]; + } + request.headers = { host: headers.host ?? request.hostname }; + } + return next(args); +}; +const websocketEndpointMiddlewareOptions = { + name: "websocketEndpointMiddleware", + tags: ["WEBSOCKET", "EVENT_STREAM"], + relation: "after", + toMiddleware: "eventStreamHeaderMiddleware", + override: true, +}; + +const getWebSocketPlugin = (config, options) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(websocketEndpointMiddleware(config, options), websocketEndpointMiddlewareOptions); + clientStack.add(injectSessionIdMiddleware(), injectSessionIdMiddlewareOptions); + }, +}); + +const isWebSocketRequest = (request) => request.protocol === "ws:" || request.protocol === "wss:"; + +class WebsocketSignatureV4 { + signer; + constructor(options) { + this.signer = options.signer; + } + presign(originalRequest, options = {}) { + return this.signer.presign(originalRequest, options); + } + async sign(toSign, options) { + if (protocolHttp.HttpRequest.isInstance(toSign) && isWebSocketRequest(toSign)) { + const signedRequest = await this.signer.presign({ ...toSign, body: "" }, { + ...options, + expiresIn: 60, + unsignableHeaders: new Set(Object.keys(toSign.headers).filter((header) => header !== "host")), + }); + return { + ...signedRequest, + body: toSign.body, + }; + } + else { + return this.signer.sign(toSign, options); + } + } +} + +const resolveWebSocketConfig = (input) => { + const { signer } = input; + return Object.assign(input, { + signer: async (authScheme) => { + const signerObj = await signer(authScheme); + if (validateSigner(signerObj)) { + return new WebsocketSignatureV4({ signer: signerObj }); + } + throw new Error("Expected WebsocketSignatureV4 signer, please check the client constructor."); + }, + }); +}; +const validateSigner = (signer) => !!signer; + +const DEFAULT_WS_CONNECTION_TIMEOUT_MS = 2000; +class WebSocketFetchHandler { + metadata = { + handlerProtocol: "websocket/h1.1", + }; + config; + configPromise; + httpHandler; + sockets = {}; + static create(instanceOrOptions, httpHandler = new fetchHttpHandler.FetchHttpHandler()) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; + } + return new WebSocketFetchHandler(instanceOrOptions, httpHandler); + } + constructor(options, httpHandler = new fetchHttpHandler.FetchHttpHandler()) { + this.httpHandler = httpHandler; + if (typeof options === "function") { + this.config = {}; + this.configPromise = options().then((opts) => (this.config = opts ?? {})); + } + else { + this.config = options ?? {}; + this.configPromise = Promise.resolve(this.config); + } + } + destroy() { + for (const [key, sockets] of Object.entries(this.sockets)) { + for (const socket of sockets) { + socket.close(1000, `Socket closed through destroy() call`); + } + delete this.sockets[key]; + } + } + async handle(request) { + if (!isWebSocketRequest(request)) { + return this.httpHandler.handle(request); + } + const url = utilFormatUrl.formatUrl(request); + const socket = new WebSocket(url); + if (!this.sockets[url]) { + this.sockets[url] = []; + } + this.sockets[url].push(socket); + socket.binaryType = "arraybuffer"; + this.config = await this.configPromise; + const { connectionTimeout = DEFAULT_WS_CONNECTION_TIMEOUT_MS } = this.config; + await this.waitForReady(socket, connectionTimeout); + const { body } = request; + const bodyStream = getIterator(body); + const asyncIterable = this.connect(socket, bodyStream); + const outputPayload = toReadableStream(asyncIterable); + return { + response: new protocolHttp.HttpResponse({ + statusCode: 200, + body: outputPayload, + }), + }; + } + updateHttpClientConfig(key, value) { + this.configPromise = this.configPromise.then((config) => { + config[key] = value; + return config; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; + } + removeNotUsableSockets(url) { + this.sockets[url] = (this.sockets[url] ?? []).filter((socket) => ![WebSocket.CLOSING, WebSocket.CLOSED].includes(socket.readyState)); + } + waitForReady(socket, connectionTimeout) { + return new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + this.removeNotUsableSockets(socket.url); + reject({ + $metadata: { + httpStatusCode: 500, + }, + }); + }, connectionTimeout); + socket.onopen = () => { + clearTimeout(timeout); + resolve(); + }; + }); + } + connect(socket, data) { + let streamError = undefined; + let socketErrorOccurred = false; + let reject = () => { }; + let resolve = () => { }; + socket.onmessage = (event) => { + resolve({ + done: false, + value: new Uint8Array(event.data), + }); + }; + socket.onerror = (error) => { + socketErrorOccurred = true; + socket.close(); + reject(error); + }; + socket.onclose = () => { + this.removeNotUsableSockets(socket.url); + if (socketErrorOccurred) + return; + if (streamError) { + reject(streamError); + } + else { + resolve({ + done: true, + value: undefined, + }); + } + }; + const outputStream = { + [Symbol.asyncIterator]: () => ({ + next: () => { + return new Promise((_resolve, _reject) => { + resolve = _resolve; + reject = _reject; + }); + }, + }), + }; + const send = async () => { + try { + for await (const inputChunk of data) { + socket.send(inputChunk); + } + } + catch (err) { + streamError = err; + } + finally { + socket.close(1000); + } + }; + send(); + return outputStream; + } +} +const getIterator = (stream) => { + if (stream[Symbol.asyncIterator]) { + return stream; + } + if (isReadableStream(stream)) { + return eventstreamSerdeBrowser.readableStreamtoIterable(stream); + } + return { + [Symbol.asyncIterator]: async function* () { + yield stream; + }, + }; +}; +const toReadableStream = (asyncIterable) => typeof ReadableStream === "function" ? eventstreamSerdeBrowser.iterableToReadableStream(asyncIterable) : asyncIterable; +const isReadableStream = (payload) => typeof ReadableStream === "function" && payload instanceof ReadableStream; + +exports.WebSocketFetchHandler = WebSocketFetchHandler; +exports.eventStreamPayloadHandlerProvider = eventStreamPayloadHandlerProvider; +exports.getWebSocketPlugin = getWebSocketPlugin; +exports.resolveWebSocketConfig = resolveWebSocketConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/dist-cjs/index.js new file mode 100644 index 00000000..e6673dc8 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/dist-cjs/index.js @@ -0,0 +1,216 @@ +'use strict'; + +var protocolHttp = require('@smithy/protocol-http'); +var querystringBuilder = require('@smithy/querystring-builder'); +var utilBase64 = require('@smithy/util-base64'); + +function createRequest(url, requestOptions) { + return new Request(url, requestOptions); +} + +function requestTimeout(timeoutInMs = 0) { + return new Promise((resolve, reject) => { + if (timeoutInMs) { + setTimeout(() => { + const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`); + timeoutError.name = "TimeoutError"; + reject(timeoutError); + }, timeoutInMs); + } + }); +} + +const keepAliveSupport = { + supported: undefined, +}; +class FetchHttpHandler { + config; + configProvider; + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; + } + return new FetchHttpHandler(instanceOrOptions); + } + constructor(options) { + if (typeof options === "function") { + this.configProvider = options().then((opts) => opts || {}); + } + else { + this.config = options ?? {}; + this.configProvider = Promise.resolve(this.config); + } + if (keepAliveSupport.supported === undefined) { + keepAliveSupport.supported = Boolean(typeof Request !== "undefined" && "keepalive" in createRequest("https://[::1]")); + } + } + destroy() { + } + async handle(request, { abortSignal, requestTimeout: requestTimeout$1 } = {}) { + if (!this.config) { + this.config = await this.configProvider; + } + const requestTimeoutInMs = requestTimeout$1 ?? this.config.requestTimeout; + const keepAlive = this.config.keepAlive === true; + const credentials = this.config.credentials; + if (abortSignal?.aborted) { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + return Promise.reject(abortError); + } + let path = request.path; + const queryString = querystringBuilder.buildQueryString(request.query || {}); + if (queryString) { + path += `?${queryString}`; + } + if (request.fragment) { + path += `#${request.fragment}`; + } + let auth = ""; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}@`; + } + const { port, method } = request; + const url = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : ""}${path}`; + const body = method === "GET" || method === "HEAD" ? undefined : request.body; + const requestOptions = { + body, + headers: new Headers(request.headers), + method: method, + credentials, + }; + if (this.config?.cache) { + requestOptions.cache = this.config.cache; + } + if (body) { + requestOptions.duplex = "half"; + } + if (typeof AbortController !== "undefined") { + requestOptions.signal = abortSignal; + } + if (keepAliveSupport.supported) { + requestOptions.keepalive = keepAlive; + } + if (typeof this.config.requestInit === "function") { + Object.assign(requestOptions, this.config.requestInit(request)); + } + let removeSignalEventListener = () => { }; + const fetchRequest = createRequest(url, requestOptions); + const raceOfPromises = [ + fetch(fetchRequest).then((response) => { + const fetchHeaders = response.headers; + const transformedHeaders = {}; + for (const pair of fetchHeaders.entries()) { + transformedHeaders[pair[0]] = pair[1]; + } + const hasReadableStream = response.body != undefined; + if (!hasReadableStream) { + return response.blob().then((body) => ({ + response: new protocolHttp.HttpResponse({ + headers: transformedHeaders, + reason: response.statusText, + statusCode: response.status, + body, + }), + })); + } + return { + response: new protocolHttp.HttpResponse({ + headers: transformedHeaders, + reason: response.statusText, + statusCode: response.status, + body: response.body, + }), + }; + }), + requestTimeout(requestTimeoutInMs), + ]; + if (abortSignal) { + raceOfPromises.push(new Promise((resolve, reject) => { + const onAbort = () => { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + }; + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + removeSignalEventListener = () => signal.removeEventListener("abort", onAbort); + } + else { + abortSignal.onabort = onAbort; + } + })); + } + return Promise.race(raceOfPromises).finally(removeSignalEventListener); + } + updateHttpClientConfig(key, value) { + this.config = undefined; + this.configProvider = this.configProvider.then((config) => { + config[key] = value; + return config; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; + } +} + +const streamCollector = async (stream) => { + if ((typeof Blob === "function" && stream instanceof Blob) || stream.constructor?.name === "Blob") { + if (Blob.prototype.arrayBuffer !== undefined) { + return new Uint8Array(await stream.arrayBuffer()); + } + return collectBlob(stream); + } + return collectStream(stream); +}; +async function collectBlob(blob) { + const base64 = await readToBase64(blob); + const arrayBuffer = utilBase64.fromBase64(base64); + return new Uint8Array(arrayBuffer); +} +async function collectStream(stream) { + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + let length = 0; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + length += value.length; + } + isDone = done; + } + const collected = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + collected.set(chunk, offset); + offset += chunk.length; + } + return collected; +} +function readToBase64(blob) { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onloadend = () => { + if (reader.readyState !== 2) { + return reject(new Error("Reader aborted too early")); + } + const result = (reader.result ?? ""); + const commaIndex = result.indexOf(","); + const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length; + resolve(result.substring(dataOffset)); + }; + reader.onabort = () => reject(new Error("Read aborted")); + reader.onerror = () => reject(reader.error); + reader.readAsDataURL(blob); + }); +} + +exports.FetchHttpHandler = FetchHttpHandler; +exports.keepAliveSupport = keepAliveSupport; +exports.streamCollector = streamCollector; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/querystring-builder/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/querystring-builder/dist-cjs/index.js new file mode 100644 index 00000000..f245489f --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/querystring-builder/dist-cjs/index.js @@ -0,0 +1,26 @@ +'use strict'; + +var utilUriEscape = require('@smithy/util-uri-escape'); + +function buildQueryString(query) { + const parts = []; + for (let key of Object.keys(query).sort()) { + const value = query[key]; + key = utilUriEscape.escapeUri(key); + if (Array.isArray(value)) { + for (let i = 0, iLen = value.length; i < iLen; i++) { + parts.push(`${key}=${utilUriEscape.escapeUri(value[i])}`); + } + } + else { + let qsEntry = key; + if (value || typeof value === "string") { + qsEntry += `=${utilUriEscape.escapeUri(value)}`; + } + parts.push(qsEntry); + } + } + return parts.join("&"); +} + +exports.buildQueryString = buildQueryString; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js new file mode 100644 index 00000000..11f942c3 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js @@ -0,0 +1,9 @@ +'use strict'; + +const escapeUri = (uri) => encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode); +const hexEncode = (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`; + +const escapeUriPath = (uri) => uri.split("/").map(escapeUri).join("/"); + +exports.escapeUri = escapeUri; +exports.escapeUriPath = escapeUriPath; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js new file mode 100644 index 00000000..b06a7b87 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromBase64 = void 0; +const util_buffer_from_1 = require("@smithy/util-buffer-from"); +const BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; +const fromBase64 = (input) => { + if ((input.length * 3) % 4 !== 0) { + throw new TypeError(`Incorrect padding on base64 string.`); + } + if (!BASE64_REGEX.exec(input)) { + throw new TypeError(`Invalid base64 string.`); + } + const buffer = (0, util_buffer_from_1.fromString)(input, "base64"); + return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); +}; +exports.fromBase64 = fromBase64; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/index.js new file mode 100644 index 00000000..c095e288 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/index.js @@ -0,0 +1,19 @@ +'use strict'; + +var fromBase64 = require('./fromBase64'); +var toBase64 = require('./toBase64'); + + + +Object.keys(fromBase64).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return fromBase64[k]; } + }); +}); +Object.keys(toBase64).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return toBase64[k]; } + }); +}); diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/toBase64.js b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/toBase64.js new file mode 100644 index 00000000..0590ce3f --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/toBase64.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.toBase64 = void 0; +const util_buffer_from_1 = require("@smithy/util-buffer-from"); +const util_utf8_1 = require("@smithy/util-utf8"); +const toBase64 = (_input) => { + let input; + if (typeof _input === "string") { + input = (0, util_utf8_1.fromUtf8)(_input); + } + else { + input = _input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); + } + return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64"); +}; +exports.toBase64 = toBase64; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js new file mode 100644 index 00000000..b577c9ca --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js @@ -0,0 +1,20 @@ +'use strict'; + +var isArrayBuffer = require('@smithy/is-array-buffer'); +var buffer = require('buffer'); + +const fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => { + if (!isArrayBuffer.isArrayBuffer(input)) { + throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); + } + return buffer.Buffer.from(input, offset, length); +}; +const fromString = (input, encoding) => { + if (typeof input !== "string") { + throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); + } + return encoding ? buffer.Buffer.from(input, encoding) : buffer.Buffer.from(input); +}; + +exports.fromArrayBuffer = fromArrayBuffer; +exports.fromString = fromString; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js new file mode 100644 index 00000000..3238bb77 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js @@ -0,0 +1,6 @@ +'use strict'; + +const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) || + Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; + +exports.isArrayBuffer = isArrayBuffer; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/protocol-http/dist-cjs/index.js new file mode 100644 index 00000000..52303c3b --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/protocol-http/dist-cjs/index.js @@ -0,0 +1,169 @@ +'use strict'; + +var types = require('@smithy/types'); + +const getHttpHandlerExtensionConfiguration = (runtimeConfig) => { + return { + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); + }, + }; +}; +const resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler(), + }; +}; + +class Field { + name; + kind; + values; + constructor({ name, kind = types.FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; + } + add(value) { + this.values.push(value); + } + set(values) { + this.values = values; + } + remove(value) { + this.values = this.values.filter((v) => v !== value); + } + toString() { + return this.values.map((v) => (v.includes(",") || v.includes(" ") ? `"${v}"` : v)).join(", "); + } + get() { + return this.values; + } +} + +class Fields { + entries = {}; + encoding; + constructor({ fields = [], encoding = "utf-8" }) { + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + setField(field) { + this.entries[field.name.toLowerCase()] = field; + } + getField(name) { + return this.entries[name.toLowerCase()]; + } + removeField(name) { + delete this.entries[name.toLowerCase()]; + } + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } +} + +class HttpRequest { + method; + protocol; + hostname; + port; + path; + query; + headers; + username; + password; + fragment; + body; + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol + ? options.protocol.slice(-1) !== ":" + ? `${options.protocol}:` + : options.protocol + : "https:"; + this.path = options.path ? (options.path.charAt(0) !== "/" ? `/${options.path}` : options.path) : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + static clone(request) { + const cloned = new HttpRequest({ + ...request, + headers: { ...request.headers }, + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); + } + return cloned; + } + static isInstance(request) { + if (!request) { + return false; + } + const req = request; + return ("method" in req && + "protocol" in req && + "hostname" in req && + "path" in req && + typeof req["query"] === "object" && + typeof req["headers"] === "object"); + } + clone() { + return HttpRequest.clone(this); + } +} +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param, + }; + }, {}); +} + +class HttpResponse { + statusCode; + reason; + headers; + body; + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) + return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + } +} + +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} + +exports.Field = Field; +exports.Fields = Fields; +exports.HttpRequest = HttpRequest; +exports.HttpResponse = HttpResponse; +exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration; +exports.isValidHostname = isValidHostname; +exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/types/dist-cjs/index.js new file mode 100644 index 00000000..be6d0e1a --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/types/dist-cjs/index.js @@ -0,0 +1,91 @@ +'use strict'; + +exports.HttpAuthLocation = void 0; +(function (HttpAuthLocation) { + HttpAuthLocation["HEADER"] = "header"; + HttpAuthLocation["QUERY"] = "query"; +})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); + +exports.HttpApiKeyAuthLocation = void 0; +(function (HttpApiKeyAuthLocation) { + HttpApiKeyAuthLocation["HEADER"] = "header"; + HttpApiKeyAuthLocation["QUERY"] = "query"; +})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); + +exports.EndpointURLScheme = void 0; +(function (EndpointURLScheme) { + EndpointURLScheme["HTTP"] = "http"; + EndpointURLScheme["HTTPS"] = "https"; +})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); + +exports.AlgorithmId = void 0; +(function (AlgorithmId) { + AlgorithmId["MD5"] = "md5"; + AlgorithmId["CRC32"] = "crc32"; + AlgorithmId["CRC32C"] = "crc32c"; + AlgorithmId["SHA1"] = "sha1"; + AlgorithmId["SHA256"] = "sha256"; +})(exports.AlgorithmId || (exports.AlgorithmId = {})); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.SHA256, + checksumConstructor: () => runtimeConfig.sha256, + }); + } + if (runtimeConfig.md5 != undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.MD5, + checksumConstructor: () => runtimeConfig.md5, + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getDefaultClientConfiguration = (runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}; +const resolveDefaultRuntimeConfig = (config) => { + return resolveChecksumRuntimeConfig(config); +}; + +exports.FieldPosition = void 0; +(function (FieldPosition) { + FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; + FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; +})(exports.FieldPosition || (exports.FieldPosition = {})); + +const SMITHY_CONTEXT_KEY = "__smithy_context"; + +exports.IniSectionType = void 0; +(function (IniSectionType) { + IniSectionType["PROFILE"] = "profile"; + IniSectionType["SSO_SESSION"] = "sso-session"; + IniSectionType["SERVICES"] = "services"; +})(exports.IniSectionType || (exports.IniSectionType = {})); + +exports.RequestHandlerProtocol = void 0; +(function (RequestHandlerProtocol) { + RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; +})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); + +exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js new file mode 100644 index 00000000..6d1eb2d1 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js @@ -0,0 +1,38 @@ +'use strict'; + +const SHORT_TO_HEX = {}; +const HEX_TO_SHORT = {}; +for (let i = 0; i < 256; i++) { + let encodedByte = i.toString(16).toLowerCase(); + if (encodedByte.length === 1) { + encodedByte = `0${encodedByte}`; + } + SHORT_TO_HEX[i] = encodedByte; + HEX_TO_SHORT[encodedByte] = i; +} +function fromHex(encoded) { + if (encoded.length % 2 !== 0) { + throw new Error("Hex encoded strings must have an even number length"); + } + const out = new Uint8Array(encoded.length / 2); + for (let i = 0; i < encoded.length; i += 2) { + const encodedByte = encoded.slice(i, i + 2).toLowerCase(); + if (encodedByte in HEX_TO_SHORT) { + out[i / 2] = HEX_TO_SHORT[encodedByte]; + } + else { + throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); + } + } + return out; +} +function toHex(bytes) { + let out = ""; + for (let i = 0; i < bytes.byteLength; i++) { + out += SHORT_TO_HEX[bytes[i]]; + } + return out; +} + +exports.fromHex = fromHex; +exports.toHex = toHex; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/auth/httpAuthSchemeProvider.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/auth/httpAuthSchemeProvider.js new file mode 100644 index 00000000..024a9fd2 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/auth/httpAuthSchemeProvider.js @@ -0,0 +1,56 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.resolveHttpAuthSchemeConfig = exports.defaultSigninHttpAuthSchemeProvider = exports.defaultSigninHttpAuthSchemeParametersProvider = void 0; +const core_1 = require("@aws-sdk/core"); +const util_middleware_1 = require("@smithy/util-middleware"); +const defaultSigninHttpAuthSchemeParametersProvider = async (config, context, input) => { + return { + operation: (0, util_middleware_1.getSmithyContext)(context).operation, + region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || + (() => { + throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); + })(), + }; +}; +exports.defaultSigninHttpAuthSchemeParametersProvider = defaultSigninHttpAuthSchemeParametersProvider; +function createAwsAuthSigv4HttpAuthOption(authParameters) { + return { + schemeId: "aws.auth#sigv4", + signingProperties: { + name: "signin", + region: authParameters.region, + }, + propertiesExtractor: (config, context) => ({ + signingProperties: { + config, + context, + }, + }), + }; +} +function createSmithyApiNoAuthHttpAuthOption(authParameters) { + return { + schemeId: "smithy.api#noAuth", + }; +} +const defaultSigninHttpAuthSchemeProvider = (authParameters) => { + const options = []; + switch (authParameters.operation) { + case "CreateOAuth2Token": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + default: { + options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); + } + } + return options; +}; +exports.defaultSigninHttpAuthSchemeProvider = defaultSigninHttpAuthSchemeProvider; +const resolveHttpAuthSchemeConfig = (config) => { + const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config); + return Object.assign(config_0, { + authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), + }); +}; +exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/endpoint/endpointResolver.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/endpoint/endpointResolver.js new file mode 100644 index 00000000..7258a356 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/endpoint/endpointResolver.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defaultEndpointResolver = void 0; +const util_endpoints_1 = require("@aws-sdk/util-endpoints"); +const util_endpoints_2 = require("@smithy/util-endpoints"); +const ruleset_1 = require("./ruleset"); +const cache = new util_endpoints_2.EndpointCache({ + size: 50, + params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"], +}); +const defaultEndpointResolver = (endpointParams, context = {}) => { + return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { + endpointParams: endpointParams, + logger: context.logger, + })); +}; +exports.defaultEndpointResolver = defaultEndpointResolver; +util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/endpoint/ruleset.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/endpoint/ruleset.js new file mode 100644 index 00000000..278a0726 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/endpoint/ruleset.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ruleSet = void 0; +const u = "required", v = "fn", w = "argv", x = "ref"; +const a = true, b = "isSet", c = "booleanEquals", d = "error", e = "endpoint", f = "tree", g = "PartitionResult", h = "stringEquals", i = { [u]: true, "default": false, "type": "boolean" }, j = { [u]: false, "type": "string" }, k = { [x]: "Endpoint" }, l = { [v]: c, [w]: [{ [x]: "UseFIPS" }, true] }, m = { [v]: c, [w]: [{ [x]: "UseDualStack" }, true] }, n = {}, o = { [v]: "getAttr", [w]: [{ [x]: g }, "name"] }, p = { [v]: c, [w]: [{ [x]: "UseFIPS" }, false] }, q = { [v]: c, [w]: [{ [x]: "UseDualStack" }, false] }, r = { [v]: "getAttr", [w]: [{ [x]: g }, "supportsFIPS"] }, s = { [v]: c, [w]: [true, { [v]: "getAttr", [w]: [{ [x]: g }, "supportsDualStack"] }] }, t = [{ [x]: "Region" }]; +const _data = { version: "1.0", parameters: { UseDualStack: i, UseFIPS: i, Endpoint: j, Region: j }, rules: [{ conditions: [{ [v]: b, [w]: [k] }], rules: [{ conditions: [l], error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d }, { rules: [{ conditions: [m], error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d }, { endpoint: { url: k, properties: n, headers: n }, type: e }], type: f }], type: f }, { rules: [{ conditions: [{ [v]: b, [w]: t }], rules: [{ conditions: [{ [v]: "aws.partition", [w]: t, assign: g }], rules: [{ conditions: [{ [v]: h, [w]: [o, "aws"] }, p, q], endpoint: { url: "https://{Region}.signin.aws.amazon.com", properties: n, headers: n }, type: e }, { conditions: [{ [v]: h, [w]: [o, "aws-cn"] }, p, q], endpoint: { url: "https://{Region}.signin.amazonaws.cn", properties: n, headers: n }, type: e }, { conditions: [{ [v]: h, [w]: [o, "aws-us-gov"] }, p, q], endpoint: { url: "https://{Region}.signin.amazonaws-us-gov.com", properties: n, headers: n }, type: e }, { conditions: [l, m], rules: [{ conditions: [{ [v]: c, [w]: [a, r] }, s], rules: [{ endpoint: { url: "https://signin-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d }], type: f }, { conditions: [l, q], rules: [{ conditions: [{ [v]: c, [w]: [r, a] }], rules: [{ endpoint: { url: "https://signin-fips.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "FIPS is enabled but this partition does not support FIPS", type: d }], type: f }, { conditions: [p, m], rules: [{ conditions: [s], rules: [{ endpoint: { url: "https://signin.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "DualStack is enabled but this partition does not support DualStack", type: d }], type: f }, { endpoint: { url: "https://signin.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }], type: f }, { error: "Invalid Configuration: Missing Region", type: d }], type: f }] }; +exports.ruleSet = _data; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/index.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/index.js new file mode 100644 index 00000000..6092f313 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/index.js @@ -0,0 +1,439 @@ +'use strict'; + +var middlewareHostHeader = require('@aws-sdk/middleware-host-header'); +var middlewareLogger = require('@aws-sdk/middleware-logger'); +var middlewareRecursionDetection = require('@aws-sdk/middleware-recursion-detection'); +var middlewareUserAgent = require('@aws-sdk/middleware-user-agent'); +var configResolver = require('@smithy/config-resolver'); +var core = require('@smithy/core'); +var schema = require('@smithy/core/schema'); +var middlewareContentLength = require('@smithy/middleware-content-length'); +var middlewareEndpoint = require('@smithy/middleware-endpoint'); +var middlewareRetry = require('@smithy/middleware-retry'); +var smithyClient = require('@smithy/smithy-client'); +var httpAuthSchemeProvider = require('./auth/httpAuthSchemeProvider'); +var runtimeConfig = require('./runtimeConfig'); +var regionConfigResolver = require('@aws-sdk/region-config-resolver'); +var protocolHttp = require('@smithy/protocol-http'); + +const resolveClientEndpointParameters = (options) => { + return Object.assign(options, { + useDualstackEndpoint: options.useDualstackEndpoint ?? false, + useFipsEndpoint: options.useFipsEndpoint ?? false, + defaultSigningName: "signin", + }); +}; +const commonParams = { + UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, + Endpoint: { type: "builtInParams", name: "endpoint" }, + Region: { type: "builtInParams", name: "region" }, + UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, +}; + +const getHttpAuthExtensionConfiguration = (runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + return { + setHttpAuthScheme(httpAuthScheme) { + const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } + else { + _httpAuthSchemes.splice(index, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; + }, + }; +}; +const resolveHttpAuthRuntimeConfig = (config) => { + return { + httpAuthSchemes: config.httpAuthSchemes(), + httpAuthSchemeProvider: config.httpAuthSchemeProvider(), + credentials: config.credentials(), + }; +}; + +const resolveRuntimeExtensions = (runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign(regionConfigResolver.getAwsRegionExtensionConfiguration(runtimeConfig), smithyClient.getDefaultExtensionConfiguration(runtimeConfig), protocolHttp.getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig)); + extensions.forEach((extension) => extension.configure(extensionConfiguration)); + return Object.assign(runtimeConfig, regionConfigResolver.resolveAwsRegionExtensionConfiguration(extensionConfiguration), smithyClient.resolveDefaultRuntimeConfig(extensionConfiguration), protocolHttp.resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration)); +}; + +class SigninClient extends smithyClient.Client { + config; + constructor(...[configuration]) { + const _config_0 = runtimeConfig.getRuntimeConfig(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = resolveClientEndpointParameters(_config_0); + const _config_2 = middlewareUserAgent.resolveUserAgentConfig(_config_1); + const _config_3 = middlewareRetry.resolveRetryConfig(_config_2); + const _config_4 = configResolver.resolveRegionConfig(_config_3); + const _config_5 = middlewareHostHeader.resolveHostHeaderConfig(_config_4); + const _config_6 = middlewareEndpoint.resolveEndpointConfig(_config_5); + const _config_7 = httpAuthSchemeProvider.resolveHttpAuthSchemeConfig(_config_6); + const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); + this.config = _config_8; + this.middlewareStack.use(schema.getSchemaSerdePlugin(this.config)); + this.middlewareStack.use(middlewareUserAgent.getUserAgentPlugin(this.config)); + this.middlewareStack.use(middlewareRetry.getRetryPlugin(this.config)); + this.middlewareStack.use(middlewareContentLength.getContentLengthPlugin(this.config)); + this.middlewareStack.use(middlewareHostHeader.getHostHeaderPlugin(this.config)); + this.middlewareStack.use(middlewareLogger.getLoggerPlugin(this.config)); + this.middlewareStack.use(middlewareRecursionDetection.getRecursionDetectionPlugin(this.config)); + this.middlewareStack.use(core.getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { + httpAuthSchemeParametersProvider: httpAuthSchemeProvider.defaultSigninHttpAuthSchemeParametersProvider, + identityProviderConfigProvider: async (config) => new core.DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config.credentials, + }), + })); + this.middlewareStack.use(core.getHttpSigningPlugin(this.config)); + } + destroy() { + super.destroy(); + } +} + +let SigninServiceException$1 = class SigninServiceException extends smithyClient.ServiceException { + constructor(options) { + super(options); + Object.setPrototypeOf(this, SigninServiceException.prototype); + } +}; + +let AccessDeniedException$1 = class AccessDeniedException extends SigninServiceException$1 { + name = "AccessDeniedException"; + $fault = "client"; + error; + constructor(opts) { + super({ + name: "AccessDeniedException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, AccessDeniedException.prototype); + this.error = opts.error; + } +}; +let InternalServerException$1 = class InternalServerException extends SigninServiceException$1 { + name = "InternalServerException"; + $fault = "server"; + error; + constructor(opts) { + super({ + name: "InternalServerException", + $fault: "server", + ...opts, + }); + Object.setPrototypeOf(this, InternalServerException.prototype); + this.error = opts.error; + } +}; +let TooManyRequestsError$1 = class TooManyRequestsError extends SigninServiceException$1 { + name = "TooManyRequestsError"; + $fault = "client"; + error; + constructor(opts) { + super({ + name: "TooManyRequestsError", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, TooManyRequestsError.prototype); + this.error = opts.error; + } +}; +let ValidationException$1 = class ValidationException extends SigninServiceException$1 { + name = "ValidationException"; + $fault = "client"; + error; + constructor(opts) { + super({ + name: "ValidationException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ValidationException.prototype); + this.error = opts.error; + } +}; + +const _ADE = "AccessDeniedException"; +const _AT = "AccessToken"; +const _COAT = "CreateOAuth2Token"; +const _COATR = "CreateOAuth2TokenRequest"; +const _COATRB = "CreateOAuth2TokenRequestBody"; +const _COATRBr = "CreateOAuth2TokenResponseBody"; +const _COATRr = "CreateOAuth2TokenResponse"; +const _ISE = "InternalServerException"; +const _RT = "RefreshToken"; +const _TMRE = "TooManyRequestsError"; +const _VE = "ValidationException"; +const _aKI = "accessKeyId"; +const _aT = "accessToken"; +const _c = "client"; +const _cI = "clientId"; +const _cV = "codeVerifier"; +const _co = "code"; +const _e = "error"; +const _eI = "expiresIn"; +const _gT = "grantType"; +const _h = "http"; +const _hE = "httpError"; +const _iT = "idToken"; +const _jN = "jsonName"; +const _m = "message"; +const _rT = "refreshToken"; +const _rU = "redirectUri"; +const _s = "server"; +const _sAK = "secretAccessKey"; +const _sT = "sessionToken"; +const _sm = "smithy.ts.sdk.synthetic.com.amazonaws.signin"; +const _tI = "tokenInput"; +const _tO = "tokenOutput"; +const _tT = "tokenType"; +const n0 = "com.amazonaws.signin"; +var RefreshToken = [0, n0, _RT, 8, 0]; +var AccessDeniedException = [ + -3, + n0, + _ADE, + { + [_e]: _c, + }, + [_e, _m], + [0, 0], +]; +schema.TypeRegistry.for(n0).registerError(AccessDeniedException, AccessDeniedException$1); +var AccessToken = [ + 3, + n0, + _AT, + 8, + [_aKI, _sAK, _sT], + [ + [ + 0, + { + [_jN]: _aKI, + }, + ], + [ + 0, + { + [_jN]: _sAK, + }, + ], + [ + 0, + { + [_jN]: _sT, + }, + ], + ], +]; +var CreateOAuth2TokenRequest = [ + 3, + n0, + _COATR, + 0, + [_tI], + [[() => CreateOAuth2TokenRequestBody, 16]], +]; +var CreateOAuth2TokenRequestBody = [ + 3, + n0, + _COATRB, + 0, + [_cI, _gT, _co, _rU, _cV, _rT], + [ + [ + 0, + { + [_jN]: _cI, + }, + ], + [ + 0, + { + [_jN]: _gT, + }, + ], + 0, + [ + 0, + { + [_jN]: _rU, + }, + ], + [ + 0, + { + [_jN]: _cV, + }, + ], + [ + () => RefreshToken, + { + [_jN]: _rT, + }, + ], + ], +]; +var CreateOAuth2TokenResponse = [ + 3, + n0, + _COATRr, + 0, + [_tO], + [[() => CreateOAuth2TokenResponseBody, 16]], +]; +var CreateOAuth2TokenResponseBody = [ + 3, + n0, + _COATRBr, + 0, + [_aT, _tT, _eI, _rT, _iT], + [ + [ + () => AccessToken, + { + [_jN]: _aT, + }, + ], + [ + 0, + { + [_jN]: _tT, + }, + ], + [ + 1, + { + [_jN]: _eI, + }, + ], + [ + () => RefreshToken, + { + [_jN]: _rT, + }, + ], + [ + 0, + { + [_jN]: _iT, + }, + ], + ], +]; +var InternalServerException = [ + -3, + n0, + _ISE, + { + [_e]: _s, + [_hE]: 500, + }, + [_e, _m], + [0, 0], +]; +schema.TypeRegistry.for(n0).registerError(InternalServerException, InternalServerException$1); +var TooManyRequestsError = [ + -3, + n0, + _TMRE, + { + [_e]: _c, + [_hE]: 429, + }, + [_e, _m], + [0, 0], +]; +schema.TypeRegistry.for(n0).registerError(TooManyRequestsError, TooManyRequestsError$1); +var ValidationException = [ + -3, + n0, + _VE, + { + [_e]: _c, + [_hE]: 400, + }, + [_e, _m], + [0, 0], +]; +schema.TypeRegistry.for(n0).registerError(ValidationException, ValidationException$1); +var SigninServiceException = [-3, _sm, "SigninServiceException", 0, [], []]; +schema.TypeRegistry.for(_sm).registerError(SigninServiceException, SigninServiceException$1); +var CreateOAuth2Token = [ + 9, + n0, + _COAT, + { + [_h]: ["POST", "/v1/token", 200], + }, + () => CreateOAuth2TokenRequest, + () => CreateOAuth2TokenResponse, +]; + +class CreateOAuth2TokenCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("Signin", "CreateOAuth2Token", {}) + .n("SigninClient", "CreateOAuth2TokenCommand") + .sc(CreateOAuth2Token) + .build() { +} + +const commands = { + CreateOAuth2TokenCommand, +}; +class Signin extends SigninClient { +} +smithyClient.createAggregatedClient(commands, Signin); + +const OAuth2ErrorCode = { + AUTHCODE_EXPIRED: "AUTHCODE_EXPIRED", + INSUFFICIENT_PERMISSIONS: "INSUFFICIENT_PERMISSIONS", + INVALID_REQUEST: "INVALID_REQUEST", + SERVER_ERROR: "server_error", + TOKEN_EXPIRED: "TOKEN_EXPIRED", + USER_CREDENTIALS_CHANGED: "USER_CREDENTIALS_CHANGED", +}; + +Object.defineProperty(exports, "$Command", { + enumerable: true, + get: function () { return smithyClient.Command; } +}); +Object.defineProperty(exports, "__Client", { + enumerable: true, + get: function () { return smithyClient.Client; } +}); +exports.AccessDeniedException = AccessDeniedException$1; +exports.CreateOAuth2TokenCommand = CreateOAuth2TokenCommand; +exports.InternalServerException = InternalServerException$1; +exports.OAuth2ErrorCode = OAuth2ErrorCode; +exports.Signin = Signin; +exports.SigninClient = SigninClient; +exports.SigninServiceException = SigninServiceException$1; +exports.TooManyRequestsError = TooManyRequestsError$1; +exports.ValidationException = ValidationException$1; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/runtimeConfig.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/runtimeConfig.js new file mode 100644 index 00000000..5c617933 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/runtimeConfig.js @@ -0,0 +1,54 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getRuntimeConfig = void 0; +const tslib_1 = require("tslib"); +const package_json_1 = tslib_1.__importDefault(require("../../../package.json")); +const core_1 = require("@aws-sdk/core"); +const util_user_agent_node_1 = require("@aws-sdk/util-user-agent-node"); +const config_resolver_1 = require("@smithy/config-resolver"); +const hash_node_1 = require("@smithy/hash-node"); +const middleware_retry_1 = require("@smithy/middleware-retry"); +const node_config_provider_1 = require("@smithy/node-config-provider"); +const node_http_handler_1 = require("@smithy/node-http-handler"); +const util_body_length_node_1 = require("@smithy/util-body-length-node"); +const util_retry_1 = require("@smithy/util-retry"); +const runtimeConfig_shared_1 = require("./runtimeConfig.shared"); +const smithy_client_1 = require("@smithy/smithy-client"); +const util_defaults_mode_node_1 = require("@smithy/util-defaults-mode-node"); +const smithy_client_2 = require("@smithy/smithy-client"); +const getRuntimeConfig = (config) => { + (0, smithy_client_2.emitWarningIfUnsupportedVersion)(process.version); + const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config); + const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode); + const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config); + (0, core_1.emitWarningIfUnsupportedVersion)(process.version); + const loaderConfig = { + profile: config?.profile, + logger: clientSharedValues.logger, + }; + return { + ...clientSharedValues, + ...config, + runtime: "node", + defaultsMode, + authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), + bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, + defaultUserAgentProvider: config?.defaultUserAgentProvider ?? + (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), + maxAttempts: config?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), + region: config?.region ?? + (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), + requestHandler: node_http_handler_1.NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), + retryMode: config?.retryMode ?? + (0, node_config_provider_1.loadConfig)({ + ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS, + default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE, + }, config), + sha256: config?.sha256 ?? hash_node_1.Hash.bind(null, "sha256"), + streamCollector: config?.streamCollector ?? node_http_handler_1.streamCollector, + useDualstackEndpoint: config?.useDualstackEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), + }; +}; +exports.getRuntimeConfig = getRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/runtimeConfig.shared.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/runtimeConfig.shared.js new file mode 100644 index 00000000..79f18c72 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/runtimeConfig.shared.js @@ -0,0 +1,42 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getRuntimeConfig = void 0; +const core_1 = require("@aws-sdk/core"); +const protocols_1 = require("@aws-sdk/core/protocols"); +const core_2 = require("@smithy/core"); +const smithy_client_1 = require("@smithy/smithy-client"); +const url_parser_1 = require("@smithy/url-parser"); +const util_base64_1 = require("@smithy/util-base64"); +const util_utf8_1 = require("@smithy/util-utf8"); +const httpAuthSchemeProvider_1 = require("./auth/httpAuthSchemeProvider"); +const endpointResolver_1 = require("./endpoint/endpointResolver"); +const getRuntimeConfig = (config) => { + return { + apiVersion: "2023-01-01", + base64Decoder: config?.base64Decoder ?? util_base64_1.fromBase64, + base64Encoder: config?.base64Encoder ?? util_base64_1.toBase64, + disableHostPrefix: config?.disableHostPrefix ?? false, + endpointProvider: config?.endpointProvider ?? endpointResolver_1.defaultEndpointResolver, + extensions: config?.extensions ?? [], + httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSigninHttpAuthSchemeProvider, + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new core_1.AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new core_2.NoAuthSigner(), + }, + ], + logger: config?.logger ?? new smithy_client_1.NoOpLogger(), + protocol: config?.protocol ?? new protocols_1.AwsRestJsonProtocol({ defaultNamespace: "com.amazonaws.signin" }), + serviceId: config?.serviceId ?? "Signin", + urlParser: config?.urlParser ?? url_parser_1.parseUrl, + utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, + utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, + }; +}; +exports.getRuntimeConfig = getRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/auth/httpAuthSchemeProvider.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/auth/httpAuthSchemeProvider.js new file mode 100644 index 00000000..7a9f28a4 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/auth/httpAuthSchemeProvider.js @@ -0,0 +1,56 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.resolveHttpAuthSchemeConfig = exports.defaultSSOOIDCHttpAuthSchemeProvider = exports.defaultSSOOIDCHttpAuthSchemeParametersProvider = void 0; +const core_1 = require("@aws-sdk/core"); +const util_middleware_1 = require("@smithy/util-middleware"); +const defaultSSOOIDCHttpAuthSchemeParametersProvider = async (config, context, input) => { + return { + operation: (0, util_middleware_1.getSmithyContext)(context).operation, + region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || + (() => { + throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); + })(), + }; +}; +exports.defaultSSOOIDCHttpAuthSchemeParametersProvider = defaultSSOOIDCHttpAuthSchemeParametersProvider; +function createAwsAuthSigv4HttpAuthOption(authParameters) { + return { + schemeId: "aws.auth#sigv4", + signingProperties: { + name: "sso-oauth", + region: authParameters.region, + }, + propertiesExtractor: (config, context) => ({ + signingProperties: { + config, + context, + }, + }), + }; +} +function createSmithyApiNoAuthHttpAuthOption(authParameters) { + return { + schemeId: "smithy.api#noAuth", + }; +} +const defaultSSOOIDCHttpAuthSchemeProvider = (authParameters) => { + const options = []; + switch (authParameters.operation) { + case "CreateToken": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + default: { + options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); + } + } + return options; +}; +exports.defaultSSOOIDCHttpAuthSchemeProvider = defaultSSOOIDCHttpAuthSchemeProvider; +const resolveHttpAuthSchemeConfig = (config) => { + const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config); + return Object.assign(config_0, { + authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), + }); +}; +exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/endpoint/endpointResolver.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/endpoint/endpointResolver.js new file mode 100644 index 00000000..7258a356 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/endpoint/endpointResolver.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defaultEndpointResolver = void 0; +const util_endpoints_1 = require("@aws-sdk/util-endpoints"); +const util_endpoints_2 = require("@smithy/util-endpoints"); +const ruleset_1 = require("./ruleset"); +const cache = new util_endpoints_2.EndpointCache({ + size: 50, + params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"], +}); +const defaultEndpointResolver = (endpointParams, context = {}) => { + return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { + endpointParams: endpointParams, + logger: context.logger, + })); +}; +exports.defaultEndpointResolver = defaultEndpointResolver; +util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/endpoint/ruleset.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/endpoint/ruleset.js new file mode 100644 index 00000000..492b2264 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/endpoint/ruleset.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ruleSet = void 0; +const u = "required", v = "fn", w = "argv", x = "ref"; +const a = true, b = "isSet", c = "booleanEquals", d = "error", e = "endpoint", f = "tree", g = "PartitionResult", h = "getAttr", i = { [u]: false, "type": "string" }, j = { [u]: true, "default": false, "type": "boolean" }, k = { [x]: "Endpoint" }, l = { [v]: c, [w]: [{ [x]: "UseFIPS" }, true] }, m = { [v]: c, [w]: [{ [x]: "UseDualStack" }, true] }, n = {}, o = { [v]: h, [w]: [{ [x]: g }, "supportsFIPS"] }, p = { [x]: g }, q = { [v]: c, [w]: [true, { [v]: h, [w]: [p, "supportsDualStack"] }] }, r = [l], s = [m], t = [{ [x]: "Region" }]; +const _data = { version: "1.0", parameters: { Region: i, UseDualStack: j, UseFIPS: j, Endpoint: i }, rules: [{ conditions: [{ [v]: b, [w]: [k] }], rules: [{ conditions: r, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d }, { conditions: s, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d }, { endpoint: { url: k, properties: n, headers: n }, type: e }], type: f }, { conditions: [{ [v]: b, [w]: t }], rules: [{ conditions: [{ [v]: "aws.partition", [w]: t, assign: g }], rules: [{ conditions: [l, m], rules: [{ conditions: [{ [v]: c, [w]: [a, o] }, q], rules: [{ endpoint: { url: "https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d }], type: f }, { conditions: r, rules: [{ conditions: [{ [v]: c, [w]: [o, a] }], rules: [{ conditions: [{ [v]: "stringEquals", [w]: [{ [v]: h, [w]: [p, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://oidc.{Region}.amazonaws.com", properties: n, headers: n }, type: e }, { endpoint: { url: "https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "FIPS is enabled but this partition does not support FIPS", type: d }], type: f }, { conditions: s, rules: [{ conditions: [q], rules: [{ endpoint: { url: "https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "DualStack is enabled but this partition does not support DualStack", type: d }], type: f }, { endpoint: { url: "https://oidc.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }], type: f }, { error: "Invalid Configuration: Missing Region", type: d }] }; +exports.ruleSet = _data; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/index.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/index.js new file mode 100644 index 00000000..61db06a2 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/index.js @@ -0,0 +1,561 @@ +'use strict'; + +var middlewareHostHeader = require('@aws-sdk/middleware-host-header'); +var middlewareLogger = require('@aws-sdk/middleware-logger'); +var middlewareRecursionDetection = require('@aws-sdk/middleware-recursion-detection'); +var middlewareUserAgent = require('@aws-sdk/middleware-user-agent'); +var configResolver = require('@smithy/config-resolver'); +var core = require('@smithy/core'); +var schema = require('@smithy/core/schema'); +var middlewareContentLength = require('@smithy/middleware-content-length'); +var middlewareEndpoint = require('@smithy/middleware-endpoint'); +var middlewareRetry = require('@smithy/middleware-retry'); +var smithyClient = require('@smithy/smithy-client'); +var httpAuthSchemeProvider = require('./auth/httpAuthSchemeProvider'); +var runtimeConfig = require('./runtimeConfig'); +var regionConfigResolver = require('@aws-sdk/region-config-resolver'); +var protocolHttp = require('@smithy/protocol-http'); + +const resolveClientEndpointParameters = (options) => { + return Object.assign(options, { + useDualstackEndpoint: options.useDualstackEndpoint ?? false, + useFipsEndpoint: options.useFipsEndpoint ?? false, + defaultSigningName: "sso-oauth", + }); +}; +const commonParams = { + UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, + Endpoint: { type: "builtInParams", name: "endpoint" }, + Region: { type: "builtInParams", name: "region" }, + UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, +}; + +const getHttpAuthExtensionConfiguration = (runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + return { + setHttpAuthScheme(httpAuthScheme) { + const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } + else { + _httpAuthSchemes.splice(index, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; + }, + }; +}; +const resolveHttpAuthRuntimeConfig = (config) => { + return { + httpAuthSchemes: config.httpAuthSchemes(), + httpAuthSchemeProvider: config.httpAuthSchemeProvider(), + credentials: config.credentials(), + }; +}; + +const resolveRuntimeExtensions = (runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign(regionConfigResolver.getAwsRegionExtensionConfiguration(runtimeConfig), smithyClient.getDefaultExtensionConfiguration(runtimeConfig), protocolHttp.getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig)); + extensions.forEach((extension) => extension.configure(extensionConfiguration)); + return Object.assign(runtimeConfig, regionConfigResolver.resolveAwsRegionExtensionConfiguration(extensionConfiguration), smithyClient.resolveDefaultRuntimeConfig(extensionConfiguration), protocolHttp.resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration)); +}; + +class SSOOIDCClient extends smithyClient.Client { + config; + constructor(...[configuration]) { + const _config_0 = runtimeConfig.getRuntimeConfig(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = resolveClientEndpointParameters(_config_0); + const _config_2 = middlewareUserAgent.resolveUserAgentConfig(_config_1); + const _config_3 = middlewareRetry.resolveRetryConfig(_config_2); + const _config_4 = configResolver.resolveRegionConfig(_config_3); + const _config_5 = middlewareHostHeader.resolveHostHeaderConfig(_config_4); + const _config_6 = middlewareEndpoint.resolveEndpointConfig(_config_5); + const _config_7 = httpAuthSchemeProvider.resolveHttpAuthSchemeConfig(_config_6); + const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); + this.config = _config_8; + this.middlewareStack.use(schema.getSchemaSerdePlugin(this.config)); + this.middlewareStack.use(middlewareUserAgent.getUserAgentPlugin(this.config)); + this.middlewareStack.use(middlewareRetry.getRetryPlugin(this.config)); + this.middlewareStack.use(middlewareContentLength.getContentLengthPlugin(this.config)); + this.middlewareStack.use(middlewareHostHeader.getHostHeaderPlugin(this.config)); + this.middlewareStack.use(middlewareLogger.getLoggerPlugin(this.config)); + this.middlewareStack.use(middlewareRecursionDetection.getRecursionDetectionPlugin(this.config)); + this.middlewareStack.use(core.getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { + httpAuthSchemeParametersProvider: httpAuthSchemeProvider.defaultSSOOIDCHttpAuthSchemeParametersProvider, + identityProviderConfigProvider: async (config) => new core.DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config.credentials, + }), + })); + this.middlewareStack.use(core.getHttpSigningPlugin(this.config)); + } + destroy() { + super.destroy(); + } +} + +let SSOOIDCServiceException$1 = class SSOOIDCServiceException extends smithyClient.ServiceException { + constructor(options) { + super(options); + Object.setPrototypeOf(this, SSOOIDCServiceException.prototype); + } +}; + +let AccessDeniedException$1 = class AccessDeniedException extends SSOOIDCServiceException$1 { + name = "AccessDeniedException"; + $fault = "client"; + error; + reason; + error_description; + constructor(opts) { + super({ + name: "AccessDeniedException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, AccessDeniedException.prototype); + this.error = opts.error; + this.reason = opts.reason; + this.error_description = opts.error_description; + } +}; +let AuthorizationPendingException$1 = class AuthorizationPendingException extends SSOOIDCServiceException$1 { + name = "AuthorizationPendingException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "AuthorizationPendingException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, AuthorizationPendingException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +}; +let ExpiredTokenException$1 = class ExpiredTokenException extends SSOOIDCServiceException$1 { + name = "ExpiredTokenException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "ExpiredTokenException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ExpiredTokenException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +}; +let InternalServerException$1 = class InternalServerException extends SSOOIDCServiceException$1 { + name = "InternalServerException"; + $fault = "server"; + error; + error_description; + constructor(opts) { + super({ + name: "InternalServerException", + $fault: "server", + ...opts, + }); + Object.setPrototypeOf(this, InternalServerException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +}; +let InvalidClientException$1 = class InvalidClientException extends SSOOIDCServiceException$1 { + name = "InvalidClientException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "InvalidClientException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, InvalidClientException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +}; +let InvalidGrantException$1 = class InvalidGrantException extends SSOOIDCServiceException$1 { + name = "InvalidGrantException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "InvalidGrantException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, InvalidGrantException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +}; +let InvalidRequestException$1 = class InvalidRequestException extends SSOOIDCServiceException$1 { + name = "InvalidRequestException"; + $fault = "client"; + error; + reason; + error_description; + constructor(opts) { + super({ + name: "InvalidRequestException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, InvalidRequestException.prototype); + this.error = opts.error; + this.reason = opts.reason; + this.error_description = opts.error_description; + } +}; +let InvalidScopeException$1 = class InvalidScopeException extends SSOOIDCServiceException$1 { + name = "InvalidScopeException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "InvalidScopeException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, InvalidScopeException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +}; +let SlowDownException$1 = class SlowDownException extends SSOOIDCServiceException$1 { + name = "SlowDownException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "SlowDownException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, SlowDownException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +}; +let UnauthorizedClientException$1 = class UnauthorizedClientException extends SSOOIDCServiceException$1 { + name = "UnauthorizedClientException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "UnauthorizedClientException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, UnauthorizedClientException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +}; +let UnsupportedGrantTypeException$1 = class UnsupportedGrantTypeException extends SSOOIDCServiceException$1 { + name = "UnsupportedGrantTypeException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "UnsupportedGrantTypeException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, UnsupportedGrantTypeException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +}; + +const _ADE = "AccessDeniedException"; +const _APE = "AuthorizationPendingException"; +const _AT = "AccessToken"; +const _CS = "ClientSecret"; +const _CT = "CreateToken"; +const _CTR = "CreateTokenRequest"; +const _CTRr = "CreateTokenResponse"; +const _CV = "CodeVerifier"; +const _ETE = "ExpiredTokenException"; +const _ICE = "InvalidClientException"; +const _IGE = "InvalidGrantException"; +const _IRE = "InvalidRequestException"; +const _ISE = "InternalServerException"; +const _ISEn = "InvalidScopeException"; +const _IT = "IdToken"; +const _RT = "RefreshToken"; +const _SDE = "SlowDownException"; +const _UCE = "UnauthorizedClientException"; +const _UGTE = "UnsupportedGrantTypeException"; +const _aT = "accessToken"; +const _c = "client"; +const _cI = "clientId"; +const _cS = "clientSecret"; +const _cV = "codeVerifier"; +const _co = "code"; +const _dC = "deviceCode"; +const _e = "error"; +const _eI = "expiresIn"; +const _ed = "error_description"; +const _gT = "grantType"; +const _h = "http"; +const _hE = "httpError"; +const _iT = "idToken"; +const _r = "reason"; +const _rT = "refreshToken"; +const _rU = "redirectUri"; +const _s = "scope"; +const _se = "server"; +const _sm = "smithy.ts.sdk.synthetic.com.amazonaws.ssooidc"; +const _tT = "tokenType"; +const n0 = "com.amazonaws.ssooidc"; +var AccessToken = [0, n0, _AT, 8, 0]; +var ClientSecret = [0, n0, _CS, 8, 0]; +var CodeVerifier = [0, n0, _CV, 8, 0]; +var IdToken = [0, n0, _IT, 8, 0]; +var RefreshToken = [0, n0, _RT, 8, 0]; +var AccessDeniedException = [ + -3, + n0, + _ADE, + { + [_e]: _c, + [_hE]: 400, + }, + [_e, _r, _ed], + [0, 0, 0], +]; +schema.TypeRegistry.for(n0).registerError(AccessDeniedException, AccessDeniedException$1); +var AuthorizationPendingException = [ + -3, + n0, + _APE, + { + [_e]: _c, + [_hE]: 400, + }, + [_e, _ed], + [0, 0], +]; +schema.TypeRegistry.for(n0).registerError(AuthorizationPendingException, AuthorizationPendingException$1); +var CreateTokenRequest = [ + 3, + n0, + _CTR, + 0, + [_cI, _cS, _gT, _dC, _co, _rT, _s, _rU, _cV], + [0, [() => ClientSecret, 0], 0, 0, 0, [() => RefreshToken, 0], 64 | 0, 0, [() => CodeVerifier, 0]], +]; +var CreateTokenResponse = [ + 3, + n0, + _CTRr, + 0, + [_aT, _tT, _eI, _rT, _iT], + [[() => AccessToken, 0], 0, 1, [() => RefreshToken, 0], [() => IdToken, 0]], +]; +var ExpiredTokenException = [ + -3, + n0, + _ETE, + { + [_e]: _c, + [_hE]: 400, + }, + [_e, _ed], + [0, 0], +]; +schema.TypeRegistry.for(n0).registerError(ExpiredTokenException, ExpiredTokenException$1); +var InternalServerException = [ + -3, + n0, + _ISE, + { + [_e]: _se, + [_hE]: 500, + }, + [_e, _ed], + [0, 0], +]; +schema.TypeRegistry.for(n0).registerError(InternalServerException, InternalServerException$1); +var InvalidClientException = [ + -3, + n0, + _ICE, + { + [_e]: _c, + [_hE]: 401, + }, + [_e, _ed], + [0, 0], +]; +schema.TypeRegistry.for(n0).registerError(InvalidClientException, InvalidClientException$1); +var InvalidGrantException = [ + -3, + n0, + _IGE, + { + [_e]: _c, + [_hE]: 400, + }, + [_e, _ed], + [0, 0], +]; +schema.TypeRegistry.for(n0).registerError(InvalidGrantException, InvalidGrantException$1); +var InvalidRequestException = [ + -3, + n0, + _IRE, + { + [_e]: _c, + [_hE]: 400, + }, + [_e, _r, _ed], + [0, 0, 0], +]; +schema.TypeRegistry.for(n0).registerError(InvalidRequestException, InvalidRequestException$1); +var InvalidScopeException = [ + -3, + n0, + _ISEn, + { + [_e]: _c, + [_hE]: 400, + }, + [_e, _ed], + [0, 0], +]; +schema.TypeRegistry.for(n0).registerError(InvalidScopeException, InvalidScopeException$1); +var SlowDownException = [ + -3, + n0, + _SDE, + { + [_e]: _c, + [_hE]: 400, + }, + [_e, _ed], + [0, 0], +]; +schema.TypeRegistry.for(n0).registerError(SlowDownException, SlowDownException$1); +var UnauthorizedClientException = [ + -3, + n0, + _UCE, + { + [_e]: _c, + [_hE]: 400, + }, + [_e, _ed], + [0, 0], +]; +schema.TypeRegistry.for(n0).registerError(UnauthorizedClientException, UnauthorizedClientException$1); +var UnsupportedGrantTypeException = [ + -3, + n0, + _UGTE, + { + [_e]: _c, + [_hE]: 400, + }, + [_e, _ed], + [0, 0], +]; +schema.TypeRegistry.for(n0).registerError(UnsupportedGrantTypeException, UnsupportedGrantTypeException$1); +var SSOOIDCServiceException = [-3, _sm, "SSOOIDCServiceException", 0, [], []]; +schema.TypeRegistry.for(_sm).registerError(SSOOIDCServiceException, SSOOIDCServiceException$1); +var CreateToken = [ + 9, + n0, + _CT, + { + [_h]: ["POST", "/token", 200], + }, + () => CreateTokenRequest, + () => CreateTokenResponse, +]; + +class CreateTokenCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSSSOOIDCService", "CreateToken", {}) + .n("SSOOIDCClient", "CreateTokenCommand") + .sc(CreateToken) + .build() { +} + +const commands = { + CreateTokenCommand, +}; +class SSOOIDC extends SSOOIDCClient { +} +smithyClient.createAggregatedClient(commands, SSOOIDC); + +const AccessDeniedExceptionReason = { + KMS_ACCESS_DENIED: "KMS_AccessDeniedException", +}; +const InvalidRequestExceptionReason = { + KMS_DISABLED_KEY: "KMS_DisabledException", + KMS_INVALID_KEY_USAGE: "KMS_InvalidKeyUsageException", + KMS_INVALID_STATE: "KMS_InvalidStateException", + KMS_KEY_NOT_FOUND: "KMS_NotFoundException", +}; + +Object.defineProperty(exports, "$Command", { + enumerable: true, + get: function () { return smithyClient.Command; } +}); +Object.defineProperty(exports, "__Client", { + enumerable: true, + get: function () { return smithyClient.Client; } +}); +exports.AccessDeniedException = AccessDeniedException$1; +exports.AccessDeniedExceptionReason = AccessDeniedExceptionReason; +exports.AuthorizationPendingException = AuthorizationPendingException$1; +exports.CreateTokenCommand = CreateTokenCommand; +exports.ExpiredTokenException = ExpiredTokenException$1; +exports.InternalServerException = InternalServerException$1; +exports.InvalidClientException = InvalidClientException$1; +exports.InvalidGrantException = InvalidGrantException$1; +exports.InvalidRequestException = InvalidRequestException$1; +exports.InvalidRequestExceptionReason = InvalidRequestExceptionReason; +exports.InvalidScopeException = InvalidScopeException$1; +exports.SSOOIDC = SSOOIDC; +exports.SSOOIDCClient = SSOOIDCClient; +exports.SSOOIDCServiceException = SSOOIDCServiceException$1; +exports.SlowDownException = SlowDownException$1; +exports.UnauthorizedClientException = UnauthorizedClientException$1; +exports.UnsupportedGrantTypeException = UnsupportedGrantTypeException$1; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/runtimeConfig.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/runtimeConfig.js new file mode 100644 index 00000000..5c617933 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/runtimeConfig.js @@ -0,0 +1,54 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getRuntimeConfig = void 0; +const tslib_1 = require("tslib"); +const package_json_1 = tslib_1.__importDefault(require("../../../package.json")); +const core_1 = require("@aws-sdk/core"); +const util_user_agent_node_1 = require("@aws-sdk/util-user-agent-node"); +const config_resolver_1 = require("@smithy/config-resolver"); +const hash_node_1 = require("@smithy/hash-node"); +const middleware_retry_1 = require("@smithy/middleware-retry"); +const node_config_provider_1 = require("@smithy/node-config-provider"); +const node_http_handler_1 = require("@smithy/node-http-handler"); +const util_body_length_node_1 = require("@smithy/util-body-length-node"); +const util_retry_1 = require("@smithy/util-retry"); +const runtimeConfig_shared_1 = require("./runtimeConfig.shared"); +const smithy_client_1 = require("@smithy/smithy-client"); +const util_defaults_mode_node_1 = require("@smithy/util-defaults-mode-node"); +const smithy_client_2 = require("@smithy/smithy-client"); +const getRuntimeConfig = (config) => { + (0, smithy_client_2.emitWarningIfUnsupportedVersion)(process.version); + const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config); + const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode); + const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config); + (0, core_1.emitWarningIfUnsupportedVersion)(process.version); + const loaderConfig = { + profile: config?.profile, + logger: clientSharedValues.logger, + }; + return { + ...clientSharedValues, + ...config, + runtime: "node", + defaultsMode, + authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), + bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, + defaultUserAgentProvider: config?.defaultUserAgentProvider ?? + (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), + maxAttempts: config?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), + region: config?.region ?? + (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), + requestHandler: node_http_handler_1.NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), + retryMode: config?.retryMode ?? + (0, node_config_provider_1.loadConfig)({ + ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS, + default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE, + }, config), + sha256: config?.sha256 ?? hash_node_1.Hash.bind(null, "sha256"), + streamCollector: config?.streamCollector ?? node_http_handler_1.streamCollector, + useDualstackEndpoint: config?.useDualstackEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), + }; +}; +exports.getRuntimeConfig = getRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/runtimeConfig.shared.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/runtimeConfig.shared.js new file mode 100644 index 00000000..0e7a44f9 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/runtimeConfig.shared.js @@ -0,0 +1,42 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getRuntimeConfig = void 0; +const core_1 = require("@aws-sdk/core"); +const protocols_1 = require("@aws-sdk/core/protocols"); +const core_2 = require("@smithy/core"); +const smithy_client_1 = require("@smithy/smithy-client"); +const url_parser_1 = require("@smithy/url-parser"); +const util_base64_1 = require("@smithy/util-base64"); +const util_utf8_1 = require("@smithy/util-utf8"); +const httpAuthSchemeProvider_1 = require("./auth/httpAuthSchemeProvider"); +const endpointResolver_1 = require("./endpoint/endpointResolver"); +const getRuntimeConfig = (config) => { + return { + apiVersion: "2019-06-10", + base64Decoder: config?.base64Decoder ?? util_base64_1.fromBase64, + base64Encoder: config?.base64Encoder ?? util_base64_1.toBase64, + disableHostPrefix: config?.disableHostPrefix ?? false, + endpointProvider: config?.endpointProvider ?? endpointResolver_1.defaultEndpointResolver, + extensions: config?.extensions ?? [], + httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSSOOIDCHttpAuthSchemeProvider, + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new core_1.AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new core_2.NoAuthSigner(), + }, + ], + logger: config?.logger ?? new smithy_client_1.NoOpLogger(), + protocol: config?.protocol ?? new protocols_1.AwsRestJsonProtocol({ defaultNamespace: "com.amazonaws.ssooidc" }), + serviceId: config?.serviceId ?? "SSO OIDC", + urlParser: config?.urlParser ?? url_parser_1.parseUrl, + utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, + utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, + }; +}; +exports.getRuntimeConfig = getRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/STSClient.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/STSClient.js new file mode 100644 index 00000000..879af8b9 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/STSClient.js @@ -0,0 +1,54 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.STSClient = exports.__Client = void 0; +const middleware_host_header_1 = require("@aws-sdk/middleware-host-header"); +const middleware_logger_1 = require("@aws-sdk/middleware-logger"); +const middleware_recursion_detection_1 = require("@aws-sdk/middleware-recursion-detection"); +const middleware_user_agent_1 = require("@aws-sdk/middleware-user-agent"); +const config_resolver_1 = require("@smithy/config-resolver"); +const core_1 = require("@smithy/core"); +const schema_1 = require("@smithy/core/schema"); +const middleware_content_length_1 = require("@smithy/middleware-content-length"); +const middleware_endpoint_1 = require("@smithy/middleware-endpoint"); +const middleware_retry_1 = require("@smithy/middleware-retry"); +const smithy_client_1 = require("@smithy/smithy-client"); +Object.defineProperty(exports, "__Client", { enumerable: true, get: function () { return smithy_client_1.Client; } }); +const httpAuthSchemeProvider_1 = require("./auth/httpAuthSchemeProvider"); +const EndpointParameters_1 = require("./endpoint/EndpointParameters"); +const runtimeConfig_1 = require("./runtimeConfig"); +const runtimeExtensions_1 = require("./runtimeExtensions"); +class STSClient extends smithy_client_1.Client { + config; + constructor(...[configuration]) { + const _config_0 = (0, runtimeConfig_1.getRuntimeConfig)(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = (0, EndpointParameters_1.resolveClientEndpointParameters)(_config_0); + const _config_2 = (0, middleware_user_agent_1.resolveUserAgentConfig)(_config_1); + const _config_3 = (0, middleware_retry_1.resolveRetryConfig)(_config_2); + const _config_4 = (0, config_resolver_1.resolveRegionConfig)(_config_3); + const _config_5 = (0, middleware_host_header_1.resolveHostHeaderConfig)(_config_4); + const _config_6 = (0, middleware_endpoint_1.resolveEndpointConfig)(_config_5); + const _config_7 = (0, httpAuthSchemeProvider_1.resolveHttpAuthSchemeConfig)(_config_6); + const _config_8 = (0, runtimeExtensions_1.resolveRuntimeExtensions)(_config_7, configuration?.extensions || []); + this.config = _config_8; + this.middlewareStack.use((0, schema_1.getSchemaSerdePlugin)(this.config)); + this.middlewareStack.use((0, middleware_user_agent_1.getUserAgentPlugin)(this.config)); + this.middlewareStack.use((0, middleware_retry_1.getRetryPlugin)(this.config)); + this.middlewareStack.use((0, middleware_content_length_1.getContentLengthPlugin)(this.config)); + this.middlewareStack.use((0, middleware_host_header_1.getHostHeaderPlugin)(this.config)); + this.middlewareStack.use((0, middleware_logger_1.getLoggerPlugin)(this.config)); + this.middlewareStack.use((0, middleware_recursion_detection_1.getRecursionDetectionPlugin)(this.config)); + this.middlewareStack.use((0, core_1.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, { + httpAuthSchemeParametersProvider: httpAuthSchemeProvider_1.defaultSTSHttpAuthSchemeParametersProvider, + identityProviderConfigProvider: async (config) => new core_1.DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config.credentials, + }), + })); + this.middlewareStack.use((0, core_1.getHttpSigningPlugin)(this.config)); + } + destroy() { + super.destroy(); + } +} +exports.STSClient = STSClient; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/auth/httpAuthExtensionConfiguration.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/auth/httpAuthExtensionConfiguration.js new file mode 100644 index 00000000..239095e0 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/auth/httpAuthExtensionConfiguration.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.resolveHttpAuthRuntimeConfig = exports.getHttpAuthExtensionConfiguration = void 0; +const getHttpAuthExtensionConfiguration = (runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + return { + setHttpAuthScheme(httpAuthScheme) { + const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } + else { + _httpAuthSchemes.splice(index, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; + }, + }; +}; +exports.getHttpAuthExtensionConfiguration = getHttpAuthExtensionConfiguration; +const resolveHttpAuthRuntimeConfig = (config) => { + return { + httpAuthSchemes: config.httpAuthSchemes(), + httpAuthSchemeProvider: config.httpAuthSchemeProvider(), + credentials: config.credentials(), + }; +}; +exports.resolveHttpAuthRuntimeConfig = resolveHttpAuthRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/auth/httpAuthSchemeProvider.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/auth/httpAuthSchemeProvider.js new file mode 100644 index 00000000..842241a7 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/auth/httpAuthSchemeProvider.js @@ -0,0 +1,62 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.resolveHttpAuthSchemeConfig = exports.resolveStsAuthConfig = exports.defaultSTSHttpAuthSchemeProvider = exports.defaultSTSHttpAuthSchemeParametersProvider = void 0; +const core_1 = require("@aws-sdk/core"); +const util_middleware_1 = require("@smithy/util-middleware"); +const STSClient_1 = require("../STSClient"); +const defaultSTSHttpAuthSchemeParametersProvider = async (config, context, input) => { + return { + operation: (0, util_middleware_1.getSmithyContext)(context).operation, + region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || + (() => { + throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); + })(), + }; +}; +exports.defaultSTSHttpAuthSchemeParametersProvider = defaultSTSHttpAuthSchemeParametersProvider; +function createAwsAuthSigv4HttpAuthOption(authParameters) { + return { + schemeId: "aws.auth#sigv4", + signingProperties: { + name: "sts", + region: authParameters.region, + }, + propertiesExtractor: (config, context) => ({ + signingProperties: { + config, + context, + }, + }), + }; +} +function createSmithyApiNoAuthHttpAuthOption(authParameters) { + return { + schemeId: "smithy.api#noAuth", + }; +} +const defaultSTSHttpAuthSchemeProvider = (authParameters) => { + const options = []; + switch (authParameters.operation) { + case "AssumeRoleWithWebIdentity": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + default: { + options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); + } + } + return options; +}; +exports.defaultSTSHttpAuthSchemeProvider = defaultSTSHttpAuthSchemeProvider; +const resolveStsAuthConfig = (input) => Object.assign(input, { + stsClientCtor: STSClient_1.STSClient, +}); +exports.resolveStsAuthConfig = resolveStsAuthConfig; +const resolveHttpAuthSchemeConfig = (config) => { + const config_0 = (0, exports.resolveStsAuthConfig)(config); + const config_1 = (0, core_1.resolveAwsSdkSigV4Config)(config_0); + return Object.assign(config_1, { + authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), + }); +}; +exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/endpoint/EndpointParameters.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/endpoint/EndpointParameters.js new file mode 100644 index 00000000..3aec6a5e --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/endpoint/EndpointParameters.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.commonParams = exports.resolveClientEndpointParameters = void 0; +const resolveClientEndpointParameters = (options) => { + return Object.assign(options, { + useDualstackEndpoint: options.useDualstackEndpoint ?? false, + useFipsEndpoint: options.useFipsEndpoint ?? false, + useGlobalEndpoint: options.useGlobalEndpoint ?? false, + defaultSigningName: "sts", + }); +}; +exports.resolveClientEndpointParameters = resolveClientEndpointParameters; +exports.commonParams = { + UseGlobalEndpoint: { type: "builtInParams", name: "useGlobalEndpoint" }, + UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, + Endpoint: { type: "builtInParams", name: "endpoint" }, + Region: { type: "builtInParams", name: "region" }, + UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, +}; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/endpoint/endpointResolver.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/endpoint/endpointResolver.js new file mode 100644 index 00000000..6bfb6e90 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/endpoint/endpointResolver.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defaultEndpointResolver = void 0; +const util_endpoints_1 = require("@aws-sdk/util-endpoints"); +const util_endpoints_2 = require("@smithy/util-endpoints"); +const ruleset_1 = require("./ruleset"); +const cache = new util_endpoints_2.EndpointCache({ + size: 50, + params: ["Endpoint", "Region", "UseDualStack", "UseFIPS", "UseGlobalEndpoint"], +}); +const defaultEndpointResolver = (endpointParams, context = {}) => { + return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { + endpointParams: endpointParams, + logger: context.logger, + })); +}; +exports.defaultEndpointResolver = defaultEndpointResolver; +util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/endpoint/ruleset.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/endpoint/ruleset.js new file mode 100644 index 00000000..a5e5cf2a --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/endpoint/ruleset.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ruleSet = void 0; +const F = "required", G = "type", H = "fn", I = "argv", J = "ref"; +const a = false, b = true, c = "booleanEquals", d = "stringEquals", e = "sigv4", f = "sts", g = "us-east-1", h = "endpoint", i = "https://sts.{Region}.{PartitionResult#dnsSuffix}", j = "tree", k = "error", l = "getAttr", m = { [F]: false, [G]: "string" }, n = { [F]: true, "default": false, [G]: "boolean" }, o = { [J]: "Endpoint" }, p = { [H]: "isSet", [I]: [{ [J]: "Region" }] }, q = { [J]: "Region" }, r = { [H]: "aws.partition", [I]: [q], "assign": "PartitionResult" }, s = { [J]: "UseFIPS" }, t = { [J]: "UseDualStack" }, u = { "url": "https://sts.amazonaws.com", "properties": { "authSchemes": [{ "name": e, "signingName": f, "signingRegion": g }] }, "headers": {} }, v = {}, w = { "conditions": [{ [H]: d, [I]: [q, "aws-global"] }], [h]: u, [G]: h }, x = { [H]: c, [I]: [s, true] }, y = { [H]: c, [I]: [t, true] }, z = { [H]: l, [I]: [{ [J]: "PartitionResult" }, "supportsFIPS"] }, A = { [J]: "PartitionResult" }, B = { [H]: c, [I]: [true, { [H]: l, [I]: [A, "supportsDualStack"] }] }, C = [{ [H]: "isSet", [I]: [o] }], D = [x], E = [y]; +const _data = { version: "1.0", parameters: { Region: m, UseDualStack: n, UseFIPS: n, Endpoint: m, UseGlobalEndpoint: n }, rules: [{ conditions: [{ [H]: c, [I]: [{ [J]: "UseGlobalEndpoint" }, b] }, { [H]: "not", [I]: C }, p, r, { [H]: c, [I]: [s, a] }, { [H]: c, [I]: [t, a] }], rules: [{ conditions: [{ [H]: d, [I]: [q, "ap-northeast-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "ap-south-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "ap-southeast-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "ap-southeast-2"] }], endpoint: u, [G]: h }, w, { conditions: [{ [H]: d, [I]: [q, "ca-central-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-central-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-north-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-west-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-west-2"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-west-3"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "sa-east-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, g] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "us-east-2"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "us-west-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "us-west-2"] }], endpoint: u, [G]: h }, { endpoint: { url: i, properties: { authSchemes: [{ name: e, signingName: f, signingRegion: "{Region}" }] }, headers: v }, [G]: h }], [G]: j }, { conditions: C, rules: [{ conditions: D, error: "Invalid Configuration: FIPS and custom endpoint are not supported", [G]: k }, { conditions: E, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", [G]: k }, { endpoint: { url: o, properties: v, headers: v }, [G]: h }], [G]: j }, { conditions: [p], rules: [{ conditions: [r], rules: [{ conditions: [x, y], rules: [{ conditions: [{ [H]: c, [I]: [b, z] }, B], rules: [{ endpoint: { url: "https://sts-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: v, headers: v }, [G]: h }], [G]: j }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", [G]: k }], [G]: j }, { conditions: D, rules: [{ conditions: [{ [H]: c, [I]: [z, b] }], rules: [{ conditions: [{ [H]: d, [I]: [{ [H]: l, [I]: [A, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://sts.{Region}.amazonaws.com", properties: v, headers: v }, [G]: h }, { endpoint: { url: "https://sts-fips.{Region}.{PartitionResult#dnsSuffix}", properties: v, headers: v }, [G]: h }], [G]: j }, { error: "FIPS is enabled but this partition does not support FIPS", [G]: k }], [G]: j }, { conditions: E, rules: [{ conditions: [B], rules: [{ endpoint: { url: "https://sts.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: v, headers: v }, [G]: h }], [G]: j }, { error: "DualStack is enabled but this partition does not support DualStack", [G]: k }], [G]: j }, w, { endpoint: { url: i, properties: v, headers: v }, [G]: h }], [G]: j }], [G]: j }, { error: "Invalid Configuration: Missing Region", [G]: k }] }; +exports.ruleSet = _data; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/index.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/index.js new file mode 100644 index 00000000..115f95a7 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/index.js @@ -0,0 +1,488 @@ +'use strict'; + +var STSClient = require('./STSClient'); +var smithyClient = require('@smithy/smithy-client'); +var middlewareEndpoint = require('@smithy/middleware-endpoint'); +var EndpointParameters = require('./endpoint/EndpointParameters'); +var schema = require('@smithy/core/schema'); +var client = require('@aws-sdk/core/client'); +var regionConfigResolver = require('@aws-sdk/region-config-resolver'); + +let STSServiceException$1 = class STSServiceException extends smithyClient.ServiceException { + constructor(options) { + super(options); + Object.setPrototypeOf(this, STSServiceException.prototype); + } +}; + +let ExpiredTokenException$1 = class ExpiredTokenException extends STSServiceException$1 { + name = "ExpiredTokenException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ExpiredTokenException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ExpiredTokenException.prototype); + } +}; +let MalformedPolicyDocumentException$1 = class MalformedPolicyDocumentException extends STSServiceException$1 { + name = "MalformedPolicyDocumentException"; + $fault = "client"; + constructor(opts) { + super({ + name: "MalformedPolicyDocumentException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, MalformedPolicyDocumentException.prototype); + } +}; +let PackedPolicyTooLargeException$1 = class PackedPolicyTooLargeException extends STSServiceException$1 { + name = "PackedPolicyTooLargeException"; + $fault = "client"; + constructor(opts) { + super({ + name: "PackedPolicyTooLargeException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, PackedPolicyTooLargeException.prototype); + } +}; +let RegionDisabledException$1 = class RegionDisabledException extends STSServiceException$1 { + name = "RegionDisabledException"; + $fault = "client"; + constructor(opts) { + super({ + name: "RegionDisabledException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, RegionDisabledException.prototype); + } +}; +let IDPRejectedClaimException$1 = class IDPRejectedClaimException extends STSServiceException$1 { + name = "IDPRejectedClaimException"; + $fault = "client"; + constructor(opts) { + super({ + name: "IDPRejectedClaimException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, IDPRejectedClaimException.prototype); + } +}; +let InvalidIdentityTokenException$1 = class InvalidIdentityTokenException extends STSServiceException$1 { + name = "InvalidIdentityTokenException"; + $fault = "client"; + constructor(opts) { + super({ + name: "InvalidIdentityTokenException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, InvalidIdentityTokenException.prototype); + } +}; +let IDPCommunicationErrorException$1 = class IDPCommunicationErrorException extends STSServiceException$1 { + name = "IDPCommunicationErrorException"; + $fault = "client"; + constructor(opts) { + super({ + name: "IDPCommunicationErrorException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, IDPCommunicationErrorException.prototype); + } +}; + +const _A = "Arn"; +const _AKI = "AccessKeyId"; +const _AR = "AssumeRole"; +const _ARI = "AssumedRoleId"; +const _ARR = "AssumeRoleRequest"; +const _ARRs = "AssumeRoleResponse"; +const _ARU = "AssumedRoleUser"; +const _ARWWI = "AssumeRoleWithWebIdentity"; +const _ARWWIR = "AssumeRoleWithWebIdentityRequest"; +const _ARWWIRs = "AssumeRoleWithWebIdentityResponse"; +const _Au = "Audience"; +const _C = "Credentials"; +const _CA = "ContextAssertion"; +const _DS = "DurationSeconds"; +const _E = "Expiration"; +const _EI = "ExternalId"; +const _ETE = "ExpiredTokenException"; +const _IDPCEE = "IDPCommunicationErrorException"; +const _IDPRCE = "IDPRejectedClaimException"; +const _IITE = "InvalidIdentityTokenException"; +const _K = "Key"; +const _MPDE = "MalformedPolicyDocumentException"; +const _P = "Policy"; +const _PA = "PolicyArns"; +const _PAr = "ProviderArn"; +const _PC = "ProvidedContexts"; +const _PCLT = "ProvidedContextsListType"; +const _PCr = "ProvidedContext"; +const _PDT = "PolicyDescriptorType"; +const _PI = "ProviderId"; +const _PPS = "PackedPolicySize"; +const _PPTLE = "PackedPolicyTooLargeException"; +const _Pr = "Provider"; +const _RA = "RoleArn"; +const _RDE = "RegionDisabledException"; +const _RSN = "RoleSessionName"; +const _SAK = "SecretAccessKey"; +const _SFWIT = "SubjectFromWebIdentityToken"; +const _SI = "SourceIdentity"; +const _SN = "SerialNumber"; +const _ST = "SessionToken"; +const _T = "Tags"; +const _TC = "TokenCode"; +const _TTK = "TransitiveTagKeys"; +const _Ta = "Tag"; +const _V = "Value"; +const _WIT = "WebIdentityToken"; +const _a = "arn"; +const _aKST = "accessKeySecretType"; +const _aQE = "awsQueryError"; +const _c = "client"; +const _cTT = "clientTokenType"; +const _e = "error"; +const _hE = "httpError"; +const _m = "message"; +const _pDLT = "policyDescriptorListType"; +const _s = "smithy.ts.sdk.synthetic.com.amazonaws.sts"; +const _tLT = "tagListType"; +const n0 = "com.amazonaws.sts"; +var accessKeySecretType = [0, n0, _aKST, 8, 0]; +var clientTokenType = [0, n0, _cTT, 8, 0]; +var AssumedRoleUser = [3, n0, _ARU, 0, [_ARI, _A], [0, 0]]; +var AssumeRoleRequest = [ + 3, + n0, + _ARR, + 0, + [_RA, _RSN, _PA, _P, _DS, _T, _TTK, _EI, _SN, _TC, _SI, _PC], + [0, 0, () => policyDescriptorListType, 0, 1, () => tagListType, 64 | 0, 0, 0, 0, 0, () => ProvidedContextsListType], +]; +var AssumeRoleResponse = [ + 3, + n0, + _ARRs, + 0, + [_C, _ARU, _PPS, _SI], + [[() => Credentials, 0], () => AssumedRoleUser, 1, 0], +]; +var AssumeRoleWithWebIdentityRequest = [ + 3, + n0, + _ARWWIR, + 0, + [_RA, _RSN, _WIT, _PI, _PA, _P, _DS], + [0, 0, [() => clientTokenType, 0], 0, () => policyDescriptorListType, 0, 1], +]; +var AssumeRoleWithWebIdentityResponse = [ + 3, + n0, + _ARWWIRs, + 0, + [_C, _SFWIT, _ARU, _PPS, _Pr, _Au, _SI], + [[() => Credentials, 0], 0, () => AssumedRoleUser, 1, 0, 0, 0], +]; +var Credentials = [ + 3, + n0, + _C, + 0, + [_AKI, _SAK, _ST, _E], + [0, [() => accessKeySecretType, 0], 0, 4], +]; +var ExpiredTokenException = [ + -3, + n0, + _ETE, + { + [_e]: _c, + [_hE]: 400, + [_aQE]: [`ExpiredTokenException`, 400], + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(ExpiredTokenException, ExpiredTokenException$1); +var IDPCommunicationErrorException = [ + -3, + n0, + _IDPCEE, + { + [_e]: _c, + [_hE]: 400, + [_aQE]: [`IDPCommunicationError`, 400], + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(IDPCommunicationErrorException, IDPCommunicationErrorException$1); +var IDPRejectedClaimException = [ + -3, + n0, + _IDPRCE, + { + [_e]: _c, + [_hE]: 403, + [_aQE]: [`IDPRejectedClaim`, 403], + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(IDPRejectedClaimException, IDPRejectedClaimException$1); +var InvalidIdentityTokenException = [ + -3, + n0, + _IITE, + { + [_e]: _c, + [_hE]: 400, + [_aQE]: [`InvalidIdentityToken`, 400], + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(InvalidIdentityTokenException, InvalidIdentityTokenException$1); +var MalformedPolicyDocumentException = [ + -3, + n0, + _MPDE, + { + [_e]: _c, + [_hE]: 400, + [_aQE]: [`MalformedPolicyDocument`, 400], + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(MalformedPolicyDocumentException, MalformedPolicyDocumentException$1); +var PackedPolicyTooLargeException = [ + -3, + n0, + _PPTLE, + { + [_e]: _c, + [_hE]: 400, + [_aQE]: [`PackedPolicyTooLarge`, 400], + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(PackedPolicyTooLargeException, PackedPolicyTooLargeException$1); +var PolicyDescriptorType = [3, n0, _PDT, 0, [_a], [0]]; +var ProvidedContext = [3, n0, _PCr, 0, [_PAr, _CA], [0, 0]]; +var RegionDisabledException = [ + -3, + n0, + _RDE, + { + [_e]: _c, + [_hE]: 403, + [_aQE]: [`RegionDisabledException`, 403], + }, + [_m], + [0], +]; +schema.TypeRegistry.for(n0).registerError(RegionDisabledException, RegionDisabledException$1); +var Tag = [3, n0, _Ta, 0, [_K, _V], [0, 0]]; +var STSServiceException = [-3, _s, "STSServiceException", 0, [], []]; +schema.TypeRegistry.for(_s).registerError(STSServiceException, STSServiceException$1); +var policyDescriptorListType = [1, n0, _pDLT, 0, () => PolicyDescriptorType]; +var ProvidedContextsListType = [1, n0, _PCLT, 0, () => ProvidedContext]; +var tagListType = [1, n0, _tLT, 0, () => Tag]; +var AssumeRole = [9, n0, _AR, 0, () => AssumeRoleRequest, () => AssumeRoleResponse]; +var AssumeRoleWithWebIdentity = [ + 9, + n0, + _ARWWI, + 0, + () => AssumeRoleWithWebIdentityRequest, + () => AssumeRoleWithWebIdentityResponse, +]; + +class AssumeRoleCommand extends smithyClient.Command + .classBuilder() + .ep(EndpointParameters.commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSSecurityTokenServiceV20110615", "AssumeRole", {}) + .n("STSClient", "AssumeRoleCommand") + .sc(AssumeRole) + .build() { +} + +class AssumeRoleWithWebIdentityCommand extends smithyClient.Command + .classBuilder() + .ep(EndpointParameters.commonParams) + .m(function (Command, cs, config, o) { + return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; +}) + .s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithWebIdentity", {}) + .n("STSClient", "AssumeRoleWithWebIdentityCommand") + .sc(AssumeRoleWithWebIdentity) + .build() { +} + +const commands = { + AssumeRoleCommand, + AssumeRoleWithWebIdentityCommand, +}; +class STS extends STSClient.STSClient { +} +smithyClient.createAggregatedClient(commands, STS); + +const getAccountIdFromAssumedRoleUser = (assumedRoleUser) => { + if (typeof assumedRoleUser?.Arn === "string") { + const arnComponents = assumedRoleUser.Arn.split(":"); + if (arnComponents.length > 4 && arnComponents[4] !== "") { + return arnComponents[4]; + } + } + return undefined; +}; +const resolveRegion = async (_region, _parentRegion, credentialProviderLogger, loaderConfig = {}) => { + const region = typeof _region === "function" ? await _region() : _region; + const parentRegion = typeof _parentRegion === "function" ? await _parentRegion() : _parentRegion; + const stsDefaultRegion = await regionConfigResolver.stsRegionDefaultResolver(loaderConfig)(); + credentialProviderLogger?.debug?.("@aws-sdk/client-sts::resolveRegion", "accepting first of:", `${region} (credential provider clientConfig)`, `${parentRegion} (contextual client)`, `${stsDefaultRegion} (STS default: AWS_REGION, profile region, or us-east-1)`); + return region ?? parentRegion ?? stsDefaultRegion; +}; +const getDefaultRoleAssumer$1 = (stsOptions, STSClient) => { + let stsClient; + let closureSourceCreds; + return async (sourceCreds, params) => { + closureSourceCreds = sourceCreds; + if (!stsClient) { + const { logger = stsOptions?.parentClientConfig?.logger, profile = stsOptions?.parentClientConfig?.profile, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger, userAgentAppId = stsOptions?.parentClientConfig?.userAgentAppId, } = stsOptions; + const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger, { + logger, + profile, + }); + const isCompatibleRequestHandler = !isH2(requestHandler); + stsClient = new STSClient({ + ...stsOptions, + userAgentAppId, + profile, + credentialDefaultProvider: () => async () => closureSourceCreds, + region: resolvedRegion, + requestHandler: isCompatibleRequestHandler ? requestHandler : undefined, + logger: logger, + }); + } + const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleCommand(params)); + if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) { + throw new Error(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`); + } + const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser); + const credentials = { + accessKeyId: Credentials.AccessKeyId, + secretAccessKey: Credentials.SecretAccessKey, + sessionToken: Credentials.SessionToken, + expiration: Credentials.Expiration, + ...(Credentials.CredentialScope && { credentialScope: Credentials.CredentialScope }), + ...(accountId && { accountId }), + }; + client.setCredentialFeature(credentials, "CREDENTIALS_STS_ASSUME_ROLE", "i"); + return credentials; + }; +}; +const getDefaultRoleAssumerWithWebIdentity$1 = (stsOptions, STSClient) => { + let stsClient; + return async (params) => { + if (!stsClient) { + const { logger = stsOptions?.parentClientConfig?.logger, profile = stsOptions?.parentClientConfig?.profile, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger, userAgentAppId = stsOptions?.parentClientConfig?.userAgentAppId, } = stsOptions; + const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger, { + logger, + profile, + }); + const isCompatibleRequestHandler = !isH2(requestHandler); + stsClient = new STSClient({ + ...stsOptions, + userAgentAppId, + profile, + region: resolvedRegion, + requestHandler: isCompatibleRequestHandler ? requestHandler : undefined, + logger: logger, + }); + } + const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleWithWebIdentityCommand(params)); + if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) { + throw new Error(`Invalid response from STS.assumeRoleWithWebIdentity call with role ${params.RoleArn}`); + } + const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser); + const credentials = { + accessKeyId: Credentials.AccessKeyId, + secretAccessKey: Credentials.SecretAccessKey, + sessionToken: Credentials.SessionToken, + expiration: Credentials.Expiration, + ...(Credentials.CredentialScope && { credentialScope: Credentials.CredentialScope }), + ...(accountId && { accountId }), + }; + if (accountId) { + client.setCredentialFeature(credentials, "RESOLVED_ACCOUNT_ID", "T"); + } + client.setCredentialFeature(credentials, "CREDENTIALS_STS_ASSUME_ROLE_WEB_ID", "k"); + return credentials; + }; +}; +const isH2 = (requestHandler) => { + return requestHandler?.metadata?.handlerProtocol === "h2"; +}; + +const getCustomizableStsClientCtor = (baseCtor, customizations) => { + if (!customizations) + return baseCtor; + else + return class CustomizableSTSClient extends baseCtor { + constructor(config) { + super(config); + for (const customization of customizations) { + this.middlewareStack.use(customization); + } + } + }; +}; +const getDefaultRoleAssumer = (stsOptions = {}, stsPlugins) => getDefaultRoleAssumer$1(stsOptions, getCustomizableStsClientCtor(STSClient.STSClient, stsPlugins)); +const getDefaultRoleAssumerWithWebIdentity = (stsOptions = {}, stsPlugins) => getDefaultRoleAssumerWithWebIdentity$1(stsOptions, getCustomizableStsClientCtor(STSClient.STSClient, stsPlugins)); +const decorateDefaultCredentialProvider = (provider) => (input) => provider({ + roleAssumer: getDefaultRoleAssumer(input), + roleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity(input), + ...input, +}); + +Object.defineProperty(exports, "$Command", { + enumerable: true, + get: function () { return smithyClient.Command; } +}); +exports.AssumeRoleCommand = AssumeRoleCommand; +exports.AssumeRoleWithWebIdentityCommand = AssumeRoleWithWebIdentityCommand; +exports.ExpiredTokenException = ExpiredTokenException$1; +exports.IDPCommunicationErrorException = IDPCommunicationErrorException$1; +exports.IDPRejectedClaimException = IDPRejectedClaimException$1; +exports.InvalidIdentityTokenException = InvalidIdentityTokenException$1; +exports.MalformedPolicyDocumentException = MalformedPolicyDocumentException$1; +exports.PackedPolicyTooLargeException = PackedPolicyTooLargeException$1; +exports.RegionDisabledException = RegionDisabledException$1; +exports.STS = STS; +exports.STSServiceException = STSServiceException$1; +exports.decorateDefaultCredentialProvider = decorateDefaultCredentialProvider; +exports.getDefaultRoleAssumer = getDefaultRoleAssumer; +exports.getDefaultRoleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity; +Object.keys(STSClient).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return STSClient[k]; } + }); +}); diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/runtimeConfig.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/runtimeConfig.js new file mode 100644 index 00000000..d98dd500 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/runtimeConfig.js @@ -0,0 +1,68 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getRuntimeConfig = void 0; +const tslib_1 = require("tslib"); +const package_json_1 = tslib_1.__importDefault(require("../../../package.json")); +const core_1 = require("@aws-sdk/core"); +const util_user_agent_node_1 = require("@aws-sdk/util-user-agent-node"); +const config_resolver_1 = require("@smithy/config-resolver"); +const core_2 = require("@smithy/core"); +const hash_node_1 = require("@smithy/hash-node"); +const middleware_retry_1 = require("@smithy/middleware-retry"); +const node_config_provider_1 = require("@smithy/node-config-provider"); +const node_http_handler_1 = require("@smithy/node-http-handler"); +const util_body_length_node_1 = require("@smithy/util-body-length-node"); +const util_retry_1 = require("@smithy/util-retry"); +const runtimeConfig_shared_1 = require("./runtimeConfig.shared"); +const smithy_client_1 = require("@smithy/smithy-client"); +const util_defaults_mode_node_1 = require("@smithy/util-defaults-mode-node"); +const smithy_client_2 = require("@smithy/smithy-client"); +const getRuntimeConfig = (config) => { + (0, smithy_client_2.emitWarningIfUnsupportedVersion)(process.version); + const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config); + const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode); + const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config); + (0, core_1.emitWarningIfUnsupportedVersion)(process.version); + const loaderConfig = { + profile: config?.profile, + logger: clientSharedValues.logger, + }; + return { + ...clientSharedValues, + ...config, + runtime: "node", + defaultsMode, + authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), + bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, + defaultUserAgentProvider: config?.defaultUserAgentProvider ?? + (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4") || + (async (idProps) => await config.credentialDefaultProvider(idProps?.__config || {})()), + signer: new core_1.AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new core_2.NoAuthSigner(), + }, + ], + maxAttempts: config?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), + region: config?.region ?? + (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), + requestHandler: node_http_handler_1.NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), + retryMode: config?.retryMode ?? + (0, node_config_provider_1.loadConfig)({ + ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS, + default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE, + }, config), + sha256: config?.sha256 ?? hash_node_1.Hash.bind(null, "sha256"), + streamCollector: config?.streamCollector ?? node_http_handler_1.streamCollector, + useDualstackEndpoint: config?.useDualstackEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), + }; +}; +exports.getRuntimeConfig = getRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/runtimeConfig.shared.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/runtimeConfig.shared.js new file mode 100644 index 00000000..5291d67e --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/runtimeConfig.shared.js @@ -0,0 +1,47 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getRuntimeConfig = void 0; +const core_1 = require("@aws-sdk/core"); +const protocols_1 = require("@aws-sdk/core/protocols"); +const core_2 = require("@smithy/core"); +const smithy_client_1 = require("@smithy/smithy-client"); +const url_parser_1 = require("@smithy/url-parser"); +const util_base64_1 = require("@smithy/util-base64"); +const util_utf8_1 = require("@smithy/util-utf8"); +const httpAuthSchemeProvider_1 = require("./auth/httpAuthSchemeProvider"); +const endpointResolver_1 = require("./endpoint/endpointResolver"); +const getRuntimeConfig = (config) => { + return { + apiVersion: "2011-06-15", + base64Decoder: config?.base64Decoder ?? util_base64_1.fromBase64, + base64Encoder: config?.base64Encoder ?? util_base64_1.toBase64, + disableHostPrefix: config?.disableHostPrefix ?? false, + endpointProvider: config?.endpointProvider ?? endpointResolver_1.defaultEndpointResolver, + extensions: config?.extensions ?? [], + httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSTSHttpAuthSchemeProvider, + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new core_1.AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new core_2.NoAuthSigner(), + }, + ], + logger: config?.logger ?? new smithy_client_1.NoOpLogger(), + protocol: config?.protocol ?? + new protocols_1.AwsQueryProtocol({ + defaultNamespace: "com.amazonaws.sts", + xmlNamespace: "https://sts.amazonaws.com/doc/2011-06-15/", + version: "2011-06-15", + }), + serviceId: config?.serviceId ?? "STS", + urlParser: config?.urlParser ?? url_parser_1.parseUrl, + utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, + utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, + }; +}; +exports.getRuntimeConfig = getRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/runtimeExtensions.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/runtimeExtensions.js new file mode 100644 index 00000000..a50ebec3 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/runtimeExtensions.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.resolveRuntimeExtensions = void 0; +const region_config_resolver_1 = require("@aws-sdk/region-config-resolver"); +const protocol_http_1 = require("@smithy/protocol-http"); +const smithy_client_1 = require("@smithy/smithy-client"); +const httpAuthExtensionConfiguration_1 = require("./auth/httpAuthExtensionConfiguration"); +const resolveRuntimeExtensions = (runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign((0, region_config_resolver_1.getAwsRegionExtensionConfiguration)(runtimeConfig), (0, smithy_client_1.getDefaultExtensionConfiguration)(runtimeConfig), (0, protocol_http_1.getHttpHandlerExtensionConfiguration)(runtimeConfig), (0, httpAuthExtensionConfiguration_1.getHttpAuthExtensionConfiguration)(runtimeConfig)); + extensions.forEach((extension) => extension.configure(extensionConfiguration)); + return Object.assign(runtimeConfig, (0, region_config_resolver_1.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), (0, smithy_client_1.resolveDefaultRuntimeConfig)(extensionConfiguration), (0, protocol_http_1.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), (0, httpAuthExtensionConfiguration_1.resolveHttpAuthRuntimeConfig)(extensionConfiguration)); +}; +exports.resolveRuntimeExtensions = resolveRuntimeExtensions; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/protocol-http/dist-cjs/index.js new file mode 100644 index 00000000..52303c3b --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/protocol-http/dist-cjs/index.js @@ -0,0 +1,169 @@ +'use strict'; + +var types = require('@smithy/types'); + +const getHttpHandlerExtensionConfiguration = (runtimeConfig) => { + return { + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); + }, + }; +}; +const resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler(), + }; +}; + +class Field { + name; + kind; + values; + constructor({ name, kind = types.FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; + } + add(value) { + this.values.push(value); + } + set(values) { + this.values = values; + } + remove(value) { + this.values = this.values.filter((v) => v !== value); + } + toString() { + return this.values.map((v) => (v.includes(",") || v.includes(" ") ? `"${v}"` : v)).join(", "); + } + get() { + return this.values; + } +} + +class Fields { + entries = {}; + encoding; + constructor({ fields = [], encoding = "utf-8" }) { + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + setField(field) { + this.entries[field.name.toLowerCase()] = field; + } + getField(name) { + return this.entries[name.toLowerCase()]; + } + removeField(name) { + delete this.entries[name.toLowerCase()]; + } + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } +} + +class HttpRequest { + method; + protocol; + hostname; + port; + path; + query; + headers; + username; + password; + fragment; + body; + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol + ? options.protocol.slice(-1) !== ":" + ? `${options.protocol}:` + : options.protocol + : "https:"; + this.path = options.path ? (options.path.charAt(0) !== "/" ? `/${options.path}` : options.path) : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + static clone(request) { + const cloned = new HttpRequest({ + ...request, + headers: { ...request.headers }, + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); + } + return cloned; + } + static isInstance(request) { + if (!request) { + return false; + } + const req = request; + return ("method" in req && + "protocol" in req && + "hostname" in req && + "path" in req && + typeof req["query"] === "object" && + typeof req["headers"] === "object"); + } + clone() { + return HttpRequest.clone(this); + } +} +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param, + }; + }, {}); +} + +class HttpResponse { + statusCode; + reason; + headers; + body; + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) + return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + } +} + +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} + +exports.Field = Field; +exports.Fields = Fields; +exports.HttpRequest = HttpRequest; +exports.HttpResponse = HttpResponse; +exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration; +exports.isValidHostname = isValidHostname; +exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/smithy-client/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/smithy-client/dist-cjs/index.js new file mode 100644 index 00000000..9f589873 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/smithy-client/dist-cjs/index.js @@ -0,0 +1,589 @@ +'use strict'; + +var middlewareStack = require('@smithy/middleware-stack'); +var protocols = require('@smithy/core/protocols'); +var types = require('@smithy/types'); +var schema = require('@smithy/core/schema'); +var serde = require('@smithy/core/serde'); + +class Client { + config; + middlewareStack = middlewareStack.constructStack(); + initConfig; + handlers; + constructor(config) { + this.config = config; + } + send(command, optionsOrCb, cb) { + const options = typeof optionsOrCb !== "function" ? optionsOrCb : undefined; + const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb; + const useHandlerCache = options === undefined && this.config.cacheMiddleware === true; + let handler; + if (useHandlerCache) { + if (!this.handlers) { + this.handlers = new WeakMap(); + } + const handlers = this.handlers; + if (handlers.has(command.constructor)) { + handler = handlers.get(command.constructor); + } + else { + handler = command.resolveMiddleware(this.middlewareStack, this.config, options); + handlers.set(command.constructor, handler); + } + } + else { + delete this.handlers; + handler = command.resolveMiddleware(this.middlewareStack, this.config, options); + } + if (callback) { + handler(command) + .then((result) => callback(null, result.output), (err) => callback(err)) + .catch(() => { }); + } + else { + return handler(command).then((result) => result.output); + } + } + destroy() { + this.config?.requestHandler?.destroy?.(); + delete this.handlers; + } +} + +const SENSITIVE_STRING$1 = "***SensitiveInformation***"; +function schemaLogFilter(schema$1, data) { + if (data == null) { + return data; + } + const ns = schema.NormalizedSchema.of(schema$1); + if (ns.getMergedTraits().sensitive) { + return SENSITIVE_STRING$1; + } + if (ns.isListSchema()) { + const isSensitive = !!ns.getValueSchema().getMergedTraits().sensitive; + if (isSensitive) { + return SENSITIVE_STRING$1; + } + } + else if (ns.isMapSchema()) { + const isSensitive = !!ns.getKeySchema().getMergedTraits().sensitive || !!ns.getValueSchema().getMergedTraits().sensitive; + if (isSensitive) { + return SENSITIVE_STRING$1; + } + } + else if (ns.isStructSchema() && typeof data === "object") { + const object = data; + const newObject = {}; + for (const [member, memberNs] of ns.structIterator()) { + if (object[member] != null) { + newObject[member] = schemaLogFilter(memberNs, object[member]); + } + } + return newObject; + } + return data; +} + +class Command { + middlewareStack = middlewareStack.constructStack(); + schema; + static classBuilder() { + return new ClassBuilder(); + } + resolveMiddlewareWithContext(clientStack, configuration, options, { middlewareFn, clientName, commandName, inputFilterSensitiveLog, outputFilterSensitiveLog, smithyContext, additionalContext, CommandCtor, }) { + for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options)) { + this.middlewareStack.use(mw); + } + const stack = clientStack.concat(this.middlewareStack); + const { logger } = configuration; + const handlerExecutionContext = { + logger, + clientName, + commandName, + inputFilterSensitiveLog, + outputFilterSensitiveLog, + [types.SMITHY_CONTEXT_KEY]: { + commandInstance: this, + ...smithyContext, + }, + ...additionalContext, + }; + const { requestHandler } = configuration; + return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); + } +} +class ClassBuilder { + _init = () => { }; + _ep = {}; + _middlewareFn = () => []; + _commandName = ""; + _clientName = ""; + _additionalContext = {}; + _smithyContext = {}; + _inputFilterSensitiveLog = undefined; + _outputFilterSensitiveLog = undefined; + _serializer = null; + _deserializer = null; + _operationSchema; + init(cb) { + this._init = cb; + } + ep(endpointParameterInstructions) { + this._ep = endpointParameterInstructions; + return this; + } + m(middlewareSupplier) { + this._middlewareFn = middlewareSupplier; + return this; + } + s(service, operation, smithyContext = {}) { + this._smithyContext = { + service, + operation, + ...smithyContext, + }; + return this; + } + c(additionalContext = {}) { + this._additionalContext = additionalContext; + return this; + } + n(clientName, commandName) { + this._clientName = clientName; + this._commandName = commandName; + return this; + } + f(inputFilter = (_) => _, outputFilter = (_) => _) { + this._inputFilterSensitiveLog = inputFilter; + this._outputFilterSensitiveLog = outputFilter; + return this; + } + ser(serializer) { + this._serializer = serializer; + return this; + } + de(deserializer) { + this._deserializer = deserializer; + return this; + } + sc(operation) { + this._operationSchema = operation; + this._smithyContext.operationSchema = operation; + return this; + } + build() { + const closure = this; + let CommandRef; + return (CommandRef = class extends Command { + input; + static getEndpointParameterInstructions() { + return closure._ep; + } + constructor(...[input]) { + super(); + this.input = input ?? {}; + closure._init(this); + this.schema = closure._operationSchema; + } + resolveMiddleware(stack, configuration, options) { + const op = closure._operationSchema; + const input = op?.[4] ?? op?.input; + const output = op?.[5] ?? op?.output; + return this.resolveMiddlewareWithContext(stack, configuration, options, { + CommandCtor: CommandRef, + middlewareFn: closure._middlewareFn, + clientName: closure._clientName, + commandName: closure._commandName, + inputFilterSensitiveLog: closure._inputFilterSensitiveLog ?? (op ? schemaLogFilter.bind(null, input) : (_) => _), + outputFilterSensitiveLog: closure._outputFilterSensitiveLog ?? (op ? schemaLogFilter.bind(null, output) : (_) => _), + smithyContext: closure._smithyContext, + additionalContext: closure._additionalContext, + }); + } + serialize = closure._serializer; + deserialize = closure._deserializer; + }); + } +} + +const SENSITIVE_STRING = "***SensitiveInformation***"; + +const createAggregatedClient = (commands, Client) => { + for (const command of Object.keys(commands)) { + const CommandCtor = commands[command]; + const methodImpl = async function (args, optionsOrCb, cb) { + const command = new CommandCtor(args); + if (typeof optionsOrCb === "function") { + this.send(command, optionsOrCb); + } + else if (typeof cb === "function") { + if (typeof optionsOrCb !== "object") + throw new Error(`Expected http options but got ${typeof optionsOrCb}`); + this.send(command, optionsOrCb || {}, cb); + } + else { + return this.send(command, optionsOrCb); + } + }; + const methodName = (command[0].toLowerCase() + command.slice(1)).replace(/Command$/, ""); + Client.prototype[methodName] = methodImpl; + } +}; + +class ServiceException extends Error { + $fault; + $response; + $retryable; + $metadata; + constructor(options) { + super(options.message); + Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype); + this.name = options.name; + this.$fault = options.$fault; + this.$metadata = options.$metadata; + } + static isInstance(value) { + if (!value) + return false; + const candidate = value; + return (ServiceException.prototype.isPrototypeOf(candidate) || + (Boolean(candidate.$fault) && + Boolean(candidate.$metadata) && + (candidate.$fault === "client" || candidate.$fault === "server"))); + } + static [Symbol.hasInstance](instance) { + if (!instance) + return false; + const candidate = instance; + if (this === ServiceException) { + return ServiceException.isInstance(instance); + } + if (ServiceException.isInstance(instance)) { + if (candidate.name && this.name) { + return this.prototype.isPrototypeOf(instance) || candidate.name === this.name; + } + return this.prototype.isPrototypeOf(instance); + } + return false; + } +} +const decorateServiceException = (exception, additions = {}) => { + Object.entries(additions) + .filter(([, v]) => v !== undefined) + .forEach(([k, v]) => { + if (exception[k] == undefined || exception[k] === "") { + exception[k] = v; + } + }); + const message = exception.message || exception.Message || "UnknownError"; + exception.message = message; + delete exception.Message; + return exception; +}; + +const throwDefaultError = ({ output, parsedBody, exceptionCtor, errorCode }) => { + const $metadata = deserializeMetadata(output); + const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : undefined; + const response = new exceptionCtor({ + name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || "UnknownError", + $fault: "client", + $metadata, + }); + throw decorateServiceException(response, parsedBody); +}; +const withBaseException = (ExceptionCtor) => { + return ({ output, parsedBody, errorCode }) => { + throwDefaultError({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode }); + }; +}; +const deserializeMetadata = (output) => ({ + httpStatusCode: output.statusCode, + requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], + extendedRequestId: output.headers["x-amz-id-2"], + cfId: output.headers["x-amz-cf-id"], +}); + +const loadConfigsForDefaultMode = (mode) => { + switch (mode) { + case "standard": + return { + retryMode: "standard", + connectionTimeout: 3100, + }; + case "in-region": + return { + retryMode: "standard", + connectionTimeout: 1100, + }; + case "cross-region": + return { + retryMode: "standard", + connectionTimeout: 3100, + }; + case "mobile": + return { + retryMode: "standard", + connectionTimeout: 30000, + }; + default: + return {}; + } +}; + +let warningEmitted = false; +const emitWarningIfUnsupportedVersion = (version) => { + if (version && !warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 16) { + warningEmitted = true; + } +}; + +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + for (const id in types.AlgorithmId) { + const algorithmId = types.AlgorithmId[id]; + if (runtimeConfig[algorithmId] === undefined) { + continue; + } + checksumAlgorithms.push({ + algorithmId: () => algorithmId, + checksumConstructor: () => runtimeConfig[algorithmId], + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getRetryConfiguration = (runtimeConfig) => { + return { + setRetryStrategy(retryStrategy) { + runtimeConfig.retryStrategy = retryStrategy; + }, + retryStrategy() { + return runtimeConfig.retryStrategy; + }, + }; +}; +const resolveRetryRuntimeConfig = (retryStrategyConfiguration) => { + const runtimeConfig = {}; + runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy(); + return runtimeConfig; +}; + +const getDefaultExtensionConfiguration = (runtimeConfig) => { + return Object.assign(getChecksumConfiguration(runtimeConfig), getRetryConfiguration(runtimeConfig)); +}; +const getDefaultClientConfiguration = getDefaultExtensionConfiguration; +const resolveDefaultRuntimeConfig = (config) => { + return Object.assign(resolveChecksumRuntimeConfig(config), resolveRetryRuntimeConfig(config)); +}; + +const getArrayIfSingleItem = (mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray]; + +const getValueFromTextNode = (obj) => { + const textNodeName = "#text"; + for (const key in obj) { + if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== undefined) { + obj[key] = obj[key][textNodeName]; + } + else if (typeof obj[key] === "object" && obj[key] !== null) { + obj[key] = getValueFromTextNode(obj[key]); + } + } + return obj; +}; + +const isSerializableHeaderValue = (value) => { + return value != null; +}; + +class NoOpLogger { + trace() { } + debug() { } + info() { } + warn() { } + error() { } +} + +function map(arg0, arg1, arg2) { + let target; + let filter; + let instructions; + if (typeof arg1 === "undefined" && typeof arg2 === "undefined") { + target = {}; + instructions = arg0; + } + else { + target = arg0; + if (typeof arg1 === "function") { + filter = arg1; + instructions = arg2; + return mapWithFilter(target, filter, instructions); + } + else { + instructions = arg1; + } + } + for (const key of Object.keys(instructions)) { + if (!Array.isArray(instructions[key])) { + target[key] = instructions[key]; + continue; + } + applyInstruction(target, null, instructions, key); + } + return target; +} +const convertMap = (target) => { + const output = {}; + for (const [k, v] of Object.entries(target || {})) { + output[k] = [, v]; + } + return output; +}; +const take = (source, instructions) => { + const out = {}; + for (const key in instructions) { + applyInstruction(out, source, instructions, key); + } + return out; +}; +const mapWithFilter = (target, filter, instructions) => { + return map(target, Object.entries(instructions).reduce((_instructions, [key, value]) => { + if (Array.isArray(value)) { + _instructions[key] = value; + } + else { + if (typeof value === "function") { + _instructions[key] = [filter, value()]; + } + else { + _instructions[key] = [filter, value]; + } + } + return _instructions; + }, {})); +}; +const applyInstruction = (target, source, instructions, targetKey) => { + if (source !== null) { + let instruction = instructions[targetKey]; + if (typeof instruction === "function") { + instruction = [, instruction]; + } + const [filter = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction; + if ((typeof filter === "function" && filter(source[sourceKey])) || (typeof filter !== "function" && !!filter)) { + target[targetKey] = valueFn(source[sourceKey]); + } + return; + } + let [filter, value] = instructions[targetKey]; + if (typeof value === "function") { + let _value; + const defaultFilterPassed = filter === undefined && (_value = value()) != null; + const customFilterPassed = (typeof filter === "function" && !!filter(void 0)) || (typeof filter !== "function" && !!filter); + if (defaultFilterPassed) { + target[targetKey] = _value; + } + else if (customFilterPassed) { + target[targetKey] = value(); + } + } + else { + const defaultFilterPassed = filter === undefined && value != null; + const customFilterPassed = (typeof filter === "function" && !!filter(value)) || (typeof filter !== "function" && !!filter); + if (defaultFilterPassed || customFilterPassed) { + target[targetKey] = value; + } + } +}; +const nonNullish = (_) => _ != null; +const pass = (_) => _; + +const serializeFloat = (value) => { + if (value !== value) { + return "NaN"; + } + switch (value) { + case Infinity: + return "Infinity"; + case -Infinity: + return "-Infinity"; + default: + return value; + } +}; +const serializeDateTime = (date) => date.toISOString().replace(".000Z", "Z"); + +const _json = (obj) => { + if (obj == null) { + return {}; + } + if (Array.isArray(obj)) { + return obj.filter((_) => _ != null).map(_json); + } + if (typeof obj === "object") { + const target = {}; + for (const key of Object.keys(obj)) { + if (obj[key] == null) { + continue; + } + target[key] = _json(obj[key]); + } + return target; + } + return obj; +}; + +Object.defineProperty(exports, "collectBody", { + enumerable: true, + get: function () { return protocols.collectBody; } +}); +Object.defineProperty(exports, "extendedEncodeURIComponent", { + enumerable: true, + get: function () { return protocols.extendedEncodeURIComponent; } +}); +Object.defineProperty(exports, "resolvedPath", { + enumerable: true, + get: function () { return protocols.resolvedPath; } +}); +exports.Client = Client; +exports.Command = Command; +exports.NoOpLogger = NoOpLogger; +exports.SENSITIVE_STRING = SENSITIVE_STRING; +exports.ServiceException = ServiceException; +exports._json = _json; +exports.convertMap = convertMap; +exports.createAggregatedClient = createAggregatedClient; +exports.decorateServiceException = decorateServiceException; +exports.emitWarningIfUnsupportedVersion = emitWarningIfUnsupportedVersion; +exports.getArrayIfSingleItem = getArrayIfSingleItem; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.getDefaultExtensionConfiguration = getDefaultExtensionConfiguration; +exports.getValueFromTextNode = getValueFromTextNode; +exports.isSerializableHeaderValue = isSerializableHeaderValue; +exports.loadConfigsForDefaultMode = loadConfigsForDefaultMode; +exports.map = map; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; +exports.serializeDateTime = serializeDateTime; +exports.serializeFloat = serializeFloat; +exports.take = take; +exports.throwDefaultError = throwDefaultError; +exports.withBaseException = withBaseException; +Object.keys(serde).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return serde[k]; } + }); +}); diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/types/dist-cjs/index.js new file mode 100644 index 00000000..be6d0e1a --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/types/dist-cjs/index.js @@ -0,0 +1,91 @@ +'use strict'; + +exports.HttpAuthLocation = void 0; +(function (HttpAuthLocation) { + HttpAuthLocation["HEADER"] = "header"; + HttpAuthLocation["QUERY"] = "query"; +})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); + +exports.HttpApiKeyAuthLocation = void 0; +(function (HttpApiKeyAuthLocation) { + HttpApiKeyAuthLocation["HEADER"] = "header"; + HttpApiKeyAuthLocation["QUERY"] = "query"; +})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); + +exports.EndpointURLScheme = void 0; +(function (EndpointURLScheme) { + EndpointURLScheme["HTTP"] = "http"; + EndpointURLScheme["HTTPS"] = "https"; +})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); + +exports.AlgorithmId = void 0; +(function (AlgorithmId) { + AlgorithmId["MD5"] = "md5"; + AlgorithmId["CRC32"] = "crc32"; + AlgorithmId["CRC32C"] = "crc32c"; + AlgorithmId["SHA1"] = "sha1"; + AlgorithmId["SHA256"] = "sha256"; +})(exports.AlgorithmId || (exports.AlgorithmId = {})); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.SHA256, + checksumConstructor: () => runtimeConfig.sha256, + }); + } + if (runtimeConfig.md5 != undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.MD5, + checksumConstructor: () => runtimeConfig.md5, + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getDefaultClientConfiguration = (runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}; +const resolveDefaultRuntimeConfig = (config) => { + return resolveChecksumRuntimeConfig(config); +}; + +exports.FieldPosition = void 0; +(function (FieldPosition) { + FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; + FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; +})(exports.FieldPosition || (exports.FieldPosition = {})); + +const SMITHY_CONTEXT_KEY = "__smithy_context"; + +exports.IniSectionType = void 0; +(function (IniSectionType) { + IniSectionType["PROFILE"] = "profile"; + IniSectionType["SSO_SESSION"] = "sso-session"; + IniSectionType["SERVICES"] = "services"; +})(exports.IniSectionType || (exports.IniSectionType = {})); + +exports.RequestHandlerProtocol = void 0; +(function (RequestHandlerProtocol) { + RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; +})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); + +exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js new file mode 100644 index 00000000..b06a7b87 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromBase64 = void 0; +const util_buffer_from_1 = require("@smithy/util-buffer-from"); +const BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; +const fromBase64 = (input) => { + if ((input.length * 3) % 4 !== 0) { + throw new TypeError(`Incorrect padding on base64 string.`); + } + if (!BASE64_REGEX.exec(input)) { + throw new TypeError(`Invalid base64 string.`); + } + const buffer = (0, util_buffer_from_1.fromString)(input, "base64"); + return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); +}; +exports.fromBase64 = fromBase64; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/dist-cjs/index.js new file mode 100644 index 00000000..c095e288 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/dist-cjs/index.js @@ -0,0 +1,19 @@ +'use strict'; + +var fromBase64 = require('./fromBase64'); +var toBase64 = require('./toBase64'); + + + +Object.keys(fromBase64).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return fromBase64[k]; } + }); +}); +Object.keys(toBase64).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return toBase64[k]; } + }); +}); diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/dist-cjs/toBase64.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/dist-cjs/toBase64.js new file mode 100644 index 00000000..0590ce3f --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/dist-cjs/toBase64.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.toBase64 = void 0; +const util_buffer_from_1 = require("@smithy/util-buffer-from"); +const util_utf8_1 = require("@smithy/util-utf8"); +const toBase64 = (_input) => { + let input; + if (typeof _input === "string") { + input = (0, util_utf8_1.fromUtf8)(_input); + } + else { + input = _input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); + } + return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64"); +}; +exports.toBase64 = toBase64; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js new file mode 100644 index 00000000..b577c9ca --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js @@ -0,0 +1,20 @@ +'use strict'; + +var isArrayBuffer = require('@smithy/is-array-buffer'); +var buffer = require('buffer'); + +const fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => { + if (!isArrayBuffer.isArrayBuffer(input)) { + throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); + } + return buffer.Buffer.from(input, offset, length); +}; +const fromString = (input, encoding) => { + if (typeof input !== "string") { + throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); + } + return encoding ? buffer.Buffer.from(input, encoding) : buffer.Buffer.from(input); +}; + +exports.fromArrayBuffer = fromArrayBuffer; +exports.fromString = fromString; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js new file mode 100644 index 00000000..3238bb77 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js @@ -0,0 +1,6 @@ +'use strict'; + +const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) || + Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; + +exports.isArrayBuffer = isArrayBuffer; diff --git a/claude-code-source/node_modules/@aws-sdk/region-config-resolver/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/region-config-resolver/dist-cjs/index.js new file mode 100644 index 00000000..89a2b7f2 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/region-config-resolver/dist-cjs/index.js @@ -0,0 +1,49 @@ +'use strict'; + +var configResolver = require('@smithy/config-resolver'); +var stsRegionDefaultResolver = require('./regionConfig/stsRegionDefaultResolver'); + +const getAwsRegionExtensionConfiguration = (runtimeConfig) => { + return { + setRegion(region) { + runtimeConfig.region = region; + }, + region() { + return runtimeConfig.region; + }, + }; +}; +const resolveAwsRegionExtensionConfiguration = (awsRegionExtensionConfiguration) => { + return { + region: awsRegionExtensionConfiguration.region(), + }; +}; + +Object.defineProperty(exports, "NODE_REGION_CONFIG_FILE_OPTIONS", { + enumerable: true, + get: function () { return configResolver.NODE_REGION_CONFIG_FILE_OPTIONS; } +}); +Object.defineProperty(exports, "NODE_REGION_CONFIG_OPTIONS", { + enumerable: true, + get: function () { return configResolver.NODE_REGION_CONFIG_OPTIONS; } +}); +Object.defineProperty(exports, "REGION_ENV_NAME", { + enumerable: true, + get: function () { return configResolver.REGION_ENV_NAME; } +}); +Object.defineProperty(exports, "REGION_INI_NAME", { + enumerable: true, + get: function () { return configResolver.REGION_INI_NAME; } +}); +Object.defineProperty(exports, "resolveRegionConfig", { + enumerable: true, + get: function () { return configResolver.resolveRegionConfig; } +}); +exports.getAwsRegionExtensionConfiguration = getAwsRegionExtensionConfiguration; +exports.resolveAwsRegionExtensionConfiguration = resolveAwsRegionExtensionConfiguration; +Object.keys(stsRegionDefaultResolver).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return stsRegionDefaultResolver[k]; } + }); +}); diff --git a/claude-code-source/node_modules/@aws-sdk/region-config-resolver/dist-cjs/regionConfig/stsRegionDefaultResolver.js b/claude-code-source/node_modules/@aws-sdk/region-config-resolver/dist-cjs/regionConfig/stsRegionDefaultResolver.js new file mode 100644 index 00000000..30d06fbd --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/region-config-resolver/dist-cjs/regionConfig/stsRegionDefaultResolver.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.warning = void 0; +exports.stsRegionDefaultResolver = stsRegionDefaultResolver; +const config_resolver_1 = require("@smithy/config-resolver"); +const node_config_provider_1 = require("@smithy/node-config-provider"); +function stsRegionDefaultResolver(loaderConfig = {}) { + return (0, node_config_provider_1.loadConfig)({ + ...config_resolver_1.NODE_REGION_CONFIG_OPTIONS, + async default() { + if (!exports.warning.silence) { + console.warn("@aws-sdk - WARN - default STS region of us-east-1 used. See @aws-sdk/credential-providers README and set a region explicitly."); + } + return "us-east-1"; + }, + }, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }); +} +exports.warning = { + silence: false, +}; diff --git a/claude-code-source/node_modules/@aws-sdk/token-providers/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/token-providers/dist-cjs/index.js new file mode 100644 index 00000000..eff14c07 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/token-providers/dist-cjs/index.js @@ -0,0 +1,164 @@ +'use strict'; + +var client = require('@aws-sdk/core/client'); +var httpAuthSchemes = require('@aws-sdk/core/httpAuthSchemes'); +var propertyProvider = require('@smithy/property-provider'); +var sharedIniFileLoader = require('@smithy/shared-ini-file-loader'); +var fs = require('fs'); + +const fromEnvSigningName = ({ logger, signingName } = {}) => async () => { + logger?.debug?.("@aws-sdk/token-providers - fromEnvSigningName"); + if (!signingName) { + throw new propertyProvider.TokenProviderError("Please pass 'signingName' to compute environment variable key", { logger }); + } + const bearerTokenKey = httpAuthSchemes.getBearerTokenEnvKey(signingName); + if (!(bearerTokenKey in process.env)) { + throw new propertyProvider.TokenProviderError(`Token not present in '${bearerTokenKey}' environment variable`, { logger }); + } + const token = { token: process.env[bearerTokenKey] }; + client.setTokenFeature(token, "BEARER_SERVICE_ENV_VARS", "3"); + return token; +}; + +const EXPIRE_WINDOW_MS = 5 * 60 * 1000; +const REFRESH_MESSAGE = `To refresh this SSO session run 'aws sso login' with the corresponding profile.`; + +const getSsoOidcClient = async (ssoRegion, init = {}) => { + const { SSOOIDCClient } = await import('@aws-sdk/nested-clients/sso-oidc'); + const coalesce = (prop) => init.clientConfig?.[prop] ?? init.parentClientConfig?.[prop]; + const ssoOidcClient = new SSOOIDCClient(Object.assign({}, init.clientConfig ?? {}, { + region: ssoRegion ?? init.clientConfig?.region, + logger: coalesce("logger"), + userAgentAppId: coalesce("userAgentAppId"), + })); + return ssoOidcClient; +}; + +const getNewSsoOidcToken = async (ssoToken, ssoRegion, init = {}) => { + const { CreateTokenCommand } = await import('@aws-sdk/nested-clients/sso-oidc'); + const ssoOidcClient = await getSsoOidcClient(ssoRegion, init); + return ssoOidcClient.send(new CreateTokenCommand({ + clientId: ssoToken.clientId, + clientSecret: ssoToken.clientSecret, + refreshToken: ssoToken.refreshToken, + grantType: "refresh_token", + })); +}; + +const validateTokenExpiry = (token) => { + if (token.expiration && token.expiration.getTime() < Date.now()) { + throw new propertyProvider.TokenProviderError(`Token is expired. ${REFRESH_MESSAGE}`, false); + } +}; + +const validateTokenKey = (key, value, forRefresh = false) => { + if (typeof value === "undefined") { + throw new propertyProvider.TokenProviderError(`Value not present for '${key}' in SSO Token${forRefresh ? ". Cannot refresh" : ""}. ${REFRESH_MESSAGE}`, false); + } +}; + +const { writeFile } = fs.promises; +const writeSSOTokenToFile = (id, ssoToken) => { + const tokenFilepath = sharedIniFileLoader.getSSOTokenFilepath(id); + const tokenString = JSON.stringify(ssoToken, null, 2); + return writeFile(tokenFilepath, tokenString); +}; + +const lastRefreshAttemptTime = new Date(0); +const fromSso = (_init = {}) => async ({ callerClientConfig } = {}) => { + const init = { + ..._init, + parentClientConfig: { + ...callerClientConfig, + ..._init.parentClientConfig, + }, + }; + init.logger?.debug("@aws-sdk/token-providers - fromSso"); + const profiles = await sharedIniFileLoader.parseKnownFiles(init); + const profileName = sharedIniFileLoader.getProfileName({ + profile: init.profile ?? callerClientConfig?.profile, + }); + const profile = profiles[profileName]; + if (!profile) { + throw new propertyProvider.TokenProviderError(`Profile '${profileName}' could not be found in shared credentials file.`, false); + } + else if (!profile["sso_session"]) { + throw new propertyProvider.TokenProviderError(`Profile '${profileName}' is missing required property 'sso_session'.`); + } + const ssoSessionName = profile["sso_session"]; + const ssoSessions = await sharedIniFileLoader.loadSsoSessionData(init); + const ssoSession = ssoSessions[ssoSessionName]; + if (!ssoSession) { + throw new propertyProvider.TokenProviderError(`Sso session '${ssoSessionName}' could not be found in shared credentials file.`, false); + } + for (const ssoSessionRequiredKey of ["sso_start_url", "sso_region"]) { + if (!ssoSession[ssoSessionRequiredKey]) { + throw new propertyProvider.TokenProviderError(`Sso session '${ssoSessionName}' is missing required property '${ssoSessionRequiredKey}'.`, false); + } + } + ssoSession["sso_start_url"]; + const ssoRegion = ssoSession["sso_region"]; + let ssoToken; + try { + ssoToken = await sharedIniFileLoader.getSSOTokenFromFile(ssoSessionName); + } + catch (e) { + throw new propertyProvider.TokenProviderError(`The SSO session token associated with profile=${profileName} was not found or is invalid. ${REFRESH_MESSAGE}`, false); + } + validateTokenKey("accessToken", ssoToken.accessToken); + validateTokenKey("expiresAt", ssoToken.expiresAt); + const { accessToken, expiresAt } = ssoToken; + const existingToken = { token: accessToken, expiration: new Date(expiresAt) }; + if (existingToken.expiration.getTime() - Date.now() > EXPIRE_WINDOW_MS) { + return existingToken; + } + if (Date.now() - lastRefreshAttemptTime.getTime() < 30 * 1000) { + validateTokenExpiry(existingToken); + return existingToken; + } + validateTokenKey("clientId", ssoToken.clientId, true); + validateTokenKey("clientSecret", ssoToken.clientSecret, true); + validateTokenKey("refreshToken", ssoToken.refreshToken, true); + try { + lastRefreshAttemptTime.setTime(Date.now()); + const newSsoOidcToken = await getNewSsoOidcToken(ssoToken, ssoRegion, init); + validateTokenKey("accessToken", newSsoOidcToken.accessToken); + validateTokenKey("expiresIn", newSsoOidcToken.expiresIn); + const newTokenExpiration = new Date(Date.now() + newSsoOidcToken.expiresIn * 1000); + try { + await writeSSOTokenToFile(ssoSessionName, { + ...ssoToken, + accessToken: newSsoOidcToken.accessToken, + expiresAt: newTokenExpiration.toISOString(), + refreshToken: newSsoOidcToken.refreshToken, + }); + } + catch (error) { + } + return { + token: newSsoOidcToken.accessToken, + expiration: newTokenExpiration, + }; + } + catch (error) { + validateTokenExpiry(existingToken); + return existingToken; + } +}; + +const fromStatic = ({ token, logger }) => async () => { + logger?.debug("@aws-sdk/token-providers - fromStatic"); + if (!token || !token.token) { + throw new propertyProvider.TokenProviderError(`Please pass a valid token to fromStatic`, false); + } + return token; +}; + +const nodeProvider = (init = {}) => propertyProvider.memoize(propertyProvider.chain(fromSso(init), async () => { + throw new propertyProvider.TokenProviderError("Could not load token from any providers", false); +}), (token) => token.expiration !== undefined && token.expiration.getTime() - Date.now() < 300000, (token) => token.expiration !== undefined); + +exports.fromEnvSigningName = fromEnvSigningName; +exports.fromSso = fromSso; +exports.fromStatic = fromStatic; +exports.nodeProvider = nodeProvider; diff --git a/claude-code-source/node_modules/@aws-sdk/util-endpoints/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/util-endpoints/dist-cjs/index.js new file mode 100644 index 00000000..db973005 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/util-endpoints/dist-cjs/index.js @@ -0,0 +1,415 @@ +'use strict'; + +var utilEndpoints = require('@smithy/util-endpoints'); +var urlParser = require('@smithy/url-parser'); + +const isVirtualHostableS3Bucket = (value, allowSubDomains = false) => { + if (allowSubDomains) { + for (const label of value.split(".")) { + if (!isVirtualHostableS3Bucket(label)) { + return false; + } + } + return true; + } + if (!utilEndpoints.isValidHostLabel(value)) { + return false; + } + if (value.length < 3 || value.length > 63) { + return false; + } + if (value !== value.toLowerCase()) { + return false; + } + if (utilEndpoints.isIpAddress(value)) { + return false; + } + return true; +}; + +const ARN_DELIMITER = ":"; +const RESOURCE_DELIMITER = "/"; +const parseArn = (value) => { + const segments = value.split(ARN_DELIMITER); + if (segments.length < 6) + return null; + const [arn, partition, service, region, accountId, ...resourcePath] = segments; + if (arn !== "arn" || partition === "" || service === "" || resourcePath.join(ARN_DELIMITER) === "") + return null; + const resourceId = resourcePath.map((resource) => resource.split(RESOURCE_DELIMITER)).flat(); + return { + partition, + service, + region, + accountId, + resourceId, + }; +}; + +var partitions = [ + { + id: "aws", + outputs: { + dnsSuffix: "amazonaws.com", + dualStackDnsSuffix: "api.aws", + implicitGlobalRegion: "us-east-1", + name: "aws", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$", + regions: { + "af-south-1": { + description: "Africa (Cape Town)" + }, + "ap-east-1": { + description: "Asia Pacific (Hong Kong)" + }, + "ap-east-2": { + description: "Asia Pacific (Taipei)" + }, + "ap-northeast-1": { + description: "Asia Pacific (Tokyo)" + }, + "ap-northeast-2": { + description: "Asia Pacific (Seoul)" + }, + "ap-northeast-3": { + description: "Asia Pacific (Osaka)" + }, + "ap-south-1": { + description: "Asia Pacific (Mumbai)" + }, + "ap-south-2": { + description: "Asia Pacific (Hyderabad)" + }, + "ap-southeast-1": { + description: "Asia Pacific (Singapore)" + }, + "ap-southeast-2": { + description: "Asia Pacific (Sydney)" + }, + "ap-southeast-3": { + description: "Asia Pacific (Jakarta)" + }, + "ap-southeast-4": { + description: "Asia Pacific (Melbourne)" + }, + "ap-southeast-5": { + description: "Asia Pacific (Malaysia)" + }, + "ap-southeast-6": { + description: "Asia Pacific (New Zealand)" + }, + "ap-southeast-7": { + description: "Asia Pacific (Thailand)" + }, + "aws-global": { + description: "aws global region" + }, + "ca-central-1": { + description: "Canada (Central)" + }, + "ca-west-1": { + description: "Canada West (Calgary)" + }, + "eu-central-1": { + description: "Europe (Frankfurt)" + }, + "eu-central-2": { + description: "Europe (Zurich)" + }, + "eu-north-1": { + description: "Europe (Stockholm)" + }, + "eu-south-1": { + description: "Europe (Milan)" + }, + "eu-south-2": { + description: "Europe (Spain)" + }, + "eu-west-1": { + description: "Europe (Ireland)" + }, + "eu-west-2": { + description: "Europe (London)" + }, + "eu-west-3": { + description: "Europe (Paris)" + }, + "il-central-1": { + description: "Israel (Tel Aviv)" + }, + "me-central-1": { + description: "Middle East (UAE)" + }, + "me-south-1": { + description: "Middle East (Bahrain)" + }, + "mx-central-1": { + description: "Mexico (Central)" + }, + "sa-east-1": { + description: "South America (Sao Paulo)" + }, + "us-east-1": { + description: "US East (N. Virginia)" + }, + "us-east-2": { + description: "US East (Ohio)" + }, + "us-west-1": { + description: "US West (N. California)" + }, + "us-west-2": { + description: "US West (Oregon)" + } + } + }, + { + id: "aws-cn", + outputs: { + dnsSuffix: "amazonaws.com.cn", + dualStackDnsSuffix: "api.amazonwebservices.com.cn", + implicitGlobalRegion: "cn-northwest-1", + name: "aws-cn", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^cn\\-\\w+\\-\\d+$", + regions: { + "aws-cn-global": { + description: "aws-cn global region" + }, + "cn-north-1": { + description: "China (Beijing)" + }, + "cn-northwest-1": { + description: "China (Ningxia)" + } + } + }, + { + id: "aws-eusc", + outputs: { + dnsSuffix: "amazonaws.eu", + dualStackDnsSuffix: "api.amazonwebservices.eu", + implicitGlobalRegion: "eusc-de-east-1", + name: "aws-eusc", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^eusc\\-(de)\\-\\w+\\-\\d+$", + regions: { + "eusc-de-east-1": { + description: "EU (Germany)" + } + } + }, + { + id: "aws-iso", + outputs: { + dnsSuffix: "c2s.ic.gov", + dualStackDnsSuffix: "api.aws.ic.gov", + implicitGlobalRegion: "us-iso-east-1", + name: "aws-iso", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^us\\-iso\\-\\w+\\-\\d+$", + regions: { + "aws-iso-global": { + description: "aws-iso global region" + }, + "us-iso-east-1": { + description: "US ISO East" + }, + "us-iso-west-1": { + description: "US ISO WEST" + } + } + }, + { + id: "aws-iso-b", + outputs: { + dnsSuffix: "sc2s.sgov.gov", + dualStackDnsSuffix: "api.aws.scloud", + implicitGlobalRegion: "us-isob-east-1", + name: "aws-iso-b", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^us\\-isob\\-\\w+\\-\\d+$", + regions: { + "aws-iso-b-global": { + description: "aws-iso-b global region" + }, + "us-isob-east-1": { + description: "US ISOB East (Ohio)" + }, + "us-isob-west-1": { + description: "US ISOB West" + } + } + }, + { + id: "aws-iso-e", + outputs: { + dnsSuffix: "cloud.adc-e.uk", + dualStackDnsSuffix: "api.cloud-aws.adc-e.uk", + implicitGlobalRegion: "eu-isoe-west-1", + name: "aws-iso-e", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^eu\\-isoe\\-\\w+\\-\\d+$", + regions: { + "aws-iso-e-global": { + description: "aws-iso-e global region" + }, + "eu-isoe-west-1": { + description: "EU ISOE West" + } + } + }, + { + id: "aws-iso-f", + outputs: { + dnsSuffix: "csp.hci.ic.gov", + dualStackDnsSuffix: "api.aws.hci.ic.gov", + implicitGlobalRegion: "us-isof-south-1", + name: "aws-iso-f", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^us\\-isof\\-\\w+\\-\\d+$", + regions: { + "aws-iso-f-global": { + description: "aws-iso-f global region" + }, + "us-isof-east-1": { + description: "US ISOF EAST" + }, + "us-isof-south-1": { + description: "US ISOF SOUTH" + } + } + }, + { + id: "aws-us-gov", + outputs: { + dnsSuffix: "amazonaws.com", + dualStackDnsSuffix: "api.aws", + implicitGlobalRegion: "us-gov-west-1", + name: "aws-us-gov", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^us\\-gov\\-\\w+\\-\\d+$", + regions: { + "aws-us-gov-global": { + description: "aws-us-gov global region" + }, + "us-gov-east-1": { + description: "AWS GovCloud (US-East)" + }, + "us-gov-west-1": { + description: "AWS GovCloud (US-West)" + } + } + } +]; +var version = "1.1"; +var partitionsInfo = { + partitions: partitions, + version: version +}; + +let selectedPartitionsInfo = partitionsInfo; +let selectedUserAgentPrefix = ""; +const partition = (value) => { + const { partitions } = selectedPartitionsInfo; + for (const partition of partitions) { + const { regions, outputs } = partition; + for (const [region, regionData] of Object.entries(regions)) { + if (region === value) { + return { + ...outputs, + ...regionData, + }; + } + } + } + for (const partition of partitions) { + const { regionRegex, outputs } = partition; + if (new RegExp(regionRegex).test(value)) { + return { + ...outputs, + }; + } + } + const DEFAULT_PARTITION = partitions.find((partition) => partition.id === "aws"); + if (!DEFAULT_PARTITION) { + throw new Error("Provided region was not found in the partition array or regex," + + " and default partition with id 'aws' doesn't exist."); + } + return { + ...DEFAULT_PARTITION.outputs, + }; +}; +const setPartitionInfo = (partitionsInfo, userAgentPrefix = "") => { + selectedPartitionsInfo = partitionsInfo; + selectedUserAgentPrefix = userAgentPrefix; +}; +const useDefaultPartitionInfo = () => { + setPartitionInfo(partitionsInfo, ""); +}; +const getUserAgentPrefix = () => selectedUserAgentPrefix; + +const awsEndpointFunctions = { + isVirtualHostableS3Bucket: isVirtualHostableS3Bucket, + parseArn: parseArn, + partition: partition, +}; +utilEndpoints.customEndpointFunctions.aws = awsEndpointFunctions; + +const resolveDefaultAwsRegionalEndpointsConfig = (input) => { + if (typeof input.endpointProvider !== "function") { + throw new Error("@aws-sdk/util-endpoint - endpointProvider and endpoint missing in config for this client."); + } + const { endpoint } = input; + if (endpoint === undefined) { + input.endpoint = async () => { + return toEndpointV1(input.endpointProvider({ + Region: typeof input.region === "function" ? await input.region() : input.region, + UseDualStack: typeof input.useDualstackEndpoint === "function" + ? await input.useDualstackEndpoint() + : input.useDualstackEndpoint, + UseFIPS: typeof input.useFipsEndpoint === "function" ? await input.useFipsEndpoint() : input.useFipsEndpoint, + Endpoint: undefined, + }, { logger: input.logger })); + }; + } + return input; +}; +const toEndpointV1 = (endpoint) => urlParser.parseUrl(endpoint.url); + +Object.defineProperty(exports, "EndpointError", { + enumerable: true, + get: function () { return utilEndpoints.EndpointError; } +}); +Object.defineProperty(exports, "isIpAddress", { + enumerable: true, + get: function () { return utilEndpoints.isIpAddress; } +}); +Object.defineProperty(exports, "resolveEndpoint", { + enumerable: true, + get: function () { return utilEndpoints.resolveEndpoint; } +}); +exports.awsEndpointFunctions = awsEndpointFunctions; +exports.getUserAgentPrefix = getUserAgentPrefix; +exports.partition = partition; +exports.resolveDefaultAwsRegionalEndpointsConfig = resolveDefaultAwsRegionalEndpointsConfig; +exports.setPartitionInfo = setPartitionInfo; +exports.toEndpointV1 = toEndpointV1; +exports.useDefaultPartitionInfo = useDefaultPartitionInfo; diff --git a/claude-code-source/node_modules/@aws-sdk/util-format-url/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/util-format-url/dist-cjs/index.js new file mode 100644 index 00000000..de16777f --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/util-format-url/dist-cjs/index.js @@ -0,0 +1,34 @@ +'use strict'; + +var querystringBuilder = require('@smithy/querystring-builder'); + +function formatUrl(request) { + const { port, query } = request; + let { protocol, path, hostname } = request; + if (protocol && protocol.slice(-1) !== ":") { + protocol += ":"; + } + if (port) { + hostname += `:${port}`; + } + if (path && path.charAt(0) !== "/") { + path = `/${path}`; + } + let queryString = query ? querystringBuilder.buildQueryString(query) : ""; + if (queryString && queryString[0] !== "?") { + queryString = `?${queryString}`; + } + let auth = ""; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}@`; + } + let fragment = ""; + if (request.fragment) { + fragment = `#${request.fragment}`; + } + return `${protocol}//${auth}${hostname}${path}${queryString}${fragment}`; +} + +exports.formatUrl = formatUrl; diff --git a/claude-code-source/node_modules/@aws-sdk/util-format-url/node_modules/@smithy/querystring-builder/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/util-format-url/node_modules/@smithy/querystring-builder/dist-cjs/index.js new file mode 100644 index 00000000..f245489f --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/util-format-url/node_modules/@smithy/querystring-builder/dist-cjs/index.js @@ -0,0 +1,26 @@ +'use strict'; + +var utilUriEscape = require('@smithy/util-uri-escape'); + +function buildQueryString(query) { + const parts = []; + for (let key of Object.keys(query).sort()) { + const value = query[key]; + key = utilUriEscape.escapeUri(key); + if (Array.isArray(value)) { + for (let i = 0, iLen = value.length; i < iLen; i++) { + parts.push(`${key}=${utilUriEscape.escapeUri(value[i])}`); + } + } + else { + let qsEntry = key; + if (value || typeof value === "string") { + qsEntry += `=${utilUriEscape.escapeUri(value)}`; + } + parts.push(qsEntry); + } + } + return parts.join("&"); +} + +exports.buildQueryString = buildQueryString; diff --git a/claude-code-source/node_modules/@aws-sdk/util-format-url/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/util-format-url/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js new file mode 100644 index 00000000..11f942c3 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/util-format-url/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js @@ -0,0 +1,9 @@ +'use strict'; + +const escapeUri = (uri) => encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode); +const hexEncode = (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`; + +const escapeUriPath = (uri) => uri.split("/").map(escapeUri).join("/"); + +exports.escapeUri = escapeUri; +exports.escapeUriPath = escapeUriPath; diff --git a/claude-code-source/node_modules/@aws-sdk/util-user-agent-node/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/util-user-agent-node/dist-cjs/index.js new file mode 100644 index 00000000..c7dc6fa3 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/util-user-agent-node/dist-cjs/index.js @@ -0,0 +1,58 @@ +'use strict'; + +var os = require('os'); +var process = require('process'); +var middlewareUserAgent = require('@aws-sdk/middleware-user-agent'); + +const crtAvailability = { + isCrtAvailable: false, +}; + +const isCrtAvailable = () => { + if (crtAvailability.isCrtAvailable) { + return ["md/crt-avail"]; + } + return null; +}; + +const createDefaultUserAgentProvider = ({ serviceId, clientVersion }) => { + return async (config) => { + const sections = [ + ["aws-sdk-js", clientVersion], + ["ua", "2.1"], + [`os/${os.platform()}`, os.release()], + ["lang/js"], + ["md/nodejs", `${process.versions.node}`], + ]; + const crtAvailable = isCrtAvailable(); + if (crtAvailable) { + sections.push(crtAvailable); + } + if (serviceId) { + sections.push([`api/${serviceId}`, clientVersion]); + } + if (process.env.AWS_EXECUTION_ENV) { + sections.push([`exec-env/${process.env.AWS_EXECUTION_ENV}`]); + } + const appId = await config?.userAgentAppId?.(); + const resolvedUserAgent = appId ? [...sections, [`app/${appId}`]] : [...sections]; + return resolvedUserAgent; + }; +}; +const defaultUserAgent = createDefaultUserAgentProvider; + +const UA_APP_ID_ENV_NAME = "AWS_SDK_UA_APP_ID"; +const UA_APP_ID_INI_NAME = "sdk_ua_app_id"; +const UA_APP_ID_INI_NAME_DEPRECATED = "sdk-ua-app-id"; +const NODE_APP_ID_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => env[UA_APP_ID_ENV_NAME], + configFileSelector: (profile) => profile[UA_APP_ID_INI_NAME] ?? profile[UA_APP_ID_INI_NAME_DEPRECATED], + default: middlewareUserAgent.DEFAULT_UA_APP_ID, +}; + +exports.NODE_APP_ID_CONFIG_OPTIONS = NODE_APP_ID_CONFIG_OPTIONS; +exports.UA_APP_ID_ENV_NAME = UA_APP_ID_ENV_NAME; +exports.UA_APP_ID_INI_NAME = UA_APP_ID_INI_NAME; +exports.createDefaultUserAgentProvider = createDefaultUserAgentProvider; +exports.crtAvailability = crtAvailability; +exports.defaultUserAgent = defaultUserAgent; diff --git a/claude-code-source/node_modules/@aws-sdk/util-utf8-browser/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/util-utf8-browser/dist-cjs/index.js new file mode 100644 index 00000000..e5960876 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/util-utf8-browser/dist-cjs/index.js @@ -0,0 +1,9 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.toUtf8 = exports.fromUtf8 = void 0; +const pureJs_1 = require("./pureJs"); +const whatwgEncodingApi_1 = require("./whatwgEncodingApi"); +const fromUtf8 = (input) => typeof TextEncoder === "function" ? (0, whatwgEncodingApi_1.fromUtf8)(input) : (0, pureJs_1.fromUtf8)(input); +exports.fromUtf8 = fromUtf8; +const toUtf8 = (input) => typeof TextDecoder === "function" ? (0, whatwgEncodingApi_1.toUtf8)(input) : (0, pureJs_1.toUtf8)(input); +exports.toUtf8 = toUtf8; diff --git a/claude-code-source/node_modules/@aws-sdk/util-utf8-browser/dist-cjs/pureJs.js b/claude-code-source/node_modules/@aws-sdk/util-utf8-browser/dist-cjs/pureJs.js new file mode 100644 index 00000000..0361b761 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/util-utf8-browser/dist-cjs/pureJs.js @@ -0,0 +1,47 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.toUtf8 = exports.fromUtf8 = void 0; +const fromUtf8 = (input) => { + const bytes = []; + for (let i = 0, len = input.length; i < len; i++) { + const value = input.charCodeAt(i); + if (value < 0x80) { + bytes.push(value); + } + else if (value < 0x800) { + bytes.push((value >> 6) | 0b11000000, (value & 0b111111) | 0b10000000); + } + else if (i + 1 < input.length && (value & 0xfc00) === 0xd800 && (input.charCodeAt(i + 1) & 0xfc00) === 0xdc00) { + const surrogatePair = 0x10000 + ((value & 0b1111111111) << 10) + (input.charCodeAt(++i) & 0b1111111111); + bytes.push((surrogatePair >> 18) | 0b11110000, ((surrogatePair >> 12) & 0b111111) | 0b10000000, ((surrogatePair >> 6) & 0b111111) | 0b10000000, (surrogatePair & 0b111111) | 0b10000000); + } + else { + bytes.push((value >> 12) | 0b11100000, ((value >> 6) & 0b111111) | 0b10000000, (value & 0b111111) | 0b10000000); + } + } + return Uint8Array.from(bytes); +}; +exports.fromUtf8 = fromUtf8; +const toUtf8 = (input) => { + let decoded = ""; + for (let i = 0, len = input.length; i < len; i++) { + const byte = input[i]; + if (byte < 0x80) { + decoded += String.fromCharCode(byte); + } + else if (0b11000000 <= byte && byte < 0b11100000) { + const nextByte = input[++i]; + decoded += String.fromCharCode(((byte & 0b11111) << 6) | (nextByte & 0b111111)); + } + else if (0b11110000 <= byte && byte < 0b101101101) { + const surrogatePair = [byte, input[++i], input[++i], input[++i]]; + const encoded = "%" + surrogatePair.map((byteValue) => byteValue.toString(16)).join("%"); + decoded += decodeURIComponent(encoded); + } + else { + decoded += String.fromCharCode(((byte & 0b1111) << 12) | ((input[++i] & 0b111111) << 6) | (input[++i] & 0b111111)); + } + } + return decoded; +}; +exports.toUtf8 = toUtf8; diff --git a/claude-code-source/node_modules/@aws-sdk/util-utf8-browser/dist-cjs/whatwgEncodingApi.js b/claude-code-source/node_modules/@aws-sdk/util-utf8-browser/dist-cjs/whatwgEncodingApi.js new file mode 100644 index 00000000..b17f4906 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/util-utf8-browser/dist-cjs/whatwgEncodingApi.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.toUtf8 = exports.fromUtf8 = void 0; +function fromUtf8(input) { + return new TextEncoder().encode(input); +} +exports.fromUtf8 = fromUtf8; +function toUtf8(input) { + return new TextDecoder("utf-8").decode(input); +} +exports.toUtf8 = toUtf8; diff --git a/claude-code-source/node_modules/@aws-sdk/xml-builder/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/xml-builder/dist-cjs/index.js new file mode 100644 index 00000000..c4f4bad4 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/xml-builder/dist-cjs/index.js @@ -0,0 +1,124 @@ +'use strict'; + +var xmlParser = require('./xml-parser'); + +function escapeAttribute(value) { + return value.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); +} + +function escapeElement(value) { + return value + .replace(/&/g, "&") + .replace(/"/g, """) + .replace(/'/g, "'") + .replace(//g, ">") + .replace(/\r/g, " ") + .replace(/\n/g, " ") + .replace(/\u0085/g, "…") + .replace(/\u2028/, "
"); +} + +class XmlText { + value; + constructor(value) { + this.value = value; + } + toString() { + return escapeElement("" + this.value); + } +} + +class XmlNode { + name; + children; + attributes = {}; + static of(name, childText, withName) { + const node = new XmlNode(name); + if (childText !== undefined) { + node.addChildNode(new XmlText(childText)); + } + if (withName !== undefined) { + node.withName(withName); + } + return node; + } + constructor(name, children = []) { + this.name = name; + this.children = children; + } + withName(name) { + this.name = name; + return this; + } + addAttribute(name, value) { + this.attributes[name] = value; + return this; + } + addChildNode(child) { + this.children.push(child); + return this; + } + removeAttribute(name) { + delete this.attributes[name]; + return this; + } + n(name) { + this.name = name; + return this; + } + c(child) { + this.children.push(child); + return this; + } + a(name, value) { + if (value != null) { + this.attributes[name] = value; + } + return this; + } + cc(input, field, withName = field) { + if (input[field] != null) { + const node = XmlNode.of(field, input[field]).withName(withName); + this.c(node); + } + } + l(input, listName, memberName, valueProvider) { + if (input[listName] != null) { + const nodes = valueProvider(); + nodes.map((node) => { + node.withName(memberName); + this.c(node); + }); + } + } + lc(input, listName, memberName, valueProvider) { + if (input[listName] != null) { + const nodes = valueProvider(); + const containerNode = new XmlNode(memberName); + nodes.map((node) => { + containerNode.c(node); + }); + this.c(containerNode); + } + } + toString() { + const hasChildren = Boolean(this.children.length); + let xmlText = `<${this.name}`; + const attributes = this.attributes; + for (const attributeName of Object.keys(attributes)) { + const attribute = attributes[attributeName]; + if (attribute != null) { + xmlText += ` ${attributeName}="${escapeAttribute("" + attribute)}"`; + } + } + return (xmlText += !hasChildren ? "/>" : `>${this.children.map((c) => c.toString()).join("")}`); + } +} + +Object.defineProperty(exports, "parseXML", { + enumerable: true, + get: function () { return xmlParser.parseXML; } +}); +exports.XmlNode = XmlNode; +exports.XmlText = XmlText; diff --git a/claude-code-source/node_modules/@aws-sdk/xml-builder/dist-cjs/xml-parser.js b/claude-code-source/node_modules/@aws-sdk/xml-builder/dist-cjs/xml-parser.js new file mode 100644 index 00000000..e6866350 --- /dev/null +++ b/claude-code-source/node_modules/@aws-sdk/xml-builder/dist-cjs/xml-parser.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseXML = parseXML; +const fast_xml_parser_1 = require("fast-xml-parser"); +const parser = new fast_xml_parser_1.XMLParser({ + attributeNamePrefix: "", + htmlEntities: true, + ignoreAttributes: false, + ignoreDeclaration: true, + parseTagValue: false, + trimValues: false, + tagValueProcessor: (_, val) => (val.trim() === "" && val.includes("\n") ? "" : undefined), +}); +parser.addEntity("#xD", "\r"); +parser.addEntity("#10", "\n"); +function parseXML(xmlString) { + return parser.parse(xmlString, true); +} diff --git a/claude-code-source/node_modules/@azure/abort-controller/dist/esm/AbortError.js b/claude-code-source/node_modules/@azure/abort-controller/dist/esm/AbortError.js new file mode 100644 index 00000000..3ae9745c --- /dev/null +++ b/claude-code-source/node_modules/@azure/abort-controller/dist/esm/AbortError.js @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * This error is thrown when an asynchronous operation has been aborted. + * Check for this error by testing the `name` that the name property of the + * error matches `"AbortError"`. + * + * @example + * ```ts + * const controller = new AbortController(); + * controller.abort(); + * try { + * doAsyncWork(controller.signal) + * } catch (e) { + * if (e.name === 'AbortError') { + * // handle abort error here. + * } + * } + * ``` + */ +export class AbortError extends Error { + constructor(message) { + super(message); + this.name = "AbortError"; + } +} +//# sourceMappingURL=AbortError.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/abort-controller/dist/esm/index.js b/claude-code-source/node_modules/@azure/abort-controller/dist/esm/index.js new file mode 100644 index 00000000..68c507cd --- /dev/null +++ b/claude-code-source/node_modules/@azure/abort-controller/dist/esm/index.js @@ -0,0 +1,4 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +export { AbortError } from "./AbortError.js"; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-client/dist/commonjs/state.js b/claude-code-source/node_modules/@azure/core-client/dist/commonjs/state.js new file mode 100644 index 00000000..b9e48ae3 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-client/dist/commonjs/state.js @@ -0,0 +1,12 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.state = void 0; +/** + * Holds the singleton operationRequestMap, to be shared across CJS and ESM imports. + */ +exports.state = { + operationRequestMap: new WeakMap(), +}; +//# sourceMappingURL=state-cjs.cjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-client/dist/esm/deserializationPolicy.js b/claude-code-source/node_modules/@azure/core-client/dist/esm/deserializationPolicy.js new file mode 100644 index 00000000..97e36024 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-client/dist/esm/deserializationPolicy.js @@ -0,0 +1,233 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { XML_CHARKEY } from "./interfaces.js"; +import { RestError } from "@azure/core-rest-pipeline"; +import { MapperTypeNames } from "./serializer.js"; +import { getOperationRequestInfo } from "./operationHelpers.js"; +const defaultJsonContentTypes = ["application/json", "text/json"]; +const defaultXmlContentTypes = ["application/xml", "application/atom+xml"]; +/** + * The programmatic identifier of the deserializationPolicy. + */ +export const deserializationPolicyName = "deserializationPolicy"; +/** + * This policy handles parsing out responses according to OperationSpecs on the request. + */ +export function deserializationPolicy(options = {}) { + var _a, _b, _c, _d, _e, _f, _g; + const jsonContentTypes = (_b = (_a = options.expectedContentTypes) === null || _a === void 0 ? void 0 : _a.json) !== null && _b !== void 0 ? _b : defaultJsonContentTypes; + const xmlContentTypes = (_d = (_c = options.expectedContentTypes) === null || _c === void 0 ? void 0 : _c.xml) !== null && _d !== void 0 ? _d : defaultXmlContentTypes; + const parseXML = options.parseXML; + const serializerOptions = options.serializerOptions; + const updatedOptions = { + xml: { + rootName: (_e = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.rootName) !== null && _e !== void 0 ? _e : "", + includeRoot: (_f = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.includeRoot) !== null && _f !== void 0 ? _f : false, + xmlCharKey: (_g = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.xmlCharKey) !== null && _g !== void 0 ? _g : XML_CHARKEY, + }, + }; + return { + name: deserializationPolicyName, + async sendRequest(request, next) { + const response = await next(request); + return deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, updatedOptions, parseXML); + }, + }; +} +function getOperationResponseMap(parsedResponse) { + let result; + const request = parsedResponse.request; + const operationInfo = getOperationRequestInfo(request); + const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec; + if (operationSpec) { + if (!(operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationResponseGetter)) { + result = operationSpec.responses[parsedResponse.status]; + } + else { + result = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationResponseGetter(operationSpec, parsedResponse); + } + } + return result; +} +function shouldDeserializeResponse(parsedResponse) { + const request = parsedResponse.request; + const operationInfo = getOperationRequestInfo(request); + const shouldDeserialize = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.shouldDeserialize; + let result; + if (shouldDeserialize === undefined) { + result = true; + } + else if (typeof shouldDeserialize === "boolean") { + result = shouldDeserialize; + } + else { + result = shouldDeserialize(parsedResponse); + } + return result; +} +async function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, options, parseXML) { + const parsedResponse = await parse(jsonContentTypes, xmlContentTypes, response, options, parseXML); + if (!shouldDeserializeResponse(parsedResponse)) { + return parsedResponse; + } + const operationInfo = getOperationRequestInfo(parsedResponse.request); + const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec; + if (!operationSpec || !operationSpec.responses) { + return parsedResponse; + } + const responseSpec = getOperationResponseMap(parsedResponse); + const { error, shouldReturnResponse } = handleErrorResponse(parsedResponse, operationSpec, responseSpec, options); + if (error) { + throw error; + } + else if (shouldReturnResponse) { + return parsedResponse; + } + // An operation response spec does exist for current status code, so + // use it to deserialize the response. + if (responseSpec) { + if (responseSpec.bodyMapper) { + let valueToDeserialize = parsedResponse.parsedBody; + if (operationSpec.isXML && responseSpec.bodyMapper.type.name === MapperTypeNames.Sequence) { + valueToDeserialize = + typeof valueToDeserialize === "object" + ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName] + : []; + } + try { + parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody", options); + } + catch (deserializeError) { + const restError = new RestError(`Error ${deserializeError} occurred in deserializing the responseBody - ${parsedResponse.bodyAsText}`, { + statusCode: parsedResponse.status, + request: parsedResponse.request, + response: parsedResponse, + }); + throw restError; + } + } + else if (operationSpec.httpMethod === "HEAD") { + // head methods never have a body, but we return a boolean to indicate presence/absence of the resource + parsedResponse.parsedBody = response.status >= 200 && response.status < 300; + } + if (responseSpec.headersMapper) { + parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.toJSON(), "operationRes.parsedHeaders", { xml: {}, ignoreUnknownProperties: true }); + } + } + return parsedResponse; +} +function isOperationSpecEmpty(operationSpec) { + const expectedStatusCodes = Object.keys(operationSpec.responses); + return (expectedStatusCodes.length === 0 || + (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default")); +} +function handleErrorResponse(parsedResponse, operationSpec, responseSpec, options) { + var _a, _b, _c, _d, _e; + const isSuccessByStatus = 200 <= parsedResponse.status && parsedResponse.status < 300; + const isExpectedStatusCode = isOperationSpecEmpty(operationSpec) + ? isSuccessByStatus + : !!responseSpec; + if (isExpectedStatusCode) { + if (responseSpec) { + if (!responseSpec.isError) { + return { error: null, shouldReturnResponse: false }; + } + } + else { + return { error: null, shouldReturnResponse: false }; + } + } + const errorResponseSpec = responseSpec !== null && responseSpec !== void 0 ? responseSpec : operationSpec.responses.default; + const initialErrorMessage = ((_a = parsedResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(parsedResponse.status)) + ? `Unexpected status code: ${parsedResponse.status}` + : parsedResponse.bodyAsText; + const error = new RestError(initialErrorMessage, { + statusCode: parsedResponse.status, + request: parsedResponse.request, + response: parsedResponse, + }); + // If the item failed but there's no error spec or default spec to deserialize the error, + // and the parsed body doesn't look like an error object, + // we should fail so we just throw the parsed response + if (!errorResponseSpec && + !(((_c = (_b = parsedResponse.parsedBody) === null || _b === void 0 ? void 0 : _b.error) === null || _c === void 0 ? void 0 : _c.code) && ((_e = (_d = parsedResponse.parsedBody) === null || _d === void 0 ? void 0 : _d.error) === null || _e === void 0 ? void 0 : _e.message))) { + throw error; + } + const defaultBodyMapper = errorResponseSpec === null || errorResponseSpec === void 0 ? void 0 : errorResponseSpec.bodyMapper; + const defaultHeadersMapper = errorResponseSpec === null || errorResponseSpec === void 0 ? void 0 : errorResponseSpec.headersMapper; + try { + // If error response has a body, try to deserialize it using default body mapper. + // Then try to extract error code & message from it + if (parsedResponse.parsedBody) { + const parsedBody = parsedResponse.parsedBody; + let deserializedError; + if (defaultBodyMapper) { + let valueToDeserialize = parsedBody; + if (operationSpec.isXML && defaultBodyMapper.type.name === MapperTypeNames.Sequence) { + valueToDeserialize = []; + const elementName = defaultBodyMapper.xmlElementName; + if (typeof parsedBody === "object" && elementName) { + valueToDeserialize = parsedBody[elementName]; + } + } + deserializedError = operationSpec.serializer.deserialize(defaultBodyMapper, valueToDeserialize, "error.response.parsedBody", options); + } + const internalError = parsedBody.error || deserializedError || parsedBody; + error.code = internalError.code; + if (internalError.message) { + error.message = internalError.message; + } + if (defaultBodyMapper) { + error.response.parsedBody = deserializedError; + } + } + // If error response has headers, try to deserialize it using default header mapper + if (parsedResponse.headers && defaultHeadersMapper) { + error.response.parsedHeaders = + operationSpec.serializer.deserialize(defaultHeadersMapper, parsedResponse.headers.toJSON(), "operationRes.parsedHeaders"); + } + } + catch (defaultError) { + error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody - "${parsedResponse.bodyAsText}" for the default response.`; + } + return { error, shouldReturnResponse: false }; +} +async function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts, parseXML) { + var _a; + if (!((_a = operationResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(operationResponse.status)) && + operationResponse.bodyAsText) { + const text = operationResponse.bodyAsText; + const contentType = operationResponse.headers.get("Content-Type") || ""; + const contentComponents = !contentType + ? [] + : contentType.split(";").map((component) => component.toLowerCase()); + try { + if (contentComponents.length === 0 || + contentComponents.some((component) => jsonContentTypes.indexOf(component) !== -1)) { + operationResponse.parsedBody = JSON.parse(text); + return operationResponse; + } + else if (contentComponents.some((component) => xmlContentTypes.indexOf(component) !== -1)) { + if (!parseXML) { + throw new Error("Parsing XML not supported."); + } + const body = await parseXML(text, opts.xml); + operationResponse.parsedBody = body; + return operationResponse; + } + } + catch (err) { + const msg = `Error "${err}" occurred while parsing the response body - ${operationResponse.bodyAsText}.`; + const errCode = err.code || RestError.PARSE_ERROR; + const e = new RestError(msg, { + code: errCode, + statusCode: operationResponse.status, + request: operationResponse.request, + response: operationResponse, + }); + throw e; + } + } + return operationResponse; +} +//# sourceMappingURL=deserializationPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-client/dist/esm/httpClientCache.js b/claude-code-source/node_modules/@azure/core-client/dist/esm/httpClientCache.js new file mode 100644 index 00000000..ff112d09 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-client/dist/esm/httpClientCache.js @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { createDefaultHttpClient } from "@azure/core-rest-pipeline"; +let cachedHttpClient; +export function getCachedDefaultHttpClient() { + if (!cachedHttpClient) { + cachedHttpClient = createDefaultHttpClient(); + } + return cachedHttpClient; +} +//# sourceMappingURL=httpClientCache.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-client/dist/esm/index.js b/claude-code-source/node_modules/@azure/core-client/dist/esm/index.js new file mode 100644 index 00000000..128a2a37 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-client/dist/esm/index.js @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +export { createSerializer, MapperTypeNames } from "./serializer.js"; +export { ServiceClient } from "./serviceClient.js"; +export { createClientPipeline } from "./pipeline.js"; +export { XML_ATTRKEY, XML_CHARKEY, } from "./interfaces.js"; +export { deserializationPolicy, deserializationPolicyName, } from "./deserializationPolicy.js"; +export { serializationPolicy, serializationPolicyName, } from "./serializationPolicy.js"; +export { authorizeRequestOnClaimChallenge } from "./authorizeRequestOnClaimChallenge.js"; +export { authorizeRequestOnTenantChallenge } from "./authorizeRequestOnTenantChallenge.js"; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-client/dist/esm/interfaceHelpers.js b/claude-code-source/node_modules/@azure/core-client/dist/esm/interfaceHelpers.js new file mode 100644 index 00000000..ba232f86 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-client/dist/esm/interfaceHelpers.js @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { MapperTypeNames } from "./serializer.js"; +/** + * Gets the list of status codes for streaming responses. + * @internal + */ +export function getStreamingResponseStatusCodes(operationSpec) { + const result = new Set(); + for (const statusCode in operationSpec.responses) { + const operationResponse = operationSpec.responses[statusCode]; + if (operationResponse.bodyMapper && + operationResponse.bodyMapper.type.name === MapperTypeNames.Stream) { + result.add(Number(statusCode)); + } + } + return result; +} +/** + * Get the path to this parameter's value as a dotted string (a.b.c). + * @param parameter - The parameter to get the path string for. + * @returns The path to this parameter's value as a dotted string. + * @internal + */ +export function getPathStringFromParameter(parameter) { + const { parameterPath, mapper } = parameter; + let result; + if (typeof parameterPath === "string") { + result = parameterPath; + } + else if (Array.isArray(parameterPath)) { + result = parameterPath.join("."); + } + else { + result = mapper.serializedName; + } + return result; +} +//# sourceMappingURL=interfaceHelpers.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-client/dist/esm/interfaces.js b/claude-code-source/node_modules/@azure/core-client/dist/esm/interfaces.js new file mode 100644 index 00000000..da2b4255 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-client/dist/esm/interfaces.js @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +/** + * Default key used to access the XML attributes. + */ +export const XML_ATTRKEY = "$"; +/** + * Default key used to access the XML value content. + */ +export const XML_CHARKEY = "_"; +//# sourceMappingURL=interfaces.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-client/dist/esm/log.js b/claude-code-source/node_modules/@azure/core-client/dist/esm/log.js new file mode 100644 index 00000000..98be3c8e --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-client/dist/esm/log.js @@ -0,0 +1,5 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { createClientLogger } from "@azure/logger"; +export const logger = createClientLogger("core-client"); +//# sourceMappingURL=log.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-client/dist/esm/operationHelpers.js b/claude-code-source/node_modules/@azure/core-client/dist/esm/operationHelpers.js new file mode 100644 index 00000000..b69e1820 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-client/dist/esm/operationHelpers.js @@ -0,0 +1,94 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { state } from "./state.js"; +/** + * @internal + * Retrieves the value to use for a given operation argument + * @param operationArguments - The arguments passed from the generated client + * @param parameter - The parameter description + * @param fallbackObject - If something isn't found in the arguments bag, look here. + * Generally used to look at the service client properties. + */ +export function getOperationArgumentValueFromParameter(operationArguments, parameter, fallbackObject) { + let parameterPath = parameter.parameterPath; + const parameterMapper = parameter.mapper; + let value; + if (typeof parameterPath === "string") { + parameterPath = [parameterPath]; + } + if (Array.isArray(parameterPath)) { + if (parameterPath.length > 0) { + if (parameterMapper.isConstant) { + value = parameterMapper.defaultValue; + } + else { + let propertySearchResult = getPropertyFromParameterPath(operationArguments, parameterPath); + if (!propertySearchResult.propertyFound && fallbackObject) { + propertySearchResult = getPropertyFromParameterPath(fallbackObject, parameterPath); + } + let useDefaultValue = false; + if (!propertySearchResult.propertyFound) { + useDefaultValue = + parameterMapper.required || + (parameterPath[0] === "options" && parameterPath.length === 2); + } + value = useDefaultValue ? parameterMapper.defaultValue : propertySearchResult.propertyValue; + } + } + } + else { + if (parameterMapper.required) { + value = {}; + } + for (const propertyName in parameterPath) { + const propertyMapper = parameterMapper.type.modelProperties[propertyName]; + const propertyPath = parameterPath[propertyName]; + const propertyValue = getOperationArgumentValueFromParameter(operationArguments, { + parameterPath: propertyPath, + mapper: propertyMapper, + }, fallbackObject); + if (propertyValue !== undefined) { + if (!value) { + value = {}; + } + value[propertyName] = propertyValue; + } + } + } + return value; +} +function getPropertyFromParameterPath(parent, parameterPath) { + const result = { propertyFound: false }; + let i = 0; + for (; i < parameterPath.length; ++i) { + const parameterPathPart = parameterPath[i]; + // Make sure to check inherited properties too, so don't use hasOwnProperty(). + if (parent && parameterPathPart in parent) { + parent = parent[parameterPathPart]; + } + else { + break; + } + } + if (i === parameterPath.length) { + result.propertyValue = parent; + result.propertyFound = true; + } + return result; +} +const originalRequestSymbol = Symbol.for("@azure/core-client original request"); +function hasOriginalRequest(request) { + return originalRequestSymbol in request; +} +export function getOperationRequestInfo(request) { + if (hasOriginalRequest(request)) { + return getOperationRequestInfo(request[originalRequestSymbol]); + } + let info = state.operationRequestMap.get(request); + if (!info) { + info = {}; + state.operationRequestMap.set(request, info); + } + return info; +} +//# sourceMappingURL=operationHelpers.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-client/dist/esm/pipeline.js b/claude-code-source/node_modules/@azure/core-client/dist/esm/pipeline.js new file mode 100644 index 00000000..dba25033 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-client/dist/esm/pipeline.js @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { deserializationPolicy } from "./deserializationPolicy.js"; +import { bearerTokenAuthenticationPolicy, createPipelineFromOptions, } from "@azure/core-rest-pipeline"; +import { serializationPolicy } from "./serializationPolicy.js"; +/** + * Creates a new Pipeline for use with a Service Client. + * Adds in deserializationPolicy by default. + * Also adds in bearerTokenAuthenticationPolicy if passed a TokenCredential. + * @param options - Options to customize the created pipeline. + */ +export function createClientPipeline(options = {}) { + const pipeline = createPipelineFromOptions(options !== null && options !== void 0 ? options : {}); + if (options.credentialOptions) { + pipeline.addPolicy(bearerTokenAuthenticationPolicy({ + credential: options.credentialOptions.credential, + scopes: options.credentialOptions.credentialScopes, + })); + } + pipeline.addPolicy(serializationPolicy(options.serializationOptions), { phase: "Serialize" }); + pipeline.addPolicy(deserializationPolicy(options.deserializationOptions), { + phase: "Deserialize", + }); + return pipeline; +} +//# sourceMappingURL=pipeline.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-client/dist/esm/serializationPolicy.js b/claude-code-source/node_modules/@azure/core-client/dist/esm/serializationPolicy.js new file mode 100644 index 00000000..cb8e6ac7 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-client/dist/esm/serializationPolicy.js @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { XML_ATTRKEY, XML_CHARKEY } from "./interfaces.js"; +import { getOperationArgumentValueFromParameter, getOperationRequestInfo, } from "./operationHelpers.js"; +import { MapperTypeNames } from "./serializer.js"; +import { getPathStringFromParameter } from "./interfaceHelpers.js"; +/** + * The programmatic identifier of the serializationPolicy. + */ +export const serializationPolicyName = "serializationPolicy"; +/** + * This policy handles assembling the request body and headers using + * an OperationSpec and OperationArguments on the request. + */ +export function serializationPolicy(options = {}) { + const stringifyXML = options.stringifyXML; + return { + name: serializationPolicyName, + async sendRequest(request, next) { + const operationInfo = getOperationRequestInfo(request); + const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec; + const operationArguments = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationArguments; + if (operationSpec && operationArguments) { + serializeHeaders(request, operationArguments, operationSpec); + serializeRequestBody(request, operationArguments, operationSpec, stringifyXML); + } + return next(request); + }, + }; +} +/** + * @internal + */ +export function serializeHeaders(request, operationArguments, operationSpec) { + var _a, _b; + if (operationSpec.headerParameters) { + for (const headerParameter of operationSpec.headerParameters) { + let headerValue = getOperationArgumentValueFromParameter(operationArguments, headerParameter); + if ((headerValue !== null && headerValue !== undefined) || headerParameter.mapper.required) { + headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, getPathStringFromParameter(headerParameter)); + const headerCollectionPrefix = headerParameter.mapper + .headerCollectionPrefix; + if (headerCollectionPrefix) { + for (const key of Object.keys(headerValue)) { + request.headers.set(headerCollectionPrefix + key, headerValue[key]); + } + } + else { + request.headers.set(headerParameter.mapper.serializedName || getPathStringFromParameter(headerParameter), headerValue); + } + } + } + } + const customHeaders = (_b = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.requestOptions) === null || _b === void 0 ? void 0 : _b.customHeaders; + if (customHeaders) { + for (const customHeaderName of Object.keys(customHeaders)) { + request.headers.set(customHeaderName, customHeaders[customHeaderName]); + } + } +} +/** + * @internal + */ +export function serializeRequestBody(request, operationArguments, operationSpec, stringifyXML = function () { + throw new Error("XML serialization unsupported!"); +}) { + var _a, _b, _c, _d, _e; + const serializerOptions = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions; + const updatedOptions = { + xml: { + rootName: (_b = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.rootName) !== null && _b !== void 0 ? _b : "", + includeRoot: (_c = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.includeRoot) !== null && _c !== void 0 ? _c : false, + xmlCharKey: (_d = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.xmlCharKey) !== null && _d !== void 0 ? _d : XML_CHARKEY, + }, + }; + const xmlCharKey = updatedOptions.xml.xmlCharKey; + if (operationSpec.requestBody && operationSpec.requestBody.mapper) { + request.body = getOperationArgumentValueFromParameter(operationArguments, operationSpec.requestBody); + const bodyMapper = operationSpec.requestBody.mapper; + const { required, serializedName, xmlName, xmlElementName, xmlNamespace, xmlNamespacePrefix, nullable, } = bodyMapper; + const typeName = bodyMapper.type.name; + try { + if ((request.body !== undefined && request.body !== null) || + (nullable && request.body === null) || + required) { + const requestBodyParameterPathString = getPathStringFromParameter(operationSpec.requestBody); + request.body = operationSpec.serializer.serialize(bodyMapper, request.body, requestBodyParameterPathString, updatedOptions); + const isStream = typeName === MapperTypeNames.Stream; + if (operationSpec.isXML) { + const xmlnsKey = xmlNamespacePrefix ? `xmlns:${xmlNamespacePrefix}` : "xmlns"; + const value = getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, request.body, updatedOptions); + if (typeName === MapperTypeNames.Sequence) { + request.body = stringifyXML(prepareXMLRootList(value, xmlElementName || xmlName || serializedName, xmlnsKey, xmlNamespace), { rootName: xmlName || serializedName, xmlCharKey }); + } + else if (!isStream) { + request.body = stringifyXML(value, { + rootName: xmlName || serializedName, + xmlCharKey, + }); + } + } + else if (typeName === MapperTypeNames.String && + (((_e = operationSpec.contentType) === null || _e === void 0 ? void 0 : _e.match("text/plain")) || operationSpec.mediaType === "text")) { + // the String serializer has validated that request body is a string + // so just send the string. + return; + } + else if (!isStream) { + request.body = JSON.stringify(request.body); + } + } + } + catch (error) { + throw new Error(`Error "${error.message}" occurred in serializing the payload - ${JSON.stringify(serializedName, undefined, " ")}.`); + } + } + else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) { + request.formData = {}; + for (const formDataParameter of operationSpec.formDataParameters) { + const formDataParameterValue = getOperationArgumentValueFromParameter(operationArguments, formDataParameter); + if (formDataParameterValue !== undefined && formDataParameterValue !== null) { + const formDataParameterPropertyName = formDataParameter.mapper.serializedName || getPathStringFromParameter(formDataParameter); + request.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, getPathStringFromParameter(formDataParameter), updatedOptions); + } + } + } +} +/** + * Adds an xml namespace to the xml serialized object if needed, otherwise it just returns the value itself + */ +function getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, serializedValue, options) { + // Composite and Sequence schemas already got their root namespace set during serialization + // We just need to add xmlns to the other schema types + if (xmlNamespace && !["Composite", "Sequence", "Dictionary"].includes(typeName)) { + const result = {}; + result[options.xml.xmlCharKey] = serializedValue; + result[XML_ATTRKEY] = { [xmlnsKey]: xmlNamespace }; + return result; + } + return serializedValue; +} +function prepareXMLRootList(obj, elementName, xmlNamespaceKey, xmlNamespace) { + if (!Array.isArray(obj)) { + obj = [obj]; + } + if (!xmlNamespaceKey || !xmlNamespace) { + return { [elementName]: obj }; + } + const result = { [elementName]: obj }; + result[XML_ATTRKEY] = { [xmlNamespaceKey]: xmlNamespace }; + return result; +} +//# sourceMappingURL=serializationPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-client/dist/esm/serializer.js b/claude-code-source/node_modules/@azure/core-client/dist/esm/serializer.js new file mode 100644 index 00000000..76add4cf --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-client/dist/esm/serializer.js @@ -0,0 +1,922 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import * as base64 from "./base64.js"; +import { XML_ATTRKEY, XML_CHARKEY } from "./interfaces.js"; +import { isDuration, isValidUuid } from "./utils.js"; +class SerializerImpl { + constructor(modelMappers = {}, isXML = false) { + this.modelMappers = modelMappers; + this.isXML = isXML; + } + /** + * @deprecated Removing the constraints validation on client side. + */ + validateConstraints(mapper, value, objectName) { + const failValidation = (constraintName, constraintValue) => { + throw new Error(`"${objectName}" with value "${value}" should satisfy the constraint "${constraintName}": ${constraintValue}.`); + }; + if (mapper.constraints && value !== undefined && value !== null) { + const { ExclusiveMaximum, ExclusiveMinimum, InclusiveMaximum, InclusiveMinimum, MaxItems, MaxLength, MinItems, MinLength, MultipleOf, Pattern, UniqueItems, } = mapper.constraints; + if (ExclusiveMaximum !== undefined && value >= ExclusiveMaximum) { + failValidation("ExclusiveMaximum", ExclusiveMaximum); + } + if (ExclusiveMinimum !== undefined && value <= ExclusiveMinimum) { + failValidation("ExclusiveMinimum", ExclusiveMinimum); + } + if (InclusiveMaximum !== undefined && value > InclusiveMaximum) { + failValidation("InclusiveMaximum", InclusiveMaximum); + } + if (InclusiveMinimum !== undefined && value < InclusiveMinimum) { + failValidation("InclusiveMinimum", InclusiveMinimum); + } + if (MaxItems !== undefined && value.length > MaxItems) { + failValidation("MaxItems", MaxItems); + } + if (MaxLength !== undefined && value.length > MaxLength) { + failValidation("MaxLength", MaxLength); + } + if (MinItems !== undefined && value.length < MinItems) { + failValidation("MinItems", MinItems); + } + if (MinLength !== undefined && value.length < MinLength) { + failValidation("MinLength", MinLength); + } + if (MultipleOf !== undefined && value % MultipleOf !== 0) { + failValidation("MultipleOf", MultipleOf); + } + if (Pattern) { + const pattern = typeof Pattern === "string" ? new RegExp(Pattern) : Pattern; + if (typeof value !== "string" || value.match(pattern) === null) { + failValidation("Pattern", Pattern); + } + } + if (UniqueItems && + value.some((item, i, ar) => ar.indexOf(item) !== i)) { + failValidation("UniqueItems", UniqueItems); + } + } + } + /** + * Serialize the given object based on its metadata defined in the mapper + * + * @param mapper - The mapper which defines the metadata of the serializable object + * + * @param object - A valid Javascript object to be serialized + * + * @param objectName - Name of the serialized object + * + * @param options - additional options to serialization + * + * @returns A valid serialized Javascript object + */ + serialize(mapper, object, objectName, options = { xml: {} }) { + var _a, _b, _c; + const updatedOptions = { + xml: { + rootName: (_a = options.xml.rootName) !== null && _a !== void 0 ? _a : "", + includeRoot: (_b = options.xml.includeRoot) !== null && _b !== void 0 ? _b : false, + xmlCharKey: (_c = options.xml.xmlCharKey) !== null && _c !== void 0 ? _c : XML_CHARKEY, + }, + }; + let payload = {}; + const mapperType = mapper.type.name; + if (!objectName) { + objectName = mapper.serializedName; + } + if (mapperType.match(/^Sequence$/i) !== null) { + payload = []; + } + if (mapper.isConstant) { + object = mapper.defaultValue; + } + // This table of allowed values should help explain + // the mapper.required and mapper.nullable properties. + // X means "neither undefined or null are allowed". + // || required + // || true | false + // nullable || ========================== + // true || null | undefined/null + // false || X | undefined + // undefined || X | undefined/null + const { required, nullable } = mapper; + if (required && nullable && object === undefined) { + throw new Error(`${objectName} cannot be undefined.`); + } + if (required && !nullable && (object === undefined || object === null)) { + throw new Error(`${objectName} cannot be null or undefined.`); + } + if (!required && nullable === false && object === null) { + throw new Error(`${objectName} cannot be null.`); + } + if (object === undefined || object === null) { + payload = object; + } + else { + if (mapperType.match(/^any$/i) !== null) { + payload = object; + } + else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/i) !== null) { + payload = serializeBasicTypes(mapperType, objectName, object); + } + else if (mapperType.match(/^Enum$/i) !== null) { + const enumMapper = mapper; + payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object); + } + else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/i) !== null) { + payload = serializeDateTypes(mapperType, object, objectName); + } + else if (mapperType.match(/^ByteArray$/i) !== null) { + payload = serializeByteArrayType(objectName, object); + } + else if (mapperType.match(/^Base64Url$/i) !== null) { + payload = serializeBase64UrlType(objectName, object); + } + else if (mapperType.match(/^Sequence$/i) !== null) { + payload = serializeSequenceType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); + } + else if (mapperType.match(/^Dictionary$/i) !== null) { + payload = serializeDictionaryType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); + } + else if (mapperType.match(/^Composite$/i) !== null) { + payload = serializeCompositeType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); + } + } + return payload; + } + /** + * Deserialize the given object based on its metadata defined in the mapper + * + * @param mapper - The mapper which defines the metadata of the serializable object + * + * @param responseBody - A valid Javascript entity to be deserialized + * + * @param objectName - Name of the deserialized object + * + * @param options - Controls behavior of XML parser and builder. + * + * @returns A valid deserialized Javascript object + */ + deserialize(mapper, responseBody, objectName, options = { xml: {} }) { + var _a, _b, _c, _d; + const updatedOptions = { + xml: { + rootName: (_a = options.xml.rootName) !== null && _a !== void 0 ? _a : "", + includeRoot: (_b = options.xml.includeRoot) !== null && _b !== void 0 ? _b : false, + xmlCharKey: (_c = options.xml.xmlCharKey) !== null && _c !== void 0 ? _c : XML_CHARKEY, + }, + ignoreUnknownProperties: (_d = options.ignoreUnknownProperties) !== null && _d !== void 0 ? _d : false, + }; + if (responseBody === undefined || responseBody === null) { + if (this.isXML && mapper.type.name === "Sequence" && !mapper.xmlIsWrapped) { + // Edge case for empty XML non-wrapped lists. xml2js can't distinguish + // between the list being empty versus being missing, + // so let's do the more user-friendly thing and return an empty list. + responseBody = []; + } + // specifically check for undefined as default value can be a falsey value `0, "", false, null` + if (mapper.defaultValue !== undefined) { + responseBody = mapper.defaultValue; + } + return responseBody; + } + let payload; + const mapperType = mapper.type.name; + if (!objectName) { + objectName = mapper.serializedName; + } + if (mapperType.match(/^Composite$/i) !== null) { + payload = deserializeCompositeType(this, mapper, responseBody, objectName, updatedOptions); + } + else { + if (this.isXML) { + const xmlCharKey = updatedOptions.xml.xmlCharKey; + /** + * If the mapper specifies this as a non-composite type value but the responseBody contains + * both header ("$" i.e., XML_ATTRKEY) and body ("#" i.e., XML_CHARKEY) properties, + * then just reduce the responseBody value to the body ("#" i.e., XML_CHARKEY) property. + */ + if (responseBody[XML_ATTRKEY] !== undefined && responseBody[xmlCharKey] !== undefined) { + responseBody = responseBody[xmlCharKey]; + } + } + if (mapperType.match(/^Number$/i) !== null) { + payload = parseFloat(responseBody); + if (isNaN(payload)) { + payload = responseBody; + } + } + else if (mapperType.match(/^Boolean$/i) !== null) { + if (responseBody === "true") { + payload = true; + } + else if (responseBody === "false") { + payload = false; + } + else { + payload = responseBody; + } + } + else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/i) !== null) { + payload = responseBody; + } + else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/i) !== null) { + payload = new Date(responseBody); + } + else if (mapperType.match(/^UnixTime$/i) !== null) { + payload = unixTimeToDate(responseBody); + } + else if (mapperType.match(/^ByteArray$/i) !== null) { + payload = base64.decodeString(responseBody); + } + else if (mapperType.match(/^Base64Url$/i) !== null) { + payload = base64UrlToByteArray(responseBody); + } + else if (mapperType.match(/^Sequence$/i) !== null) { + payload = deserializeSequenceType(this, mapper, responseBody, objectName, updatedOptions); + } + else if (mapperType.match(/^Dictionary$/i) !== null) { + payload = deserializeDictionaryType(this, mapper, responseBody, objectName, updatedOptions); + } + } + if (mapper.isConstant) { + payload = mapper.defaultValue; + } + return payload; + } +} +/** + * Method that creates and returns a Serializer. + * @param modelMappers - Known models to map + * @param isXML - If XML should be supported + */ +export function createSerializer(modelMappers = {}, isXML = false) { + return new SerializerImpl(modelMappers, isXML); +} +function trimEnd(str, ch) { + let len = str.length; + while (len - 1 >= 0 && str[len - 1] === ch) { + --len; + } + return str.substr(0, len); +} +function bufferToBase64Url(buffer) { + if (!buffer) { + return undefined; + } + if (!(buffer instanceof Uint8Array)) { + throw new Error(`Please provide an input of type Uint8Array for converting to Base64Url.`); + } + // Uint8Array to Base64. + const str = base64.encodeByteArray(buffer); + // Base64 to Base64Url. + return trimEnd(str, "=").replace(/\+/g, "-").replace(/\//g, "_"); +} +function base64UrlToByteArray(str) { + if (!str) { + return undefined; + } + if (str && typeof str.valueOf() !== "string") { + throw new Error("Please provide an input of type string for converting to Uint8Array"); + } + // Base64Url to Base64. + str = str.replace(/-/g, "+").replace(/_/g, "/"); + // Base64 to Uint8Array. + return base64.decodeString(str); +} +function splitSerializeName(prop) { + const classes = []; + let partialclass = ""; + if (prop) { + const subwords = prop.split("."); + for (const item of subwords) { + if (item.charAt(item.length - 1) === "\\") { + partialclass += item.substr(0, item.length - 1) + "."; + } + else { + partialclass += item; + classes.push(partialclass); + partialclass = ""; + } + } + } + return classes; +} +function dateToUnixTime(d) { + if (!d) { + return undefined; + } + if (typeof d.valueOf() === "string") { + d = new Date(d); + } + return Math.floor(d.getTime() / 1000); +} +function unixTimeToDate(n) { + if (!n) { + return undefined; + } + return new Date(n * 1000); +} +function serializeBasicTypes(typeName, objectName, value) { + if (value !== null && value !== undefined) { + if (typeName.match(/^Number$/i) !== null) { + if (typeof value !== "number") { + throw new Error(`${objectName} with value ${value} must be of type number.`); + } + } + else if (typeName.match(/^String$/i) !== null) { + if (typeof value.valueOf() !== "string") { + throw new Error(`${objectName} with value "${value}" must be of type string.`); + } + } + else if (typeName.match(/^Uuid$/i) !== null) { + if (!(typeof value.valueOf() === "string" && isValidUuid(value))) { + throw new Error(`${objectName} with value "${value}" must be of type string and a valid uuid.`); + } + } + else if (typeName.match(/^Boolean$/i) !== null) { + if (typeof value !== "boolean") { + throw new Error(`${objectName} with value ${value} must be of type boolean.`); + } + } + else if (typeName.match(/^Stream$/i) !== null) { + const objectType = typeof value; + if (objectType !== "string" && + typeof value.pipe !== "function" && // NodeJS.ReadableStream + typeof value.tee !== "function" && // browser ReadableStream + !(value instanceof ArrayBuffer) && + !ArrayBuffer.isView(value) && + // File objects count as a type of Blob, so we want to use instanceof explicitly + !((typeof Blob === "function" || typeof Blob === "object") && value instanceof Blob) && + objectType !== "function") { + throw new Error(`${objectName} must be a string, Blob, ArrayBuffer, ArrayBufferView, ReadableStream, or () => ReadableStream.`); + } + } + } + return value; +} +function serializeEnumType(objectName, allowedValues, value) { + if (!allowedValues) { + throw new Error(`Please provide a set of allowedValues to validate ${objectName} as an Enum Type.`); + } + const isPresent = allowedValues.some((item) => { + if (typeof item.valueOf() === "string") { + return item.toLowerCase() === value.toLowerCase(); + } + return item === value; + }); + if (!isPresent) { + throw new Error(`${value} is not a valid value for ${objectName}. The valid values are: ${JSON.stringify(allowedValues)}.`); + } + return value; +} +function serializeByteArrayType(objectName, value) { + if (value !== undefined && value !== null) { + if (!(value instanceof Uint8Array)) { + throw new Error(`${objectName} must be of type Uint8Array.`); + } + value = base64.encodeByteArray(value); + } + return value; +} +function serializeBase64UrlType(objectName, value) { + if (value !== undefined && value !== null) { + if (!(value instanceof Uint8Array)) { + throw new Error(`${objectName} must be of type Uint8Array.`); + } + value = bufferToBase64Url(value); + } + return value; +} +function serializeDateTypes(typeName, value, objectName) { + if (value !== undefined && value !== null) { + if (typeName.match(/^Date$/i) !== null) { + if (!(value instanceof Date || + (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { + throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`); + } + value = + value instanceof Date + ? value.toISOString().substring(0, 10) + : new Date(value).toISOString().substring(0, 10); + } + else if (typeName.match(/^DateTime$/i) !== null) { + if (!(value instanceof Date || + (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { + throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`); + } + value = value instanceof Date ? value.toISOString() : new Date(value).toISOString(); + } + else if (typeName.match(/^DateTimeRfc1123$/i) !== null) { + if (!(value instanceof Date || + (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { + throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123 format.`); + } + value = value instanceof Date ? value.toUTCString() : new Date(value).toUTCString(); + } + else if (typeName.match(/^UnixTime$/i) !== null) { + if (!(value instanceof Date || + (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { + throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123/ISO8601 format ` + + `for it to be serialized in UnixTime/Epoch format.`); + } + value = dateToUnixTime(value); + } + else if (typeName.match(/^TimeSpan$/i) !== null) { + if (!isDuration(value)) { + throw new Error(`${objectName} must be a string in ISO 8601 format. Instead was "${value}".`); + } + } + } + return value; +} +function serializeSequenceType(serializer, mapper, object, objectName, isXml, options) { + var _a; + if (!Array.isArray(object)) { + throw new Error(`${objectName} must be of type Array.`); + } + let elementType = mapper.type.element; + if (!elementType || typeof elementType !== "object") { + throw new Error(`element" metadata for an Array must be defined in the ` + + `mapper and it must of type "object" in ${objectName}.`); + } + // Quirk: Composite mappers referenced by `element` might + // not have *all* properties declared (like uberParent), + // so let's try to look up the full definition by name. + if (elementType.type.name === "Composite" && elementType.type.className) { + elementType = (_a = serializer.modelMappers[elementType.type.className]) !== null && _a !== void 0 ? _a : elementType; + } + const tempArray = []; + for (let i = 0; i < object.length; i++) { + const serializedValue = serializer.serialize(elementType, object[i], objectName, options); + if (isXml && elementType.xmlNamespace) { + const xmlnsKey = elementType.xmlNamespacePrefix + ? `xmlns:${elementType.xmlNamespacePrefix}` + : "xmlns"; + if (elementType.type.name === "Composite") { + tempArray[i] = Object.assign({}, serializedValue); + tempArray[i][XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace }; + } + else { + tempArray[i] = {}; + tempArray[i][options.xml.xmlCharKey] = serializedValue; + tempArray[i][XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace }; + } + } + else { + tempArray[i] = serializedValue; + } + } + return tempArray; +} +function serializeDictionaryType(serializer, mapper, object, objectName, isXml, options) { + if (typeof object !== "object") { + throw new Error(`${objectName} must be of type object.`); + } + const valueType = mapper.type.value; + if (!valueType || typeof valueType !== "object") { + throw new Error(`"value" metadata for a Dictionary must be defined in the ` + + `mapper and it must of type "object" in ${objectName}.`); + } + const tempDictionary = {}; + for (const key of Object.keys(object)) { + const serializedValue = serializer.serialize(valueType, object[key], objectName, options); + // If the element needs an XML namespace we need to add it within the $ property + tempDictionary[key] = getXmlObjectValue(valueType, serializedValue, isXml, options); + } + // Add the namespace to the root element if needed + if (isXml && mapper.xmlNamespace) { + const xmlnsKey = mapper.xmlNamespacePrefix ? `xmlns:${mapper.xmlNamespacePrefix}` : "xmlns"; + const result = tempDictionary; + result[XML_ATTRKEY] = { [xmlnsKey]: mapper.xmlNamespace }; + return result; + } + return tempDictionary; +} +/** + * Resolves the additionalProperties property from a referenced mapper + * @param serializer - the serializer containing the entire set of mappers + * @param mapper - the composite mapper to resolve + * @param objectName - name of the object being serialized + */ +function resolveAdditionalProperties(serializer, mapper, objectName) { + const additionalProperties = mapper.type.additionalProperties; + if (!additionalProperties && mapper.type.className) { + const modelMapper = resolveReferencedMapper(serializer, mapper, objectName); + return modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.additionalProperties; + } + return additionalProperties; +} +/** + * Finds the mapper referenced by className + * @param serializer - the serializer containing the entire set of mappers + * @param mapper - the composite mapper to resolve + * @param objectName - name of the object being serialized + */ +function resolveReferencedMapper(serializer, mapper, objectName) { + const className = mapper.type.className; + if (!className) { + throw new Error(`Class name for model "${objectName}" is not provided in the mapper "${JSON.stringify(mapper, undefined, 2)}".`); + } + return serializer.modelMappers[className]; +} +/** + * Resolves a composite mapper's modelProperties. + * @param serializer - the serializer containing the entire set of mappers + * @param mapper - the composite mapper to resolve + */ +function resolveModelProperties(serializer, mapper, objectName) { + let modelProps = mapper.type.modelProperties; + if (!modelProps) { + const modelMapper = resolveReferencedMapper(serializer, mapper, objectName); + if (!modelMapper) { + throw new Error(`mapper() cannot be null or undefined for model "${mapper.type.className}".`); + } + modelProps = modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.modelProperties; + if (!modelProps) { + throw new Error(`modelProperties cannot be null or undefined in the ` + + `mapper "${JSON.stringify(modelMapper)}" of type "${mapper.type.className}" for object "${objectName}".`); + } + } + return modelProps; +} +function serializeCompositeType(serializer, mapper, object, objectName, isXml, options) { + if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) { + mapper = getPolymorphicMapper(serializer, mapper, object, "clientName"); + } + if (object !== undefined && object !== null) { + const payload = {}; + const modelProps = resolveModelProperties(serializer, mapper, objectName); + for (const key of Object.keys(modelProps)) { + const propertyMapper = modelProps[key]; + if (propertyMapper.readOnly) { + continue; + } + let propName; + let parentObject = payload; + if (serializer.isXML) { + if (propertyMapper.xmlIsWrapped) { + propName = propertyMapper.xmlName; + } + else { + propName = propertyMapper.xmlElementName || propertyMapper.xmlName; + } + } + else { + const paths = splitSerializeName(propertyMapper.serializedName); + propName = paths.pop(); + for (const pathName of paths) { + const childObject = parentObject[pathName]; + if ((childObject === undefined || childObject === null) && + ((object[key] !== undefined && object[key] !== null) || + propertyMapper.defaultValue !== undefined)) { + parentObject[pathName] = {}; + } + parentObject = parentObject[pathName]; + } + } + if (parentObject !== undefined && parentObject !== null) { + if (isXml && mapper.xmlNamespace) { + const xmlnsKey = mapper.xmlNamespacePrefix + ? `xmlns:${mapper.xmlNamespacePrefix}` + : "xmlns"; + parentObject[XML_ATTRKEY] = Object.assign(Object.assign({}, parentObject[XML_ATTRKEY]), { [xmlnsKey]: mapper.xmlNamespace }); + } + const propertyObjectName = propertyMapper.serializedName !== "" + ? objectName + "." + propertyMapper.serializedName + : objectName; + let toSerialize = object[key]; + const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper); + if (polymorphicDiscriminator && + polymorphicDiscriminator.clientName === key && + (toSerialize === undefined || toSerialize === null)) { + toSerialize = mapper.serializedName; + } + const serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName, options); + if (serializedValue !== undefined && propName !== undefined && propName !== null) { + const value = getXmlObjectValue(propertyMapper, serializedValue, isXml, options); + if (isXml && propertyMapper.xmlIsAttribute) { + // XML_ATTRKEY, i.e., $ is the key attributes are kept under in xml2js. + // This keeps things simple while preventing name collision + // with names in user documents. + parentObject[XML_ATTRKEY] = parentObject[XML_ATTRKEY] || {}; + parentObject[XML_ATTRKEY][propName] = serializedValue; + } + else if (isXml && propertyMapper.xmlIsWrapped) { + parentObject[propName] = { [propertyMapper.xmlElementName]: value }; + } + else { + parentObject[propName] = value; + } + } + } + } + const additionalPropertiesMapper = resolveAdditionalProperties(serializer, mapper, objectName); + if (additionalPropertiesMapper) { + const propNames = Object.keys(modelProps); + for (const clientPropName in object) { + const isAdditionalProperty = propNames.every((pn) => pn !== clientPropName); + if (isAdditionalProperty) { + payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '["' + clientPropName + '"]', options); + } + } + } + return payload; + } + return object; +} +function getXmlObjectValue(propertyMapper, serializedValue, isXml, options) { + if (!isXml || !propertyMapper.xmlNamespace) { + return serializedValue; + } + const xmlnsKey = propertyMapper.xmlNamespacePrefix + ? `xmlns:${propertyMapper.xmlNamespacePrefix}` + : "xmlns"; + const xmlNamespace = { [xmlnsKey]: propertyMapper.xmlNamespace }; + if (["Composite"].includes(propertyMapper.type.name)) { + if (serializedValue[XML_ATTRKEY]) { + return serializedValue; + } + else { + const result = Object.assign({}, serializedValue); + result[XML_ATTRKEY] = xmlNamespace; + return result; + } + } + const result = {}; + result[options.xml.xmlCharKey] = serializedValue; + result[XML_ATTRKEY] = xmlNamespace; + return result; +} +function isSpecialXmlProperty(propertyName, options) { + return [XML_ATTRKEY, options.xml.xmlCharKey].includes(propertyName); +} +function deserializeCompositeType(serializer, mapper, responseBody, objectName, options) { + var _a, _b; + const xmlCharKey = (_a = options.xml.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; + if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) { + mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName"); + } + const modelProps = resolveModelProperties(serializer, mapper, objectName); + let instance = {}; + const handledPropertyNames = []; + for (const key of Object.keys(modelProps)) { + const propertyMapper = modelProps[key]; + const paths = splitSerializeName(modelProps[key].serializedName); + handledPropertyNames.push(paths[0]); + const { serializedName, xmlName, xmlElementName } = propertyMapper; + let propertyObjectName = objectName; + if (serializedName !== "" && serializedName !== undefined) { + propertyObjectName = objectName + "." + serializedName; + } + const headerCollectionPrefix = propertyMapper.headerCollectionPrefix; + if (headerCollectionPrefix) { + const dictionary = {}; + for (const headerKey of Object.keys(responseBody)) { + if (headerKey.startsWith(headerCollectionPrefix)) { + dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize(propertyMapper.type.value, responseBody[headerKey], propertyObjectName, options); + } + handledPropertyNames.push(headerKey); + } + instance[key] = dictionary; + } + else if (serializer.isXML) { + if (propertyMapper.xmlIsAttribute && responseBody[XML_ATTRKEY]) { + instance[key] = serializer.deserialize(propertyMapper, responseBody[XML_ATTRKEY][xmlName], propertyObjectName, options); + } + else if (propertyMapper.xmlIsMsText) { + if (responseBody[xmlCharKey] !== undefined) { + instance[key] = responseBody[xmlCharKey]; + } + else if (typeof responseBody === "string") { + // The special case where xml parser parses "content" into JSON of + // `{ name: "content"}` instead of `{ name: { "_": "content" }}` + instance[key] = responseBody; + } + } + else { + const propertyName = xmlElementName || xmlName || serializedName; + if (propertyMapper.xmlIsWrapped) { + /* a list of wrapped by + For the xml example below + + ... + ... + + the responseBody has + { + Cors: { + CorsRule: [{...}, {...}] + } + } + xmlName is "Cors" and xmlElementName is"CorsRule". + */ + const wrapped = responseBody[xmlName]; + const elementList = (_b = wrapped === null || wrapped === void 0 ? void 0 : wrapped[xmlElementName]) !== null && _b !== void 0 ? _b : []; + instance[key] = serializer.deserialize(propertyMapper, elementList, propertyObjectName, options); + handledPropertyNames.push(xmlName); + } + else { + const property = responseBody[propertyName]; + instance[key] = serializer.deserialize(propertyMapper, property, propertyObjectName, options); + handledPropertyNames.push(propertyName); + } + } + } + else { + // deserialize the property if it is present in the provided responseBody instance + let propertyInstance; + let res = responseBody; + // traversing the object step by step. + let steps = 0; + for (const item of paths) { + if (!res) + break; + steps++; + res = res[item]; + } + // only accept null when reaching the last position of object otherwise it would be undefined + if (res === null && steps < paths.length) { + res = undefined; + } + propertyInstance = res; + const polymorphicDiscriminator = mapper.type.polymorphicDiscriminator; + // checking that the model property name (key)(ex: "fishtype") and the + // clientName of the polymorphicDiscriminator {metadata} (ex: "fishtype") + // instead of the serializedName of the polymorphicDiscriminator (ex: "fish.type") + // is a better approach. The generator is not consistent with escaping '\.' in the + // serializedName of the property (ex: "fish\.type") that is marked as polymorphic discriminator + // and the serializedName of the metadata polymorphicDiscriminator (ex: "fish.type"). However, + // the clientName transformation of the polymorphicDiscriminator (ex: "fishtype") and + // the transformation of model property name (ex: "fishtype") is done consistently. + // Hence, it is a safer bet to rely on the clientName of the polymorphicDiscriminator. + if (polymorphicDiscriminator && + key === polymorphicDiscriminator.clientName && + (propertyInstance === undefined || propertyInstance === null)) { + propertyInstance = mapper.serializedName; + } + let serializedValue; + // paging + if (Array.isArray(responseBody[key]) && modelProps[key].serializedName === "") { + propertyInstance = responseBody[key]; + const arrayInstance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options); + // Copy over any properties that have already been added into the instance, where they do + // not exist on the newly de-serialized array + for (const [k, v] of Object.entries(instance)) { + if (!Object.prototype.hasOwnProperty.call(arrayInstance, k)) { + arrayInstance[k] = v; + } + } + instance = arrayInstance; + } + else if (propertyInstance !== undefined || propertyMapper.defaultValue !== undefined) { + serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options); + instance[key] = serializedValue; + } + } + } + const additionalPropertiesMapper = mapper.type.additionalProperties; + if (additionalPropertiesMapper) { + const isAdditionalProperty = (responsePropName) => { + for (const clientPropName in modelProps) { + const paths = splitSerializeName(modelProps[clientPropName].serializedName); + if (paths[0] === responsePropName) { + return false; + } + } + return true; + }; + for (const responsePropName in responseBody) { + if (isAdditionalProperty(responsePropName)) { + instance[responsePropName] = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '["' + responsePropName + '"]', options); + } + } + } + else if (responseBody && !options.ignoreUnknownProperties) { + for (const key of Object.keys(responseBody)) { + if (instance[key] === undefined && + !handledPropertyNames.includes(key) && + !isSpecialXmlProperty(key, options)) { + instance[key] = responseBody[key]; + } + } + } + return instance; +} +function deserializeDictionaryType(serializer, mapper, responseBody, objectName, options) { + /* jshint validthis: true */ + const value = mapper.type.value; + if (!value || typeof value !== "object") { + throw new Error(`"value" metadata for a Dictionary must be defined in the ` + + `mapper and it must of type "object" in ${objectName}`); + } + if (responseBody) { + const tempDictionary = {}; + for (const key of Object.keys(responseBody)) { + tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName, options); + } + return tempDictionary; + } + return responseBody; +} +function deserializeSequenceType(serializer, mapper, responseBody, objectName, options) { + var _a; + let element = mapper.type.element; + if (!element || typeof element !== "object") { + throw new Error(`element" metadata for an Array must be defined in the ` + + `mapper and it must of type "object" in ${objectName}`); + } + if (responseBody) { + if (!Array.isArray(responseBody)) { + // xml2js will interpret a single element array as just the element, so force it to be an array + responseBody = [responseBody]; + } + // Quirk: Composite mappers referenced by `element` might + // not have *all* properties declared (like uberParent), + // so let's try to look up the full definition by name. + if (element.type.name === "Composite" && element.type.className) { + element = (_a = serializer.modelMappers[element.type.className]) !== null && _a !== void 0 ? _a : element; + } + const tempArray = []; + for (let i = 0; i < responseBody.length; i++) { + tempArray[i] = serializer.deserialize(element, responseBody[i], `${objectName}[${i}]`, options); + } + return tempArray; + } + return responseBody; +} +function getIndexDiscriminator(discriminators, discriminatorValue, typeName) { + const typeNamesToCheck = [typeName]; + while (typeNamesToCheck.length) { + const currentName = typeNamesToCheck.shift(); + const indexDiscriminator = discriminatorValue === currentName + ? discriminatorValue + : currentName + "." + discriminatorValue; + if (Object.prototype.hasOwnProperty.call(discriminators, indexDiscriminator)) { + return discriminators[indexDiscriminator]; + } + else { + for (const [name, mapper] of Object.entries(discriminators)) { + if (name.startsWith(currentName + ".") && + mapper.type.uberParent === currentName && + mapper.type.className) { + typeNamesToCheck.push(mapper.type.className); + } + } + } + } + return undefined; +} +function getPolymorphicMapper(serializer, mapper, object, polymorphicPropertyName) { + var _a; + const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper); + if (polymorphicDiscriminator) { + let discriminatorName = polymorphicDiscriminator[polymorphicPropertyName]; + if (discriminatorName) { + // The serializedName might have \\, which we just want to ignore + if (polymorphicPropertyName === "serializedName") { + discriminatorName = discriminatorName.replace(/\\/gi, ""); + } + const discriminatorValue = object[discriminatorName]; + const typeName = (_a = mapper.type.uberParent) !== null && _a !== void 0 ? _a : mapper.type.className; + if (typeof discriminatorValue === "string" && typeName) { + const polymorphicMapper = getIndexDiscriminator(serializer.modelMappers.discriminators, discriminatorValue, typeName); + if (polymorphicMapper) { + mapper = polymorphicMapper; + } + } + } + } + return mapper; +} +function getPolymorphicDiscriminatorRecursively(serializer, mapper) { + return (mapper.type.polymorphicDiscriminator || + getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent) || + getPolymorphicDiscriminatorSafely(serializer, mapper.type.className)); +} +function getPolymorphicDiscriminatorSafely(serializer, typeName) { + return (typeName && + serializer.modelMappers[typeName] && + serializer.modelMappers[typeName].type.polymorphicDiscriminator); +} +/** + * Known types of Mappers + */ +export const MapperTypeNames = { + Base64Url: "Base64Url", + Boolean: "Boolean", + ByteArray: "ByteArray", + Composite: "Composite", + Date: "Date", + DateTime: "DateTime", + DateTimeRfc1123: "DateTimeRfc1123", + Dictionary: "Dictionary", + Enum: "Enum", + Number: "Number", + Object: "Object", + Sequence: "Sequence", + String: "String", + Stream: "Stream", + TimeSpan: "TimeSpan", + UnixTime: "UnixTime", +}; +//# sourceMappingURL=serializer.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-client/dist/esm/serviceClient.js b/claude-code-source/node_modules/@azure/core-client/dist/esm/serviceClient.js new file mode 100644 index 00000000..5a8efb51 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-client/dist/esm/serviceClient.js @@ -0,0 +1,148 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { createPipelineRequest } from "@azure/core-rest-pipeline"; +import { createClientPipeline } from "./pipeline.js"; +import { flattenResponse } from "./utils.js"; +import { getCachedDefaultHttpClient } from "./httpClientCache.js"; +import { getOperationRequestInfo } from "./operationHelpers.js"; +import { getRequestUrl } from "./urlHelpers.js"; +import { getStreamingResponseStatusCodes } from "./interfaceHelpers.js"; +import { logger } from "./log.js"; +/** + * Initializes a new instance of the ServiceClient. + */ +export class ServiceClient { + /** + * The ServiceClient constructor + * @param options - The service client options that govern the behavior of the client. + */ + constructor(options = {}) { + var _a, _b; + this._requestContentType = options.requestContentType; + this._endpoint = (_a = options.endpoint) !== null && _a !== void 0 ? _a : options.baseUri; + if (options.baseUri) { + logger.warning("The baseUri option for SDK Clients has been deprecated, please use endpoint instead."); + } + this._allowInsecureConnection = options.allowInsecureConnection; + this._httpClient = options.httpClient || getCachedDefaultHttpClient(); + this.pipeline = options.pipeline || createDefaultPipeline(options); + if ((_b = options.additionalPolicies) === null || _b === void 0 ? void 0 : _b.length) { + for (const { policy, position } of options.additionalPolicies) { + // Sign happens after Retry and is commonly needed to occur + // before policies that intercept post-retry. + const afterPhase = position === "perRetry" ? "Sign" : undefined; + this.pipeline.addPolicy(policy, { + afterPhase, + }); + } + } + } + /** + * Send the provided httpRequest. + */ + async sendRequest(request) { + return this.pipeline.sendRequest(this._httpClient, request); + } + /** + * Send an HTTP request that is populated using the provided OperationSpec. + * @typeParam T - The typed result of the request, based on the OperationSpec. + * @param operationArguments - The arguments that the HTTP request's templated values will be populated from. + * @param operationSpec - The OperationSpec to use to populate the httpRequest. + */ + async sendOperationRequest(operationArguments, operationSpec) { + const endpoint = operationSpec.baseUrl || this._endpoint; + if (!endpoint) { + throw new Error("If operationSpec.baseUrl is not specified, then the ServiceClient must have a endpoint string property that contains the base URL to use."); + } + // Templatized URLs sometimes reference properties on the ServiceClient child class, + // so we have to pass `this` below in order to search these properties if they're + // not part of OperationArguments + const url = getRequestUrl(endpoint, operationSpec, operationArguments, this); + const request = createPipelineRequest({ + url, + }); + request.method = operationSpec.httpMethod; + const operationInfo = getOperationRequestInfo(request); + operationInfo.operationSpec = operationSpec; + operationInfo.operationArguments = operationArguments; + const contentType = operationSpec.contentType || this._requestContentType; + if (contentType && operationSpec.requestBody) { + request.headers.set("Content-Type", contentType); + } + const options = operationArguments.options; + if (options) { + const requestOptions = options.requestOptions; + if (requestOptions) { + if (requestOptions.timeout) { + request.timeout = requestOptions.timeout; + } + if (requestOptions.onUploadProgress) { + request.onUploadProgress = requestOptions.onUploadProgress; + } + if (requestOptions.onDownloadProgress) { + request.onDownloadProgress = requestOptions.onDownloadProgress; + } + if (requestOptions.shouldDeserialize !== undefined) { + operationInfo.shouldDeserialize = requestOptions.shouldDeserialize; + } + if (requestOptions.allowInsecureConnection) { + request.allowInsecureConnection = true; + } + } + if (options.abortSignal) { + request.abortSignal = options.abortSignal; + } + if (options.tracingOptions) { + request.tracingOptions = options.tracingOptions; + } + } + if (this._allowInsecureConnection) { + request.allowInsecureConnection = true; + } + if (request.streamResponseStatusCodes === undefined) { + request.streamResponseStatusCodes = getStreamingResponseStatusCodes(operationSpec); + } + try { + const rawResponse = await this.sendRequest(request); + const flatResponse = flattenResponse(rawResponse, operationSpec.responses[rawResponse.status]); + if (options === null || options === void 0 ? void 0 : options.onResponse) { + options.onResponse(rawResponse, flatResponse); + } + return flatResponse; + } + catch (error) { + if (typeof error === "object" && (error === null || error === void 0 ? void 0 : error.response)) { + const rawResponse = error.response; + const flatResponse = flattenResponse(rawResponse, operationSpec.responses[error.statusCode] || operationSpec.responses["default"]); + error.details = flatResponse; + if (options === null || options === void 0 ? void 0 : options.onResponse) { + options.onResponse(rawResponse, flatResponse, error); + } + } + throw error; + } + } +} +function createDefaultPipeline(options) { + const credentialScopes = getCredentialScopes(options); + const credentialOptions = options.credential && credentialScopes + ? { credentialScopes, credential: options.credential } + : undefined; + return createClientPipeline(Object.assign(Object.assign({}, options), { credentialOptions })); +} +function getCredentialScopes(options) { + if (options.credentialScopes) { + return options.credentialScopes; + } + if (options.endpoint) { + return `${options.endpoint}/.default`; + } + if (options.baseUri) { + return `${options.baseUri}/.default`; + } + if (options.credential && !options.credentialScopes) { + throw new Error(`When using credentials, the ServiceClientOptions must contain either a endpoint or a credentialScopes. Unable to create a bearerTokenAuthenticationPolicy`); + } + return undefined; +} +//# sourceMappingURL=serviceClient.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-client/dist/esm/state.js b/claude-code-source/node_modules/@azure/core-client/dist/esm/state.js new file mode 100644 index 00000000..e42b6638 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-client/dist/esm/state.js @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +// @ts-expect-error The recommended approach to sharing module state between ESM and CJS. +// See https://github.com/isaacs/tshy/blob/main/README.md#module-local-state for additional information. +import { state as cjsState } from "../commonjs/state.js"; +/** + * Defines the shared state between CJS and ESM by re-exporting the CJS state. + */ +export const state = cjsState; +//# sourceMappingURL=state.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-client/dist/esm/urlHelpers.js b/claude-code-source/node_modules/@azure/core-client/dist/esm/urlHelpers.js new file mode 100644 index 00000000..2dddee39 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-client/dist/esm/urlHelpers.js @@ -0,0 +1,235 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { getOperationArgumentValueFromParameter } from "./operationHelpers.js"; +import { getPathStringFromParameter } from "./interfaceHelpers.js"; +const CollectionFormatToDelimiterMap = { + CSV: ",", + SSV: " ", + Multi: "Multi", + TSV: "\t", + Pipes: "|", +}; +export function getRequestUrl(baseUri, operationSpec, operationArguments, fallbackObject) { + const urlReplacements = calculateUrlReplacements(operationSpec, operationArguments, fallbackObject); + let isAbsolutePath = false; + let requestUrl = replaceAll(baseUri, urlReplacements); + if (operationSpec.path) { + let path = replaceAll(operationSpec.path, urlReplacements); + // QUIRK: sometimes we get a path component like /{nextLink} + // which may be a fully formed URL with a leading /. In that case, we should + // remove the leading / + if (operationSpec.path === "/{nextLink}" && path.startsWith("/")) { + path = path.substring(1); + } + // QUIRK: sometimes we get a path component like {nextLink} + // which may be a fully formed URL. In that case, we should + // ignore the baseUri. + if (isAbsoluteUrl(path)) { + requestUrl = path; + isAbsolutePath = true; + } + else { + requestUrl = appendPath(requestUrl, path); + } + } + const { queryParams, sequenceParams } = calculateQueryParameters(operationSpec, operationArguments, fallbackObject); + /** + * Notice that this call sets the `noOverwrite` parameter to true if the `requestUrl` + * is an absolute path. This ensures that existing query parameter values in `requestUrl` + * do not get overwritten. On the other hand when `requestUrl` is not absolute path, it + * is still being built so there is nothing to overwrite. + */ + requestUrl = appendQueryParams(requestUrl, queryParams, sequenceParams, isAbsolutePath); + return requestUrl; +} +function replaceAll(input, replacements) { + let result = input; + for (const [searchValue, replaceValue] of replacements) { + result = result.split(searchValue).join(replaceValue); + } + return result; +} +function calculateUrlReplacements(operationSpec, operationArguments, fallbackObject) { + var _a; + const result = new Map(); + if ((_a = operationSpec.urlParameters) === null || _a === void 0 ? void 0 : _a.length) { + for (const urlParameter of operationSpec.urlParameters) { + let urlParameterValue = getOperationArgumentValueFromParameter(operationArguments, urlParameter, fallbackObject); + const parameterPathString = getPathStringFromParameter(urlParameter); + urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, parameterPathString); + if (!urlParameter.skipEncoding) { + urlParameterValue = encodeURIComponent(urlParameterValue); + } + result.set(`{${urlParameter.mapper.serializedName || parameterPathString}}`, urlParameterValue); + } + } + return result; +} +function isAbsoluteUrl(url) { + return url.includes("://"); +} +function appendPath(url, pathToAppend) { + if (!pathToAppend) { + return url; + } + const parsedUrl = new URL(url); + let newPath = parsedUrl.pathname; + if (!newPath.endsWith("/")) { + newPath = `${newPath}/`; + } + if (pathToAppend.startsWith("/")) { + pathToAppend = pathToAppend.substring(1); + } + const searchStart = pathToAppend.indexOf("?"); + if (searchStart !== -1) { + const path = pathToAppend.substring(0, searchStart); + const search = pathToAppend.substring(searchStart + 1); + newPath = newPath + path; + if (search) { + parsedUrl.search = parsedUrl.search ? `${parsedUrl.search}&${search}` : search; + } + } + else { + newPath = newPath + pathToAppend; + } + parsedUrl.pathname = newPath; + return parsedUrl.toString(); +} +function calculateQueryParameters(operationSpec, operationArguments, fallbackObject) { + var _a; + const result = new Map(); + const sequenceParams = new Set(); + if ((_a = operationSpec.queryParameters) === null || _a === void 0 ? void 0 : _a.length) { + for (const queryParameter of operationSpec.queryParameters) { + if (queryParameter.mapper.type.name === "Sequence" && queryParameter.mapper.serializedName) { + sequenceParams.add(queryParameter.mapper.serializedName); + } + let queryParameterValue = getOperationArgumentValueFromParameter(operationArguments, queryParameter, fallbackObject); + if ((queryParameterValue !== undefined && queryParameterValue !== null) || + queryParameter.mapper.required) { + queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, getPathStringFromParameter(queryParameter)); + const delimiter = queryParameter.collectionFormat + ? CollectionFormatToDelimiterMap[queryParameter.collectionFormat] + : ""; + if (Array.isArray(queryParameterValue)) { + // replace null and undefined + queryParameterValue = queryParameterValue.map((item) => { + if (item === null || item === undefined) { + return ""; + } + return item; + }); + } + if (queryParameter.collectionFormat === "Multi" && queryParameterValue.length === 0) { + continue; + } + else if (Array.isArray(queryParameterValue) && + (queryParameter.collectionFormat === "SSV" || queryParameter.collectionFormat === "TSV")) { + queryParameterValue = queryParameterValue.join(delimiter); + } + if (!queryParameter.skipEncoding) { + if (Array.isArray(queryParameterValue)) { + queryParameterValue = queryParameterValue.map((item) => { + return encodeURIComponent(item); + }); + } + else { + queryParameterValue = encodeURIComponent(queryParameterValue); + } + } + // Join pipes and CSV *after* encoding, or the server will be upset. + if (Array.isArray(queryParameterValue) && + (queryParameter.collectionFormat === "CSV" || queryParameter.collectionFormat === "Pipes")) { + queryParameterValue = queryParameterValue.join(delimiter); + } + result.set(queryParameter.mapper.serializedName || getPathStringFromParameter(queryParameter), queryParameterValue); + } + } + } + return { + queryParams: result, + sequenceParams, + }; +} +function simpleParseQueryParams(queryString) { + const result = new Map(); + if (!queryString || queryString[0] !== "?") { + return result; + } + // remove the leading ? + queryString = queryString.slice(1); + const pairs = queryString.split("&"); + for (const pair of pairs) { + const [name, value] = pair.split("=", 2); + const existingValue = result.get(name); + if (existingValue) { + if (Array.isArray(existingValue)) { + existingValue.push(value); + } + else { + result.set(name, [existingValue, value]); + } + } + else { + result.set(name, value); + } + } + return result; +} +/** @internal */ +export function appendQueryParams(url, queryParams, sequenceParams, noOverwrite = false) { + if (queryParams.size === 0) { + return url; + } + const parsedUrl = new URL(url); + // QUIRK: parsedUrl.searchParams will have their name/value pairs decoded, which + // can change their meaning to the server, such as in the case of a SAS signature. + // To avoid accidentally un-encoding a query param, we parse the key/values ourselves + const combinedParams = simpleParseQueryParams(parsedUrl.search); + for (const [name, value] of queryParams) { + const existingValue = combinedParams.get(name); + if (Array.isArray(existingValue)) { + if (Array.isArray(value)) { + existingValue.push(...value); + const valueSet = new Set(existingValue); + combinedParams.set(name, Array.from(valueSet)); + } + else { + existingValue.push(value); + } + } + else if (existingValue) { + if (Array.isArray(value)) { + value.unshift(existingValue); + } + else if (sequenceParams.has(name)) { + combinedParams.set(name, [existingValue, value]); + } + if (!noOverwrite) { + combinedParams.set(name, value); + } + } + else { + combinedParams.set(name, value); + } + } + const searchPieces = []; + for (const [name, value] of combinedParams) { + if (typeof value === "string") { + searchPieces.push(`${name}=${value}`); + } + else if (Array.isArray(value)) { + // QUIRK: If we get an array of values, include multiple key/value pairs + for (const subValue of value) { + searchPieces.push(`${name}=${subValue}`); + } + } + else { + searchPieces.push(`${name}=${value}`); + } + } + // QUIRK: we have to set search manually as searchParams will encode comma when it shouldn't. + parsedUrl.search = searchPieces.length ? `?${searchPieces.join("&")}` : ""; + return parsedUrl.toString(); +} +//# sourceMappingURL=urlHelpers.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-client/dist/esm/utils.js b/claude-code-source/node_modules/@azure/core-client/dist/esm/utils.js new file mode 100644 index 00000000..ca2bf052 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-client/dist/esm/utils.js @@ -0,0 +1,115 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +/** + * A type guard for a primitive response body. + * @param value - Value to test + * + * @internal + */ +export function isPrimitiveBody(value, mapperTypeName) { + return (mapperTypeName !== "Composite" && + mapperTypeName !== "Dictionary" && + (typeof value === "string" || + typeof value === "number" || + typeof value === "boolean" || + (mapperTypeName === null || mapperTypeName === void 0 ? void 0 : mapperTypeName.match(/^(Date|DateTime|DateTimeRfc1123|UnixTime|ByteArray|Base64Url)$/i)) !== + null || + value === undefined || + value === null)); +} +const validateISODuration = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/; +/** + * Returns true if the given string is in ISO 8601 format. + * @param value - The value to be validated for ISO 8601 duration format. + * @internal + */ +export function isDuration(value) { + return validateISODuration.test(value); +} +const validUuidRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i; +/** + * Returns true if the provided uuid is valid. + * + * @param uuid - The uuid that needs to be validated. + * + * @internal + */ +export function isValidUuid(uuid) { + return validUuidRegex.test(uuid); +} +/** + * Maps the response as follows: + * - wraps the response body if needed (typically if its type is primitive). + * - returns null if the combination of the headers and the body is empty. + * - otherwise, returns the combination of the headers and the body. + * + * @param responseObject - a representation of the parsed response + * @returns the response that will be returned to the user which can be null and/or wrapped + * + * @internal + */ +function handleNullableResponseAndWrappableBody(responseObject) { + const combinedHeadersAndBody = Object.assign(Object.assign({}, responseObject.headers), responseObject.body); + if (responseObject.hasNullableType && + Object.getOwnPropertyNames(combinedHeadersAndBody).length === 0) { + return responseObject.shouldWrapBody ? { body: null } : null; + } + else { + return responseObject.shouldWrapBody + ? Object.assign(Object.assign({}, responseObject.headers), { body: responseObject.body }) : combinedHeadersAndBody; + } +} +/** + * Take a `FullOperationResponse` and turn it into a flat + * response object to hand back to the consumer. + * @param fullResponse - The processed response from the operation request + * @param responseSpec - The response map from the OperationSpec + * + * @internal + */ +export function flattenResponse(fullResponse, responseSpec) { + var _a, _b; + const parsedHeaders = fullResponse.parsedHeaders; + // head methods never have a body, but we return a boolean set to body property + // to indicate presence/absence of the resource + if (fullResponse.request.method === "HEAD") { + return Object.assign(Object.assign({}, parsedHeaders), { body: fullResponse.parsedBody }); + } + const bodyMapper = responseSpec && responseSpec.bodyMapper; + const isNullable = Boolean(bodyMapper === null || bodyMapper === void 0 ? void 0 : bodyMapper.nullable); + const expectedBodyTypeName = bodyMapper === null || bodyMapper === void 0 ? void 0 : bodyMapper.type.name; + /** If the body is asked for, we look at the expected body type to handle it */ + if (expectedBodyTypeName === "Stream") { + return Object.assign(Object.assign({}, parsedHeaders), { blobBody: fullResponse.blobBody, readableStreamBody: fullResponse.readableStreamBody }); + } + const modelProperties = (expectedBodyTypeName === "Composite" && + bodyMapper.type.modelProperties) || + {}; + const isPageableResponse = Object.keys(modelProperties).some((k) => modelProperties[k].serializedName === ""); + if (expectedBodyTypeName === "Sequence" || isPageableResponse) { + const arrayResponse = (_a = fullResponse.parsedBody) !== null && _a !== void 0 ? _a : []; + for (const key of Object.keys(modelProperties)) { + if (modelProperties[key].serializedName) { + arrayResponse[key] = (_b = fullResponse.parsedBody) === null || _b === void 0 ? void 0 : _b[key]; + } + } + if (parsedHeaders) { + for (const key of Object.keys(parsedHeaders)) { + arrayResponse[key] = parsedHeaders[key]; + } + } + return isNullable && + !fullResponse.parsedBody && + !parsedHeaders && + Object.getOwnPropertyNames(modelProperties).length === 0 + ? null + : arrayResponse; + } + return handleNullableResponseAndWrappableBody({ + body: fullResponse.parsedBody, + headers: parsedHeaders, + hasNullableType: isNullable, + shouldWrapBody: isPrimitiveBody(fullResponse.parsedBody, expectedBodyTypeName), + }); +} +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/constants.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/constants.js new file mode 100644 index 00000000..d63b2b98 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/constants.js @@ -0,0 +1,5 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +export const SDK_VERSION = "1.21.0"; +export const DEFAULT_RETRY_POLICY_COUNT = 3; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/createPipelineFromOptions.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/createPipelineFromOptions.js new file mode 100644 index 00000000..8cc8514c --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/createPipelineFromOptions.js @@ -0,0 +1,55 @@ +// 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) { + var _a; + 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((_a = options.telemetryOptions) === null || _a === void 0 ? void 0 : _a.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(Object.assign(Object.assign({}, 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/defaultHttpClient.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/defaultHttpClient.js new file mode 100644 index 00000000..b031abf8 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/defaultHttpClient.js @@ -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 === null || cleanup === void 0 ? void 0 : cleanup(); + } + }, + }; +} +//# sourceMappingURL=defaultHttpClient.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/httpHeaders.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/httpHeaders.js new file mode 100644 index 00000000..8c0677c3 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/httpHeaders.js @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/index.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/index.js new file mode 100644 index 00000000..6b5609db --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/index.js @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/log.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/log.js new file mode 100644 index 00000000..6e3a66a4 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/log.js @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/pipeline.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/pipeline.js new file mode 100644 index 00000000..566258a9 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/pipeline.js @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/pipelineRequest.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/pipelineRequest.js new file mode 100644 index 00000000..463dac5e --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/pipelineRequest.js @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/agentPolicy.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/agentPolicy.js new file mode 100644 index 00000000..b4f11e8a --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/agentPolicy.js @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/bearerTokenAuthenticationPolicy.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/bearerTokenAuthenticationPolicy.js new file mode 100644 index 00000000..6ace777a --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/bearerTokenAuthenticationPolicy.js @@ -0,0 +1,238 @@ +// 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) { + var _a; + const { scopes } = onChallengeOptions; + const accessToken = await onChallengeOptions.getAccessToken(scopes, { + enableCae: true, + claims: caeClaims, + }); + if (!accessToken) { + return false; + } + onChallengeOptions.request.headers.set("Authorization", `${(_a = accessToken.tokenType) !== null && _a !== void 0 ? _a : "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) { + var _a, _b, _c; + const { credential, scopes, challengeCallbacks } = options; + const logger = options.logger || coreLogger; + const callbacks = { + authorizeRequest: (_b = (_a = challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequest) === null || _a === void 0 ? void 0 : _a.bind(challengeCallbacks)) !== null && _b !== void 0 ? _b : defaultAuthorizeRequest, + authorizeRequestOnChallenge: (_c = challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequestOnChallenge) === null || _c === void 0 ? void 0 : _c.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) { + var _a; + if (!challenges) { + return; + } + // Find all challenges present in the header + const parsedChallenges = parseChallenges(challenges); + return (_a = parsedChallenges.find((x) => x.scheme === "Bearer" && x.params.claims && x.params.error === "insufficient_claims")) === null || _a === void 0 ? void 0 : _a.params.claims; +} +//# sourceMappingURL=bearerTokenAuthenticationPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/decompressResponsePolicy.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/decompressResponsePolicy.js new file mode 100644 index 00000000..3cb1afb6 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/decompressResponsePolicy.js @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/defaultRetryPolicy.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/defaultRetryPolicy.js new file mode 100644 index 00000000..f3d8f35d --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/defaultRetryPolicy.js @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/formDataPolicy.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/formDataPolicy.js new file mode 100644 index 00000000..3d978c94 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/formDataPolicy.js @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/logPolicy.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/logPolicy.js new file mode 100644 index 00000000..ee71a286 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/logPolicy.js @@ -0,0 +1,16 @@ +// 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(Object.assign({ logger: coreLogger.info }, options)); +} +//# sourceMappingURL=logPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/multipartPolicy.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/multipartPolicy.js new file mode 100644 index 00000000..e0617750 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/multipartPolicy.js @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/proxyPolicy.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/proxyPolicy.js new file mode 100644 index 00000000..092b1ef3 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/proxyPolicy.js @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/redirectPolicy.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/redirectPolicy.js new file mode 100644 index 00000000..503c33e3 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/redirectPolicy.js @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/retryPolicy.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/retryPolicy.js new file mode 100644 index 00000000..748f1a2b --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/retryPolicy.js @@ -0,0 +1,16 @@ +// 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, Object.assign({ logger: retryPolicyLogger }, options)); +} +//# sourceMappingURL=retryPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/setClientRequestIdPolicy.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/setClientRequestIdPolicy.js new file mode 100644 index 00000000..4bbf2822 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/setClientRequestIdPolicy.js @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/tlsPolicy.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/tlsPolicy.js new file mode 100644 index 00000000..d8a21dda --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/tlsPolicy.js @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/tracingPolicy.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/tracingPolicy.js new file mode 100644 index 00000000..a54c6332 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/tracingPolicy.js @@ -0,0 +1,132 @@ +// 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) { + var _a; + 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 } = (_a = tryCreateSpan(tracingClient, request, spanAttributes)) !== null && _a !== void 0 ? _a : {}; + 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/userAgentPolicy.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/userAgentPolicy.js new file mode 100644 index 00000000..57d47077 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/userAgentPolicy.js @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/wrapAbortSignalLikePolicy.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/wrapAbortSignalLikePolicy.js new file mode 100644 index 00000000..4487214e --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/wrapAbortSignalLikePolicy.js @@ -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 === null || cleanup === void 0 ? void 0 : cleanup(); + } + }, + }; +} +//# sourceMappingURL=wrapAbortSignalLikePolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/restError.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/restError.js new file mode 100644 index 00000000..b2e2161f --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/restError.js @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/file.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/file.js new file mode 100644 index 00000000..e8951bfa --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/file.js @@ -0,0 +1,104 @@ +// 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 = {}) { + var _a, _b, _c, _d; + return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : new Date().getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: (_d = options.size) !== null && _d !== void 0 ? _d : -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 = {}) { + var _a, _b, _c; + if (isNodeLike) { + return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : new Date().getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/tokenCycler.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/tokenCycler.js new file mode 100644 index 00000000..0d522dba --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/tokenCycler.js @@ -0,0 +1,162 @@ +// 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 (_a) { + 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 = Object.assign(Object.assign({}, 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() { + var _a; + if (cycler.isRefreshing) { + return false; + } + if ((token === null || token === void 0 ? void 0 : token.refreshAfterTimestamp) && token.refreshAfterTimestamp < Date.now()) { + return true; + } + return ((_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : 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) { + var _a; + 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 + (_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/userAgent.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/userAgent.js new file mode 100644 index 00000000..ed9dc78e --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/userAgent.js @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/userAgentPlatform.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/userAgentPlatform.js new file mode 100644 index 00000000..f5a2c680 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/userAgentPlatform.js @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import * as os from "node:os"; +import * as process from "node:process"; +/** + * @internal + */ +export function getHeaderName() { + return "User-Agent"; +} +/** + * @internal + */ +export async function setPlatformSpecificData(map) { + if (process && process.versions) { + const versions = process.versions; + if (versions.bun) { + map.set("Bun", versions.bun); + } + else if (versions.deno) { + map.set("Deno", versions.deno); + } + else if (versions.node) { + map.set("Node", versions.node); + } + } + map.set("OS", `(${os.arch()}-${os.type()}-${os.release()})`); +} +//# sourceMappingURL=userAgentPlatform.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/wrapAbortSignal.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/wrapAbortSignal.js new file mode 100644 index 00000000..dbd1fbd5 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/wrapAbortSignal.js @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +/** + * Creates a native AbortSignal which reflects the state of the provided AbortSignalLike. + * If the AbortSignalLike is already a native AbortSignal, it is returned as is. + * @param abortSignalLike - The AbortSignalLike to wrap. + * @returns - An object containing the native AbortSignal and an optional cleanup function. The cleanup function should be called when the AbortSignal is no longer needed. + */ +export function wrapAbortSignalLike(abortSignalLike) { + if (abortSignalLike instanceof AbortSignal) { + return { abortSignal: abortSignalLike }; + } + if (abortSignalLike.aborted) { + return { abortSignal: AbortSignal.abort(abortSignalLike.reason) }; + } + const controller = new AbortController(); + let needsCleanup = true; + function cleanup() { + if (needsCleanup) { + abortSignalLike.removeEventListener("abort", listener); + needsCleanup = false; + } + } + function listener() { + controller.abort(abortSignalLike.reason); + cleanup(); + } + abortSignalLike.addEventListener("abort", listener); + return { abortSignal: controller.signal, cleanup }; +} +//# sourceMappingURL=wrapAbortSignal.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-tracing/dist/commonjs/state.js b/claude-code-source/node_modules/@azure/core-tracing/dist/commonjs/state.js new file mode 100644 index 00000000..3e781757 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-tracing/dist/commonjs/state.js @@ -0,0 +1,14 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.state = void 0; +/** + * @internal + * + * Holds the singleton instrumenter, to be shared across CJS and ESM imports. + */ +exports.state = { + instrumenterImplementation: undefined, +}; +//# sourceMappingURL=state-cjs.cjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-tracing/dist/esm/index.js b/claude-code-source/node_modules/@azure/core-tracing/dist/esm/index.js new file mode 100644 index 00000000..c2376651 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-tracing/dist/esm/index.js @@ -0,0 +1,5 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +export { useInstrumenter } from "./instrumenter.js"; +export { createTracingClient } from "./tracingClient.js"; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-tracing/dist/esm/instrumenter.js b/claude-code-source/node_modules/@azure/core-tracing/dist/esm/instrumenter.js new file mode 100644 index 00000000..a394aa99 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-tracing/dist/esm/instrumenter.js @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { createTracingContext } from "./tracingContext.js"; +import { state } from "./state.js"; +export function createDefaultTracingSpan() { + return { + end: () => { + // noop + }, + isRecording: () => false, + recordException: () => { + // noop + }, + setAttribute: () => { + // noop + }, + setStatus: () => { + // noop + }, + addEvent: () => { + // noop + }, + }; +} +export function createDefaultInstrumenter() { + return { + createRequestHeaders: () => { + return {}; + }, + parseTraceparentHeader: () => { + return undefined; + }, + startSpan: (_name, spanOptions) => { + return { + span: createDefaultTracingSpan(), + tracingContext: createTracingContext({ parentContext: spanOptions.tracingContext }), + }; + }, + withContext(_context, callback, ...callbackArgs) { + return callback(...callbackArgs); + }, + }; +} +/** + * Extends the Azure SDK with support for a given instrumenter implementation. + * + * @param instrumenter - The instrumenter implementation to use. + */ +export function useInstrumenter(instrumenter) { + state.instrumenterImplementation = instrumenter; +} +/** + * Gets the currently set instrumenter, a No-Op instrumenter by default. + * + * @returns The currently set instrumenter + */ +export function getInstrumenter() { + if (!state.instrumenterImplementation) { + state.instrumenterImplementation = createDefaultInstrumenter(); + } + return state.instrumenterImplementation; +} +//# sourceMappingURL=instrumenter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-tracing/dist/esm/state.js b/claude-code-source/node_modules/@azure/core-tracing/dist/esm/state.js new file mode 100644 index 00000000..e42b6638 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-tracing/dist/esm/state.js @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +// @ts-expect-error The recommended approach to sharing module state between ESM and CJS. +// See https://github.com/isaacs/tshy/blob/main/README.md#module-local-state for additional information. +import { state as cjsState } from "../commonjs/state.js"; +/** + * Defines the shared state between CJS and ESM by re-exporting the CJS state. + */ +export const state = cjsState; +//# sourceMappingURL=state.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-tracing/dist/esm/tracingClient.js b/claude-code-source/node_modules/@azure/core-tracing/dist/esm/tracingClient.js new file mode 100644 index 00000000..3e79edd1 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-tracing/dist/esm/tracingClient.js @@ -0,0 +1,74 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { getInstrumenter } from "./instrumenter.js"; +import { knownContextKeys } from "./tracingContext.js"; +/** + * Creates a new tracing client. + * + * @param options - Options used to configure the tracing client. + * @returns - An instance of {@link TracingClient}. + */ +export function createTracingClient(options) { + const { namespace, packageName, packageVersion } = options; + function startSpan(name, operationOptions, spanOptions) { + var _a; + const startSpanResult = getInstrumenter().startSpan(name, Object.assign(Object.assign({}, spanOptions), { packageName: packageName, packageVersion: packageVersion, tracingContext: (_a = operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions) === null || _a === void 0 ? void 0 : _a.tracingContext })); + let tracingContext = startSpanResult.tracingContext; + const span = startSpanResult.span; + if (!tracingContext.getValue(knownContextKeys.namespace)) { + tracingContext = tracingContext.setValue(knownContextKeys.namespace, namespace); + } + span.setAttribute("az.namespace", tracingContext.getValue(knownContextKeys.namespace)); + const updatedOptions = Object.assign({}, operationOptions, { + tracingOptions: Object.assign(Object.assign({}, operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions), { tracingContext }), + }); + return { + span, + updatedOptions, + }; + } + async function withSpan(name, operationOptions, callback, spanOptions) { + const { span, updatedOptions } = startSpan(name, operationOptions, spanOptions); + try { + const result = await withContext(updatedOptions.tracingOptions.tracingContext, () => Promise.resolve(callback(updatedOptions, span))); + span.setStatus({ status: "success" }); + return result; + } + catch (err) { + span.setStatus({ status: "error", error: err }); + throw err; + } + finally { + span.end(); + } + } + function withContext(context, callback, ...callbackArgs) { + return getInstrumenter().withContext(context, callback, ...callbackArgs); + } + /** + * Parses a traceparent header value into a span identifier. + * + * @param traceparentHeader - The traceparent header to parse. + * @returns An implementation-specific identifier for the span. + */ + function parseTraceparentHeader(traceparentHeader) { + return getInstrumenter().parseTraceparentHeader(traceparentHeader); + } + /** + * Creates a set of request headers to propagate tracing information to a backend. + * + * @param tracingContext - The context containing the span to serialize. + * @returns The set of headers to add to a request. + */ + function createRequestHeaders(tracingContext) { + return getInstrumenter().createRequestHeaders(tracingContext); + } + return { + startSpan, + withSpan, + withContext, + parseTraceparentHeader, + createRequestHeaders, + }; +} +//# sourceMappingURL=tracingClient.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-tracing/dist/esm/tracingContext.js b/claude-code-source/node_modules/@azure/core-tracing/dist/esm/tracingContext.js new file mode 100644 index 00000000..46a0bb8e --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-tracing/dist/esm/tracingContext.js @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +/** @internal */ +export const knownContextKeys = { + span: Symbol.for("@azure/core-tracing span"), + namespace: Symbol.for("@azure/core-tracing namespace"), +}; +/** + * Creates a new {@link TracingContext} with the given options. + * @param options - A set of known keys that may be set on the context. + * @returns A new {@link TracingContext} with the given options. + * + * @internal + */ +export function createTracingContext(options = {}) { + let context = new TracingContextImpl(options.parentContext); + if (options.span) { + context = context.setValue(knownContextKeys.span, options.span); + } + if (options.namespace) { + context = context.setValue(knownContextKeys.namespace, options.namespace); + } + return context; +} +/** @internal */ +export class TracingContextImpl { + constructor(initialContext) { + this._contextMap = + initialContext instanceof TracingContextImpl + ? new Map(initialContext._contextMap) + : new Map(); + } + setValue(key, value) { + const newContext = new TracingContextImpl(this); + newContext._contextMap.set(key, value); + return newContext; + } + getValue(key) { + return this._contextMap.get(key); + } + deleteValue(key) { + const newContext = new TracingContextImpl(this); + newContext._contextMap.delete(key); + return newContext; + } +} +//# sourceMappingURL=tracingContext.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-util/dist/esm/createAbortablePromise.js b/claude-code-source/node_modules/@azure/core-util/dist/esm/createAbortablePromise.js new file mode 100644 index 00000000..b58c71c3 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-util/dist/esm/createAbortablePromise.js @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { AbortError } from "@azure/abort-controller"; +/** + * Creates an abortable promise. + * @param buildPromise - A function that takes the resolve and reject functions as parameters. + * @param options - The options for the abortable promise. + * @returns A promise that can be aborted. + */ +export function createAbortablePromise(buildPromise, options) { + const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; + return new Promise((resolve, reject) => { + function rejectOnAbort() { + reject(new AbortError(abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : "The operation was aborted.")); + } + function removeListeners() { + abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener("abort", onAbort); + } + function onAbort() { + cleanupBeforeAbort === null || cleanupBeforeAbort === void 0 ? void 0 : cleanupBeforeAbort(); + removeListeners(); + rejectOnAbort(); + } + if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) { + return rejectOnAbort(); + } + try { + buildPromise((x) => { + removeListeners(); + resolve(x); + }, (x) => { + removeListeners(); + reject(x); + }); + } + catch (err) { + reject(err); + } + abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.addEventListener("abort", onAbort); + }); +} +//# sourceMappingURL=createAbortablePromise.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-util/dist/esm/delay.js b/claude-code-source/node_modules/@azure/core-util/dist/esm/delay.js new file mode 100644 index 00000000..4e83133a --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-util/dist/esm/delay.js @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { createAbortablePromise } from "./createAbortablePromise.js"; +import { getRandomIntegerInclusive } from "@typespec/ts-http-runtime/internal/util"; +const StandardAbortMessage = "The delay was aborted."; +/** + * A wrapper for setTimeout that resolves a promise after timeInMs milliseconds. + * @param timeInMs - The number of milliseconds to be delayed. + * @param options - The options for delay - currently abort options + * @returns Promise that is resolved after timeInMs + */ +export function delay(timeInMs, options) { + let token; + const { abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; + return createAbortablePromise((resolve) => { + token = setTimeout(resolve, timeInMs); + }, { + cleanupBeforeAbort: () => clearTimeout(token), + abortSignal, + abortErrorMsg: abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : StandardAbortMessage, + }); +} +/** + * Calculates the delay interval for retry attempts using exponential delay with jitter. + * @param retryAttempt - The current retry attempt number. + * @param config - The exponential retry configuration. + * @returns An object containing the calculated retry delay. + */ +export function calculateRetryDelay(retryAttempt, config) { + // Exponentially increase the delay each time + const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt); + // Don't let the delay exceed the maximum + const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay); + // Allow the final value to have some "jitter" (within 50% of the delay size) so + // that retries across multiple clients don't occur simultaneously. + const retryAfterInMs = clampedDelay / 2 + getRandomIntegerInclusive(0, clampedDelay / 2); + return { retryAfterInMs }; +} +//# sourceMappingURL=delay.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-util/dist/esm/error.js b/claude-code-source/node_modules/@azure/core-util/dist/esm/error.js new file mode 100644 index 00000000..b28f2866 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-util/dist/esm/error.js @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { isError } from "@typespec/ts-http-runtime/internal/util"; +/** + * Given what is thought to be an error object, return the message if possible. + * If the message is missing, returns a stringified version of the input. + * @param e - Something thrown from a try block + * @returns The error message or a string of the input + */ +export function getErrorMessage(e) { + if (isError(e)) { + return e.message; + } + else { + let stringified; + try { + if (typeof e === "object" && e) { + stringified = JSON.stringify(e); + } + else { + stringified = String(e); + } + } + catch (err) { + stringified = "[unable to stringify input]"; + } + return `Unknown error ${stringified}`; + } +} +//# sourceMappingURL=error.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-util/dist/esm/index.js b/claude-code-source/node_modules/@azure/core-util/dist/esm/index.js new file mode 100644 index 00000000..4ce68b72 --- /dev/null +++ b/claude-code-source/node_modules/@azure/core-util/dist/esm/index.js @@ -0,0 +1,131 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import * as tspRuntime from "@typespec/ts-http-runtime/internal/util"; +export { cancelablePromiseRace, } from "./aborterUtils.js"; +export { createAbortablePromise, } from "./createAbortablePromise.js"; +export { delay } from "./delay.js"; +export { getErrorMessage } from "./error.js"; +export { isDefined, isObjectWithProperties, objectHasProperty } from "./typeGuards.js"; +/** + * Calculates the delay interval for retry attempts using exponential delay with jitter. + * + * @param retryAttempt - The current retry attempt number. + * + * @param config - The exponential retry configuration. + * + * @returns An object containing the calculated retry delay. + */ +export function calculateRetryDelay(retryAttempt, config) { + return tspRuntime.calculateRetryDelay(retryAttempt, config); +} +/** + * Generates a SHA-256 hash. + * + * @param content - The data to be included in the hash. + * + * @param encoding - The textual encoding to use for the returned hash. + */ +export function computeSha256Hash(content, encoding) { + return tspRuntime.computeSha256Hash(content, encoding); +} +/** + * Generates a SHA-256 HMAC signature. + * + * @param key - The HMAC key represented as a base64 string, used to generate the cryptographic HMAC hash. + * + * @param stringToSign - The data to be signed. + * + * @param encoding - The textual encoding to use for the returned HMAC digest. + */ +export function computeSha256Hmac(key, stringToSign, encoding) { + return tspRuntime.computeSha256Hmac(key, stringToSign, encoding); +} +/** + * Returns a random integer value between a lower and upper bound, inclusive of both bounds. Note that this uses Math.random and isn't secure. If you need to use this for any kind of security purpose, find a better source of random. + * + * @param min - The smallest integer value allowed. + * + * @param max - The largest integer value allowed. + */ +export function getRandomIntegerInclusive(min, max) { + return tspRuntime.getRandomIntegerInclusive(min, max); +} +/** + * Typeguard for an error object shape (has name and message) + * + * @param e - Something caught by a catch clause. + */ +export function isError(e) { + return tspRuntime.isError(e); +} +/** + * Helper to determine when an input is a generic JS object. + * + * @returns true when input is an object type that is not null, Array, RegExp, or Date. + */ +export function isObject(input) { + return tspRuntime.isObject(input); +} +/** + * Generated Universally Unique Identifier + * + * @returns RFC4122 v4 UUID. + */ +export function randomUUID() { + return tspRuntime.randomUUID(); +} +/** + * A constant that indicates whether the environment the code is running is a Web Browser. + */ +export const isBrowser = tspRuntime.isBrowser; +/** + * A constant that indicates whether the environment the code is running is Bun.sh. + */ +export const isBun = tspRuntime.isBun; +/** + * A constant that indicates whether the environment the code is running is Deno. + */ +export const isDeno = tspRuntime.isDeno; +/** + * A constant that indicates whether the environment the code is running is a Node.js compatible environment. + * + * @deprecated + * + * Use `isNodeLike` instead. + */ +export const isNode = tspRuntime.isNodeLike; +/** + * A constant that indicates whether the environment the code is running is a Node.js compatible environment. + */ +export const isNodeLike = tspRuntime.isNodeLike; +/** + * A constant that indicates whether the environment the code is running is Node.JS. + */ +export const isNodeRuntime = tspRuntime.isNodeRuntime; +/** + * A constant that indicates whether the environment the code is running is in React-Native. + */ +export const isReactNative = tspRuntime.isReactNative; +/** + * A constant that indicates whether the environment the code is running is a Web Worker. + */ +export const isWebWorker = tspRuntime.isWebWorker; +/** + * The helper that transforms bytes with specific character encoding into string + * @param bytes - the uint8array bytes + * @param format - the format we use to encode the byte + * @returns a string of the encoded string + */ +export function uint8ArrayToString(bytes, format) { + return tspRuntime.uint8ArrayToString(bytes, format); +} +/** + * The helper that transforms string to specific character encoded bytes array. + * @param value - the string to be converted + * @param format - the format we use to decode the value + * @returns a uint8array + */ +export function stringToUint8Array(value, format) { + return tspRuntime.stringToUint8Array(value, format); +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/client/identityClient.js b/claude-code-source/node_modules/@azure/identity/dist/esm/client/identityClient.js new file mode 100644 index 00000000..ba7eca57 --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/client/identityClient.js @@ -0,0 +1,248 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { ServiceClient } from "@azure/core-client"; +import { isNode } from "@azure/core-util"; +import { createHttpHeaders, createPipelineRequest } from "@azure/core-rest-pipeline"; +import { AuthenticationError, AuthenticationErrorName } from "../errors.js"; +import { getIdentityTokenEndpointSuffix } from "../util/identityTokenEndpoint.js"; +import { DefaultAuthorityHost, SDK_VERSION } from "../constants.js"; +import { tracingClient } from "../util/tracing.js"; +import { logger } from "../util/logging.js"; +import { parseExpirationTimestamp, parseRefreshTimestamp, } from "../credentials/managedIdentityCredential/utils.js"; +const noCorrelationId = "noCorrelationId"; +/** + * @internal + */ +export function getIdentityClientAuthorityHost(options) { + // The authorityHost can come from options or from the AZURE_AUTHORITY_HOST environment variable. + let authorityHost = options === null || options === void 0 ? void 0 : options.authorityHost; + // The AZURE_AUTHORITY_HOST environment variable can only be provided in Node.js. + if (isNode) { + authorityHost = authorityHost !== null && authorityHost !== void 0 ? authorityHost : process.env.AZURE_AUTHORITY_HOST; + } + // If the authorityHost is not provided, we use the default one from the public cloud: https://login.microsoftonline.com + return authorityHost !== null && authorityHost !== void 0 ? authorityHost : DefaultAuthorityHost; +} +/** + * The network module used by the Identity credentials. + * + * It allows for credentials to abort any pending request independently of the MSAL flow, + * by calling to the `abortRequests()` method. + * + */ +export class IdentityClient extends ServiceClient { + constructor(options) { + var _a, _b; + const packageDetails = `azsdk-js-identity/${SDK_VERSION}`; + const userAgentPrefix = ((_a = options === null || options === void 0 ? void 0 : options.userAgentOptions) === null || _a === void 0 ? void 0 : _a.userAgentPrefix) + ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}` + : `${packageDetails}`; + const baseUri = getIdentityClientAuthorityHost(options); + if (!baseUri.startsWith("https:")) { + throw new Error("The authorityHost address must use the 'https' protocol."); + } + super(Object.assign(Object.assign({ requestContentType: "application/json; charset=utf-8", retryOptions: { + maxRetries: 3, + } }, options), { userAgentOptions: { + userAgentPrefix, + }, baseUri })); + this.allowInsecureConnection = false; + this.authorityHost = baseUri; + this.abortControllers = new Map(); + this.allowLoggingAccountIdentifiers = (_b = options === null || options === void 0 ? void 0 : options.loggingOptions) === null || _b === void 0 ? void 0 : _b.allowLoggingAccountIdentifiers; + // used for WorkloadIdentity + this.tokenCredentialOptions = Object.assign({}, options); + // used for ManagedIdentity + if (options === null || options === void 0 ? void 0 : options.allowInsecureConnection) { + this.allowInsecureConnection = options.allowInsecureConnection; + } + } + async sendTokenRequest(request) { + logger.info(`IdentityClient: sending token request to [${request.url}]`); + const response = await this.sendRequest(request); + if (response.bodyAsText && (response.status === 200 || response.status === 201)) { + const parsedBody = JSON.parse(response.bodyAsText); + if (!parsedBody.access_token) { + return null; + } + this.logIdentifiers(response); + const token = { + accessToken: { + token: parsedBody.access_token, + expiresOnTimestamp: parseExpirationTimestamp(parsedBody), + refreshAfterTimestamp: parseRefreshTimestamp(parsedBody), + tokenType: "Bearer", + }, + refreshToken: parsedBody.refresh_token, + }; + logger.info(`IdentityClient: [${request.url}] token acquired, expires on ${token.accessToken.expiresOnTimestamp}`); + return token; + } + else { + const error = new AuthenticationError(response.status, response.bodyAsText); + logger.warning(`IdentityClient: authentication error. HTTP status: ${response.status}, ${error.errorResponse.errorDescription}`); + throw error; + } + } + async refreshAccessToken(tenantId, clientId, scopes, refreshToken, clientSecret, options = {}) { + if (refreshToken === undefined) { + return null; + } + logger.info(`IdentityClient: refreshing access token with client ID: ${clientId}, scopes: ${scopes} started`); + const refreshParams = { + grant_type: "refresh_token", + client_id: clientId, + refresh_token: refreshToken, + scope: scopes, + }; + if (clientSecret !== undefined) { + refreshParams.client_secret = clientSecret; + } + const query = new URLSearchParams(refreshParams); + return tracingClient.withSpan("IdentityClient.refreshAccessToken", options, async (updatedOptions) => { + try { + const urlSuffix = getIdentityTokenEndpointSuffix(tenantId); + const request = createPipelineRequest({ + url: `${this.authorityHost}/${tenantId}/${urlSuffix}`, + method: "POST", + body: query.toString(), + abortSignal: options.abortSignal, + headers: createHttpHeaders({ + Accept: "application/json", + "Content-Type": "application/x-www-form-urlencoded", + }), + tracingOptions: updatedOptions.tracingOptions, + }); + const response = await this.sendTokenRequest(request); + logger.info(`IdentityClient: refreshed token for client ID: ${clientId}`); + return response; + } + catch (err) { + if (err.name === AuthenticationErrorName && + err.errorResponse.error === "interaction_required") { + // It's likely that the refresh token has expired, so + // return null so that the credential implementation will + // initiate the authentication flow again. + logger.info(`IdentityClient: interaction required for client ID: ${clientId}`); + return null; + } + else { + logger.warning(`IdentityClient: failed refreshing token for client ID: ${clientId}: ${err}`); + throw err; + } + } + }); + } + // Here is a custom layer that allows us to abort requests that go through MSAL, + // since MSAL doesn't allow us to pass options all the way through. + generateAbortSignal(correlationId) { + const controller = new AbortController(); + const controllers = this.abortControllers.get(correlationId) || []; + controllers.push(controller); + this.abortControllers.set(correlationId, controllers); + const existingOnAbort = controller.signal.onabort; + controller.signal.onabort = (...params) => { + this.abortControllers.set(correlationId, undefined); + if (existingOnAbort) { + existingOnAbort.apply(controller.signal, params); + } + }; + return controller.signal; + } + abortRequests(correlationId) { + const key = correlationId || noCorrelationId; + const controllers = [ + ...(this.abortControllers.get(key) || []), + // MSAL passes no correlation ID to the get requests... + ...(this.abortControllers.get(noCorrelationId) || []), + ]; + if (!controllers.length) { + return; + } + for (const controller of controllers) { + controller.abort(); + } + this.abortControllers.set(key, undefined); + } + getCorrelationId(options) { + var _a; + const parameter = (_a = options === null || options === void 0 ? void 0 : options.body) === null || _a === void 0 ? void 0 : _a.split("&").map((part) => part.split("=")).find(([key]) => key === "client-request-id"); + return parameter && parameter.length ? parameter[1] || noCorrelationId : noCorrelationId; + } + // The MSAL network module methods follow + async sendGetRequestAsync(url, options) { + const request = createPipelineRequest({ + url, + method: "GET", + body: options === null || options === void 0 ? void 0 : options.body, + allowInsecureConnection: this.allowInsecureConnection, + headers: createHttpHeaders(options === null || options === void 0 ? void 0 : options.headers), + abortSignal: this.generateAbortSignal(noCorrelationId), + }); + const response = await this.sendRequest(request); + this.logIdentifiers(response); + return { + body: response.bodyAsText ? JSON.parse(response.bodyAsText) : undefined, + headers: response.headers.toJSON(), + status: response.status, + }; + } + async sendPostRequestAsync(url, options) { + const request = createPipelineRequest({ + url, + method: "POST", + body: options === null || options === void 0 ? void 0 : options.body, + headers: createHttpHeaders(options === null || options === void 0 ? void 0 : options.headers), + allowInsecureConnection: this.allowInsecureConnection, + // MSAL doesn't send the correlation ID on the get requests. + abortSignal: this.generateAbortSignal(this.getCorrelationId(options)), + }); + const response = await this.sendRequest(request); + this.logIdentifiers(response); + return { + body: response.bodyAsText ? JSON.parse(response.bodyAsText) : undefined, + headers: response.headers.toJSON(), + status: response.status, + }; + } + /** + * + * @internal + */ + getTokenCredentialOptions() { + return this.tokenCredentialOptions; + } + /** + * If allowLoggingAccountIdentifiers was set on the constructor options + * we try to log the account identifiers by parsing the received access token. + * + * The account identifiers we try to log are: + * - `appid`: The application or Client Identifier. + * - `upn`: User Principal Name. + * - It might not be available in some authentication scenarios. + * - If it's not available, we put a placeholder: "No User Principal Name available". + * - `tid`: Tenant Identifier. + * - `oid`: Object Identifier of the authenticated user. + */ + logIdentifiers(response) { + if (!this.allowLoggingAccountIdentifiers || !response.bodyAsText) { + return; + } + const unavailableUpn = "No User Principal Name available"; + try { + const parsed = response.parsedBody || JSON.parse(response.bodyAsText); + const accessToken = parsed.access_token; + if (!accessToken) { + // Without an access token allowLoggingAccountIdentifiers isn't useful. + return; + } + const base64Metadata = accessToken.split(".")[1]; + const { appid, upn, tid, oid } = JSON.parse(Buffer.from(base64Metadata, "base64").toString("utf8")); + logger.info(`[Authenticated account] Client ID: ${appid}. Tenant ID: ${tid}. User Principal Name: ${upn || unavailableUpn}. Object ID (user): ${oid}`); + } + catch (e) { + logger.warning("allowLoggingAccountIdentifiers was set, but we couldn't log the account information. Error:", e.message); + } + } +} +//# sourceMappingURL=identityClient.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/constants.js b/claude-code-source/node_modules/@azure/identity/dist/esm/constants.js new file mode 100644 index 00000000..5f60f124 --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/constants.js @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +/** + * Current version of the `@azure/identity` package. + */ +export const SDK_VERSION = `4.10.1`; +/** + * The default client ID for authentication + * @internal + */ +// TODO: temporary - this is the Azure CLI clientID - we'll replace it when +// Developer Sign On application is available +// https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/Constants.cs#L9 +export const DeveloperSignOnClientId = "04b07795-8ddb-461a-bbee-02f9e1bf7b46"; +/** + * The default tenant for authentication + * @internal + */ +export const DefaultTenantId = "common"; +/** + * A list of known Azure authority hosts + */ +export var AzureAuthorityHosts; +(function (AzureAuthorityHosts) { + /** + * China-based Azure Authority Host + */ + AzureAuthorityHosts["AzureChina"] = "https://login.chinacloudapi.cn"; + /** + * Germany-based Azure Authority Host + * + * @deprecated Microsoft Cloud Germany was closed on October 29th, 2021. + * + * */ + AzureAuthorityHosts["AzureGermany"] = "https://login.microsoftonline.de"; + /** + * US Government Azure Authority Host + */ + AzureAuthorityHosts["AzureGovernment"] = "https://login.microsoftonline.us"; + /** + * Public Cloud Azure Authority Host + */ + AzureAuthorityHosts["AzurePublicCloud"] = "https://login.microsoftonline.com"; +})(AzureAuthorityHosts || (AzureAuthorityHosts = {})); +/** + * @internal + * The default authority host. + */ +export const DefaultAuthorityHost = AzureAuthorityHosts.AzurePublicCloud; +/** + * @internal + * The default environment host for Azure Public Cloud + */ +export const DefaultAuthority = "login.microsoftonline.com"; +/** + * @internal + * Allow acquiring tokens for any tenant for multi-tentant auth. + */ +export const ALL_TENANTS = ["*"]; +/** + * @internal + */ +export const CACHE_CAE_SUFFIX = "cae"; +/** + * @internal + */ +export const CACHE_NON_CAE_SUFFIX = "nocae"; +/** + * @internal + * + * The default name for the cache persistence plugin. + * Matches the constant defined in the cache persistence package. + */ +export const DEFAULT_TOKEN_CACHE_NAME = "msal.cache"; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/authorizationCodeCredential.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/authorizationCodeCredential.js new file mode 100644 index 00000000..e0ffb9b8 --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/authorizationCodeCredential.js @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, } from "../util/tenantIdUtils.js"; +import { checkTenantId } from "../util/tenantIdUtils.js"; +import { credentialLogger } from "../util/logging.js"; +import { ensureScopes } from "../util/scopeUtils.js"; +import { tracingClient } from "../util/tracing.js"; +import { createMsalClient } from "../msal/nodeFlows/msalClient.js"; +const logger = credentialLogger("AuthorizationCodeCredential"); +/** + * Enables authentication to Microsoft Entra ID using an authorization code + * that was obtained through the authorization code flow, described in more detail + * in the Microsoft Entra ID documentation: + * + * https://learn.microsoft.com/entra/identity-platform/v2-oauth2-auth-code-flow + */ +export class AuthorizationCodeCredential { + /** + * @hidden + * @internal + */ + constructor(tenantId, clientId, clientSecretOrAuthorizationCode, authorizationCodeOrRedirectUri, redirectUriOrOptions, options) { + checkTenantId(logger, tenantId); + this.clientSecret = clientSecretOrAuthorizationCode; + if (typeof redirectUriOrOptions === "string") { + // the clientId+clientSecret constructor + this.authorizationCode = authorizationCodeOrRedirectUri; + this.redirectUri = redirectUriOrOptions; + // in this case, options are good as they come + } + else { + // clientId only + this.authorizationCode = clientSecretOrAuthorizationCode; + this.redirectUri = authorizationCodeOrRedirectUri; + this.clientSecret = undefined; + options = redirectUriOrOptions; + } + // TODO: Validate tenant if provided + this.tenantId = tenantId; + this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants); + this.msalClient = createMsalClient(clientId, tenantId, Object.assign(Object.assign({}, options), { logger, tokenCredentialOptions: options !== null && options !== void 0 ? options : {} })); + } + /** + * Authenticates with Microsoft Entra ID and returns an access token if successful. + * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure. + * + * @param scopes - The list of scopes for which the token will have access. + * @param options - The options used to configure any requests this + * TokenCredential implementation might make. + */ + async getToken(scopes, options = {}) { + return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async (newOptions) => { + const tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds); + newOptions.tenantId = tenantId; + const arrayScopes = ensureScopes(scopes); + return this.msalClient.getTokenByAuthorizationCode(arrayScopes, this.redirectUri, this.authorizationCode, this.clientSecret, Object.assign(Object.assign({}, newOptions), { disableAutomaticAuthentication: this.disableAutomaticAuthentication })); + }); + } +} +//# sourceMappingURL=authorizationCodeCredential.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/azureCliCredential.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/azureCliCredential.js new file mode 100644 index 00000000..15cd22fc --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/azureCliCredential.js @@ -0,0 +1,191 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { checkTenantId, processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, } from "../util/tenantIdUtils.js"; +import { credentialLogger, formatError, formatSuccess } from "../util/logging.js"; +import { ensureValidScopeForDevTimeCreds, getScopeResource } from "../util/scopeUtils.js"; +import { CredentialUnavailableError } from "../errors.js"; +import child_process from "child_process"; +import { tracingClient } from "../util/tracing.js"; +import { checkSubscription } from "../util/subscriptionUtils.js"; +const logger = credentialLogger("AzureCliCredential"); +/** + * Mockable reference to the CLI credential cliCredentialFunctions + * @internal + */ +export const cliCredentialInternals = { + /** + * @internal + */ + getSafeWorkingDir() { + if (process.platform === "win32") { + let systemRoot = process.env.SystemRoot || process.env["SYSTEMROOT"]; + if (!systemRoot) { + logger.getToken.warning("The SystemRoot environment variable is not set. This may cause issues when using the Azure CLI credential."); + systemRoot = "C:\\Windows"; + } + return systemRoot; + } + else { + return "/bin"; + } + }, + /** + * Gets the access token from Azure CLI + * @param resource - The resource to use when getting the token + * @internal + */ + async getAzureCliAccessToken(resource, tenantId, subscription, timeout) { + let tenantSection = []; + let subscriptionSection = []; + if (tenantId) { + tenantSection = ["--tenant", tenantId]; + } + if (subscription) { + // Add quotes around the subscription to handle subscriptions with spaces + subscriptionSection = ["--subscription", `"${subscription}"`]; + } + return new Promise((resolve, reject) => { + try { + child_process.execFile("az", [ + "account", + "get-access-token", + "--output", + "json", + "--resource", + resource, + ...tenantSection, + ...subscriptionSection, + ], { cwd: cliCredentialInternals.getSafeWorkingDir(), shell: true, timeout }, (error, stdout, stderr) => { + resolve({ stdout: stdout, stderr: stderr, error }); + }); + } + catch (err) { + reject(err); + } + }); + }, +}; +/** + * This credential will use the currently logged-in user login information + * via the Azure CLI ('az') commandline tool. + * To do so, it will read the user access token and expire time + * with Azure CLI command "az account get-access-token". + */ +export class AzureCliCredential { + /** + * Creates an instance of the {@link AzureCliCredential}. + * + * To use this credential, ensure that you have already logged + * in via the 'az' tool using the command "az login" from the commandline. + * + * @param options - Options, to optionally allow multi-tenant requests. + */ + constructor(options) { + if (options === null || options === void 0 ? void 0 : options.tenantId) { + checkTenantId(logger, options === null || options === void 0 ? void 0 : options.tenantId); + this.tenantId = options === null || options === void 0 ? void 0 : options.tenantId; + } + if (options === null || options === void 0 ? void 0 : options.subscription) { + checkSubscription(logger, options === null || options === void 0 ? void 0 : options.subscription); + this.subscription = options === null || options === void 0 ? void 0 : options.subscription; + } + this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants); + this.timeout = options === null || options === void 0 ? void 0 : options.processTimeoutInMs; + } + /** + * Authenticates with Microsoft Entra ID and returns an access token if successful. + * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure. + * + * @param scopes - The list of scopes for which the token will have access. + * @param options - The options used to configure any requests this + * TokenCredential implementation might make. + */ + async getToken(scopes, options = {}) { + const tenantId = processMultiTenantRequest(this.tenantId, options, this.additionallyAllowedTenantIds); + if (tenantId) { + checkTenantId(logger, tenantId); + } + if (this.subscription) { + checkSubscription(logger, this.subscription); + } + const scope = typeof scopes === "string" ? scopes : scopes[0]; + logger.getToken.info(`Using the scope ${scope}`); + return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async () => { + var _a, _b, _c, _d; + try { + ensureValidScopeForDevTimeCreds(scope, logger); + const resource = getScopeResource(scope); + const obj = await cliCredentialInternals.getAzureCliAccessToken(resource, tenantId, this.subscription, this.timeout); + const specificScope = (_a = obj.stderr) === null || _a === void 0 ? void 0 : _a.match("(.*)az login --scope(.*)"); + const isLoginError = ((_b = obj.stderr) === null || _b === void 0 ? void 0 : _b.match("(.*)az login(.*)")) && !specificScope; + const isNotInstallError = ((_c = obj.stderr) === null || _c === void 0 ? void 0 : _c.match("az:(.*)not found")) || ((_d = obj.stderr) === null || _d === void 0 ? void 0 : _d.startsWith("'az' is not recognized")); + if (isNotInstallError) { + const error = new CredentialUnavailableError("Azure CLI could not be found. Please visit https://aka.ms/azure-cli for installation instructions and then, once installed, authenticate to your Azure account using 'az login'."); + logger.getToken.info(formatError(scopes, error)); + throw error; + } + if (isLoginError) { + const error = new CredentialUnavailableError("Please run 'az login' from a command prompt to authenticate before using this credential."); + logger.getToken.info(formatError(scopes, error)); + throw error; + } + try { + const responseData = obj.stdout; + const response = this.parseRawResponse(responseData); + logger.getToken.info(formatSuccess(scopes)); + return response; + } + catch (e) { + if (obj.stderr) { + throw new CredentialUnavailableError(obj.stderr); + } + throw e; + } + } + catch (err) { + const error = err.name === "CredentialUnavailableError" + ? err + : new CredentialUnavailableError(err.message || "Unknown error while trying to retrieve the access token"); + logger.getToken.info(formatError(scopes, error)); + throw error; + } + }); + } + /** + * Parses the raw JSON response from the Azure CLI into a usable AccessToken object + * + * @param rawResponse - The raw JSON response from the Azure CLI + * @returns An access token with the expiry time parsed from the raw response + * + * The expiryTime of the credential's access token, in milliseconds, is calculated as follows: + * + * When available, expires_on (introduced in Azure CLI v2.54.0) will be preferred. Otherwise falls back to expiresOn. + */ + parseRawResponse(rawResponse) { + const response = JSON.parse(rawResponse); + const token = response.accessToken; + // if available, expires_on will be a number representing seconds since epoch. + // ensure it's a number or NaN + let expiresOnTimestamp = Number.parseInt(response.expires_on, 10) * 1000; + if (!isNaN(expiresOnTimestamp)) { + logger.getToken.info("expires_on is available and is valid, using it"); + return { + token, + expiresOnTimestamp, + tokenType: "Bearer", + }; + } + // fallback to the older expiresOn - an RFC3339 date string + expiresOnTimestamp = new Date(response.expiresOn).getTime(); + // ensure expiresOn is well-formatted + if (isNaN(expiresOnTimestamp)) { + throw new CredentialUnavailableError(`Unexpected response from Azure CLI when getting token. Expected "expiresOn" to be a RFC3339 date string. Got: "${response.expiresOn}"`); + } + return { + token, + expiresOnTimestamp, + tokenType: "Bearer", + }; + } +} +//# sourceMappingURL=azureCliCredential.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/azureDeveloperCliCredential.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/azureDeveloperCliCredential.js new file mode 100644 index 00000000..423ac8ca --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/azureDeveloperCliCredential.js @@ -0,0 +1,173 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { credentialLogger, formatError, formatSuccess } from "../util/logging.js"; +import { CredentialUnavailableError } from "../errors.js"; +import child_process from "child_process"; +import { checkTenantId, processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, } from "../util/tenantIdUtils.js"; +import { tracingClient } from "../util/tracing.js"; +import { ensureValidScopeForDevTimeCreds } from "../util/scopeUtils.js"; +const logger = credentialLogger("AzureDeveloperCliCredential"); +/** + * Mockable reference to the Developer CLI credential cliCredentialFunctions + * @internal + */ +export const developerCliCredentialInternals = { + /** + * @internal + */ + getSafeWorkingDir() { + if (process.platform === "win32") { + let systemRoot = process.env.SystemRoot || process.env["SYSTEMROOT"]; + if (!systemRoot) { + logger.getToken.warning("The SystemRoot environment variable is not set. This may cause issues when using the Azure Developer CLI credential."); + systemRoot = "C:\\Windows"; + } + return systemRoot; + } + else { + return "/bin"; + } + }, + /** + * Gets the access token from Azure Developer CLI + * @param scopes - The scopes to use when getting the token + * @internal + */ + async getAzdAccessToken(scopes, tenantId, timeout) { + let tenantSection = []; + if (tenantId) { + tenantSection = ["--tenant-id", tenantId]; + } + return new Promise((resolve, reject) => { + try { + child_process.execFile("azd", [ + "auth", + "token", + "--output", + "json", + ...scopes.reduce((previous, current) => previous.concat("--scope", current), []), + ...tenantSection, + ], { + cwd: developerCliCredentialInternals.getSafeWorkingDir(), + timeout, + }, (error, stdout, stderr) => { + resolve({ stdout, stderr, error }); + }); + } + catch (err) { + reject(err); + } + }); + }, +}; +/** + * Azure Developer CLI is a command-line interface tool that allows developers to create, manage, and deploy + * resources in Azure. It's built on top of the Azure CLI and provides additional functionality specific + * to Azure developers. It allows users to authenticate as a user and/or a service principal against + * Microsoft Entra ID. The + * AzureDeveloperCliCredential authenticates in a development environment and acquires a token on behalf of + * the logged-in user or service principal in the Azure Developer CLI. It acts as the Azure Developer CLI logged in user or + * service principal and executes an Azure CLI command underneath to authenticate the application against + * Microsoft Entra ID. + * + *

Configure AzureDeveloperCliCredential

+ * + * To use this credential, the developer needs to authenticate locally in Azure Developer CLI using one of the + * commands below: + * + *
    + *
  1. Run "azd auth login" in Azure Developer CLI to authenticate interactively as a user.
  2. + *
  3. Run "azd auth login --client-id clientID --client-secret clientSecret + * --tenant-id tenantID" to authenticate as a service principal.
  4. + *
+ * + * You may need to repeat this process after a certain time period, depending on the refresh token validity in your + * organization. Generally, the refresh token validity period is a few weeks to a few months. + * AzureDeveloperCliCredential will prompt you to sign in again. + */ +export class AzureDeveloperCliCredential { + /** + * Creates an instance of the {@link AzureDeveloperCliCredential}. + * + * To use this credential, ensure that you have already logged + * in via the 'azd' tool using the command "azd auth login" from the commandline. + * + * @param options - Options, to optionally allow multi-tenant requests. + */ + constructor(options) { + if (options === null || options === void 0 ? void 0 : options.tenantId) { + checkTenantId(logger, options === null || options === void 0 ? void 0 : options.tenantId); + this.tenantId = options === null || options === void 0 ? void 0 : options.tenantId; + } + this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants); + this.timeout = options === null || options === void 0 ? void 0 : options.processTimeoutInMs; + } + /** + * Authenticates with Microsoft Entra ID and returns an access token if successful. + * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure. + * + * @param scopes - The list of scopes for which the token will have access. + * @param options - The options used to configure any requests this + * TokenCredential implementation might make. + */ + async getToken(scopes, options = {}) { + const tenantId = processMultiTenantRequest(this.tenantId, options, this.additionallyAllowedTenantIds); + if (tenantId) { + checkTenantId(logger, tenantId); + } + let scopeList; + if (typeof scopes === "string") { + scopeList = [scopes]; + } + else { + scopeList = scopes; + } + logger.getToken.info(`Using the scopes ${scopes}`); + return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async () => { + var _a, _b, _c, _d; + try { + scopeList.forEach((scope) => { + ensureValidScopeForDevTimeCreds(scope, logger); + }); + const obj = await developerCliCredentialInternals.getAzdAccessToken(scopeList, tenantId, this.timeout); + const isNotLoggedInError = ((_a = obj.stderr) === null || _a === void 0 ? void 0 : _a.match("not logged in, run `azd login` to login")) || + ((_b = obj.stderr) === null || _b === void 0 ? void 0 : _b.match("not logged in, run `azd auth login` to login")); + const isNotInstallError = ((_c = obj.stderr) === null || _c === void 0 ? void 0 : _c.match("azd:(.*)not found")) || + ((_d = obj.stderr) === null || _d === void 0 ? void 0 : _d.startsWith("'azd' is not recognized")); + if (isNotInstallError || (obj.error && obj.error.code === "ENOENT")) { + const error = new CredentialUnavailableError("Azure Developer CLI couldn't be found. To mitigate this issue, see the troubleshooting guidelines at https://aka.ms/azsdk/js/identity/azdevclicredential/troubleshoot."); + logger.getToken.info(formatError(scopes, error)); + throw error; + } + if (isNotLoggedInError) { + const error = new CredentialUnavailableError("Please run 'azd auth login' from a command prompt to authenticate before using this credential. For more information, see the troubleshooting guidelines at https://aka.ms/azsdk/js/identity/azdevclicredential/troubleshoot."); + logger.getToken.info(formatError(scopes, error)); + throw error; + } + try { + const resp = JSON.parse(obj.stdout); + logger.getToken.info(formatSuccess(scopes)); + return { + token: resp.token, + expiresOnTimestamp: new Date(resp.expiresOn).getTime(), + tokenType: "Bearer", + }; + } + catch (e) { + if (obj.stderr) { + throw new CredentialUnavailableError(obj.stderr); + } + throw e; + } + } + catch (err) { + const error = err.name === "CredentialUnavailableError" + ? err + : new CredentialUnavailableError(err.message || "Unknown error while trying to retrieve the access token"); + logger.getToken.info(formatError(scopes, error)); + throw error; + } + }); + } +} +//# sourceMappingURL=azureDeveloperCliCredential.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/azurePipelinesCredential.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/azurePipelinesCredential.js new file mode 100644 index 00000000..e44cdddd --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/azurePipelinesCredential.js @@ -0,0 +1,141 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { AuthenticationError, CredentialUnavailableError } from "../errors.js"; +import { createHttpHeaders, createPipelineRequest } from "@azure/core-rest-pipeline"; +import { ClientAssertionCredential } from "./clientAssertionCredential.js"; +import { IdentityClient } from "../client/identityClient.js"; +import { checkTenantId } from "../util/tenantIdUtils.js"; +import { credentialLogger } from "../util/logging.js"; +const credentialName = "AzurePipelinesCredential"; +const logger = credentialLogger(credentialName); +const OIDC_API_VERSION = "7.1"; +/** + * This credential is designed to be used in Azure Pipelines with service connections + * as a setup for workload identity federation. + */ +export class AzurePipelinesCredential { + /** + * AzurePipelinesCredential supports Federated Identity on Azure Pipelines through Service Connections. + * @param tenantId - tenantId associated with the service connection + * @param clientId - clientId associated with the service connection + * @param serviceConnectionId - Unique ID for the service connection, as found in the querystring's resourceId key + * @param systemAccessToken - The pipeline's System.AccessToken value. + * @param options - The identity client options to use for authentication. + */ + constructor(tenantId, clientId, serviceConnectionId, systemAccessToken, options = {}) { + var _a, _b; + if (!clientId) { + throw new CredentialUnavailableError(`${credentialName}: is unavailable. clientId is a required parameter.`); + } + if (!tenantId) { + throw new CredentialUnavailableError(`${credentialName}: is unavailable. tenantId is a required parameter.`); + } + if (!serviceConnectionId) { + throw new CredentialUnavailableError(`${credentialName}: is unavailable. serviceConnectionId is a required parameter.`); + } + if (!systemAccessToken) { + throw new CredentialUnavailableError(`${credentialName}: is unavailable. systemAccessToken is a required parameter.`); + } + // Allow these headers to be logged for troubleshooting by AzurePipelines. + options.loggingOptions = Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.loggingOptions), { additionalAllowedHeaderNames: [ + ...((_b = (_a = options.loggingOptions) === null || _a === void 0 ? void 0 : _a.additionalAllowedHeaderNames) !== null && _b !== void 0 ? _b : []), + "x-vss-e2eid", + "x-msedge-ref", + ] }); + this.identityClient = new IdentityClient(options); + checkTenantId(logger, tenantId); + logger.info(`Invoking AzurePipelinesCredential with tenant ID: ${tenantId}, client ID: ${clientId}, and service connection ID: ${serviceConnectionId}`); + if (!process.env.SYSTEM_OIDCREQUESTURI) { + throw new CredentialUnavailableError(`${credentialName}: is unavailable. Ensure that you're running this task in an Azure Pipeline, so that following missing system variable(s) can be defined- "SYSTEM_OIDCREQUESTURI"`); + } + const oidcRequestUrl = `${process.env.SYSTEM_OIDCREQUESTURI}?api-version=${OIDC_API_VERSION}&serviceConnectionId=${serviceConnectionId}`; + logger.info(`Invoking ClientAssertionCredential with tenant ID: ${tenantId}, client ID: ${clientId} and service connection ID: ${serviceConnectionId}`); + this.clientAssertionCredential = new ClientAssertionCredential(tenantId, clientId, this.requestOidcToken.bind(this, oidcRequestUrl, systemAccessToken), options); + } + /** + * Authenticates with Microsoft Entra ID and returns an access token if successful. + * If authentication fails, a {@link CredentialUnavailableError} or {@link AuthenticationError} will be thrown with the details of the failure. + * + * @param scopes - The list of scopes for which the token will have access. + * @param options - The options used to configure any requests this + * TokenCredential implementation might make. + */ + async getToken(scopes, options) { + if (!this.clientAssertionCredential) { + const errorMessage = `${credentialName}: is unavailable. To use Federation Identity in Azure Pipelines, the following parameters are required - + tenantId, + clientId, + serviceConnectionId, + systemAccessToken, + "SYSTEM_OIDCREQUESTURI". + See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/azurepipelinescredential/troubleshoot`; + logger.error(errorMessage); + throw new CredentialUnavailableError(errorMessage); + } + logger.info("Invoking getToken() of Client Assertion Credential"); + return this.clientAssertionCredential.getToken(scopes, options); + } + /** + * + * @param oidcRequestUrl - oidc request url + * @param systemAccessToken - system access token + * @returns OIDC token from Azure Pipelines + */ + async requestOidcToken(oidcRequestUrl, systemAccessToken) { + logger.info("Requesting OIDC token from Azure Pipelines..."); + logger.info(oidcRequestUrl); + const request = createPipelineRequest({ + url: oidcRequestUrl, + method: "POST", + headers: createHttpHeaders({ + "Content-Type": "application/json", + Authorization: `Bearer ${systemAccessToken}`, + // Prevents the service from responding with a redirect HTTP status code (useful for automation). + "X-TFS-FedAuthRedirect": "Suppress", + }), + }); + const response = await this.identityClient.sendRequest(request); + return handleOidcResponse(response); + } +} +export function handleOidcResponse(response) { + // OIDC token is present in `bodyAsText` field + const text = response.bodyAsText; + if (!text) { + logger.error(`${credentialName}: Authentication Failed. Received null token from OIDC request. Response status- ${response.status}. Complete response - ${JSON.stringify(response)}`); + throw new AuthenticationError(response.status, { + error: `${credentialName}: Authentication Failed. Received null token from OIDC request.`, + error_description: `${JSON.stringify(response)}. See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/azurepipelinescredential/troubleshoot`, + }); + } + try { + const result = JSON.parse(text); + if (result === null || result === void 0 ? void 0 : result.oidcToken) { + return result.oidcToken; + } + else { + const errorMessage = `${credentialName}: Authentication Failed. oidcToken field not detected in the response.`; + let errorDescription = ``; + if (response.status !== 200) { + errorDescription = `Response body = ${text}. Response Headers ["x-vss-e2eid"] = ${response.headers.get("x-vss-e2eid")} and ["x-msedge-ref"] = ${response.headers.get("x-msedge-ref")}. See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/azurepipelinescredential/troubleshoot`; + } + logger.error(errorMessage); + logger.error(errorDescription); + throw new AuthenticationError(response.status, { + error: errorMessage, + error_description: errorDescription, + }); + } + } + catch (e) { + const errorDetails = `${credentialName}: Authentication Failed. oidcToken field not detected in the response.`; + logger.error(`Response from service = ${text}, Response Headers ["x-vss-e2eid"] = ${response.headers.get("x-vss-e2eid")} + and ["x-msedge-ref"] = ${response.headers.get("x-msedge-ref")}, error message = ${e.message}`); + logger.error(errorDetails); + throw new AuthenticationError(response.status, { + error: errorDetails, + error_description: `Response = ${text}. Response headers ["x-vss-e2eid"] = ${response.headers.get("x-vss-e2eid")} and ["x-msedge-ref"] = ${response.headers.get("x-msedge-ref")}. See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/azurepipelinescredential/troubleshoot`, + }); + } +} +//# sourceMappingURL=azurePipelinesCredential.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/azurePowerShellCredential.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/azurePowerShellCredential.js new file mode 100644 index 00000000..cdf54277 --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/azurePowerShellCredential.js @@ -0,0 +1,229 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { checkTenantId, processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, } from "../util/tenantIdUtils.js"; +import { credentialLogger, formatError, formatSuccess } from "../util/logging.js"; +import { ensureValidScopeForDevTimeCreds, getScopeResource } from "../util/scopeUtils.js"; +import { CredentialUnavailableError } from "../errors.js"; +import { processUtils } from "../util/processUtils.js"; +import { tracingClient } from "../util/tracing.js"; +const logger = credentialLogger("AzurePowerShellCredential"); +const isWindows = process.platform === "win32"; +/** + * Returns a platform-appropriate command name by appending ".exe" on Windows. + * + * @internal + */ +export function formatCommand(commandName) { + if (isWindows) { + return `${commandName}.exe`; + } + else { + return commandName; + } +} +/** + * Receives a list of commands to run, executes them, then returns the outputs. + * If anything fails, an error is thrown. + * @internal + */ +async function runCommands(commands, timeout) { + const results = []; + for (const command of commands) { + const [file, ...parameters] = command; + const result = (await processUtils.execFile(file, parameters, { + encoding: "utf8", + timeout, + })); + results.push(result); + } + return results; +} +/** + * Known PowerShell errors + * @internal + */ +export const powerShellErrors = { + login: "Run Connect-AzAccount to login", + installed: "The specified module 'Az.Accounts' with version '2.2.0' was not loaded because no valid module file was found in any module directory", +}; +/** + * Messages to use when throwing in this credential. + * @internal + */ +export const powerShellPublicErrorMessages = { + login: "Please run 'Connect-AzAccount' from PowerShell to authenticate before using this credential.", + installed: `The 'Az.Account' module >= 2.2.0 is not installed. Install the Azure Az PowerShell module with: "Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force".`, + troubleshoot: `To troubleshoot, visit https://aka.ms/azsdk/js/identity/powershellcredential/troubleshoot.`, +}; +// PowerShell Azure User not logged in error check. +const isLoginError = (err) => err.message.match(`(.*)${powerShellErrors.login}(.*)`); +// Az Module not Installed in Azure PowerShell check. +const isNotInstalledError = (err) => err.message.match(powerShellErrors.installed); +/** + * The PowerShell commands to be tried, in order. + * + * @internal + */ +export const commandStack = [formatCommand("pwsh")]; +if (isWindows) { + commandStack.push(formatCommand("powershell")); +} +/** + * This credential will use the currently logged-in user information from the + * Azure PowerShell module. To do so, it will read the user access token and + * expire time with Azure PowerShell command `Get-AzAccessToken -ResourceUrl {ResourceScope}` + */ +export class AzurePowerShellCredential { + /** + * Creates an instance of the {@link AzurePowerShellCredential}. + * + * To use this credential: + * - Install the Azure Az PowerShell module with: + * `Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force`. + * - You have already logged in to Azure PowerShell using the command + * `Connect-AzAccount` from the command line. + * + * @param options - Options, to optionally allow multi-tenant requests. + */ + constructor(options) { + if (options === null || options === void 0 ? void 0 : options.tenantId) { + checkTenantId(logger, options === null || options === void 0 ? void 0 : options.tenantId); + this.tenantId = options === null || options === void 0 ? void 0 : options.tenantId; + } + this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants); + this.timeout = options === null || options === void 0 ? void 0 : options.processTimeoutInMs; + } + /** + * Gets the access token from Azure PowerShell + * @param resource - The resource to use when getting the token + */ + async getAzurePowerShellAccessToken(resource, tenantId, timeout) { + // Clone the stack to avoid mutating it while iterating + for (const powerShellCommand of [...commandStack]) { + try { + await runCommands([[powerShellCommand, "/?"]], timeout); + } + catch (e) { + // Remove this credential from the original stack so that we don't try it again. + commandStack.shift(); + continue; + } + const results = await runCommands([ + [ + powerShellCommand, + "-NoProfile", + "-NonInteractive", + "-Command", + ` + $tenantId = "${tenantId !== null && tenantId !== void 0 ? tenantId : ""}" + $m = Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru + $useSecureString = $m.Version -ge [version]'2.17.0' + + $params = @{ + ResourceUrl = "${resource}" + } + + if ($tenantId.Length -gt 0) { + $params["TenantId"] = $tenantId + } + + if ($useSecureString) { + $params["AsSecureString"] = $true + } + + $token = Get-AzAccessToken @params + + $result = New-Object -TypeName PSObject + $result | Add-Member -MemberType NoteProperty -Name ExpiresOn -Value $token.ExpiresOn + if ($useSecureString) { + $result | Add-Member -MemberType NoteProperty -Name Token -Value (ConvertFrom-SecureString -AsPlainText $token.Token) + } else { + $result | Add-Member -MemberType NoteProperty -Name Token -Value $token.Token + } + + Write-Output (ConvertTo-Json $result) + `, + ], + ]); + const result = results[0]; + return parseJsonToken(result); + } + throw new Error(`Unable to execute PowerShell. Ensure that it is installed in your system`); + } + /** + * Authenticates with Microsoft Entra ID and returns an access token if successful. + * If the authentication cannot be performed through PowerShell, a {@link CredentialUnavailableError} will be thrown. + * + * @param scopes - The list of scopes for which the token will have access. + * @param options - The options used to configure any requests this TokenCredential implementation might make. + */ + async getToken(scopes, options = {}) { + return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async () => { + const tenantId = processMultiTenantRequest(this.tenantId, options, this.additionallyAllowedTenantIds); + const scope = typeof scopes === "string" ? scopes : scopes[0]; + if (tenantId) { + checkTenantId(logger, tenantId); + } + try { + ensureValidScopeForDevTimeCreds(scope, logger); + logger.getToken.info(`Using the scope ${scope}`); + const resource = getScopeResource(scope); + const response = await this.getAzurePowerShellAccessToken(resource, tenantId, this.timeout); + logger.getToken.info(formatSuccess(scopes)); + return { + token: response.Token, + expiresOnTimestamp: new Date(response.ExpiresOn).getTime(), + tokenType: "Bearer", + }; + } + catch (err) { + if (isNotInstalledError(err)) { + const error = new CredentialUnavailableError(powerShellPublicErrorMessages.installed); + logger.getToken.info(formatError(scope, error)); + throw error; + } + else if (isLoginError(err)) { + const error = new CredentialUnavailableError(powerShellPublicErrorMessages.login); + logger.getToken.info(formatError(scope, error)); + throw error; + } + const error = new CredentialUnavailableError(`${err}. ${powerShellPublicErrorMessages.troubleshoot}`); + logger.getToken.info(formatError(scope, error)); + throw error; + } + }); + } +} +/** + * + * @internal + */ +export async function parseJsonToken(result) { + const jsonRegex = /{[^{}]*}/g; + const matches = result.match(jsonRegex); + let resultWithoutToken = result; + if (matches) { + try { + for (const item of matches) { + try { + const jsonContent = JSON.parse(item); + if (jsonContent === null || jsonContent === void 0 ? void 0 : jsonContent.Token) { + resultWithoutToken = resultWithoutToken.replace(item, ""); + if (resultWithoutToken) { + logger.getToken.warning(resultWithoutToken); + } + return jsonContent; + } + } + catch (e) { + continue; + } + } + } + catch (e) { + throw new Error(`Unable to parse the output of PowerShell. Received output: ${result}`); + } + } + throw new Error(`No access token found in the output. Received output: ${result}`); +} +//# sourceMappingURL=azurePowerShellCredential.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/chainedTokenCredential.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/chainedTokenCredential.js new file mode 100644 index 00000000..030bb403 --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/chainedTokenCredential.js @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { AggregateAuthenticationError, CredentialUnavailableError } from "../errors.js"; +import { credentialLogger, formatError, formatSuccess } from "../util/logging.js"; +import { tracingClient } from "../util/tracing.js"; +/** + * @internal + */ +export const logger = credentialLogger("ChainedTokenCredential"); +/** + * Enables multiple `TokenCredential` implementations to be tried in order until + * one of the getToken methods returns an access token. For more information, see + * [ChainedTokenCredential overview](https://aka.ms/azsdk/js/identity/credential-chains#use-chainedtokencredential-for-granularity). + */ +export class ChainedTokenCredential { + /** + * Creates an instance of ChainedTokenCredential using the given credentials. + * + * @param sources - `TokenCredential` implementations to be tried in order. + * + * Example usage: + * ```ts snippet:chained_token_credential_example + * import { ClientSecretCredential, ChainedTokenCredential } from "@azure/identity"; + * + * const tenantId = ""; + * const clientId = ""; + * const clientSecret = ""; + * const anotherClientId = ""; + * const anotherSecret = ""; + * + * const firstCredential = new ClientSecretCredential(tenantId, clientId, clientSecret); + * const secondCredential = new ClientSecretCredential(tenantId, anotherClientId, anotherSecret); + * + * const credentialChain = new ChainedTokenCredential(firstCredential, secondCredential); + * ``` + */ + constructor(...sources) { + this._sources = []; + this._sources = sources; + } + /** + * Returns the first access token returned by one of the chained + * `TokenCredential` implementations. Throws an {@link AggregateAuthenticationError} + * when one or more credentials throws an {@link AuthenticationError} and + * no credentials have returned an access token. + * + * This method is called automatically by Azure SDK client libraries. You may call this method + * directly, but you must also handle token caching and token refreshing. + * + * @param scopes - The list of scopes for which the token will have access. + * @param options - The options used to configure any requests this + * `TokenCredential` implementation might make. + */ + async getToken(scopes, options = {}) { + const { token } = await this.getTokenInternal(scopes, options); + return token; + } + async getTokenInternal(scopes, options = {}) { + let token = null; + let successfulCredential; + const errors = []; + return tracingClient.withSpan("ChainedTokenCredential.getToken", options, async (updatedOptions) => { + for (let i = 0; i < this._sources.length && token === null; i++) { + try { + token = await this._sources[i].getToken(scopes, updatedOptions); + successfulCredential = this._sources[i]; + } + catch (err) { + if (err.name === "CredentialUnavailableError" || + err.name === "AuthenticationRequiredError") { + errors.push(err); + } + else { + logger.getToken.info(formatError(scopes, err)); + throw err; + } + } + } + if (!token && errors.length > 0) { + const err = new AggregateAuthenticationError(errors, "ChainedTokenCredential authentication failed."); + logger.getToken.info(formatError(scopes, err)); + throw err; + } + logger.getToken.info(`Result for ${successfulCredential.constructor.name}: ${formatSuccess(scopes)}`); + if (token === null) { + throw new CredentialUnavailableError("Failed to retrieve a valid token"); + } + return { token, successfulCredential }; + }); + } +} +//# sourceMappingURL=chainedTokenCredential.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/clientAssertionCredential.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/clientAssertionCredential.js new file mode 100644 index 00000000..a5071d47 --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/clientAssertionCredential.js @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { createMsalClient } from "../msal/nodeFlows/msalClient.js"; +import { processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, } from "../util/tenantIdUtils.js"; +import { CredentialUnavailableError } from "../errors.js"; +import { credentialLogger } from "../util/logging.js"; +import { tracingClient } from "../util/tracing.js"; +const logger = credentialLogger("ClientAssertionCredential"); +/** + * Authenticates a service principal with a JWT assertion. + */ +export class ClientAssertionCredential { + /** + * Creates an instance of the ClientAssertionCredential with the details + * needed to authenticate against Microsoft Entra ID with a client + * assertion provided by the developer through the `getAssertion` function parameter. + * + * @param tenantId - The Microsoft Entra tenant (directory) ID. + * @param clientId - The client (application) ID of an App Registration in the tenant. + * @param getAssertion - A function that retrieves the assertion for the credential to use. + * @param options - Options for configuring the client which makes the authentication request. + */ + constructor(tenantId, clientId, getAssertion, options = {}) { + if (!tenantId) { + throw new CredentialUnavailableError("ClientAssertionCredential: tenantId is a required parameter."); + } + if (!clientId) { + throw new CredentialUnavailableError("ClientAssertionCredential: clientId is a required parameter."); + } + if (!getAssertion) { + throw new CredentialUnavailableError("ClientAssertionCredential: clientAssertion is a required parameter."); + } + this.tenantId = tenantId; + this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants); + this.options = options; + this.getAssertion = getAssertion; + this.msalClient = createMsalClient(clientId, tenantId, Object.assign(Object.assign({}, options), { logger, tokenCredentialOptions: this.options })); + } + /** + * Authenticates with Microsoft Entra ID and returns an access token if successful. + * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure. + * + * @param scopes - The list of scopes for which the token will have access. + * @param options - The options used to configure any requests this + * TokenCredential implementation might make. + */ + async getToken(scopes, options = {}) { + return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async (newOptions) => { + newOptions.tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds, logger); + const arrayScopes = Array.isArray(scopes) ? scopes : [scopes]; + return this.msalClient.getTokenByClientAssertion(arrayScopes, this.getAssertion, newOptions); + }); + } +} +//# sourceMappingURL=clientAssertionCredential.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/clientCertificateCredential.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/clientCertificateCredential.js new file mode 100644 index 00000000..be43e121 --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/clientCertificateCredential.js @@ -0,0 +1,128 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { createMsalClient } from "../msal/nodeFlows/msalClient.js"; +import { createHash, createPrivateKey } from "node:crypto"; +import { processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, } from "../util/tenantIdUtils.js"; +import { credentialLogger } from "../util/logging.js"; +import { readFile } from "node:fs/promises"; +import { tracingClient } from "../util/tracing.js"; +const credentialName = "ClientCertificateCredential"; +const logger = credentialLogger(credentialName); +/** + * Enables authentication to Microsoft Entra ID using a PEM-encoded + * certificate that is assigned to an App Registration. More information + * on how to configure certificate authentication can be found here: + * + * https://learn.microsoft.com/azure/active-directory/develop/active-directory-certificate-credentials#register-your-certificate-with-azure-ad + * + */ +export class ClientCertificateCredential { + constructor(tenantId, clientId, certificatePathOrConfiguration, options = {}) { + if (!tenantId || !clientId) { + throw new Error(`${credentialName}: tenantId and clientId are required parameters.`); + } + this.tenantId = tenantId; + this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants); + this.sendCertificateChain = options.sendCertificateChain; + this.certificateConfiguration = Object.assign({}, (typeof certificatePathOrConfiguration === "string" + ? { + certificatePath: certificatePathOrConfiguration, + } + : certificatePathOrConfiguration)); + const certificate = this.certificateConfiguration + .certificate; + const certificatePath = this.certificateConfiguration + .certificatePath; + if (!this.certificateConfiguration || !(certificate || certificatePath)) { + throw new Error(`${credentialName}: Provide either a PEM certificate in string form, or the path to that certificate in the filesystem. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`); + } + if (certificate && certificatePath) { + throw new Error(`${credentialName}: To avoid unexpected behaviors, providing both the contents of a PEM certificate and the path to a PEM certificate is forbidden. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`); + } + this.msalClient = createMsalClient(clientId, tenantId, Object.assign(Object.assign({}, options), { logger, tokenCredentialOptions: options })); + } + /** + * Authenticates with Microsoft Entra ID and returns an access token if successful. + * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure. + * + * @param scopes - The list of scopes for which the token will have access. + * @param options - The options used to configure any requests this + * TokenCredential implementation might make. + */ + async getToken(scopes, options = {}) { + return tracingClient.withSpan(`${credentialName}.getToken`, options, async (newOptions) => { + newOptions.tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds, logger); + const arrayScopes = Array.isArray(scopes) ? scopes : [scopes]; + const certificate = await this.buildClientCertificate(); + return this.msalClient.getTokenByClientCertificate(arrayScopes, certificate, newOptions); + }); + } + async buildClientCertificate() { + var _a; + const parts = await parseCertificate(this.certificateConfiguration, (_a = this.sendCertificateChain) !== null && _a !== void 0 ? _a : false); + let privateKey; + if (this.certificateConfiguration.certificatePassword !== undefined) { + privateKey = createPrivateKey({ + key: parts.certificateContents, + passphrase: this.certificateConfiguration.certificatePassword, + format: "pem", + }) + .export({ + format: "pem", + type: "pkcs8", + }) + .toString(); + } + else { + privateKey = parts.certificateContents; + } + return { + thumbprint: parts.thumbprint, + thumbprintSha256: parts.thumbprintSha256, + privateKey, + x5c: parts.x5c, + }; + } +} +/** + * Parses a certificate into its relevant parts + * + * @param certificateConfiguration - The certificate contents or path to the certificate + * @param sendCertificateChain - true if the entire certificate chain should be sent for SNI, false otherwise + * @returns The parsed certificate parts and the certificate contents + */ +export async function parseCertificate(certificateConfiguration, sendCertificateChain) { + const certificate = certificateConfiguration.certificate; + const certificatePath = certificateConfiguration + .certificatePath; + const certificateContents = certificate || (await readFile(certificatePath, "utf8")); + const x5c = sendCertificateChain ? certificateContents : undefined; + const certificatePattern = /(-+BEGIN CERTIFICATE-+)(\n\r?|\r\n?)([A-Za-z0-9+/\n\r]+=*)(\n\r?|\r\n?)(-+END CERTIFICATE-+)/g; + const publicKeys = []; + // Match all possible certificates, in the order they are in the file. These will form the chain that is used for x5c + let match; + do { + match = certificatePattern.exec(certificateContents); + if (match) { + publicKeys.push(match[3]); + } + } while (match); + if (publicKeys.length === 0) { + throw new Error("The file at the specified path does not contain a PEM-encoded certificate."); + } + const thumbprint = createHash("sha1") + .update(Buffer.from(publicKeys[0], "base64")) + .digest("hex") + .toUpperCase(); + const thumbprintSha256 = createHash("sha256") + .update(Buffer.from(publicKeys[0], "base64")) + .digest("hex") + .toUpperCase(); + return { + certificateContents, + thumbprintSha256, + thumbprint, + x5c, + }; +} +//# sourceMappingURL=clientCertificateCredential.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/clientSecretCredential.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/clientSecretCredential.js new file mode 100644 index 00000000..c6a68a18 --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/clientSecretCredential.js @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { createMsalClient } from "../msal/nodeFlows/msalClient.js"; +import { processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, } from "../util/tenantIdUtils.js"; +import { CredentialUnavailableError } from "../errors.js"; +import { credentialLogger } from "../util/logging.js"; +import { ensureScopes } from "../util/scopeUtils.js"; +import { tracingClient } from "../util/tracing.js"; +const logger = credentialLogger("ClientSecretCredential"); +/** + * Enables authentication to Microsoft Entra ID using a client secret + * that was generated for an App Registration. More information on how + * to configure a client secret can be found here: + * + * https://learn.microsoft.com/entra/identity-platform/quickstart-configure-app-access-web-apis#add-credentials-to-your-web-application + * + */ +export class ClientSecretCredential { + /** + * Creates an instance of the ClientSecretCredential with the details + * needed to authenticate against Microsoft Entra ID with a client + * secret. + * + * @param tenantId - The Microsoft Entra tenant (directory) ID. + * @param clientId - The client (application) ID of an App Registration in the tenant. + * @param clientSecret - A client secret that was generated for the App Registration. + * @param options - Options for configuring the client which makes the authentication request. + */ + constructor(tenantId, clientId, clientSecret, options = {}) { + if (!tenantId) { + throw new CredentialUnavailableError("ClientSecretCredential: tenantId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot."); + } + if (!clientId) { + throw new CredentialUnavailableError("ClientSecretCredential: clientId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot."); + } + if (!clientSecret) { + throw new CredentialUnavailableError("ClientSecretCredential: clientSecret is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot."); + } + this.clientSecret = clientSecret; + this.tenantId = tenantId; + this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants); + this.msalClient = createMsalClient(clientId, tenantId, Object.assign(Object.assign({}, options), { logger, tokenCredentialOptions: options })); + } + /** + * Authenticates with Microsoft Entra ID and returns an access token if successful. + * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure. + * + * @param scopes - The list of scopes for which the token will have access. + * @param options - The options used to configure any requests this + * TokenCredential implementation might make. + */ + async getToken(scopes, options = {}) { + return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async (newOptions) => { + newOptions.tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds, logger); + const arrayScopes = ensureScopes(scopes); + return this.msalClient.getTokenByClientSecret(arrayScopes, this.clientSecret, newOptions); + }); + } +} +//# sourceMappingURL=clientSecretCredential.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/defaultAzureCredential.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/defaultAzureCredential.js new file mode 100644 index 00000000..b8df5544 --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/defaultAzureCredential.js @@ -0,0 +1,196 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { ManagedIdentityCredential } from "./managedIdentityCredential/index.js"; +import { AzureCliCredential } from "./azureCliCredential.js"; +import { AzureDeveloperCliCredential } from "./azureDeveloperCliCredential.js"; +import { AzurePowerShellCredential } from "./azurePowerShellCredential.js"; +import { ChainedTokenCredential } from "./chainedTokenCredential.js"; +import { EnvironmentCredential } from "./environmentCredential.js"; +import { WorkloadIdentityCredential } from "./workloadIdentityCredential.js"; +import { credentialLogger } from "../util/logging.js"; +const logger = credentialLogger("DefaultAzureCredential"); +/** + * Creates a {@link ManagedIdentityCredential} from the provided options. + * @param options - Options to configure the credential. + * + * @internal + */ +export function createDefaultManagedIdentityCredential(options = {}) { + var _a, _b, _c, _d; + (_a = options.retryOptions) !== null && _a !== void 0 ? _a : (options.retryOptions = { + maxRetries: 5, + retryDelayInMs: 800, + }); + const managedIdentityClientId = (_b = options === null || options === void 0 ? void 0 : options.managedIdentityClientId) !== null && _b !== void 0 ? _b : process.env.AZURE_CLIENT_ID; + const workloadIdentityClientId = (_c = options === null || options === void 0 ? void 0 : options.workloadIdentityClientId) !== null && _c !== void 0 ? _c : managedIdentityClientId; + const managedResourceId = options === null || options === void 0 ? void 0 : options.managedIdentityResourceId; + const workloadFile = process.env.AZURE_FEDERATED_TOKEN_FILE; + const tenantId = (_d = options === null || options === void 0 ? void 0 : options.tenantId) !== null && _d !== void 0 ? _d : process.env.AZURE_TENANT_ID; + if (managedResourceId) { + const managedIdentityResourceIdOptions = Object.assign(Object.assign({}, options), { resourceId: managedResourceId }); + return new ManagedIdentityCredential(managedIdentityResourceIdOptions); + } + if (workloadFile && workloadIdentityClientId) { + const workloadIdentityCredentialOptions = Object.assign(Object.assign({}, options), { tenantId: tenantId }); + return new ManagedIdentityCredential(workloadIdentityClientId, workloadIdentityCredentialOptions); + } + if (managedIdentityClientId) { + const managedIdentityClientOptions = Object.assign(Object.assign({}, options), { clientId: managedIdentityClientId }); + return new ManagedIdentityCredential(managedIdentityClientOptions); + } + // We may be able to return a UnavailableCredential here, but that may be a breaking change + return new ManagedIdentityCredential(options); +} +/** + * Creates a {@link WorkloadIdentityCredential} from the provided options. + * @param options - Options to configure the credential. + * + * @internal + */ +function createDefaultWorkloadIdentityCredential(options) { + var _a, _b, _c; + const managedIdentityClientId = (_a = options === null || options === void 0 ? void 0 : options.managedIdentityClientId) !== null && _a !== void 0 ? _a : process.env.AZURE_CLIENT_ID; + const workloadIdentityClientId = (_b = options === null || options === void 0 ? void 0 : options.workloadIdentityClientId) !== null && _b !== void 0 ? _b : managedIdentityClientId; + const workloadFile = process.env.AZURE_FEDERATED_TOKEN_FILE; + const tenantId = (_c = options === null || options === void 0 ? void 0 : options.tenantId) !== null && _c !== void 0 ? _c : process.env.AZURE_TENANT_ID; + if (workloadFile && workloadIdentityClientId) { + const workloadIdentityCredentialOptions = Object.assign(Object.assign({}, options), { tenantId, clientId: workloadIdentityClientId, tokenFilePath: workloadFile }); + return new WorkloadIdentityCredential(workloadIdentityCredentialOptions); + } + if (tenantId) { + const workloadIdentityClientTenantOptions = Object.assign(Object.assign({}, options), { tenantId }); + return new WorkloadIdentityCredential(workloadIdentityClientTenantOptions); + } + // We may be able to return a UnavailableCredential here, but that may be a breaking change + return new WorkloadIdentityCredential(options); +} +/** + * Creates a {@link AzureDeveloperCliCredential} from the provided options. + * @param options - Options to configure the credential. + * + * @internal + */ +function createDefaultAzureDeveloperCliCredential(options = {}) { + const processTimeoutInMs = options.processTimeoutInMs; + return new AzureDeveloperCliCredential(Object.assign({ processTimeoutInMs }, options)); +} +/** + * Creates a {@link AzureCliCredential} from the provided options. + * @param options - Options to configure the credential. + * + * @internal + */ +function createDefaultAzureCliCredential(options = {}) { + const processTimeoutInMs = options.processTimeoutInMs; + return new AzureCliCredential(Object.assign({ processTimeoutInMs }, options)); +} +/** + * Creates a {@link AzurePowerShellCredential} from the provided options. + * @param options - Options to configure the credential. + * + * @internal + */ +function createDefaultAzurePowershellCredential(options = {}) { + const processTimeoutInMs = options.processTimeoutInMs; + return new AzurePowerShellCredential(Object.assign({ processTimeoutInMs }, options)); +} +/** + * Creates an {@link EnvironmentCredential} from the provided options. + * @param options - Options to configure the credential. + * + * @internal + */ +export function createEnvironmentCredential(options = {}) { + return new EnvironmentCredential(options); +} +/** + * A no-op credential that logs the reason it was skipped if getToken is called. + * @internal + */ +export class UnavailableDefaultCredential { + constructor(credentialName, message) { + this.credentialName = credentialName; + this.credentialUnavailableErrorMessage = message; + } + getToken() { + logger.getToken.info(`Skipping ${this.credentialName}, reason: ${this.credentialUnavailableErrorMessage}`); + return Promise.resolve(null); + } +} +/** + * Provides a default {@link ChainedTokenCredential} configuration that works for most + * applications that use Azure SDK client libraries. For more information, see + * [DefaultAzureCredential overview](https://aka.ms/azsdk/js/identity/credential-chains#use-defaultazurecredential-for-flexibility). + * + * The following credential types will be tried, in order: + * + * - {@link EnvironmentCredential} + * - {@link WorkloadIdentityCredential} + * - {@link ManagedIdentityCredential} + * - {@link AzureCliCredential} + * - {@link AzurePowerShellCredential} + * - {@link AzureDeveloperCliCredential} + * + * Consult the documentation of these credential types for more information + * on how they attempt authentication. + */ +export class DefaultAzureCredential extends ChainedTokenCredential { + constructor(options) { + // If AZURE_TOKEN_CREDENTIALS is not set, use the default credential chain. + const azureTokenCredentials = process.env.AZURE_TOKEN_CREDENTIALS + ? process.env.AZURE_TOKEN_CREDENTIALS.trim().toLowerCase() + : undefined; + const devCredentialFunctions = [ + createDefaultAzureCliCredential, + createDefaultAzurePowershellCredential, + createDefaultAzureDeveloperCliCredential, + ]; + const prodCredentialFunctions = [ + createEnvironmentCredential, + createDefaultWorkloadIdentityCredential, + createDefaultManagedIdentityCredential, + ]; + let credentialFunctions = []; + // If AZURE_TOKEN_CREDENTIALS is set, use it to determine which credentials to use. + // The value of AZURE_TOKEN_CREDENTIALS should be either "dev" or "prod". + if (azureTokenCredentials) { + switch (azureTokenCredentials) { + case "dev": + // If AZURE_TOKEN_CREDENTIALS is set to "dev", use the developer tool-based credential chain. + credentialFunctions = devCredentialFunctions; + break; + case "prod": + // If AZURE_TOKEN_CREDENTIALS is set to "prod", use the production credential chain. + credentialFunctions = prodCredentialFunctions; + break; + default: { + // If AZURE_TOKEN_CREDENTIALS is set to an unsupported value, throw an error. + // We will throw an error here to prevent the creation of the DefaultAzureCredential. + const errorMessage = `Invalid value for AZURE_TOKEN_CREDENTIALS = ${process.env.AZURE_TOKEN_CREDENTIALS}. Valid values are 'prod' or 'dev'.`; + logger.warning(errorMessage); + throw new Error(errorMessage); + } + } + } + else { + // If AZURE_TOKEN_CREDENTIALS is not set, use the default credential chain. + credentialFunctions = [...prodCredentialFunctions, ...devCredentialFunctions]; + } + // Errors from individual credentials should not be thrown in the DefaultAzureCredential constructor, instead throwing on getToken() which is handled by ChainedTokenCredential. + // When adding new credentials to the default chain, consider: + // 1. Making the constructor parameters required and explicit + // 2. Validating any required parameters in the factory function + // 3. Returning a UnavailableDefaultCredential from the factory function if a credential is unavailable for any reason + const credentials = credentialFunctions.map((createCredentialFn) => { + try { + return createCredentialFn(options); + } + catch (err) { + logger.warning(`Skipped ${createCredentialFn.name} because of an error creating the credential: ${err}`); + return new UnavailableDefaultCredential(createCredentialFn.name, err.message); + } + }); + super(...credentials); + } +} +//# sourceMappingURL=defaultAzureCredential.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/deviceCodeCredential.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/deviceCodeCredential.js new file mode 100644 index 00000000..e8e95f90 --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/deviceCodeCredential.js @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, resolveTenantId, } from "../util/tenantIdUtils.js"; +import { credentialLogger } from "../util/logging.js"; +import { ensureScopes } from "../util/scopeUtils.js"; +import { tracingClient } from "../util/tracing.js"; +import { createMsalClient } from "../msal/nodeFlows/msalClient.js"; +import { DeveloperSignOnClientId } from "../constants.js"; +const logger = credentialLogger("DeviceCodeCredential"); +/** + * Method that logs the user code from the DeviceCodeCredential. + * @param deviceCodeInfo - The device code. + */ +export function defaultDeviceCodePromptCallback(deviceCodeInfo) { + console.log(deviceCodeInfo.message); +} +/** + * Enables authentication to Microsoft Entra ID using a device code + * that the user can enter into https://microsoft.com/devicelogin. + */ +export class DeviceCodeCredential { + /** + * Creates an instance of DeviceCodeCredential with the details needed + * to initiate the device code authorization flow with Microsoft Entra ID. + * + * A message will be logged, giving users a code that they can use to authenticate once they go to https://microsoft.com/devicelogin + * + * Developers can configure how this message is shown by passing a custom `userPromptCallback`: + * + * ```ts snippet:device_code_credential_example + * import { DeviceCodeCredential } from "@azure/identity"; + * + * const credential = new DeviceCodeCredential({ + * tenantId: process.env.AZURE_TENANT_ID, + * clientId: process.env.AZURE_CLIENT_ID, + * userPromptCallback: (info) => { + * console.log("CUSTOMIZED PROMPT CALLBACK", info.message); + * }, + * }); + * ``` + * + * @param options - Options for configuring the client which makes the authentication requests. + */ + constructor(options) { + var _a, _b; + this.tenantId = options === null || options === void 0 ? void 0 : options.tenantId; + this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants); + const clientId = (_a = options === null || options === void 0 ? void 0 : options.clientId) !== null && _a !== void 0 ? _a : DeveloperSignOnClientId; + const tenantId = resolveTenantId(logger, options === null || options === void 0 ? void 0 : options.tenantId, clientId); + this.userPromptCallback = (_b = options === null || options === void 0 ? void 0 : options.userPromptCallback) !== null && _b !== void 0 ? _b : defaultDeviceCodePromptCallback; + this.msalClient = createMsalClient(clientId, tenantId, Object.assign(Object.assign({}, options), { logger, tokenCredentialOptions: options || {} })); + this.disableAutomaticAuthentication = options === null || options === void 0 ? void 0 : options.disableAutomaticAuthentication; + } + /** + * Authenticates with Microsoft Entra ID and returns an access token if successful. + * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure. + * + * If the user provided the option `disableAutomaticAuthentication`, + * once the token can't be retrieved silently, + * this method won't attempt to request user interaction to retrieve the token. + * + * @param scopes - The list of scopes for which the token will have access. + * @param options - The options used to configure any requests this + * TokenCredential implementation might make. + */ + async getToken(scopes, options = {}) { + return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async (newOptions) => { + newOptions.tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds, logger); + const arrayScopes = ensureScopes(scopes); + return this.msalClient.getTokenByDeviceCode(arrayScopes, this.userPromptCallback, Object.assign(Object.assign({}, newOptions), { disableAutomaticAuthentication: this.disableAutomaticAuthentication })); + }); + } + /** + * Authenticates with Microsoft Entra ID and returns an access token if successful. + * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure. + * + * If the token can't be retrieved silently, this method will always generate a challenge for the user. + * + * @param scopes - The list of scopes for which the token will have access. + * @param options - The options used to configure any requests this + * TokenCredential implementation might make. + */ + async authenticate(scopes, options = {}) { + return tracingClient.withSpan(`${this.constructor.name}.authenticate`, options, async (newOptions) => { + const arrayScopes = Array.isArray(scopes) ? scopes : [scopes]; + await this.msalClient.getTokenByDeviceCode(arrayScopes, this.userPromptCallback, Object.assign(Object.assign({}, newOptions), { disableAutomaticAuthentication: false })); + return this.msalClient.getActiveAccount(); + }); + } +} +//# sourceMappingURL=deviceCodeCredential.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/environmentCredential.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/environmentCredential.js new file mode 100644 index 00000000..365c07f3 --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/environmentCredential.js @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { AuthenticationError, CredentialUnavailableError } from "../errors.js"; +import { credentialLogger, formatError, formatSuccess, processEnvVars } from "../util/logging.js"; +import { ClientCertificateCredential } from "./clientCertificateCredential.js"; +import { ClientSecretCredential } from "./clientSecretCredential.js"; +import { UsernamePasswordCredential } from "./usernamePasswordCredential.js"; +import { checkTenantId } from "../util/tenantIdUtils.js"; +import { tracingClient } from "../util/tracing.js"; +/** + * Contains the list of all supported environment variable names so that an + * appropriate error message can be generated when no credentials can be + * configured. + * + * @internal + */ +export const AllSupportedEnvironmentVariables = [ + "AZURE_TENANT_ID", + "AZURE_CLIENT_ID", + "AZURE_CLIENT_SECRET", + "AZURE_CLIENT_CERTIFICATE_PATH", + "AZURE_CLIENT_CERTIFICATE_PASSWORD", + "AZURE_USERNAME", + "AZURE_PASSWORD", + "AZURE_ADDITIONALLY_ALLOWED_TENANTS", + "AZURE_CLIENT_SEND_CERTIFICATE_CHAIN", +]; +function getAdditionallyAllowedTenants() { + var _a; + const additionallyAllowedValues = (_a = process.env.AZURE_ADDITIONALLY_ALLOWED_TENANTS) !== null && _a !== void 0 ? _a : ""; + return additionallyAllowedValues.split(";"); +} +const credentialName = "EnvironmentCredential"; +const logger = credentialLogger(credentialName); +export function getSendCertificateChain() { + var _a; + const sendCertificateChain = ((_a = process.env.AZURE_CLIENT_SEND_CERTIFICATE_CHAIN) !== null && _a !== void 0 ? _a : "").toLowerCase(); + const result = sendCertificateChain === "true" || sendCertificateChain === "1"; + logger.verbose(`AZURE_CLIENT_SEND_CERTIFICATE_CHAIN: ${process.env.AZURE_CLIENT_SEND_CERTIFICATE_CHAIN}; sendCertificateChain: ${result}`); + return result; +} +/** + * Enables authentication to Microsoft Entra ID using a client secret or certificate. + */ +export class EnvironmentCredential { + /** + * Creates an instance of the EnvironmentCredential class and decides what credential to use depending on the available environment variables. + * + * Required environment variables: + * - `AZURE_TENANT_ID`: The Microsoft Entra tenant (directory) ID. + * - `AZURE_CLIENT_ID`: The client (application) ID of an App Registration in the tenant. + * + * If setting the AZURE_TENANT_ID, then you can also set the additionally allowed tenants + * - `AZURE_ADDITIONALLY_ALLOWED_TENANTS`: For multi-tenant applications, specifies additional tenants for which the credential may acquire tokens with a single semicolon delimited string. Use * to allow all tenants. + * + * Environment variables used for client credential authentication: + * - `AZURE_CLIENT_SECRET`: A client secret that was generated for the App Registration. + * - `AZURE_CLIENT_CERTIFICATE_PATH`: The path to a PEM certificate to use during the authentication, instead of the client secret. + * - `AZURE_CLIENT_CERTIFICATE_PASSWORD`: (optional) password for the certificate file. + * - `AZURE_CLIENT_SEND_CERTIFICATE_CHAIN`: (optional) indicates that the certificate chain should be set in x5c header to support subject name / issuer based authentication. + * + * Username and password authentication is deprecated, since it doesn't support multifactor authentication (MFA). See https://aka.ms/azsdk/identity/mfa for more details. Users can still provide environment variables for this authentication method: + * - `AZURE_USERNAME`: Username to authenticate with. + * - `AZURE_PASSWORD`: Password to authenticate with. + * + * If the environment variables required to perform the authentication are missing, a {@link CredentialUnavailableError} will be thrown. + * If the authentication fails, or if there's an unknown error, an {@link AuthenticationError} will be thrown. + * + * @param options - Options for configuring the client which makes the authentication request. + */ + constructor(options) { + // Keep track of any missing environment variables for error details + this._credential = undefined; + const assigned = processEnvVars(AllSupportedEnvironmentVariables).assigned.join(", "); + logger.info(`Found the following environment variables: ${assigned}`); + const tenantId = process.env.AZURE_TENANT_ID, clientId = process.env.AZURE_CLIENT_ID, clientSecret = process.env.AZURE_CLIENT_SECRET; + const additionallyAllowedTenantIds = getAdditionallyAllowedTenants(); + const sendCertificateChain = getSendCertificateChain(); + const newOptions = Object.assign(Object.assign({}, options), { additionallyAllowedTenantIds, sendCertificateChain }); + if (tenantId) { + checkTenantId(logger, tenantId); + } + if (tenantId && clientId && clientSecret) { + logger.info(`Invoking ClientSecretCredential with tenant ID: ${tenantId}, clientId: ${clientId} and clientSecret: [REDACTED]`); + this._credential = new ClientSecretCredential(tenantId, clientId, clientSecret, newOptions); + return; + } + const certificatePath = process.env.AZURE_CLIENT_CERTIFICATE_PATH; + const certificatePassword = process.env.AZURE_CLIENT_CERTIFICATE_PASSWORD; + if (tenantId && clientId && certificatePath) { + logger.info(`Invoking ClientCertificateCredential with tenant ID: ${tenantId}, clientId: ${clientId} and certificatePath: ${certificatePath}`); + this._credential = new ClientCertificateCredential(tenantId, clientId, { certificatePath, certificatePassword }, newOptions); + return; + } + const username = process.env.AZURE_USERNAME; + const password = process.env.AZURE_PASSWORD; + if (tenantId && clientId && username && password) { + logger.info(`Invoking UsernamePasswordCredential with tenant ID: ${tenantId}, clientId: ${clientId} and username: ${username}`); + logger.warning("Environment is configured to use username and password authentication. This authentication method is deprecated, as it doesn't support multifactor authentication (MFA). Use a more secure credential. For more details, see https://aka.ms/azsdk/identity/mfa."); + this._credential = new UsernamePasswordCredential(tenantId, clientId, username, password, newOptions); + } + } + /** + * Authenticates with Microsoft Entra ID and returns an access token if successful. + * + * @param scopes - The list of scopes for which the token will have access. + * @param options - Optional parameters. See {@link GetTokenOptions}. + */ + async getToken(scopes, options = {}) { + return tracingClient.withSpan(`${credentialName}.getToken`, options, async (newOptions) => { + if (this._credential) { + try { + const result = await this._credential.getToken(scopes, newOptions); + logger.getToken.info(formatSuccess(scopes)); + return result; + } + catch (err) { + const authenticationError = new AuthenticationError(400, { + error: `${credentialName} authentication failed. To troubleshoot, visit https://aka.ms/azsdk/js/identity/environmentcredential/troubleshoot.`, + error_description: err.message.toString().split("More details:").join(""), + }); + logger.getToken.info(formatError(scopes, authenticationError)); + throw authenticationError; + } + } + throw new CredentialUnavailableError(`${credentialName} is unavailable. No underlying credential could be used. To troubleshoot, visit https://aka.ms/azsdk/js/identity/environmentcredential/troubleshoot.`); + }); + } +} +//# sourceMappingURL=environmentCredential.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/interactiveBrowserCredential.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/interactiveBrowserCredential.js new file mode 100644 index 00000000..0ec597f6 --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/interactiveBrowserCredential.js @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, resolveTenantId, } from "../util/tenantIdUtils.js"; +import { credentialLogger } from "../util/logging.js"; +import { ensureScopes } from "../util/scopeUtils.js"; +import { tracingClient } from "../util/tracing.js"; +import { createMsalClient } from "../msal/nodeFlows/msalClient.js"; +import { DeveloperSignOnClientId } from "../constants.js"; +const logger = credentialLogger("InteractiveBrowserCredential"); +/** + * Enables authentication to Microsoft Entra ID inside of the web browser + * using the interactive login flow. + */ +export class InteractiveBrowserCredential { + /** + * Creates an instance of InteractiveBrowserCredential with the details needed. + * + * This credential uses the [Authorization Code Flow](https://learn.microsoft.com/entra/identity-platform/v2-oauth2-auth-code-flow). + * On Node.js, it will open a browser window while it listens for a redirect response from the authentication service. + * On browsers, it authenticates via popups. The `loginStyle` optional parameter can be set to `redirect` to authenticate by redirecting the user to an Azure secure login page, which then will redirect the user back to the web application where the authentication started. + * + * For Node.js, if a `clientId` is provided, the Microsoft Entra application will need to be configured to have a "Mobile and desktop applications" redirect endpoint. + * Follow our guide on [setting up Redirect URIs for Desktop apps that calls to web APIs](https://learn.microsoft.com/entra/identity-platform/scenario-desktop-app-registration#redirect-uris). + * + * @param options - Options for configuring the client which makes the authentication requests. + */ + constructor(options) { + var _a, _b, _c, _d, _e; + this.tenantId = resolveTenantId(logger, options.tenantId, options.clientId); + this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants); + const msalClientOptions = Object.assign(Object.assign({}, options), { tokenCredentialOptions: options, logger }); + const ibcNodeOptions = options; + this.browserCustomizationOptions = ibcNodeOptions.browserCustomizationOptions; + this.loginHint = ibcNodeOptions.loginHint; + if ((_a = ibcNodeOptions === null || ibcNodeOptions === void 0 ? void 0 : ibcNodeOptions.brokerOptions) === null || _a === void 0 ? void 0 : _a.enabled) { + if (!((_b = ibcNodeOptions === null || ibcNodeOptions === void 0 ? void 0 : ibcNodeOptions.brokerOptions) === null || _b === void 0 ? void 0 : _b.parentWindowHandle)) { + throw new Error("In order to do WAM authentication, `parentWindowHandle` under `brokerOptions` is a required parameter"); + } + else { + msalClientOptions.brokerOptions = { + enabled: true, + parentWindowHandle: ibcNodeOptions.brokerOptions.parentWindowHandle, + legacyEnableMsaPassthrough: (_c = ibcNodeOptions.brokerOptions) === null || _c === void 0 ? void 0 : _c.legacyEnableMsaPassthrough, + useDefaultBrokerAccount: (_d = ibcNodeOptions.brokerOptions) === null || _d === void 0 ? void 0 : _d.useDefaultBrokerAccount, + }; + } + } + this.msalClient = createMsalClient((_e = options.clientId) !== null && _e !== void 0 ? _e : DeveloperSignOnClientId, this.tenantId, msalClientOptions); + this.disableAutomaticAuthentication = options === null || options === void 0 ? void 0 : options.disableAutomaticAuthentication; + } + /** + * Authenticates with Microsoft Entra ID and returns an access token if successful. + * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure. + * + * If the user provided the option `disableAutomaticAuthentication`, + * once the token can't be retrieved silently, + * this method won't attempt to request user interaction to retrieve the token. + * + * @param scopes - The list of scopes for which the token will have access. + * @param options - The options used to configure any requests this + * TokenCredential implementation might make. + */ + async getToken(scopes, options = {}) { + return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async (newOptions) => { + newOptions.tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds, logger); + const arrayScopes = ensureScopes(scopes); + return this.msalClient.getTokenByInteractiveRequest(arrayScopes, Object.assign(Object.assign({}, newOptions), { disableAutomaticAuthentication: this.disableAutomaticAuthentication, browserCustomizationOptions: this.browserCustomizationOptions, loginHint: this.loginHint })); + }); + } + /** + * Authenticates with Microsoft Entra ID and returns an access token if successful. + * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure. + * + * If the token can't be retrieved silently, this method will always generate a challenge for the user. + * + * On Node.js, this credential has [Proof Key for Code Exchange (PKCE)](https://datatracker.ietf.org/doc/html/rfc7636) enabled by default. + * PKCE is a security feature that mitigates authentication code interception attacks. + * + * @param scopes - The list of scopes for which the token will have access. + * @param options - The options used to configure any requests this + * TokenCredential implementation might make. + */ + async authenticate(scopes, options = {}) { + return tracingClient.withSpan(`${this.constructor.name}.authenticate`, options, async (newOptions) => { + const arrayScopes = ensureScopes(scopes); + await this.msalClient.getTokenByInteractiveRequest(arrayScopes, Object.assign(Object.assign({}, newOptions), { disableAutomaticAuthentication: false, browserCustomizationOptions: this.browserCustomizationOptions, loginHint: this.loginHint })); + return this.msalClient.getActiveAccount(); + }); + } +} +//# sourceMappingURL=interactiveBrowserCredential.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/imdsMsi.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/imdsMsi.js new file mode 100644 index 00000000..6f38f0a4 --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/imdsMsi.js @@ -0,0 +1,99 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { createHttpHeaders, createPipelineRequest } from "@azure/core-rest-pipeline"; +import { isError } from "@azure/core-util"; +import { credentialLogger } from "../../util/logging.js"; +import { mapScopesToResource } from "./utils.js"; +import { tracingClient } from "../../util/tracing.js"; +const msiName = "ManagedIdentityCredential - IMDS"; +const logger = credentialLogger(msiName); +const imdsHost = "http://169.254.169.254"; +const imdsEndpointPath = "/metadata/identity/oauth2/token"; +/** + * Generates an invalid request options to get a response quickly from IMDS endpoint. + * The response indicates the availability of IMSD service; otherwise the request would time out. + */ +function prepareInvalidRequestOptions(scopes) { + var _a; + const resource = mapScopesToResource(scopes); + if (!resource) { + throw new Error(`${msiName}: Multiple scopes are not supported.`); + } + // Pod Identity will try to process this request even if the Metadata header is missing. + // We can exclude the request query to ensure no IMDS endpoint tries to process the ping request. + const url = new URL(imdsEndpointPath, (_a = process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST) !== null && _a !== void 0 ? _a : imdsHost); + const rawHeaders = { + Accept: "application/json", + // intentionally leave out the Metadata header to invoke an error from IMDS endpoint. + }; + return { + // intentionally not including any query + url: `${url}`, + method: "GET", + headers: createHttpHeaders(rawHeaders), + }; +} +/** + * Defines how to determine whether the Azure IMDS MSI is available. + * + * Actually getting the token once we determine IMDS is available is handled by MSAL. + */ +export const imdsMsi = { + name: "imdsMsi", + async isAvailable(options) { + const { scopes, identityClient, getTokenOptions } = options; + const resource = mapScopesToResource(scopes); + if (!resource) { + logger.info(`${msiName}: Unavailable. Multiple scopes are not supported.`); + return false; + } + // if the PodIdentityEndpoint environment variable was set no need to probe the endpoint, it can be assumed to exist + if (process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST) { + return true; + } + if (!identityClient) { + throw new Error("Missing IdentityClient"); + } + const requestOptions = prepareInvalidRequestOptions(resource); + return tracingClient.withSpan("ManagedIdentityCredential-pingImdsEndpoint", getTokenOptions !== null && getTokenOptions !== void 0 ? getTokenOptions : {}, async (updatedOptions) => { + var _a, _b; + requestOptions.tracingOptions = updatedOptions.tracingOptions; + // Create a request with a timeout since we expect that + // not having a "Metadata" header should cause an error to be + // returned quickly from the endpoint, proving its availability. + const request = createPipelineRequest(requestOptions); + // Default to 1000 if the default of 0 is used. + // Negative values can still be used to disable the timeout. + request.timeout = ((_a = updatedOptions.requestOptions) === null || _a === void 0 ? void 0 : _a.timeout) || 1000; + // This MSI uses the imdsEndpoint to get the token, which only uses http:// + request.allowInsecureConnection = true; + let response; + try { + logger.info(`${msiName}: Pinging the Azure IMDS endpoint`); + response = await identityClient.sendRequest(request); + } + catch (err) { + // If the request failed, or Node.js was unable to establish a connection, + // or the host was down, we'll assume the IMDS endpoint isn't available. + if (isError(err)) { + logger.verbose(`${msiName}: Caught error ${err.name}: ${err.message}`); + } + // This is a special case for Docker Desktop which responds with a 403 with a message that contains "A socket operation was attempted to an unreachable network" or "A socket operation was attempted to an unreachable host" + // rather than just timing out, as expected. + logger.info(`${msiName}: The Azure IMDS endpoint is unavailable`); + return false; + } + if (response.status === 403) { + if ((_b = response.bodyAsText) === null || _b === void 0 ? void 0 : _b.includes("unreachable")) { + logger.info(`${msiName}: The Azure IMDS endpoint is unavailable`); + logger.info(`${msiName}: ${response.bodyAsText}`); + return false; + } + } + // If we received any response, the endpoint is available + logger.info(`${msiName}: The Azure IMDS endpoint is available`); + return true; + }); + }, +}; +//# sourceMappingURL=imdsMsi.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/imdsRetryPolicy.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/imdsRetryPolicy.js new file mode 100644 index 00000000..af248aae --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/imdsRetryPolicy.js @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { retryPolicy } from "@azure/core-rest-pipeline"; +import { calculateRetryDelay } from "@azure/core-util"; +// Matches the default retry configuration in expontentialRetryStrategy.ts +const DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 64; +/** + * An additional policy that retries on 404 errors. The default retry policy does not retry on + * 404s, but the IMDS endpoint can return 404s when the token is not yet available. This policy + * will retry on 404s with an exponential backoff. + * + * @param msiRetryConfig - The retry configuration for the MSI credential. + * @returns - The policy that will retry on 404s. + */ +export function imdsRetryPolicy(msiRetryConfig) { + return retryPolicy([ + { + name: "imdsRetryPolicy", + retry: ({ retryCount, response }) => { + if ((response === null || response === void 0 ? void 0 : response.status) !== 404) { + return { skipStrategy: true }; + } + return calculateRetryDelay(retryCount, { + retryDelayInMs: msiRetryConfig.startDelayInMs, + maxRetryDelayInMs: DEFAULT_CLIENT_MAX_RETRY_INTERVAL, + }); + }, + }, + ], { + maxRetries: msiRetryConfig.maxRetries, + }); +} +//# sourceMappingURL=imdsRetryPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/index.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/index.js new file mode 100644 index 00000000..fa64e374 --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/index.js @@ -0,0 +1,239 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { getLogLevel } from "@azure/logger"; +import { ManagedIdentityApplication } from "@azure/msal-node"; +import { IdentityClient } from "../../client/identityClient.js"; +import { AuthenticationRequiredError, CredentialUnavailableError } from "../../errors.js"; +import { getMSALLogLevel, defaultLoggerCallback } from "../../msal/utils.js"; +import { imdsRetryPolicy } from "./imdsRetryPolicy.js"; +import { formatSuccess, formatError, credentialLogger } from "../../util/logging.js"; +import { tracingClient } from "../../util/tracing.js"; +import { imdsMsi } from "./imdsMsi.js"; +import { tokenExchangeMsi } from "./tokenExchangeMsi.js"; +import { mapScopesToResource, serviceFabricErrorMessage } from "./utils.js"; +const logger = credentialLogger("ManagedIdentityCredential"); +/** + * Attempts authentication using a managed identity available at the deployment environment. + * This authentication type works in Azure VMs, App Service instances, Azure Functions applications, + * Azure Kubernetes Services, Azure Service Fabric instances and inside of the Azure Cloud Shell. + * + * More information about configuring managed identities can be found here: + * https://learn.microsoft.com/azure/active-directory/managed-identities-azure-resources/overview + */ +export class ManagedIdentityCredential { + /** + * @internal + * @hidden + */ + constructor(clientIdOrOptions, options) { + var _a, _b; + this.msiRetryConfig = { + maxRetries: 5, + startDelayInMs: 800, + intervalIncrement: 2, + }; + let _options; + if (typeof clientIdOrOptions === "string") { + this.clientId = clientIdOrOptions; + _options = options !== null && options !== void 0 ? options : {}; + } + else { + this.clientId = clientIdOrOptions === null || clientIdOrOptions === void 0 ? void 0 : clientIdOrOptions.clientId; + _options = clientIdOrOptions !== null && clientIdOrOptions !== void 0 ? clientIdOrOptions : {}; + } + this.resourceId = _options === null || _options === void 0 ? void 0 : _options.resourceId; + this.objectId = _options === null || _options === void 0 ? void 0 : _options.objectId; + // For JavaScript users. + const providedIds = [ + { key: "clientId", value: this.clientId }, + { key: "resourceId", value: this.resourceId }, + { key: "objectId", value: this.objectId }, + ].filter((id) => id.value); + if (providedIds.length > 1) { + throw new Error(`ManagedIdentityCredential: only one of 'clientId', 'resourceId', or 'objectId' can be provided. Received values: ${JSON.stringify({ clientId: this.clientId, resourceId: this.resourceId, objectId: this.objectId })}`); + } + // ManagedIdentity uses http for local requests + _options.allowInsecureConnection = true; + if (((_a = _options.retryOptions) === null || _a === void 0 ? void 0 : _a.maxRetries) !== undefined) { + this.msiRetryConfig.maxRetries = _options.retryOptions.maxRetries; + } + this.identityClient = new IdentityClient(Object.assign(Object.assign({}, _options), { additionalPolicies: [{ policy: imdsRetryPolicy(this.msiRetryConfig), position: "perCall" }] })); + this.managedIdentityApp = new ManagedIdentityApplication({ + managedIdentityIdParams: { + userAssignedClientId: this.clientId, + userAssignedResourceId: this.resourceId, + userAssignedObjectId: this.objectId, + }, + system: { + disableInternalRetries: true, + networkClient: this.identityClient, + loggerOptions: { + logLevel: getMSALLogLevel(getLogLevel()), + piiLoggingEnabled: (_b = _options.loggingOptions) === null || _b === void 0 ? void 0 : _b.enableUnsafeSupportLogging, + loggerCallback: defaultLoggerCallback(logger), + }, + }, + }); + this.isAvailableIdentityClient = new IdentityClient(Object.assign(Object.assign({}, _options), { retryOptions: { + maxRetries: 0, + } })); + const managedIdentitySource = this.managedIdentityApp.getManagedIdentitySource(); + // CloudShell MSI will ignore any user-assigned identity passed as parameters. To avoid confusion, we prevent this from happening as early as possible. + if (managedIdentitySource === "CloudShell") { + if (this.clientId || this.resourceId || this.objectId) { + logger.warning(`CloudShell MSI detected with user-provided IDs - throwing. Received values: ${JSON.stringify({ + clientId: this.clientId, + resourceId: this.resourceId, + objectId: this.objectId, + })}.`); + throw new CredentialUnavailableError("ManagedIdentityCredential: Specifying a user-assigned managed identity is not supported for CloudShell at runtime. When using Managed Identity in CloudShell, omit the clientId, resourceId, and objectId parameters."); + } + } + // ServiceFabric does not support specifying user-assigned managed identity by client ID or resource ID. The managed identity selected is based on the resource configuration. + if (managedIdentitySource === "ServiceFabric") { + if (this.clientId || this.resourceId || this.objectId) { + logger.warning(`Service Fabric detected with user-provided IDs - throwing. Received values: ${JSON.stringify({ + clientId: this.clientId, + resourceId: this.resourceId, + objectId: this.objectId, + })}.`); + throw new CredentialUnavailableError(`ManagedIdentityCredential: ${serviceFabricErrorMessage}`); + } + } + logger.info(`Using ${managedIdentitySource} managed identity.`); + // Check if either clientId, resourceId or objectId was provided and log the value used + if (providedIds.length === 1) { + const { key, value } = providedIds[0]; + logger.info(`${managedIdentitySource} with ${key}: ${value}`); + } + } + /** + * Authenticates with Microsoft Entra ID and returns an access token if successful. + * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure. + * If an unexpected error occurs, an {@link AuthenticationError} will be thrown with the details of the failure. + * + * @param scopes - The list of scopes for which the token will have access. + * @param options - The options used to configure any requests this + * TokenCredential implementation might make. + */ + async getToken(scopes, options = {}) { + logger.getToken.info("Using the MSAL provider for Managed Identity."); + const resource = mapScopesToResource(scopes); + if (!resource) { + throw new CredentialUnavailableError(`ManagedIdentityCredential: Multiple scopes are not supported. Scopes: ${JSON.stringify(scopes)}`); + } + return tracingClient.withSpan("ManagedIdentityCredential.getToken", options, async () => { + var _a; + try { + const isTokenExchangeMsi = await tokenExchangeMsi.isAvailable(this.clientId); + // Most scenarios are handled by MSAL except for two: + // AKS pod identity - MSAL does not implement the token exchange flow. + // IMDS Endpoint probing - MSAL does not do any probing before trying to get a token. + // As a DefaultAzureCredential optimization we probe the IMDS endpoint with a short timeout and no retries before actually trying to get a token + // We will continue to implement these features in the Identity library. + const identitySource = this.managedIdentityApp.getManagedIdentitySource(); + const isImdsMsi = identitySource === "DefaultToImds" || identitySource === "Imds"; // Neither actually checks that IMDS endpoint is available, just that it's the source the MSAL _would_ try to use. + logger.getToken.info(`MSAL Identity source: ${identitySource}`); + if (isTokenExchangeMsi) { + // In the AKS scenario we will use the existing tokenExchangeMsi indefinitely. + logger.getToken.info("Using the token exchange managed identity."); + const result = await tokenExchangeMsi.getToken({ + scopes, + clientId: this.clientId, + identityClient: this.identityClient, + retryConfig: this.msiRetryConfig, + resourceId: this.resourceId, + }); + if (result === null) { + throw new CredentialUnavailableError("Attempted to use the token exchange managed identity, but received a null response."); + } + return result; + } + else if (isImdsMsi) { + // In the IMDS scenario we will probe the IMDS endpoint to ensure it's available before trying to get a token. + // If the IMDS endpoint is not available and this is the source that MSAL will use, we will fail-fast with an error that tells DAC to move to the next credential. + logger.getToken.info("Using the IMDS endpoint to probe for availability."); + const isAvailable = await imdsMsi.isAvailable({ + scopes, + clientId: this.clientId, + getTokenOptions: options, + identityClient: this.isAvailableIdentityClient, + resourceId: this.resourceId, + }); + if (!isAvailable) { + throw new CredentialUnavailableError(`Attempted to use the IMDS endpoint, but it is not available.`); + } + } + // If we got this far, it means: + // - This is not a tokenExchangeMsi, + // - We already probed for IMDS endpoint availability and failed-fast if it's unreachable. + // We can proceed normally by calling MSAL for a token. + logger.getToken.info("Calling into MSAL for managed identity token."); + const token = await this.managedIdentityApp.acquireToken({ + resource, + }); + this.ensureValidMsalToken(scopes, token, options); + logger.getToken.info(formatSuccess(scopes)); + return { + expiresOnTimestamp: token.expiresOn.getTime(), + token: token.accessToken, + refreshAfterTimestamp: (_a = token.refreshOn) === null || _a === void 0 ? void 0 : _a.getTime(), + tokenType: "Bearer", + }; + } + catch (err) { + logger.getToken.error(formatError(scopes, err)); + // AuthenticationRequiredError described as Error to enforce authentication after trying to retrieve a token silently. + // TODO: why would this _ever_ happen considering we're not trying the silent request in this flow? + if (err.name === "AuthenticationRequiredError") { + throw err; + } + if (isNetworkError(err)) { + throw new CredentialUnavailableError(`ManagedIdentityCredential: Network unreachable. Message: ${err.message}`, { cause: err }); + } + throw new CredentialUnavailableError(`ManagedIdentityCredential: Authentication failed. Message ${err.message}`, { cause: err }); + } + }); + } + /** + * Ensures the validity of the MSAL token + */ + ensureValidMsalToken(scopes, msalToken, getTokenOptions) { + const createError = (message) => { + logger.getToken.info(message); + return new AuthenticationRequiredError({ + scopes: Array.isArray(scopes) ? scopes : [scopes], + getTokenOptions, + message, + }); + }; + if (!msalToken) { + throw createError("No response."); + } + if (!msalToken.expiresOn) { + throw createError(`Response had no "expiresOn" property.`); + } + if (!msalToken.accessToken) { + throw createError(`Response had no "accessToken" property.`); + } + } +} +function isNetworkError(err) { + // MSAL error + if (err.errorCode === "network_error") { + return true; + } + // Probe errors + if (err.code === "ENETUNREACH" || err.code === "EHOSTUNREACH") { + return true; + } + // This is a special case for Docker Desktop which responds with a 403 with a message that contains "A socket operation was attempted to an unreachable network" or "A socket operation was attempted to an unreachable host" + // rather than just timing out, as expected. + if (err.statusCode === 403 || err.code === 403) { + if (err.message.includes("unreachable")) { + return true; + } + } + return false; +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/tokenExchangeMsi.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/tokenExchangeMsi.js new file mode 100644 index 00000000..ba748f1a --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/tokenExchangeMsi.js @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { WorkloadIdentityCredential } from "../workloadIdentityCredential.js"; +import { credentialLogger } from "../../util/logging.js"; +const msiName = "ManagedIdentityCredential - Token Exchange"; +const logger = credentialLogger(msiName); +/** + * Defines how to determine whether the token exchange MSI is available, and also how to retrieve a token from the token exchange MSI. + * + * Token exchange MSI (used by AKS) is the only MSI implementation handled entirely by Azure Identity. + * The rest have been migrated to MSAL. + */ +export const tokenExchangeMsi = { + name: "tokenExchangeMsi", + async isAvailable(clientId) { + const env = process.env; + const result = Boolean((clientId || env.AZURE_CLIENT_ID) && + env.AZURE_TENANT_ID && + process.env.AZURE_FEDERATED_TOKEN_FILE); + if (!result) { + logger.info(`${msiName}: Unavailable. The environment variables needed are: AZURE_CLIENT_ID (or the client ID sent through the parameters), AZURE_TENANT_ID and AZURE_FEDERATED_TOKEN_FILE`); + } + return result; + }, + async getToken(configuration, getTokenOptions = {}) { + const { scopes, clientId } = configuration; + const identityClientTokenCredentialOptions = {}; + const workloadIdentityCredential = new WorkloadIdentityCredential(Object.assign(Object.assign({ clientId, tenantId: process.env.AZURE_TENANT_ID, tokenFilePath: process.env.AZURE_FEDERATED_TOKEN_FILE }, identityClientTokenCredentialOptions), { disableInstanceDiscovery: true })); + return workloadIdentityCredential.getToken(scopes, getTokenOptions); + }, +}; +//# sourceMappingURL=tokenExchangeMsi.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/utils.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/utils.js new file mode 100644 index 00000000..6bf58871 --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/utils.js @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +const DefaultScopeSuffix = "/.default"; +/** + * Error message for Service Fabric Managed Identity environment. + */ +export const serviceFabricErrorMessage = "Specifying a `clientId` or `resourceId` is not supported by the Service Fabric managed identity environment. The managed identity configuration is determined by the Service Fabric cluster resource configuration. See https://aka.ms/servicefabricmi for more information"; +/** + * Most MSIs send requests to the IMDS endpoint, or a similar endpoint. + * These are GET requests that require sending a `resource` parameter on the query. + * This resource can be derived from the scopes received through the getToken call, as long as only one scope is received. + * Multiple scopes assume that the resulting token will have access to multiple resources, which won't be the case. + * + * For that reason, when we encounter multiple scopes, we return undefined. + * It's up to the individual MSI implementations to throw the errors (which helps us provide less generic errors). + */ +export function mapScopesToResource(scopes) { + let scope = ""; + if (Array.isArray(scopes)) { + if (scopes.length !== 1) { + return; + } + scope = scopes[0]; + } + else if (typeof scopes === "string") { + scope = scopes; + } + if (!scope.endsWith(DefaultScopeSuffix)) { + return scope; + } + return scope.substr(0, scope.lastIndexOf(DefaultScopeSuffix)); +} +/** + * Given a token response, return the expiration timestamp as the number of milliseconds from the Unix epoch. + * @param body - A parsed response body from the authentication endpoint. + */ +export function parseExpirationTimestamp(body) { + if (typeof body.expires_on === "number") { + return body.expires_on * 1000; + } + if (typeof body.expires_on === "string") { + const asNumber = +body.expires_on; + if (!isNaN(asNumber)) { + return asNumber * 1000; + } + const asDate = Date.parse(body.expires_on); + if (!isNaN(asDate)) { + return asDate; + } + } + if (typeof body.expires_in === "number") { + return Date.now() + body.expires_in * 1000; + } + throw new Error(`Failed to parse token expiration from body. expires_in="${body.expires_in}", expires_on="${body.expires_on}"`); +} +/** + * Given a token response, return the expiration timestamp as the number of milliseconds from the Unix epoch. + * @param body - A parsed response body from the authentication endpoint. + */ +export function parseRefreshTimestamp(body) { + if (body.refresh_on) { + if (typeof body.refresh_on === "number") { + return body.refresh_on * 1000; + } + if (typeof body.refresh_on === "string") { + const asNumber = +body.refresh_on; + if (!isNaN(asNumber)) { + return asNumber * 1000; + } + const asDate = Date.parse(body.refresh_on); + if (!isNaN(asDate)) { + return asDate; + } + } + throw new Error(`Failed to parse refresh_on from body. refresh_on="${body.refresh_on}"`); + } + else { + return undefined; + } +} +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/onBehalfOfCredential.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/onBehalfOfCredential.js new file mode 100644 index 00000000..4c3188b8 --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/onBehalfOfCredential.js @@ -0,0 +1,118 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { createMsalClient } from "../msal/nodeFlows/msalClient.js"; +import { credentialLogger, formatError } from "../util/logging.js"; +import { processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, } from "../util/tenantIdUtils.js"; +import { CredentialUnavailableError } from "../errors.js"; +import { createHash } from "node:crypto"; +import { ensureScopes } from "../util/scopeUtils.js"; +import { readFile } from "node:fs/promises"; +import { tracingClient } from "../util/tracing.js"; +const credentialName = "OnBehalfOfCredential"; +const logger = credentialLogger(credentialName); +/** + * Enables authentication to Microsoft Entra ID using the [On Behalf Of flow](https://learn.microsoft.com/entra/identity-platform/v2-oauth2-on-behalf-of-flow). + */ +export class OnBehalfOfCredential { + constructor(options) { + const { clientSecret } = options; + const { certificatePath, sendCertificateChain } = options; + const { getAssertion } = options; + const { tenantId, clientId, userAssertionToken, additionallyAllowedTenants: additionallyAllowedTenantIds, } = options; + if (!tenantId) { + throw new CredentialUnavailableError(`${credentialName}: tenantId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`); + } + if (!clientId) { + throw new CredentialUnavailableError(`${credentialName}: clientId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`); + } + if (!clientSecret && !certificatePath && !getAssertion) { + throw new CredentialUnavailableError(`${credentialName}: You must provide one of clientSecret, certificatePath, or a getAssertion callback but none were provided. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`); + } + if (!userAssertionToken) { + throw new CredentialUnavailableError(`${credentialName}: userAssertionToken is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`); + } + this.certificatePath = certificatePath; + this.clientSecret = clientSecret; + this.userAssertionToken = userAssertionToken; + this.sendCertificateChain = sendCertificateChain; + this.clientAssertion = getAssertion; + this.tenantId = tenantId; + this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(additionallyAllowedTenantIds); + this.msalClient = createMsalClient(clientId, this.tenantId, Object.assign(Object.assign({}, options), { logger, tokenCredentialOptions: options })); + } + /** + * Authenticates with Microsoft Entra ID and returns an access token if successful. + * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure. + * + * @param scopes - The list of scopes for which the token will have access. + * @param options - The options used to configure the underlying network requests. + */ + async getToken(scopes, options = {}) { + return tracingClient.withSpan(`${credentialName}.getToken`, options, async (newOptions) => { + newOptions.tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds, logger); + const arrayScopes = ensureScopes(scopes); + if (this.certificatePath) { + const clientCertificate = await this.buildClientCertificate(this.certificatePath); + return this.msalClient.getTokenOnBehalfOf(arrayScopes, this.userAssertionToken, clientCertificate, newOptions); + } + else if (this.clientSecret) { + return this.msalClient.getTokenOnBehalfOf(arrayScopes, this.userAssertionToken, this.clientSecret, options); + } + else if (this.clientAssertion) { + return this.msalClient.getTokenOnBehalfOf(arrayScopes, this.userAssertionToken, this.clientAssertion, options); + } + else { + // this is an invalid scenario and is a bug, as the constructor should have thrown an error if neither clientSecret nor certificatePath nor clientAssertion were provided + throw new Error("Expected either clientSecret or certificatePath or clientAssertion to be defined."); + } + }); + } + async buildClientCertificate(certificatePath) { + try { + const parts = await this.parseCertificate({ certificatePath }, this.sendCertificateChain); + return { + thumbprint: parts.thumbprint, + thumbprintSha256: parts.thumbprintSha256, + privateKey: parts.certificateContents, + x5c: parts.x5c, + }; + } + catch (error) { + logger.info(formatError("", error)); + throw error; + } + } + async parseCertificate(configuration, sendCertificateChain) { + const certificatePath = configuration.certificatePath; + const certificateContents = await readFile(certificatePath, "utf8"); + const x5c = sendCertificateChain ? certificateContents : undefined; + const certificatePattern = /(-+BEGIN CERTIFICATE-+)(\n\r?|\r\n?)([A-Za-z0-9+/\n\r]+=*)(\n\r?|\r\n?)(-+END CERTIFICATE-+)/g; + const publicKeys = []; + // Match all possible certificates, in the order they are in the file. These will form the chain that is used for x5c + let match; + do { + match = certificatePattern.exec(certificateContents); + if (match) { + publicKeys.push(match[3]); + } + } while (match); + if (publicKeys.length === 0) { + throw new Error("The file at the specified path does not contain a PEM-encoded certificate."); + } + const thumbprint = createHash("sha1") + .update(Buffer.from(publicKeys[0], "base64")) + .digest("hex") + .toUpperCase(); + const thumbprintSha256 = createHash("sha256") + .update(Buffer.from(publicKeys[0], "base64")) + .digest("hex") + .toUpperCase(); + return { + certificateContents, + thumbprintSha256, + thumbprint, + x5c, + }; + } +} +//# sourceMappingURL=onBehalfOfCredential.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/usernamePasswordCredential.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/usernamePasswordCredential.js new file mode 100644 index 00000000..93ee5455 --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/usernamePasswordCredential.js @@ -0,0 +1,68 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { createMsalClient } from "../msal/nodeFlows/msalClient.js"; +import { processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, } from "../util/tenantIdUtils.js"; +import { CredentialUnavailableError } from "../errors.js"; +import { credentialLogger } from "../util/logging.js"; +import { ensureScopes } from "../util/scopeUtils.js"; +import { tracingClient } from "../util/tracing.js"; +const logger = credentialLogger("UsernamePasswordCredential"); +/** + * Enables authentication to Microsoft Entra ID with a user's + * username and password. This credential requires a high degree of + * trust so you should only use it when other, more secure credential + * types can't be used. + * @deprecated UsernamePasswordCredential is deprecated. Use a more secure credential. See https://aka.ms/azsdk/identity/mfa for details. + */ +export class UsernamePasswordCredential { + /** + * Creates an instance of the UsernamePasswordCredential with the details + * needed to authenticate against Microsoft Entra ID with a username + * and password. + * + * @param tenantId - The Microsoft Entra tenant (directory). + * @param clientId - The client (application) ID of an App Registration in the tenant. + * @param username - The user account's e-mail address (user name). + * @param password - The user account's account password + * @param options - Options for configuring the client which makes the authentication request. + */ + constructor(tenantId, clientId, username, password, options = {}) { + if (!tenantId) { + throw new CredentialUnavailableError("UsernamePasswordCredential: tenantId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/usernamepasswordcredential/troubleshoot."); + } + if (!clientId) { + throw new CredentialUnavailableError("UsernamePasswordCredential: clientId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/usernamepasswordcredential/troubleshoot."); + } + if (!username) { + throw new CredentialUnavailableError("UsernamePasswordCredential: username is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/usernamepasswordcredential/troubleshoot."); + } + if (!password) { + throw new CredentialUnavailableError("UsernamePasswordCredential: password is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/usernamepasswordcredential/troubleshoot."); + } + this.tenantId = tenantId; + this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants); + this.username = username; + this.password = password; + this.msalClient = createMsalClient(clientId, this.tenantId, Object.assign(Object.assign({}, options), { tokenCredentialOptions: options !== null && options !== void 0 ? options : {} })); + } + /** + * Authenticates with Microsoft Entra ID and returns an access token if successful. + * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure. + * + * If the user provided the option `disableAutomaticAuthentication`, + * once the token can't be retrieved silently, + * this method won't attempt to request user interaction to retrieve the token. + * + * @param scopes - The list of scopes for which the token will have access. + * @param options - The options used to configure any requests this + * TokenCredential implementation might make. + */ + async getToken(scopes, options = {}) { + return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async (newOptions) => { + newOptions.tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds, logger); + const arrayScopes = ensureScopes(scopes); + return this.msalClient.getTokenByUsernamePassword(arrayScopes, this.username, this.password, newOptions); + }); + } +} +//# sourceMappingURL=usernamePasswordCredential.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/visualStudioCodeCredential.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/visualStudioCodeCredential.js new file mode 100644 index 00000000..afa39e59 --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/visualStudioCodeCredential.js @@ -0,0 +1,196 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { credentialLogger, formatError, formatSuccess } from "../util/logging.js"; +import { processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, } from "../util/tenantIdUtils.js"; +import { AzureAuthorityHosts } from "../constants.js"; +import { CredentialUnavailableError } from "../errors.js"; +import { IdentityClient } from "../client/identityClient.js"; +import { checkTenantId } from "../util/tenantIdUtils.js"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +const CommonTenantId = "common"; +const AzureAccountClientId = "aebc6443-996d-45c2-90f0-388ff96faa56"; // VSC: 'aebc6443-996d-45c2-90f0-388ff96faa56' +const logger = credentialLogger("VisualStudioCodeCredential"); +let findCredentials = undefined; +export const vsCodeCredentialControl = { + setVsCodeCredentialFinder(finder) { + findCredentials = finder; + }, +}; +// Map of unsupported Tenant IDs and the errors we will be throwing. +const unsupportedTenantIds = { + adfs: "The VisualStudioCodeCredential does not support authentication with ADFS tenants.", +}; +function checkUnsupportedTenant(tenantId) { + // If the Tenant ID isn't supported, we throw. + const unsupportedTenantError = unsupportedTenantIds[tenantId]; + if (unsupportedTenantError) { + throw new CredentialUnavailableError(unsupportedTenantError); + } +} +const mapVSCodeAuthorityHosts = { + AzureCloud: AzureAuthorityHosts.AzurePublicCloud, + AzureChina: AzureAuthorityHosts.AzureChina, + AzureGermanCloud: AzureAuthorityHosts.AzureGermany, + AzureUSGovernment: AzureAuthorityHosts.AzureGovernment, +}; +/** + * Attempts to load a specific property from the VSCode configurations of the current OS. + * If it fails at any point, returns undefined. + */ +export function getPropertyFromVSCode(property) { + const settingsPath = ["User", "settings.json"]; + // Eventually we can add more folders for more versions of VSCode. + const vsCodeFolder = "Code"; + const homedir = os.homedir(); + function loadProperty(...pathSegments) { + const fullPath = path.join(...pathSegments, vsCodeFolder, ...settingsPath); + const settings = JSON.parse(fs.readFileSync(fullPath, { encoding: "utf8" })); + return settings[property]; + } + try { + let appData; + switch (process.platform) { + case "win32": + appData = process.env.APPDATA; + return appData ? loadProperty(appData) : undefined; + case "darwin": + return loadProperty(homedir, "Library", "Application Support"); + case "linux": + return loadProperty(homedir, ".config"); + default: + return; + } + } + catch (e) { + logger.info(`Failed to load the Visual Studio Code configuration file. Error: ${e.message}`); + return; + } +} +/** + * Connects to Azure using the credential provided by the VSCode extension 'Azure Account'. + * Once the user has logged in via the extension, this credential can share the same refresh token + * that is cached by the extension. + * + * It's a [known issue](https://github.com/Azure/azure-sdk-for-js/issues/20500) that this credential doesn't + * work with [Azure Account extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode.azure-account) + * versions newer than **0.9.11**. A long-term fix to this problem is in progress. In the meantime, consider + * authenticating with {@link AzureCliCredential}. + * + * @deprecated This credential is deprecated because the VS Code Azure Account extension on which this credential + * relies has been deprecated. Users should use other dev-time credentials, such as {@link AzureCliCredential}, + * {@link AzureDeveloperCliCredential}, or {@link AzurePowerShellCredential} for their + * local development needs. See Azure Account extension deprecation notice [here](https://github.com/microsoft/vscode-azure-account/issues/964). + * + */ +export class VisualStudioCodeCredential { + /** + * Creates an instance of VisualStudioCodeCredential to use for automatically authenticating via VSCode. + * + * **Note**: `VisualStudioCodeCredential` is provided by a plugin package: + * `@azure/identity-vscode`. If this package is not installed and registered + * using the plugin API (`useIdentityPlugin`), then authentication using + * `VisualStudioCodeCredential` will not be available. + * + * @param options - Options for configuring the client which makes the authentication request. + */ + constructor(options) { + // We want to make sure we use the one assigned by the user on the VSCode settings. + // Or just `AzureCloud` by default. + this.cloudName = (getPropertyFromVSCode("azure.cloud") || "AzureCloud"); + // Picking an authority host based on the cloud name. + const authorityHost = mapVSCodeAuthorityHosts[this.cloudName]; + this.identityClient = new IdentityClient(Object.assign({ authorityHost }, options)); + if (options && options.tenantId) { + checkTenantId(logger, options.tenantId); + this.tenantId = options.tenantId; + } + else { + this.tenantId = CommonTenantId; + } + this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants); + checkUnsupportedTenant(this.tenantId); + } + /** + * Runs preparations for any further getToken request. + */ + async prepare() { + // Attempts to load the tenant from the VSCode configuration file. + const settingsTenant = getPropertyFromVSCode("azure.tenant"); + if (settingsTenant) { + this.tenantId = settingsTenant; + } + checkUnsupportedTenant(this.tenantId); + } + /** + * Runs preparations for any further getToken, but only once. + */ + prepareOnce() { + if (!this.preparePromise) { + this.preparePromise = this.prepare(); + } + return this.preparePromise; + } + /** + * Returns the token found by searching VSCode's authentication cache or + * returns null if no token could be found. + * + * @param scopes - The list of scopes for which the token will have access. + * @param options - The options used to configure any requests this + * `TokenCredential` implementation might make. + */ + async getToken(scopes, options) { + var _a, _b; + await this.prepareOnce(); + const tenantId = processMultiTenantRequest(this.tenantId, options, this.additionallyAllowedTenantIds, logger) || this.tenantId; + if (findCredentials === undefined) { + throw new CredentialUnavailableError([ + "No implementation of `VisualStudioCodeCredential` is available.", + "You must install the identity-vscode plugin package (`npm install --save-dev @azure/identity-vscode`)", + "and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling", + "`useIdentityPlugin(vsCodePlugin)` before creating a `VisualStudioCodeCredential`.", + "To troubleshoot, visit https://aka.ms/azsdk/js/identity/vscodecredential/troubleshoot.", + ].join(" ")); + } + let scopeString = typeof scopes === "string" ? scopes : scopes.join(" "); + // Check to make sure the scope we get back is a valid scope + if (!scopeString.match(/^[0-9a-zA-Z-.:/]+$/)) { + const error = new Error("Invalid scope was specified by the user or calling client"); + logger.getToken.info(formatError(scopes, error)); + throw error; + } + if (scopeString.indexOf("offline_access") < 0) { + scopeString += " offline_access"; + } + // findCredentials returns an array similar to: + // [ + // { + // account: "", + // password: "", + // }, + // /* ... */ + // ] + const credentials = await findCredentials(); + // If we can't find the credential based on the name, we'll pick the first one available. + const { password: refreshToken } = (_b = (_a = credentials.find(({ account }) => account === this.cloudName)) !== null && _a !== void 0 ? _a : credentials[0]) !== null && _b !== void 0 ? _b : {}; + if (refreshToken) { + const tokenResponse = await this.identityClient.refreshAccessToken(tenantId, AzureAccountClientId, scopeString, refreshToken, undefined); + if (tokenResponse) { + logger.getToken.info(formatSuccess(scopes)); + return tokenResponse.accessToken; + } + else { + const error = new CredentialUnavailableError("Could not retrieve the token associated with Visual Studio Code. Have you connected using the 'Azure Account' extension recently? To troubleshoot, visit https://aka.ms/azsdk/js/identity/vscodecredential/troubleshoot."); + logger.getToken.info(formatError(scopes, error)); + throw error; + } + } + else { + const error = new CredentialUnavailableError("Could not retrieve the token associated with Visual Studio Code. Did you connect using the 'Azure Account' extension? To troubleshoot, visit https://aka.ms/azsdk/js/identity/vscodecredential/troubleshoot."); + logger.getToken.info(formatError(scopes, error)); + throw error; + } + } +} +//# sourceMappingURL=visualStudioCodeCredential.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/workloadIdentityCredential.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/workloadIdentityCredential.js new file mode 100644 index 00000000..e80d8b0b --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/workloadIdentityCredential.js @@ -0,0 +1,114 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { credentialLogger, processEnvVars } from "../util/logging.js"; +import { ClientAssertionCredential } from "./clientAssertionCredential.js"; +import { CredentialUnavailableError } from "../errors.js"; +import { checkTenantId } from "../util/tenantIdUtils.js"; +import { readFile } from "node:fs/promises"; +const credentialName = "WorkloadIdentityCredential"; +/** + * Contains the list of all supported environment variable names so that an + * appropriate error message can be generated when no credentials can be + * configured. + * + * @internal + */ +export const SupportedWorkloadEnvironmentVariables = [ + "AZURE_TENANT_ID", + "AZURE_CLIENT_ID", + "AZURE_FEDERATED_TOKEN_FILE", +]; +const logger = credentialLogger(credentialName); +/** + * Workload Identity authentication is a feature in Azure that allows applications running on virtual machines (VMs) + * to access other Azure resources without the need for a service principal or managed identity. With Workload Identity + * authentication, applications authenticate themselves using their own identity, rather than using a shared service + * principal or managed identity. Under the hood, Workload Identity authentication uses the concept of Service Account + * Credentials (SACs), which are automatically created by Azure and stored securely in the VM. By using Workload + * Identity authentication, you can avoid the need to manage and rotate service principals or managed identities for + * each application on each VM. Additionally, because SACs are created automatically and managed by Azure, you don't + * need to worry about storing and securing sensitive credentials themselves. + * The WorkloadIdentityCredential supports Microsoft Entra Workload ID authentication on Azure Kubernetes and acquires + * a token using the SACs available in the Azure Kubernetes environment. + * Refer to Microsoft Entra + * Workload ID for more information. + */ +export class WorkloadIdentityCredential { + /** + * WorkloadIdentityCredential supports Microsoft Entra Workload ID on Kubernetes. + * + * @param options - The identity client options to use for authentication. + */ + constructor(options) { + this.azureFederatedTokenFileContent = undefined; + this.cacheDate = undefined; + // Logging environment variables for error details + const assignedEnv = processEnvVars(SupportedWorkloadEnvironmentVariables).assigned.join(", "); + logger.info(`Found the following environment variables: ${assignedEnv}`); + const workloadIdentityCredentialOptions = options !== null && options !== void 0 ? options : {}; + const tenantId = workloadIdentityCredentialOptions.tenantId || process.env.AZURE_TENANT_ID; + const clientId = workloadIdentityCredentialOptions.clientId || process.env.AZURE_CLIENT_ID; + this.federatedTokenFilePath = + workloadIdentityCredentialOptions.tokenFilePath || process.env.AZURE_FEDERATED_TOKEN_FILE; + if (tenantId) { + checkTenantId(logger, tenantId); + } + if (!clientId) { + throw new CredentialUnavailableError(`${credentialName}: is unavailable. clientId is a required parameter. In DefaultAzureCredential and ManagedIdentityCredential, this can be provided as an environment variable - "AZURE_CLIENT_ID". + See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/workloadidentitycredential/troubleshoot`); + } + if (!tenantId) { + throw new CredentialUnavailableError(`${credentialName}: is unavailable. tenantId is a required parameter. In DefaultAzureCredential and ManagedIdentityCredential, this can be provided as an environment variable - "AZURE_TENANT_ID". + See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/workloadidentitycredential/troubleshoot`); + } + if (!this.federatedTokenFilePath) { + throw new CredentialUnavailableError(`${credentialName}: is unavailable. federatedTokenFilePath is a required parameter. In DefaultAzureCredential and ManagedIdentityCredential, this can be provided as an environment variable - "AZURE_FEDERATED_TOKEN_FILE". + See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/workloadidentitycredential/troubleshoot`); + } + logger.info(`Invoking ClientAssertionCredential with tenant ID: ${tenantId}, clientId: ${workloadIdentityCredentialOptions.clientId} and federated token path: [REDACTED]`); + this.client = new ClientAssertionCredential(tenantId, clientId, this.readFileContents.bind(this), options); + } + /** + * Authenticates with Microsoft Entra ID and returns an access token if successful. + * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure. + * + * @param scopes - The list of scopes for which the token will have access. + * @param options - The options used to configure any requests this + * TokenCredential implementation might make. + */ + async getToken(scopes, options) { + if (!this.client) { + const errorMessage = `${credentialName}: is unavailable. tenantId, clientId, and federatedTokenFilePath are required parameters. + In DefaultAzureCredential and ManagedIdentityCredential, these can be provided as environment variables - + "AZURE_TENANT_ID", + "AZURE_CLIENT_ID", + "AZURE_FEDERATED_TOKEN_FILE". See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/workloadidentitycredential/troubleshoot`; + logger.info(errorMessage); + throw new CredentialUnavailableError(errorMessage); + } + logger.info("Invoking getToken() of Client Assertion Credential"); + return this.client.getToken(scopes, options); + } + async readFileContents() { + // Cached assertions expire after 5 minutes + if (this.cacheDate !== undefined && Date.now() - this.cacheDate >= 1000 * 60 * 5) { + this.azureFederatedTokenFileContent = undefined; + } + if (!this.federatedTokenFilePath) { + throw new CredentialUnavailableError(`${credentialName}: is unavailable. Invalid file path provided ${this.federatedTokenFilePath}.`); + } + if (!this.azureFederatedTokenFileContent) { + const file = await readFile(this.federatedTokenFilePath, "utf8"); + const value = file.trim(); + if (!value) { + throw new CredentialUnavailableError(`${credentialName}: is unavailable. No content on the file ${this.federatedTokenFilePath}.`); + } + else { + this.azureFederatedTokenFileContent = value; + this.cacheDate = Date.now(); + } + } + return this.azureFederatedTokenFileContent; + } +} +//# sourceMappingURL=workloadIdentityCredential.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/errors.js b/claude-code-source/node_modules/@azure/identity/dist/esm/errors.js new file mode 100644 index 00000000..d015c473 --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/errors.js @@ -0,0 +1,123 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +function isErrorResponse(errorResponse) { + return (errorResponse && + typeof errorResponse.error === "string" && + typeof errorResponse.error_description === "string"); +} +/** + * The Error.name value of an CredentialUnavailable + */ +export const CredentialUnavailableErrorName = "CredentialUnavailableError"; +/** + * This signifies that the credential that was tried in a chained credential + * was not available to be used as the credential. Rather than treating this as + * an error that should halt the chain, it's caught and the chain continues + */ +export class CredentialUnavailableError extends Error { + constructor(message, options) { + // @ts-expect-error - TypeScript does not recognize this until we use ES2022 as the target; however, all our major runtimes do support the `cause` property + super(message, options); + this.name = CredentialUnavailableErrorName; + } +} +/** + * The Error.name value of an AuthenticationError + */ +export const AuthenticationErrorName = "AuthenticationError"; +/** + * Provides details about a failure to authenticate with Azure Active + * Directory. The `errorResponse` field contains more details about + * the specific failure. + */ +export class AuthenticationError extends Error { + constructor(statusCode, errorBody, options) { + let errorResponse = { + error: "unknown", + errorDescription: "An unknown error occurred and no additional details are available.", + }; + if (isErrorResponse(errorBody)) { + errorResponse = convertOAuthErrorResponseToErrorResponse(errorBody); + } + else if (typeof errorBody === "string") { + try { + // Most error responses will contain JSON-formatted error details + // in the response body + const oauthErrorResponse = JSON.parse(errorBody); + errorResponse = convertOAuthErrorResponseToErrorResponse(oauthErrorResponse); + } + catch (e) { + if (statusCode === 400) { + errorResponse = { + error: "invalid_request", + errorDescription: `The service indicated that the request was invalid.\n\n${errorBody}`, + }; + } + else { + errorResponse = { + error: "unknown_error", + errorDescription: `An unknown error has occurred. Response body:\n\n${errorBody}`, + }; + } + } + } + else { + errorResponse = { + error: "unknown_error", + errorDescription: "An unknown error occurred and no additional details are available.", + }; + } + super(`${errorResponse.error} Status code: ${statusCode}\nMore details:\n${errorResponse.errorDescription},`, + // @ts-expect-error - TypeScript does not recognize this until we use ES2022 as the target; however, all our major runtimes do support the `cause` property + options); + this.statusCode = statusCode; + this.errorResponse = errorResponse; + // Ensure that this type reports the correct name + this.name = AuthenticationErrorName; + } +} +/** + * The Error.name value of an AggregateAuthenticationError + */ +export const AggregateAuthenticationErrorName = "AggregateAuthenticationError"; +/** + * Provides an `errors` array containing {@link AuthenticationError} instance + * for authentication failures from credentials in a {@link ChainedTokenCredential}. + */ +export class AggregateAuthenticationError extends Error { + constructor(errors, errorMessage) { + const errorDetail = errors.join("\n"); + super(`${errorMessage}\n${errorDetail}`); + this.errors = errors; + // Ensure that this type reports the correct name + this.name = AggregateAuthenticationErrorName; + } +} +function convertOAuthErrorResponseToErrorResponse(errorBody) { + return { + error: errorBody.error, + errorDescription: errorBody.error_description, + correlationId: errorBody.correlation_id, + errorCodes: errorBody.error_codes, + timestamp: errorBody.timestamp, + traceId: errorBody.trace_id, + }; +} +/** + * Error used to enforce authentication after trying to retrieve a token silently. + */ +export class AuthenticationRequiredError extends Error { + constructor( + /** + * Optional parameters. A message can be specified. The {@link GetTokenOptions} of the request can also be specified to more easily associate the error with the received parameters. + */ + options) { + super(options.message, + // @ts-expect-error - TypeScript does not recognize this until we use ES2022 as the target; however, all our major runtimes do support the `cause` property + options.cause ? { cause: options.cause } : undefined); + this.scopes = options.scopes; + this.getTokenOptions = options.getTokenOptions; + this.name = "AuthenticationRequiredError"; + } +} +//# sourceMappingURL=errors.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/index.js b/claude-code-source/node_modules/@azure/identity/dist/esm/index.js new file mode 100644 index 00000000..c376aadb --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/index.js @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +export * from "./plugins/consumer.js"; +import { DefaultAzureCredential } from "./credentials/defaultAzureCredential.js"; +export { AuthenticationError, AggregateAuthenticationError, AuthenticationErrorName, AggregateAuthenticationErrorName, CredentialUnavailableError, CredentialUnavailableErrorName, AuthenticationRequiredError, } from "./errors.js"; +export { serializeAuthenticationRecord, deserializeAuthenticationRecord } from "./msal/utils.js"; +export { ChainedTokenCredential } from "./credentials/chainedTokenCredential.js"; +export { ClientSecretCredential } from "./credentials/clientSecretCredential.js"; +export { DefaultAzureCredential } from "./credentials/defaultAzureCredential.js"; +export { EnvironmentCredential } from "./credentials/environmentCredential.js"; +export { ClientCertificateCredential } from "./credentials/clientCertificateCredential.js"; +export { ClientAssertionCredential } from "./credentials/clientAssertionCredential.js"; +export { AzureCliCredential } from "./credentials/azureCliCredential.js"; +export { AzureDeveloperCliCredential } from "./credentials/azureDeveloperCliCredential.js"; +export { InteractiveBrowserCredential } from "./credentials/interactiveBrowserCredential.js"; +export { ManagedIdentityCredential } from "./credentials/managedIdentityCredential/index.js"; +export { DeviceCodeCredential } from "./credentials/deviceCodeCredential.js"; +export { AzurePipelinesCredential as AzurePipelinesCredential } from "./credentials/azurePipelinesCredential.js"; +export { AuthorizationCodeCredential } from "./credentials/authorizationCodeCredential.js"; +export { AzurePowerShellCredential } from "./credentials/azurePowerShellCredential.js"; +export { UsernamePasswordCredential } from "./credentials/usernamePasswordCredential.js"; +export { VisualStudioCodeCredential } from "./credentials/visualStudioCodeCredential.js"; +export { OnBehalfOfCredential } from "./credentials/onBehalfOfCredential.js"; +export { WorkloadIdentityCredential } from "./credentials/workloadIdentityCredential.js"; +export { logger } from "./util/logging.js"; +export { AzureAuthorityHosts } from "./constants.js"; +/** + * Returns a new instance of the {@link DefaultAzureCredential}. + */ +export function getDefaultAzureCredential() { + return new DefaultAzureCredential(); +} +export { getBearerTokenProvider } from "./tokenProvider.js"; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/msal/msal.js b/claude-code-source/node_modules/@azure/identity/dist/esm/msal/msal.js new file mode 100644 index 00000000..269bbc0b --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/msal/msal.js @@ -0,0 +1,5 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import * as msalCommon from "@azure/msal-node"; +export { msalCommon }; +//# sourceMappingURL=msal.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/msal/nodeFlows/msalClient.js b/claude-code-source/node_modules/@azure/identity/dist/esm/msal/nodeFlows/msalClient.js new file mode 100644 index 00000000..8a66c937 --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/msal/nodeFlows/msalClient.js @@ -0,0 +1,469 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import * as msal from "@azure/msal-node"; +import { credentialLogger, formatSuccess } from "../../util/logging.js"; +import { msalPlugins } from "./msalPlugins.js"; +import { defaultLoggerCallback, ensureValidMsalToken, getAuthority, getAuthorityHost, getKnownAuthorities, getMSALLogLevel, handleMsalError, msalToPublic, publicToMsal, } from "../utils.js"; +import { AuthenticationRequiredError } from "../../errors.js"; +import { IdentityClient } from "../../client/identityClient.js"; +import { calculateRegionalAuthority } from "../../regionalAuthority.js"; +import { getLogLevel } from "@azure/logger"; +import { resolveTenantId } from "../../util/tenantIdUtils.js"; +/** + * The default logger used if no logger was passed in by the credential. + */ +const msalLogger = credentialLogger("MsalClient"); +/** + * Generates the configuration for MSAL (Microsoft Authentication Library). + * + * @param clientId - The client ID of the application. + * @param tenantId - The tenant ID of the Azure Active Directory. + * @param msalClientOptions - Optional. Additional options for creating the MSAL client. + * @returns The MSAL configuration object. + */ +export function generateMsalConfiguration(clientId, tenantId, msalClientOptions = {}) { + var _a, _b, _c; + const resolvedTenant = resolveTenantId((_a = msalClientOptions.logger) !== null && _a !== void 0 ? _a : msalLogger, tenantId, clientId); + // TODO: move and reuse getIdentityClientAuthorityHost + const authority = getAuthority(resolvedTenant, getAuthorityHost(msalClientOptions)); + const httpClient = new IdentityClient(Object.assign(Object.assign({}, msalClientOptions.tokenCredentialOptions), { authorityHost: authority, loggingOptions: msalClientOptions.loggingOptions })); + const msalConfig = { + auth: { + clientId, + authority, + knownAuthorities: getKnownAuthorities(resolvedTenant, authority, msalClientOptions.disableInstanceDiscovery), + }, + system: { + networkClient: httpClient, + loggerOptions: { + loggerCallback: defaultLoggerCallback((_b = msalClientOptions.logger) !== null && _b !== void 0 ? _b : msalLogger), + logLevel: getMSALLogLevel(getLogLevel()), + piiLoggingEnabled: (_c = msalClientOptions.loggingOptions) === null || _c === void 0 ? void 0 : _c.enableUnsafeSupportLogging, + }, + }, + }; + return msalConfig; +} +/** + * Creates an instance of the MSAL (Microsoft Authentication Library) client. + * + * @param clientId - The client ID of the application. + * @param tenantId - The tenant ID of the Azure Active Directory. + * @param createMsalClientOptions - Optional. Additional options for creating the MSAL client. + * @returns An instance of the MSAL client. + * + * @public + */ +export function createMsalClient(clientId, tenantId, createMsalClientOptions = {}) { + var _a; + const state = { + msalConfig: generateMsalConfiguration(clientId, tenantId, createMsalClientOptions), + cachedAccount: createMsalClientOptions.authenticationRecord + ? publicToMsal(createMsalClientOptions.authenticationRecord) + : null, + pluginConfiguration: msalPlugins.generatePluginConfiguration(createMsalClientOptions), + logger: (_a = createMsalClientOptions.logger) !== null && _a !== void 0 ? _a : msalLogger, + }; + const publicApps = new Map(); + async function getPublicApp(options = {}) { + const appKey = options.enableCae ? "CAE" : "default"; + let publicClientApp = publicApps.get(appKey); + if (publicClientApp) { + state.logger.getToken.info("Existing PublicClientApplication found in cache, returning it."); + return publicClientApp; + } + // Initialize a new app and cache it + state.logger.getToken.info(`Creating new PublicClientApplication with CAE ${options.enableCae ? "enabled" : "disabled"}.`); + const cachePlugin = options.enableCae + ? state.pluginConfiguration.cache.cachePluginCae + : state.pluginConfiguration.cache.cachePlugin; + state.msalConfig.auth.clientCapabilities = options.enableCae ? ["cp1"] : undefined; + publicClientApp = new msal.PublicClientApplication(Object.assign(Object.assign({}, state.msalConfig), { broker: { nativeBrokerPlugin: state.pluginConfiguration.broker.nativeBrokerPlugin }, cache: { cachePlugin: await cachePlugin } })); + publicApps.set(appKey, publicClientApp); + return publicClientApp; + } + const confidentialApps = new Map(); + async function getConfidentialApp(options = {}) { + const appKey = options.enableCae ? "CAE" : "default"; + let confidentialClientApp = confidentialApps.get(appKey); + if (confidentialClientApp) { + state.logger.getToken.info("Existing ConfidentialClientApplication found in cache, returning it."); + return confidentialClientApp; + } + // Initialize a new app and cache it + state.logger.getToken.info(`Creating new ConfidentialClientApplication with CAE ${options.enableCae ? "enabled" : "disabled"}.`); + const cachePlugin = options.enableCae + ? state.pluginConfiguration.cache.cachePluginCae + : state.pluginConfiguration.cache.cachePlugin; + state.msalConfig.auth.clientCapabilities = options.enableCae ? ["cp1"] : undefined; + confidentialClientApp = new msal.ConfidentialClientApplication(Object.assign(Object.assign({}, state.msalConfig), { broker: { nativeBrokerPlugin: state.pluginConfiguration.broker.nativeBrokerPlugin }, cache: { cachePlugin: await cachePlugin } })); + confidentialApps.set(appKey, confidentialClientApp); + return confidentialClientApp; + } + async function getTokenSilent(app, scopes, options = {}) { + if (state.cachedAccount === null) { + state.logger.getToken.info("No cached account found in local state."); + throw new AuthenticationRequiredError({ scopes }); + } + // Keep track and reuse the claims we received across challenges + if (options.claims) { + state.cachedClaims = options.claims; + } + const silentRequest = { + account: state.cachedAccount, + scopes, + claims: state.cachedClaims, + }; + if (state.pluginConfiguration.broker.isEnabled) { + silentRequest.tokenQueryParameters || (silentRequest.tokenQueryParameters = {}); + if (state.pluginConfiguration.broker.enableMsaPassthrough) { + silentRequest.tokenQueryParameters["msal_request_type"] = "consumer_passthrough"; + } + } + if (options.proofOfPossessionOptions) { + silentRequest.shrNonce = options.proofOfPossessionOptions.nonce; + silentRequest.authenticationScheme = "pop"; + silentRequest.resourceRequestMethod = options.proofOfPossessionOptions.resourceRequestMethod; + silentRequest.resourceRequestUri = options.proofOfPossessionOptions.resourceRequestUrl; + } + state.logger.getToken.info("Attempting to acquire token silently"); + try { + return await app.acquireTokenSilent(silentRequest); + } + catch (err) { + throw handleMsalError(scopes, err, options); + } + } + /** + * Builds an authority URL for the given request. The authority may be different than the one used when creating the MSAL client + * if the user is creating cross-tenant requests + */ + function calculateRequestAuthority(options) { + if (options === null || options === void 0 ? void 0 : options.tenantId) { + return getAuthority(options.tenantId, getAuthorityHost(createMsalClientOptions)); + } + return state.msalConfig.auth.authority; + } + /** + * Performs silent authentication using MSAL to acquire an access token. + * If silent authentication fails, falls back to interactive authentication. + * + * @param msalApp - The MSAL application instance. + * @param scopes - The scopes for which to acquire the access token. + * @param options - The options for acquiring the access token. + * @param onAuthenticationRequired - A callback function to handle interactive authentication when silent authentication fails. + * @returns A promise that resolves to an AccessToken object containing the access token and its expiration timestamp. + */ + async function withSilentAuthentication(msalApp, scopes, options, onAuthenticationRequired) { + var _a, _b; + let response = null; + try { + response = await getTokenSilent(msalApp, scopes, options); + } + catch (e) { + if (e.name !== "AuthenticationRequiredError") { + throw e; + } + if (options.disableAutomaticAuthentication) { + throw new AuthenticationRequiredError({ + scopes, + getTokenOptions: options, + message: "Automatic authentication has been disabled. You may call the authentication() method.", + }); + } + } + // Silent authentication failed + if (response === null) { + try { + response = await onAuthenticationRequired(); + } + catch (err) { + throw handleMsalError(scopes, err, options); + } + } + // At this point we should have a token, process it + ensureValidMsalToken(scopes, response, options); + state.cachedAccount = (_a = response === null || response === void 0 ? void 0 : response.account) !== null && _a !== void 0 ? _a : null; + state.logger.getToken.info(formatSuccess(scopes)); + return { + token: response.accessToken, + expiresOnTimestamp: response.expiresOn.getTime(), + refreshAfterTimestamp: (_b = response.refreshOn) === null || _b === void 0 ? void 0 : _b.getTime(), + tokenType: response.tokenType, + }; + } + async function getTokenByClientSecret(scopes, clientSecret, options = {}) { + var _a; + state.logger.getToken.info(`Attempting to acquire token using client secret`); + state.msalConfig.auth.clientSecret = clientSecret; + const msalApp = await getConfidentialApp(options); + try { + const response = await msalApp.acquireTokenByClientCredential({ + scopes, + authority: calculateRequestAuthority(options), + azureRegion: calculateRegionalAuthority(), + claims: options === null || options === void 0 ? void 0 : options.claims, + }); + ensureValidMsalToken(scopes, response, options); + state.logger.getToken.info(formatSuccess(scopes)); + return { + token: response.accessToken, + expiresOnTimestamp: response.expiresOn.getTime(), + refreshAfterTimestamp: (_a = response.refreshOn) === null || _a === void 0 ? void 0 : _a.getTime(), + tokenType: response.tokenType, + }; + } + catch (err) { + throw handleMsalError(scopes, err, options); + } + } + async function getTokenByClientAssertion(scopes, clientAssertion, options = {}) { + var _a; + state.logger.getToken.info(`Attempting to acquire token using client assertion`); + state.msalConfig.auth.clientAssertion = clientAssertion; + const msalApp = await getConfidentialApp(options); + try { + const response = await msalApp.acquireTokenByClientCredential({ + scopes, + authority: calculateRequestAuthority(options), + azureRegion: calculateRegionalAuthority(), + claims: options === null || options === void 0 ? void 0 : options.claims, + clientAssertion, + }); + ensureValidMsalToken(scopes, response, options); + state.logger.getToken.info(formatSuccess(scopes)); + return { + token: response.accessToken, + expiresOnTimestamp: response.expiresOn.getTime(), + refreshAfterTimestamp: (_a = response.refreshOn) === null || _a === void 0 ? void 0 : _a.getTime(), + tokenType: response.tokenType, + }; + } + catch (err) { + throw handleMsalError(scopes, err, options); + } + } + async function getTokenByClientCertificate(scopes, certificate, options = {}) { + var _a; + state.logger.getToken.info(`Attempting to acquire token using client certificate`); + state.msalConfig.auth.clientCertificate = certificate; + const msalApp = await getConfidentialApp(options); + try { + const response = await msalApp.acquireTokenByClientCredential({ + scopes, + authority: calculateRequestAuthority(options), + azureRegion: calculateRegionalAuthority(), + claims: options === null || options === void 0 ? void 0 : options.claims, + }); + ensureValidMsalToken(scopes, response, options); + state.logger.getToken.info(formatSuccess(scopes)); + return { + token: response.accessToken, + expiresOnTimestamp: response.expiresOn.getTime(), + refreshAfterTimestamp: (_a = response.refreshOn) === null || _a === void 0 ? void 0 : _a.getTime(), + tokenType: response.tokenType, + }; + } + catch (err) { + throw handleMsalError(scopes, err, options); + } + } + async function getTokenByDeviceCode(scopes, deviceCodeCallback, options = {}) { + state.logger.getToken.info(`Attempting to acquire token using device code`); + const msalApp = await getPublicApp(options); + return withSilentAuthentication(msalApp, scopes, options, () => { + var _a, _b; + const requestOptions = { + scopes, + cancel: (_b = (_a = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) !== null && _b !== void 0 ? _b : false, + deviceCodeCallback, + authority: calculateRequestAuthority(options), + claims: options === null || options === void 0 ? void 0 : options.claims, + }; + const deviceCodeRequest = msalApp.acquireTokenByDeviceCode(requestOptions); + if (options.abortSignal) { + options.abortSignal.addEventListener("abort", () => { + requestOptions.cancel = true; + }); + } + return deviceCodeRequest; + }); + } + async function getTokenByUsernamePassword(scopes, username, password, options = {}) { + state.logger.getToken.info(`Attempting to acquire token using username and password`); + const msalApp = await getPublicApp(options); + return withSilentAuthentication(msalApp, scopes, options, () => { + const requestOptions = { + scopes, + username, + password, + authority: calculateRequestAuthority(options), + claims: options === null || options === void 0 ? void 0 : options.claims, + }; + return msalApp.acquireTokenByUsernamePassword(requestOptions); + }); + } + function getActiveAccount() { + if (!state.cachedAccount) { + return undefined; + } + return msalToPublic(clientId, state.cachedAccount); + } + async function getTokenByAuthorizationCode(scopes, redirectUri, authorizationCode, clientSecret, options = {}) { + state.logger.getToken.info(`Attempting to acquire token using authorization code`); + let msalApp; + if (clientSecret) { + // If a client secret is provided, we need to use a confidential client application + // See https://learn.microsoft.com/entra/identity-platform/v2-oauth2-auth-code-flow#request-an-access-token-with-a-client_secret + state.msalConfig.auth.clientSecret = clientSecret; + msalApp = await getConfidentialApp(options); + } + else { + msalApp = await getPublicApp(options); + } + return withSilentAuthentication(msalApp, scopes, options, () => { + return msalApp.acquireTokenByCode({ + scopes, + redirectUri, + code: authorizationCode, + authority: calculateRequestAuthority(options), + claims: options === null || options === void 0 ? void 0 : options.claims, + }); + }); + } + async function getTokenOnBehalfOf(scopes, userAssertionToken, clientCredentials, options = {}) { + var _a; + msalLogger.getToken.info(`Attempting to acquire token on behalf of another user`); + if (typeof clientCredentials === "string") { + // Client secret + msalLogger.getToken.info(`Using client secret for on behalf of flow`); + state.msalConfig.auth.clientSecret = clientCredentials; + } + else if (typeof clientCredentials === "function") { + // Client Assertion + msalLogger.getToken.info(`Using client assertion callback for on behalf of flow`); + state.msalConfig.auth.clientAssertion = clientCredentials; + } + else { + // Client certificate + msalLogger.getToken.info(`Using client certificate for on behalf of flow`); + state.msalConfig.auth.clientCertificate = clientCredentials; + } + const msalApp = await getConfidentialApp(options); + try { + const response = await msalApp.acquireTokenOnBehalfOf({ + scopes, + authority: calculateRequestAuthority(options), + claims: options.claims, + oboAssertion: userAssertionToken, + }); + ensureValidMsalToken(scopes, response, options); + msalLogger.getToken.info(formatSuccess(scopes)); + return { + token: response.accessToken, + expiresOnTimestamp: response.expiresOn.getTime(), + refreshAfterTimestamp: (_a = response.refreshOn) === null || _a === void 0 ? void 0 : _a.getTime(), + tokenType: response.tokenType, + }; + } + catch (err) { + throw handleMsalError(scopes, err, options); + } + } + async function getTokenByInteractiveRequest(scopes, options = {}) { + msalLogger.getToken.info(`Attempting to acquire token interactively`); + const app = await getPublicApp(options); + /** + * A helper function that supports brokered authentication through the MSAL's public application. + * + * When options.useDefaultBrokerAccount is true, the method will attempt to authenticate using the default broker account. + * If the default broker account is not available, the method will fall back to interactive authentication. + */ + async function getBrokeredToken(useDefaultBrokerAccount) { + var _a; + msalLogger.verbose("Authentication will resume through the broker"); + const interactiveRequest = createBaseInteractiveRequest(); + if (state.pluginConfiguration.broker.parentWindowHandle) { + interactiveRequest.windowHandle = Buffer.from(state.pluginConfiguration.broker.parentWindowHandle); + } + else { + // this is a bug, as the pluginConfiguration handler should validate this case. + msalLogger.warning("Parent window handle is not specified for the broker. This may cause unexpected behavior. Please provide the parentWindowHandle."); + } + if (state.pluginConfiguration.broker.enableMsaPassthrough) { + ((_a = interactiveRequest.tokenQueryParameters) !== null && _a !== void 0 ? _a : (interactiveRequest.tokenQueryParameters = {}))["msal_request_type"] = + "consumer_passthrough"; + } + if (useDefaultBrokerAccount) { + interactiveRequest.prompt = "none"; + msalLogger.verbose("Attempting broker authentication using the default broker account"); + } + else { + msalLogger.verbose("Attempting broker authentication without the default broker account"); + } + if (options.proofOfPossessionOptions) { + interactiveRequest.shrNonce = options.proofOfPossessionOptions.nonce; + interactiveRequest.authenticationScheme = "pop"; + interactiveRequest.resourceRequestMethod = + options.proofOfPossessionOptions.resourceRequestMethod; + interactiveRequest.resourceRequestUri = options.proofOfPossessionOptions.resourceRequestUrl; + } + try { + return await app.acquireTokenInteractive(interactiveRequest); + } + catch (e) { + msalLogger.verbose(`Failed to authenticate through the broker: ${e.message}`); + // If we tried to use the default broker account and failed, fall back to interactive authentication + if (useDefaultBrokerAccount) { + return getBrokeredToken(/* useDefaultBrokerAccount: */ false); + } + else { + throw e; + } + } + } + function createBaseInteractiveRequest() { + var _a, _b; + return { + openBrowser: async (url) => { + const open = await import("open"); + await open.default(url, { wait: true, newInstance: true }); + }, + scopes, + authority: calculateRequestAuthority(options), + claims: options === null || options === void 0 ? void 0 : options.claims, + loginHint: options === null || options === void 0 ? void 0 : options.loginHint, + errorTemplate: (_a = options === null || options === void 0 ? void 0 : options.browserCustomizationOptions) === null || _a === void 0 ? void 0 : _a.errorMessage, + successTemplate: (_b = options === null || options === void 0 ? void 0 : options.browserCustomizationOptions) === null || _b === void 0 ? void 0 : _b.successMessage, + prompt: (options === null || options === void 0 ? void 0 : options.loginHint) ? "login" : "select_account", + }; + } + return withSilentAuthentication(app, scopes, options, async () => { + var _a; + const interactiveRequest = createBaseInteractiveRequest(); + if (state.pluginConfiguration.broker.isEnabled) { + return getBrokeredToken((_a = state.pluginConfiguration.broker.useDefaultBrokerAccount) !== null && _a !== void 0 ? _a : false); + } + if (options.proofOfPossessionOptions) { + interactiveRequest.shrNonce = options.proofOfPossessionOptions.nonce; + interactiveRequest.authenticationScheme = "pop"; + interactiveRequest.resourceRequestMethod = + options.proofOfPossessionOptions.resourceRequestMethod; + interactiveRequest.resourceRequestUri = options.proofOfPossessionOptions.resourceRequestUrl; + } + return app.acquireTokenInteractive(interactiveRequest); + }); + } + return { + getActiveAccount, + getTokenByClientSecret, + getTokenByClientAssertion, + getTokenByClientCertificate, + getTokenByDeviceCode, + getTokenByUsernamePassword, + getTokenByAuthorizationCode, + getTokenOnBehalfOf, + getTokenByInteractiveRequest, + }; +} +//# sourceMappingURL=msalClient.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/msal/nodeFlows/msalPlugins.js b/claude-code-source/node_modules/@azure/identity/dist/esm/msal/nodeFlows/msalPlugins.js new file mode 100644 index 00000000..bcd2057c --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/msal/nodeFlows/msalPlugins.js @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { CACHE_CAE_SUFFIX, CACHE_NON_CAE_SUFFIX, DEFAULT_TOKEN_CACHE_NAME, } from "../../constants.js"; +/** + * The current persistence provider, undefined by default. + * @internal + */ +export let persistenceProvider = undefined; +/** + * An object that allows setting the persistence provider. + * @internal + */ +export const msalNodeFlowCacheControl = { + setPersistence(pluginProvider) { + persistenceProvider = pluginProvider; + }, +}; +/** + * The current native broker provider, undefined by default. + * @internal + */ +export let nativeBrokerInfo = undefined; +export function hasNativeBroker() { + return nativeBrokerInfo !== undefined; +} +/** + * An object that allows setting the native broker provider. + * @internal + */ +export const msalNodeFlowNativeBrokerControl = { + setNativeBroker(broker) { + nativeBrokerInfo = { + broker, + }; + }, +}; +/** + * Configures plugins, validating that required plugins are available and enabled. + * + * Does not create the plugins themselves, but rather returns the configuration that will be used to create them. + * + * @param options - options for creating the MSAL client + * @returns plugin configuration + */ +function generatePluginConfiguration(options) { + var _a, _b, _c, _d, _e, _f, _g; + const config = { + cache: {}, + broker: { + isEnabled: (_b = (_a = options.brokerOptions) === null || _a === void 0 ? void 0 : _a.enabled) !== null && _b !== void 0 ? _b : false, + enableMsaPassthrough: (_d = (_c = options.brokerOptions) === null || _c === void 0 ? void 0 : _c.legacyEnableMsaPassthrough) !== null && _d !== void 0 ? _d : false, + parentWindowHandle: (_e = options.brokerOptions) === null || _e === void 0 ? void 0 : _e.parentWindowHandle, + }, + }; + if ((_f = options.tokenCachePersistenceOptions) === null || _f === void 0 ? void 0 : _f.enabled) { + if (persistenceProvider === undefined) { + throw new Error([ + "Persistent token caching was requested, but no persistence provider was configured.", + "You must install the identity-cache-persistence plugin package (`npm install --save @azure/identity-cache-persistence`)", + "and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling", + "`useIdentityPlugin(cachePersistencePlugin)` before using `tokenCachePersistenceOptions`.", + ].join(" ")); + } + const cacheBaseName = options.tokenCachePersistenceOptions.name || DEFAULT_TOKEN_CACHE_NAME; + config.cache.cachePlugin = persistenceProvider(Object.assign({ name: `${cacheBaseName}.${CACHE_NON_CAE_SUFFIX}` }, options.tokenCachePersistenceOptions)); + config.cache.cachePluginCae = persistenceProvider(Object.assign({ name: `${cacheBaseName}.${CACHE_CAE_SUFFIX}` }, options.tokenCachePersistenceOptions)); + } + if ((_g = options.brokerOptions) === null || _g === void 0 ? void 0 : _g.enabled) { + if (nativeBrokerInfo === undefined) { + throw new Error([ + "Broker for WAM was requested to be enabled, but no native broker was configured.", + "You must install the identity-broker plugin package (`npm install --save @azure/identity-broker`)", + "and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling", + "`useIdentityPlugin(createNativeBrokerPlugin())` before using `enableBroker`.", + ].join(" ")); + } + config.broker.nativeBrokerPlugin = nativeBrokerInfo.broker; + } + return config; +} +/** + * Wraps generatePluginConfiguration as a writeable property for test stubbing purposes. + */ +export const msalPlugins = { + generatePluginConfiguration, +}; +//# sourceMappingURL=msalPlugins.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/msal/utils.js b/claude-code-source/node_modules/@azure/identity/dist/esm/msal/utils.js new file mode 100644 index 00000000..b221d132 --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/msal/utils.js @@ -0,0 +1,238 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { AuthenticationRequiredError, CredentialUnavailableError } from "../errors.js"; +import { credentialLogger, formatError } from "../util/logging.js"; +import { DefaultAuthority, DefaultAuthorityHost, DefaultTenantId } from "../constants.js"; +import { randomUUID as coreRandomUUID, isNode, isNodeLike } from "@azure/core-util"; +import { AbortError } from "@azure/abort-controller"; +import { msalCommon } from "./msal.js"; +/** + * @internal + */ +const logger = credentialLogger("IdentityUtils"); +/** + * Latest AuthenticationRecord version + * @internal + */ +const LatestAuthenticationRecordVersion = "1.0"; +/** + * Ensures the validity of the MSAL token + * @internal + */ +export function ensureValidMsalToken(scopes, msalToken, getTokenOptions) { + const error = (message) => { + logger.getToken.info(message); + return new AuthenticationRequiredError({ + scopes: Array.isArray(scopes) ? scopes : [scopes], + getTokenOptions, + message, + }); + }; + if (!msalToken) { + throw error("No response"); + } + if (!msalToken.expiresOn) { + throw error(`Response had no "expiresOn" property.`); + } + if (!msalToken.accessToken) { + throw error(`Response had no "accessToken" property.`); + } +} +/** + * Returns the authority host from either the options bag or the AZURE_AUTHORITY_HOST environment variable. + * + * Defaults to {@link DefaultAuthorityHost}. + * @internal + */ +export function getAuthorityHost(options) { + let authorityHost = options === null || options === void 0 ? void 0 : options.authorityHost; + if (!authorityHost && isNodeLike) { + authorityHost = process.env.AZURE_AUTHORITY_HOST; + } + return authorityHost !== null && authorityHost !== void 0 ? authorityHost : DefaultAuthorityHost; +} +/** + * Generates a valid authority by combining a host with a tenantId. + * @internal + */ +export function getAuthority(tenantId, host) { + if (!host) { + host = DefaultAuthorityHost; + } + if (new RegExp(`${tenantId}/?$`).test(host)) { + return host; + } + if (host.endsWith("/")) { + return host + tenantId; + } + else { + return `${host}/${tenantId}`; + } +} +/** + * Generates the known authorities. + * If the Tenant Id is `adfs`, the authority can't be validated since the format won't match the expected one. + * For that reason, we have to force MSAL to disable validating the authority + * by sending it within the known authorities in the MSAL configuration. + * @internal + */ +export function getKnownAuthorities(tenantId, authorityHost, disableInstanceDiscovery) { + if ((tenantId === "adfs" && authorityHost) || disableInstanceDiscovery) { + return [authorityHost]; + } + return []; +} +/** + * Generates a logger that can be passed to the MSAL clients. + * @param credLogger - The logger of the credential. + * @internal + */ +export const defaultLoggerCallback = (credLogger, platform = isNode ? "Node" : "Browser") => (level, message, containsPii) => { + if (containsPii) { + return; + } + switch (level) { + case msalCommon.LogLevel.Error: + credLogger.info(`MSAL ${platform} V2 error: ${message}`); + return; + case msalCommon.LogLevel.Info: + credLogger.info(`MSAL ${platform} V2 info message: ${message}`); + return; + case msalCommon.LogLevel.Verbose: + credLogger.info(`MSAL ${platform} V2 verbose message: ${message}`); + return; + case msalCommon.LogLevel.Warning: + credLogger.info(`MSAL ${platform} V2 warning: ${message}`); + return; + } +}; +/** + * @internal + */ +export function getMSALLogLevel(logLevel) { + switch (logLevel) { + case "error": + return msalCommon.LogLevel.Error; + case "info": + return msalCommon.LogLevel.Info; + case "verbose": + return msalCommon.LogLevel.Verbose; + case "warning": + return msalCommon.LogLevel.Warning; + default: + // default msal logging level should be Info + return msalCommon.LogLevel.Info; + } +} +/** + * Wraps core-util's randomUUID in order to allow for mocking in tests. + * This prepares the library for the upcoming core-util update to ESM. + * + * @internal + * @returns A string containing a random UUID + */ +export function randomUUID() { + return coreRandomUUID(); +} +/** + * Handles MSAL errors. + */ +export function handleMsalError(scopes, error, getTokenOptions) { + if (error.name === "AuthError" || + error.name === "ClientAuthError" || + error.name === "BrowserAuthError") { + const msalError = error; + switch (msalError.errorCode) { + case "endpoints_resolution_error": + logger.info(formatError(scopes, error.message)); + return new CredentialUnavailableError(error.message); + case "device_code_polling_cancelled": + return new AbortError("The authentication has been aborted by the caller."); + case "consent_required": + case "interaction_required": + case "login_required": + logger.info(formatError(scopes, `Authentication returned errorCode ${msalError.errorCode}`)); + break; + default: + logger.info(formatError(scopes, `Failed to acquire token: ${error.message}`)); + break; + } + } + if (error.name === "ClientConfigurationError" || + error.name === "BrowserConfigurationAuthError" || + error.name === "AbortError" || + error.name === "AuthenticationError") { + return error; + } + if (error.name === "NativeAuthError") { + logger.info(formatError(scopes, `Error from the native broker: ${error.message} with status code: ${error.statusCode}`)); + return error; + } + return new AuthenticationRequiredError({ scopes, getTokenOptions, message: error.message }); +} +// transformations +export function publicToMsal(account) { + return { + localAccountId: account.homeAccountId, + environment: account.authority, + username: account.username, + homeAccountId: account.homeAccountId, + tenantId: account.tenantId, + }; +} +export function msalToPublic(clientId, account) { + var _a; + const record = { + authority: (_a = account.environment) !== null && _a !== void 0 ? _a : DefaultAuthority, + homeAccountId: account.homeAccountId, + tenantId: account.tenantId || DefaultTenantId, + username: account.username, + clientId, + version: LatestAuthenticationRecordVersion, + }; + return record; +} +/** + * Serializes an `AuthenticationRecord` into a string. + * + * The output of a serialized authentication record will contain the following properties: + * + * - "authority" + * - "homeAccountId" + * - "clientId" + * - "tenantId" + * - "username" + * - "version" + * + * To later convert this string to a serialized `AuthenticationRecord`, please use the exported function `deserializeAuthenticationRecord()`. + */ +export function serializeAuthenticationRecord(record) { + return JSON.stringify(record); +} +/** + * Deserializes a previously serialized authentication record from a string into an object. + * + * The input string must contain the following properties: + * + * - "authority" + * - "homeAccountId" + * - "clientId" + * - "tenantId" + * - "username" + * - "version" + * + * If the version we receive is unsupported, an error will be thrown. + * + * At the moment, the only available version is: "1.0", which is always set when the authentication record is serialized. + * + * @param serializedRecord - Authentication record previously serialized into string. + * @returns AuthenticationRecord. + */ +export function deserializeAuthenticationRecord(serializedRecord) { + const parsed = JSON.parse(serializedRecord); + if (parsed.version && parsed.version !== LatestAuthenticationRecordVersion) { + throw Error("Unsupported AuthenticationRecord version"); + } + return parsed; +} +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/plugins/consumer.js b/claude-code-source/node_modules/@azure/identity/dist/esm/plugins/consumer.js new file mode 100644 index 00000000..95c1b1a2 --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/plugins/consumer.js @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { msalNodeFlowCacheControl, msalNodeFlowNativeBrokerControl, } from "../msal/nodeFlows/msalPlugins.js"; +import { vsCodeCredentialControl } from "../credentials/visualStudioCodeCredential.js"; +/** + * The context passed to an Identity plugin. This contains objects that + * plugins can use to set backend implementations. + * @internal + */ +const pluginContext = { + cachePluginControl: msalNodeFlowCacheControl, + nativeBrokerPluginControl: msalNodeFlowNativeBrokerControl, + vsCodeCredentialControl: vsCodeCredentialControl, +}; +/** + * Extend Azure Identity with additional functionality. Pass a plugin from + * a plugin package, such as: + * + * - `@azure/identity-cache-persistence`: provides persistent token caching + * - `@azure/identity-vscode`: provides the dependencies of + * `VisualStudioCodeCredential` and enables it + * + * Example: + * + * ```ts snippet:consumer_example + * import { useIdentityPlugin, DeviceCodeCredential } from "@azure/identity"; + * + * useIdentityPlugin(cachePersistencePlugin); + * // The plugin has the capability to extend `DeviceCodeCredential` and to + * // add middleware to the underlying credentials, such as persistence. + * const credential = new DeviceCodeCredential({ + * tokenCachePersistenceOptions: { + * enabled: true, + * }, + * }); + * ``` + * + * @param plugin - the plugin to register + */ +export function useIdentityPlugin(plugin) { + plugin(pluginContext); +} +//# sourceMappingURL=consumer.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/regionalAuthority.js b/claude-code-source/node_modules/@azure/identity/dist/esm/regionalAuthority.js new file mode 100644 index 00000000..16f73f11 --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/regionalAuthority.js @@ -0,0 +1,140 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +/** + * Helps specify a regional authority, or "AutoDiscoverRegion" to auto-detect the region. + */ +export var RegionalAuthority; +(function (RegionalAuthority) { + /** Instructs MSAL to attempt to discover the region */ + RegionalAuthority["AutoDiscoverRegion"] = "AutoDiscoverRegion"; + /** Uses the {@link RegionalAuthority} for the Azure 'westus' region. */ + RegionalAuthority["USWest"] = "westus"; + /** Uses the {@link RegionalAuthority} for the Azure 'westus2' region. */ + RegionalAuthority["USWest2"] = "westus2"; + /** Uses the {@link RegionalAuthority} for the Azure 'centralus' region. */ + RegionalAuthority["USCentral"] = "centralus"; + /** Uses the {@link RegionalAuthority} for the Azure 'eastus' region. */ + RegionalAuthority["USEast"] = "eastus"; + /** Uses the {@link RegionalAuthority} for the Azure 'eastus2' region. */ + RegionalAuthority["USEast2"] = "eastus2"; + /** Uses the {@link RegionalAuthority} for the Azure 'northcentralus' region. */ + RegionalAuthority["USNorthCentral"] = "northcentralus"; + /** Uses the {@link RegionalAuthority} for the Azure 'southcentralus' region. */ + RegionalAuthority["USSouthCentral"] = "southcentralus"; + /** Uses the {@link RegionalAuthority} for the Azure 'westcentralus' region. */ + RegionalAuthority["USWestCentral"] = "westcentralus"; + /** Uses the {@link RegionalAuthority} for the Azure 'canadacentral' region. */ + RegionalAuthority["CanadaCentral"] = "canadacentral"; + /** Uses the {@link RegionalAuthority} for the Azure 'canadaeast' region. */ + RegionalAuthority["CanadaEast"] = "canadaeast"; + /** Uses the {@link RegionalAuthority} for the Azure 'brazilsouth' region. */ + RegionalAuthority["BrazilSouth"] = "brazilsouth"; + /** Uses the {@link RegionalAuthority} for the Azure 'northeurope' region. */ + RegionalAuthority["EuropeNorth"] = "northeurope"; + /** Uses the {@link RegionalAuthority} for the Azure 'westeurope' region. */ + RegionalAuthority["EuropeWest"] = "westeurope"; + /** Uses the {@link RegionalAuthority} for the Azure 'uksouth' region. */ + RegionalAuthority["UKSouth"] = "uksouth"; + /** Uses the {@link RegionalAuthority} for the Azure 'ukwest' region. */ + RegionalAuthority["UKWest"] = "ukwest"; + /** Uses the {@link RegionalAuthority} for the Azure 'francecentral' region. */ + RegionalAuthority["FranceCentral"] = "francecentral"; + /** Uses the {@link RegionalAuthority} for the Azure 'francesouth' region. */ + RegionalAuthority["FranceSouth"] = "francesouth"; + /** Uses the {@link RegionalAuthority} for the Azure 'switzerlandnorth' region. */ + RegionalAuthority["SwitzerlandNorth"] = "switzerlandnorth"; + /** Uses the {@link RegionalAuthority} for the Azure 'switzerlandwest' region. */ + RegionalAuthority["SwitzerlandWest"] = "switzerlandwest"; + /** Uses the {@link RegionalAuthority} for the Azure 'germanynorth' region. */ + RegionalAuthority["GermanyNorth"] = "germanynorth"; + /** Uses the {@link RegionalAuthority} for the Azure 'germanywestcentral' region. */ + RegionalAuthority["GermanyWestCentral"] = "germanywestcentral"; + /** Uses the {@link RegionalAuthority} for the Azure 'norwaywest' region. */ + RegionalAuthority["NorwayWest"] = "norwaywest"; + /** Uses the {@link RegionalAuthority} for the Azure 'norwayeast' region. */ + RegionalAuthority["NorwayEast"] = "norwayeast"; + /** Uses the {@link RegionalAuthority} for the Azure 'eastasia' region. */ + RegionalAuthority["AsiaEast"] = "eastasia"; + /** Uses the {@link RegionalAuthority} for the Azure 'southeastasia' region. */ + RegionalAuthority["AsiaSouthEast"] = "southeastasia"; + /** Uses the {@link RegionalAuthority} for the Azure 'japaneast' region. */ + RegionalAuthority["JapanEast"] = "japaneast"; + /** Uses the {@link RegionalAuthority} for the Azure 'japanwest' region. */ + RegionalAuthority["JapanWest"] = "japanwest"; + /** Uses the {@link RegionalAuthority} for the Azure 'australiaeast' region. */ + RegionalAuthority["AustraliaEast"] = "australiaeast"; + /** Uses the {@link RegionalAuthority} for the Azure 'australiasoutheast' region. */ + RegionalAuthority["AustraliaSouthEast"] = "australiasoutheast"; + /** Uses the {@link RegionalAuthority} for the Azure 'australiacentral' region. */ + RegionalAuthority["AustraliaCentral"] = "australiacentral"; + /** Uses the {@link RegionalAuthority} for the Azure 'australiacentral2' region. */ + RegionalAuthority["AustraliaCentral2"] = "australiacentral2"; + /** Uses the {@link RegionalAuthority} for the Azure 'centralindia' region. */ + RegionalAuthority["IndiaCentral"] = "centralindia"; + /** Uses the {@link RegionalAuthority} for the Azure 'southindia' region. */ + RegionalAuthority["IndiaSouth"] = "southindia"; + /** Uses the {@link RegionalAuthority} for the Azure 'westindia' region. */ + RegionalAuthority["IndiaWest"] = "westindia"; + /** Uses the {@link RegionalAuthority} for the Azure 'koreasouth' region. */ + RegionalAuthority["KoreaSouth"] = "koreasouth"; + /** Uses the {@link RegionalAuthority} for the Azure 'koreacentral' region. */ + RegionalAuthority["KoreaCentral"] = "koreacentral"; + /** Uses the {@link RegionalAuthority} for the Azure 'uaecentral' region. */ + RegionalAuthority["UAECentral"] = "uaecentral"; + /** Uses the {@link RegionalAuthority} for the Azure 'uaenorth' region. */ + RegionalAuthority["UAENorth"] = "uaenorth"; + /** Uses the {@link RegionalAuthority} for the Azure 'southafricanorth' region. */ + RegionalAuthority["SouthAfricaNorth"] = "southafricanorth"; + /** Uses the {@link RegionalAuthority} for the Azure 'southafricawest' region. */ + RegionalAuthority["SouthAfricaWest"] = "southafricawest"; + /** Uses the {@link RegionalAuthority} for the Azure 'chinanorth' region. */ + RegionalAuthority["ChinaNorth"] = "chinanorth"; + /** Uses the {@link RegionalAuthority} for the Azure 'chinaeast' region. */ + RegionalAuthority["ChinaEast"] = "chinaeast"; + /** Uses the {@link RegionalAuthority} for the Azure 'chinanorth2' region. */ + RegionalAuthority["ChinaNorth2"] = "chinanorth2"; + /** Uses the {@link RegionalAuthority} for the Azure 'chinaeast2' region. */ + RegionalAuthority["ChinaEast2"] = "chinaeast2"; + /** Uses the {@link RegionalAuthority} for the Azure 'germanycentral' region. */ + RegionalAuthority["GermanyCentral"] = "germanycentral"; + /** Uses the {@link RegionalAuthority} for the Azure 'germanynortheast' region. */ + RegionalAuthority["GermanyNorthEast"] = "germanynortheast"; + /** Uses the {@link RegionalAuthority} for the Azure 'usgovvirginia' region. */ + RegionalAuthority["GovernmentUSVirginia"] = "usgovvirginia"; + /** Uses the {@link RegionalAuthority} for the Azure 'usgoviowa' region. */ + RegionalAuthority["GovernmentUSIowa"] = "usgoviowa"; + /** Uses the {@link RegionalAuthority} for the Azure 'usgovarizona' region. */ + RegionalAuthority["GovernmentUSArizona"] = "usgovarizona"; + /** Uses the {@link RegionalAuthority} for the Azure 'usgovtexas' region. */ + RegionalAuthority["GovernmentUSTexas"] = "usgovtexas"; + /** Uses the {@link RegionalAuthority} for the Azure 'usdodeast' region. */ + RegionalAuthority["GovernmentUSDodEast"] = "usdodeast"; + /** Uses the {@link RegionalAuthority} for the Azure 'usdodcentral' region. */ + RegionalAuthority["GovernmentUSDodCentral"] = "usdodcentral"; +})(RegionalAuthority || (RegionalAuthority = {})); +/** + * Calculates the correct regional authority based on the supplied value + * and the AZURE_REGIONAL_AUTHORITY_NAME environment variable. + * + * Values will be returned verbatim, except for {@link RegionalAuthority.AutoDiscoverRegion} + * which is mapped to a value MSAL can understand. + * + * @internal + */ +export function calculateRegionalAuthority(regionalAuthority) { + // Note: as of today only 3 credentials support regional authority, and the parameter + // is not exposed via the public API. Regional Authority is _only_ supported + // via the AZURE_REGIONAL_AUTHORITY_NAME env var and _only_ for: ClientSecretCredential, ClientCertificateCredential, and ClientAssertionCredential. + var _a, _b; + // Accepting the regionalAuthority parameter will allow us to support it in the future. + let azureRegion = regionalAuthority; + if (azureRegion === undefined && + ((_b = (_a = globalThis.process) === null || _a === void 0 ? void 0 : _a.env) === null || _b === void 0 ? void 0 : _b.AZURE_REGIONAL_AUTHORITY_NAME) !== undefined) { + azureRegion = process.env.AZURE_REGIONAL_AUTHORITY_NAME; + } + if (azureRegion === RegionalAuthority.AutoDiscoverRegion) { + return "AUTO_DISCOVER"; + } + return azureRegion; +} +//# sourceMappingURL=regionalAuthority.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/tokenProvider.js b/claude-code-source/node_modules/@azure/identity/dist/esm/tokenProvider.js new file mode 100644 index 00000000..26187e70 --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/tokenProvider.js @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { bearerTokenAuthenticationPolicy, createEmptyPipeline, createPipelineRequest, } from "@azure/core-rest-pipeline"; +/** + * Returns a callback that provides a bearer token. + * For example, the bearer token can be used to authenticate a request as follows: + * ```ts snippet:token_provider_example + * import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity"; + * import { createPipelineRequest } from "@azure/core-rest-pipeline"; + * + * const credential = new DefaultAzureCredential(); + * const scope = "https://cognitiveservices.azure.com/.default"; + * const getAccessToken = getBearerTokenProvider(credential, scope); + * const token = await getAccessToken(); + * + * // usage + * const request = createPipelineRequest({ url: "https://example.com" }); + * request.headers.set("Authorization", `Bearer ${token}`); + * ``` + * + * @param credential - The credential used to authenticate the request. + * @param scopes - The scopes required for the bearer token. + * @param options - Options to configure the token provider. + * @returns a callback that provides a bearer token. + */ +export function getBearerTokenProvider(credential, scopes, options) { + const { abortSignal, tracingOptions } = options || {}; + const pipeline = createEmptyPipeline(); + pipeline.addPolicy(bearerTokenAuthenticationPolicy({ credential, scopes })); + async function getRefreshedToken() { + var _a; + // Create a pipeline with just the bearer token policy + // and run a dummy request through it to get the token + const res = await pipeline.sendRequest({ + sendRequest: (request) => Promise.resolve({ + request, + status: 200, + headers: request.headers, + }), + }, createPipelineRequest({ + url: "https://example.com", + abortSignal, + tracingOptions, + })); + const accessToken = (_a = res.headers.get("authorization")) === null || _a === void 0 ? void 0 : _a.split(" ")[1]; + if (!accessToken) { + throw new Error("Failed to get access token"); + } + return accessToken; + } + return getRefreshedToken; +} +//# sourceMappingURL=tokenProvider.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/util/identityTokenEndpoint.js b/claude-code-source/node_modules/@azure/identity/dist/esm/util/identityTokenEndpoint.js new file mode 100644 index 00000000..157ac18f --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/util/identityTokenEndpoint.js @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +export function getIdentityTokenEndpointSuffix(tenantId) { + if (tenantId === "adfs") { + return "oauth2/token"; + } + else { + return "oauth2/v2.0/token"; + } +} +//# sourceMappingURL=identityTokenEndpoint.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/util/logging.js b/claude-code-source/node_modules/@azure/identity/dist/esm/util/logging.js new file mode 100644 index 00000000..c79c4dcf --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/util/logging.js @@ -0,0 +1,94 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { createClientLogger } from "@azure/logger"; +/** + * The AzureLogger used for all clients within the identity package + */ +export const logger = createClientLogger("identity"); +/** + * Separates a list of environment variable names into a plain object with two arrays: an array of missing environment variables and another array with assigned environment variables. + * @param supportedEnvVars - List of environment variable names + */ +export function processEnvVars(supportedEnvVars) { + return supportedEnvVars.reduce((acc, envVariable) => { + if (process.env[envVariable]) { + acc.assigned.push(envVariable); + } + else { + acc.missing.push(envVariable); + } + return acc; + }, { missing: [], assigned: [] }); +} +/** + * Based on a given list of environment variable names, + * logs the environment variables currently assigned during the usage of a credential that goes by the given name. + * @param credentialName - Name of the credential in use + * @param supportedEnvVars - List of environment variables supported by that credential + */ +export function logEnvVars(credentialName, supportedEnvVars) { + const { assigned } = processEnvVars(supportedEnvVars); + logger.info(`${credentialName} => Found the following environment variables: ${assigned.join(", ")}`); +} +/** + * Formatting the success event on the credentials + */ +export function formatSuccess(scope) { + return `SUCCESS. Scopes: ${Array.isArray(scope) ? scope.join(", ") : scope}.`; +} +/** + * Formatting the success event on the credentials + */ +export function formatError(scope, error) { + let message = "ERROR."; + if (scope === null || scope === void 0 ? void 0 : scope.length) { + message += ` Scopes: ${Array.isArray(scope) ? scope.join(", ") : scope}.`; + } + return `${message} Error message: ${typeof error === "string" ? error : error.message}.`; +} +/** + * Generates a CredentialLoggerInstance. + * + * It logs with the format: + * + * `[title] => [message]` + * + */ +export function credentialLoggerInstance(title, parent, log = logger) { + const fullTitle = parent ? `${parent.fullTitle} ${title}` : title; + function info(message) { + log.info(`${fullTitle} =>`, message); + } + function warning(message) { + log.warning(`${fullTitle} =>`, message); + } + function verbose(message) { + log.verbose(`${fullTitle} =>`, message); + } + function error(message) { + log.error(`${fullTitle} =>`, message); + } + return { + title, + fullTitle, + info, + warning, + verbose, + error, + }; +} +/** + * Generates a CredentialLogger, which is a logger declared at the credential's constructor, and used at any point in the credential. + * It has all the properties of a CredentialLoggerInstance, plus other logger instances, one per method. + * + * It logs with the format: + * + * `[title] => [message]` + * `[title] => getToken() => [message]` + * + */ +export function credentialLogger(title, log = logger) { + const credLogger = credentialLoggerInstance(title, undefined, log); + return Object.assign(Object.assign({}, credLogger), { parent: log, getToken: credentialLoggerInstance("=> getToken()", credLogger, log) }); +} +//# sourceMappingURL=logging.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/util/processMultiTenantRequest.js b/claude-code-source/node_modules/@azure/identity/dist/esm/util/processMultiTenantRequest.js new file mode 100644 index 00000000..7faf281d --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/util/processMultiTenantRequest.js @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { CredentialUnavailableError } from "../errors.js"; +function createConfigurationErrorMessage(tenantId) { + return `The current credential is not configured to acquire tokens for tenant ${tenantId}. To enable acquiring tokens for this tenant add it to the AdditionallyAllowedTenants on the credential options, or add "*" to AdditionallyAllowedTenants to allow acquiring tokens for any tenant.`; +} +/** + * Of getToken contains a tenantId, this functions allows picking this tenantId as the appropriate for authentication, + * unless multitenant authentication has been disabled through the AZURE_IDENTITY_DISABLE_MULTITENANTAUTH (on Node.js), + * or unless the original tenant Id is `adfs`. + * @internal + */ +export function processMultiTenantRequest(tenantId, getTokenOptions, additionallyAllowedTenantIds = [], logger) { + var _a; + let resolvedTenantId; + if (process.env.AZURE_IDENTITY_DISABLE_MULTITENANTAUTH) { + resolvedTenantId = tenantId; + } + else if (tenantId === "adfs") { + resolvedTenantId = tenantId; + } + else { + resolvedTenantId = (_a = getTokenOptions === null || getTokenOptions === void 0 ? void 0 : getTokenOptions.tenantId) !== null && _a !== void 0 ? _a : tenantId; + } + if (tenantId && + resolvedTenantId !== tenantId && + !additionallyAllowedTenantIds.includes("*") && + !additionallyAllowedTenantIds.some((t) => t.localeCompare(resolvedTenantId) === 0)) { + const message = createConfigurationErrorMessage(resolvedTenantId); + logger === null || logger === void 0 ? void 0 : logger.info(message); + throw new CredentialUnavailableError(message); + } + return resolvedTenantId; +} +//# sourceMappingURL=processMultiTenantRequest.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/util/processUtils.js b/claude-code-source/node_modules/@azure/identity/dist/esm/util/processUtils.js new file mode 100644 index 00000000..70beda48 --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/util/processUtils.js @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import * as childProcess from "child_process"; +/** + * Easy to mock childProcess utils. + * @internal + */ +export const processUtils = { + /** + * Promisifying childProcess.execFile + * @internal + */ + execFile(file, params, options) { + return new Promise((resolve, reject) => { + childProcess.execFile(file, params, options, (error, stdout, stderr) => { + if (Buffer.isBuffer(stdout)) { + stdout = stdout.toString("utf8"); + } + if (Buffer.isBuffer(stderr)) { + stderr = stderr.toString("utf8"); + } + if (stderr || error) { + reject(stderr ? new Error(stderr) : error); + } + else { + resolve(stdout); + } + }); + }); + }, +}; +//# sourceMappingURL=processUtils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/util/scopeUtils.js b/claude-code-source/node_modules/@azure/identity/dist/esm/util/scopeUtils.js new file mode 100644 index 00000000..2e0ace33 --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/util/scopeUtils.js @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { formatError } from "./logging.js"; +/** + * Ensures the scopes value is an array. + * @internal + */ +export function ensureScopes(scopes) { + return Array.isArray(scopes) ? scopes : [scopes]; +} +/** + * Throws if the received scope is not valid. + * @internal + */ +export function ensureValidScopeForDevTimeCreds(scope, logger) { + if (!scope.match(/^[0-9a-zA-Z-_.:/]+$/)) { + const error = new Error("Invalid scope was specified by the user or calling client"); + logger.getToken.info(formatError(scope, error)); + throw error; + } +} +/** + * Returns the resource out of a scope. + * @internal + */ +export function getScopeResource(scope) { + return scope.replace(/\/.default$/, ""); +} +//# sourceMappingURL=scopeUtils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/util/subscriptionUtils.js b/claude-code-source/node_modules/@azure/identity/dist/esm/util/subscriptionUtils.js new file mode 100644 index 00000000..9aa6afef --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/util/subscriptionUtils.js @@ -0,0 +1,14 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { formatError } from "./logging.js"; +/** + * @internal + */ +export function checkSubscription(logger, subscription) { + if (!subscription.match(/^[0-9a-zA-Z-._ ]+$/)) { + const error = new Error("Invalid subscription provided. You can locate your subscription by following the instructions listed here: https://learn.microsoft.com/azure/azure-portal/get-subscription-tenant-id."); + logger.info(formatError("", error)); + throw error; + } +} +//# sourceMappingURL=subscriptionUtils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/util/tenantIdUtils.js b/claude-code-source/node_modules/@azure/identity/dist/esm/util/tenantIdUtils.js new file mode 100644 index 00000000..2cbf4d5a --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/util/tenantIdUtils.js @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { ALL_TENANTS, DeveloperSignOnClientId } from "../constants.js"; +import { formatError } from "./logging.js"; +export { processMultiTenantRequest } from "./processMultiTenantRequest.js"; +/** + * @internal + */ +export function checkTenantId(logger, tenantId) { + if (!tenantId.match(/^[0-9a-zA-Z-.]+$/)) { + const error = new Error("Invalid tenant id provided. You can locate your tenant id by following the instructions listed here: https://learn.microsoft.com/partner-center/find-ids-and-domain-names."); + logger.info(formatError("", error)); + throw error; + } +} +/** + * @internal + */ +export function resolveTenantId(logger, tenantId, clientId) { + if (tenantId) { + checkTenantId(logger, tenantId); + return tenantId; + } + if (!clientId) { + clientId = DeveloperSignOnClientId; + } + if (clientId !== DeveloperSignOnClientId) { + return "common"; + } + return "organizations"; +} +/** + * @internal + */ +export function resolveAdditionallyAllowedTenantIds(additionallyAllowedTenants) { + if (!additionallyAllowedTenants || additionallyAllowedTenants.length === 0) { + return []; + } + if (additionallyAllowedTenants.includes("*")) { + return ALL_TENANTS; + } + return additionallyAllowedTenants; +} +//# sourceMappingURL=tenantIdUtils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/util/tracing.js b/claude-code-source/node_modules/@azure/identity/dist/esm/util/tracing.js new file mode 100644 index 00000000..e4a0411c --- /dev/null +++ b/claude-code-source/node_modules/@azure/identity/dist/esm/util/tracing.js @@ -0,0 +1,14 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { SDK_VERSION } from "../constants.js"; +import { createTracingClient } from "@azure/core-tracing"; +/** + * Creates a span using the global tracer. + * @internal + */ +export const tracingClient = createTracingClient({ + namespace: "Microsoft.AAD", + packageName: "@azure/identity", + packageVersion: SDK_VERSION, +}); +//# sourceMappingURL=tracing.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/logger/dist/esm/index.js b/claude-code-source/node_modules/@azure/logger/dist/esm/index.js new file mode 100644 index 00000000..2cad4bd9 --- /dev/null +++ b/claude-code-source/node_modules/@azure/logger/dist/esm/index.js @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { createLoggerContext } from "@typespec/ts-http-runtime/internal/logger"; +const context = createLoggerContext({ + logLevelEnvVarName: "AZURE_LOG_LEVEL", + namespace: "azure", +}); +/** + * The AzureLogger provides a mechanism for overriding where logs are output to. + * By default, logs are sent to stderr. + * Override the `log` method to redirect logs to another location. + */ +export const AzureLogger = context.logger; +/** + * Immediately enables logging at the specified log level. If no level is specified, logging is disabled. + * @param level - The log level to enable for logging. + * Options from most verbose to least verbose are: + * - verbose + * - info + * - warning + * - error + */ +export function setLogLevel(level) { + context.setLogLevel(level); +} +/** + * Retrieves the currently specified log level. + */ +export function getLogLevel() { + return context.getLogLevel(); +} +/** + * Creates a logger for use by the Azure SDKs that inherits from `AzureLogger`. + * @param namespace - The name of the SDK package. + * @hidden + */ +export function createClientLogger(namespace) { + return context.createClientLogger(namespace); +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/account/AccountInfo.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/account/AccountInfo.mjs new file mode 100644 index 00000000..1ff56926 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/account/AccountInfo.mjs @@ -0,0 +1,85 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * Returns true if tenantId matches the utid portion of homeAccountId + * @param tenantId + * @param homeAccountId + * @returns + */ +function tenantIdMatchesHomeTenant(tenantId, homeAccountId) { + return (!!tenantId && + !!homeAccountId && + tenantId === homeAccountId.split(".")[1]); +} +/** + * Build tenant profile + * @param homeAccountId - Home account identifier for this account object + * @param localAccountId - Local account identifer for this account object + * @param tenantId - Full tenant or organizational id that this account belongs to + * @param idTokenClaims - Claims from the ID token + * @returns + */ +function buildTenantProfile(homeAccountId, localAccountId, tenantId, idTokenClaims) { + if (idTokenClaims) { + const { oid, sub, tid, name, tfp, acr, preferred_username, upn, login_hint, } = idTokenClaims; + /** + * Since there is no way to determine if the authority is AAD or B2C, we exhaust all the possible claims that can serve as tenant ID with the following precedence: + * tid - TenantID claim that identifies the tenant that issued the token in AAD. Expected in all AAD ID tokens, not present in B2C ID Tokens. + * tfp - Trust Framework Policy claim that identifies the policy that was used to authenticate the user. Functions as tenant for B2C scenarios. + * acr - Authentication Context Class Reference claim used only with older B2C policies. Fallback in case tfp is not present, but likely won't be present anyway. + */ + const tenantId = tid || tfp || acr || ""; + return { + tenantId: tenantId, + localAccountId: oid || sub || "", + name: name, + username: preferred_username || upn || "", + loginHint: login_hint, + isHomeTenant: tenantIdMatchesHomeTenant(tenantId, homeAccountId), + }; + } + else { + return { + tenantId, + localAccountId, + username: "", + isHomeTenant: tenantIdMatchesHomeTenant(tenantId, homeAccountId), + }; + } +} +/** + * Replaces account info that varies by tenant profile sourced from the ID token claims passed in with the tenant-specific account info + * @param baseAccountInfo + * @param idTokenClaims + * @returns + */ +function updateAccountTenantProfileData(baseAccountInfo, tenantProfile, idTokenClaims, idTokenSecret) { + let updatedAccountInfo = baseAccountInfo; + // Tenant Profile overrides passed in account info + if (tenantProfile) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const { isHomeTenant, ...tenantProfileOverride } = tenantProfile; + updatedAccountInfo = { ...baseAccountInfo, ...tenantProfileOverride }; + } + // ID token claims override passed in account info and tenant profile + if (idTokenClaims) { + // Ignore isHomeTenant, loginHint, and sid which are part of tenant profile but not base account info + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const { isHomeTenant, ...claimsSourcedTenantProfile } = buildTenantProfile(baseAccountInfo.homeAccountId, baseAccountInfo.localAccountId, baseAccountInfo.tenantId, idTokenClaims); + updatedAccountInfo = { + ...updatedAccountInfo, + ...claimsSourcedTenantProfile, + idTokenClaims: idTokenClaims, + idToken: idTokenSecret, + }; + return updatedAccountInfo; + } + return updatedAccountInfo; +} + +export { buildTenantProfile, tenantIdMatchesHomeTenant, updateAccountTenantProfileData }; +//# sourceMappingURL=AccountInfo.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/account/AuthToken.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/account/AuthToken.mjs new file mode 100644 index 00000000..3b04a3c9 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/account/AuthToken.mjs @@ -0,0 +1,86 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +import { createClientAuthError } from '../error/ClientAuthError.mjs'; +import { tokenParsingError, nullOrEmptyToken, maxAgeTranspired } from '../error/ClientAuthErrorCodes.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * Extract token by decoding the rawToken + * + * @param encodedToken + */ +function extractTokenClaims(encodedToken, base64Decode) { + const jswPayload = getJWSPayload(encodedToken); + // token will be decoded to get the username + try { + // base64Decode() should throw an error if there is an issue + const base64Decoded = base64Decode(jswPayload); + return JSON.parse(base64Decoded); + } + catch (err) { + throw createClientAuthError(tokenParsingError); + } +} +/** + * Check if the signin_state claim contains "kmsi" + * @param idTokenClaims + * @returns + */ +function isKmsi(idTokenClaims) { + if (!idTokenClaims.signin_state) { + return false; + } + /** + * Signin_state claim known values: + * dvc_mngd - device is managed + * dvc_dmjd - device is domain joined + * kmsi - user opted to "keep me signed in" + * inknownntwk - Request made inside a known network. Don't use this, use CAE instead. + */ + const kmsiClaims = ["kmsi", "dvc_dmjd"]; // There are some cases where kmsi may not be returned but persistent storage is still OK - allow dvc_dmjd as well + const kmsi = idTokenClaims.signin_state.some((value) => kmsiClaims.includes(value.trim().toLowerCase())); + return kmsi; +} +/** + * decode a JWT + * + * @param authToken + */ +function getJWSPayload(authToken) { + if (!authToken) { + throw createClientAuthError(nullOrEmptyToken); + } + const tokenPartsRegex = /^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/; + const matches = tokenPartsRegex.exec(authToken); + if (!matches || matches.length < 4) { + throw createClientAuthError(tokenParsingError); + } + /** + * const crackedToken = { + * header: matches[1], + * JWSPayload: matches[2], + * JWSSig: matches[3], + * }; + */ + return matches[2]; +} +/** + * Determine if the token's max_age has transpired + */ +function checkMaxAge(authTime, maxAge) { + /* + * per https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest + * To force an immediate re-authentication: If an app requires that a user re-authenticate prior to access, + * provide a value of 0 for the max_age parameter and the AS will force a fresh login. + */ + const fiveMinuteSkew = 300000; // five minutes in milliseconds + if (maxAge === 0 || Date.now() - fiveMinuteSkew > authTime + maxAge) { + throw createClientAuthError(maxAgeTranspired); + } +} + +export { checkMaxAge, extractTokenClaims, getJWSPayload, isKmsi }; +//# sourceMappingURL=AuthToken.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/account/CcsCredential.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/account/CcsCredential.mjs new file mode 100644 index 00000000..3310d948 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/account/CcsCredential.mjs @@ -0,0 +1,13 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +const CcsCredentialType = { + HOME_ACCOUNT_ID: "home_account_id", + UPN: "UPN", +}; + +export { CcsCredentialType }; +//# sourceMappingURL=CcsCredential.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/account/ClientInfo.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/account/ClientInfo.mjs new file mode 100644 index 00000000..1219e36a --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/account/ClientInfo.mjs @@ -0,0 +1,46 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +import { createClientAuthError } from '../error/ClientAuthError.mjs'; +import { Separators, Constants } from '../utils/Constants.mjs'; +import { clientInfoEmptyError, clientInfoDecodingError } from '../error/ClientAuthErrorCodes.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * Function to build a client info object from server clientInfo string + * @param rawClientInfo + * @param crypto + */ +function buildClientInfo(rawClientInfo, base64Decode) { + if (!rawClientInfo) { + throw createClientAuthError(clientInfoEmptyError); + } + try { + const decodedClientInfo = base64Decode(rawClientInfo); + return JSON.parse(decodedClientInfo); + } + catch (e) { + throw createClientAuthError(clientInfoDecodingError); + } +} +/** + * Function to build a client info object from cached homeAccountId string + * @param homeAccountId + */ +function buildClientInfoFromHomeAccountId(homeAccountId) { + if (!homeAccountId) { + throw createClientAuthError(clientInfoDecodingError); + } + const clientInfoParts = homeAccountId.split(Separators.CLIENT_INFO_SEPARATOR, 2); + return { + uid: clientInfoParts[0], + utid: clientInfoParts.length < 2 + ? Constants.EMPTY_STRING + : clientInfoParts[1], + }; +} + +export { buildClientInfo, buildClientInfoFromHomeAccountId }; +//# sourceMappingURL=ClientInfo.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/account/TokenClaims.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/account/TokenClaims.mjs new file mode 100644 index 00000000..a4c491b6 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/account/TokenClaims.mjs @@ -0,0 +1,25 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * Gets tenantId from available ID token claims to set as credential realm with the following precedence: + * 1. tid - if the token is acquired from an Azure AD tenant tid will be present + * 2. tfp - if the token is acquired from a modern B2C tenant tfp should be present + * 3. acr - if the token is acquired from a legacy B2C tenant acr should be present + * Downcased to match the realm case-insensitive comparison requirements + * @param idTokenClaims + * @returns + */ +function getTenantIdFromIdTokenClaims(idTokenClaims) { + if (idTokenClaims) { + const tenantId = idTokenClaims.tid || idTokenClaims.tfp || idTokenClaims.acr; + return tenantId || null; + } + return null; +} + +export { getTenantIdFromIdTokenClaims }; +//# sourceMappingURL=TokenClaims.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/authority/Authority.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/authority/Authority.mjs new file mode 100644 index 00000000..6804a032 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/authority/Authority.mjs @@ -0,0 +1,860 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +import { AuthorityType } from './AuthorityType.mjs'; +import { isOpenIdConfigResponse } from './OpenIdConfigResponse.mjs'; +import { UrlString } from '../url/UrlString.mjs'; +import { createClientAuthError } from '../error/ClientAuthError.mjs'; +import { Constants, AuthorityMetadataSource, RegionDiscoveryOutcomes, AADAuthorityConstants } from '../utils/Constants.mjs'; +import { EndpointMetadata, getCloudDiscoveryMetadataFromHardcodedValues, getCloudDiscoveryMetadataFromNetworkResponse, InstanceDiscoveryMetadataAliases } from './AuthorityMetadata.mjs'; +import { createClientConfigurationError } from '../error/ClientConfigurationError.mjs'; +import { ProtocolMode } from './ProtocolMode.mjs'; +import { AzureCloudInstance } from './AuthorityOptions.mjs'; +import { isCloudInstanceDiscoveryResponse } from './CloudInstanceDiscoveryResponse.mjs'; +import { isCloudInstanceDiscoveryErrorResponse } from './CloudInstanceDiscoveryErrorResponse.mjs'; +import { RegionDiscovery } from './RegionDiscovery.mjs'; +import { AuthError } from '../error/AuthError.mjs'; +import { PerformanceEvents } from '../telemetry/performance/PerformanceEvent.mjs'; +import { invokeAsync } from '../utils/FunctionWrappers.mjs'; +import { generateAuthorityMetadataExpiresAt, updateAuthorityEndpointMetadata, isAuthorityMetadataExpired, updateCloudDiscoveryMetadata } from '../cache/utils/CacheHelpers.mjs'; +import { endpointResolutionError, endSessionEndpointNotSupported, openIdConfigError } from '../error/ClientAuthErrorCodes.mjs'; +import { invalidAuthorityMetadata, untrustedAuthority, invalidCloudDiscoveryMetadata } from '../error/ClientConfigurationErrorCodes.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * The authority class validates the authority URIs used by the user, and retrieves the OpenID Configuration Data from the + * endpoint. It will store the pertinent config data in this object for use during token calls. + * @internal + */ +class Authority { + constructor(authority, networkInterface, cacheManager, authorityOptions, logger, correlationId, performanceClient, managedIdentity) { + this.canonicalAuthority = authority; + this._canonicalAuthority.validateAsUri(); + this.networkInterface = networkInterface; + this.cacheManager = cacheManager; + this.authorityOptions = authorityOptions; + this.regionDiscoveryMetadata = { + region_used: undefined, + region_source: undefined, + region_outcome: undefined, + }; + this.logger = logger; + this.performanceClient = performanceClient; + this.correlationId = correlationId; + this.managedIdentity = managedIdentity || false; + this.regionDiscovery = new RegionDiscovery(networkInterface, this.logger, this.performanceClient, this.correlationId); + } + /** + * Get {@link AuthorityType} + * @param authorityUri {@link IUri} + * @private + */ + getAuthorityType(authorityUri) { + // CIAM auth url pattern is being standardized as: .ciamlogin.com + if (authorityUri.HostNameAndPort.endsWith(Constants.CIAM_AUTH_URL)) { + return AuthorityType.Ciam; + } + const pathSegments = authorityUri.PathSegments; + if (pathSegments.length) { + switch (pathSegments[0].toLowerCase()) { + case Constants.ADFS: + return AuthorityType.Adfs; + case Constants.DSTS: + return AuthorityType.Dsts; + } + } + return AuthorityType.Default; + } + // See above for AuthorityType + get authorityType() { + return this.getAuthorityType(this.canonicalAuthorityUrlComponents); + } + /** + * ProtocolMode enum representing the way endpoints are constructed. + */ + get protocolMode() { + return this.authorityOptions.protocolMode; + } + /** + * Returns authorityOptions which can be used to reinstantiate a new authority instance + */ + get options() { + return this.authorityOptions; + } + /** + * A URL that is the authority set by the developer + */ + get canonicalAuthority() { + return this._canonicalAuthority.urlString; + } + /** + * Sets canonical authority. + */ + set canonicalAuthority(url) { + this._canonicalAuthority = new UrlString(url); + this._canonicalAuthority.validateAsUri(); + this._canonicalAuthorityUrlComponents = null; + } + /** + * Get authority components. + */ + get canonicalAuthorityUrlComponents() { + if (!this._canonicalAuthorityUrlComponents) { + this._canonicalAuthorityUrlComponents = + this._canonicalAuthority.getUrlComponents(); + } + return this._canonicalAuthorityUrlComponents; + } + /** + * Get hostname and port i.e. login.microsoftonline.com + */ + get hostnameAndPort() { + return this.canonicalAuthorityUrlComponents.HostNameAndPort.toLowerCase(); + } + /** + * Get tenant for authority. + */ + get tenant() { + return this.canonicalAuthorityUrlComponents.PathSegments[0]; + } + /** + * OAuth /authorize endpoint for requests + */ + get authorizationEndpoint() { + if (this.discoveryComplete()) { + return this.replacePath(this.metadata.authorization_endpoint); + } + else { + throw createClientAuthError(endpointResolutionError); + } + } + /** + * OAuth /token endpoint for requests + */ + get tokenEndpoint() { + if (this.discoveryComplete()) { + return this.replacePath(this.metadata.token_endpoint); + } + else { + throw createClientAuthError(endpointResolutionError); + } + } + get deviceCodeEndpoint() { + if (this.discoveryComplete()) { + return this.replacePath(this.metadata.token_endpoint.replace("/token", "/devicecode")); + } + else { + throw createClientAuthError(endpointResolutionError); + } + } + /** + * OAuth logout endpoint for requests + */ + get endSessionEndpoint() { + if (this.discoveryComplete()) { + // ROPC policies may not have end_session_endpoint set + if (!this.metadata.end_session_endpoint) { + throw createClientAuthError(endSessionEndpointNotSupported); + } + return this.replacePath(this.metadata.end_session_endpoint); + } + else { + throw createClientAuthError(endpointResolutionError); + } + } + /** + * OAuth issuer for requests + */ + get selfSignedJwtAudience() { + if (this.discoveryComplete()) { + return this.replacePath(this.metadata.issuer); + } + else { + throw createClientAuthError(endpointResolutionError); + } + } + /** + * Jwks_uri for token signing keys + */ + get jwksUri() { + if (this.discoveryComplete()) { + return this.replacePath(this.metadata.jwks_uri); + } + else { + throw createClientAuthError(endpointResolutionError); + } + } + /** + * Returns a flag indicating that tenant name can be replaced in authority {@link IUri} + * @param authorityUri {@link IUri} + * @private + */ + canReplaceTenant(authorityUri) { + return (authorityUri.PathSegments.length === 1 && + !Authority.reservedTenantDomains.has(authorityUri.PathSegments[0]) && + this.getAuthorityType(authorityUri) === AuthorityType.Default && + this.protocolMode !== ProtocolMode.OIDC); + } + /** + * Replaces tenant in url path with current tenant. Defaults to common. + * @param urlString + */ + replaceTenant(urlString) { + return urlString.replace(/{tenant}|{tenantid}/g, this.tenant); + } + /** + * Replaces path such as tenant or policy with the current tenant or policy. + * @param urlString + */ + replacePath(urlString) { + let endpoint = urlString; + const cachedAuthorityUrl = new UrlString(this.metadata.canonical_authority); + const cachedAuthorityUrlComponents = cachedAuthorityUrl.getUrlComponents(); + const cachedAuthorityParts = cachedAuthorityUrlComponents.PathSegments; + const currentAuthorityParts = this.canonicalAuthorityUrlComponents.PathSegments; + currentAuthorityParts.forEach((currentPart, index) => { + let cachedPart = cachedAuthorityParts[index]; + if (index === 0 && + this.canReplaceTenant(cachedAuthorityUrlComponents)) { + const tenantId = new UrlString(this.metadata.authorization_endpoint).getUrlComponents().PathSegments[0]; + /** + * Check if AAD canonical authority contains tenant domain name, for example "testdomain.onmicrosoft.com", + * by comparing its first path segment to the corresponding authorization endpoint path segment, which is + * always resolved with tenant id by OIDC. + */ + if (cachedPart !== tenantId) { + this.logger.verbose(`Replacing tenant domain name ${cachedPart} with id ${tenantId}`); + cachedPart = tenantId; + } + } + if (currentPart !== cachedPart) { + endpoint = endpoint.replace(`/${cachedPart}/`, `/${currentPart}/`); + } + }); + return this.replaceTenant(endpoint); + } + /** + * The default open id configuration endpoint for any canonical authority. + */ + get defaultOpenIdConfigurationEndpoint() { + const canonicalAuthorityHost = this.hostnameAndPort; + if (this.canonicalAuthority.endsWith("v2.0/") || + this.authorityType === AuthorityType.Adfs || + (this.protocolMode === ProtocolMode.OIDC && + !this.isAliasOfKnownMicrosoftAuthority(canonicalAuthorityHost))) { + return `${this.canonicalAuthority}.well-known/openid-configuration`; + } + return `${this.canonicalAuthority}v2.0/.well-known/openid-configuration`; + } + /** + * Boolean that returns whether or not tenant discovery has been completed. + */ + discoveryComplete() { + return !!this.metadata; + } + /** + * Perform endpoint discovery to discover aliases, preferred_cache, preferred_network + * and the /authorize, /token and logout endpoints. + */ + async resolveEndpointsAsync() { + this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityResolveEndpointsAsync, this.correlationId); + const metadataEntity = this.getCurrentMetadataEntity(); + const cloudDiscoverySource = await invokeAsync(this.updateCloudDiscoveryMetadata.bind(this), PerformanceEvents.AuthorityUpdateCloudDiscoveryMetadata, this.logger, this.performanceClient, this.correlationId)(metadataEntity); + this.canonicalAuthority = this.canonicalAuthority.replace(this.hostnameAndPort, metadataEntity.preferred_network); + const endpointSource = await invokeAsync(this.updateEndpointMetadata.bind(this), PerformanceEvents.AuthorityUpdateEndpointMetadata, this.logger, this.performanceClient, this.correlationId)(metadataEntity); + this.updateCachedMetadata(metadataEntity, cloudDiscoverySource, { + source: endpointSource, + }); + this.performanceClient?.addFields({ + cloudDiscoverySource: cloudDiscoverySource, + authorityEndpointSource: endpointSource, + }, this.correlationId); + } + /** + * Returns metadata entity from cache if it exists, otherwiser returns a new metadata entity built + * from the configured canonical authority + * @returns + */ + getCurrentMetadataEntity() { + let metadataEntity = this.cacheManager.getAuthorityMetadataByAlias(this.hostnameAndPort); + if (!metadataEntity) { + metadataEntity = { + aliases: [], + preferred_cache: this.hostnameAndPort, + preferred_network: this.hostnameAndPort, + canonical_authority: this.canonicalAuthority, + authorization_endpoint: "", + token_endpoint: "", + end_session_endpoint: "", + issuer: "", + aliasesFromNetwork: false, + endpointsFromNetwork: false, + expiresAt: generateAuthorityMetadataExpiresAt(), + jwks_uri: "", + }; + } + return metadataEntity; + } + /** + * Updates cached metadata based on metadata source and sets the instance's metadata + * property to the same value + * @param metadataEntity + * @param cloudDiscoverySource + * @param endpointMetadataResult + */ + updateCachedMetadata(metadataEntity, cloudDiscoverySource, endpointMetadataResult) { + if (cloudDiscoverySource !== AuthorityMetadataSource.CACHE && + endpointMetadataResult?.source !== AuthorityMetadataSource.CACHE) { + // Reset the expiration time unless both values came from a successful cache lookup + metadataEntity.expiresAt = + generateAuthorityMetadataExpiresAt(); + metadataEntity.canonical_authority = this.canonicalAuthority; + } + const cacheKey = this.cacheManager.generateAuthorityMetadataCacheKey(metadataEntity.preferred_cache); + this.cacheManager.setAuthorityMetadata(cacheKey, metadataEntity); + this.metadata = metadataEntity; + } + /** + * Update AuthorityMetadataEntity with new endpoints and return where the information came from + * @param metadataEntity + */ + async updateEndpointMetadata(metadataEntity) { + this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityUpdateEndpointMetadata, this.correlationId); + const localMetadata = this.updateEndpointMetadataFromLocalSources(metadataEntity); + // Further update may be required for hardcoded metadata if regional metadata is preferred + if (localMetadata) { + if (localMetadata.source === + AuthorityMetadataSource.HARDCODED_VALUES) { + // If the user prefers to use an azure region replace the global endpoints with regional information. + if (this.authorityOptions.azureRegionConfiguration?.azureRegion) { + if (localMetadata.metadata) { + const hardcodedMetadata = await invokeAsync(this.updateMetadataWithRegionalInformation.bind(this), PerformanceEvents.AuthorityUpdateMetadataWithRegionalInformation, this.logger, this.performanceClient, this.correlationId)(localMetadata.metadata); + updateAuthorityEndpointMetadata(metadataEntity, hardcodedMetadata, false); + metadataEntity.canonical_authority = + this.canonicalAuthority; + } + } + } + return localMetadata.source; + } + // Get metadata from network if local sources aren't available + let metadata = await invokeAsync(this.getEndpointMetadataFromNetwork.bind(this), PerformanceEvents.AuthorityGetEndpointMetadataFromNetwork, this.logger, this.performanceClient, this.correlationId)(); + if (metadata) { + // If the user prefers to use an azure region replace the global endpoints with regional information. + if (this.authorityOptions.azureRegionConfiguration?.azureRegion) { + metadata = await invokeAsync(this.updateMetadataWithRegionalInformation.bind(this), PerformanceEvents.AuthorityUpdateMetadataWithRegionalInformation, this.logger, this.performanceClient, this.correlationId)(metadata); + } + updateAuthorityEndpointMetadata(metadataEntity, metadata, true); + return AuthorityMetadataSource.NETWORK; + } + else { + // Metadata could not be obtained from the config, cache, network or hardcoded values + throw createClientAuthError(openIdConfigError, this.defaultOpenIdConfigurationEndpoint); + } + } + /** + * Updates endpoint metadata from local sources and returns where the information was retrieved from and the metadata config + * response if the source is hardcoded metadata + * @param metadataEntity + * @returns + */ + updateEndpointMetadataFromLocalSources(metadataEntity) { + this.logger.verbose("Attempting to get endpoint metadata from authority configuration"); + const configMetadata = this.getEndpointMetadataFromConfig(); + if (configMetadata) { + this.logger.verbose("Found endpoint metadata in authority configuration"); + updateAuthorityEndpointMetadata(metadataEntity, configMetadata, false); + return { + source: AuthorityMetadataSource.CONFIG, + }; + } + this.logger.verbose("Did not find endpoint metadata in the config... Attempting to get endpoint metadata from the hardcoded values."); + // skipAuthorityMetadataCache is used to bypass hardcoded authority metadata and force a network metadata cache lookup and network metadata request if no cached response is available. + if (this.authorityOptions.skipAuthorityMetadataCache) { + this.logger.verbose("Skipping hardcoded metadata cache since skipAuthorityMetadataCache is set to true. Attempting to get endpoint metadata from the network metadata cache."); + } + else { + const hardcodedMetadata = this.getEndpointMetadataFromHardcodedValues(); + if (hardcodedMetadata) { + updateAuthorityEndpointMetadata(metadataEntity, hardcodedMetadata, false); + return { + source: AuthorityMetadataSource.HARDCODED_VALUES, + metadata: hardcodedMetadata, + }; + } + else { + this.logger.verbose("Did not find endpoint metadata in hardcoded values... Attempting to get endpoint metadata from the network metadata cache."); + } + } + // Check cached metadata entity expiration status + const metadataEntityExpired = isAuthorityMetadataExpired(metadataEntity); + if (this.isAuthoritySameType(metadataEntity) && + metadataEntity.endpointsFromNetwork && + !metadataEntityExpired) { + // No need to update + this.logger.verbose("Found endpoint metadata in the cache."); + return { source: AuthorityMetadataSource.CACHE }; + } + else if (metadataEntityExpired) { + this.logger.verbose("The metadata entity is expired."); + } + return null; + } + /** + * Compares the number of url components after the domain to determine if the cached + * authority metadata can be used for the requested authority. Protects against same domain different + * authority such as login.microsoftonline.com/tenant and login.microsoftonline.com/tfp/tenant/policy + * @param metadataEntity + */ + isAuthoritySameType(metadataEntity) { + const cachedAuthorityUrl = new UrlString(metadataEntity.canonical_authority); + const cachedParts = cachedAuthorityUrl.getUrlComponents().PathSegments; + return (cachedParts.length === + this.canonicalAuthorityUrlComponents.PathSegments.length); + } + /** + * Parse authorityMetadata config option + */ + getEndpointMetadataFromConfig() { + if (this.authorityOptions.authorityMetadata) { + try { + return JSON.parse(this.authorityOptions.authorityMetadata); + } + catch (e) { + throw createClientConfigurationError(invalidAuthorityMetadata); + } + } + return null; + } + /** + * Gets OAuth endpoints from the given OpenID configuration endpoint. + * + * @param hasHardcodedMetadata boolean + */ + async getEndpointMetadataFromNetwork() { + this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityGetEndpointMetadataFromNetwork, this.correlationId); + const options = {}; + /* + * TODO: Add a timeout if the authority exists in our library's + * hardcoded list of metadata + */ + const openIdConfigurationEndpoint = this.defaultOpenIdConfigurationEndpoint; + this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: attempting to retrieve OAuth endpoints from ${openIdConfigurationEndpoint}`); + try { + const response = await this.networkInterface.sendGetRequestAsync(openIdConfigurationEndpoint, options); + const isValidResponse = isOpenIdConfigResponse(response.body); + if (isValidResponse) { + return response.body; + } + else { + this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: could not parse response as OpenID configuration`); + return null; + } + } + catch (e) { + this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: ${e}`); + return null; + } + } + /** + * Get OAuth endpoints for common authorities. + */ + getEndpointMetadataFromHardcodedValues() { + if (this.hostnameAndPort in EndpointMetadata) { + return EndpointMetadata[this.hostnameAndPort]; + } + return null; + } + /** + * Update the retrieved metadata with regional information. + * User selected Azure region will be used if configured. + */ + async updateMetadataWithRegionalInformation(metadata) { + this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityUpdateMetadataWithRegionalInformation, this.correlationId); + const userConfiguredAzureRegion = this.authorityOptions.azureRegionConfiguration?.azureRegion; + if (userConfiguredAzureRegion) { + if (userConfiguredAzureRegion !== + Constants.AZURE_REGION_AUTO_DISCOVER_FLAG) { + this.regionDiscoveryMetadata.region_outcome = + RegionDiscoveryOutcomes.CONFIGURED_NO_AUTO_DETECTION; + this.regionDiscoveryMetadata.region_used = + userConfiguredAzureRegion; + return Authority.replaceWithRegionalInformation(metadata, userConfiguredAzureRegion); + } + const autodetectedRegionName = await invokeAsync(this.regionDiscovery.detectRegion.bind(this.regionDiscovery), PerformanceEvents.RegionDiscoveryDetectRegion, this.logger, this.performanceClient, this.correlationId)(this.authorityOptions.azureRegionConfiguration + ?.environmentRegion, this.regionDiscoveryMetadata); + if (autodetectedRegionName) { + this.regionDiscoveryMetadata.region_outcome = + RegionDiscoveryOutcomes.AUTO_DETECTION_REQUESTED_SUCCESSFUL; + this.regionDiscoveryMetadata.region_used = + autodetectedRegionName; + return Authority.replaceWithRegionalInformation(metadata, autodetectedRegionName); + } + this.regionDiscoveryMetadata.region_outcome = + RegionDiscoveryOutcomes.AUTO_DETECTION_REQUESTED_FAILED; + } + return metadata; + } + /** + * Updates the AuthorityMetadataEntity with new aliases, preferred_network and preferred_cache + * and returns where the information was retrieved from + * @param metadataEntity + * @returns AuthorityMetadataSource + */ + async updateCloudDiscoveryMetadata(metadataEntity) { + this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityUpdateCloudDiscoveryMetadata, this.correlationId); + const localMetadataSource = this.updateCloudDiscoveryMetadataFromLocalSources(metadataEntity); + if (localMetadataSource) { + return localMetadataSource; + } + // Fallback to network as metadata source + const metadata = await invokeAsync(this.getCloudDiscoveryMetadataFromNetwork.bind(this), PerformanceEvents.AuthorityGetCloudDiscoveryMetadataFromNetwork, this.logger, this.performanceClient, this.correlationId)(); + if (metadata) { + updateCloudDiscoveryMetadata(metadataEntity, metadata, true); + return AuthorityMetadataSource.NETWORK; + } + // Metadata could not be obtained from the config, cache, network or hardcoded values + throw createClientConfigurationError(untrustedAuthority); + } + updateCloudDiscoveryMetadataFromLocalSources(metadataEntity) { + this.logger.verbose("Attempting to get cloud discovery metadata from authority configuration"); + this.logger.verbosePii(`Known Authorities: ${this.authorityOptions.knownAuthorities || + Constants.NOT_APPLICABLE}`); + this.logger.verbosePii(`Authority Metadata: ${this.authorityOptions.authorityMetadata || + Constants.NOT_APPLICABLE}`); + this.logger.verbosePii(`Canonical Authority: ${metadataEntity.canonical_authority || Constants.NOT_APPLICABLE}`); + const metadata = this.getCloudDiscoveryMetadataFromConfig(); + if (metadata) { + this.logger.verbose("Found cloud discovery metadata in authority configuration"); + updateCloudDiscoveryMetadata(metadataEntity, metadata, false); + return AuthorityMetadataSource.CONFIG; + } + // If the cached metadata came from config but that config was not passed to this instance, we must go to hardcoded values + this.logger.verbose("Did not find cloud discovery metadata in the config... Attempting to get cloud discovery metadata from the hardcoded values."); + if (this.options.skipAuthorityMetadataCache) { + this.logger.verbose("Skipping hardcoded cloud discovery metadata cache since skipAuthorityMetadataCache is set to true. Attempting to get cloud discovery metadata from the network metadata cache."); + } + else { + const hardcodedMetadata = getCloudDiscoveryMetadataFromHardcodedValues(this.hostnameAndPort); + if (hardcodedMetadata) { + this.logger.verbose("Found cloud discovery metadata from hardcoded values."); + updateCloudDiscoveryMetadata(metadataEntity, hardcodedMetadata, false); + return AuthorityMetadataSource.HARDCODED_VALUES; + } + this.logger.verbose("Did not find cloud discovery metadata in hardcoded values... Attempting to get cloud discovery metadata from the network metadata cache."); + } + const metadataEntityExpired = isAuthorityMetadataExpired(metadataEntity); + if (this.isAuthoritySameType(metadataEntity) && + metadataEntity.aliasesFromNetwork && + !metadataEntityExpired) { + this.logger.verbose("Found cloud discovery metadata in the cache."); + // No need to update + return AuthorityMetadataSource.CACHE; + } + else if (metadataEntityExpired) { + this.logger.verbose("The metadata entity is expired."); + } + return null; + } + /** + * Parse cloudDiscoveryMetadata config or check knownAuthorities + */ + getCloudDiscoveryMetadataFromConfig() { + // CIAM does not support cloud discovery metadata + if (this.authorityType === AuthorityType.Ciam) { + this.logger.verbose("CIAM authorities do not support cloud discovery metadata, generate the aliases from authority host."); + return Authority.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort); + } + // Check if network response was provided in config + if (this.authorityOptions.cloudDiscoveryMetadata) { + this.logger.verbose("The cloud discovery metadata has been provided as a network response, in the config."); + try { + this.logger.verbose("Attempting to parse the cloud discovery metadata."); + const parsedResponse = JSON.parse(this.authorityOptions.cloudDiscoveryMetadata); + const metadata = getCloudDiscoveryMetadataFromNetworkResponse(parsedResponse.metadata, this.hostnameAndPort); + this.logger.verbose("Parsed the cloud discovery metadata."); + if (metadata) { + this.logger.verbose("There is returnable metadata attached to the parsed cloud discovery metadata."); + return metadata; + } + else { + this.logger.verbose("There is no metadata attached to the parsed cloud discovery metadata."); + } + } + catch (e) { + this.logger.verbose("Unable to parse the cloud discovery metadata. Throwing Invalid Cloud Discovery Metadata Error."); + throw createClientConfigurationError(invalidCloudDiscoveryMetadata); + } + } + // If cloudDiscoveryMetadata is empty or does not contain the host, check knownAuthorities + if (this.isInKnownAuthorities()) { + this.logger.verbose("The host is included in knownAuthorities. Creating new cloud discovery metadata from the host."); + return Authority.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort); + } + return null; + } + /** + * Called to get metadata from network if CloudDiscoveryMetadata was not populated by config + * + * @param hasHardcodedMetadata boolean + */ + async getCloudDiscoveryMetadataFromNetwork() { + this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityGetCloudDiscoveryMetadataFromNetwork, this.correlationId); + const instanceDiscoveryEndpoint = `${Constants.AAD_INSTANCE_DISCOVERY_ENDPT}${this.canonicalAuthority}oauth2/v2.0/authorize`; + const options = {}; + /* + * TODO: Add a timeout if the authority exists in our library's + * hardcoded list of metadata + */ + let match = null; + try { + const response = await this.networkInterface.sendGetRequestAsync(instanceDiscoveryEndpoint, options); + let typedResponseBody; + let metadata; + if (isCloudInstanceDiscoveryResponse(response.body)) { + typedResponseBody = + response.body; + metadata = typedResponseBody.metadata; + this.logger.verbosePii(`tenant_discovery_endpoint is: ${typedResponseBody.tenant_discovery_endpoint}`); + } + else if (isCloudInstanceDiscoveryErrorResponse(response.body)) { + this.logger.warning(`A CloudInstanceDiscoveryErrorResponse was returned. The cloud instance discovery network request's status code is: ${response.status}`); + typedResponseBody = + response.body; + if (typedResponseBody.error === Constants.INVALID_INSTANCE) { + this.logger.error("The CloudInstanceDiscoveryErrorResponse error is invalid_instance."); + return null; + } + this.logger.warning(`The CloudInstanceDiscoveryErrorResponse error is ${typedResponseBody.error}`); + this.logger.warning(`The CloudInstanceDiscoveryErrorResponse error description is ${typedResponseBody.error_description}`); + this.logger.warning("Setting the value of the CloudInstanceDiscoveryMetadata (returned from the network) to []"); + metadata = []; + } + else { + this.logger.error("AAD did not return a CloudInstanceDiscoveryResponse or CloudInstanceDiscoveryErrorResponse"); + return null; + } + this.logger.verbose("Attempting to find a match between the developer's authority and the CloudInstanceDiscoveryMetadata returned from the network request."); + match = getCloudDiscoveryMetadataFromNetworkResponse(metadata, this.hostnameAndPort); + } + catch (error) { + if (error instanceof AuthError) { + this.logger.error(`There was a network error while attempting to get the cloud discovery instance metadata.\nError: ${error.errorCode}\nError Description: ${error.errorMessage}`); + } + else { + const typedError = error; + this.logger.error(`A non-MSALJS error was thrown while attempting to get the cloud instance discovery metadata.\nError: ${typedError.name}\nError Description: ${typedError.message}`); + } + return null; + } + // Custom Domain scenario, host is trusted because Instance Discovery call succeeded + if (!match) { + this.logger.warning("The developer's authority was not found within the CloudInstanceDiscoveryMetadata returned from the network request."); + this.logger.verbose("Creating custom Authority for custom domain scenario."); + match = Authority.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort); + } + return match; + } + /** + * Helper function to determine if this host is included in the knownAuthorities config option + */ + isInKnownAuthorities() { + const matches = this.authorityOptions.knownAuthorities.filter((authority) => { + return (authority && + UrlString.getDomainFromUrl(authority).toLowerCase() === + this.hostnameAndPort); + }); + return matches.length > 0; + } + /** + * helper function to populate the authority based on azureCloudOptions + * @param authorityString + * @param azureCloudOptions + */ + static generateAuthority(authorityString, azureCloudOptions) { + let authorityAzureCloudInstance; + if (azureCloudOptions && + azureCloudOptions.azureCloudInstance !== AzureCloudInstance.None) { + const tenant = azureCloudOptions.tenant + ? azureCloudOptions.tenant + : Constants.DEFAULT_COMMON_TENANT; + authorityAzureCloudInstance = `${azureCloudOptions.azureCloudInstance}/${tenant}/`; + } + return authorityAzureCloudInstance + ? authorityAzureCloudInstance + : authorityString; + } + /** + * Creates cloud discovery metadata object from a given host + * @param host + */ + static createCloudDiscoveryMetadataFromHost(host) { + return { + preferred_network: host, + preferred_cache: host, + aliases: [host], + }; + } + /** + * helper function to generate environment from authority object + */ + getPreferredCache() { + if (this.managedIdentity) { + return Constants.DEFAULT_AUTHORITY_HOST; + } + else if (this.discoveryComplete()) { + return this.metadata.preferred_cache; + } + else { + throw createClientAuthError(endpointResolutionError); + } + } + /** + * Returns whether or not the provided host is an alias of this authority instance + * @param host + */ + isAlias(host) { + return this.metadata.aliases.indexOf(host) > -1; + } + /** + * Returns whether or not the provided host is an alias of a known Microsoft authority for purposes of endpoint discovery + * @param host + */ + isAliasOfKnownMicrosoftAuthority(host) { + return InstanceDiscoveryMetadataAliases.has(host); + } + /** + * Checks whether the provided host is that of a public cloud authority + * + * @param authority string + * @returns bool + */ + static isPublicCloudAuthority(host) { + return Constants.KNOWN_PUBLIC_CLOUDS.indexOf(host) >= 0; + } + /** + * Rebuild the authority string with the region + * + * @param host string + * @param region string + */ + static buildRegionalAuthorityString(host, region, queryString) { + // Create and validate a Url string object with the initial authority string + const authorityUrlInstance = new UrlString(host); + authorityUrlInstance.validateAsUri(); + const authorityUrlParts = authorityUrlInstance.getUrlComponents(); + let hostNameAndPort = `${region}.${authorityUrlParts.HostNameAndPort}`; + if (this.isPublicCloudAuthority(authorityUrlParts.HostNameAndPort)) { + hostNameAndPort = `${region}.${Constants.REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX}`; + } + // Include the query string portion of the url + const url = UrlString.constructAuthorityUriFromObject({ + ...authorityUrlInstance.getUrlComponents(), + HostNameAndPort: hostNameAndPort, + }).urlString; + // Add the query string if a query string was provided + if (queryString) + return `${url}?${queryString}`; + return url; + } + /** + * Replace the endpoints in the metadata object with their regional equivalents. + * + * @param metadata OpenIdConfigResponse + * @param azureRegion string + */ + static replaceWithRegionalInformation(metadata, azureRegion) { + const regionalMetadata = { ...metadata }; + regionalMetadata.authorization_endpoint = + Authority.buildRegionalAuthorityString(regionalMetadata.authorization_endpoint, azureRegion); + regionalMetadata.token_endpoint = + Authority.buildRegionalAuthorityString(regionalMetadata.token_endpoint, azureRegion); + if (regionalMetadata.end_session_endpoint) { + regionalMetadata.end_session_endpoint = + Authority.buildRegionalAuthorityString(regionalMetadata.end_session_endpoint, azureRegion); + } + return regionalMetadata; + } + /** + * Transform CIAM_AUTHORIY as per the below rules: + * If no path segments found and it is a CIAM authority (hostname ends with .ciamlogin.com), then transform it + * + * NOTE: The transformation path should go away once STS supports CIAM with the format: `tenantIdorDomain.ciamlogin.com` + * `ciamlogin.com` can also change in the future and we should accommodate the same + * + * @param authority + */ + static transformCIAMAuthority(authority) { + let ciamAuthority = authority; + const authorityUrl = new UrlString(authority); + const authorityUrlComponents = authorityUrl.getUrlComponents(); + // check if transformation is needed + if (authorityUrlComponents.PathSegments.length === 0 && + authorityUrlComponents.HostNameAndPort.endsWith(Constants.CIAM_AUTH_URL)) { + const tenantIdOrDomain = authorityUrlComponents.HostNameAndPort.split(".")[0]; + ciamAuthority = `${ciamAuthority}${tenantIdOrDomain}${Constants.AAD_TENANT_DOMAIN_SUFFIX}`; + } + return ciamAuthority; + } +} +// Reserved tenant domain names that will not be replaced with tenant id +Authority.reservedTenantDomains = new Set([ + "{tenant}", + "{tenantid}", + AADAuthorityConstants.COMMON, + AADAuthorityConstants.CONSUMERS, + AADAuthorityConstants.ORGANIZATIONS, +]); +/** + * Extract tenantId from authority + */ +function getTenantFromAuthorityString(authority) { + const authorityUrl = new UrlString(authority); + const authorityUrlComponents = authorityUrl.getUrlComponents(); + /** + * For credential matching purposes, tenantId is the last path segment of the authority URL: + * AAD Authority - domain/tenantId -> Credentials are cached with realm = tenantId + * B2C Authority - domain/{tenantId}?/.../policy -> Credentials are cached with realm = policy + * tenantId is downcased because B2C policies can have mixed case but tfp claim is downcased + * + * Note that we may not have any path segments in certain OIDC scenarios. + */ + const tenantId = authorityUrlComponents.PathSegments.slice(-1)[0]?.toLowerCase(); + switch (tenantId) { + case AADAuthorityConstants.COMMON: + case AADAuthorityConstants.ORGANIZATIONS: + case AADAuthorityConstants.CONSUMERS: + return undefined; + default: + return tenantId; + } +} +function formatAuthorityUri(authorityUri) { + return authorityUri.endsWith(Constants.FORWARD_SLASH) + ? authorityUri + : `${authorityUri}${Constants.FORWARD_SLASH}`; +} +function buildStaticAuthorityOptions(authOptions) { + const rawCloudDiscoveryMetadata = authOptions.cloudDiscoveryMetadata; + let cloudDiscoveryMetadata = undefined; + if (rawCloudDiscoveryMetadata) { + try { + cloudDiscoveryMetadata = JSON.parse(rawCloudDiscoveryMetadata); + } + catch (e) { + throw createClientConfigurationError(invalidCloudDiscoveryMetadata); + } + } + return { + canonicalAuthority: authOptions.authority + ? formatAuthorityUri(authOptions.authority) + : undefined, + knownAuthorities: authOptions.knownAuthorities, + cloudDiscoveryMetadata: cloudDiscoveryMetadata, + }; +} + +export { Authority, buildStaticAuthorityOptions, formatAuthorityUri, getTenantFromAuthorityString }; +//# sourceMappingURL=Authority.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/authority/AuthorityFactory.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/authority/AuthorityFactory.mjs new file mode 100644 index 00000000..53341f26 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/authority/AuthorityFactory.mjs @@ -0,0 +1,39 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +import { Authority, formatAuthorityUri } from './Authority.mjs'; +import { createClientAuthError } from '../error/ClientAuthError.mjs'; +import { PerformanceEvents } from '../telemetry/performance/PerformanceEvent.mjs'; +import { invokeAsync } from '../utils/FunctionWrappers.mjs'; +import { endpointResolutionError } from '../error/ClientAuthErrorCodes.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * Create an authority object of the correct type based on the url + * Performs basic authority validation - checks to see if the authority is of a valid type (i.e. aad, b2c, adfs) + * + * Also performs endpoint discovery. + * + * @param authorityUri + * @param networkClient + * @param protocolMode + * @internal + */ +async function createDiscoveredInstance(authorityUri, networkClient, cacheManager, authorityOptions, logger, correlationId, performanceClient) { + performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityFactoryCreateDiscoveredInstance, correlationId); + const authorityUriFinal = Authority.transformCIAMAuthority(formatAuthorityUri(authorityUri)); + // Initialize authority and perform discovery endpoint check. + const acquireTokenAuthority = new Authority(authorityUriFinal, networkClient, cacheManager, authorityOptions, logger, correlationId, performanceClient); + try { + await invokeAsync(acquireTokenAuthority.resolveEndpointsAsync.bind(acquireTokenAuthority), PerformanceEvents.AuthorityResolveEndpointsAsync, logger, performanceClient, correlationId)(); + return acquireTokenAuthority; + } + catch (e) { + throw createClientAuthError(endpointResolutionError); + } +} + +export { createDiscoveredInstance }; +//# sourceMappingURL=AuthorityFactory.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/authority/AuthorityMetadata.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/authority/AuthorityMetadata.mjs new file mode 100644 index 00000000..61beae40 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/authority/AuthorityMetadata.mjs @@ -0,0 +1,144 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +import { UrlString } from '../url/UrlString.mjs'; +import { AuthorityMetadataSource } from '../utils/Constants.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +const rawMetdataJSON = { + endpointMetadata: { + "login.microsoftonline.com": { + token_endpoint: "https://login.microsoftonline.com/{tenantid}/oauth2/v2.0/token", + jwks_uri: "https://login.microsoftonline.com/{tenantid}/discovery/v2.0/keys", + issuer: "https://login.microsoftonline.com/{tenantid}/v2.0", + authorization_endpoint: "https://login.microsoftonline.com/{tenantid}/oauth2/v2.0/authorize", + end_session_endpoint: "https://login.microsoftonline.com/{tenantid}/oauth2/v2.0/logout", + }, + "login.chinacloudapi.cn": { + token_endpoint: "https://login.chinacloudapi.cn/{tenantid}/oauth2/v2.0/token", + jwks_uri: "https://login.chinacloudapi.cn/{tenantid}/discovery/v2.0/keys", + issuer: "https://login.partner.microsoftonline.cn/{tenantid}/v2.0", + authorization_endpoint: "https://login.chinacloudapi.cn/{tenantid}/oauth2/v2.0/authorize", + end_session_endpoint: "https://login.chinacloudapi.cn/{tenantid}/oauth2/v2.0/logout", + }, + "login.microsoftonline.us": { + token_endpoint: "https://login.microsoftonline.us/{tenantid}/oauth2/v2.0/token", + jwks_uri: "https://login.microsoftonline.us/{tenantid}/discovery/v2.0/keys", + issuer: "https://login.microsoftonline.us/{tenantid}/v2.0", + authorization_endpoint: "https://login.microsoftonline.us/{tenantid}/oauth2/v2.0/authorize", + end_session_endpoint: "https://login.microsoftonline.us/{tenantid}/oauth2/v2.0/logout", + }, + }, + instanceDiscoveryMetadata: { + metadata: [ + { + preferred_network: "login.microsoftonline.com", + preferred_cache: "login.windows.net", + aliases: [ + "login.microsoftonline.com", + "login.windows.net", + "login.microsoft.com", + "sts.windows.net", + ], + }, + { + preferred_network: "login.partner.microsoftonline.cn", + preferred_cache: "login.partner.microsoftonline.cn", + aliases: [ + "login.partner.microsoftonline.cn", + "login.chinacloudapi.cn", + ], + }, + { + preferred_network: "login.microsoftonline.de", + preferred_cache: "login.microsoftonline.de", + aliases: ["login.microsoftonline.de"], + }, + { + preferred_network: "login.microsoftonline.us", + preferred_cache: "login.microsoftonline.us", + aliases: [ + "login.microsoftonline.us", + "login.usgovcloudapi.net", + ], + }, + { + preferred_network: "login-us.microsoftonline.com", + preferred_cache: "login-us.microsoftonline.com", + aliases: ["login-us.microsoftonline.com"], + }, + ], + }, +}; +const EndpointMetadata = rawMetdataJSON.endpointMetadata; +const InstanceDiscoveryMetadata = rawMetdataJSON.instanceDiscoveryMetadata; +const InstanceDiscoveryMetadataAliases = new Set(); +InstanceDiscoveryMetadata.metadata.forEach((metadataEntry) => { + metadataEntry.aliases.forEach((alias) => { + InstanceDiscoveryMetadataAliases.add(alias); + }); +}); +/** + * Attempts to get an aliases array from the static authority metadata sources based on the canonical authority host + * @param staticAuthorityOptions + * @param logger + * @returns + */ +function getAliasesFromStaticSources(staticAuthorityOptions, logger) { + let staticAliases; + const canonicalAuthority = staticAuthorityOptions.canonicalAuthority; + if (canonicalAuthority) { + const authorityHost = new UrlString(canonicalAuthority).getUrlComponents().HostNameAndPort; + staticAliases = + getAliasesFromMetadata(authorityHost, staticAuthorityOptions.cloudDiscoveryMetadata?.metadata, AuthorityMetadataSource.CONFIG, logger) || + getAliasesFromMetadata(authorityHost, InstanceDiscoveryMetadata.metadata, AuthorityMetadataSource.HARDCODED_VALUES, logger) || + staticAuthorityOptions.knownAuthorities; + } + return staticAliases || []; +} +/** + * Returns aliases for from the raw cloud discovery metadata passed in + * @param authorityHost + * @param rawCloudDiscoveryMetadata + * @returns + */ +function getAliasesFromMetadata(authorityHost, cloudDiscoveryMetadata, source, logger) { + logger?.trace(`getAliasesFromMetadata called with source: ${source}`); + if (authorityHost && cloudDiscoveryMetadata) { + const metadata = getCloudDiscoveryMetadataFromNetworkResponse(cloudDiscoveryMetadata, authorityHost); + if (metadata) { + logger?.trace(`getAliasesFromMetadata: found cloud discovery metadata in ${source}, returning aliases`); + return metadata.aliases; + } + else { + logger?.trace(`getAliasesFromMetadata: did not find cloud discovery metadata in ${source}`); + } + } + return null; +} +/** + * Get cloud discovery metadata for common authorities + */ +function getCloudDiscoveryMetadataFromHardcodedValues(authorityHost) { + const metadata = getCloudDiscoveryMetadataFromNetworkResponse(InstanceDiscoveryMetadata.metadata, authorityHost); + return metadata; +} +/** + * Searches instance discovery network response for the entry that contains the host in the aliases list + * @param response + * @param authority + */ +function getCloudDiscoveryMetadataFromNetworkResponse(response, authorityHost) { + for (let i = 0; i < response.length; i++) { + const metadata = response[i]; + if (metadata.aliases.includes(authorityHost)) { + return metadata; + } + } + return null; +} + +export { EndpointMetadata, InstanceDiscoveryMetadata, InstanceDiscoveryMetadataAliases, getAliasesFromMetadata, getAliasesFromStaticSources, getCloudDiscoveryMetadataFromHardcodedValues, getCloudDiscoveryMetadataFromNetworkResponse, rawMetdataJSON }; +//# sourceMappingURL=AuthorityMetadata.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/authority/AuthorityOptions.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/authority/AuthorityOptions.mjs new file mode 100644 index 00000000..f78d2198 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/authority/AuthorityOptions.mjs @@ -0,0 +1,23 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +const AzureCloudInstance = { + // AzureCloudInstance is not specified. + None: "none", + // Microsoft Azure public cloud + AzurePublic: "https://login.microsoftonline.com", + // Microsoft PPE + AzurePpe: "https://login.windows-ppe.net", + // Microsoft Chinese national/regional cloud + AzureChina: "https://login.chinacloudapi.cn", + // Microsoft German national/regional cloud ("Black Forest") + AzureGermany: "https://login.microsoftonline.de", + // US Government cloud + AzureUsGovernment: "https://login.microsoftonline.us", +}; + +export { AzureCloudInstance }; +//# sourceMappingURL=AuthorityOptions.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/authority/AuthorityType.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/authority/AuthorityType.mjs new file mode 100644 index 00000000..a29e4839 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/authority/AuthorityType.mjs @@ -0,0 +1,18 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * Authority types supported by MSAL. + */ +const AuthorityType = { + Default: 0, + Adfs: 1, + Dsts: 2, + Ciam: 3, +}; + +export { AuthorityType }; +//# sourceMappingURL=AuthorityType.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/authority/CloudInstanceDiscoveryErrorResponse.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/authority/CloudInstanceDiscoveryErrorResponse.mjs new file mode 100644 index 00000000..71709801 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/authority/CloudInstanceDiscoveryErrorResponse.mjs @@ -0,0 +1,13 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +function isCloudInstanceDiscoveryErrorResponse(response) { + return (response.hasOwnProperty("error") && + response.hasOwnProperty("error_description")); +} + +export { isCloudInstanceDiscoveryErrorResponse }; +//# sourceMappingURL=CloudInstanceDiscoveryErrorResponse.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/authority/CloudInstanceDiscoveryResponse.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/authority/CloudInstanceDiscoveryResponse.mjs new file mode 100644 index 00000000..6608cb34 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/authority/CloudInstanceDiscoveryResponse.mjs @@ -0,0 +1,13 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +function isCloudInstanceDiscoveryResponse(response) { + return (response.hasOwnProperty("tenant_discovery_endpoint") && + response.hasOwnProperty("metadata")); +} + +export { isCloudInstanceDiscoveryResponse }; +//# sourceMappingURL=CloudInstanceDiscoveryResponse.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/authority/OpenIdConfigResponse.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/authority/OpenIdConfigResponse.mjs new file mode 100644 index 00000000..99b0ef61 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/authority/OpenIdConfigResponse.mjs @@ -0,0 +1,15 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +function isOpenIdConfigResponse(response) { + return (response.hasOwnProperty("authorization_endpoint") && + response.hasOwnProperty("token_endpoint") && + response.hasOwnProperty("issuer") && + response.hasOwnProperty("jwks_uri")); +} + +export { isOpenIdConfigResponse }; +//# sourceMappingURL=OpenIdConfigResponse.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/authority/ProtocolMode.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/authority/ProtocolMode.mjs new file mode 100644 index 00000000..cd2d7d2b --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/authority/ProtocolMode.mjs @@ -0,0 +1,27 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * Protocol modes supported by MSAL. + */ +const ProtocolMode = { + /** + * Auth Code + PKCE with Entra ID (formerly AAD) specific optimizations and features + */ + AAD: "AAD", + /** + * Auth Code + PKCE without Entra ID specific optimizations and features. For use only with non-Microsoft owned authorities. + * Support is limited for this mode. + */ + OIDC: "OIDC", + /** + * Encrypted Authorize Response (EAR) with Entra ID specific optimizations and features + */ + EAR: "EAR", +}; + +export { ProtocolMode }; +//# sourceMappingURL=ProtocolMode.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/authority/RegionDiscovery.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/authority/RegionDiscovery.mjs new file mode 100644 index 00000000..c144b170 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/authority/RegionDiscovery.mjs @@ -0,0 +1,112 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +import { Constants, HttpStatus, RegionDiscoverySources } from '../utils/Constants.mjs'; +import { PerformanceEvents } from '../telemetry/performance/PerformanceEvent.mjs'; +import { invokeAsync } from '../utils/FunctionWrappers.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +class RegionDiscovery { + constructor(networkInterface, logger, performanceClient, correlationId) { + this.networkInterface = networkInterface; + this.logger = logger; + this.performanceClient = performanceClient; + this.correlationId = correlationId; + } + /** + * Detect the region from the application's environment. + * + * @returns Promise + */ + async detectRegion(environmentRegion, regionDiscoveryMetadata) { + this.performanceClient?.addQueueMeasurement(PerformanceEvents.RegionDiscoveryDetectRegion, this.correlationId); + // Initialize auto detected region with the region from the envrionment + let autodetectedRegionName = environmentRegion; + // Check if a region was detected from the environment, if not, attempt to get the region from IMDS + if (!autodetectedRegionName) { + const options = RegionDiscovery.IMDS_OPTIONS; + try { + const localIMDSVersionResponse = await invokeAsync(this.getRegionFromIMDS.bind(this), PerformanceEvents.RegionDiscoveryGetRegionFromIMDS, this.logger, this.performanceClient, this.correlationId)(Constants.IMDS_VERSION, options); + if (localIMDSVersionResponse.status === HttpStatus.SUCCESS) { + autodetectedRegionName = localIMDSVersionResponse.body; + regionDiscoveryMetadata.region_source = + RegionDiscoverySources.IMDS; + } + // If the response using the local IMDS version failed, try to fetch the current version of IMDS and retry. + if (localIMDSVersionResponse.status === HttpStatus.BAD_REQUEST) { + const currentIMDSVersion = await invokeAsync(this.getCurrentVersion.bind(this), PerformanceEvents.RegionDiscoveryGetCurrentVersion, this.logger, this.performanceClient, this.correlationId)(options); + if (!currentIMDSVersion) { + regionDiscoveryMetadata.region_source = + RegionDiscoverySources.FAILED_AUTO_DETECTION; + return null; + } + const currentIMDSVersionResponse = await invokeAsync(this.getRegionFromIMDS.bind(this), PerformanceEvents.RegionDiscoveryGetRegionFromIMDS, this.logger, this.performanceClient, this.correlationId)(currentIMDSVersion, options); + if (currentIMDSVersionResponse.status === HttpStatus.SUCCESS) { + autodetectedRegionName = + currentIMDSVersionResponse.body; + regionDiscoveryMetadata.region_source = + RegionDiscoverySources.IMDS; + } + } + } + catch (e) { + regionDiscoveryMetadata.region_source = + RegionDiscoverySources.FAILED_AUTO_DETECTION; + return null; + } + } + else { + regionDiscoveryMetadata.region_source = + RegionDiscoverySources.ENVIRONMENT_VARIABLE; + } + // If no region was auto detected from the environment or from the IMDS endpoint, mark the attempt as a FAILED_AUTO_DETECTION + if (!autodetectedRegionName) { + regionDiscoveryMetadata.region_source = + RegionDiscoverySources.FAILED_AUTO_DETECTION; + } + return autodetectedRegionName || null; + } + /** + * Make the call to the IMDS endpoint + * + * @param imdsEndpointUrl + * @returns Promise> + */ + async getRegionFromIMDS(version, options) { + this.performanceClient?.addQueueMeasurement(PerformanceEvents.RegionDiscoveryGetRegionFromIMDS, this.correlationId); + return this.networkInterface.sendGetRequestAsync(`${Constants.IMDS_ENDPOINT}?api-version=${version}&format=text`, options, Constants.IMDS_TIMEOUT); + } + /** + * Get the most recent version of the IMDS endpoint available + * + * @returns Promise + */ + async getCurrentVersion(options) { + this.performanceClient?.addQueueMeasurement(PerformanceEvents.RegionDiscoveryGetCurrentVersion, this.correlationId); + try { + const response = await this.networkInterface.sendGetRequestAsync(`${Constants.IMDS_ENDPOINT}?format=json`, options); + // When IMDS endpoint is called without the api version query param, bad request response comes back with latest version. + if (response.status === HttpStatus.BAD_REQUEST && + response.body && + response.body["newest-versions"] && + response.body["newest-versions"].length > 0) { + return response.body["newest-versions"][0]; + } + return null; + } + catch (e) { + return null; + } + } +} +// Options for the IMDS endpoint request +RegionDiscovery.IMDS_OPTIONS = { + headers: { + Metadata: "true", + }, +}; + +export { RegionDiscovery }; +//# sourceMappingURL=RegionDiscovery.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/cache/CacheManager.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/cache/CacheManager.mjs new file mode 100644 index 00000000..7d4a67d4 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/cache/CacheManager.mjs @@ -0,0 +1,1124 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +import { CredentialType, AuthenticationScheme, THE_FAMILY_ID, APP_METADATA, AUTHORITY_METADATA_CONSTANTS } from '../utils/Constants.mjs'; +import { ScopeSet } from '../request/ScopeSet.mjs'; +import { AccountEntity } from './entities/AccountEntity.mjs'; +import { createClientAuthError } from '../error/ClientAuthError.mjs'; +import { updateAccountTenantProfileData } from '../account/AccountInfo.mjs'; +import { extractTokenClaims } from '../account/AuthToken.mjs'; +import { name, version } from '../packageMetadata.mjs'; +import { getAliasesFromStaticSources } from '../authority/AuthorityMetadata.mjs'; +import { createCacheError } from '../error/CacheError.mjs'; +import { AuthError } from '../error/AuthError.mjs'; +import { invalidCacheRecord, multipleMatchingAppMetadata, methodNotImplemented } from '../error/ClientAuthErrorCodes.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * Interface class which implement cache storage functions used by MSAL to perform validity checks, and store tokens. + * @internal + */ +class CacheManager { + constructor(clientId, cryptoImpl, logger, performanceClient, staticAuthorityOptions) { + this.clientId = clientId; + this.cryptoImpl = cryptoImpl; + this.commonLogger = logger.clone(name, version); + this.staticAuthorityOptions = staticAuthorityOptions; + this.performanceClient = performanceClient; + } + /** + * Returns all the accounts in the cache that match the optional filter. If no filter is provided, all accounts are returned. + * @param accountFilter - (Optional) filter to narrow down the accounts returned + * @returns Array of AccountInfo objects in cache + */ + getAllAccounts(accountFilter, correlationId) { + return this.buildTenantProfiles(this.getAccountsFilteredBy(accountFilter, correlationId), correlationId, accountFilter); + } + /** + * Gets first tenanted AccountInfo object found based on provided filters + */ + getAccountInfoFilteredBy(accountFilter, correlationId) { + if (Object.keys(accountFilter).length === 0 || + Object.values(accountFilter).every((value) => !value)) { + this.commonLogger.warning("getAccountInfoFilteredBy: Account filter is empty or invalid, returning null"); + return null; + } + const allAccounts = this.getAllAccounts(accountFilter, correlationId); + if (allAccounts.length > 1) { + // If one or more accounts are found, prioritize accounts that have an ID token + const sortedAccounts = allAccounts.sort((account) => { + return account.idTokenClaims ? -1 : 1; + }); + return sortedAccounts[0]; + } + else if (allAccounts.length === 1) { + // If only one account is found, return it regardless of whether a matching ID token was found + return allAccounts[0]; + } + else { + return null; + } + } + /** + * Returns a single matching + * @param accountFilter + * @returns + */ + getBaseAccountInfo(accountFilter, correlationId) { + const accountEntities = this.getAccountsFilteredBy(accountFilter, correlationId); + if (accountEntities.length > 0) { + return AccountEntity.getAccountInfo(accountEntities[0]); + } + else { + return null; + } + } + /** + * Matches filtered account entities with cached ID tokens that match the tenant profile-specific account filters + * and builds the account info objects from the matching ID token's claims + * @param cachedAccounts + * @param accountFilter + * @returns Array of AccountInfo objects that match account and tenant profile filters + */ + buildTenantProfiles(cachedAccounts, correlationId, accountFilter) { + return cachedAccounts.flatMap((accountEntity) => { + return this.getTenantProfilesFromAccountEntity(accountEntity, correlationId, accountFilter?.tenantId, accountFilter); + }); + } + getTenantedAccountInfoByFilter(accountInfo, tokenKeys, tenantProfile, correlationId, tenantProfileFilter) { + let tenantedAccountInfo = null; + let idTokenClaims; + if (tenantProfileFilter) { + if (!this.tenantProfileMatchesFilter(tenantProfile, tenantProfileFilter)) { + return null; + } + } + const idToken = this.getIdToken(accountInfo, correlationId, tokenKeys, tenantProfile.tenantId); + if (idToken) { + idTokenClaims = extractTokenClaims(idToken.secret, this.cryptoImpl.base64Decode); + if (!this.idTokenClaimsMatchTenantProfileFilter(idTokenClaims, tenantProfileFilter)) { + // ID token sourced claims don't match so this tenant profile is not a match + return null; + } + } + // Expand tenant profile into account info based on matching tenant profile and if available matching ID token claims + tenantedAccountInfo = updateAccountTenantProfileData(accountInfo, tenantProfile, idTokenClaims, idToken?.secret); + return tenantedAccountInfo; + } + getTenantProfilesFromAccountEntity(accountEntity, correlationId, targetTenantId, tenantProfileFilter) { + const accountInfo = AccountEntity.getAccountInfo(accountEntity); + let searchTenantProfiles = accountInfo.tenantProfiles || new Map(); + const tokenKeys = this.getTokenKeys(); + // If a tenant ID was provided, only return the tenant profile for that tenant ID if it exists + if (targetTenantId) { + const tenantProfile = searchTenantProfiles.get(targetTenantId); + if (tenantProfile) { + // Reduce search field to just this tenant profile + searchTenantProfiles = new Map([ + [targetTenantId, tenantProfile], + ]); + } + else { + // No tenant profile for search tenant ID, return empty array + return []; + } + } + const matchingTenantProfiles = []; + searchTenantProfiles.forEach((tenantProfile) => { + const tenantedAccountInfo = this.getTenantedAccountInfoByFilter(accountInfo, tokenKeys, tenantProfile, correlationId, tenantProfileFilter); + if (tenantedAccountInfo) { + matchingTenantProfiles.push(tenantedAccountInfo); + } + }); + return matchingTenantProfiles; + } + tenantProfileMatchesFilter(tenantProfile, tenantProfileFilter) { + if (!!tenantProfileFilter.localAccountId && + !this.matchLocalAccountIdFromTenantProfile(tenantProfile, tenantProfileFilter.localAccountId)) { + return false; + } + if (!!tenantProfileFilter.name && + !(tenantProfile.name === tenantProfileFilter.name)) { + return false; + } + if (tenantProfileFilter.isHomeTenant !== undefined && + !(tenantProfile.isHomeTenant === tenantProfileFilter.isHomeTenant)) { + return false; + } + return true; + } + idTokenClaimsMatchTenantProfileFilter(idTokenClaims, tenantProfileFilter) { + // Tenant Profile filtering + if (tenantProfileFilter) { + if (!!tenantProfileFilter.localAccountId && + !this.matchLocalAccountIdFromTokenClaims(idTokenClaims, tenantProfileFilter.localAccountId)) { + return false; + } + if (!!tenantProfileFilter.loginHint && + !this.matchLoginHintFromTokenClaims(idTokenClaims, tenantProfileFilter.loginHint)) { + return false; + } + if (!!tenantProfileFilter.username && + !this.matchUsername(idTokenClaims.preferred_username, tenantProfileFilter.username)) { + return false; + } + if (!!tenantProfileFilter.name && + !this.matchName(idTokenClaims, tenantProfileFilter.name)) { + return false; + } + if (!!tenantProfileFilter.sid && + !this.matchSid(idTokenClaims, tenantProfileFilter.sid)) { + return false; + } + } + return true; + } + /** + * saves a cache record + * @param cacheRecord {CacheRecord} + * @param correlationId {?string} correlation id + * @param kmsi - Keep Me Signed In + * @param storeInCache {?StoreInCache} + */ + async saveCacheRecord(cacheRecord, correlationId, kmsi, storeInCache) { + if (!cacheRecord) { + throw createClientAuthError(invalidCacheRecord); + } + try { + if (!!cacheRecord.account) { + await this.setAccount(cacheRecord.account, correlationId, kmsi); + } + if (!!cacheRecord.idToken && storeInCache?.idToken !== false) { + await this.setIdTokenCredential(cacheRecord.idToken, correlationId, kmsi); + } + if (!!cacheRecord.accessToken && + storeInCache?.accessToken !== false) { + await this.saveAccessToken(cacheRecord.accessToken, correlationId, kmsi); + } + if (!!cacheRecord.refreshToken && + storeInCache?.refreshToken !== false) { + await this.setRefreshTokenCredential(cacheRecord.refreshToken, correlationId, kmsi); + } + if (!!cacheRecord.appMetadata) { + this.setAppMetadata(cacheRecord.appMetadata, correlationId); + } + } + catch (e) { + this.commonLogger?.error(`CacheManager.saveCacheRecord: failed`); + if (e instanceof AuthError) { + throw e; + } + else { + throw createCacheError(e); + } + } + } + /** + * saves access token credential + * @param credential + */ + async saveAccessToken(credential, correlationId, kmsi) { + const accessTokenFilter = { + clientId: credential.clientId, + credentialType: credential.credentialType, + environment: credential.environment, + homeAccountId: credential.homeAccountId, + realm: credential.realm, + tokenType: credential.tokenType, + requestedClaimsHash: credential.requestedClaimsHash, + }; + const tokenKeys = this.getTokenKeys(); + const currentScopes = ScopeSet.fromString(credential.target); + tokenKeys.accessToken.forEach((key) => { + if (!this.accessTokenKeyMatchesFilter(key, accessTokenFilter, false)) { + return; + } + const tokenEntity = this.getAccessTokenCredential(key, correlationId); + if (tokenEntity && + this.credentialMatchesFilter(tokenEntity, accessTokenFilter)) { + const tokenScopeSet = ScopeSet.fromString(tokenEntity.target); + if (tokenScopeSet.intersectingScopeSets(currentScopes)) { + this.removeAccessToken(key, correlationId); + } + } + }); + await this.setAccessTokenCredential(credential, correlationId, kmsi); + } + /** + * Retrieve account entities matching all provided tenant-agnostic filters; if no filter is set, get all account entities in the cache + * Not checking for casing as keys are all generated in lower case, remember to convert to lower case if object properties are compared + * @param accountFilter - An object containing Account properties to filter by + */ + getAccountsFilteredBy(accountFilter, correlationId) { + const allAccountKeys = this.getAccountKeys(); + const matchingAccounts = []; + allAccountKeys.forEach((cacheKey) => { + const entity = this.getAccount(cacheKey, correlationId); + // Match base account fields + if (!entity) { + return; + } + if (!!accountFilter.homeAccountId && + !this.matchHomeAccountId(entity, accountFilter.homeAccountId)) { + return; + } + if (!!accountFilter.username && + !this.matchUsername(entity.username, accountFilter.username)) { + return; + } + if (!!accountFilter.environment && + !this.matchEnvironment(entity, accountFilter.environment)) { + return; + } + if (!!accountFilter.realm && + !this.matchRealm(entity, accountFilter.realm)) { + return; + } + if (!!accountFilter.nativeAccountId && + !this.matchNativeAccountId(entity, accountFilter.nativeAccountId)) { + return; + } + if (!!accountFilter.authorityType && + !this.matchAuthorityType(entity, accountFilter.authorityType)) { + return; + } + // If at least one tenant profile matches the tenant profile filter, add the account to the list of matching accounts + const tenantProfileFilter = { + localAccountId: accountFilter?.localAccountId, + name: accountFilter?.name, + }; + const matchingTenantProfiles = entity.tenantProfiles?.filter((tenantProfile) => { + return this.tenantProfileMatchesFilter(tenantProfile, tenantProfileFilter); + }); + if (matchingTenantProfiles && matchingTenantProfiles.length === 0) { + // No tenant profile for this account matches filter, don't add to list of matching accounts + return; + } + matchingAccounts.push(entity); + }); + return matchingAccounts; + } + /** + * Returns whether or not the given credential entity matches the filter + * @param entity + * @param filter + * @returns + */ + credentialMatchesFilter(entity, filter) { + if (!!filter.clientId && !this.matchClientId(entity, filter.clientId)) { + return false; + } + if (!!filter.userAssertionHash && + !this.matchUserAssertionHash(entity, filter.userAssertionHash)) { + return false; + } + /* + * homeAccountId can be undefined, and we want to filter out cached items that have a homeAccountId of "" + * because we don't want a client_credential request to return a cached token that has a homeAccountId + */ + if (typeof filter.homeAccountId === "string" && + !this.matchHomeAccountId(entity, filter.homeAccountId)) { + return false; + } + if (!!filter.environment && + !this.matchEnvironment(entity, filter.environment)) { + return false; + } + if (!!filter.realm && !this.matchRealm(entity, filter.realm)) { + return false; + } + if (!!filter.credentialType && + !this.matchCredentialType(entity, filter.credentialType)) { + return false; + } + if (!!filter.familyId && !this.matchFamilyId(entity, filter.familyId)) { + return false; + } + /* + * idTokens do not have "target", target specific refreshTokens do exist for some types of authentication + * Resource specific refresh tokens case will be added when the support is deemed necessary + */ + if (!!filter.target && !this.matchTarget(entity, filter.target)) { + return false; + } + // If request OR cached entity has requested Claims Hash, check if they match + if (filter.requestedClaimsHash || entity.requestedClaimsHash) { + // Don't match if either is undefined or they are different + if (entity.requestedClaimsHash !== filter.requestedClaimsHash) { + return false; + } + } + // Access Token with Auth Scheme specific matching + if (entity.credentialType === + CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME) { + if (!!filter.tokenType && + !this.matchTokenType(entity, filter.tokenType)) { + return false; + } + // KeyId (sshKid) in request must match cached SSH certificate keyId because SSH cert is bound to a specific key + if (filter.tokenType === AuthenticationScheme.SSH) { + if (filter.keyId && !this.matchKeyId(entity, filter.keyId)) { + return false; + } + } + } + return true; + } + /** + * retrieve appMetadata matching all provided filters; if no filter is set, get all appMetadata + * @param filter + */ + getAppMetadataFilteredBy(filter) { + const allCacheKeys = this.getKeys(); + const matchingAppMetadata = {}; + allCacheKeys.forEach((cacheKey) => { + // don't parse any non-appMetadata type cache entities + if (!this.isAppMetadata(cacheKey)) { + return; + } + // Attempt retrieval + const entity = this.getAppMetadata(cacheKey); + if (!entity) { + return; + } + if (!!filter.environment && + !this.matchEnvironment(entity, filter.environment)) { + return; + } + if (!!filter.clientId && + !this.matchClientId(entity, filter.clientId)) { + return; + } + matchingAppMetadata[cacheKey] = entity; + }); + return matchingAppMetadata; + } + /** + * retrieve authorityMetadata that contains a matching alias + * @param filter + */ + getAuthorityMetadataByAlias(host) { + const allCacheKeys = this.getAuthorityMetadataKeys(); + let matchedEntity = null; + allCacheKeys.forEach((cacheKey) => { + // don't parse any non-authorityMetadata type cache entities + if (!this.isAuthorityMetadata(cacheKey) || + cacheKey.indexOf(this.clientId) === -1) { + return; + } + // Attempt retrieval + const entity = this.getAuthorityMetadata(cacheKey); + if (!entity) { + return; + } + if (entity.aliases.indexOf(host) === -1) { + return; + } + matchedEntity = entity; + }); + return matchedEntity; + } + /** + * Removes all accounts and related tokens from cache. + */ + removeAllAccounts(correlationId) { + const accounts = this.getAllAccounts({}, correlationId); + accounts.forEach((account) => { + this.removeAccount(account, correlationId); + }); + } + /** + * Removes the account and related tokens for a given account key + * @param account + */ + removeAccount(account, correlationId) { + this.removeAccountContext(account, correlationId); + const accountKeys = this.getAccountKeys(); + const keyFilter = (key) => { + return (key.includes(account.homeAccountId) && + key.includes(account.environment)); + }; + accountKeys.filter(keyFilter).forEach((key) => { + this.removeItem(key, correlationId); + this.performanceClient.incrementFields({ accountsRemoved: 1 }, correlationId); + }); + } + /** + * Removes credentials associated with the provided account + * @param account + */ + removeAccountContext(account, correlationId) { + const allTokenKeys = this.getTokenKeys(); + const keyFilter = (key) => { + return (key.includes(account.homeAccountId) && + key.includes(account.environment)); + }; + allTokenKeys.idToken.filter(keyFilter).forEach((key) => { + this.removeIdToken(key, correlationId); + }); + allTokenKeys.accessToken.filter(keyFilter).forEach((key) => { + this.removeAccessToken(key, correlationId); + }); + allTokenKeys.refreshToken.filter(keyFilter).forEach((key) => { + this.removeRefreshToken(key, correlationId); + }); + } + /** + * Removes accessToken from the cache + * @param key + * @param correlationId + */ + removeAccessToken(key, correlationId) { + const credential = this.getAccessTokenCredential(key, correlationId); + this.removeItem(key, correlationId); + this.performanceClient.incrementFields({ accessTokensRemoved: 1 }, correlationId); + if (!credential || + credential.credentialType.toLowerCase() !== + CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME.toLowerCase() || + credential.tokenType !== AuthenticationScheme.POP) { + // If the credential is not a PoP token, we can return + return; + } + // Remove Token Binding Key from key store for PoP Tokens Credentials + const kid = credential.keyId; + if (kid) { + void this.cryptoImpl.removeTokenBindingKey(kid).catch(() => { + this.commonLogger.error(`Failed to remove token binding key ${kid}`, correlationId); + this.performanceClient?.incrementFields({ removeTokenBindingKeyFailure: 1 }, correlationId); + }); + } + } + /** + * Removes all app metadata objects from cache. + */ + removeAppMetadata(correlationId) { + const allCacheKeys = this.getKeys(); + allCacheKeys.forEach((cacheKey) => { + if (this.isAppMetadata(cacheKey)) { + this.removeItem(cacheKey, correlationId); + } + }); + return true; + } + /** + * Retrieve IdTokenEntity from cache + * @param account {AccountInfo} + * @param tokenKeys {?TokenKeys} + * @param targetRealm {?string} + * @param performanceClient {?IPerformanceClient} + * @param correlationId {?string} + */ + getIdToken(account, correlationId, tokenKeys, targetRealm, performanceClient) { + this.commonLogger.trace("CacheManager - getIdToken called"); + const idTokenFilter = { + homeAccountId: account.homeAccountId, + environment: account.environment, + credentialType: CredentialType.ID_TOKEN, + clientId: this.clientId, + realm: targetRealm, + }; + const idTokenMap = this.getIdTokensByFilter(idTokenFilter, correlationId, tokenKeys); + const numIdTokens = idTokenMap.size; + if (numIdTokens < 1) { + this.commonLogger.info("CacheManager:getIdToken - No token found"); + return null; + } + else if (numIdTokens > 1) { + let tokensToBeRemoved = idTokenMap; + // Multiple tenant profiles and no tenant specified, pick home account + if (!targetRealm) { + const homeIdTokenMap = new Map(); + idTokenMap.forEach((idToken, key) => { + if (idToken.realm === account.tenantId) { + homeIdTokenMap.set(key, idToken); + } + }); + const numHomeIdTokens = homeIdTokenMap.size; + if (numHomeIdTokens < 1) { + this.commonLogger.info("CacheManager:getIdToken - Multiple ID tokens found for account but none match account entity tenant id, returning first result"); + return idTokenMap.values().next().value; + } + else if (numHomeIdTokens === 1) { + this.commonLogger.info("CacheManager:getIdToken - Multiple ID tokens found for account, defaulting to home tenant profile"); + return homeIdTokenMap.values().next().value; + } + else { + // Multiple ID tokens for home tenant profile, remove all and return null + tokensToBeRemoved = homeIdTokenMap; + } + } + // Multiple tokens for a single tenant profile, remove all and return null + this.commonLogger.info("CacheManager:getIdToken - Multiple matching ID tokens found, clearing them"); + tokensToBeRemoved.forEach((idToken, key) => { + this.removeIdToken(key, correlationId); + }); + if (performanceClient && correlationId) { + performanceClient.addFields({ multiMatchedID: idTokenMap.size }, correlationId); + } + return null; + } + this.commonLogger.info("CacheManager:getIdToken - Returning ID token"); + return idTokenMap.values().next().value; + } + /** + * Gets all idTokens matching the given filter + * @param filter + * @returns + */ + getIdTokensByFilter(filter, correlationId, tokenKeys) { + const idTokenKeys = (tokenKeys && tokenKeys.idToken) || this.getTokenKeys().idToken; + const idTokens = new Map(); + idTokenKeys.forEach((key) => { + if (!this.idTokenKeyMatchesFilter(key, { + clientId: this.clientId, + ...filter, + })) { + return; + } + const idToken = this.getIdTokenCredential(key, correlationId); + if (idToken && this.credentialMatchesFilter(idToken, filter)) { + idTokens.set(key, idToken); + } + }); + return idTokens; + } + /** + * Validate the cache key against filter before retrieving and parsing cache value + * @param key + * @param filter + * @returns + */ + idTokenKeyMatchesFilter(inputKey, filter) { + const key = inputKey.toLowerCase(); + if (filter.clientId && + key.indexOf(filter.clientId.toLowerCase()) === -1) { + return false; + } + if (filter.homeAccountId && + key.indexOf(filter.homeAccountId.toLowerCase()) === -1) { + return false; + } + return true; + } + /** + * Removes idToken from the cache + * @param key + */ + removeIdToken(key, correlationId) { + this.removeItem(key, correlationId); + } + /** + * Removes refresh token from the cache + * @param key + */ + removeRefreshToken(key, correlationId) { + this.removeItem(key, correlationId); + } + /** + * Retrieve AccessTokenEntity from cache + * @param account {AccountInfo} + * @param request {BaseAuthRequest} + * @param correlationId {?string} + * @param tokenKeys {?TokenKeys} + * @param performanceClient {?IPerformanceClient} + */ + getAccessToken(account, request, tokenKeys, targetRealm) { + const correlationId = request.correlationId; + this.commonLogger.trace("CacheManager - getAccessToken called", correlationId); + const scopes = ScopeSet.createSearchScopes(request.scopes); + const authScheme = request.authenticationScheme || AuthenticationScheme.BEARER; + /* + * Distinguish between Bearer and PoP/SSH token cache types + * Cast to lowercase to handle "bearer" from ADFS + */ + const credentialType = authScheme && + authScheme.toLowerCase() !== + AuthenticationScheme.BEARER.toLowerCase() + ? CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME + : CredentialType.ACCESS_TOKEN; + const accessTokenFilter = { + homeAccountId: account.homeAccountId, + environment: account.environment, + credentialType: credentialType, + clientId: this.clientId, + realm: targetRealm || account.tenantId, + target: scopes, + tokenType: authScheme, + keyId: request.sshKid, + requestedClaimsHash: request.requestedClaimsHash, + }; + const accessTokenKeys = (tokenKeys && tokenKeys.accessToken) || + this.getTokenKeys().accessToken; + const accessTokens = []; + accessTokenKeys.forEach((key) => { + // Validate key + if (this.accessTokenKeyMatchesFilter(key, accessTokenFilter, true)) { + const accessToken = this.getAccessTokenCredential(key, correlationId); + // Validate value + if (accessToken && + this.credentialMatchesFilter(accessToken, accessTokenFilter)) { + accessTokens.push(accessToken); + } + } + }); + const numAccessTokens = accessTokens.length; + if (numAccessTokens < 1) { + this.commonLogger.info("CacheManager:getAccessToken - No token found", correlationId); + return null; + } + else if (numAccessTokens > 1) { + this.commonLogger.info("CacheManager:getAccessToken - Multiple access tokens found, clearing them", correlationId); + accessTokens.forEach((accessToken) => { + this.removeAccessToken(this.generateCredentialKey(accessToken), correlationId); + }); + this.performanceClient.addFields({ multiMatchedAT: accessTokens.length }, correlationId); + return null; + } + this.commonLogger.info("CacheManager:getAccessToken - Returning access token", correlationId); + return accessTokens[0]; + } + /** + * Validate the cache key against filter before retrieving and parsing cache value + * @param key + * @param filter + * @param keyMustContainAllScopes + * @returns + */ + accessTokenKeyMatchesFilter(inputKey, filter, keyMustContainAllScopes) { + const key = inputKey.toLowerCase(); + if (filter.clientId && + key.indexOf(filter.clientId.toLowerCase()) === -1) { + return false; + } + if (filter.homeAccountId && + key.indexOf(filter.homeAccountId.toLowerCase()) === -1) { + return false; + } + if (filter.realm && key.indexOf(filter.realm.toLowerCase()) === -1) { + return false; + } + if (filter.requestedClaimsHash && + key.indexOf(filter.requestedClaimsHash.toLowerCase()) === -1) { + return false; + } + if (filter.target) { + const scopes = filter.target.asArray(); + for (let i = 0; i < scopes.length; i++) { + if (keyMustContainAllScopes && + !key.includes(scopes[i].toLowerCase())) { + // When performing a cache lookup a missing scope would be a cache miss + return false; + } + else if (!keyMustContainAllScopes && + key.includes(scopes[i].toLowerCase())) { + // When performing a cache write, any token with a subset of requested scopes should be replaced + return true; + } + } + } + return true; + } + /** + * Gets all access tokens matching the filter + * @param filter + * @returns + */ + getAccessTokensByFilter(filter, correlationId) { + const tokenKeys = this.getTokenKeys(); + const accessTokens = []; + tokenKeys.accessToken.forEach((key) => { + if (!this.accessTokenKeyMatchesFilter(key, filter, true)) { + return; + } + const accessToken = this.getAccessTokenCredential(key, correlationId); + if (accessToken && + this.credentialMatchesFilter(accessToken, filter)) { + accessTokens.push(accessToken); + } + }); + return accessTokens; + } + /** + * Helper to retrieve the appropriate refresh token from cache + * @param account {AccountInfo} + * @param familyRT {boolean} + * @param correlationId {?string} + * @param tokenKeys {?TokenKeys} + * @param performanceClient {?IPerformanceClient} + */ + getRefreshToken(account, familyRT, correlationId, tokenKeys, performanceClient) { + this.commonLogger.trace("CacheManager - getRefreshToken called"); + const id = familyRT ? THE_FAMILY_ID : undefined; + const refreshTokenFilter = { + homeAccountId: account.homeAccountId, + environment: account.environment, + credentialType: CredentialType.REFRESH_TOKEN, + clientId: this.clientId, + familyId: id, + }; + const refreshTokenKeys = (tokenKeys && tokenKeys.refreshToken) || + this.getTokenKeys().refreshToken; + const refreshTokens = []; + refreshTokenKeys.forEach((key) => { + // Validate key + if (this.refreshTokenKeyMatchesFilter(key, refreshTokenFilter)) { + const refreshToken = this.getRefreshTokenCredential(key, correlationId); + // Validate value + if (refreshToken && + this.credentialMatchesFilter(refreshToken, refreshTokenFilter)) { + refreshTokens.push(refreshToken); + } + } + }); + const numRefreshTokens = refreshTokens.length; + if (numRefreshTokens < 1) { + this.commonLogger.info("CacheManager:getRefreshToken - No refresh token found."); + return null; + } + // address the else case after remove functions address environment aliases + if (numRefreshTokens > 1 && performanceClient && correlationId) { + performanceClient.addFields({ multiMatchedRT: numRefreshTokens }, correlationId); + } + this.commonLogger.info("CacheManager:getRefreshToken - returning refresh token"); + return refreshTokens[0]; + } + /** + * Validate the cache key against filter before retrieving and parsing cache value + * @param key + * @param filter + */ + refreshTokenKeyMatchesFilter(inputKey, filter) { + const key = inputKey.toLowerCase(); + if (filter.familyId && + key.indexOf(filter.familyId.toLowerCase()) === -1) { + return false; + } + // If familyId is used, clientId is not in the key + if (!filter.familyId && + filter.clientId && + key.indexOf(filter.clientId.toLowerCase()) === -1) { + return false; + } + if (filter.homeAccountId && + key.indexOf(filter.homeAccountId.toLowerCase()) === -1) { + return false; + } + return true; + } + /** + * Retrieve AppMetadataEntity from cache + */ + readAppMetadataFromCache(environment) { + const appMetadataFilter = { + environment, + clientId: this.clientId, + }; + const appMetadata = this.getAppMetadataFilteredBy(appMetadataFilter); + const appMetadataEntries = Object.keys(appMetadata).map((key) => appMetadata[key]); + const numAppMetadata = appMetadataEntries.length; + if (numAppMetadata < 1) { + return null; + } + else if (numAppMetadata > 1) { + throw createClientAuthError(multipleMatchingAppMetadata); + } + return appMetadataEntries[0]; + } + /** + * Return the family_id value associated with FOCI + * @param environment + * @param clientId + */ + isAppMetadataFOCI(environment) { + const appMetadata = this.readAppMetadataFromCache(environment); + return !!(appMetadata && appMetadata.familyId === THE_FAMILY_ID); + } + /** + * helper to match account ids + * @param value + * @param homeAccountId + */ + matchHomeAccountId(entity, homeAccountId) { + return !!(typeof entity.homeAccountId === "string" && + homeAccountId === entity.homeAccountId); + } + /** + * helper to match account ids + * @param entity + * @param localAccountId + * @returns + */ + matchLocalAccountIdFromTokenClaims(tokenClaims, localAccountId) { + const idTokenLocalAccountId = tokenClaims.oid || tokenClaims.sub; + return localAccountId === idTokenLocalAccountId; + } + matchLocalAccountIdFromTenantProfile(tenantProfile, localAccountId) { + return tenantProfile.localAccountId === localAccountId; + } + /** + * helper to match names + * @param entity + * @param name + * @returns true if the downcased name properties are present and match in the filter and the entity + */ + matchName(claims, name) { + return !!(name.toLowerCase() === claims.name?.toLowerCase()); + } + /** + * helper to match usernames + * @param entity + * @param username + * @returns + */ + matchUsername(cachedUsername, filterUsername) { + return !!(cachedUsername && + typeof cachedUsername === "string" && + filterUsername?.toLowerCase() === cachedUsername.toLowerCase()); + } + /** + * helper to match assertion + * @param value + * @param oboAssertion + */ + matchUserAssertionHash(entity, userAssertionHash) { + return !!(entity.userAssertionHash && + userAssertionHash === entity.userAssertionHash); + } + /** + * helper to match environment + * @param value + * @param environment + */ + matchEnvironment(entity, environment) { + // Check static authority options first for cases where authority metadata has not been resolved and cached yet + if (this.staticAuthorityOptions) { + const staticAliases = getAliasesFromStaticSources(this.staticAuthorityOptions, this.commonLogger); + if (staticAliases.includes(environment) && + staticAliases.includes(entity.environment)) { + return true; + } + } + // Query metadata cache if no static authority configuration has aliases that match enviroment + const cloudMetadata = this.getAuthorityMetadataByAlias(environment); + if (cloudMetadata && + cloudMetadata.aliases.indexOf(entity.environment) > -1) { + return true; + } + return false; + } + /** + * helper to match credential type + * @param entity + * @param credentialType + */ + matchCredentialType(entity, credentialType) { + return (entity.credentialType && + credentialType.toLowerCase() === entity.credentialType.toLowerCase()); + } + /** + * helper to match client ids + * @param entity + * @param clientId + */ + matchClientId(entity, clientId) { + return !!(entity.clientId && clientId === entity.clientId); + } + /** + * helper to match family ids + * @param entity + * @param familyId + */ + matchFamilyId(entity, familyId) { + return !!(entity.familyId && familyId === entity.familyId); + } + /** + * helper to match realm + * @param entity + * @param realm + */ + matchRealm(entity, realm) { + return !!(entity.realm?.toLowerCase() === realm.toLowerCase()); + } + /** + * helper to match nativeAccountId + * @param entity + * @param nativeAccountId + * @returns boolean indicating the match result + */ + matchNativeAccountId(entity, nativeAccountId) { + return !!(entity.nativeAccountId && nativeAccountId === entity.nativeAccountId); + } + /** + * helper to match loginHint which can be either: + * 1. login_hint ID token claim + * 2. username in cached account object + * 3. upn in ID token claims + * @param entity + * @param loginHint + * @returns + */ + matchLoginHintFromTokenClaims(tokenClaims, loginHint) { + if (tokenClaims.login_hint === loginHint) { + return true; + } + if (tokenClaims.preferred_username === loginHint) { + return true; + } + if (tokenClaims.upn === loginHint) { + return true; + } + return false; + } + /** + * Helper to match sid + * @param entity + * @param sid + * @returns true if the sid claim is present and matches the filter + */ + matchSid(idTokenClaims, sid) { + return idTokenClaims.sid === sid; + } + matchAuthorityType(entity, authorityType) { + return !!(entity.authorityType && + authorityType.toLowerCase() === entity.authorityType.toLowerCase()); + } + /** + * Returns true if the target scopes are a subset of the current entity's scopes, false otherwise. + * @param entity + * @param target + */ + matchTarget(entity, target) { + const isNotAccessTokenCredential = entity.credentialType !== CredentialType.ACCESS_TOKEN && + entity.credentialType !== + CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME; + if (isNotAccessTokenCredential || !entity.target) { + return false; + } + const entityScopeSet = ScopeSet.fromString(entity.target); + return entityScopeSet.containsScopeSet(target); + } + /** + * Returns true if the credential's tokenType or Authentication Scheme matches the one in the request, false otherwise + * @param entity + * @param tokenType + */ + matchTokenType(entity, tokenType) { + return !!(entity.tokenType && entity.tokenType === tokenType); + } + /** + * Returns true if the credential's keyId matches the one in the request, false otherwise + * @param entity + * @param keyId + */ + matchKeyId(entity, keyId) { + return !!(entity.keyId && entity.keyId === keyId); + } + /** + * returns if a given cache entity is of the type appmetadata + * @param key + */ + isAppMetadata(key) { + return key.indexOf(APP_METADATA) !== -1; + } + /** + * returns if a given cache entity is of the type authoritymetadata + * @param key + */ + isAuthorityMetadata(key) { + return key.indexOf(AUTHORITY_METADATA_CONSTANTS.CACHE_KEY) !== -1; + } + /** + * returns cache key used for cloud instance metadata + */ + generateAuthorityMetadataCacheKey(authority) { + return `${AUTHORITY_METADATA_CONSTANTS.CACHE_KEY}-${this.clientId}-${authority}`; + } + /** + * Helper to convert serialized data to object + * @param obj + * @param json + */ + static toObject(obj, json) { + for (const propertyName in json) { + obj[propertyName] = json[propertyName]; + } + return obj; + } +} +/** @internal */ +class DefaultStorageClass extends CacheManager { + async setAccount() { + throw createClientAuthError(methodNotImplemented); + } + getAccount() { + throw createClientAuthError(methodNotImplemented); + } + async setIdTokenCredential() { + throw createClientAuthError(methodNotImplemented); + } + getIdTokenCredential() { + throw createClientAuthError(methodNotImplemented); + } + async setAccessTokenCredential() { + throw createClientAuthError(methodNotImplemented); + } + getAccessTokenCredential() { + throw createClientAuthError(methodNotImplemented); + } + async setRefreshTokenCredential() { + throw createClientAuthError(methodNotImplemented); + } + getRefreshTokenCredential() { + throw createClientAuthError(methodNotImplemented); + } + setAppMetadata() { + throw createClientAuthError(methodNotImplemented); + } + getAppMetadata() { + throw createClientAuthError(methodNotImplemented); + } + setServerTelemetry() { + throw createClientAuthError(methodNotImplemented); + } + getServerTelemetry() { + throw createClientAuthError(methodNotImplemented); + } + setAuthorityMetadata() { + throw createClientAuthError(methodNotImplemented); + } + getAuthorityMetadata() { + throw createClientAuthError(methodNotImplemented); + } + getAuthorityMetadataKeys() { + throw createClientAuthError(methodNotImplemented); + } + setThrottlingCache() { + throw createClientAuthError(methodNotImplemented); + } + getThrottlingCache() { + throw createClientAuthError(methodNotImplemented); + } + removeItem() { + throw createClientAuthError(methodNotImplemented); + } + getKeys() { + throw createClientAuthError(methodNotImplemented); + } + getAccountKeys() { + throw createClientAuthError(methodNotImplemented); + } + getTokenKeys() { + throw createClientAuthError(methodNotImplemented); + } + generateCredentialKey() { + throw createClientAuthError(methodNotImplemented); + } + generateAccountKey() { + throw createClientAuthError(methodNotImplemented); + } +} + +export { CacheManager, DefaultStorageClass }; +//# sourceMappingURL=CacheManager.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/cache/entities/AccountEntity.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/cache/entities/AccountEntity.mjs new file mode 100644 index 00000000..eb0ea4f6 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/cache/entities/AccountEntity.mjs @@ -0,0 +1,232 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +import { CacheAccountType } from '../../utils/Constants.mjs'; +import { buildClientInfo } from '../../account/ClientInfo.mjs'; +import { buildTenantProfile } from '../../account/AccountInfo.mjs'; +import { createClientAuthError } from '../../error/ClientAuthError.mjs'; +import { AuthorityType } from '../../authority/AuthorityType.mjs'; +import { getTenantIdFromIdTokenClaims } from '../../account/TokenClaims.mjs'; +import { ProtocolMode } from '../../authority/ProtocolMode.mjs'; +import { invalidCacheEnvironment } from '../../error/ClientAuthErrorCodes.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * Type that defines required and optional parameters for an Account field (based on universal cache schema implemented by all MSALs). + * + * Key : Value Schema + * + * Key: -- + * + * Value Schema: + * { + * homeAccountId: home account identifier for the auth scheme, + * environment: entity that issued the token, represented as a full host + * realm: Full tenant or organizational identifier that the account belongs to + * localAccountId: Original tenant-specific accountID, usually used for legacy cases + * username: primary username that represents the user, usually corresponds to preferred_username in the v2 endpt + * authorityType: Accounts authority type as a string + * name: Full name for the account, including given name and family name, + * lastModificationTime: last time this entity was modified in the cache + * lastModificationApp: + * nativeAccountId: Account identifier on the native device + * tenantProfiles: Array of tenant profile objects for each tenant that the account has authenticated with in the browser + * } + * @internal + */ +class AccountEntity { + /** + * Returns the AccountInfo interface for this account. + */ + static getAccountInfo(accountEntity) { + return { + homeAccountId: accountEntity.homeAccountId, + environment: accountEntity.environment, + tenantId: accountEntity.realm, + username: accountEntity.username, + localAccountId: accountEntity.localAccountId, + loginHint: accountEntity.loginHint, + name: accountEntity.name, + nativeAccountId: accountEntity.nativeAccountId, + authorityType: accountEntity.authorityType, + // Deserialize tenant profiles array into a Map + tenantProfiles: new Map((accountEntity.tenantProfiles || []).map((tenantProfile) => { + return [tenantProfile.tenantId, tenantProfile]; + })), + dataBoundary: accountEntity.dataBoundary, + }; + } + /** + * Returns true if the account entity is in single tenant format (outdated), false otherwise + */ + isSingleTenant() { + return !this.tenantProfiles; + } + /** + * Build Account cache from IdToken, clientInfo and authority/policy. Associated with AAD. + * @param accountDetails + */ + static createAccount(accountDetails, authority, base64Decode) { + const account = new AccountEntity(); + if (authority.authorityType === AuthorityType.Adfs) { + account.authorityType = CacheAccountType.ADFS_ACCOUNT_TYPE; + } + else if (authority.protocolMode === ProtocolMode.OIDC) { + account.authorityType = CacheAccountType.GENERIC_ACCOUNT_TYPE; + } + else { + account.authorityType = CacheAccountType.MSSTS_ACCOUNT_TYPE; + } + let clientInfo; + if (accountDetails.clientInfo && base64Decode) { + clientInfo = buildClientInfo(accountDetails.clientInfo, base64Decode); + if (clientInfo.xms_tdbr) { + account.dataBoundary = + clientInfo.xms_tdbr === "EU" ? "EU" : "None"; + } + } + account.clientInfo = accountDetails.clientInfo; + account.homeAccountId = accountDetails.homeAccountId; + account.nativeAccountId = accountDetails.nativeAccountId; + const env = accountDetails.environment || + (authority && authority.getPreferredCache()); + if (!env) { + throw createClientAuthError(invalidCacheEnvironment); + } + account.environment = env; + // non AAD scenarios can have empty realm + account.realm = + clientInfo?.utid || + getTenantIdFromIdTokenClaims(accountDetails.idTokenClaims) || + ""; + // How do you account for MSA CID here? + account.localAccountId = + clientInfo?.uid || + accountDetails.idTokenClaims?.oid || + accountDetails.idTokenClaims?.sub || + ""; + /* + * In B2C scenarios the emails claim is used instead of preferred_username and it is an array. + * In most cases it will contain a single email. This field should not be relied upon if a custom + * policy is configured to return more than 1 email. + */ + const preferredUsername = accountDetails.idTokenClaims?.preferred_username || + accountDetails.idTokenClaims?.upn; + const email = accountDetails.idTokenClaims?.emails + ? accountDetails.idTokenClaims.emails[0] + : null; + account.username = preferredUsername || email || ""; + account.loginHint = accountDetails.idTokenClaims?.login_hint; + account.name = accountDetails.idTokenClaims?.name || ""; + account.cloudGraphHostName = accountDetails.cloudGraphHostName; + account.msGraphHost = accountDetails.msGraphHost; + if (accountDetails.tenantProfiles) { + account.tenantProfiles = accountDetails.tenantProfiles; + } + else { + const tenantProfile = buildTenantProfile(accountDetails.homeAccountId, account.localAccountId, account.realm, accountDetails.idTokenClaims); + account.tenantProfiles = [tenantProfile]; + } + return account; + } + /** + * Creates an AccountEntity object from AccountInfo + * @param accountInfo + * @param cloudGraphHostName + * @param msGraphHost + * @returns + */ + static createFromAccountInfo(accountInfo, cloudGraphHostName, msGraphHost) { + const account = new AccountEntity(); + account.authorityType = + accountInfo.authorityType || CacheAccountType.GENERIC_ACCOUNT_TYPE; + account.homeAccountId = accountInfo.homeAccountId; + account.localAccountId = accountInfo.localAccountId; + account.nativeAccountId = accountInfo.nativeAccountId; + account.realm = accountInfo.tenantId; + account.environment = accountInfo.environment; + account.username = accountInfo.username; + account.name = accountInfo.name; + account.loginHint = accountInfo.loginHint; + account.cloudGraphHostName = cloudGraphHostName; + account.msGraphHost = msGraphHost; + // Serialize tenant profiles map into an array + account.tenantProfiles = Array.from(accountInfo.tenantProfiles?.values() || []); + account.dataBoundary = accountInfo.dataBoundary; + return account; + } + /** + * Generate HomeAccountId from server response + * @param serverClientInfo + * @param authType + */ + static generateHomeAccountId(serverClientInfo, authType, logger, cryptoObj, idTokenClaims) { + // since ADFS/DSTS do not have tid and does not set client_info + if (!(authType === AuthorityType.Adfs || + authType === AuthorityType.Dsts)) { + // for cases where there is clientInfo + if (serverClientInfo) { + try { + const clientInfo = buildClientInfo(serverClientInfo, cryptoObj.base64Decode); + if (clientInfo.uid && clientInfo.utid) { + return `${clientInfo.uid}.${clientInfo.utid}`; + } + } + catch (e) { } + } + logger.warning("No client info in response"); + } + // default to "sub" claim + return idTokenClaims?.sub || ""; + } + /** + * Validates an entity: checks for all expected params + * @param entity + */ + static isAccountEntity(entity) { + if (!entity) { + return false; + } + return (entity.hasOwnProperty("homeAccountId") && + entity.hasOwnProperty("environment") && + entity.hasOwnProperty("realm") && + entity.hasOwnProperty("localAccountId") && + entity.hasOwnProperty("username") && + entity.hasOwnProperty("authorityType")); + } + /** + * Helper function to determine whether 2 accountInfo objects represent the same account + * @param accountA + * @param accountB + * @param compareClaims - If set to true idTokenClaims will also be compared to determine account equality + */ + static accountInfoIsEqual(accountA, accountB, compareClaims) { + if (!accountA || !accountB) { + return false; + } + let claimsMatch = true; // default to true so as to not fail comparison below if compareClaims: false + if (compareClaims) { + const accountAClaims = (accountA.idTokenClaims || + {}); + const accountBClaims = (accountB.idTokenClaims || + {}); + // issued at timestamp and nonce are expected to change each time a new id token is acquired + claimsMatch = + accountAClaims.iat === accountBClaims.iat && + accountAClaims.nonce === accountBClaims.nonce; + } + return (accountA.homeAccountId === accountB.homeAccountId && + accountA.localAccountId === accountB.localAccountId && + accountA.username === accountB.username && + accountA.tenantId === accountB.tenantId && + accountA.loginHint === accountB.loginHint && + accountA.environment === accountB.environment && + accountA.nativeAccountId === accountB.nativeAccountId && + claimsMatch); + } +} + +export { AccountEntity }; +//# sourceMappingURL=AccountEntity.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/cache/persistence/TokenCacheContext.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/cache/persistence/TokenCacheContext.mjs new file mode 100644 index 00000000..688d8ea1 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/cache/persistence/TokenCacheContext.mjs @@ -0,0 +1,30 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * This class instance helps track the memory changes facilitating + * decisions to read from and write to the persistent cache + */ class TokenCacheContext { + constructor(tokenCache, hasChanged) { + this.cache = tokenCache; + this.hasChanged = hasChanged; + } + /** + * boolean which indicates the changes in cache + */ + get cacheHasChanged() { + return this.hasChanged; + } + /** + * function to retrieve the token cache + */ + get tokenCache() { + return this.cache; + } +} + +export { TokenCacheContext }; +//# sourceMappingURL=TokenCacheContext.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/cache/utils/CacheHelpers.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/cache/utils/CacheHelpers.mjs new file mode 100644 index 00000000..77996654 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/cache/utils/CacheHelpers.mjs @@ -0,0 +1,270 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +import { extractTokenClaims } from '../../account/AuthToken.mjs'; +import { createClientAuthError } from '../../error/ClientAuthError.mjs'; +import { CredentialType, AuthenticationScheme, SERVER_TELEM_CONSTANTS, ThrottlingConstants, APP_METADATA, Separators, AUTHORITY_METADATA_CONSTANTS } from '../../utils/Constants.mjs'; +import { nowSeconds } from '../../utils/TimeUtils.mjs'; +import { tokenClaimsCnfRequiredForSignedJwt } from '../../error/ClientAuthErrorCodes.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * Create IdTokenEntity + * @param homeAccountId + * @param authenticationResult + * @param clientId + * @param authority + */ +function createIdTokenEntity(homeAccountId, environment, idToken, clientId, tenantId) { + const idTokenEntity = { + credentialType: CredentialType.ID_TOKEN, + homeAccountId: homeAccountId, + environment: environment, + clientId: clientId, + secret: idToken, + realm: tenantId, + lastUpdatedAt: Date.now().toString(), // Set the last updated time to now + }; + return idTokenEntity; +} +/** + * Create AccessTokenEntity + * @param homeAccountId + * @param environment + * @param accessToken + * @param clientId + * @param tenantId + * @param scopes + * @param expiresOn + * @param extExpiresOn + */ +function createAccessTokenEntity(homeAccountId, environment, accessToken, clientId, tenantId, scopes, expiresOn, extExpiresOn, base64Decode, refreshOn, tokenType, userAssertionHash, keyId, requestedClaims, requestedClaimsHash) { + const atEntity = { + homeAccountId: homeAccountId, + credentialType: CredentialType.ACCESS_TOKEN, + secret: accessToken, + cachedAt: nowSeconds().toString(), + expiresOn: expiresOn.toString(), + extendedExpiresOn: extExpiresOn.toString(), + environment: environment, + clientId: clientId, + realm: tenantId, + target: scopes, + tokenType: tokenType || AuthenticationScheme.BEARER, + lastUpdatedAt: Date.now().toString(), // Set the last updated time to now + }; + if (userAssertionHash) { + atEntity.userAssertionHash = userAssertionHash; + } + if (refreshOn) { + atEntity.refreshOn = refreshOn.toString(); + } + if (requestedClaims) { + atEntity.requestedClaims = requestedClaims; + atEntity.requestedClaimsHash = requestedClaimsHash; + } + /* + * Create Access Token With Auth Scheme instead of regular access token + * Cast to lower to handle "bearer" from ADFS + */ + if (atEntity.tokenType?.toLowerCase() !== + AuthenticationScheme.BEARER.toLowerCase()) { + atEntity.credentialType = CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME; + switch (atEntity.tokenType) { + case AuthenticationScheme.POP: + // Make sure keyId is present and add it to credential + const tokenClaims = extractTokenClaims(accessToken, base64Decode); + if (!tokenClaims?.cnf?.kid) { + throw createClientAuthError(tokenClaimsCnfRequiredForSignedJwt); + } + atEntity.keyId = tokenClaims.cnf.kid; + break; + case AuthenticationScheme.SSH: + atEntity.keyId = keyId; + } + } + return atEntity; +} +/** + * Create RefreshTokenEntity + * @param homeAccountId + * @param authenticationResult + * @param clientId + * @param authority + */ +function createRefreshTokenEntity(homeAccountId, environment, refreshToken, clientId, familyId, userAssertionHash, expiresOn) { + const rtEntity = { + credentialType: CredentialType.REFRESH_TOKEN, + homeAccountId: homeAccountId, + environment: environment, + clientId: clientId, + secret: refreshToken, + lastUpdatedAt: Date.now().toString(), + }; + if (userAssertionHash) { + rtEntity.userAssertionHash = userAssertionHash; + } + if (familyId) { + rtEntity.familyId = familyId; + } + if (expiresOn) { + rtEntity.expiresOn = expiresOn.toString(); + } + return rtEntity; +} +function isCredentialEntity(entity) { + return (entity.hasOwnProperty("homeAccountId") && + entity.hasOwnProperty("environment") && + entity.hasOwnProperty("credentialType") && + entity.hasOwnProperty("clientId") && + entity.hasOwnProperty("secret")); +} +/** + * Validates an entity: checks for all expected params + * @param entity + */ +function isAccessTokenEntity(entity) { + if (!entity) { + return false; + } + return (isCredentialEntity(entity) && + entity.hasOwnProperty("realm") && + entity.hasOwnProperty("target") && + (entity["credentialType"] === CredentialType.ACCESS_TOKEN || + entity["credentialType"] === + CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME)); +} +/** + * Validates an entity: checks for all expected params + * @param entity + */ +function isIdTokenEntity(entity) { + if (!entity) { + return false; + } + return (isCredentialEntity(entity) && + entity.hasOwnProperty("realm") && + entity["credentialType"] === CredentialType.ID_TOKEN); +} +/** + * Validates an entity: checks for all expected params + * @param entity + */ +function isRefreshTokenEntity(entity) { + if (!entity) { + return false; + } + return (isCredentialEntity(entity) && + entity["credentialType"] === CredentialType.REFRESH_TOKEN); +} +/** + * validates if a given cache entry is "Telemetry", parses + * @param key + * @param entity + */ +function isServerTelemetryEntity(key, entity) { + const validateKey = key.indexOf(SERVER_TELEM_CONSTANTS.CACHE_KEY) === 0; + let validateEntity = true; + if (entity) { + validateEntity = + entity.hasOwnProperty("failedRequests") && + entity.hasOwnProperty("errors") && + entity.hasOwnProperty("cacheHits"); + } + return validateKey && validateEntity; +} +/** + * validates if a given cache entry is "Throttling", parses + * @param key + * @param entity + */ +function isThrottlingEntity(key, entity) { + let validateKey = false; + if (key) { + validateKey = key.indexOf(ThrottlingConstants.THROTTLING_PREFIX) === 0; + } + let validateEntity = true; + if (entity) { + validateEntity = entity.hasOwnProperty("throttleTime"); + } + return validateKey && validateEntity; +} +/** + * Generate AppMetadata Cache Key as per the schema: appmetadata-- + */ +function generateAppMetadataKey({ environment, clientId, }) { + const appMetaDataKeyArray = [ + APP_METADATA, + environment, + clientId, + ]; + return appMetaDataKeyArray + .join(Separators.CACHE_KEY_SEPARATOR) + .toLowerCase(); +} +/* + * Validates an entity: checks for all expected params + * @param entity + */ +function isAppMetadataEntity(key, entity) { + if (!entity) { + return false; + } + return (key.indexOf(APP_METADATA) === 0 && + entity.hasOwnProperty("clientId") && + entity.hasOwnProperty("environment")); +} +/** + * Validates an entity: checks for all expected params + * @param entity + */ +function isAuthorityMetadataEntity(key, entity) { + if (!entity) { + return false; + } + return (key.indexOf(AUTHORITY_METADATA_CONSTANTS.CACHE_KEY) === 0 && + entity.hasOwnProperty("aliases") && + entity.hasOwnProperty("preferred_cache") && + entity.hasOwnProperty("preferred_network") && + entity.hasOwnProperty("canonical_authority") && + entity.hasOwnProperty("authorization_endpoint") && + entity.hasOwnProperty("token_endpoint") && + entity.hasOwnProperty("issuer") && + entity.hasOwnProperty("aliasesFromNetwork") && + entity.hasOwnProperty("endpointsFromNetwork") && + entity.hasOwnProperty("expiresAt") && + entity.hasOwnProperty("jwks_uri")); +} +/** + * Reset the exiresAt value + */ +function generateAuthorityMetadataExpiresAt() { + return (nowSeconds() + + AUTHORITY_METADATA_CONSTANTS.REFRESH_TIME_SECONDS); +} +function updateAuthorityEndpointMetadata(authorityMetadata, updatedValues, fromNetwork) { + authorityMetadata.authorization_endpoint = + updatedValues.authorization_endpoint; + authorityMetadata.token_endpoint = updatedValues.token_endpoint; + authorityMetadata.end_session_endpoint = updatedValues.end_session_endpoint; + authorityMetadata.issuer = updatedValues.issuer; + authorityMetadata.endpointsFromNetwork = fromNetwork; + authorityMetadata.jwks_uri = updatedValues.jwks_uri; +} +function updateCloudDiscoveryMetadata(authorityMetadata, updatedValues, fromNetwork) { + authorityMetadata.aliases = updatedValues.aliases; + authorityMetadata.preferred_cache = updatedValues.preferred_cache; + authorityMetadata.preferred_network = updatedValues.preferred_network; + authorityMetadata.aliasesFromNetwork = fromNetwork; +} +/** + * Returns whether or not the data needs to be refreshed + */ +function isAuthorityMetadataExpired(metadata) { + return metadata.expiresAt <= nowSeconds(); +} + +export { createAccessTokenEntity, createIdTokenEntity, createRefreshTokenEntity, generateAppMetadataKey, generateAuthorityMetadataExpiresAt, isAccessTokenEntity, isAppMetadataEntity, isAuthorityMetadataEntity, isAuthorityMetadataExpired, isCredentialEntity, isIdTokenEntity, isRefreshTokenEntity, isServerTelemetryEntity, isThrottlingEntity, updateAuthorityEndpointMetadata, updateCloudDiscoveryMetadata }; +//# sourceMappingURL=CacheHelpers.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/client/AuthorizationCodeClient.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/client/AuthorizationCodeClient.mjs new file mode 100644 index 00000000..d41eadc8 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/client/AuthorizationCodeClient.mjs @@ -0,0 +1,259 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +import { BaseClient } from './BaseClient.mjs'; +import { addClientId, addRedirectUri, addScopes, addAuthorizationCode, addLibraryInfo, addApplicationTelemetry, addThrottling, addServerTelemetry, addCodeVerifier, addClientSecret, addClientAssertion, addClientAssertionType, addGrantType, addClientInfo, addPopToken, addSshJwk, addClaims, addCcsUpn, addCcsOid, addBrokerParameters, addExtraQueryParameters, instrumentBrokerParams, addPostLogoutRedirectUri, addCorrelationId, addIdTokenHint, addState, addLogoutHint, addInstanceAware } from '../request/RequestParameterBuilder.mjs'; +import { mapToQueryString } from '../utils/UrlUtils.mjs'; +import { Separators, AuthenticationScheme, HeaderNames, GrantType } from '../utils/Constants.mjs'; +import { RETURN_SPA_CODE, CLIENT_ID } from '../constants/AADServerParamKeys.mjs'; +import { isOidcProtocolMode } from '../config/ClientConfiguration.mjs'; +import { ResponseHandler } from '../response/ResponseHandler.mjs'; +import { StringUtils } from '../utils/StringUtils.mjs'; +import { createClientAuthError } from '../error/ClientAuthError.mjs'; +import { UrlString } from '../url/UrlString.mjs'; +import { PopTokenGenerator } from '../crypto/PopTokenGenerator.mjs'; +import { nowSeconds } from '../utils/TimeUtils.mjs'; +import { buildClientInfo, buildClientInfoFromHomeAccountId } from '../account/ClientInfo.mjs'; +import { CcsCredentialType } from '../account/CcsCredential.mjs'; +import { createClientConfigurationError } from '../error/ClientConfigurationError.mjs'; +import { PerformanceEvents } from '../telemetry/performance/PerformanceEvent.mjs'; +import { invokeAsync } from '../utils/FunctionWrappers.mjs'; +import { getClientAssertion } from '../utils/ClientAssertionUtils.mjs'; +import { getRequestThumbprint } from '../network/RequestThumbprint.mjs'; +import { requestCannotBeMade } from '../error/ClientAuthErrorCodes.mjs'; +import { logoutRequestEmpty, redirectUriEmpty, missingSshJwk } from '../error/ClientConfigurationErrorCodes.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * Oauth2.0 Authorization Code client + * @internal + */ +class AuthorizationCodeClient extends BaseClient { + constructor(configuration, performanceClient) { + super(configuration, performanceClient); + // Flag to indicate if client is for hybrid spa auth code redemption + this.includeRedirectUri = true; + this.oidcDefaultScopes = + this.config.authOptions.authority.options.OIDCOptions?.defaultScopes; + } + /** + * API to acquire a token in exchange of 'authorization_code` acquired by the user in the first leg of the + * authorization_code_grant + * @param request + */ + async acquireToken(request, authCodePayload) { + this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthClientAcquireToken, request.correlationId); + if (!request.code) { + throw createClientAuthError(requestCannotBeMade); + } + const reqTimestamp = nowSeconds(); + const response = await invokeAsync(this.executeTokenRequest.bind(this), PerformanceEvents.AuthClientExecuteTokenRequest, this.logger, this.performanceClient, request.correlationId)(this.authority, request); + // Retrieve requestId from response headers + const requestId = response.headers?.[HeaderNames.X_MS_REQUEST_ID]; + const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.config.serializableCache, this.config.persistencePlugin, this.performanceClient); + // Validate response. This function throws a server error if an error is returned by the server. + responseHandler.validateTokenResponse(response.body); + return invokeAsync(responseHandler.handleServerTokenResponse.bind(responseHandler), PerformanceEvents.HandleServerTokenResponse, this.logger, this.performanceClient, request.correlationId)(response.body, this.authority, reqTimestamp, request, authCodePayload, undefined, undefined, undefined, requestId); + } + /** + * Used to log out the current user, and redirect the user to the postLogoutRedirectUri. + * Default behaviour is to redirect the user to `window.location.href`. + * @param authorityUri + */ + getLogoutUri(logoutRequest) { + // Throw error if logoutRequest is null/undefined + if (!logoutRequest) { + throw createClientConfigurationError(logoutRequestEmpty); + } + const queryString = this.createLogoutUrlQueryString(logoutRequest); + // Construct logout URI + return UrlString.appendQueryString(this.authority.endSessionEndpoint, queryString); + } + /** + * Executes POST request to token endpoint + * @param authority + * @param request + */ + async executeTokenRequest(authority, request) { + this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthClientExecuteTokenRequest, request.correlationId); + const queryParametersString = this.createTokenQueryParameters(request); + const endpoint = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString); + const requestBody = await invokeAsync(this.createTokenRequestBody.bind(this), PerformanceEvents.AuthClientCreateTokenRequestBody, this.logger, this.performanceClient, request.correlationId)(request); + let ccsCredential = undefined; + if (request.clientInfo) { + try { + const clientInfo = buildClientInfo(request.clientInfo, this.cryptoUtils.base64Decode); + ccsCredential = { + credential: `${clientInfo.uid}${Separators.CLIENT_INFO_SEPARATOR}${clientInfo.utid}`, + type: CcsCredentialType.HOME_ACCOUNT_ID, + }; + } + catch (e) { + this.logger.verbose("Could not parse client info for CCS Header: " + e); + } + } + const headers = this.createTokenRequestHeaders(ccsCredential || request.ccsCredential); + const thumbprint = getRequestThumbprint(this.config.authOptions.clientId, request); + return invokeAsync(this.executePostToTokenEndpoint.bind(this), PerformanceEvents.AuthorizationCodeClientExecutePostToTokenEndpoint, this.logger, this.performanceClient, request.correlationId)(endpoint, requestBody, headers, thumbprint, request.correlationId, PerformanceEvents.AuthorizationCodeClientExecutePostToTokenEndpoint); + } + /** + * Generates a map for all the params to be sent to the service + * @param request + */ + async createTokenRequestBody(request) { + this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthClientCreateTokenRequestBody, request.correlationId); + const parameters = new Map(); + addClientId(parameters, request.embeddedClientId || + request.tokenBodyParameters?.[CLIENT_ID] || + this.config.authOptions.clientId); + /* + * For hybrid spa flow, there will be a code but no verifier + * In this scenario, don't include redirect uri as auth code will not be bound to redirect URI + */ + if (!this.includeRedirectUri) { + // Just validate + if (!request.redirectUri) { + throw createClientConfigurationError(redirectUriEmpty); + } + } + else { + // Validate and include redirect uri + addRedirectUri(parameters, request.redirectUri); + } + // Add scope array, parameter builder will add default scopes and dedupe + addScopes(parameters, request.scopes, true, this.oidcDefaultScopes); + // add code: user set, not validated + addAuthorizationCode(parameters, request.code); + // Add library metadata + addLibraryInfo(parameters, this.config.libraryInfo); + addApplicationTelemetry(parameters, this.config.telemetry.application); + addThrottling(parameters); + if (this.serverTelemetryManager && !isOidcProtocolMode(this.config)) { + addServerTelemetry(parameters, this.serverTelemetryManager); + } + // add code_verifier if passed + if (request.codeVerifier) { + addCodeVerifier(parameters, request.codeVerifier); + } + if (this.config.clientCredentials.clientSecret) { + addClientSecret(parameters, this.config.clientCredentials.clientSecret); + } + if (this.config.clientCredentials.clientAssertion) { + const clientAssertion = this.config.clientCredentials.clientAssertion; + addClientAssertion(parameters, await getClientAssertion(clientAssertion.assertion, this.config.authOptions.clientId, request.resourceRequestUri)); + addClientAssertionType(parameters, clientAssertion.assertionType); + } + addGrantType(parameters, GrantType.AUTHORIZATION_CODE_GRANT); + addClientInfo(parameters); + if (request.authenticationScheme === AuthenticationScheme.POP) { + const popTokenGenerator = new PopTokenGenerator(this.cryptoUtils, this.performanceClient); + let reqCnfData; + if (!request.popKid) { + const generatedReqCnfData = await invokeAsync(popTokenGenerator.generateCnf.bind(popTokenGenerator), PerformanceEvents.PopTokenGenerateCnf, this.logger, this.performanceClient, request.correlationId)(request, this.logger); + reqCnfData = generatedReqCnfData.reqCnfString; + } + else { + reqCnfData = this.cryptoUtils.encodeKid(request.popKid); + } + // SPA PoP requires full Base64Url encoded req_cnf string (unhashed) + addPopToken(parameters, reqCnfData); + } + else if (request.authenticationScheme === AuthenticationScheme.SSH) { + if (request.sshJwk) { + addSshJwk(parameters, request.sshJwk); + } + else { + throw createClientConfigurationError(missingSshJwk); + } + } + if (!StringUtils.isEmptyObj(request.claims) || + (this.config.authOptions.clientCapabilities && + this.config.authOptions.clientCapabilities.length > 0)) { + addClaims(parameters, request.claims, this.config.authOptions.clientCapabilities); + } + let ccsCred = undefined; + if (request.clientInfo) { + try { + const clientInfo = buildClientInfo(request.clientInfo, this.cryptoUtils.base64Decode); + ccsCred = { + credential: `${clientInfo.uid}${Separators.CLIENT_INFO_SEPARATOR}${clientInfo.utid}`, + type: CcsCredentialType.HOME_ACCOUNT_ID, + }; + } + catch (e) { + this.logger.verbose("Could not parse client info for CCS Header: " + e); + } + } + else { + ccsCred = request.ccsCredential; + } + // Adds these as parameters in the request instead of headers to prevent CORS preflight request + if (this.config.systemOptions.preventCorsPreflight && ccsCred) { + switch (ccsCred.type) { + case CcsCredentialType.HOME_ACCOUNT_ID: + try { + const clientInfo = buildClientInfoFromHomeAccountId(ccsCred.credential); + addCcsOid(parameters, clientInfo); + } + catch (e) { + this.logger.verbose("Could not parse home account ID for CCS Header: " + + e); + } + break; + case CcsCredentialType.UPN: + addCcsUpn(parameters, ccsCred.credential); + break; + } + } + if (request.embeddedClientId) { + addBrokerParameters(parameters, this.config.authOptions.clientId, this.config.authOptions.redirectUri); + } + if (request.tokenBodyParameters) { + addExtraQueryParameters(parameters, request.tokenBodyParameters); + } + // Add hybrid spa parameters if not already provided + if (request.enableSpaAuthorizationCode && + (!request.tokenBodyParameters || + !request.tokenBodyParameters[RETURN_SPA_CODE])) { + addExtraQueryParameters(parameters, { + [RETURN_SPA_CODE]: "1", + }); + } + instrumentBrokerParams(parameters, request.correlationId, this.performanceClient); + return mapToQueryString(parameters); + } + /** + * This API validates the `EndSessionRequest` and creates a URL + * @param request + */ + createLogoutUrlQueryString(request) { + const parameters = new Map(); + if (request.postLogoutRedirectUri) { + addPostLogoutRedirectUri(parameters, request.postLogoutRedirectUri); + } + if (request.correlationId) { + addCorrelationId(parameters, request.correlationId); + } + if (request.idTokenHint) { + addIdTokenHint(parameters, request.idTokenHint); + } + if (request.state) { + addState(parameters, request.state); + } + if (request.logoutHint) { + addLogoutHint(parameters, request.logoutHint); + } + if (request.extraQueryParameters) { + addExtraQueryParameters(parameters, request.extraQueryParameters); + } + if (this.config.authOptions.instanceAware) { + addInstanceAware(parameters); + } + return mapToQueryString(parameters, this.config.authOptions.encodeExtraQueryParams, request.extraQueryParameters); + } +} + +export { AuthorizationCodeClient }; +//# sourceMappingURL=AuthorizationCodeClient.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/client/BaseClient.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/client/BaseClient.mjs new file mode 100644 index 00000000..21e5535a --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/client/BaseClient.mjs @@ -0,0 +1,167 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +import { buildClientConfiguration } from '../config/ClientConfiguration.mjs'; +import { Logger } from '../logger/Logger.mjs'; +import { Constants, HeaderNames } from '../utils/Constants.mjs'; +import { name, version } from '../packageMetadata.mjs'; +import { CcsCredentialType } from '../account/CcsCredential.mjs'; +import { buildClientInfoFromHomeAccountId } from '../account/ClientInfo.mjs'; +import { addBrokerParameters, addExtraQueryParameters, addCorrelationId, instrumentBrokerParams } from '../request/RequestParameterBuilder.mjs'; +import { mapToQueryString } from '../utils/UrlUtils.mjs'; +import { createDiscoveredInstance } from '../authority/AuthorityFactory.mjs'; +import { PerformanceEvents } from '../telemetry/performance/PerformanceEvent.mjs'; +import { ThrottlingUtils } from '../network/ThrottlingUtils.mjs'; +import { AuthError } from '../error/AuthError.mjs'; +import { createClientAuthError } from '../error/ClientAuthError.mjs'; +import { NetworkError } from '../error/NetworkError.mjs'; +import { invokeAsync } from '../utils/FunctionWrappers.mjs'; +import { networkError } from '../error/ClientAuthErrorCodes.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * Base application class which will construct requests to send to and handle responses from the Microsoft STS using the authorization code flow. + * @internal + */ +class BaseClient { + constructor(configuration, performanceClient) { + // Set the configuration + this.config = buildClientConfiguration(configuration); + // Initialize the logger + this.logger = new Logger(this.config.loggerOptions, name, version); + // Initialize crypto + this.cryptoUtils = this.config.cryptoInterface; + // Initialize storage interface + this.cacheManager = this.config.storageInterface; + // Set the network interface + this.networkClient = this.config.networkInterface; + // Set TelemetryManager + this.serverTelemetryManager = this.config.serverTelemetryManager; + // set Authority + this.authority = this.config.authOptions.authority; + // set performance telemetry client + this.performanceClient = performanceClient; + } + /** + * Creates default headers for requests to token endpoint + */ + createTokenRequestHeaders(ccsCred) { + const headers = {}; + headers[HeaderNames.CONTENT_TYPE] = Constants.URL_FORM_CONTENT_TYPE; + if (!this.config.systemOptions.preventCorsPreflight && ccsCred) { + switch (ccsCred.type) { + case CcsCredentialType.HOME_ACCOUNT_ID: + try { + const clientInfo = buildClientInfoFromHomeAccountId(ccsCred.credential); + headers[HeaderNames.CCS_HEADER] = `Oid:${clientInfo.uid}@${clientInfo.utid}`; + } + catch (e) { + this.logger.verbose("Could not parse home account ID for CCS Header: " + + e); + } + break; + case CcsCredentialType.UPN: + headers[HeaderNames.CCS_HEADER] = `UPN: ${ccsCred.credential}`; + break; + } + } + return headers; + } + /** + * Http post to token endpoint + * @param tokenEndpoint + * @param queryString + * @param headers + * @param thumbprint + */ + async executePostToTokenEndpoint(tokenEndpoint, queryString, headers, thumbprint, correlationId, queuedEvent) { + if (queuedEvent) { + this.performanceClient?.addQueueMeasurement(queuedEvent, correlationId); + } + const response = await this.sendPostRequest(thumbprint, tokenEndpoint, { body: queryString, headers: headers }, correlationId); + if (this.config.serverTelemetryManager && + response.status < 500 && + response.status !== 429) { + // Telemetry data successfully logged by server, clear Telemetry cache + this.config.serverTelemetryManager.clearTelemetryCache(); + } + return response; + } + /** + * Wraps sendPostRequestAsync with necessary preflight and postflight logic + * @param thumbprint - Request thumbprint for throttling + * @param tokenEndpoint - Endpoint to make the POST to + * @param options - Body and Headers to include on the POST request + * @param correlationId - CorrelationId for telemetry + */ + async sendPostRequest(thumbprint, tokenEndpoint, options, correlationId) { + ThrottlingUtils.preProcess(this.cacheManager, thumbprint, correlationId); + let response; + try { + response = await invokeAsync((this.networkClient.sendPostRequestAsync.bind(this.networkClient)), PerformanceEvents.NetworkClientSendPostRequestAsync, this.logger, this.performanceClient, correlationId)(tokenEndpoint, options); + const responseHeaders = response.headers || {}; + this.performanceClient?.addFields({ + refreshTokenSize: response.body.refresh_token?.length || 0, + httpVerToken: responseHeaders[HeaderNames.X_MS_HTTP_VERSION] || "", + requestId: responseHeaders[HeaderNames.X_MS_REQUEST_ID] || "", + }, correlationId); + } + catch (e) { + if (e instanceof NetworkError) { + const responseHeaders = e.responseHeaders; + if (responseHeaders) { + this.performanceClient?.addFields({ + httpVerToken: responseHeaders[HeaderNames.X_MS_HTTP_VERSION] || "", + requestId: responseHeaders[HeaderNames.X_MS_REQUEST_ID] || + "", + contentTypeHeader: responseHeaders[HeaderNames.CONTENT_TYPE] || + undefined, + contentLengthHeader: responseHeaders[HeaderNames.CONTENT_LENGTH] || + undefined, + httpStatus: e.httpStatus, + }, correlationId); + } + throw e.error; + } + if (e instanceof AuthError) { + throw e; + } + else { + throw createClientAuthError(networkError); + } + } + ThrottlingUtils.postProcess(this.cacheManager, thumbprint, response, correlationId); + return response; + } + /** + * Updates the authority object of the client. Endpoint discovery must be completed. + * @param updatedAuthority + */ + async updateAuthority(cloudInstanceHostname, correlationId) { + this.performanceClient?.addQueueMeasurement(PerformanceEvents.UpdateTokenEndpointAuthority, correlationId); + const cloudInstanceAuthorityUri = `https://${cloudInstanceHostname}/${this.authority.tenant}/`; + const cloudInstanceAuthority = await createDiscoveredInstance(cloudInstanceAuthorityUri, this.networkClient, this.cacheManager, this.authority.options, this.logger, correlationId, this.performanceClient); + this.authority = cloudInstanceAuthority; + } + /** + * Creates query string for the /token request + * @param request + */ + createTokenQueryParameters(request) { + const parameters = new Map(); + if (request.embeddedClientId) { + addBrokerParameters(parameters, this.config.authOptions.clientId, this.config.authOptions.redirectUri); + } + if (request.tokenQueryParameters) { + addExtraQueryParameters(parameters, request.tokenQueryParameters); + } + addCorrelationId(parameters, request.correlationId); + instrumentBrokerParams(parameters, request.correlationId, this.performanceClient); + return mapToQueryString(parameters); + } +} + +export { BaseClient }; +//# sourceMappingURL=BaseClient.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/client/RefreshTokenClient.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/client/RefreshTokenClient.mjs new file mode 100644 index 00000000..78b3fd82 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/client/RefreshTokenClient.mjs @@ -0,0 +1,236 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +import { isOidcProtocolMode } from '../config/ClientConfiguration.mjs'; +import { BaseClient } from './BaseClient.mjs'; +import { addClientId, addRedirectUri, addScopes, addGrantType, addClientInfo, addLibraryInfo, addApplicationTelemetry, addThrottling, addServerTelemetry, addRefreshToken, addClientSecret, addClientAssertion, addClientAssertionType, addPopToken, addSshJwk, addClaims, addCcsUpn, addCcsOid, addBrokerParameters, addExtraQueryParameters, instrumentBrokerParams } from '../request/RequestParameterBuilder.mjs'; +import { mapToQueryString } from '../utils/UrlUtils.mjs'; +import { AuthenticationScheme, HeaderNames, Errors, GrantType } from '../utils/Constants.mjs'; +import { CLIENT_ID } from '../constants/AADServerParamKeys.mjs'; +import { ResponseHandler } from '../response/ResponseHandler.mjs'; +import { PopTokenGenerator } from '../crypto/PopTokenGenerator.mjs'; +import { StringUtils } from '../utils/StringUtils.mjs'; +import { createClientConfigurationError } from '../error/ClientConfigurationError.mjs'; +import { createClientAuthError } from '../error/ClientAuthError.mjs'; +import { ServerError } from '../error/ServerError.mjs'; +import { nowSeconds, isTokenExpired } from '../utils/TimeUtils.mjs'; +import { UrlString } from '../url/UrlString.mjs'; +import { CcsCredentialType } from '../account/CcsCredential.mjs'; +import { buildClientInfoFromHomeAccountId } from '../account/ClientInfo.mjs'; +import { createInteractionRequiredAuthError, InteractionRequiredAuthError } from '../error/InteractionRequiredAuthError.mjs'; +import { PerformanceEvents } from '../telemetry/performance/PerformanceEvent.mjs'; +import { invokeAsync, invoke } from '../utils/FunctionWrappers.mjs'; +import { getClientAssertion } from '../utils/ClientAssertionUtils.mjs'; +import { getRequestThumbprint } from '../network/RequestThumbprint.mjs'; +import { badToken, noTokensFound, refreshTokenExpired } from '../error/InteractionRequiredAuthErrorCodes.mjs'; +import { tokenRequestEmpty, missingSshJwk } from '../error/ClientConfigurationErrorCodes.mjs'; +import { noAccountInSilentRequest } from '../error/ClientAuthErrorCodes.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +const DEFAULT_REFRESH_TOKEN_EXPIRATION_OFFSET_SECONDS = 300; // 5 Minutes +/** + * OAuth2.0 refresh token client + * @internal + */ +class RefreshTokenClient extends BaseClient { + constructor(configuration, performanceClient) { + super(configuration, performanceClient); + } + async acquireToken(request) { + this.performanceClient?.addQueueMeasurement(PerformanceEvents.RefreshTokenClientAcquireToken, request.correlationId); + const reqTimestamp = nowSeconds(); + const response = await invokeAsync(this.executeTokenRequest.bind(this), PerformanceEvents.RefreshTokenClientExecuteTokenRequest, this.logger, this.performanceClient, request.correlationId)(request, this.authority); + // Retrieve requestId from response headers + const requestId = response.headers?.[HeaderNames.X_MS_REQUEST_ID]; + const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.config.serializableCache, this.config.persistencePlugin); + responseHandler.validateTokenResponse(response.body); + return invokeAsync(responseHandler.handleServerTokenResponse.bind(responseHandler), PerformanceEvents.HandleServerTokenResponse, this.logger, this.performanceClient, request.correlationId)(response.body, this.authority, reqTimestamp, request, undefined, undefined, true, request.forceCache, requestId); + } + /** + * Gets cached refresh token and attaches to request, then calls acquireToken API + * @param request + */ + async acquireTokenByRefreshToken(request) { + // Cannot renew token if no request object is given. + if (!request) { + throw createClientConfigurationError(tokenRequestEmpty); + } + this.performanceClient?.addQueueMeasurement(PerformanceEvents.RefreshTokenClientAcquireTokenByRefreshToken, request.correlationId); + // We currently do not support silent flow for account === null use cases; This will be revisited for confidential flow usecases + if (!request.account) { + throw createClientAuthError(noAccountInSilentRequest); + } + // try checking if FOCI is enabled for the given application + const isFOCI = this.cacheManager.isAppMetadataFOCI(request.account.environment); + // if the app is part of the family, retrive a Family refresh token if present and make a refreshTokenRequest + if (isFOCI) { + try { + return await invokeAsync(this.acquireTokenWithCachedRefreshToken.bind(this), PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken, this.logger, this.performanceClient, request.correlationId)(request, true); + } + catch (e) { + const noFamilyRTInCache = e instanceof InteractionRequiredAuthError && + e.errorCode === + noTokensFound; + const clientMismatchErrorWithFamilyRT = e instanceof ServerError && + e.errorCode === Errors.INVALID_GRANT_ERROR && + e.subError === Errors.CLIENT_MISMATCH_ERROR; + // if family Refresh Token (FRT) cache acquisition fails or if client_mismatch error is seen with FRT, reattempt with application Refresh Token (ART) + if (noFamilyRTInCache || clientMismatchErrorWithFamilyRT) { + return invokeAsync(this.acquireTokenWithCachedRefreshToken.bind(this), PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken, this.logger, this.performanceClient, request.correlationId)(request, false); + // throw in all other cases + } + else { + throw e; + } + } + } + // fall back to application refresh token acquisition + return invokeAsync(this.acquireTokenWithCachedRefreshToken.bind(this), PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken, this.logger, this.performanceClient, request.correlationId)(request, false); + } + /** + * makes a network call to acquire tokens by exchanging RefreshToken available in userCache; throws if refresh token is not cached + * @param request + */ + async acquireTokenWithCachedRefreshToken(request, foci) { + this.performanceClient?.addQueueMeasurement(PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken, request.correlationId); + // fetches family RT or application RT based on FOCI value + const refreshToken = invoke(this.cacheManager.getRefreshToken.bind(this.cacheManager), PerformanceEvents.CacheManagerGetRefreshToken, this.logger, this.performanceClient, request.correlationId)(request.account, foci, request.correlationId, undefined, this.performanceClient); + if (!refreshToken) { + throw createInteractionRequiredAuthError(noTokensFound); + } + if (refreshToken.expiresOn && + isTokenExpired(refreshToken.expiresOn, request.refreshTokenExpirationOffsetSeconds || + DEFAULT_REFRESH_TOKEN_EXPIRATION_OFFSET_SECONDS)) { + this.performanceClient?.addFields({ rtExpiresOnMs: Number(refreshToken.expiresOn) }, request.correlationId); + throw createInteractionRequiredAuthError(refreshTokenExpired); + } + // attach cached RT size to the current measurement + const refreshTokenRequest = { + ...request, + refreshToken: refreshToken.secret, + authenticationScheme: request.authenticationScheme || AuthenticationScheme.BEARER, + ccsCredential: { + credential: request.account.homeAccountId, + type: CcsCredentialType.HOME_ACCOUNT_ID, + }, + }; + try { + return await invokeAsync(this.acquireToken.bind(this), PerformanceEvents.RefreshTokenClientAcquireToken, this.logger, this.performanceClient, request.correlationId)(refreshTokenRequest); + } + catch (e) { + if (e instanceof InteractionRequiredAuthError) { + this.performanceClient?.addFields({ rtExpiresOnMs: Number(refreshToken.expiresOn) }, request.correlationId); + if (e.subError === badToken) { + // Remove bad refresh token from cache + this.logger.verbose("acquireTokenWithRefreshToken: bad refresh token, removing from cache"); + const badRefreshTokenKey = this.cacheManager.generateCredentialKey(refreshToken); + this.cacheManager.removeRefreshToken(badRefreshTokenKey, request.correlationId); + } + } + throw e; + } + } + /** + * Constructs the network message and makes a NW call to the underlying secure token service + * @param request + * @param authority + */ + async executeTokenRequest(request, authority) { + this.performanceClient?.addQueueMeasurement(PerformanceEvents.RefreshTokenClientExecuteTokenRequest, request.correlationId); + const queryParametersString = this.createTokenQueryParameters(request); + const endpoint = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString); + const requestBody = await invokeAsync(this.createTokenRequestBody.bind(this), PerformanceEvents.RefreshTokenClientCreateTokenRequestBody, this.logger, this.performanceClient, request.correlationId)(request); + const headers = this.createTokenRequestHeaders(request.ccsCredential); + const thumbprint = getRequestThumbprint(this.config.authOptions.clientId, request); + return invokeAsync(this.executePostToTokenEndpoint.bind(this), PerformanceEvents.RefreshTokenClientExecutePostToTokenEndpoint, this.logger, this.performanceClient, request.correlationId)(endpoint, requestBody, headers, thumbprint, request.correlationId, PerformanceEvents.RefreshTokenClientExecutePostToTokenEndpoint); + } + /** + * Helper function to create the token request body + * @param request + */ + async createTokenRequestBody(request) { + this.performanceClient?.addQueueMeasurement(PerformanceEvents.RefreshTokenClientCreateTokenRequestBody, request.correlationId); + const parameters = new Map(); + addClientId(parameters, request.embeddedClientId || + request.tokenBodyParameters?.[CLIENT_ID] || + this.config.authOptions.clientId); + if (request.redirectUri) { + addRedirectUri(parameters, request.redirectUri); + } + addScopes(parameters, request.scopes, true, this.config.authOptions.authority.options.OIDCOptions?.defaultScopes); + addGrantType(parameters, GrantType.REFRESH_TOKEN_GRANT); + addClientInfo(parameters); + addLibraryInfo(parameters, this.config.libraryInfo); + addApplicationTelemetry(parameters, this.config.telemetry.application); + addThrottling(parameters); + if (this.serverTelemetryManager && !isOidcProtocolMode(this.config)) { + addServerTelemetry(parameters, this.serverTelemetryManager); + } + addRefreshToken(parameters, request.refreshToken); + if (this.config.clientCredentials.clientSecret) { + addClientSecret(parameters, this.config.clientCredentials.clientSecret); + } + if (this.config.clientCredentials.clientAssertion) { + const clientAssertion = this.config.clientCredentials.clientAssertion; + addClientAssertion(parameters, await getClientAssertion(clientAssertion.assertion, this.config.authOptions.clientId, request.resourceRequestUri)); + addClientAssertionType(parameters, clientAssertion.assertionType); + } + if (request.authenticationScheme === AuthenticationScheme.POP) { + const popTokenGenerator = new PopTokenGenerator(this.cryptoUtils, this.performanceClient); + let reqCnfData; + if (!request.popKid) { + const generatedReqCnfData = await invokeAsync(popTokenGenerator.generateCnf.bind(popTokenGenerator), PerformanceEvents.PopTokenGenerateCnf, this.logger, this.performanceClient, request.correlationId)(request, this.logger); + reqCnfData = generatedReqCnfData.reqCnfString; + } + else { + reqCnfData = this.cryptoUtils.encodeKid(request.popKid); + } + // SPA PoP requires full Base64Url encoded req_cnf string (unhashed) + addPopToken(parameters, reqCnfData); + } + else if (request.authenticationScheme === AuthenticationScheme.SSH) { + if (request.sshJwk) { + addSshJwk(parameters, request.sshJwk); + } + else { + throw createClientConfigurationError(missingSshJwk); + } + } + if (!StringUtils.isEmptyObj(request.claims) || + (this.config.authOptions.clientCapabilities && + this.config.authOptions.clientCapabilities.length > 0)) { + addClaims(parameters, request.claims, this.config.authOptions.clientCapabilities); + } + if (this.config.systemOptions.preventCorsPreflight && + request.ccsCredential) { + switch (request.ccsCredential.type) { + case CcsCredentialType.HOME_ACCOUNT_ID: + try { + const clientInfo = buildClientInfoFromHomeAccountId(request.ccsCredential.credential); + addCcsOid(parameters, clientInfo); + } + catch (e) { + this.logger.verbose("Could not parse home account ID for CCS Header: " + + e); + } + break; + case CcsCredentialType.UPN: + addCcsUpn(parameters, request.ccsCredential.credential); + break; + } + } + if (request.embeddedClientId) { + addBrokerParameters(parameters, this.config.authOptions.clientId, this.config.authOptions.redirectUri); + } + if (request.tokenBodyParameters) { + addExtraQueryParameters(parameters, request.tokenBodyParameters); + } + instrumentBrokerParams(parameters, request.correlationId, this.performanceClient); + return mapToQueryString(parameters); + } +} + +export { RefreshTokenClient }; +//# sourceMappingURL=RefreshTokenClient.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/client/SilentFlowClient.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/client/SilentFlowClient.mjs new file mode 100644 index 00000000..0ea3444c --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/client/SilentFlowClient.mjs @@ -0,0 +1,112 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +import { BaseClient } from './BaseClient.mjs'; +import { wasClockTurnedBack, isTokenExpired } from '../utils/TimeUtils.mjs'; +import { createClientAuthError } from '../error/ClientAuthError.mjs'; +import { ResponseHandler } from '../response/ResponseHandler.mjs'; +import { CacheOutcome } from '../utils/Constants.mjs'; +import { StringUtils } from '../utils/StringUtils.mjs'; +import { extractTokenClaims, checkMaxAge } from '../account/AuthToken.mjs'; +import { PerformanceEvents } from '../telemetry/performance/PerformanceEvent.mjs'; +import { invokeAsync } from '../utils/FunctionWrappers.mjs'; +import { getTenantFromAuthorityString } from '../authority/Authority.mjs'; +import { tokenRefreshRequired, noAccountInSilentRequest, authTimeNotFound } from '../error/ClientAuthErrorCodes.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** @internal */ +class SilentFlowClient extends BaseClient { + constructor(configuration, performanceClient) { + super(configuration, performanceClient); + } + /** + * Retrieves token from cache or throws an error if it must be refreshed. + * @param request + */ + async acquireCachedToken(request) { + this.performanceClient?.addQueueMeasurement(PerformanceEvents.SilentFlowClientAcquireCachedToken, request.correlationId); + let lastCacheOutcome = CacheOutcome.NOT_APPLICABLE; + if (request.forceRefresh || + (!this.config.cacheOptions.claimsBasedCachingEnabled && + !StringUtils.isEmptyObj(request.claims))) { + // Must refresh due to present force_refresh flag. + this.setCacheOutcome(CacheOutcome.FORCE_REFRESH_OR_CLAIMS, request.correlationId); + throw createClientAuthError(tokenRefreshRequired); + } + // We currently do not support silent flow for account === null use cases; This will be revisited for confidential flow usecases + if (!request.account) { + throw createClientAuthError(noAccountInSilentRequest); + } + const requestTenantId = request.account.tenantId || + getTenantFromAuthorityString(request.authority); + const tokenKeys = this.cacheManager.getTokenKeys(); + const cachedAccessToken = this.cacheManager.getAccessToken(request.account, request, tokenKeys, requestTenantId); + if (!cachedAccessToken) { + // must refresh due to non-existent access_token + this.setCacheOutcome(CacheOutcome.NO_CACHED_ACCESS_TOKEN, request.correlationId); + throw createClientAuthError(tokenRefreshRequired); + } + else if (wasClockTurnedBack(cachedAccessToken.cachedAt) || + isTokenExpired(cachedAccessToken.expiresOn, this.config.systemOptions.tokenRenewalOffsetSeconds)) { + // must refresh due to the expires_in value + this.setCacheOutcome(CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED, request.correlationId); + throw createClientAuthError(tokenRefreshRequired); + } + else if (cachedAccessToken.refreshOn && + isTokenExpired(cachedAccessToken.refreshOn, 0)) { + // must refresh (in the background) due to the refresh_in value + lastCacheOutcome = CacheOutcome.PROACTIVELY_REFRESHED; + // don't throw ClientAuthError.createRefreshRequiredError(), return cached token instead + } + const environment = request.authority || this.authority.getPreferredCache(); + const cacheRecord = { + account: this.cacheManager.getAccount(this.cacheManager.generateAccountKey(request.account), request.correlationId), + accessToken: cachedAccessToken, + idToken: this.cacheManager.getIdToken(request.account, request.correlationId, tokenKeys, requestTenantId, this.performanceClient), + refreshToken: null, + appMetadata: this.cacheManager.readAppMetadataFromCache(environment), + }; + this.setCacheOutcome(lastCacheOutcome, request.correlationId); + if (this.config.serverTelemetryManager) { + this.config.serverTelemetryManager.incrementCacheHits(); + } + return [ + await invokeAsync(this.generateResultFromCacheRecord.bind(this), PerformanceEvents.SilentFlowClientGenerateResultFromCacheRecord, this.logger, this.performanceClient, request.correlationId)(cacheRecord, request), + lastCacheOutcome, + ]; + } + setCacheOutcome(cacheOutcome, correlationId) { + this.serverTelemetryManager?.setCacheOutcome(cacheOutcome); + this.performanceClient?.addFields({ + cacheOutcome: cacheOutcome, + }, correlationId); + if (cacheOutcome !== CacheOutcome.NOT_APPLICABLE) { + this.logger.info(`Token refresh is required due to cache outcome: ${cacheOutcome}`); + } + } + /** + * Helper function to build response object from the CacheRecord + * @param cacheRecord + */ + async generateResultFromCacheRecord(cacheRecord, request) { + this.performanceClient?.addQueueMeasurement(PerformanceEvents.SilentFlowClientGenerateResultFromCacheRecord, request.correlationId); + let idTokenClaims; + if (cacheRecord.idToken) { + idTokenClaims = extractTokenClaims(cacheRecord.idToken.secret, this.config.cryptoInterface.base64Decode); + } + // token max_age check + if (request.maxAge || request.maxAge === 0) { + const authTime = idTokenClaims?.auth_time; + if (!authTime) { + throw createClientAuthError(authTimeNotFound); + } + checkMaxAge(authTime, request.maxAge); + } + return ResponseHandler.generateAuthenticationResult(this.cryptoUtils, this.authority, cacheRecord, true, request, idTokenClaims); + } +} + +export { SilentFlowClient }; +//# sourceMappingURL=SilentFlowClient.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/config/ClientConfiguration.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/config/ClientConfiguration.mjs new file mode 100644 index 00000000..8a91ccd7 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/config/ClientConfiguration.mjs @@ -0,0 +1,113 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +import { DEFAULT_CRYPTO_IMPLEMENTATION } from '../crypto/ICrypto.mjs'; +import { LogLevel, Logger } from '../logger/Logger.mjs'; +import { DEFAULT_TOKEN_RENEWAL_OFFSET_SEC, Constants } from '../utils/Constants.mjs'; +import { version } from '../packageMetadata.mjs'; +import { AzureCloudInstance } from '../authority/AuthorityOptions.mjs'; +import { DefaultStorageClass } from '../cache/CacheManager.mjs'; +import { ProtocolMode } from '../authority/ProtocolMode.mjs'; +import { createClientAuthError } from '../error/ClientAuthError.mjs'; +import { StubPerformanceClient } from '../telemetry/performance/StubPerformanceClient.mjs'; +import { methodNotImplemented } from '../error/ClientAuthErrorCodes.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +const DEFAULT_SYSTEM_OPTIONS = { + tokenRenewalOffsetSeconds: DEFAULT_TOKEN_RENEWAL_OFFSET_SEC, + preventCorsPreflight: false, +}; +const DEFAULT_LOGGER_IMPLEMENTATION = { + loggerCallback: () => { + // allow users to not set loggerCallback + }, + piiLoggingEnabled: false, + logLevel: LogLevel.Info, + correlationId: Constants.EMPTY_STRING, +}; +const DEFAULT_CACHE_OPTIONS = { + claimsBasedCachingEnabled: false, +}; +const DEFAULT_NETWORK_IMPLEMENTATION = { + async sendGetRequestAsync() { + throw createClientAuthError(methodNotImplemented); + }, + async sendPostRequestAsync() { + throw createClientAuthError(methodNotImplemented); + }, +}; +const DEFAULT_LIBRARY_INFO = { + sku: Constants.SKU, + version: version, + cpu: Constants.EMPTY_STRING, + os: Constants.EMPTY_STRING, +}; +const DEFAULT_CLIENT_CREDENTIALS = { + clientSecret: Constants.EMPTY_STRING, + clientAssertion: undefined, +}; +const DEFAULT_AZURE_CLOUD_OPTIONS = { + azureCloudInstance: AzureCloudInstance.None, + tenant: `${Constants.DEFAULT_COMMON_TENANT}`, +}; +const DEFAULT_TELEMETRY_OPTIONS = { + application: { + appName: "", + appVersion: "", + }, +}; +/** + * Function that sets the default options when not explicitly configured from app developer + * + * @param Configuration + * + * @returns Configuration + */ +function buildClientConfiguration({ authOptions: userAuthOptions, systemOptions: userSystemOptions, loggerOptions: userLoggerOption, cacheOptions: userCacheOptions, storageInterface: storageImplementation, networkInterface: networkImplementation, cryptoInterface: cryptoImplementation, clientCredentials: clientCredentials, libraryInfo: libraryInfo, telemetry: telemetry, serverTelemetryManager: serverTelemetryManager, persistencePlugin: persistencePlugin, serializableCache: serializableCache, }) { + const loggerOptions = { + ...DEFAULT_LOGGER_IMPLEMENTATION, + ...userLoggerOption, + }; + return { + authOptions: buildAuthOptions(userAuthOptions), + systemOptions: { ...DEFAULT_SYSTEM_OPTIONS, ...userSystemOptions }, + loggerOptions: loggerOptions, + cacheOptions: { ...DEFAULT_CACHE_OPTIONS, ...userCacheOptions }, + storageInterface: storageImplementation || + new DefaultStorageClass(userAuthOptions.clientId, DEFAULT_CRYPTO_IMPLEMENTATION, new Logger(loggerOptions), new StubPerformanceClient()), + networkInterface: networkImplementation || DEFAULT_NETWORK_IMPLEMENTATION, + cryptoInterface: cryptoImplementation || DEFAULT_CRYPTO_IMPLEMENTATION, + clientCredentials: clientCredentials || DEFAULT_CLIENT_CREDENTIALS, + libraryInfo: { ...DEFAULT_LIBRARY_INFO, ...libraryInfo }, + telemetry: { ...DEFAULT_TELEMETRY_OPTIONS, ...telemetry }, + serverTelemetryManager: serverTelemetryManager || null, + persistencePlugin: persistencePlugin || null, + serializableCache: serializableCache || null, + }; +} +/** + * Construct authoptions from the client and platform passed values + * @param authOptions + */ +function buildAuthOptions(authOptions) { + return { + clientCapabilities: [], + azureCloudOptions: DEFAULT_AZURE_CLOUD_OPTIONS, + skipAuthorityMetadataCache: false, + instanceAware: false, + encodeExtraQueryParams: false, + ...authOptions, + }; +} +/** + * Returns true if config has protocolMode set to ProtocolMode.OIDC, false otherwise + * @param ClientConfiguration + */ +function isOidcProtocolMode(config) { + return (config.authOptions.authority.options.protocolMode === ProtocolMode.OIDC); +} + +export { DEFAULT_SYSTEM_OPTIONS, buildClientConfiguration, isOidcProtocolMode }; +//# sourceMappingURL=ClientConfiguration.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/constants/AADServerParamKeys.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/constants/AADServerParamKeys.mjs new file mode 100644 index 00000000..d084642f --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/constants/AADServerParamKeys.mjs @@ -0,0 +1,67 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +const CLIENT_ID = "client_id"; +const REDIRECT_URI = "redirect_uri"; +const RESPONSE_TYPE = "response_type"; +const RESPONSE_MODE = "response_mode"; +const GRANT_TYPE = "grant_type"; +const CLAIMS = "claims"; +const SCOPE = "scope"; +const ERROR = "error"; +const ERROR_DESCRIPTION = "error_description"; +const ACCESS_TOKEN = "access_token"; +const ID_TOKEN = "id_token"; +const REFRESH_TOKEN = "refresh_token"; +const EXPIRES_IN = "expires_in"; +const REFRESH_TOKEN_EXPIRES_IN = "refresh_token_expires_in"; +const STATE = "state"; +const NONCE = "nonce"; +const PROMPT = "prompt"; +const SESSION_STATE = "session_state"; +const CLIENT_INFO = "client_info"; +const CODE = "code"; +const CODE_CHALLENGE = "code_challenge"; +const CODE_CHALLENGE_METHOD = "code_challenge_method"; +const CODE_VERIFIER = "code_verifier"; +const CLIENT_REQUEST_ID = "client-request-id"; +const X_CLIENT_SKU = "x-client-SKU"; +const X_CLIENT_VER = "x-client-VER"; +const X_CLIENT_OS = "x-client-OS"; +const X_CLIENT_CPU = "x-client-CPU"; +const X_CLIENT_CURR_TELEM = "x-client-current-telemetry"; +const X_CLIENT_LAST_TELEM = "x-client-last-telemetry"; +const X_MS_LIB_CAPABILITY = "x-ms-lib-capability"; +const X_APP_NAME = "x-app-name"; +const X_APP_VER = "x-app-ver"; +const POST_LOGOUT_URI = "post_logout_redirect_uri"; +const ID_TOKEN_HINT = "id_token_hint"; +const DEVICE_CODE = "device_code"; +const CLIENT_SECRET = "client_secret"; +const CLIENT_ASSERTION = "client_assertion"; +const CLIENT_ASSERTION_TYPE = "client_assertion_type"; +const TOKEN_TYPE = "token_type"; +const REQ_CNF = "req_cnf"; +const OBO_ASSERTION = "assertion"; +const REQUESTED_TOKEN_USE = "requested_token_use"; +const ON_BEHALF_OF = "on_behalf_of"; +const FOCI = "foci"; +const CCS_HEADER = "X-AnchorMailbox"; +const RETURN_SPA_CODE = "return_spa_code"; +const NATIVE_BROKER = "nativebroker"; +const LOGOUT_HINT = "logout_hint"; +const SID = "sid"; +const LOGIN_HINT = "login_hint"; +const DOMAIN_HINT = "domain_hint"; +const X_CLIENT_EXTRA_SKU = "x-client-xtra-sku"; +const BROKER_CLIENT_ID = "brk_client_id"; +const BROKER_REDIRECT_URI = "brk_redirect_uri"; +const INSTANCE_AWARE = "instance_aware"; +const EAR_JWK = "ear_jwk"; +const EAR_JWE_CRYPTO = "ear_jwe_crypto"; + +export { ACCESS_TOKEN, BROKER_CLIENT_ID, BROKER_REDIRECT_URI, CCS_HEADER, CLAIMS, CLIENT_ASSERTION, CLIENT_ASSERTION_TYPE, CLIENT_ID, CLIENT_INFO, CLIENT_REQUEST_ID, CLIENT_SECRET, CODE, CODE_CHALLENGE, CODE_CHALLENGE_METHOD, CODE_VERIFIER, DEVICE_CODE, DOMAIN_HINT, EAR_JWE_CRYPTO, EAR_JWK, ERROR, ERROR_DESCRIPTION, EXPIRES_IN, FOCI, GRANT_TYPE, ID_TOKEN, ID_TOKEN_HINT, INSTANCE_AWARE, LOGIN_HINT, LOGOUT_HINT, NATIVE_BROKER, NONCE, OBO_ASSERTION, ON_BEHALF_OF, POST_LOGOUT_URI, PROMPT, REDIRECT_URI, REFRESH_TOKEN, REFRESH_TOKEN_EXPIRES_IN, REQUESTED_TOKEN_USE, REQ_CNF, RESPONSE_MODE, RESPONSE_TYPE, RETURN_SPA_CODE, SCOPE, SESSION_STATE, SID, STATE, TOKEN_TYPE, X_APP_NAME, X_APP_VER, X_CLIENT_CPU, X_CLIENT_CURR_TELEM, X_CLIENT_EXTRA_SKU, X_CLIENT_LAST_TELEM, X_CLIENT_OS, X_CLIENT_SKU, X_CLIENT_VER, X_MS_LIB_CAPABILITY }; +//# sourceMappingURL=AADServerParamKeys.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/crypto/ICrypto.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/crypto/ICrypto.mjs new file mode 100644 index 00000000..562c4c41 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/crypto/ICrypto.mjs @@ -0,0 +1,44 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +import { createClientAuthError } from '../error/ClientAuthError.mjs'; +import { methodNotImplemented } from '../error/ClientAuthErrorCodes.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +const DEFAULT_CRYPTO_IMPLEMENTATION = { + createNewGuid: () => { + throw createClientAuthError(methodNotImplemented); + }, + base64Decode: () => { + throw createClientAuthError(methodNotImplemented); + }, + base64Encode: () => { + throw createClientAuthError(methodNotImplemented); + }, + base64UrlEncode: () => { + throw createClientAuthError(methodNotImplemented); + }, + encodeKid: () => { + throw createClientAuthError(methodNotImplemented); + }, + async getPublicKeyThumbprint() { + throw createClientAuthError(methodNotImplemented); + }, + async removeTokenBindingKey() { + throw createClientAuthError(methodNotImplemented); + }, + async clearKeystore() { + throw createClientAuthError(methodNotImplemented); + }, + async signJwt() { + throw createClientAuthError(methodNotImplemented); + }, + async hashString() { + throw createClientAuthError(methodNotImplemented); + }, +}; + +export { DEFAULT_CRYPTO_IMPLEMENTATION }; +//# sourceMappingURL=ICrypto.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/crypto/PopTokenGenerator.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/crypto/PopTokenGenerator.mjs new file mode 100644 index 00000000..2def7f2b --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/crypto/PopTokenGenerator.mjs @@ -0,0 +1,89 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +import { nowSeconds } from '../utils/TimeUtils.mjs'; +import { UrlString } from '../url/UrlString.mjs'; +import { PerformanceEvents } from '../telemetry/performance/PerformanceEvent.mjs'; +import { invokeAsync } from '../utils/FunctionWrappers.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +const KeyLocation = { + SW: "sw"}; +/** @internal */ +class PopTokenGenerator { + constructor(cryptoUtils, performanceClient) { + this.cryptoUtils = cryptoUtils; + this.performanceClient = performanceClient; + } + /** + * Generates the req_cnf validated at the RP in the POP protocol for SHR parameters + * and returns an object containing the keyid, the full req_cnf string and the req_cnf string hash + * @param request + * @returns + */ + async generateCnf(request, logger) { + this.performanceClient?.addQueueMeasurement(PerformanceEvents.PopTokenGenerateCnf, request.correlationId); + const reqCnf = await invokeAsync(this.generateKid.bind(this), PerformanceEvents.PopTokenGenerateCnf, logger, this.performanceClient, request.correlationId)(request); + const reqCnfString = this.cryptoUtils.base64UrlEncode(JSON.stringify(reqCnf)); + return { + kid: reqCnf.kid, + reqCnfString, + }; + } + /** + * Generates key_id for a SHR token request + * @param request + * @returns + */ + async generateKid(request) { + this.performanceClient?.addQueueMeasurement(PerformanceEvents.PopTokenGenerateKid, request.correlationId); + const kidThumbprint = await this.cryptoUtils.getPublicKeyThumbprint(request); + return { + kid: kidThumbprint, + xms_ksl: KeyLocation.SW, + }; + } + /** + * Signs the POP access_token with the local generated key-pair + * @param accessToken + * @param request + * @returns + */ + async signPopToken(accessToken, keyId, request) { + return this.signPayload(accessToken, keyId, request); + } + /** + * Utility function to generate the signed JWT for an access_token + * @param payload + * @param kid + * @param request + * @param claims + * @returns + */ + async signPayload(payload, keyId, request, claims) { + // Deconstruct request to extract SHR parameters + const { resourceRequestMethod, resourceRequestUri, shrClaims, shrNonce, shrOptions, } = request; + const resourceUrlString = resourceRequestUri + ? new UrlString(resourceRequestUri) + : undefined; + const resourceUrlComponents = resourceUrlString?.getUrlComponents(); + return this.cryptoUtils.signJwt({ + at: payload, + ts: nowSeconds(), + m: resourceRequestMethod?.toUpperCase(), + u: resourceUrlComponents?.HostNameAndPort, + nonce: shrNonce || this.cryptoUtils.createNewGuid(), + p: resourceUrlComponents?.AbsolutePath, + q: resourceUrlComponents?.QueryString + ? [[], resourceUrlComponents.QueryString] + : undefined, + client_claims: shrClaims || undefined, + ...claims, + }, keyId, shrOptions, request.correlationId); + } +} + +export { PopTokenGenerator }; +//# sourceMappingURL=PopTokenGenerator.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/error/AuthError.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/error/AuthError.mjs new file mode 100644 index 00000000..f92abafc --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/error/AuthError.mjs @@ -0,0 +1,56 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +import { Constants } from '../utils/Constants.mjs'; +import { postRequestFailed, unexpectedError } from './AuthErrorCodes.mjs'; +import * as AuthErrorCodes from './AuthErrorCodes.mjs'; +export { AuthErrorCodes }; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +const AuthErrorMessages = { + [unexpectedError]: "Unexpected error in authentication.", + [postRequestFailed]: "Post request failed from the network, could be a 4xx/5xx or a network unavailability. Please check the exact error code for details.", +}; +/** + * AuthErrorMessage class containing string constants used by error codes and messages. + * @deprecated Use AuthErrorCodes instead + */ +const AuthErrorMessage = { + unexpectedError: { + code: unexpectedError, + desc: AuthErrorMessages[unexpectedError], + }, + postRequestFailed: { + code: postRequestFailed, + desc: AuthErrorMessages[postRequestFailed], + }, +}; +/** + * General error class thrown by the MSAL.js library. + */ +class AuthError extends Error { + constructor(errorCode, errorMessage, suberror) { + const errorString = errorMessage + ? `${errorCode}: ${errorMessage}` + : errorCode; + super(errorString); + Object.setPrototypeOf(this, AuthError.prototype); + this.errorCode = errorCode || Constants.EMPTY_STRING; + this.errorMessage = errorMessage || Constants.EMPTY_STRING; + this.subError = suberror || Constants.EMPTY_STRING; + this.name = "AuthError"; + } + setCorrelationId(correlationId) { + this.correlationId = correlationId; + } +} +function createAuthError(code, additionalMessage) { + return new AuthError(code, additionalMessage + ? `${AuthErrorMessages[code]} ${additionalMessage}` + : AuthErrorMessages[code]); +} + +export { AuthError, AuthErrorMessage, AuthErrorMessages, createAuthError }; +//# sourceMappingURL=AuthError.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/error/AuthErrorCodes.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/error/AuthErrorCodes.mjs new file mode 100644 index 00000000..4da8c460 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/error/AuthErrorCodes.mjs @@ -0,0 +1,14 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * AuthErrorMessage class containing string constants used by error codes and messages. + */ +const unexpectedError = "unexpected_error"; +const postRequestFailed = "post_request_failed"; + +export { postRequestFailed, unexpectedError }; +//# sourceMappingURL=AuthErrorCodes.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/error/CacheError.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/error/CacheError.mjs new file mode 100644 index 00000000..95bd233e --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/error/CacheError.mjs @@ -0,0 +1,52 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +import { AuthError } from './AuthError.mjs'; +import { cacheErrorUnknown, cacheQuotaExceeded } from './CacheErrorCodes.mjs'; +import * as CacheErrorCodes from './CacheErrorCodes.mjs'; +export { CacheErrorCodes }; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +const CacheErrorMessages = { + [cacheQuotaExceeded]: "Exceeded cache storage capacity.", + [cacheErrorUnknown]: "Unexpected error occurred when using cache storage.", +}; +/** + * Error thrown when there is an error with the cache + */ +class CacheError extends AuthError { + constructor(errorCode, errorMessage) { + const message = errorMessage || + (CacheErrorMessages[errorCode] + ? CacheErrorMessages[errorCode] + : CacheErrorMessages[cacheErrorUnknown]); + super(`${errorCode}: ${message}`); + Object.setPrototypeOf(this, CacheError.prototype); + this.name = "CacheError"; + this.errorCode = errorCode; + this.errorMessage = message; + } +} +/** + * Helper function to wrap browser errors in a CacheError object + * @param e + * @returns + */ +function createCacheError(e) { + if (!(e instanceof Error)) { + return new CacheError(cacheErrorUnknown); + } + if (e.name === "QuotaExceededError" || + e.name === "NS_ERROR_DOM_QUOTA_REACHED" || + e.message.includes("exceeded the quota")) { + return new CacheError(cacheQuotaExceeded); + } + else { + return new CacheError(e.name, e.message); + } +} + +export { CacheError, CacheErrorMessages, createCacheError }; +//# sourceMappingURL=CacheError.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/error/CacheErrorCodes.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/error/CacheErrorCodes.mjs new file mode 100644 index 00000000..f8aa9244 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/error/CacheErrorCodes.mjs @@ -0,0 +1,11 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +const cacheQuotaExceeded = "cache_quota_exceeded"; +const cacheErrorUnknown = "cache_error_unknown"; + +export { cacheErrorUnknown, cacheQuotaExceeded }; +//# sourceMappingURL=CacheErrorCodes.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/error/ClientAuthError.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/error/ClientAuthError.mjs new file mode 100644 index 00000000..2a7dc322 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/error/ClientAuthError.mjs @@ -0,0 +1,259 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +import { AuthError } from './AuthError.mjs'; +import { nestedAppAuthBridgeDisabled, missingTenantIdError, userCanceled, noNetworkConnectivity, keyIdMissing, endSessionEndpointNotSupported, bindingKeyNotRemoved, authorizationCodeMissingFromServerResponse, tokenClaimsCnfRequiredForSignedJwt, userTimeoutReached, tokenRefreshRequired, invalidClientCredential, invalidAssertion, unexpectedCredentialType, noCryptoObject, noAccountFound, invalidCacheEnvironment, invalidCacheRecord, noAccountInSilentRequest, deviceCodeUnknownError, deviceCodeExpired, deviceCodePollingCancelled, emptyInputScopeSet, cannotAppendScopeSet, cannotRemoveEmptyScope, requestCannotBeMade, multipleMatchingAppMetadata, multipleMatchingAccounts, multipleMatchingTokens, maxAgeTranspired, authTimeNotFound, nonceMismatch, stateNotFound, stateMismatch, invalidState, hashNotDeserialized, openIdConfigError, networkError, endpointResolutionError, nullOrEmptyToken, tokenParsingError, clientInfoEmptyError, clientInfoDecodingError, methodNotImplemented } from './ClientAuthErrorCodes.mjs'; +import * as ClientAuthErrorCodes from './ClientAuthErrorCodes.mjs'; +export { ClientAuthErrorCodes }; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * ClientAuthErrorMessage class containing string constants used by error codes and messages. + */ +const ClientAuthErrorMessages = { + [clientInfoDecodingError]: "The client info could not be parsed/decoded correctly", + [clientInfoEmptyError]: "The client info was empty", + [tokenParsingError]: "Token cannot be parsed", + [nullOrEmptyToken]: "The token is null or empty", + [endpointResolutionError]: "Endpoints cannot be resolved", + [networkError]: "Network request failed", + [openIdConfigError]: "Could not retrieve endpoints. Check your authority and verify the .well-known/openid-configuration endpoint returns the required endpoints.", + [hashNotDeserialized]: "The hash parameters could not be deserialized", + [invalidState]: "State was not the expected format", + [stateMismatch]: "State mismatch error", + [stateNotFound]: "State not found", + [nonceMismatch]: "Nonce mismatch error", + [authTimeNotFound]: "Max Age was requested and the ID token is missing the auth_time variable." + + " auth_time is an optional claim and is not enabled by default - it must be enabled." + + " See https://aka.ms/msaljs/optional-claims for more information.", + [maxAgeTranspired]: "Max Age is set to 0, or too much time has elapsed since the last end-user authentication.", + [multipleMatchingTokens]: "The cache contains multiple tokens satisfying the requirements. " + + "Call AcquireToken again providing more requirements such as authority or account.", + [multipleMatchingAccounts]: "The cache contains multiple accounts satisfying the given parameters. Please pass more info to obtain the correct account", + [multipleMatchingAppMetadata]: "The cache contains multiple appMetadata satisfying the given parameters. Please pass more info to obtain the correct appMetadata", + [requestCannotBeMade]: "Token request cannot be made without authorization code or refresh token.", + [cannotRemoveEmptyScope]: "Cannot remove null or empty scope from ScopeSet", + [cannotAppendScopeSet]: "Cannot append ScopeSet", + [emptyInputScopeSet]: "Empty input ScopeSet cannot be processed", + [deviceCodePollingCancelled]: "Caller has cancelled token endpoint polling during device code flow by setting DeviceCodeRequest.cancel = true.", + [deviceCodeExpired]: "Device code is expired.", + [deviceCodeUnknownError]: "Device code stopped polling for unknown reasons.", + [noAccountInSilentRequest]: "Please pass an account object, silent flow is not supported without account information", + [invalidCacheRecord]: "Cache record object was null or undefined.", + [invalidCacheEnvironment]: "Invalid environment when attempting to create cache entry", + [noAccountFound]: "No account found in cache for given key.", + [noCryptoObject]: "No crypto object detected.", + [unexpectedCredentialType]: "Unexpected credential type.", + [invalidAssertion]: "Client assertion must meet requirements described in https://tools.ietf.org/html/rfc7515", + [invalidClientCredential]: "Client credential (secret, certificate, or assertion) must not be empty when creating a confidential client. An application should at most have one credential", + [tokenRefreshRequired]: "Cannot return token from cache because it must be refreshed. This may be due to one of the following reasons: forceRefresh parameter is set to true, claims have been requested, there is no cached access token or it is expired.", + [userTimeoutReached]: "User defined timeout for device code polling reached", + [tokenClaimsCnfRequiredForSignedJwt]: "Cannot generate a POP jwt if the token_claims are not populated", + [authorizationCodeMissingFromServerResponse]: "Server response does not contain an authorization code to proceed", + [bindingKeyNotRemoved]: "Could not remove the credential's binding key from storage.", + [endSessionEndpointNotSupported]: "The provided authority does not support logout", + [keyIdMissing]: "A keyId value is missing from the requested bound token's cache record and is required to match the token to it's stored binding key.", + [noNetworkConnectivity]: "No network connectivity. Check your internet connection.", + [userCanceled]: "User cancelled the flow.", + [missingTenantIdError]: "A tenant id - not common, organizations, or consumers - must be specified when using the client_credentials flow.", + [methodNotImplemented]: "This method has not been implemented", + [nestedAppAuthBridgeDisabled]: "The nested app auth bridge is disabled", +}; +/** + * String constants used by error codes and messages. + * @deprecated Use ClientAuthErrorCodes instead + */ +const ClientAuthErrorMessage = { + clientInfoDecodingError: { + code: clientInfoDecodingError, + desc: ClientAuthErrorMessages[clientInfoDecodingError], + }, + clientInfoEmptyError: { + code: clientInfoEmptyError, + desc: ClientAuthErrorMessages[clientInfoEmptyError], + }, + tokenParsingError: { + code: tokenParsingError, + desc: ClientAuthErrorMessages[tokenParsingError], + }, + nullOrEmptyToken: { + code: nullOrEmptyToken, + desc: ClientAuthErrorMessages[nullOrEmptyToken], + }, + endpointResolutionError: { + code: endpointResolutionError, + desc: ClientAuthErrorMessages[endpointResolutionError], + }, + networkError: { + code: networkError, + desc: ClientAuthErrorMessages[networkError], + }, + unableToGetOpenidConfigError: { + code: openIdConfigError, + desc: ClientAuthErrorMessages[openIdConfigError], + }, + hashNotDeserialized: { + code: hashNotDeserialized, + desc: ClientAuthErrorMessages[hashNotDeserialized], + }, + invalidStateError: { + code: invalidState, + desc: ClientAuthErrorMessages[invalidState], + }, + stateMismatchError: { + code: stateMismatch, + desc: ClientAuthErrorMessages[stateMismatch], + }, + stateNotFoundError: { + code: stateNotFound, + desc: ClientAuthErrorMessages[stateNotFound], + }, + nonceMismatchError: { + code: nonceMismatch, + desc: ClientAuthErrorMessages[nonceMismatch], + }, + authTimeNotFoundError: { + code: authTimeNotFound, + desc: ClientAuthErrorMessages[authTimeNotFound], + }, + maxAgeTranspired: { + code: maxAgeTranspired, + desc: ClientAuthErrorMessages[maxAgeTranspired], + }, + multipleMatchingTokens: { + code: multipleMatchingTokens, + desc: ClientAuthErrorMessages[multipleMatchingTokens], + }, + multipleMatchingAccounts: { + code: multipleMatchingAccounts, + desc: ClientAuthErrorMessages[multipleMatchingAccounts], + }, + multipleMatchingAppMetadata: { + code: multipleMatchingAppMetadata, + desc: ClientAuthErrorMessages[multipleMatchingAppMetadata], + }, + tokenRequestCannotBeMade: { + code: requestCannotBeMade, + desc: ClientAuthErrorMessages[requestCannotBeMade], + }, + removeEmptyScopeError: { + code: cannotRemoveEmptyScope, + desc: ClientAuthErrorMessages[cannotRemoveEmptyScope], + }, + appendScopeSetError: { + code: cannotAppendScopeSet, + desc: ClientAuthErrorMessages[cannotAppendScopeSet], + }, + emptyInputScopeSetError: { + code: emptyInputScopeSet, + desc: ClientAuthErrorMessages[emptyInputScopeSet], + }, + DeviceCodePollingCancelled: { + code: deviceCodePollingCancelled, + desc: ClientAuthErrorMessages[deviceCodePollingCancelled], + }, + DeviceCodeExpired: { + code: deviceCodeExpired, + desc: ClientAuthErrorMessages[deviceCodeExpired], + }, + DeviceCodeUnknownError: { + code: deviceCodeUnknownError, + desc: ClientAuthErrorMessages[deviceCodeUnknownError], + }, + NoAccountInSilentRequest: { + code: noAccountInSilentRequest, + desc: ClientAuthErrorMessages[noAccountInSilentRequest], + }, + invalidCacheRecord: { + code: invalidCacheRecord, + desc: ClientAuthErrorMessages[invalidCacheRecord], + }, + invalidCacheEnvironment: { + code: invalidCacheEnvironment, + desc: ClientAuthErrorMessages[invalidCacheEnvironment], + }, + noAccountFound: { + code: noAccountFound, + desc: ClientAuthErrorMessages[noAccountFound], + }, + noCryptoObj: { + code: noCryptoObject, + desc: ClientAuthErrorMessages[noCryptoObject], + }, + unexpectedCredentialType: { + code: unexpectedCredentialType, + desc: ClientAuthErrorMessages[unexpectedCredentialType], + }, + invalidAssertion: { + code: invalidAssertion, + desc: ClientAuthErrorMessages[invalidAssertion], + }, + invalidClientCredential: { + code: invalidClientCredential, + desc: ClientAuthErrorMessages[invalidClientCredential], + }, + tokenRefreshRequired: { + code: tokenRefreshRequired, + desc: ClientAuthErrorMessages[tokenRefreshRequired], + }, + userTimeoutReached: { + code: userTimeoutReached, + desc: ClientAuthErrorMessages[userTimeoutReached], + }, + tokenClaimsRequired: { + code: tokenClaimsCnfRequiredForSignedJwt, + desc: ClientAuthErrorMessages[tokenClaimsCnfRequiredForSignedJwt], + }, + noAuthorizationCodeFromServer: { + code: authorizationCodeMissingFromServerResponse, + desc: ClientAuthErrorMessages[authorizationCodeMissingFromServerResponse], + }, + bindingKeyNotRemovedError: { + code: bindingKeyNotRemoved, + desc: ClientAuthErrorMessages[bindingKeyNotRemoved], + }, + logoutNotSupported: { + code: endSessionEndpointNotSupported, + desc: ClientAuthErrorMessages[endSessionEndpointNotSupported], + }, + keyIdMissing: { + code: keyIdMissing, + desc: ClientAuthErrorMessages[keyIdMissing], + }, + noNetworkConnectivity: { + code: noNetworkConnectivity, + desc: ClientAuthErrorMessages[noNetworkConnectivity], + }, + userCanceledError: { + code: userCanceled, + desc: ClientAuthErrorMessages[userCanceled], + }, + missingTenantIdError: { + code: missingTenantIdError, + desc: ClientAuthErrorMessages[missingTenantIdError], + }, + nestedAppAuthBridgeDisabled: { + code: nestedAppAuthBridgeDisabled, + desc: ClientAuthErrorMessages[nestedAppAuthBridgeDisabled], + }, +}; +/** + * Error thrown when there is an error in the client code running on the browser. + */ +class ClientAuthError extends AuthError { + constructor(errorCode, additionalMessage) { + super(errorCode, additionalMessage + ? `${ClientAuthErrorMessages[errorCode]}: ${additionalMessage}` + : ClientAuthErrorMessages[errorCode]); + this.name = "ClientAuthError"; + Object.setPrototypeOf(this, ClientAuthError.prototype); + } +} +function createClientAuthError(errorCode, additionalMessage) { + return new ClientAuthError(errorCode, additionalMessage); +} + +export { ClientAuthError, ClientAuthErrorMessage, ClientAuthErrorMessages, createClientAuthError }; +//# sourceMappingURL=ClientAuthError.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/error/ClientAuthErrorCodes.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/error/ClientAuthErrorCodes.mjs new file mode 100644 index 00000000..745c8d20 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/error/ClientAuthErrorCodes.mjs @@ -0,0 +1,53 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +const clientInfoDecodingError = "client_info_decoding_error"; +const clientInfoEmptyError = "client_info_empty_error"; +const tokenParsingError = "token_parsing_error"; +const nullOrEmptyToken = "null_or_empty_token"; +const endpointResolutionError = "endpoints_resolution_error"; +const networkError = "network_error"; +const openIdConfigError = "openid_config_error"; +const hashNotDeserialized = "hash_not_deserialized"; +const invalidState = "invalid_state"; +const stateMismatch = "state_mismatch"; +const stateNotFound = "state_not_found"; +const nonceMismatch = "nonce_mismatch"; +const authTimeNotFound = "auth_time_not_found"; +const maxAgeTranspired = "max_age_transpired"; +const multipleMatchingTokens = "multiple_matching_tokens"; +const multipleMatchingAccounts = "multiple_matching_accounts"; +const multipleMatchingAppMetadata = "multiple_matching_appMetadata"; +const requestCannotBeMade = "request_cannot_be_made"; +const cannotRemoveEmptyScope = "cannot_remove_empty_scope"; +const cannotAppendScopeSet = "cannot_append_scopeset"; +const emptyInputScopeSet = "empty_input_scopeset"; +const deviceCodePollingCancelled = "device_code_polling_cancelled"; +const deviceCodeExpired = "device_code_expired"; +const deviceCodeUnknownError = "device_code_unknown_error"; +const noAccountInSilentRequest = "no_account_in_silent_request"; +const invalidCacheRecord = "invalid_cache_record"; +const invalidCacheEnvironment = "invalid_cache_environment"; +const noAccountFound = "no_account_found"; +const noCryptoObject = "no_crypto_object"; +const unexpectedCredentialType = "unexpected_credential_type"; +const invalidAssertion = "invalid_assertion"; +const invalidClientCredential = "invalid_client_credential"; +const tokenRefreshRequired = "token_refresh_required"; +const userTimeoutReached = "user_timeout_reached"; +const tokenClaimsCnfRequiredForSignedJwt = "token_claims_cnf_required_for_signedjwt"; +const authorizationCodeMissingFromServerResponse = "authorization_code_missing_from_server_response"; +const bindingKeyNotRemoved = "binding_key_not_removed"; +const endSessionEndpointNotSupported = "end_session_endpoint_not_supported"; +const keyIdMissing = "key_id_missing"; +const noNetworkConnectivity = "no_network_connectivity"; +const userCanceled = "user_canceled"; +const missingTenantIdError = "missing_tenant_id_error"; +const methodNotImplemented = "method_not_implemented"; +const nestedAppAuthBridgeDisabled = "nested_app_auth_bridge_disabled"; + +export { authTimeNotFound, authorizationCodeMissingFromServerResponse, bindingKeyNotRemoved, cannotAppendScopeSet, cannotRemoveEmptyScope, clientInfoDecodingError, clientInfoEmptyError, deviceCodeExpired, deviceCodePollingCancelled, deviceCodeUnknownError, emptyInputScopeSet, endSessionEndpointNotSupported, endpointResolutionError, hashNotDeserialized, invalidAssertion, invalidCacheEnvironment, invalidCacheRecord, invalidClientCredential, invalidState, keyIdMissing, maxAgeTranspired, methodNotImplemented, missingTenantIdError, multipleMatchingAccounts, multipleMatchingAppMetadata, multipleMatchingTokens, nestedAppAuthBridgeDisabled, networkError, noAccountFound, noAccountInSilentRequest, noCryptoObject, noNetworkConnectivity, nonceMismatch, nullOrEmptyToken, openIdConfigError, requestCannotBeMade, stateMismatch, stateNotFound, tokenClaimsCnfRequiredForSignedJwt, tokenParsingError, tokenRefreshRequired, unexpectedCredentialType, userCanceled, userTimeoutReached }; +//# sourceMappingURL=ClientAuthErrorCodes.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/error/ClientConfigurationError.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/error/ClientConfigurationError.mjs new file mode 100644 index 00000000..960d4d8c --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/error/ClientConfigurationError.mjs @@ -0,0 +1,150 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +import { AuthError } from './AuthError.mjs'; +import { invalidRequestMethodForEAR, invalidAuthorizePostBodyParameters, authorityMismatch, cannotAllowPlatformBroker, cannotSetOIDCOptions, invalidAuthenticationHeader, missingNonceAuthenticationHeader, missingSshKid, missingSshJwk, untrustedAuthority, invalidAuthorityMetadata, invalidCloudDiscoveryMetadata, pkceParamsMissing, invalidCodeChallengeMethod, logoutRequestEmpty, tokenRequestEmpty, invalidClaims, emptyInputScopesError, urlEmptyError, urlParseError, authorityUriInsecure, claimsRequestParsingError, redirectUriEmpty } from './ClientConfigurationErrorCodes.mjs'; +import * as ClientConfigurationErrorCodes from './ClientConfigurationErrorCodes.mjs'; +export { ClientConfigurationErrorCodes }; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +const ClientConfigurationErrorMessages = { + [redirectUriEmpty]: "A redirect URI is required for all calls, and none has been set.", + [claimsRequestParsingError]: "Could not parse the given claims request object.", + [authorityUriInsecure]: "Authority URIs must use https. Please see here for valid authority configuration options: https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-js-initializing-client-applications#configuration-options", + [urlParseError]: "URL could not be parsed into appropriate segments.", + [urlEmptyError]: "URL was empty or null.", + [emptyInputScopesError]: "Scopes cannot be passed as null, undefined or empty array because they are required to obtain an access token.", + [invalidClaims]: "Given claims parameter must be a stringified JSON object.", + [tokenRequestEmpty]: "Token request was empty and not found in cache.", + [logoutRequestEmpty]: "The logout request was null or undefined.", + [invalidCodeChallengeMethod]: 'code_challenge_method passed is invalid. Valid values are "plain" and "S256".', + [pkceParamsMissing]: "Both params: code_challenge and code_challenge_method are to be passed if to be sent in the request", + [invalidCloudDiscoveryMetadata]: "Invalid cloudDiscoveryMetadata provided. Must be a stringified JSON object containing tenant_discovery_endpoint and metadata fields", + [invalidAuthorityMetadata]: "Invalid authorityMetadata provided. Must by a stringified JSON object containing authorization_endpoint, token_endpoint, issuer fields.", + [untrustedAuthority]: "The provided authority is not a trusted authority. Please include this authority in the knownAuthorities config parameter.", + [missingSshJwk]: "Missing sshJwk in SSH certificate request. A stringified JSON Web Key is required when using the SSH authentication scheme.", + [missingSshKid]: "Missing sshKid in SSH certificate request. A string that uniquely identifies the public SSH key is required when using the SSH authentication scheme.", + [missingNonceAuthenticationHeader]: "Unable to find an authentication header containing server nonce. Either the Authentication-Info or WWW-Authenticate headers must be present in order to obtain a server nonce.", + [invalidAuthenticationHeader]: "Invalid authentication header provided", + [cannotSetOIDCOptions]: "Cannot set OIDCOptions parameter. Please change the protocol mode to OIDC or use a non-Microsoft authority.", + [cannotAllowPlatformBroker]: "Cannot set allowPlatformBroker parameter to true when not in AAD protocol mode.", + [authorityMismatch]: "Authority mismatch error. Authority provided in login request or PublicClientApplication config does not match the environment of the provided account. Please use a matching account or make an interactive request to login to this authority.", + [invalidAuthorizePostBodyParameters]: "Invalid authorize post body parameters provided. If you are using authorizePostBodyParameters, the request method must be POST. Please check the request method and parameters.", + [invalidRequestMethodForEAR]: "Invalid request method for EAR protocol mode. The request method cannot be GET when using EAR protocol mode. Please change the request method to POST.", +}; +/** + * ClientConfigurationErrorMessage class containing string constants used by error codes and messages. + * @deprecated Use ClientConfigurationErrorCodes instead + */ +const ClientConfigurationErrorMessage = { + redirectUriNotSet: { + code: redirectUriEmpty, + desc: ClientConfigurationErrorMessages[redirectUriEmpty], + }, + claimsRequestParsingError: { + code: claimsRequestParsingError, + desc: ClientConfigurationErrorMessages[claimsRequestParsingError], + }, + authorityUriInsecure: { + code: authorityUriInsecure, + desc: ClientConfigurationErrorMessages[authorityUriInsecure], + }, + urlParseError: { + code: urlParseError, + desc: ClientConfigurationErrorMessages[urlParseError], + }, + urlEmptyError: { + code: urlEmptyError, + desc: ClientConfigurationErrorMessages[urlEmptyError], + }, + emptyScopesError: { + code: emptyInputScopesError, + desc: ClientConfigurationErrorMessages[emptyInputScopesError], + }, + invalidClaimsRequest: { + code: invalidClaims, + desc: ClientConfigurationErrorMessages[invalidClaims], + }, + tokenRequestEmptyError: { + code: tokenRequestEmpty, + desc: ClientConfigurationErrorMessages[tokenRequestEmpty], + }, + logoutRequestEmptyError: { + code: logoutRequestEmpty, + desc: ClientConfigurationErrorMessages[logoutRequestEmpty], + }, + invalidCodeChallengeMethod: { + code: invalidCodeChallengeMethod, + desc: ClientConfigurationErrorMessages[invalidCodeChallengeMethod], + }, + invalidCodeChallengeParams: { + code: pkceParamsMissing, + desc: ClientConfigurationErrorMessages[pkceParamsMissing], + }, + invalidCloudDiscoveryMetadata: { + code: invalidCloudDiscoveryMetadata, + desc: ClientConfigurationErrorMessages[invalidCloudDiscoveryMetadata], + }, + invalidAuthorityMetadata: { + code: invalidAuthorityMetadata, + desc: ClientConfigurationErrorMessages[invalidAuthorityMetadata], + }, + untrustedAuthority: { + code: untrustedAuthority, + desc: ClientConfigurationErrorMessages[untrustedAuthority], + }, + missingSshJwk: { + code: missingSshJwk, + desc: ClientConfigurationErrorMessages[missingSshJwk], + }, + missingSshKid: { + code: missingSshKid, + desc: ClientConfigurationErrorMessages[missingSshKid], + }, + missingNonceAuthenticationHeader: { + code: missingNonceAuthenticationHeader, + desc: ClientConfigurationErrorMessages[missingNonceAuthenticationHeader], + }, + invalidAuthenticationHeader: { + code: invalidAuthenticationHeader, + desc: ClientConfigurationErrorMessages[invalidAuthenticationHeader], + }, + cannotSetOIDCOptions: { + code: cannotSetOIDCOptions, + desc: ClientConfigurationErrorMessages[cannotSetOIDCOptions], + }, + cannotAllowPlatformBroker: { + code: cannotAllowPlatformBroker, + desc: ClientConfigurationErrorMessages[cannotAllowPlatformBroker], + }, + authorityMismatch: { + code: authorityMismatch, + desc: ClientConfigurationErrorMessages[authorityMismatch], + }, + invalidAuthorizePostBodyParameters: { + code: invalidAuthorizePostBodyParameters, + desc: ClientConfigurationErrorMessages[invalidAuthorizePostBodyParameters], + }, + invalidRequestMethodForEAR: { + code: invalidRequestMethodForEAR, + desc: ClientConfigurationErrorMessages[invalidRequestMethodForEAR], + }, +}; +/** + * Error thrown when there is an error in configuration of the MSAL.js library. + */ +class ClientConfigurationError extends AuthError { + constructor(errorCode) { + super(errorCode, ClientConfigurationErrorMessages[errorCode]); + this.name = "ClientConfigurationError"; + Object.setPrototypeOf(this, ClientConfigurationError.prototype); + } +} +function createClientConfigurationError(errorCode) { + return new ClientConfigurationError(errorCode); +} + +export { ClientConfigurationError, ClientConfigurationErrorMessage, ClientConfigurationErrorMessages, createClientConfigurationError }; +//# sourceMappingURL=ClientConfigurationError.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/error/ClientConfigurationErrorCodes.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/error/ClientConfigurationErrorCodes.mjs new file mode 100644 index 00000000..8368520b --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/error/ClientConfigurationErrorCodes.mjs @@ -0,0 +1,32 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +const redirectUriEmpty = "redirect_uri_empty"; +const claimsRequestParsingError = "claims_request_parsing_error"; +const authorityUriInsecure = "authority_uri_insecure"; +const urlParseError = "url_parse_error"; +const urlEmptyError = "empty_url_error"; +const emptyInputScopesError = "empty_input_scopes_error"; +const invalidClaims = "invalid_claims"; +const tokenRequestEmpty = "token_request_empty"; +const logoutRequestEmpty = "logout_request_empty"; +const invalidCodeChallengeMethod = "invalid_code_challenge_method"; +const pkceParamsMissing = "pkce_params_missing"; +const invalidCloudDiscoveryMetadata = "invalid_cloud_discovery_metadata"; +const invalidAuthorityMetadata = "invalid_authority_metadata"; +const untrustedAuthority = "untrusted_authority"; +const missingSshJwk = "missing_ssh_jwk"; +const missingSshKid = "missing_ssh_kid"; +const missingNonceAuthenticationHeader = "missing_nonce_authentication_header"; +const invalidAuthenticationHeader = "invalid_authentication_header"; +const cannotSetOIDCOptions = "cannot_set_OIDCOptions"; +const cannotAllowPlatformBroker = "cannot_allow_platform_broker"; +const authorityMismatch = "authority_mismatch"; +const invalidRequestMethodForEAR = "invalid_request_method_for_EAR"; +const invalidAuthorizePostBodyParameters = "invalid_authorize_post_body_parameters"; + +export { authorityMismatch, authorityUriInsecure, cannotAllowPlatformBroker, cannotSetOIDCOptions, claimsRequestParsingError, emptyInputScopesError, invalidAuthenticationHeader, invalidAuthorityMetadata, invalidAuthorizePostBodyParameters, invalidClaims, invalidCloudDiscoveryMetadata, invalidCodeChallengeMethod, invalidRequestMethodForEAR, logoutRequestEmpty, missingNonceAuthenticationHeader, missingSshJwk, missingSshKid, pkceParamsMissing, redirectUriEmpty, tokenRequestEmpty, untrustedAuthority, urlEmptyError, urlParseError }; +//# sourceMappingURL=ClientConfigurationErrorCodes.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/error/InteractionRequiredAuthError.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/error/InteractionRequiredAuthError.mjs new file mode 100644 index 00000000..1b3d60a7 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/error/InteractionRequiredAuthError.mjs @@ -0,0 +1,98 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +import { Constants } from '../utils/Constants.mjs'; +import { AuthError } from './AuthError.mjs'; +import { badToken, nativeAccountUnavailable, noTokensFound, uxNotAllowed, refreshTokenExpired, interactionRequired, consentRequired, loginRequired } from './InteractionRequiredAuthErrorCodes.mjs'; +import * as InteractionRequiredAuthErrorCodes from './InteractionRequiredAuthErrorCodes.mjs'; +export { InteractionRequiredAuthErrorCodes }; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * InteractionRequiredServerErrorMessage contains string constants used by error codes and messages returned by the server indicating interaction is required + */ +const InteractionRequiredServerErrorMessage = [ + interactionRequired, + consentRequired, + loginRequired, + badToken, + uxNotAllowed, +]; +const InteractionRequiredAuthSubErrorMessage = [ + "message_only", + "additional_action", + "basic_action", + "user_password_expired", + "consent_required", + "bad_token", +]; +const InteractionRequiredAuthErrorMessages = { + [noTokensFound]: "No refresh token found in the cache. Please sign-in.", + [nativeAccountUnavailable]: "The requested account is not available in the native broker. It may have been deleted or logged out. Please sign-in again using an interactive API.", + [refreshTokenExpired]: "Refresh token has expired.", + [badToken]: "Identity provider returned bad_token due to an expired or invalid refresh token. Please invoke an interactive API to resolve.", + [uxNotAllowed]: "`canShowUI` flag in Edge was set to false. User interaction required on web page. Please invoke an interactive API to resolve.", +}; +/** + * Interaction required errors defined by the SDK + * @deprecated Use InteractionRequiredAuthErrorCodes instead + */ +const InteractionRequiredAuthErrorMessage = { + noTokensFoundError: { + code: noTokensFound, + desc: InteractionRequiredAuthErrorMessages[noTokensFound], + }, + native_account_unavailable: { + code: nativeAccountUnavailable, + desc: InteractionRequiredAuthErrorMessages[nativeAccountUnavailable], + }, + bad_token: { + code: badToken, + desc: InteractionRequiredAuthErrorMessages[badToken], + }, +}; +/** + * Error thrown when user interaction is required. + */ +class InteractionRequiredAuthError extends AuthError { + constructor(errorCode, errorMessage, subError, timestamp, traceId, correlationId, claims, errorNo) { + super(errorCode, errorMessage, subError); + Object.setPrototypeOf(this, InteractionRequiredAuthError.prototype); + this.timestamp = timestamp || Constants.EMPTY_STRING; + this.traceId = traceId || Constants.EMPTY_STRING; + this.correlationId = correlationId || Constants.EMPTY_STRING; + this.claims = claims || Constants.EMPTY_STRING; + this.name = "InteractionRequiredAuthError"; + this.errorNo = errorNo; + } +} +/** + * Helper function used to determine if an error thrown by the server requires interaction to resolve + * @param errorCode + * @param errorString + * @param subError + */ +function isInteractionRequiredError(errorCode, errorString, subError) { + const isInteractionRequiredErrorCode = !!errorCode && + InteractionRequiredServerErrorMessage.indexOf(errorCode) > -1; + const isInteractionRequiredSubError = !!subError && + InteractionRequiredAuthSubErrorMessage.indexOf(subError) > -1; + const isInteractionRequiredErrorDesc = !!errorString && + InteractionRequiredServerErrorMessage.some((irErrorCode) => { + return errorString.indexOf(irErrorCode) > -1; + }); + return (isInteractionRequiredErrorCode || + isInteractionRequiredErrorDesc || + isInteractionRequiredSubError); +} +/** + * Creates an InteractionRequiredAuthError + */ +function createInteractionRequiredAuthError(errorCode) { + return new InteractionRequiredAuthError(errorCode, InteractionRequiredAuthErrorMessages[errorCode]); +} + +export { InteractionRequiredAuthError, InteractionRequiredAuthErrorMessage, InteractionRequiredAuthSubErrorMessage, InteractionRequiredServerErrorMessage, createInteractionRequiredAuthError, isInteractionRequiredError }; +//# sourceMappingURL=InteractionRequiredAuthError.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/error/InteractionRequiredAuthErrorCodes.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/error/InteractionRequiredAuthErrorCodes.mjs new file mode 100644 index 00000000..c15b837f --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/error/InteractionRequiredAuthErrorCodes.mjs @@ -0,0 +1,19 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +// Codes defined by MSAL +const noTokensFound = "no_tokens_found"; +const nativeAccountUnavailable = "native_account_unavailable"; +const refreshTokenExpired = "refresh_token_expired"; +const uxNotAllowed = "ux_not_allowed"; +// Codes potentially returned by server +const interactionRequired = "interaction_required"; +const consentRequired = "consent_required"; +const loginRequired = "login_required"; +const badToken = "bad_token"; + +export { badToken, consentRequired, interactionRequired, loginRequired, nativeAccountUnavailable, noTokensFound, refreshTokenExpired, uxNotAllowed }; +//# sourceMappingURL=InteractionRequiredAuthErrorCodes.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/error/NetworkError.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/error/NetworkError.mjs new file mode 100644 index 00000000..e5109ae3 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/error/NetworkError.mjs @@ -0,0 +1,35 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +import { AuthError } from './AuthError.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * Represents network related errors + */ +class NetworkError extends AuthError { + constructor(error, httpStatus, responseHeaders) { + super(error.errorCode, error.errorMessage, error.subError); + Object.setPrototypeOf(this, NetworkError.prototype); + this.name = "NetworkError"; + this.error = error; + this.httpStatus = httpStatus; + this.responseHeaders = responseHeaders; + } +} +/** + * Creates NetworkError object for a failed network request + * @param error - Error to be thrown back to the caller + * @param httpStatus - Status code of the network request + * @param responseHeaders - Response headers of the network request, when available + * @returns NetworkError object + */ +function createNetworkError(error, httpStatus, responseHeaders, additionalError) { + error.errorMessage = `${error.errorMessage}, additionalErrorInfo: error.name:${additionalError?.name}, error.message:${additionalError?.message}`; + return new NetworkError(error, httpStatus, responseHeaders); +} + +export { NetworkError, createNetworkError }; +//# sourceMappingURL=NetworkError.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/error/ServerError.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/error/ServerError.mjs new file mode 100644 index 00000000..24b83f94 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/error/ServerError.mjs @@ -0,0 +1,23 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +import { AuthError } from './AuthError.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * Error thrown when there is an error with the server code, for example, unavailability. + */ +class ServerError extends AuthError { + constructor(errorCode, errorMessage, subError, errorNo, status) { + super(errorCode, errorMessage, subError); + this.name = "ServerError"; + this.errorNo = errorNo; + this.status = status; + Object.setPrototypeOf(this, ServerError.prototype); + } +} + +export { ServerError }; +//# sourceMappingURL=ServerError.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/index-node.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/index-node.mjs new file mode 100644 index 00000000..48883931 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/index-node.mjs @@ -0,0 +1,70 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +export { AuthorizationCodeClient } from './client/AuthorizationCodeClient.mjs'; +export { RefreshTokenClient } from './client/RefreshTokenClient.mjs'; +export { SilentFlowClient } from './client/SilentFlowClient.mjs'; +export { BaseClient } from './client/BaseClient.mjs'; +export { DEFAULT_SYSTEM_OPTIONS } from './config/ClientConfiguration.mjs'; +export { buildTenantProfile, tenantIdMatchesHomeTenant, updateAccountTenantProfileData } from './account/AccountInfo.mjs'; +export { getTenantIdFromIdTokenClaims } from './account/TokenClaims.mjs'; +export { CcsCredentialType } from './account/CcsCredential.mjs'; +export { buildClientInfo, buildClientInfoFromHomeAccountId } from './account/ClientInfo.mjs'; +export { Authority, buildStaticAuthorityOptions, formatAuthorityUri } from './authority/Authority.mjs'; +export { AzureCloudInstance } from './authority/AuthorityOptions.mjs'; +export { AuthorityType } from './authority/AuthorityType.mjs'; +export { ProtocolMode } from './authority/ProtocolMode.mjs'; +export { CacheManager, DefaultStorageClass } from './cache/CacheManager.mjs'; +export { AccountEntity } from './cache/entities/AccountEntity.mjs'; +export { StubbedNetworkModule } from './network/INetworkModule.mjs'; +export { ThrottlingUtils } from './network/ThrottlingUtils.mjs'; +export { getRequestThumbprint } from './network/RequestThumbprint.mjs'; +export { UrlString } from './url/UrlString.mjs'; +export { DEFAULT_CRYPTO_IMPLEMENTATION } from './crypto/ICrypto.mjs'; +import * as Authorize from './protocol/Authorize.mjs'; +export { Authorize as AuthorizeProtocol }; +import * as RequestParameterBuilder from './request/RequestParameterBuilder.mjs'; +export { RequestParameterBuilder }; +export { ResponseHandler, buildAccountToCache } from './response/ResponseHandler.mjs'; +export { ScopeSet } from './request/ScopeSet.mjs'; +export { AuthenticationHeaderParser } from './request/AuthenticationHeaderParser.mjs'; +export { LogLevel, Logger } from './logger/Logger.mjs'; +export { InteractionRequiredAuthError, InteractionRequiredAuthErrorMessage, createInteractionRequiredAuthError } from './error/InteractionRequiredAuthError.mjs'; +import * as InteractionRequiredAuthErrorCodes from './error/InteractionRequiredAuthErrorCodes.mjs'; +export { InteractionRequiredAuthErrorCodes }; +export { AuthError, AuthErrorMessage, createAuthError } from './error/AuthError.mjs'; +import * as AuthErrorCodes from './error/AuthErrorCodes.mjs'; +export { AuthErrorCodes }; +export { ServerError } from './error/ServerError.mjs'; +export { NetworkError, createNetworkError } from './error/NetworkError.mjs'; +export { CacheError, createCacheError } from './error/CacheError.mjs'; +import * as CacheErrorCodes from './error/CacheErrorCodes.mjs'; +export { CacheErrorCodes }; +export { ClientAuthError, ClientAuthErrorMessage, createClientAuthError } from './error/ClientAuthError.mjs'; +import * as ClientAuthErrorCodes from './error/ClientAuthErrorCodes.mjs'; +export { ClientAuthErrorCodes }; +export { ClientConfigurationError, ClientConfigurationErrorMessage, createClientConfigurationError } from './error/ClientConfigurationError.mjs'; +import * as ClientConfigurationErrorCodes from './error/ClientConfigurationErrorCodes.mjs'; +export { ClientConfigurationErrorCodes }; +export { AADAuthorityConstants, AuthenticationScheme, CacheAccountType, CacheOutcome, CacheType, ClaimsRequestKeys, CodeChallengeMethodValues, Constants, CredentialType, DEFAULT_TOKEN_RENEWAL_OFFSET_SEC, EncodingTypes, Errors, GrantType, HeaderNames, HttpMethod, HttpStatus, JsonWebTokenTypes, OAuthResponseType, OIDC_DEFAULT_SCOPES, ONE_DAY_IN_MS, PasswordGrantConstants, PersistentCacheKeys, PromptValue, ResponseMode, ServerResponseType, THE_FAMILY_ID, ThrottlingConstants } from './utils/Constants.mjs'; +export { StringUtils } from './utils/StringUtils.mjs'; +export { ProtocolUtils } from './utils/ProtocolUtils.mjs'; +export { ServerTelemetryManager } from './telemetry/server/ServerTelemetryManager.mjs'; +export { version } from './packageMetadata.mjs'; +export { invoke, invokeAsync } from './utils/FunctionWrappers.mjs'; +import * as AuthToken from './account/AuthToken.mjs'; +export { AuthToken }; +import * as AuthorityFactory from './authority/AuthorityFactory.mjs'; +export { AuthorityFactory }; +import * as CacheHelpers from './cache/utils/CacheHelpers.mjs'; +export { CacheHelpers }; +import * as TimeUtils from './utils/TimeUtils.mjs'; +export { TimeUtils }; +import * as UrlUtils from './utils/UrlUtils.mjs'; +export { UrlUtils }; +import * as AADServerParamKeys from './constants/AADServerParamKeys.mjs'; +export { AADServerParamKeys }; +export { TokenCacheContext } from './cache/persistence/TokenCacheContext.mjs'; +import * as ClientAssertionUtils from './utils/ClientAssertionUtils.mjs'; +export { ClientAssertionUtils }; +export { getClientAssertion } from './utils/ClientAssertionUtils.mjs'; +//# sourceMappingURL=index-node.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/index.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/index.mjs new file mode 100644 index 00000000..df10aa3e --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/index.mjs @@ -0,0 +1,75 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +export { AuthorizationCodeClient } from './client/AuthorizationCodeClient.mjs'; +export { RefreshTokenClient } from './client/RefreshTokenClient.mjs'; +export { SilentFlowClient } from './client/SilentFlowClient.mjs'; +export { BaseClient } from './client/BaseClient.mjs'; +export { DEFAULT_SYSTEM_OPTIONS } from './config/ClientConfiguration.mjs'; +export { buildTenantProfile, tenantIdMatchesHomeTenant, updateAccountTenantProfileData } from './account/AccountInfo.mjs'; +export { getTenantIdFromIdTokenClaims } from './account/TokenClaims.mjs'; +export { CcsCredentialType } from './account/CcsCredential.mjs'; +export { buildClientInfo, buildClientInfoFromHomeAccountId } from './account/ClientInfo.mjs'; +export { Authority, buildStaticAuthorityOptions, formatAuthorityUri } from './authority/Authority.mjs'; +export { AzureCloudInstance } from './authority/AuthorityOptions.mjs'; +export { AuthorityType } from './authority/AuthorityType.mjs'; +export { ProtocolMode } from './authority/ProtocolMode.mjs'; +export { CacheManager, DefaultStorageClass } from './cache/CacheManager.mjs'; +export { AccountEntity } from './cache/entities/AccountEntity.mjs'; +export { StubbedNetworkModule } from './network/INetworkModule.mjs'; +export { ThrottlingUtils } from './network/ThrottlingUtils.mjs'; +export { getRequestThumbprint } from './network/RequestThumbprint.mjs'; +export { UrlString } from './url/UrlString.mjs'; +export { DEFAULT_CRYPTO_IMPLEMENTATION } from './crypto/ICrypto.mjs'; +import * as Authorize from './protocol/Authorize.mjs'; +export { Authorize as AuthorizeProtocol }; +import * as RequestParameterBuilder from './request/RequestParameterBuilder.mjs'; +export { RequestParameterBuilder }; +export { ResponseHandler, buildAccountToCache } from './response/ResponseHandler.mjs'; +export { ScopeSet } from './request/ScopeSet.mjs'; +export { AuthenticationHeaderParser } from './request/AuthenticationHeaderParser.mjs'; +export { LogLevel, Logger } from './logger/Logger.mjs'; +export { InteractionRequiredAuthError, InteractionRequiredAuthErrorMessage, createInteractionRequiredAuthError } from './error/InteractionRequiredAuthError.mjs'; +import * as InteractionRequiredAuthErrorCodes from './error/InteractionRequiredAuthErrorCodes.mjs'; +export { InteractionRequiredAuthErrorCodes }; +export { AuthError, AuthErrorMessage, createAuthError } from './error/AuthError.mjs'; +import * as AuthErrorCodes from './error/AuthErrorCodes.mjs'; +export { AuthErrorCodes }; +export { ServerError } from './error/ServerError.mjs'; +export { NetworkError, createNetworkError } from './error/NetworkError.mjs'; +export { CacheError, createCacheError } from './error/CacheError.mjs'; +import * as CacheErrorCodes from './error/CacheErrorCodes.mjs'; +export { CacheErrorCodes }; +export { ClientAuthError, ClientAuthErrorMessage, createClientAuthError } from './error/ClientAuthError.mjs'; +import * as ClientAuthErrorCodes from './error/ClientAuthErrorCodes.mjs'; +export { ClientAuthErrorCodes }; +export { ClientConfigurationError, ClientConfigurationErrorMessage, createClientConfigurationError } from './error/ClientConfigurationError.mjs'; +import * as ClientConfigurationErrorCodes from './error/ClientConfigurationErrorCodes.mjs'; +export { ClientConfigurationErrorCodes }; +export { AADAuthorityConstants, AuthenticationScheme, CacheAccountType, CacheOutcome, CacheType, ClaimsRequestKeys, CodeChallengeMethodValues, Constants, CredentialType, DEFAULT_TOKEN_RENEWAL_OFFSET_SEC, EncodingTypes, Errors, GrantType, HeaderNames, HttpMethod, HttpStatus, JsonWebTokenTypes, OAuthResponseType, OIDC_DEFAULT_SCOPES, ONE_DAY_IN_MS, PasswordGrantConstants, PersistentCacheKeys, PromptValue, ResponseMode, ServerResponseType, THE_FAMILY_ID, ThrottlingConstants } from './utils/Constants.mjs'; +export { StringUtils } from './utils/StringUtils.mjs'; +export { ProtocolUtils } from './utils/ProtocolUtils.mjs'; +export { ServerTelemetryManager } from './telemetry/server/ServerTelemetryManager.mjs'; +export { version } from './packageMetadata.mjs'; +export { invoke, invokeAsync } from './utils/FunctionWrappers.mjs'; +import * as AuthToken from './account/AuthToken.mjs'; +export { AuthToken }; +import * as AuthorityFactory from './authority/AuthorityFactory.mjs'; +export { AuthorityFactory }; +import * as CacheHelpers from './cache/utils/CacheHelpers.mjs'; +export { CacheHelpers }; +import * as TimeUtils from './utils/TimeUtils.mjs'; +export { TimeUtils }; +import * as UrlUtils from './utils/UrlUtils.mjs'; +export { UrlUtils }; +import * as AADServerParamKeys from './constants/AADServerParamKeys.mjs'; +export { AADServerParamKeys }; +export { JoseHeader } from './crypto/JoseHeader.mjs'; +export { IntFields, PerformanceEventStatus, PerformanceEvents } from './telemetry/performance/PerformanceEvent.mjs'; +export { PerformanceClient } from './telemetry/performance/PerformanceClient.mjs'; +export { StubPerformanceClient } from './telemetry/performance/StubPerformanceClient.mjs'; +export { PopTokenGenerator } from './crypto/PopTokenGenerator.mjs'; +export { TokenCacheContext } from './cache/persistence/TokenCacheContext.mjs'; +import * as ClientAssertionUtils from './utils/ClientAssertionUtils.mjs'; +export { ClientAssertionUtils }; +export { getClientAssertion } from './utils/ClientAssertionUtils.mjs'; +//# sourceMappingURL=index.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/logger/Logger.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/logger/Logger.mjs new file mode 100644 index 00000000..8af83586 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/logger/Logger.mjs @@ -0,0 +1,195 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +import { Constants } from '../utils/Constants.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * Log message level. + */ +var LogLevel; +(function (LogLevel) { + LogLevel[LogLevel["Error"] = 0] = "Error"; + LogLevel[LogLevel["Warning"] = 1] = "Warning"; + LogLevel[LogLevel["Info"] = 2] = "Info"; + LogLevel[LogLevel["Verbose"] = 3] = "Verbose"; + LogLevel[LogLevel["Trace"] = 4] = "Trace"; +})(LogLevel || (LogLevel = {})); +/** + * Class which facilitates logging of messages to a specific place. + */ +class Logger { + constructor(loggerOptions, packageName, packageVersion) { + // Current log level, defaults to info. + this.level = LogLevel.Info; + const defaultLoggerCallback = () => { + return; + }; + const setLoggerOptions = loggerOptions || Logger.createDefaultLoggerOptions(); + this.localCallback = + setLoggerOptions.loggerCallback || defaultLoggerCallback; + this.piiLoggingEnabled = setLoggerOptions.piiLoggingEnabled || false; + this.level = + typeof setLoggerOptions.logLevel === "number" + ? setLoggerOptions.logLevel + : LogLevel.Info; + this.correlationId = + setLoggerOptions.correlationId || Constants.EMPTY_STRING; + this.packageName = packageName || Constants.EMPTY_STRING; + this.packageVersion = packageVersion || Constants.EMPTY_STRING; + } + static createDefaultLoggerOptions() { + return { + loggerCallback: () => { + // allow users to not set loggerCallback + }, + piiLoggingEnabled: false, + logLevel: LogLevel.Info, + }; + } + /** + * Create new Logger with existing configurations. + */ + clone(packageName, packageVersion, correlationId) { + return new Logger({ + loggerCallback: this.localCallback, + piiLoggingEnabled: this.piiLoggingEnabled, + logLevel: this.level, + correlationId: correlationId || this.correlationId, + }, packageName, packageVersion); + } + /** + * Log message with required options. + */ + logMessage(logMessage, options) { + if (options.logLevel > this.level || + (!this.piiLoggingEnabled && options.containsPii)) { + return; + } + const timestamp = new Date().toUTCString(); + // Add correlationId to logs if set, correlationId provided on log messages take precedence + const logHeader = `[${timestamp}] : [${options.correlationId || this.correlationId || ""}]`; + const log = `${logHeader} : ${this.packageName}@${this.packageVersion} : ${LogLevel[options.logLevel]} - ${logMessage}`; + // debug(`msal:${LogLevel[options.logLevel]}${options.containsPii ? "-Pii": Constants.EMPTY_STRING}${options.context ? `:${options.context}` : Constants.EMPTY_STRING}`)(logMessage); + this.executeCallback(options.logLevel, log, options.containsPii || false); + } + /** + * Execute callback with message. + */ + executeCallback(level, message, containsPii) { + if (this.localCallback) { + this.localCallback(level, message, containsPii); + } + } + /** + * Logs error messages. + */ + error(message, correlationId) { + this.logMessage(message, { + logLevel: LogLevel.Error, + containsPii: false, + correlationId: correlationId || Constants.EMPTY_STRING, + }); + } + /** + * Logs error messages with PII. + */ + errorPii(message, correlationId) { + this.logMessage(message, { + logLevel: LogLevel.Error, + containsPii: true, + correlationId: correlationId || Constants.EMPTY_STRING, + }); + } + /** + * Logs warning messages. + */ + warning(message, correlationId) { + this.logMessage(message, { + logLevel: LogLevel.Warning, + containsPii: false, + correlationId: correlationId || Constants.EMPTY_STRING, + }); + } + /** + * Logs warning messages with PII. + */ + warningPii(message, correlationId) { + this.logMessage(message, { + logLevel: LogLevel.Warning, + containsPii: true, + correlationId: correlationId || Constants.EMPTY_STRING, + }); + } + /** + * Logs info messages. + */ + info(message, correlationId) { + this.logMessage(message, { + logLevel: LogLevel.Info, + containsPii: false, + correlationId: correlationId || Constants.EMPTY_STRING, + }); + } + /** + * Logs info messages with PII. + */ + infoPii(message, correlationId) { + this.logMessage(message, { + logLevel: LogLevel.Info, + containsPii: true, + correlationId: correlationId || Constants.EMPTY_STRING, + }); + } + /** + * Logs verbose messages. + */ + verbose(message, correlationId) { + this.logMessage(message, { + logLevel: LogLevel.Verbose, + containsPii: false, + correlationId: correlationId || Constants.EMPTY_STRING, + }); + } + /** + * Logs verbose messages with PII. + */ + verbosePii(message, correlationId) { + this.logMessage(message, { + logLevel: LogLevel.Verbose, + containsPii: true, + correlationId: correlationId || Constants.EMPTY_STRING, + }); + } + /** + * Logs trace messages. + */ + trace(message, correlationId) { + this.logMessage(message, { + logLevel: LogLevel.Trace, + containsPii: false, + correlationId: correlationId || Constants.EMPTY_STRING, + }); + } + /** + * Logs trace messages with PII. + */ + tracePii(message, correlationId) { + this.logMessage(message, { + logLevel: LogLevel.Trace, + containsPii: true, + correlationId: correlationId || Constants.EMPTY_STRING, + }); + } + /** + * Returns whether PII Logging is enabled or not. + */ + isPiiLoggingEnabled() { + return this.piiLoggingEnabled || false; + } +} + +export { LogLevel, Logger }; +//# sourceMappingURL=Logger.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/network/RequestThumbprint.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/network/RequestThumbprint.mjs new file mode 100644 index 00000000..08ed9e64 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/network/RequestThumbprint.mjs @@ -0,0 +1,24 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +function getRequestThumbprint(clientId, request, homeAccountId) { + return { + clientId: clientId, + authority: request.authority, + scopes: request.scopes, + homeAccountIdentifier: homeAccountId, + claims: request.claims, + authenticationScheme: request.authenticationScheme, + resourceRequestMethod: request.resourceRequestMethod, + resourceRequestUri: request.resourceRequestUri, + shrClaims: request.shrClaims, + sshKid: request.sshKid, + embeddedClientId: request.embeddedClientId || request.tokenBodyParameters?.clientId, + }; +} + +export { getRequestThumbprint }; +//# sourceMappingURL=RequestThumbprint.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/network/ThrottlingUtils.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/network/ThrottlingUtils.mjs new file mode 100644 index 00000000..24a2b62e --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/network/ThrottlingUtils.mjs @@ -0,0 +1,93 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +import { ThrottlingConstants, Constants, HeaderNames } from '../utils/Constants.mjs'; +import { ServerError } from '../error/ServerError.mjs'; +import { getRequestThumbprint } from './RequestThumbprint.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** @internal */ +class ThrottlingUtils { + /** + * Prepares a RequestThumbprint to be stored as a key. + * @param thumbprint + */ + static generateThrottlingStorageKey(thumbprint) { + return `${ThrottlingConstants.THROTTLING_PREFIX}.${JSON.stringify(thumbprint)}`; + } + /** + * Performs necessary throttling checks before a network request. + * @param cacheManager + * @param thumbprint + */ + static preProcess(cacheManager, thumbprint, correlationId) { + const key = ThrottlingUtils.generateThrottlingStorageKey(thumbprint); + const value = cacheManager.getThrottlingCache(key); + if (value) { + if (value.throttleTime < Date.now()) { + cacheManager.removeItem(key, correlationId); + return; + } + throw new ServerError(value.errorCodes?.join(" ") || Constants.EMPTY_STRING, value.errorMessage, value.subError); + } + } + /** + * Performs necessary throttling checks after a network request. + * @param cacheManager + * @param thumbprint + * @param response + */ + static postProcess(cacheManager, thumbprint, response, correlationId) { + if (ThrottlingUtils.checkResponseStatus(response) || + ThrottlingUtils.checkResponseForRetryAfter(response)) { + const thumbprintValue = { + throttleTime: ThrottlingUtils.calculateThrottleTime(parseInt(response.headers[HeaderNames.RETRY_AFTER])), + error: response.body.error, + errorCodes: response.body.error_codes, + errorMessage: response.body.error_description, + subError: response.body.suberror, + }; + cacheManager.setThrottlingCache(ThrottlingUtils.generateThrottlingStorageKey(thumbprint), thumbprintValue, correlationId); + } + } + /** + * Checks a NetworkResponse object's status codes against 429 or 5xx + * @param response + */ + static checkResponseStatus(response) { + return (response.status === 429 || + (response.status >= 500 && response.status < 600)); + } + /** + * Checks a NetworkResponse object's RetryAfter header + * @param response + */ + static checkResponseForRetryAfter(response) { + if (response.headers) { + return (response.headers.hasOwnProperty(HeaderNames.RETRY_AFTER) && + (response.status < 200 || response.status >= 300)); + } + return false; + } + /** + * Calculates the Unix-time value for a throttle to expire given throttleTime in seconds. + * @param throttleTime + */ + static calculateThrottleTime(throttleTime) { + const time = throttleTime <= 0 ? 0 : throttleTime; + const currentSeconds = Date.now() / 1000; + return Math.floor(Math.min(currentSeconds + + (time || ThrottlingConstants.DEFAULT_THROTTLE_TIME_SECONDS), currentSeconds + + ThrottlingConstants.DEFAULT_MAX_THROTTLE_TIME_SECONDS) * 1000); + } + static removeThrottle(cacheManager, clientId, request, homeAccountIdentifier) { + const thumbprint = getRequestThumbprint(clientId, request, homeAccountIdentifier); + const key = this.generateThrottlingStorageKey(thumbprint); + cacheManager.removeItem(key, request.correlationId); + } +} + +export { ThrottlingUtils }; +//# sourceMappingURL=ThrottlingUtils.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/packageMetadata.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/packageMetadata.mjs new file mode 100644 index 00000000..66c2d945 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/packageMetadata.mjs @@ -0,0 +1,8 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +/* eslint-disable header/header */ +const name = "@azure/msal-common"; +const version = "15.13.1"; + +export { name, version }; +//# sourceMappingURL=packageMetadata.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/protocol/Authorize.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/protocol/Authorize.mjs new file mode 100644 index 00000000..4b872c4e --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/protocol/Authorize.mjs @@ -0,0 +1,237 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +import { addClientId, addScopes, addRedirectUri, addCorrelationId, addResponseMode, addClientInfo, addPrompt, addDomainHint, addSid, addLoginHint, addCcsOid, addCcsUpn, addNonce, addState, addClaims, addBrokerParameters, addInstanceAware } from '../request/RequestParameterBuilder.mjs'; +import { INSTANCE_AWARE, CLIENT_ID } from '../constants/AADServerParamKeys.mjs'; +import { PromptValue } from '../utils/Constants.mjs'; +import { buildClientInfoFromHomeAccountId } from '../account/ClientInfo.mjs'; +import { mapToQueryString } from '../utils/UrlUtils.mjs'; +import { UrlString } from '../url/UrlString.mjs'; +import { createClientAuthError } from '../error/ClientAuthError.mjs'; +import { isInteractionRequiredError, InteractionRequiredAuthError } from '../error/InteractionRequiredAuthError.mjs'; +import { ServerError } from '../error/ServerError.mjs'; +import { authorizationCodeMissingFromServerResponse, stateNotFound, invalidState, stateMismatch } from '../error/ClientAuthErrorCodes.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * Returns map of parameters that are applicable to all calls to /authorize whether using PKCE or EAR + * @param config + * @param request + * @param logger + * @param performanceClient + * @returns + */ +function getStandardAuthorizeRequestParameters(authOptions, request, logger, performanceClient) { + // generate the correlationId if not set by the user and add + const correlationId = request.correlationId; + const parameters = new Map(); + addClientId(parameters, request.embeddedClientId || + request.extraQueryParameters?.[CLIENT_ID] || + authOptions.clientId); + const requestScopes = [ + ...(request.scopes || []), + ...(request.extraScopesToConsent || []), + ]; + addScopes(parameters, requestScopes, true, authOptions.authority.options.OIDCOptions?.defaultScopes); + addRedirectUri(parameters, request.redirectUri); + addCorrelationId(parameters, correlationId); + // add response_mode. If not passed in it defaults to query. + addResponseMode(parameters, request.responseMode); + // add client_info=1 + addClientInfo(parameters); + if (request.prompt) { + addPrompt(parameters, request.prompt); + performanceClient?.addFields({ prompt: request.prompt }, correlationId); + } + if (request.domainHint) { + addDomainHint(parameters, request.domainHint); + performanceClient?.addFields({ domainHintFromRequest: true }, correlationId); + } + // Add sid or loginHint with preference for login_hint claim (in request) -> sid -> loginHint (upn/email) -> username of AccountInfo object + if (request.prompt !== PromptValue.SELECT_ACCOUNT) { + // AAD will throw if prompt=select_account is passed with an account hint + if (request.sid && request.prompt === PromptValue.NONE) { + // SessionID is only used in silent calls + logger.verbose("createAuthCodeUrlQueryString: Prompt is none, adding sid from request"); + addSid(parameters, request.sid); + performanceClient?.addFields({ sidFromRequest: true }, correlationId); + } + else if (request.account) { + const accountSid = extractAccountSid(request.account); + let accountLoginHintClaim = extractLoginHint(request.account); + if (accountLoginHintClaim && request.domainHint) { + logger.warning(`AuthorizationCodeClient.createAuthCodeUrlQueryString: "domainHint" param is set, skipping opaque "login_hint" claim. Please consider not passing domainHint`); + accountLoginHintClaim = null; + } + // If login_hint claim is present, use it over sid/username + if (accountLoginHintClaim) { + logger.verbose("createAuthCodeUrlQueryString: login_hint claim present on account"); + addLoginHint(parameters, accountLoginHintClaim); + performanceClient?.addFields({ loginHintFromClaim: true }, correlationId); + try { + const clientInfo = buildClientInfoFromHomeAccountId(request.account.homeAccountId); + addCcsOid(parameters, clientInfo); + } + catch (e) { + logger.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header"); + } + } + else if (accountSid && request.prompt === PromptValue.NONE) { + /* + * If account and loginHint are provided, we will check account first for sid before adding loginHint + * SessionId is only used in silent calls + */ + logger.verbose("createAuthCodeUrlQueryString: Prompt is none, adding sid from account"); + addSid(parameters, accountSid); + performanceClient?.addFields({ sidFromClaim: true }, correlationId); + try { + const clientInfo = buildClientInfoFromHomeAccountId(request.account.homeAccountId); + addCcsOid(parameters, clientInfo); + } + catch (e) { + logger.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header"); + } + } + else if (request.loginHint) { + logger.verbose("createAuthCodeUrlQueryString: Adding login_hint from request"); + addLoginHint(parameters, request.loginHint); + addCcsUpn(parameters, request.loginHint); + performanceClient?.addFields({ loginHintFromRequest: true }, correlationId); + } + else if (request.account.username) { + // Fallback to account username if provided + logger.verbose("createAuthCodeUrlQueryString: Adding login_hint from account"); + addLoginHint(parameters, request.account.username); + performanceClient?.addFields({ loginHintFromUpn: true }, correlationId); + try { + const clientInfo = buildClientInfoFromHomeAccountId(request.account.homeAccountId); + addCcsOid(parameters, clientInfo); + } + catch (e) { + logger.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header"); + } + } + } + else if (request.loginHint) { + logger.verbose("createAuthCodeUrlQueryString: No account, adding login_hint from request"); + addLoginHint(parameters, request.loginHint); + addCcsUpn(parameters, request.loginHint); + performanceClient?.addFields({ loginHintFromRequest: true }, correlationId); + } + } + else { + logger.verbose("createAuthCodeUrlQueryString: Prompt is select_account, ignoring account hints"); + } + if (request.nonce) { + addNonce(parameters, request.nonce); + } + if (request.state) { + addState(parameters, request.state); + } + if (request.claims || + (authOptions.clientCapabilities && + authOptions.clientCapabilities.length > 0)) { + addClaims(parameters, request.claims, authOptions.clientCapabilities); + } + if (request.embeddedClientId) { + addBrokerParameters(parameters, authOptions.clientId, authOptions.redirectUri); + } + // If extraQueryParameters includes instance_aware its value will be added when extraQueryParameters are added + if (authOptions.instanceAware && + (!request.extraQueryParameters || + !Object.keys(request.extraQueryParameters).includes(INSTANCE_AWARE))) { + addInstanceAware(parameters); + } + return parameters; +} +/** + * Returns authorize endpoint with given request parameters in the query string + * @param authority + * @param requestParameters + * @returns + */ +function getAuthorizeUrl(authority, requestParameters, encodeParams, extraQueryParameters) { + const queryString = mapToQueryString(requestParameters, encodeParams, extraQueryParameters); + return UrlString.appendQueryString(authority.authorizationEndpoint, queryString); +} +/** + * Handles the hash fragment response from public client code request. Returns a code response used by + * the client to exchange for a token in acquireToken. + * @param serverParams + * @param cachedState + */ +function getAuthorizationCodePayload(serverParams, cachedState) { + // Get code response + validateAuthorizationResponse(serverParams, cachedState); + // throw when there is no auth code in the response + if (!serverParams.code) { + throw createClientAuthError(authorizationCodeMissingFromServerResponse); + } + return serverParams; +} +/** + * Function which validates server authorization code response. + * @param serverResponseHash + * @param requestState + */ +function validateAuthorizationResponse(serverResponse, requestState) { + if (!serverResponse.state || !requestState) { + throw serverResponse.state + ? createClientAuthError(stateNotFound, "Cached State") + : createClientAuthError(stateNotFound, "Server State"); + } + let decodedServerResponseState; + let decodedRequestState; + try { + decodedServerResponseState = decodeURIComponent(serverResponse.state); + } + catch (e) { + throw createClientAuthError(invalidState, serverResponse.state); + } + try { + decodedRequestState = decodeURIComponent(requestState); + } + catch (e) { + throw createClientAuthError(invalidState, serverResponse.state); + } + if (decodedServerResponseState !== decodedRequestState) { + throw createClientAuthError(stateMismatch); + } + // Check for error + if (serverResponse.error || + serverResponse.error_description || + serverResponse.suberror) { + const serverErrorNo = parseServerErrorNo(serverResponse); + if (isInteractionRequiredError(serverResponse.error, serverResponse.error_description, serverResponse.suberror)) { + throw new InteractionRequiredAuthError(serverResponse.error || "", serverResponse.error_description, serverResponse.suberror, serverResponse.timestamp || "", serverResponse.trace_id || "", serverResponse.correlation_id || "", serverResponse.claims || "", serverErrorNo); + } + throw new ServerError(serverResponse.error || "", serverResponse.error_description, serverResponse.suberror, serverErrorNo); + } +} +/** + * Get server error No from the error_uri + * @param serverResponse + * @returns + */ +function parseServerErrorNo(serverResponse) { + const errorCodePrefix = "code="; + const errorCodePrefixIndex = serverResponse.error_uri?.lastIndexOf(errorCodePrefix); + return errorCodePrefixIndex && errorCodePrefixIndex >= 0 + ? serverResponse.error_uri?.substring(errorCodePrefixIndex + errorCodePrefix.length) + : undefined; +} +/** + * Helper to get sid from account. Returns null if idTokenClaims are not present or sid is not present. + * @param account + */ +function extractAccountSid(account) { + return account.idTokenClaims?.sid || null; +} +function extractLoginHint(account) { + return account.loginHint || account.idTokenClaims?.login_hint || null; +} + +export { getAuthorizationCodePayload, getAuthorizeUrl, getStandardAuthorizeRequestParameters, validateAuthorizationResponse }; +//# sourceMappingURL=Authorize.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/request/RequestParameterBuilder.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/request/RequestParameterBuilder.mjs new file mode 100644 index 00000000..15485722 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/request/RequestParameterBuilder.mjs @@ -0,0 +1,423 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +import { OIDC_DEFAULT_SCOPES, ResponseMode, HeaderNames, CLIENT_INFO, ClaimsRequestKeys, PasswordGrantConstants, AuthenticationScheme, ThrottlingConstants } from '../utils/Constants.mjs'; +import { CLIENT_ID, BROKER_CLIENT_ID, REDIRECT_URI, RESPONSE_TYPE, RESPONSE_MODE, NATIVE_BROKER, SCOPE, POST_LOGOUT_URI, ID_TOKEN_HINT, DOMAIN_HINT, LOGIN_HINT, SID, CLAIMS, CLIENT_REQUEST_ID, X_CLIENT_SKU, X_CLIENT_VER, X_CLIENT_OS, X_CLIENT_CPU, X_APP_NAME, X_APP_VER, PROMPT, STATE, NONCE, CODE_CHALLENGE, CODE_CHALLENGE_METHOD, CODE, DEVICE_CODE, REFRESH_TOKEN, CODE_VERIFIER, CLIENT_SECRET, CLIENT_ASSERTION, CLIENT_ASSERTION_TYPE, OBO_ASSERTION, REQUESTED_TOKEN_USE, GRANT_TYPE, INSTANCE_AWARE, TOKEN_TYPE, REQ_CNF, X_CLIENT_CURR_TELEM, X_CLIENT_LAST_TELEM, X_MS_LIB_CAPABILITY, LOGOUT_HINT, BROKER_REDIRECT_URI, EAR_JWK, EAR_JWE_CRYPTO } from '../constants/AADServerParamKeys.mjs'; +import { ScopeSet } from './ScopeSet.mjs'; +import { createClientConfigurationError } from '../error/ClientConfigurationError.mjs'; +import { invalidClaims, pkceParamsMissing } from '../error/ClientConfigurationErrorCodes.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +function instrumentBrokerParams(parameters, correlationId, performanceClient) { + if (!correlationId) { + return; + } + const clientId = parameters.get(CLIENT_ID); + if (clientId && parameters.has(BROKER_CLIENT_ID)) { + performanceClient?.addFields({ + embeddedClientId: clientId, + embeddedRedirectUri: parameters.get(REDIRECT_URI), + }, correlationId); + } +} +/** + * Add the given response_type + * @param parameters + * @param responseType + */ +function addResponseType(parameters, responseType) { + parameters.set(RESPONSE_TYPE, responseType); +} +/** + * add response_mode. defaults to query. + * @param responseMode + */ +function addResponseMode(parameters, responseMode) { + parameters.set(RESPONSE_MODE, responseMode ? responseMode : ResponseMode.QUERY); +} +/** + * Add flag to indicate STS should attempt to use WAM if available + */ +function addNativeBroker(parameters) { + parameters.set(NATIVE_BROKER, "1"); +} +/** + * add scopes. set addOidcScopes to false to prevent default scopes in non-user scenarios + * @param scopeSet + * @param addOidcScopes + */ +function addScopes(parameters, scopes, addOidcScopes = true, defaultScopes = OIDC_DEFAULT_SCOPES) { + // Always add openid to the scopes when adding OIDC scopes + if (addOidcScopes && + !defaultScopes.includes("openid") && + !scopes.includes("openid")) { + defaultScopes.push("openid"); + } + const requestScopes = addOidcScopes + ? [...(scopes || []), ...defaultScopes] + : scopes || []; + const scopeSet = new ScopeSet(requestScopes); + parameters.set(SCOPE, scopeSet.printScopes()); +} +/** + * add clientId + * @param clientId + */ +function addClientId(parameters, clientId) { + parameters.set(CLIENT_ID, clientId); +} +/** + * add redirect_uri + * @param redirectUri + */ +function addRedirectUri(parameters, redirectUri) { + parameters.set(REDIRECT_URI, redirectUri); +} +/** + * add post logout redirectUri + * @param redirectUri + */ +function addPostLogoutRedirectUri(parameters, redirectUri) { + parameters.set(POST_LOGOUT_URI, redirectUri); +} +/** + * add id_token_hint to logout request + * @param idTokenHint + */ +function addIdTokenHint(parameters, idTokenHint) { + parameters.set(ID_TOKEN_HINT, idTokenHint); +} +/** + * add domain_hint + * @param domainHint + */ +function addDomainHint(parameters, domainHint) { + parameters.set(DOMAIN_HINT, domainHint); +} +/** + * add login_hint + * @param loginHint + */ +function addLoginHint(parameters, loginHint) { + parameters.set(LOGIN_HINT, loginHint); +} +/** + * Adds the CCS (Cache Credential Service) query parameter for login_hint + * @param loginHint + */ +function addCcsUpn(parameters, loginHint) { + parameters.set(HeaderNames.CCS_HEADER, `UPN:${loginHint}`); +} +/** + * Adds the CCS (Cache Credential Service) query parameter for account object + * @param loginHint + */ +function addCcsOid(parameters, clientInfo) { + parameters.set(HeaderNames.CCS_HEADER, `Oid:${clientInfo.uid}@${clientInfo.utid}`); +} +/** + * add sid + * @param sid + */ +function addSid(parameters, sid) { + parameters.set(SID, sid); +} +/** + * add claims + * @param claims + */ +function addClaims(parameters, claims, clientCapabilities) { + const mergedClaims = addClientCapabilitiesToClaims(claims, clientCapabilities); + try { + JSON.parse(mergedClaims); + } + catch (e) { + throw createClientConfigurationError(invalidClaims); + } + parameters.set(CLAIMS, mergedClaims); +} +/** + * add correlationId + * @param correlationId + */ +function addCorrelationId(parameters, correlationId) { + parameters.set(CLIENT_REQUEST_ID, correlationId); +} +/** + * add library info query params + * @param libraryInfo + */ +function addLibraryInfo(parameters, libraryInfo) { + // Telemetry Info + parameters.set(X_CLIENT_SKU, libraryInfo.sku); + parameters.set(X_CLIENT_VER, libraryInfo.version); + if (libraryInfo.os) { + parameters.set(X_CLIENT_OS, libraryInfo.os); + } + if (libraryInfo.cpu) { + parameters.set(X_CLIENT_CPU, libraryInfo.cpu); + } +} +/** + * Add client telemetry parameters + * @param appTelemetry + */ +function addApplicationTelemetry(parameters, appTelemetry) { + if (appTelemetry?.appName) { + parameters.set(X_APP_NAME, appTelemetry.appName); + } + if (appTelemetry?.appVersion) { + parameters.set(X_APP_VER, appTelemetry.appVersion); + } +} +/** + * add prompt + * @param prompt + */ +function addPrompt(parameters, prompt) { + parameters.set(PROMPT, prompt); +} +/** + * add state + * @param state + */ +function addState(parameters, state) { + if (state) { + parameters.set(STATE, state); + } +} +/** + * add nonce + * @param nonce + */ +function addNonce(parameters, nonce) { + parameters.set(NONCE, nonce); +} +/** + * add code_challenge and code_challenge_method + * - throw if either of them are not passed + * @param codeChallenge + * @param codeChallengeMethod + */ +function addCodeChallengeParams(parameters, codeChallenge, codeChallengeMethod) { + if (codeChallenge && codeChallengeMethod) { + parameters.set(CODE_CHALLENGE, codeChallenge); + parameters.set(CODE_CHALLENGE_METHOD, codeChallengeMethod); + } + else { + throw createClientConfigurationError(pkceParamsMissing); + } +} +/** + * add the `authorization_code` passed by the user to exchange for a token + * @param code + */ +function addAuthorizationCode(parameters, code) { + parameters.set(CODE, code); +} +/** + * add the `authorization_code` passed by the user to exchange for a token + * @param code + */ +function addDeviceCode(parameters, code) { + parameters.set(DEVICE_CODE, code); +} +/** + * add the `refreshToken` passed by the user + * @param refreshToken + */ +function addRefreshToken(parameters, refreshToken) { + parameters.set(REFRESH_TOKEN, refreshToken); +} +/** + * add the `code_verifier` passed by the user to exchange for a token + * @param codeVerifier + */ +function addCodeVerifier(parameters, codeVerifier) { + parameters.set(CODE_VERIFIER, codeVerifier); +} +/** + * add client_secret + * @param clientSecret + */ +function addClientSecret(parameters, clientSecret) { + parameters.set(CLIENT_SECRET, clientSecret); +} +/** + * add clientAssertion for confidential client flows + * @param clientAssertion + */ +function addClientAssertion(parameters, clientAssertion) { + if (clientAssertion) { + parameters.set(CLIENT_ASSERTION, clientAssertion); + } +} +/** + * add clientAssertionType for confidential client flows + * @param clientAssertionType + */ +function addClientAssertionType(parameters, clientAssertionType) { + if (clientAssertionType) { + parameters.set(CLIENT_ASSERTION_TYPE, clientAssertionType); + } +} +/** + * add OBO assertion for confidential client flows + * @param clientAssertion + */ +function addOboAssertion(parameters, oboAssertion) { + parameters.set(OBO_ASSERTION, oboAssertion); +} +/** + * add grant type + * @param grantType + */ +function addRequestTokenUse(parameters, tokenUse) { + parameters.set(REQUESTED_TOKEN_USE, tokenUse); +} +/** + * add grant type + * @param grantType + */ +function addGrantType(parameters, grantType) { + parameters.set(GRANT_TYPE, grantType); +} +/** + * add client info + * + */ +function addClientInfo(parameters) { + parameters.set(CLIENT_INFO, "1"); +} +function addInstanceAware(parameters) { + if (!parameters.has(INSTANCE_AWARE)) { + parameters.set(INSTANCE_AWARE, "true"); + } +} +/** + * add extraQueryParams + * @param eQParams + */ +function addExtraQueryParameters(parameters, eQParams) { + Object.entries(eQParams).forEach(([key, value]) => { + if (!parameters.has(key) && value) { + parameters.set(key, value); + } + }); +} +function addClientCapabilitiesToClaims(claims, clientCapabilities) { + let mergedClaims; + // Parse provided claims into JSON object or initialize empty object + if (!claims) { + mergedClaims = {}; + } + else { + try { + mergedClaims = JSON.parse(claims); + } + catch (e) { + throw createClientConfigurationError(invalidClaims); + } + } + if (clientCapabilities && clientCapabilities.length > 0) { + if (!mergedClaims.hasOwnProperty(ClaimsRequestKeys.ACCESS_TOKEN)) { + // Add access_token key to claims object + mergedClaims[ClaimsRequestKeys.ACCESS_TOKEN] = {}; + } + // Add xms_cc claim with provided clientCapabilities to access_token key + mergedClaims[ClaimsRequestKeys.ACCESS_TOKEN][ClaimsRequestKeys.XMS_CC] = + { + values: clientCapabilities, + }; + } + return JSON.stringify(mergedClaims); +} +/** + * adds `username` for Password Grant flow + * @param username + */ +function addUsername(parameters, username) { + parameters.set(PasswordGrantConstants.username, username); +} +/** + * adds `password` for Password Grant flow + * @param password + */ +function addPassword(parameters, password) { + parameters.set(PasswordGrantConstants.password, password); +} +/** + * add pop_jwk to query params + * @param cnfString + */ +function addPopToken(parameters, cnfString) { + if (cnfString) { + parameters.set(TOKEN_TYPE, AuthenticationScheme.POP); + parameters.set(REQ_CNF, cnfString); + } +} +/** + * add SSH JWK and key ID to query params + */ +function addSshJwk(parameters, sshJwkString) { + if (sshJwkString) { + parameters.set(TOKEN_TYPE, AuthenticationScheme.SSH); + parameters.set(REQ_CNF, sshJwkString); + } +} +/** + * add server telemetry fields + * @param serverTelemetryManager + */ +function addServerTelemetry(parameters, serverTelemetryManager) { + parameters.set(X_CLIENT_CURR_TELEM, serverTelemetryManager.generateCurrentRequestHeaderValue()); + parameters.set(X_CLIENT_LAST_TELEM, serverTelemetryManager.generateLastRequestHeaderValue()); +} +/** + * Adds parameter that indicates to the server that throttling is supported + */ +function addThrottling(parameters) { + parameters.set(X_MS_LIB_CAPABILITY, ThrottlingConstants.X_MS_LIB_CAPABILITY_VALUE); +} +/** + * Adds logout_hint parameter for "silent" logout which prevent server account picker + */ +function addLogoutHint(parameters, logoutHint) { + parameters.set(LOGOUT_HINT, logoutHint); +} +function addBrokerParameters(parameters, brokerClientId, brokerRedirectUri) { + if (!parameters.has(BROKER_CLIENT_ID)) { + parameters.set(BROKER_CLIENT_ID, brokerClientId); + } + if (!parameters.has(BROKER_REDIRECT_URI)) { + parameters.set(BROKER_REDIRECT_URI, brokerRedirectUri); + } +} +/** + * Add EAR (Encrypted Authorize Response) request parameters + * @param parameters + * @param jwk + */ +function addEARParameters(parameters, jwk) { + parameters.set(EAR_JWK, encodeURIComponent(jwk)); + // ear_jwe_crypto will always have value: {"alg":"dir","enc":"A256GCM"} so we can hardcode this + const jweCryptoB64Encoded = "eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0"; + parameters.set(EAR_JWE_CRYPTO, jweCryptoB64Encoded); +} +/** + * Adds authorize body parameters to the request parameters + * @param parameters + * @param bodyParameters + */ +function addPostBodyParameters(parameters, bodyParameters) { + Object.entries(bodyParameters).forEach(([key, value]) => { + if (value) { + parameters.set(key, value); + } + }); +} + +export { addApplicationTelemetry, addAuthorizationCode, addBrokerParameters, addCcsOid, addCcsUpn, addClaims, addClientAssertion, addClientAssertionType, addClientCapabilitiesToClaims, addClientId, addClientInfo, addClientSecret, addCodeChallengeParams, addCodeVerifier, addCorrelationId, addDeviceCode, addDomainHint, addEARParameters, addExtraQueryParameters, addGrantType, addIdTokenHint, addInstanceAware, addLibraryInfo, addLoginHint, addLogoutHint, addNativeBroker, addNonce, addOboAssertion, addPassword, addPopToken, addPostBodyParameters, addPostLogoutRedirectUri, addPrompt, addRedirectUri, addRefreshToken, addRequestTokenUse, addResponseMode, addResponseType, addScopes, addServerTelemetry, addSid, addSshJwk, addState, addThrottling, addUsername, instrumentBrokerParams }; +//# sourceMappingURL=RequestParameterBuilder.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/request/ScopeSet.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/request/ScopeSet.mjs new file mode 100644 index 00000000..b60814d8 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/request/ScopeSet.mjs @@ -0,0 +1,204 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +import { createClientConfigurationError } from '../error/ClientConfigurationError.mjs'; +import { StringUtils } from '../utils/StringUtils.mjs'; +import { createClientAuthError } from '../error/ClientAuthError.mjs'; +import { Constants, OIDC_DEFAULT_SCOPES, OIDC_SCOPES } from '../utils/Constants.mjs'; +import { emptyInputScopesError } from '../error/ClientConfigurationErrorCodes.mjs'; +import { cannotAppendScopeSet, cannotRemoveEmptyScope, emptyInputScopeSet } from '../error/ClientAuthErrorCodes.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * The ScopeSet class creates a set of scopes. Scopes are case-insensitive, unique values, so the Set object in JS makes + * the most sense to implement for this class. All scopes are trimmed and converted to lower case strings in intersection and union functions + * to ensure uniqueness of strings. + */ +class ScopeSet { + constructor(inputScopes) { + // Filter empty string and null/undefined array items + const scopeArr = inputScopes + ? StringUtils.trimArrayEntries([...inputScopes]) + : []; + const filteredInput = scopeArr + ? StringUtils.removeEmptyStringsFromArray(scopeArr) + : []; + // Check if scopes array has at least one member + if (!filteredInput || !filteredInput.length) { + throw createClientConfigurationError(emptyInputScopesError); + } + this.scopes = new Set(); // Iterator in constructor not supported by IE11 + filteredInput.forEach((scope) => this.scopes.add(scope)); + } + /** + * Factory method to create ScopeSet from space-delimited string + * @param inputScopeString + * @param appClientId + * @param scopesRequired + */ + static fromString(inputScopeString) { + const scopeString = inputScopeString || Constants.EMPTY_STRING; + const inputScopes = scopeString.split(" "); + return new ScopeSet(inputScopes); + } + /** + * Creates the set of scopes to search for in cache lookups + * @param inputScopeString + * @returns + */ + static createSearchScopes(inputScopeString) { + // Handle empty scopes by using default OIDC scopes for cache lookup + const scopesToUse = inputScopeString && inputScopeString.length > 0 + ? inputScopeString + : [...OIDC_DEFAULT_SCOPES]; + const scopeSet = new ScopeSet(scopesToUse); + if (!scopeSet.containsOnlyOIDCScopes()) { + scopeSet.removeOIDCScopes(); + } + else { + scopeSet.removeScope(Constants.OFFLINE_ACCESS_SCOPE); + } + return scopeSet; + } + /** + * Check if a given scope is present in this set of scopes. + * @param scope + */ + containsScope(scope) { + const lowerCaseScopes = this.printScopesLowerCase().split(" "); + const lowerCaseScopesSet = new ScopeSet(lowerCaseScopes); + // compare lowercase scopes + return scope + ? lowerCaseScopesSet.scopes.has(scope.toLowerCase()) + : false; + } + /** + * Check if a set of scopes is present in this set of scopes. + * @param scopeSet + */ + containsScopeSet(scopeSet) { + if (!scopeSet || scopeSet.scopes.size <= 0) { + return false; + } + return (this.scopes.size >= scopeSet.scopes.size && + scopeSet.asArray().every((scope) => this.containsScope(scope))); + } + /** + * Check if set of scopes contains only the defaults + */ + containsOnlyOIDCScopes() { + let defaultScopeCount = 0; + OIDC_SCOPES.forEach((defaultScope) => { + if (this.containsScope(defaultScope)) { + defaultScopeCount += 1; + } + }); + return this.scopes.size === defaultScopeCount; + } + /** + * Appends single scope if passed + * @param newScope + */ + appendScope(newScope) { + if (newScope) { + this.scopes.add(newScope.trim()); + } + } + /** + * Appends multiple scopes if passed + * @param newScopes + */ + appendScopes(newScopes) { + try { + newScopes.forEach((newScope) => this.appendScope(newScope)); + } + catch (e) { + throw createClientAuthError(cannotAppendScopeSet); + } + } + /** + * Removes element from set of scopes. + * @param scope + */ + removeScope(scope) { + if (!scope) { + throw createClientAuthError(cannotRemoveEmptyScope); + } + this.scopes.delete(scope.trim()); + } + /** + * Removes default scopes from set of scopes + * Primarily used to prevent cache misses if the default scopes are not returned from the server + */ + removeOIDCScopes() { + OIDC_SCOPES.forEach((defaultScope) => { + this.scopes.delete(defaultScope); + }); + } + /** + * Combines an array of scopes with the current set of scopes. + * @param otherScopes + */ + unionScopeSets(otherScopes) { + if (!otherScopes) { + throw createClientAuthError(emptyInputScopeSet); + } + const unionScopes = new Set(); // Iterator in constructor not supported in IE11 + otherScopes.scopes.forEach((scope) => unionScopes.add(scope.toLowerCase())); + this.scopes.forEach((scope) => unionScopes.add(scope.toLowerCase())); + return unionScopes; + } + /** + * Check if scopes intersect between this set and another. + * @param otherScopes + */ + intersectingScopeSets(otherScopes) { + if (!otherScopes) { + throw createClientAuthError(emptyInputScopeSet); + } + // Do not allow OIDC scopes to be the only intersecting scopes + if (!otherScopes.containsOnlyOIDCScopes()) { + otherScopes.removeOIDCScopes(); + } + const unionScopes = this.unionScopeSets(otherScopes); + const sizeOtherScopes = otherScopes.getScopeCount(); + const sizeThisScopes = this.getScopeCount(); + const sizeUnionScopes = unionScopes.size; + return sizeUnionScopes < sizeThisScopes + sizeOtherScopes; + } + /** + * Returns size of set of scopes. + */ + getScopeCount() { + return this.scopes.size; + } + /** + * Returns the scopes as an array of string values + */ + asArray() { + const array = []; + this.scopes.forEach((val) => array.push(val)); + return array; + } + /** + * Prints scopes into a space-delimited string + */ + printScopes() { + if (this.scopes) { + const scopeArr = this.asArray(); + return scopeArr.join(" "); + } + return Constants.EMPTY_STRING; + } + /** + * Prints scopes into a space-delimited lower-case string (used for caching) + */ + printScopesLowerCase() { + return this.printScopes().toLowerCase(); + } +} + +export { ScopeSet }; +//# sourceMappingURL=ScopeSet.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/response/ResponseHandler.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/response/ResponseHandler.mjs new file mode 100644 index 00000000..4b9f0ffc --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/response/ResponseHandler.mjs @@ -0,0 +1,350 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +import { createClientAuthError } from '../error/ClientAuthError.mjs'; +import { ServerError } from '../error/ServerError.mjs'; +import { ScopeSet } from '../request/ScopeSet.mjs'; +import { AccountEntity } from '../cache/entities/AccountEntity.mjs'; +import { isInteractionRequiredError, InteractionRequiredAuthError } from '../error/InteractionRequiredAuthError.mjs'; +import { ProtocolUtils } from '../utils/ProtocolUtils.mjs'; +import { Constants, HttpStatus, AuthenticationScheme, THE_FAMILY_ID } from '../utils/Constants.mjs'; +import { PopTokenGenerator } from '../crypto/PopTokenGenerator.mjs'; +import { TokenCacheContext } from '../cache/persistence/TokenCacheContext.mjs'; +import { PerformanceEvents } from '../telemetry/performance/PerformanceEvent.mjs'; +import { extractTokenClaims, checkMaxAge, isKmsi } from '../account/AuthToken.mjs'; +import { getTenantIdFromIdTokenClaims } from '../account/TokenClaims.mjs'; +import { updateAccountTenantProfileData, buildTenantProfile } from '../account/AccountInfo.mjs'; +import { createIdTokenEntity, createAccessTokenEntity, createRefreshTokenEntity } from '../cache/utils/CacheHelpers.mjs'; +import { toDateFromSeconds } from '../utils/TimeUtils.mjs'; +import { nonceMismatch, authTimeNotFound, invalidCacheEnvironment, keyIdMissing } from '../error/ClientAuthErrorCodes.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * Class that handles response parsing. + * @internal + */ +class ResponseHandler { + constructor(clientId, cacheStorage, cryptoObj, logger, serializableCache, persistencePlugin, performanceClient) { + this.clientId = clientId; + this.cacheStorage = cacheStorage; + this.cryptoObj = cryptoObj; + this.logger = logger; + this.serializableCache = serializableCache; + this.persistencePlugin = persistencePlugin; + this.performanceClient = performanceClient; + } + /** + * Function which validates server authorization token response. + * @param serverResponse + * @param refreshAccessToken + */ + validateTokenResponse(serverResponse, refreshAccessToken) { + // Check for error + if (serverResponse.error || + serverResponse.error_description || + serverResponse.suberror) { + const errString = `Error(s): ${serverResponse.error_codes || Constants.NOT_AVAILABLE} - Timestamp: ${serverResponse.timestamp || Constants.NOT_AVAILABLE} - Description: ${serverResponse.error_description || Constants.NOT_AVAILABLE} - Correlation ID: ${serverResponse.correlation_id || Constants.NOT_AVAILABLE} - Trace ID: ${serverResponse.trace_id || Constants.NOT_AVAILABLE}`; + const serverErrorNo = serverResponse.error_codes?.length + ? serverResponse.error_codes[0] + : undefined; + const serverError = new ServerError(serverResponse.error, errString, serverResponse.suberror, serverErrorNo, serverResponse.status); + // check if 500 error + if (refreshAccessToken && + serverResponse.status && + serverResponse.status >= HttpStatus.SERVER_ERROR_RANGE_START && + serverResponse.status <= HttpStatus.SERVER_ERROR_RANGE_END) { + this.logger.warning(`executeTokenRequest:validateTokenResponse - AAD is currently unavailable and the access token is unable to be refreshed.\n${serverError}`); + // don't throw an exception, but alert the user via a log that the token was unable to be refreshed + return; + // check if 400 error + } + else if (refreshAccessToken && + serverResponse.status && + serverResponse.status >= HttpStatus.CLIENT_ERROR_RANGE_START && + serverResponse.status <= HttpStatus.CLIENT_ERROR_RANGE_END) { + this.logger.warning(`executeTokenRequest:validateTokenResponse - AAD is currently available but is unable to refresh the access token.\n${serverError}`); + // don't throw an exception, but alert the user via a log that the token was unable to be refreshed + return; + } + if (isInteractionRequiredError(serverResponse.error, serverResponse.error_description, serverResponse.suberror)) { + throw new InteractionRequiredAuthError(serverResponse.error, serverResponse.error_description, serverResponse.suberror, serverResponse.timestamp || Constants.EMPTY_STRING, serverResponse.trace_id || Constants.EMPTY_STRING, serverResponse.correlation_id || Constants.EMPTY_STRING, serverResponse.claims || Constants.EMPTY_STRING, serverErrorNo); + } + throw serverError; + } + } + /** + * Returns a constructed token response based on given string. Also manages the cache updates and cleanups. + * @param serverTokenResponse + * @param authority + */ + async handleServerTokenResponse(serverTokenResponse, authority, reqTimestamp, request, authCodePayload, userAssertionHash, handlingRefreshTokenResponse, forceCacheRefreshTokenResponse, serverRequestId) { + this.performanceClient?.addQueueMeasurement(PerformanceEvents.HandleServerTokenResponse, serverTokenResponse.correlation_id); + // create an idToken object (not entity) + let idTokenClaims; + if (serverTokenResponse.id_token) { + idTokenClaims = extractTokenClaims(serverTokenResponse.id_token || Constants.EMPTY_STRING, this.cryptoObj.base64Decode); + // token nonce check (TODO: Add a warning if no nonce is given?) + if (authCodePayload && authCodePayload.nonce) { + if (idTokenClaims.nonce !== authCodePayload.nonce) { + throw createClientAuthError(nonceMismatch); + } + } + // token max_age check + if (request.maxAge || request.maxAge === 0) { + const authTime = idTokenClaims.auth_time; + if (!authTime) { + throw createClientAuthError(authTimeNotFound); + } + checkMaxAge(authTime, request.maxAge); + } + } + // generate homeAccountId + this.homeAccountIdentifier = AccountEntity.generateHomeAccountId(serverTokenResponse.client_info || Constants.EMPTY_STRING, authority.authorityType, this.logger, this.cryptoObj, idTokenClaims); + // save the response tokens + let requestStateObj; + if (!!authCodePayload && !!authCodePayload.state) { + requestStateObj = ProtocolUtils.parseRequestState(this.cryptoObj, authCodePayload.state); + } + // Add keyId from request to serverTokenResponse if defined + serverTokenResponse.key_id = + serverTokenResponse.key_id || request.sshKid || undefined; + const cacheRecord = this.generateCacheRecord(serverTokenResponse, authority, reqTimestamp, request, idTokenClaims, userAssertionHash, authCodePayload); + let cacheContext; + try { + if (this.persistencePlugin && this.serializableCache) { + this.logger.verbose("Persistence enabled, calling beforeCacheAccess"); + cacheContext = new TokenCacheContext(this.serializableCache, true); + await this.persistencePlugin.beforeCacheAccess(cacheContext); + } + /* + * When saving a refreshed tokens to the cache, it is expected that the account that was used is present in the cache. + * If not present, we should return null, as it's the case that another application called removeAccount in between + * the calls to getAllAccounts and acquireTokenSilent. We should not overwrite that removal, unless explicitly flagged by + * the developer, as in the case of refresh token flow used in ADAL Node to MSAL Node migration. + */ + if (handlingRefreshTokenResponse && + !forceCacheRefreshTokenResponse && + cacheRecord.account) { + const key = this.cacheStorage.generateAccountKey(AccountEntity.getAccountInfo(cacheRecord.account)); + const account = this.cacheStorage.getAccount(key, request.correlationId); + if (!account) { + this.logger.warning("Account used to refresh tokens not in persistence, refreshed tokens will not be stored in the cache"); + return await ResponseHandler.generateAuthenticationResult(this.cryptoObj, authority, cacheRecord, false, request, idTokenClaims, requestStateObj, undefined, serverRequestId); + } + } + await this.cacheStorage.saveCacheRecord(cacheRecord, request.correlationId, isKmsi(idTokenClaims || {}), request.storeInCache); + } + finally { + if (this.persistencePlugin && + this.serializableCache && + cacheContext) { + this.logger.verbose("Persistence enabled, calling afterCacheAccess"); + await this.persistencePlugin.afterCacheAccess(cacheContext); + } + } + return ResponseHandler.generateAuthenticationResult(this.cryptoObj, authority, cacheRecord, false, request, idTokenClaims, requestStateObj, serverTokenResponse, serverRequestId); + } + /** + * Generates CacheRecord + * @param serverTokenResponse + * @param idTokenObj + * @param authority + */ + generateCacheRecord(serverTokenResponse, authority, reqTimestamp, request, idTokenClaims, userAssertionHash, authCodePayload) { + const env = authority.getPreferredCache(); + if (!env) { + throw createClientAuthError(invalidCacheEnvironment); + } + const claimsTenantId = getTenantIdFromIdTokenClaims(idTokenClaims); + // IdToken: non AAD scenarios can have empty realm + let cachedIdToken; + let cachedAccount; + if (serverTokenResponse.id_token && !!idTokenClaims) { + cachedIdToken = createIdTokenEntity(this.homeAccountIdentifier, env, serverTokenResponse.id_token, this.clientId, claimsTenantId || ""); + cachedAccount = buildAccountToCache(this.cacheStorage, authority, this.homeAccountIdentifier, this.cryptoObj.base64Decode, request.correlationId, idTokenClaims, serverTokenResponse.client_info, env, claimsTenantId, authCodePayload, undefined, // nativeAccountId + this.logger); + } + // AccessToken + let cachedAccessToken = null; + if (serverTokenResponse.access_token) { + // If scopes not returned in server response, use request scopes + const responseScopes = serverTokenResponse.scope + ? ScopeSet.fromString(serverTokenResponse.scope) + : new ScopeSet(request.scopes || []); + /* + * Use timestamp calculated before request + * Server may return timestamps as strings, parse to numbers if so. + */ + const expiresIn = (typeof serverTokenResponse.expires_in === "string" + ? parseInt(serverTokenResponse.expires_in, 10) + : serverTokenResponse.expires_in) || 0; + const extExpiresIn = (typeof serverTokenResponse.ext_expires_in === "string" + ? parseInt(serverTokenResponse.ext_expires_in, 10) + : serverTokenResponse.ext_expires_in) || 0; + const refreshIn = (typeof serverTokenResponse.refresh_in === "string" + ? parseInt(serverTokenResponse.refresh_in, 10) + : serverTokenResponse.refresh_in) || undefined; + const tokenExpirationSeconds = reqTimestamp + expiresIn; + const extendedTokenExpirationSeconds = tokenExpirationSeconds + extExpiresIn; + const refreshOnSeconds = refreshIn && refreshIn > 0 + ? reqTimestamp + refreshIn + : undefined; + // non AAD scenarios can have empty realm + cachedAccessToken = createAccessTokenEntity(this.homeAccountIdentifier, env, serverTokenResponse.access_token, this.clientId, claimsTenantId || authority.tenant || "", responseScopes.printScopes(), tokenExpirationSeconds, extendedTokenExpirationSeconds, this.cryptoObj.base64Decode, refreshOnSeconds, serverTokenResponse.token_type, userAssertionHash, serverTokenResponse.key_id, request.claims, request.requestedClaimsHash); + } + // refreshToken + let cachedRefreshToken = null; + if (serverTokenResponse.refresh_token) { + let rtExpiresOn; + if (serverTokenResponse.refresh_token_expires_in) { + const rtExpiresIn = typeof serverTokenResponse.refresh_token_expires_in === + "string" + ? parseInt(serverTokenResponse.refresh_token_expires_in, 10) + : serverTokenResponse.refresh_token_expires_in; + rtExpiresOn = reqTimestamp + rtExpiresIn; + } + cachedRefreshToken = createRefreshTokenEntity(this.homeAccountIdentifier, env, serverTokenResponse.refresh_token, this.clientId, serverTokenResponse.foci, userAssertionHash, rtExpiresOn); + } + // appMetadata + let cachedAppMetadata = null; + if (serverTokenResponse.foci) { + cachedAppMetadata = { + clientId: this.clientId, + environment: env, + familyId: serverTokenResponse.foci, + }; + } + return { + account: cachedAccount, + idToken: cachedIdToken, + accessToken: cachedAccessToken, + refreshToken: cachedRefreshToken, + appMetadata: cachedAppMetadata, + }; + } + /** + * Creates an @AuthenticationResult from @CacheRecord , @IdToken , and a boolean that states whether or not the result is from cache. + * + * Optionally takes a state string that is set as-is in the response. + * + * @param cacheRecord + * @param idTokenObj + * @param fromTokenCache + * @param stateString + */ + static async generateAuthenticationResult(cryptoObj, authority, cacheRecord, fromTokenCache, request, idTokenClaims, requestState, serverTokenResponse, requestId) { + let accessToken = Constants.EMPTY_STRING; + let responseScopes = []; + let expiresOn = null; + let extExpiresOn; + let refreshOn; + let familyId = Constants.EMPTY_STRING; + if (cacheRecord.accessToken) { + /* + * if the request object has `popKid` property, `signPopToken` will be set to false and + * the token will be returned unsigned + */ + if (cacheRecord.accessToken.tokenType === + AuthenticationScheme.POP && + !request.popKid) { + const popTokenGenerator = new PopTokenGenerator(cryptoObj); + const { secret, keyId } = cacheRecord.accessToken; + if (!keyId) { + throw createClientAuthError(keyIdMissing); + } + accessToken = await popTokenGenerator.signPopToken(secret, keyId, request); + } + else { + accessToken = cacheRecord.accessToken.secret; + } + responseScopes = ScopeSet.fromString(cacheRecord.accessToken.target).asArray(); + // Access token expiresOn cached in seconds, converting to Date for AuthenticationResult + expiresOn = toDateFromSeconds(cacheRecord.accessToken.expiresOn); + extExpiresOn = toDateFromSeconds(cacheRecord.accessToken.extendedExpiresOn); + if (cacheRecord.accessToken.refreshOn) { + refreshOn = toDateFromSeconds(cacheRecord.accessToken.refreshOn); + } + } + if (cacheRecord.appMetadata) { + familyId = + cacheRecord.appMetadata.familyId === THE_FAMILY_ID + ? THE_FAMILY_ID + : ""; + } + const uid = idTokenClaims?.oid || idTokenClaims?.sub || ""; + const tid = idTokenClaims?.tid || ""; + // for hybrid + native bridge enablement, send back the native account Id + if (serverTokenResponse?.spa_accountid && !!cacheRecord.account) { + cacheRecord.account.nativeAccountId = + serverTokenResponse?.spa_accountid; + } + const accountInfo = cacheRecord.account + ? updateAccountTenantProfileData(AccountEntity.getAccountInfo(cacheRecord.account), undefined, // tenantProfile optional + idTokenClaims, cacheRecord.idToken?.secret) + : null; + return { + authority: authority.canonicalAuthority, + uniqueId: uid, + tenantId: tid, + scopes: responseScopes, + account: accountInfo, + idToken: cacheRecord?.idToken?.secret || "", + idTokenClaims: idTokenClaims || {}, + accessToken: accessToken, + fromCache: fromTokenCache, + expiresOn: expiresOn, + extExpiresOn: extExpiresOn, + refreshOn: refreshOn, + correlationId: request.correlationId, + requestId: requestId || Constants.EMPTY_STRING, + familyId: familyId, + tokenType: cacheRecord.accessToken?.tokenType || Constants.EMPTY_STRING, + state: requestState + ? requestState.userRequestState + : Constants.EMPTY_STRING, + cloudGraphHostName: cacheRecord.account?.cloudGraphHostName || + Constants.EMPTY_STRING, + msGraphHost: cacheRecord.account?.msGraphHost || Constants.EMPTY_STRING, + code: serverTokenResponse?.spa_code, + fromNativeBroker: false, + }; + } +} +function buildAccountToCache(cacheStorage, authority, homeAccountId, base64Decode, correlationId, idTokenClaims, clientInfo, environment, claimsTenantId, authCodePayload, nativeAccountId, logger) { + logger?.verbose("setCachedAccount called"); + // Check if base account is already cached + const accountKeys = cacheStorage.getAccountKeys(); + const baseAccountKey = accountKeys.find((accountKey) => { + return accountKey.startsWith(homeAccountId); + }); + let cachedAccount = null; + if (baseAccountKey) { + cachedAccount = cacheStorage.getAccount(baseAccountKey, correlationId); + } + const baseAccount = cachedAccount || + AccountEntity.createAccount({ + homeAccountId, + idTokenClaims, + clientInfo, + environment, + cloudGraphHostName: authCodePayload?.cloud_graph_host_name, + msGraphHost: authCodePayload?.msgraph_host, + nativeAccountId: nativeAccountId, + }, authority, base64Decode); + const tenantProfiles = baseAccount.tenantProfiles || []; + const tenantId = claimsTenantId || baseAccount.realm; + if (tenantId && + !tenantProfiles.find((tenantProfile) => { + return tenantProfile.tenantId === tenantId; + })) { + const newTenantProfile = buildTenantProfile(homeAccountId, baseAccount.localAccountId, tenantId, idTokenClaims); + tenantProfiles.push(newTenantProfile); + } + baseAccount.tenantProfiles = tenantProfiles; + return baseAccount; +} + +export { ResponseHandler, buildAccountToCache }; +//# sourceMappingURL=ResponseHandler.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/telemetry/performance/PerformanceEvent.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/telemetry/performance/PerformanceEvent.mjs new file mode 100644 index 00000000..8acf86b6 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/telemetry/performance/PerformanceEvent.mjs @@ -0,0 +1,526 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * Enumeration of operations that are instrumented by have their performance measured by the PerformanceClient. + * + * @export + * @enum {number} + */ +const PerformanceEvents = { + /** + * acquireTokenByCode API (msal-browser and msal-node). + * Used to acquire tokens by trading an authorization code against the token endpoint. + */ + AcquireTokenByCode: "acquireTokenByCode", + /** + * acquireTokenByRefreshToken API (msal-browser and msal-node). + * Used to renew an access token using a refresh token against the token endpoint. + */ + AcquireTokenByRefreshToken: "acquireTokenByRefreshToken", + /** + * acquireTokenSilent API (msal-browser and msal-node). + * Used to silently acquire a new access token (from the cache or the network). + */ + AcquireTokenSilent: "acquireTokenSilent", + /** + * acquireTokenSilentAsync (msal-browser). + * Internal API for acquireTokenSilent. + */ + AcquireTokenSilentAsync: "acquireTokenSilentAsync", + /** + * acquireTokenPopup (msal-browser). + * Used to acquire a new access token interactively through pop ups + */ + AcquireTokenPopup: "acquireTokenPopup", + /** + * acquireTokenPreRedirect (msal-browser). + * First part of the redirect flow. + * Used to acquire a new access token interactively through redirects. + */ + AcquireTokenPreRedirect: "acquireTokenPreRedirect", + /** + * acquireTokenRedirect (msal-browser). + * Second part of the redirect flow. + * Used to acquire a new access token interactively through redirects. + */ + AcquireTokenRedirect: "acquireTokenRedirect", + /** + * getPublicKeyThumbprint API in CryptoOpts class (msal-browser). + * Used to generate a public/private keypair and generate a public key thumbprint for pop requests. + */ + CryptoOptsGetPublicKeyThumbprint: "cryptoOptsGetPublicKeyThumbprint", + /** + * signJwt API in CryptoOpts class (msal-browser). + * Used to signed a pop token. + */ + CryptoOptsSignJwt: "cryptoOptsSignJwt", + /** + * acquireToken API in the SilentCacheClient class (msal-browser). + * Used to read access tokens from the cache. + */ + SilentCacheClientAcquireToken: "silentCacheClientAcquireToken", + /** + * acquireToken API in the SilentIframeClient class (msal-browser). + * Used to acquire a new set of tokens from the authorize endpoint in a hidden iframe. + */ + SilentIframeClientAcquireToken: "silentIframeClientAcquireToken", + AwaitConcurrentIframe: "awaitConcurrentIframe", + /** + * acquireToken API in SilentRereshClient (msal-browser). + * Used to acquire a new set of tokens from the token endpoint using a refresh token. + */ + SilentRefreshClientAcquireToken: "silentRefreshClientAcquireToken", + /** + * ssoSilent API (msal-browser). + * Used to silently acquire an authorization code and set of tokens using a hidden iframe. + */ + SsoSilent: "ssoSilent", + /** + * getDiscoveredAuthority API in StandardInteractionClient class (msal-browser). + * Used to load authority metadata for a request. + */ + StandardInteractionClientGetDiscoveredAuthority: "standardInteractionClientGetDiscoveredAuthority", + /** + * acquireToken APIs in msal-browser. + * Used to make an /authorize endpoint call with native brokering enabled. + */ + FetchAccountIdWithNativeBroker: "fetchAccountIdWithNativeBroker", + /** + * acquireToken API in NativeInteractionClient class (msal-browser). + * Used to acquire a token from Native component when native brokering is enabled. + */ + NativeInteractionClientAcquireToken: "nativeInteractionClientAcquireToken", + /** + * Time spent creating default headers for requests to token endpoint + */ + BaseClientCreateTokenRequestHeaders: "baseClientCreateTokenRequestHeaders", + /** + * Time spent sending/waiting for the response of a request to the token endpoint + */ + NetworkClientSendPostRequestAsync: "networkClientSendPostRequestAsync", + RefreshTokenClientExecutePostToTokenEndpoint: "refreshTokenClientExecutePostToTokenEndpoint", + AuthorizationCodeClientExecutePostToTokenEndpoint: "authorizationCodeClientExecutePostToTokenEndpoint", + /** + * Used to measure the time taken for completing embedded-broker handshake (PW-Broker). + */ + BrokerHandhshake: "brokerHandshake", + /** + * acquireTokenByRefreshToken API in BrokerClientApplication (PW-Broker) . + */ + AcquireTokenByRefreshTokenInBroker: "acquireTokenByRefreshTokenInBroker", + /** + * Time taken for token acquisition by broker + */ + AcquireTokenByBroker: "acquireTokenByBroker", + /** + * Time spent on the network for refresh token acquisition + */ + RefreshTokenClientExecuteTokenRequest: "refreshTokenClientExecuteTokenRequest", + /** + * Time taken for acquiring refresh token , records RT size + */ + RefreshTokenClientAcquireToken: "refreshTokenClientAcquireToken", + /** + * Time taken for acquiring cached refresh token + */ + RefreshTokenClientAcquireTokenWithCachedRefreshToken: "refreshTokenClientAcquireTokenWithCachedRefreshToken", + /** + * acquireTokenByRefreshToken API in RefreshTokenClient (msal-common). + */ + RefreshTokenClientAcquireTokenByRefreshToken: "refreshTokenClientAcquireTokenByRefreshToken", + /** + * Helper function to create token request body in RefreshTokenClient (msal-common). + */ + RefreshTokenClientCreateTokenRequestBody: "refreshTokenClientCreateTokenRequestBody", + /** + * acquireTokenFromCache (msal-browser). + * Internal API for acquiring token from cache + */ + AcquireTokenFromCache: "acquireTokenFromCache", + SilentFlowClientAcquireCachedToken: "silentFlowClientAcquireCachedToken", + SilentFlowClientGenerateResultFromCacheRecord: "silentFlowClientGenerateResultFromCacheRecord", + /** + * acquireTokenBySilentIframe (msal-browser). + * Internal API for acquiring token by silent Iframe + */ + AcquireTokenBySilentIframe: "acquireTokenBySilentIframe", + /** + * Internal API for initializing base request in BaseInteractionClient (msal-browser) + */ + InitializeBaseRequest: "initializeBaseRequest", + /** + * Internal API for initializing silent request in SilentCacheClient (msal-browser) + */ + InitializeSilentRequest: "initializeSilentRequest", + InitializeClientApplication: "initializeClientApplication", + InitializeCache: "initializeCache", + /** + * Helper function in SilentIframeClient class (msal-browser). + */ + SilentIframeClientTokenHelper: "silentIframeClientTokenHelper", + /** + * SilentHandler + */ + SilentHandlerInitiateAuthRequest: "silentHandlerInitiateAuthRequest", + SilentHandlerMonitorIframeForHash: "silentHandlerMonitorIframeForHash", + SilentHandlerLoadFrame: "silentHandlerLoadFrame", + SilentHandlerLoadFrameSync: "silentHandlerLoadFrameSync", + /** + * Helper functions in StandardInteractionClient class (msal-browser) + */ + StandardInteractionClientCreateAuthCodeClient: "standardInteractionClientCreateAuthCodeClient", + StandardInteractionClientGetClientConfiguration: "standardInteractionClientGetClientConfiguration", + StandardInteractionClientInitializeAuthorizationRequest: "standardInteractionClientInitializeAuthorizationRequest", + /** + * getAuthCodeUrl API (msal-browser and msal-node). + */ + GetAuthCodeUrl: "getAuthCodeUrl", + GetStandardParams: "getStandardParams", + /** + * Functions from InteractionHandler (msal-browser) + */ + HandleCodeResponseFromServer: "handleCodeResponseFromServer", + HandleCodeResponse: "handleCodeResponse", + HandleResponseEar: "handleResponseEar", + HandleResponsePlatformBroker: "handleResponsePlatformBroker", + HandleResponseCode: "handleResponseCode", + UpdateTokenEndpointAuthority: "updateTokenEndpointAuthority", + /** + * APIs in Authorization Code Client (msal-common) + */ + AuthClientAcquireToken: "authClientAcquireToken", + AuthClientExecuteTokenRequest: "authClientExecuteTokenRequest", + AuthClientCreateTokenRequestBody: "authClientCreateTokenRequestBody", + /** + * Generate functions in PopTokenGenerator (msal-common) + */ + PopTokenGenerateCnf: "popTokenGenerateCnf", + PopTokenGenerateKid: "popTokenGenerateKid", + /** + * handleServerTokenResponse API in ResponseHandler (msal-common) + */ + HandleServerTokenResponse: "handleServerTokenResponse", + DeserializeResponse: "deserializeResponse", + /** + * Authority functions + */ + AuthorityFactoryCreateDiscoveredInstance: "authorityFactoryCreateDiscoveredInstance", + AuthorityResolveEndpointsAsync: "authorityResolveEndpointsAsync", + AuthorityResolveEndpointsFromLocalSources: "authorityResolveEndpointsFromLocalSources", + AuthorityGetCloudDiscoveryMetadataFromNetwork: "authorityGetCloudDiscoveryMetadataFromNetwork", + AuthorityUpdateCloudDiscoveryMetadata: "authorityUpdateCloudDiscoveryMetadata", + AuthorityGetEndpointMetadataFromNetwork: "authorityGetEndpointMetadataFromNetwork", + AuthorityUpdateEndpointMetadata: "authorityUpdateEndpointMetadata", + AuthorityUpdateMetadataWithRegionalInformation: "authorityUpdateMetadataWithRegionalInformation", + /** + * Region Discovery functions + */ + RegionDiscoveryDetectRegion: "regionDiscoveryDetectRegion", + RegionDiscoveryGetRegionFromIMDS: "regionDiscoveryGetRegionFromIMDS", + RegionDiscoveryGetCurrentVersion: "regionDiscoveryGetCurrentVersion", + AcquireTokenByCodeAsync: "acquireTokenByCodeAsync", + GetEndpointMetadataFromNetwork: "getEndpointMetadataFromNetwork", + GetCloudDiscoveryMetadataFromNetworkMeasurement: "getCloudDiscoveryMetadataFromNetworkMeasurement", + HandleRedirectPromiseMeasurement: "handleRedirectPromise", + HandleNativeRedirectPromiseMeasurement: "handleNativeRedirectPromise", + UpdateCloudDiscoveryMetadataMeasurement: "updateCloudDiscoveryMetadataMeasurement", + UsernamePasswordClientAcquireToken: "usernamePasswordClientAcquireToken", + NativeMessageHandlerHandshake: "nativeMessageHandlerHandshake", + NativeGenerateAuthResult: "nativeGenerateAuthResult", + RemoveHiddenIframe: "removeHiddenIframe", + /** + * Cache operations + */ + ClearTokensAndKeysWithClaims: "clearTokensAndKeysWithClaims", + CacheManagerGetRefreshToken: "cacheManagerGetRefreshToken", + ImportExistingCache: "importExistingCache", + SetUserData: "setUserData", + LocalStorageUpdated: "localStorageUpdated", + /** + * Crypto Operations + */ + GeneratePkceCodes: "generatePkceCodes", + GenerateCodeVerifier: "generateCodeVerifier", + GenerateCodeChallengeFromVerifier: "generateCodeChallengeFromVerifier", + Sha256Digest: "sha256Digest", + GetRandomValues: "getRandomValues", + GenerateHKDF: "generateHKDF", + GenerateBaseKey: "generateBaseKey", + Base64Decode: "base64Decode", + UrlEncodeArr: "urlEncodeArr", + Encrypt: "encrypt", + Decrypt: "decrypt", + GenerateEarKey: "generateEarKey", + DecryptEarResponse: "decryptEarResponse", +}; +const PerformanceEventAbbreviations = new Map([ + [PerformanceEvents.AcquireTokenByCode, "ATByCode"], + [PerformanceEvents.AcquireTokenByRefreshToken, "ATByRT"], + [PerformanceEvents.AcquireTokenSilent, "ATS"], + [PerformanceEvents.AcquireTokenSilentAsync, "ATSAsync"], + [PerformanceEvents.AcquireTokenPopup, "ATPopup"], + [PerformanceEvents.AcquireTokenRedirect, "ATRedirect"], + [ + PerformanceEvents.CryptoOptsGetPublicKeyThumbprint, + "CryptoGetPKThumb", + ], + [PerformanceEvents.CryptoOptsSignJwt, "CryptoSignJwt"], + [PerformanceEvents.SilentCacheClientAcquireToken, "SltCacheClientAT"], + [PerformanceEvents.SilentIframeClientAcquireToken, "SltIframeClientAT"], + [PerformanceEvents.SilentRefreshClientAcquireToken, "SltRClientAT"], + [PerformanceEvents.SsoSilent, "SsoSlt"], + [ + PerformanceEvents.StandardInteractionClientGetDiscoveredAuthority, + "StdIntClientGetDiscAuth", + ], + [ + PerformanceEvents.FetchAccountIdWithNativeBroker, + "FetchAccIdWithNtvBroker", + ], + [ + PerformanceEvents.NativeInteractionClientAcquireToken, + "NtvIntClientAT", + ], + [ + PerformanceEvents.BaseClientCreateTokenRequestHeaders, + "BaseClientCreateTReqHead", + ], + [ + PerformanceEvents.NetworkClientSendPostRequestAsync, + "NetClientSendPost", + ], + [ + PerformanceEvents.RefreshTokenClientExecutePostToTokenEndpoint, + "RTClientExecPost", + ], + [ + PerformanceEvents.AuthorizationCodeClientExecutePostToTokenEndpoint, + "AuthCodeClientExecPost", + ], + [PerformanceEvents.BrokerHandhshake, "BrokerHandshake"], + [ + PerformanceEvents.AcquireTokenByRefreshTokenInBroker, + "ATByRTInBroker", + ], + [PerformanceEvents.AcquireTokenByBroker, "ATByBroker"], + [ + PerformanceEvents.RefreshTokenClientExecuteTokenRequest, + "RTClientExecTReq", + ], + [PerformanceEvents.RefreshTokenClientAcquireToken, "RTClientAT"], + [ + PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken, + "RTClientATWithCachedRT", + ], + [ + PerformanceEvents.RefreshTokenClientAcquireTokenByRefreshToken, + "RTClientATByRT", + ], + [ + PerformanceEvents.RefreshTokenClientCreateTokenRequestBody, + "RTClientCreateTReqBody", + ], + [PerformanceEvents.AcquireTokenFromCache, "ATFromCache"], + [ + PerformanceEvents.SilentFlowClientAcquireCachedToken, + "SltFlowClientATCached", + ], + [ + PerformanceEvents.SilentFlowClientGenerateResultFromCacheRecord, + "SltFlowClientGenResFromCache", + ], + [PerformanceEvents.AcquireTokenBySilentIframe, "ATBySltIframe"], + [PerformanceEvents.InitializeBaseRequest, "InitBaseReq"], + [PerformanceEvents.InitializeSilentRequest, "InitSltReq"], + [ + PerformanceEvents.InitializeClientApplication, + "InitClientApplication", + ], + [PerformanceEvents.InitializeCache, "InitCache"], + [PerformanceEvents.ImportExistingCache, "importCache"], + [PerformanceEvents.SetUserData, "setUserData"], + [PerformanceEvents.LocalStorageUpdated, "localStorageUpdated"], + [PerformanceEvents.SilentIframeClientTokenHelper, "SIClientTHelper"], + [ + PerformanceEvents.SilentHandlerInitiateAuthRequest, + "SHandlerInitAuthReq", + ], + [ + PerformanceEvents.SilentHandlerMonitorIframeForHash, + "SltHandlerMonitorIframeForHash", + ], + [PerformanceEvents.SilentHandlerLoadFrame, "SHandlerLoadFrame"], + [PerformanceEvents.SilentHandlerLoadFrameSync, "SHandlerLoadFrameSync"], + [ + PerformanceEvents.StandardInteractionClientCreateAuthCodeClient, + "StdIntClientCreateAuthCodeClient", + ], + [ + PerformanceEvents.StandardInteractionClientGetClientConfiguration, + "StdIntClientGetClientConf", + ], + [ + PerformanceEvents.StandardInteractionClientInitializeAuthorizationRequest, + "StdIntClientInitAuthReq", + ], + [PerformanceEvents.GetAuthCodeUrl, "GetAuthCodeUrl"], + [ + PerformanceEvents.HandleCodeResponseFromServer, + "HandleCodeResFromServer", + ], + [PerformanceEvents.HandleCodeResponse, "HandleCodeResp"], + [PerformanceEvents.HandleResponseEar, "HandleRespEar"], + [PerformanceEvents.HandleResponseCode, "HandleRespCode"], + [ + PerformanceEvents.HandleResponsePlatformBroker, + "HandleRespPlatBroker", + ], + [PerformanceEvents.UpdateTokenEndpointAuthority, "UpdTEndpointAuth"], + [PerformanceEvents.AuthClientAcquireToken, "AuthClientAT"], + [PerformanceEvents.AuthClientExecuteTokenRequest, "AuthClientExecTReq"], + [ + PerformanceEvents.AuthClientCreateTokenRequestBody, + "AuthClientCreateTReqBody", + ], + [PerformanceEvents.PopTokenGenerateCnf, "PopTGenCnf"], + [PerformanceEvents.PopTokenGenerateKid, "PopTGenKid"], + [PerformanceEvents.HandleServerTokenResponse, "HandleServerTRes"], + [PerformanceEvents.DeserializeResponse, "DeserializeRes"], + [ + PerformanceEvents.AuthorityFactoryCreateDiscoveredInstance, + "AuthFactCreateDiscInst", + ], + [ + PerformanceEvents.AuthorityResolveEndpointsAsync, + "AuthResolveEndpointsAsync", + ], + [ + PerformanceEvents.AuthorityResolveEndpointsFromLocalSources, + "AuthResolveEndpointsFromLocal", + ], + [ + PerformanceEvents.AuthorityGetCloudDiscoveryMetadataFromNetwork, + "AuthGetCDMetaFromNet", + ], + [ + PerformanceEvents.AuthorityUpdateCloudDiscoveryMetadata, + "AuthUpdCDMeta", + ], + [ + PerformanceEvents.AuthorityGetEndpointMetadataFromNetwork, + "AuthUpdCDMetaFromNet", + ], + [ + PerformanceEvents.AuthorityUpdateEndpointMetadata, + "AuthUpdEndpointMeta", + ], + [ + PerformanceEvents.AuthorityUpdateMetadataWithRegionalInformation, + "AuthUpdMetaWithRegInfo", + ], + [PerformanceEvents.RegionDiscoveryDetectRegion, "RegDiscDetectReg"], + [ + PerformanceEvents.RegionDiscoveryGetRegionFromIMDS, + "RegDiscGetRegFromIMDS", + ], + [ + PerformanceEvents.RegionDiscoveryGetCurrentVersion, + "RegDiscGetCurrentVer", + ], + [PerformanceEvents.AcquireTokenByCodeAsync, "ATByCodeAsync"], + [ + PerformanceEvents.GetEndpointMetadataFromNetwork, + "GetEndpointMetaFromNet", + ], + [ + PerformanceEvents.GetCloudDiscoveryMetadataFromNetworkMeasurement, + "GetCDMetaFromNet", + ], + [ + PerformanceEvents.HandleRedirectPromiseMeasurement, + "HandleRedirectPromise", + ], + [ + PerformanceEvents.HandleNativeRedirectPromiseMeasurement, + "HandleNtvRedirectPromise", + ], + [ + PerformanceEvents.UpdateCloudDiscoveryMetadataMeasurement, + "UpdateCDMeta", + ], + [ + PerformanceEvents.UsernamePasswordClientAcquireToken, + "UserPassClientAT", + ], + [ + PerformanceEvents.NativeMessageHandlerHandshake, + "NtvMsgHandlerHandshake", + ], + [PerformanceEvents.NativeGenerateAuthResult, "NtvGenAuthRes"], + [PerformanceEvents.RemoveHiddenIframe, "RemoveHiddenIframe"], + [ + PerformanceEvents.ClearTokensAndKeysWithClaims, + "ClearTAndKeysWithClaims", + ], + [PerformanceEvents.CacheManagerGetRefreshToken, "CacheManagerGetRT"], + [PerformanceEvents.GeneratePkceCodes, "GenPkceCodes"], + [PerformanceEvents.GenerateCodeVerifier, "GenCodeVerifier"], + [ + PerformanceEvents.GenerateCodeChallengeFromVerifier, + "GenCodeChallengeFromVerifier", + ], + [PerformanceEvents.Sha256Digest, "Sha256Digest"], + [PerformanceEvents.GetRandomValues, "GetRandomValues"], + [PerformanceEvents.GenerateHKDF, "genHKDF"], + [PerformanceEvents.GenerateBaseKey, "genBaseKey"], + [PerformanceEvents.Base64Decode, "b64Decode"], + [PerformanceEvents.UrlEncodeArr, "urlEncArr"], + [PerformanceEvents.Encrypt, "encrypt"], + [PerformanceEvents.Decrypt, "decrypt"], + [PerformanceEvents.GenerateEarKey, "genEarKey"], + [PerformanceEvents.DecryptEarResponse, "decryptEarResp"], +]); +/** + * State of the performance event. + * + * @export + * @enum {number} + */ +const PerformanceEventStatus = { + NotStarted: 0, + InProgress: 1, + Completed: 2, +}; +const IntFields = new Set([ + "accessTokenSize", + "durationMs", + "idTokenSize", + "matsSilentStatus", + "matsHttpStatus", + "refreshTokenSize", + "queuedTimeMs", + "startTimeMs", + "status", + "multiMatchedAT", + "multiMatchedID", + "multiMatchedRT", + "unencryptedCacheCount", + "encryptedCacheExpiredCount", + "oldAccountCount", + "oldAccessCount", + "oldIdCount", + "oldRefreshCount", + "currAccountCount", + "currAccessCount", + "currIdCount", + "currRefreshCount", + "expiredCacheRemovedCount", + "upgradedCacheCount", +]); + +export { IntFields, PerformanceEventAbbreviations, PerformanceEventStatus, PerformanceEvents }; +//# sourceMappingURL=PerformanceEvent.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/telemetry/performance/StubPerformanceClient.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/telemetry/performance/StubPerformanceClient.mjs new file mode 100644 index 00000000..4d6ce0ad --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/telemetry/performance/StubPerformanceClient.mjs @@ -0,0 +1,83 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +import { PerformanceEventStatus } from './PerformanceEvent.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +class StubPerformanceMeasurement { + startMeasurement() { + return; + } + endMeasurement() { + return; + } + flushMeasurement() { + return null; + } +} +class StubPerformanceClient { + generateId() { + return "callback-id"; + } + startMeasurement(measureName, correlationId) { + return { + end: () => null, + discard: () => { }, + add: () => { }, + increment: () => { }, + event: { + eventId: this.generateId(), + status: PerformanceEventStatus.InProgress, + authority: "", + libraryName: "", + libraryVersion: "", + clientId: "", + name: measureName, + startTimeMs: Date.now(), + correlationId: correlationId || "", + }, + measurement: new StubPerformanceMeasurement(), + }; + } + startPerformanceMeasurement() { + return new StubPerformanceMeasurement(); + } + calculateQueuedTime() { + return 0; + } + addQueueMeasurement() { + return; + } + setPreQueueTime() { + return; + } + endMeasurement() { + return null; + } + discardMeasurements() { + return; + } + removePerformanceCallback() { + return true; + } + addPerformanceCallback() { + return ""; + } + emitEvents() { + return; + } + addFields() { + return; + } + incrementFields() { + return; + } + cacheEventByCorrelationId() { + return; + } +} + +export { StubPerformanceClient, StubPerformanceMeasurement }; +//# sourceMappingURL=StubPerformanceClient.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/telemetry/server/ServerTelemetryManager.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/telemetry/server/ServerTelemetryManager.mjs new file mode 100644 index 00000000..8f731d00 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/telemetry/server/ServerTelemetryManager.mjs @@ -0,0 +1,268 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +import { CacheOutcome, Constants, SERVER_TELEM_CONSTANTS, Separators } from '../../utils/Constants.mjs'; +import { AuthError } from '../../error/AuthError.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +const skuGroupSeparator = ","; +const skuValueSeparator = "|"; +function makeExtraSkuString(params) { + const { skus, libraryName, libraryVersion, extensionName, extensionVersion, } = params; + const skuMap = new Map([ + [0, [libraryName, libraryVersion]], + [2, [extensionName, extensionVersion]], + ]); + let skuArr = []; + if (skus?.length) { + skuArr = skus.split(skuGroupSeparator); + // Ignore invalid input sku param + if (skuArr.length < 4) { + return skus; + } + } + else { + skuArr = Array.from({ length: 4 }, () => skuValueSeparator); + } + skuMap.forEach((value, key) => { + if (value.length === 2 && value[0]?.length && value[1]?.length) { + setSku({ + skuArr, + index: key, + skuName: value[0], + skuVersion: value[1], + }); + } + }); + return skuArr.join(skuGroupSeparator); +} +function setSku(params) { + const { skuArr, index, skuName, skuVersion } = params; + if (index >= skuArr.length) { + return; + } + skuArr[index] = [skuName, skuVersion].join(skuValueSeparator); +} +/** @internal */ +class ServerTelemetryManager { + constructor(telemetryRequest, cacheManager) { + this.cacheOutcome = CacheOutcome.NOT_APPLICABLE; + this.cacheManager = cacheManager; + this.apiId = telemetryRequest.apiId; + this.correlationId = telemetryRequest.correlationId; + this.wrapperSKU = telemetryRequest.wrapperSKU || Constants.EMPTY_STRING; + this.wrapperVer = telemetryRequest.wrapperVer || Constants.EMPTY_STRING; + this.telemetryCacheKey = + SERVER_TELEM_CONSTANTS.CACHE_KEY + + Separators.CACHE_KEY_SEPARATOR + + telemetryRequest.clientId; + } + /** + * API to add MSER Telemetry to request + */ + generateCurrentRequestHeaderValue() { + const request = `${this.apiId}${SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR}${this.cacheOutcome}`; + const platformFieldsArr = [this.wrapperSKU, this.wrapperVer]; + const nativeBrokerErrorCode = this.getNativeBrokerErrorCode(); + if (nativeBrokerErrorCode?.length) { + platformFieldsArr.push(`broker_error=${nativeBrokerErrorCode}`); + } + const platformFields = platformFieldsArr.join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR); + const regionDiscoveryFields = this.getRegionDiscoveryFields(); + const requestWithRegionDiscoveryFields = [ + request, + regionDiscoveryFields, + ].join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR); + return [ + SERVER_TELEM_CONSTANTS.SCHEMA_VERSION, + requestWithRegionDiscoveryFields, + platformFields, + ].join(SERVER_TELEM_CONSTANTS.CATEGORY_SEPARATOR); + } + /** + * API to add MSER Telemetry for the last failed request + */ + generateLastRequestHeaderValue() { + const lastRequests = this.getLastRequests(); + const maxErrors = ServerTelemetryManager.maxErrorsToSend(lastRequests); + const failedRequests = lastRequests.failedRequests + .slice(0, 2 * maxErrors) + .join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR); + const errors = lastRequests.errors + .slice(0, maxErrors) + .join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR); + const errorCount = lastRequests.errors.length; + // Indicate whether this header contains all data or partial data + const overflow = maxErrors < errorCount + ? SERVER_TELEM_CONSTANTS.OVERFLOW_TRUE + : SERVER_TELEM_CONSTANTS.OVERFLOW_FALSE; + const platformFields = [errorCount, overflow].join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR); + return [ + SERVER_TELEM_CONSTANTS.SCHEMA_VERSION, + lastRequests.cacheHits, + failedRequests, + errors, + platformFields, + ].join(SERVER_TELEM_CONSTANTS.CATEGORY_SEPARATOR); + } + /** + * API to cache token failures for MSER data capture + * @param error + */ + cacheFailedRequest(error) { + const lastRequests = this.getLastRequests(); + if (lastRequests.errors.length >= + SERVER_TELEM_CONSTANTS.MAX_CACHED_ERRORS) { + // Remove a cached error to make room, first in first out + lastRequests.failedRequests.shift(); // apiId + lastRequests.failedRequests.shift(); // correlationId + lastRequests.errors.shift(); + } + lastRequests.failedRequests.push(this.apiId, this.correlationId); + if (error instanceof Error && !!error && error.toString()) { + if (error instanceof AuthError) { + if (error.subError) { + lastRequests.errors.push(error.subError); + } + else if (error.errorCode) { + lastRequests.errors.push(error.errorCode); + } + else { + lastRequests.errors.push(error.toString()); + } + } + else { + lastRequests.errors.push(error.toString()); + } + } + else { + lastRequests.errors.push(SERVER_TELEM_CONSTANTS.UNKNOWN_ERROR); + } + this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests, this.correlationId); + return; + } + /** + * Update server telemetry cache entry by incrementing cache hit counter + */ + incrementCacheHits() { + const lastRequests = this.getLastRequests(); + lastRequests.cacheHits += 1; + this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests, this.correlationId); + return lastRequests.cacheHits; + } + /** + * Get the server telemetry entity from cache or initialize a new one + */ + getLastRequests() { + const initialValue = { + failedRequests: [], + errors: [], + cacheHits: 0, + }; + const lastRequests = this.cacheManager.getServerTelemetry(this.telemetryCacheKey); + return lastRequests || initialValue; + } + /** + * Remove server telemetry cache entry + */ + clearTelemetryCache() { + const lastRequests = this.getLastRequests(); + const numErrorsFlushed = ServerTelemetryManager.maxErrorsToSend(lastRequests); + const errorCount = lastRequests.errors.length; + if (numErrorsFlushed === errorCount) { + // All errors were sent on last request, clear Telemetry cache + this.cacheManager.removeItem(this.telemetryCacheKey, this.correlationId); + } + else { + // Partial data was flushed to server, construct a new telemetry cache item with errors that were not flushed + const serverTelemEntity = { + failedRequests: lastRequests.failedRequests.slice(numErrorsFlushed * 2), + errors: lastRequests.errors.slice(numErrorsFlushed), + cacheHits: 0, + }; + this.cacheManager.setServerTelemetry(this.telemetryCacheKey, serverTelemEntity, this.correlationId); + } + } + /** + * Returns the maximum number of errors that can be flushed to the server in the next network request + * @param serverTelemetryEntity + */ + static maxErrorsToSend(serverTelemetryEntity) { + let i; + let maxErrors = 0; + let dataSize = 0; + const errorCount = serverTelemetryEntity.errors.length; + for (i = 0; i < errorCount; i++) { + // failedRequests parameter contains pairs of apiId and correlationId, multiply index by 2 to preserve pairs + const apiId = serverTelemetryEntity.failedRequests[2 * i] || + Constants.EMPTY_STRING; + const correlationId = serverTelemetryEntity.failedRequests[2 * i + 1] || + Constants.EMPTY_STRING; + const errorCode = serverTelemetryEntity.errors[i] || Constants.EMPTY_STRING; + // Count number of characters that would be added to header, each character is 1 byte. Add 3 at the end to account for separators + dataSize += + apiId.toString().length + + correlationId.toString().length + + errorCode.length + + 3; + if (dataSize < SERVER_TELEM_CONSTANTS.MAX_LAST_HEADER_BYTES) { + // Adding this entry to the header would still keep header size below the limit + maxErrors += 1; + } + else { + break; + } + } + return maxErrors; + } + /** + * Get the region discovery fields + * + * @returns string + */ + getRegionDiscoveryFields() { + const regionDiscoveryFields = []; + regionDiscoveryFields.push(this.regionUsed || Constants.EMPTY_STRING); + regionDiscoveryFields.push(this.regionSource || Constants.EMPTY_STRING); + regionDiscoveryFields.push(this.regionOutcome || Constants.EMPTY_STRING); + return regionDiscoveryFields.join(","); + } + /** + * Update the region discovery metadata + * + * @param regionDiscoveryMetadata + * @returns void + */ + updateRegionDiscoveryMetadata(regionDiscoveryMetadata) { + this.regionUsed = regionDiscoveryMetadata.region_used; + this.regionSource = regionDiscoveryMetadata.region_source; + this.regionOutcome = regionDiscoveryMetadata.region_outcome; + } + /** + * Set cache outcome + */ + setCacheOutcome(cacheOutcome) { + this.cacheOutcome = cacheOutcome; + } + setNativeBrokerErrorCode(errorCode) { + const lastRequests = this.getLastRequests(); + lastRequests.nativeBrokerErrorCode = errorCode; + this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests, this.correlationId); + } + getNativeBrokerErrorCode() { + return this.getLastRequests().nativeBrokerErrorCode; + } + clearNativeBrokerErrorCode() { + const lastRequests = this.getLastRequests(); + delete lastRequests.nativeBrokerErrorCode; + this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests, this.correlationId); + } + static makeExtraSkuString(params) { + return makeExtraSkuString(params); + } +} + +export { ServerTelemetryManager }; +//# sourceMappingURL=ServerTelemetryManager.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/url/UrlString.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/url/UrlString.mjs new file mode 100644 index 00000000..902f732e --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/url/UrlString.mjs @@ -0,0 +1,172 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +import { createClientConfigurationError } from '../error/ClientConfigurationError.mjs'; +import { StringUtils } from '../utils/StringUtils.mjs'; +import { AADAuthorityConstants, Constants } from '../utils/Constants.mjs'; +import { getDeserializedResponse } from '../utils/UrlUtils.mjs'; +import { urlEmptyError, urlParseError, authorityUriInsecure } from '../error/ClientConfigurationErrorCodes.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * Url object class which can perform various transformations on url strings. + */ +class UrlString { + get urlString() { + return this._urlString; + } + constructor(url) { + this._urlString = url; + if (!this._urlString) { + // Throws error if url is empty + throw createClientConfigurationError(urlEmptyError); + } + if (!url.includes("#")) { + this._urlString = UrlString.canonicalizeUri(url); + } + } + /** + * Ensure urls are lower case and end with a / character. + * @param url + */ + static canonicalizeUri(url) { + if (url) { + let lowerCaseUrl = url.toLowerCase(); + if (StringUtils.endsWith(lowerCaseUrl, "?")) { + lowerCaseUrl = lowerCaseUrl.slice(0, -1); + } + else if (StringUtils.endsWith(lowerCaseUrl, "?/")) { + lowerCaseUrl = lowerCaseUrl.slice(0, -2); + } + if (!StringUtils.endsWith(lowerCaseUrl, "/")) { + lowerCaseUrl += "/"; + } + return lowerCaseUrl; + } + return url; + } + /** + * Throws if urlString passed is not a valid authority URI string. + */ + validateAsUri() { + // Attempts to parse url for uri components + let components; + try { + components = this.getUrlComponents(); + } + catch (e) { + throw createClientConfigurationError(urlParseError); + } + // Throw error if URI or path segments are not parseable. + if (!components.HostNameAndPort || !components.PathSegments) { + throw createClientConfigurationError(urlParseError); + } + // Throw error if uri is insecure. + if (!components.Protocol || + components.Protocol.toLowerCase() !== "https:") { + throw createClientConfigurationError(authorityUriInsecure); + } + } + /** + * Given a url and a query string return the url with provided query string appended + * @param url + * @param queryString + */ + static appendQueryString(url, queryString) { + if (!queryString) { + return url; + } + return url.indexOf("?") < 0 + ? `${url}?${queryString}` + : `${url}&${queryString}`; + } + /** + * Returns a url with the hash removed + * @param url + */ + static removeHashFromUrl(url) { + return UrlString.canonicalizeUri(url.split("#")[0]); + } + /** + * Given a url like https://a:b/common/d?e=f#g, and a tenantId, returns https://a:b/tenantId/d + * @param href The url + * @param tenantId The tenant id to replace + */ + replaceTenantPath(tenantId) { + const urlObject = this.getUrlComponents(); + const pathArray = urlObject.PathSegments; + if (tenantId && + pathArray.length !== 0 && + (pathArray[0] === AADAuthorityConstants.COMMON || + pathArray[0] === AADAuthorityConstants.ORGANIZATIONS)) { + pathArray[0] = tenantId; + } + return UrlString.constructAuthorityUriFromObject(urlObject); + } + /** + * Parses out the components from a url string. + * @returns An object with the various components. Please cache this value insted of calling this multiple times on the same url. + */ + getUrlComponents() { + // https://gist.github.com/curtisz/11139b2cfcaef4a261e0 + const regEx = RegExp("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?"); + // If url string does not match regEx, we throw an error + const match = this.urlString.match(regEx); + if (!match) { + throw createClientConfigurationError(urlParseError); + } + // Url component object + const urlComponents = { + Protocol: match[1], + HostNameAndPort: match[4], + AbsolutePath: match[5], + QueryString: match[7], + }; + let pathSegments = urlComponents.AbsolutePath.split("/"); + pathSegments = pathSegments.filter((val) => val && val.length > 0); // remove empty elements + urlComponents.PathSegments = pathSegments; + if (urlComponents.QueryString && + urlComponents.QueryString.endsWith("/")) { + urlComponents.QueryString = urlComponents.QueryString.substring(0, urlComponents.QueryString.length - 1); + } + return urlComponents; + } + static getDomainFromUrl(url) { + const regEx = RegExp("^([^:/?#]+://)?([^/?#]*)"); + const match = url.match(regEx); + if (!match) { + throw createClientConfigurationError(urlParseError); + } + return match[2]; + } + static getAbsoluteUrl(relativeUrl, baseUrl) { + if (relativeUrl[0] === Constants.FORWARD_SLASH) { + const url = new UrlString(baseUrl); + const baseComponents = url.getUrlComponents(); + return (baseComponents.Protocol + + "//" + + baseComponents.HostNameAndPort + + relativeUrl); + } + return relativeUrl; + } + static constructAuthorityUriFromObject(urlObject) { + return new UrlString(urlObject.Protocol + + "//" + + urlObject.HostNameAndPort + + "/" + + urlObject.PathSegments.join("/")); + } + /** + * Check if the hash of the URL string contains known properties + * @deprecated This API will be removed in a future version + */ + static hashContainsKnownProperties(response) { + return !!getDeserializedResponse(response); + } +} + +export { UrlString }; +//# sourceMappingURL=UrlString.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/utils/ClientAssertionUtils.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/utils/ClientAssertionUtils.mjs new file mode 100644 index 00000000..9e8cce70 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/utils/ClientAssertionUtils.mjs @@ -0,0 +1,21 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +async function getClientAssertion(clientAssertion, clientId, tokenEndpoint) { + if (typeof clientAssertion === "string") { + return clientAssertion; + } + else { + const config = { + clientId: clientId, + tokenEndpoint: tokenEndpoint, + }; + return clientAssertion(config); + } +} + +export { getClientAssertion }; +//# sourceMappingURL=ClientAssertionUtils.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/utils/Constants.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/utils/Constants.mjs new file mode 100644 index 00000000..5b296da1 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/utils/Constants.mjs @@ -0,0 +1,325 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +const Constants = { + LIBRARY_NAME: "MSAL.JS", + SKU: "msal.js.common", + // default authority + DEFAULT_AUTHORITY: "https://login.microsoftonline.com/common/", + DEFAULT_AUTHORITY_HOST: "login.microsoftonline.com", + DEFAULT_COMMON_TENANT: "common", + // ADFS String + ADFS: "adfs", + DSTS: "dstsv2", + // Default AAD Instance Discovery Endpoint + AAD_INSTANCE_DISCOVERY_ENDPT: "https://login.microsoftonline.com/common/discovery/instance?api-version=1.1&authorization_endpoint=", + // CIAM URL + CIAM_AUTH_URL: ".ciamlogin.com", + AAD_TENANT_DOMAIN_SUFFIX: ".onmicrosoft.com", + // Resource delimiter - used for certain cache entries + RESOURCE_DELIM: "|", + // Placeholder for non-existent account ids/objects + NO_ACCOUNT: "NO_ACCOUNT", + // Claims + CLAIMS: "claims", + // Consumer UTID + CONSUMER_UTID: "9188040d-6c67-4c5b-b112-36a304b66dad", + // Default scopes + OPENID_SCOPE: "openid", + PROFILE_SCOPE: "profile", + OFFLINE_ACCESS_SCOPE: "offline_access", + EMAIL_SCOPE: "email", + CODE_GRANT_TYPE: "authorization_code", + RT_GRANT_TYPE: "refresh_token", + S256_CODE_CHALLENGE_METHOD: "S256", + URL_FORM_CONTENT_TYPE: "application/x-www-form-urlencoded;charset=utf-8", + AUTHORIZATION_PENDING: "authorization_pending", + NOT_DEFINED: "not_defined", + EMPTY_STRING: "", + NOT_APPLICABLE: "N/A", + NOT_AVAILABLE: "Not Available", + FORWARD_SLASH: "/", + IMDS_ENDPOINT: "http://169.254.169.254/metadata/instance/compute/location", + IMDS_VERSION: "2020-06-01", + IMDS_TIMEOUT: 2000, + AZURE_REGION_AUTO_DISCOVER_FLAG: "TryAutoDetect", + REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX: "login.microsoft.com", + KNOWN_PUBLIC_CLOUDS: [ + "login.microsoftonline.com", + "login.windows.net", + "login.microsoft.com", + "sts.windows.net", + ], + SHR_NONCE_VALIDITY: 240, + INVALID_INSTANCE: "invalid_instance", +}; +const HttpStatus = { + SUCCESS: 200, + SUCCESS_RANGE_START: 200, + SUCCESS_RANGE_END: 299, + REDIRECT: 302, + CLIENT_ERROR: 400, + CLIENT_ERROR_RANGE_START: 400, + BAD_REQUEST: 400, + UNAUTHORIZED: 401, + NOT_FOUND: 404, + REQUEST_TIMEOUT: 408, + GONE: 410, + TOO_MANY_REQUESTS: 429, + CLIENT_ERROR_RANGE_END: 499, + SERVER_ERROR: 500, + SERVER_ERROR_RANGE_START: 500, + SERVICE_UNAVAILABLE: 503, + GATEWAY_TIMEOUT: 504, + SERVER_ERROR_RANGE_END: 599, + MULTI_SIDED_ERROR: 600, +}; +const HttpMethod = { + GET: "GET", + POST: "POST", +}; +const OIDC_DEFAULT_SCOPES = [ + Constants.OPENID_SCOPE, + Constants.PROFILE_SCOPE, + Constants.OFFLINE_ACCESS_SCOPE, +]; +const OIDC_SCOPES = [...OIDC_DEFAULT_SCOPES, Constants.EMAIL_SCOPE]; +/** + * Request header names + */ +const HeaderNames = { + CONTENT_TYPE: "Content-Type", + CONTENT_LENGTH: "Content-Length", + RETRY_AFTER: "Retry-After", + CCS_HEADER: "X-AnchorMailbox", + WWWAuthenticate: "WWW-Authenticate", + AuthenticationInfo: "Authentication-Info", + X_MS_REQUEST_ID: "x-ms-request-id", + X_MS_HTTP_VERSION: "x-ms-httpver", +}; +/** + * Persistent cache keys MSAL which stay while user is logged in. + */ +const PersistentCacheKeys = { + ACTIVE_ACCOUNT_FILTERS: "active-account-filters", // new cache entry for active_account for a more robust version for browser +}; +/** + * String constants related to AAD Authority + */ +const AADAuthorityConstants = { + COMMON: "common", + ORGANIZATIONS: "organizations", + CONSUMERS: "consumers", +}; +/** + * Claims request keys + */ +const ClaimsRequestKeys = { + ACCESS_TOKEN: "access_token", + XMS_CC: "xms_cc", +}; +/** + * we considered making this "enum" in the request instead of string, however it looks like the allowed list of + * prompt values kept changing over past couple of years. There are some undocumented prompt values for some + * internal partners too, hence the choice of generic "string" type instead of the "enum" + */ +const PromptValue = { + LOGIN: "login", + SELECT_ACCOUNT: "select_account", + CONSENT: "consent", + NONE: "none", + CREATE: "create", + NO_SESSION: "no_session", +}; +/** + * allowed values for codeVerifier + */ +const CodeChallengeMethodValues = { + PLAIN: "plain", + S256: "S256", +}; +/** + * Allowed values for response_type + */ +const OAuthResponseType = { + CODE: "code", + IDTOKEN_TOKEN: "id_token token", + IDTOKEN_TOKEN_REFRESHTOKEN: "id_token token refresh_token", +}; +/** + * allowed values for server response type + * @deprecated Use ResponseMode instead + */ +const ServerResponseType = { + QUERY: "query", + FRAGMENT: "fragment", +}; +/** + * allowed values for response_mode + */ +const ResponseMode = { + QUERY: "query", + FRAGMENT: "fragment", + FORM_POST: "form_post", +}; +/** + * allowed grant_type + */ +const GrantType = { + IMPLICIT_GRANT: "implicit", + AUTHORIZATION_CODE_GRANT: "authorization_code", + CLIENT_CREDENTIALS_GRANT: "client_credentials", + RESOURCE_OWNER_PASSWORD_GRANT: "password", + REFRESH_TOKEN_GRANT: "refresh_token", + DEVICE_CODE_GRANT: "device_code", + JWT_BEARER: "urn:ietf:params:oauth:grant-type:jwt-bearer", +}; +/** + * Account types in Cache + */ +const CacheAccountType = { + MSSTS_ACCOUNT_TYPE: "MSSTS", + ADFS_ACCOUNT_TYPE: "ADFS", + MSAV1_ACCOUNT_TYPE: "MSA", + GENERIC_ACCOUNT_TYPE: "Generic", // NTLM, Kerberos, FBA, Basic etc +}; +/** + * Separators used in cache + */ +const Separators = { + CACHE_KEY_SEPARATOR: "-", + CLIENT_INFO_SEPARATOR: ".", +}; +/** + * Credential Type stored in the cache + */ +const CredentialType = { + ID_TOKEN: "IdToken", + ACCESS_TOKEN: "AccessToken", + ACCESS_TOKEN_WITH_AUTH_SCHEME: "AccessToken_With_AuthScheme", + REFRESH_TOKEN: "RefreshToken", +}; +/** + * Combine all cache types + */ +const CacheType = { + ADFS: 1001, + MSA: 1002, + MSSTS: 1003, + GENERIC: 1004, + ACCESS_TOKEN: 2001, + REFRESH_TOKEN: 2002, + ID_TOKEN: 2003, + APP_METADATA: 3001, + UNDEFINED: 9999, +}; +/** + * More Cache related constants + */ +const APP_METADATA = "appmetadata"; +const CLIENT_INFO = "client_info"; +const THE_FAMILY_ID = "1"; +const AUTHORITY_METADATA_CONSTANTS = { + CACHE_KEY: "authority-metadata", + REFRESH_TIME_SECONDS: 3600 * 24, // 24 Hours +}; +const AuthorityMetadataSource = { + CONFIG: "config", + CACHE: "cache", + NETWORK: "network", + HARDCODED_VALUES: "hardcoded_values", +}; +const SERVER_TELEM_CONSTANTS = { + SCHEMA_VERSION: 5, + MAX_LAST_HEADER_BYTES: 330, + MAX_CACHED_ERRORS: 50, + CACHE_KEY: "server-telemetry", + CATEGORY_SEPARATOR: "|", + VALUE_SEPARATOR: ",", + OVERFLOW_TRUE: "1", + OVERFLOW_FALSE: "0", + UNKNOWN_ERROR: "unknown_error", +}; +/** + * Type of the authentication request + */ +const AuthenticationScheme = { + BEARER: "Bearer", + POP: "pop", + SSH: "ssh-cert", +}; +/** + * Constants related to throttling + */ +const ThrottlingConstants = { + // Default time to throttle RequestThumbprint in seconds + DEFAULT_THROTTLE_TIME_SECONDS: 60, + // Default maximum time to throttle in seconds, overrides what the server sends back + DEFAULT_MAX_THROTTLE_TIME_SECONDS: 3600, + // Prefix for storing throttling entries + THROTTLING_PREFIX: "throttling", + // Value assigned to the x-ms-lib-capability header to indicate to the server the library supports throttling + X_MS_LIB_CAPABILITY_VALUE: "retry-after, h429", +}; +const Errors = { + INVALID_GRANT_ERROR: "invalid_grant", + CLIENT_MISMATCH_ERROR: "client_mismatch", +}; +/** + * Password grant parameters + */ +const PasswordGrantConstants = { + username: "username", + password: "password", +}; +/** + * Region Discovery Sources + */ +const RegionDiscoverySources = { + FAILED_AUTO_DETECTION: "1", + INTERNAL_CACHE: "2", + ENVIRONMENT_VARIABLE: "3", + IMDS: "4", +}; +/** + * Region Discovery Outcomes + */ +const RegionDiscoveryOutcomes = { + CONFIGURED_NO_AUTO_DETECTION: "2", + AUTO_DETECTION_REQUESTED_SUCCESSFUL: "4", + AUTO_DETECTION_REQUESTED_FAILED: "5", +}; +/** + * Specifies the reason for fetching the access token from the identity provider + */ +const CacheOutcome = { + // When a token is found in the cache or the cache is not supposed to be hit when making the request + NOT_APPLICABLE: "0", + // When the token request goes to the identity provider because force_refresh was set to true. Also occurs if claims were requested + FORCE_REFRESH_OR_CLAIMS: "1", + // When the token request goes to the identity provider because no cached access token exists + NO_CACHED_ACCESS_TOKEN: "2", + // When the token request goes to the identity provider because cached access token expired + CACHED_ACCESS_TOKEN_EXPIRED: "3", + // When the token request goes to the identity provider because refresh_in was used and the existing token needs to be refreshed + PROACTIVELY_REFRESHED: "4", +}; +const JsonWebTokenTypes = { + Jwt: "JWT", + Jwk: "JWK", + Pop: "pop", +}; +const ONE_DAY_IN_MS = 86400000; +// Token renewal offset default in seconds +const DEFAULT_TOKEN_RENEWAL_OFFSET_SEC = 300; +const EncodingTypes = { + BASE64: "base64", + HEX: "hex", + UTF8: "utf-8", +}; + +export { AADAuthorityConstants, APP_METADATA, AUTHORITY_METADATA_CONSTANTS, AuthenticationScheme, AuthorityMetadataSource, CLIENT_INFO, CacheAccountType, CacheOutcome, CacheType, ClaimsRequestKeys, CodeChallengeMethodValues, Constants, CredentialType, DEFAULT_TOKEN_RENEWAL_OFFSET_SEC, EncodingTypes, Errors, GrantType, HeaderNames, HttpMethod, HttpStatus, JsonWebTokenTypes, OAuthResponseType, OIDC_DEFAULT_SCOPES, OIDC_SCOPES, ONE_DAY_IN_MS, PasswordGrantConstants, PersistentCacheKeys, PromptValue, RegionDiscoveryOutcomes, RegionDiscoverySources, ResponseMode, SERVER_TELEM_CONSTANTS, Separators, ServerResponseType, THE_FAMILY_ID, ThrottlingConstants }; +//# sourceMappingURL=Constants.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/utils/FunctionWrappers.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/utils/FunctionWrappers.mjs new file mode 100644 index 00000000..3b048c8a --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/utils/FunctionWrappers.mjs @@ -0,0 +1,99 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * Wraps a function with a performance measurement. + * Usage: invoke(functionToCall, performanceClient, "EventName", "correlationId")(...argsToPassToFunction) + * @param callback + * @param eventName + * @param logger + * @param telemetryClient + * @param correlationId + * @returns + * @internal + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const invoke = (callback, eventName, logger, telemetryClient, correlationId) => { + return (...args) => { + logger.trace(`Executing function ${eventName}`); + const inProgressEvent = telemetryClient?.startMeasurement(eventName, correlationId); + if (correlationId) { + // Track number of times this API is called in a single request + const eventCount = eventName + "CallCount"; + telemetryClient?.incrementFields({ [eventCount]: 1 }, correlationId); + } + try { + const result = callback(...args); + inProgressEvent?.end({ + success: true, + }); + logger.trace(`Returning result from ${eventName}`); + return result; + } + catch (e) { + logger.trace(`Error occurred in ${eventName}`); + try { + logger.trace(JSON.stringify(e)); + } + catch (e) { + logger.trace("Unable to print error message."); + } + inProgressEvent?.end({ + success: false, + }, e); + throw e; + } + }; +}; +/** + * Wraps an async function with a performance measurement. + * Usage: invokeAsync(functionToCall, performanceClient, "EventName", "correlationId")(...argsToPassToFunction) + * @param callback + * @param eventName + * @param logger + * @param telemetryClient + * @param correlationId + * @returns + * @internal + * + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const invokeAsync = (callback, eventName, logger, telemetryClient, correlationId) => { + return (...args) => { + logger.trace(`Executing function ${eventName}`); + const inProgressEvent = telemetryClient?.startMeasurement(eventName, correlationId); + if (correlationId) { + // Track number of times this API is called in a single request + const eventCount = eventName + "CallCount"; + telemetryClient?.incrementFields({ [eventCount]: 1 }, correlationId); + } + telemetryClient?.setPreQueueTime(eventName, correlationId); + return callback(...args) + .then((response) => { + logger.trace(`Returning result from ${eventName}`); + inProgressEvent?.end({ + success: true, + }); + return response; + }) + .catch((e) => { + logger.trace(`Error occurred in ${eventName}`); + try { + logger.trace(JSON.stringify(e)); + } + catch (e) { + logger.trace("Unable to print error message."); + } + inProgressEvent?.end({ + success: false, + }, e); + throw e; + }); + }; +}; + +export { invoke, invokeAsync }; +//# sourceMappingURL=FunctionWrappers.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/utils/ProtocolUtils.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/utils/ProtocolUtils.mjs new file mode 100644 index 00000000..3da8d459 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/utils/ProtocolUtils.mjs @@ -0,0 +1,78 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +import { Constants } from './Constants.mjs'; +import { createClientAuthError } from '../error/ClientAuthError.mjs'; +import { noCryptoObject, invalidState } from '../error/ClientAuthErrorCodes.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * Class which provides helpers for OAuth 2.0 protocol specific values + */ +class ProtocolUtils { + /** + * Appends user state with random guid, or returns random guid. + * @param userState + * @param randomGuid + */ + static setRequestState(cryptoObj, userState, meta) { + const libraryState = ProtocolUtils.generateLibraryState(cryptoObj, meta); + return userState + ? `${libraryState}${Constants.RESOURCE_DELIM}${userState}` + : libraryState; + } + /** + * Generates the state value used by the common library. + * @param randomGuid + * @param cryptoObj + */ + static generateLibraryState(cryptoObj, meta) { + if (!cryptoObj) { + throw createClientAuthError(noCryptoObject); + } + // Create a state object containing a unique id and the timestamp of the request creation + const stateObj = { + id: cryptoObj.createNewGuid(), + }; + if (meta) { + stateObj.meta = meta; + } + const stateString = JSON.stringify(stateObj); + return cryptoObj.base64Encode(stateString); + } + /** + * Parses the state into the RequestStateObject, which contains the LibraryState info and the state passed by the user. + * @param state + * @param cryptoObj + */ + static parseRequestState(cryptoObj, state) { + if (!cryptoObj) { + throw createClientAuthError(noCryptoObject); + } + if (!state) { + throw createClientAuthError(invalidState); + } + try { + // Split the state between library state and user passed state and decode them separately + const splitState = state.split(Constants.RESOURCE_DELIM); + const libraryState = splitState[0]; + const userState = splitState.length > 1 + ? splitState.slice(1).join(Constants.RESOURCE_DELIM) + : Constants.EMPTY_STRING; + const libraryStateString = cryptoObj.base64Decode(libraryState); + const libraryStateObj = JSON.parse(libraryStateString); + return { + userRequestState: userState || Constants.EMPTY_STRING, + libraryState: libraryStateObj, + }; + } + catch (e) { + throw createClientAuthError(invalidState); + } + } +} + +export { ProtocolUtils }; +//# sourceMappingURL=ProtocolUtils.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/utils/StringUtils.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/utils/StringUtils.mjs new file mode 100644 index 00000000..2c870989 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/utils/StringUtils.mjs @@ -0,0 +1,100 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * @hidden + */ +class StringUtils { + /** + * Check if stringified object is empty + * @param strObj + */ + static isEmptyObj(strObj) { + if (strObj) { + try { + const obj = JSON.parse(strObj); + return Object.keys(obj).length === 0; + } + catch (e) { } + } + return true; + } + static startsWith(str, search) { + return str.indexOf(search) === 0; + } + static endsWith(str, search) { + return (str.length >= search.length && + str.lastIndexOf(search) === str.length - search.length); + } + /** + * Parses string into an object. + * + * @param query + */ + static queryStringToObject(query) { + const obj = {}; + const params = query.split("&"); + const decode = (s) => decodeURIComponent(s.replace(/\+/g, " ")); + params.forEach((pair) => { + if (pair.trim()) { + const [key, value] = pair.split(/=(.+)/g, 2); // Split on the first occurence of the '=' character + if (key && value) { + obj[decode(key)] = decode(value); + } + } + }); + return obj; + } + /** + * Trims entries in an array. + * + * @param arr + */ + static trimArrayEntries(arr) { + return arr.map((entry) => entry.trim()); + } + /** + * Removes empty strings from array + * @param arr + */ + static removeEmptyStringsFromArray(arr) { + return arr.filter((entry) => { + return !!entry; + }); + } + /** + * Attempts to parse a string into JSON + * @param str + */ + static jsonParseHelper(str) { + try { + return JSON.parse(str); + } + catch (e) { + return null; + } + } + /** + * Tests if a given string matches a given pattern, with support for wildcards and queries. + * @param pattern Wildcard pattern to string match. Supports "*" for wildcards and "?" for queries + * @param input String to match against + */ + static matchPattern(pattern, input) { + /** + * Wildcard support: https://stackoverflow.com/a/3117248/4888559 + * Queries: replaces "?" in string with escaped "\?" for regex test + */ + // eslint-disable-next-line security/detect-non-literal-regexp + const regex = new RegExp(pattern + .replace(/\\/g, "\\\\") + .replace(/\*/g, "[^ ]*") + .replace(/\?/g, "\\?")); + return regex.test(input); + } +} + +export { StringUtils }; +//# sourceMappingURL=StringUtils.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/utils/TimeUtils.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/utils/TimeUtils.mjs new file mode 100644 index 00000000..38d4e425 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/utils/TimeUtils.mjs @@ -0,0 +1,76 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * Utility functions for managing date and time operations. + */ +/** + * return the current time in Unix time (seconds). + */ +function nowSeconds() { + // Date.getTime() returns in milliseconds. + return Math.round(new Date().getTime() / 1000.0); +} +/** + * Converts JS Date object to seconds + * @param date Date + */ +function toSecondsFromDate(date) { + // Convert date to seconds + return date.getTime() / 1000; +} +/** + * Convert seconds to JS Date object. Seconds can be in a number or string format or undefined (will still return a date). + * @param seconds + */ +function toDateFromSeconds(seconds) { + if (seconds) { + return new Date(Number(seconds) * 1000); + } + return new Date(); +} +/** + * check if a token is expired based on given UTC time in seconds. + * @param expiresOn + */ +function isTokenExpired(expiresOn, offset) { + // check for access token expiry + const expirationSec = Number(expiresOn) || 0; + const offsetCurrentTimeSec = nowSeconds() + offset; + // If current time + offset is greater than token expiration time, then token is expired. + return offsetCurrentTimeSec > expirationSec; +} +/** + * Checks if a cache entry is expired based on the last updated time and cache retention days. + * @param lastUpdatedAt + * @param cacheRetentionDays + * @returns + */ +function isCacheExpired(lastUpdatedAt, cacheRetentionDays) { + const cacheExpirationTimestamp = Number(lastUpdatedAt) + cacheRetentionDays * 24 * 60 * 60 * 1000; + return Date.now() > cacheExpirationTimestamp; +} +/** + * If the current time is earlier than the time that a token was cached at, we must discard the token + * i.e. The system clock was turned back after acquiring the cached token + * @param cachedAt + * @param offset + */ +function wasClockTurnedBack(cachedAt) { + const cachedAtSec = Number(cachedAt); + return cachedAtSec > nowSeconds(); +} +/** + * Waits for t number of milliseconds + * @param t number + * @param value T + */ +function delay(t, value) { + return new Promise((resolve) => setTimeout(() => resolve(value), t)); +} + +export { delay, isCacheExpired, isTokenExpired, nowSeconds, toDateFromSeconds, toSecondsFromDate, wasClockTurnedBack }; +//# sourceMappingURL=TimeUtils.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/utils/UrlUtils.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/utils/UrlUtils.mjs new file mode 100644 index 00000000..fcfd9569 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-common/dist/utils/UrlUtils.mjs @@ -0,0 +1,122 @@ +/*! @azure/msal-common v15.13.1 2025-10-29 */ +'use strict'; +import { createClientAuthError } from '../error/ClientAuthError.mjs'; +import { StringUtils } from './StringUtils.mjs'; +import { hashNotDeserialized } from '../error/ClientAuthErrorCodes.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * Canonicalizes a URL by making it lowercase and ensuring it ends with / + * Inlined version of UrlString.canonicalizeUri to avoid circular dependency + * @param url - URL to canonicalize + * @returns Canonicalized URL + */ +function canonicalizeUrl(url) { + if (!url) { + return url; + } + let lowerCaseUrl = url.toLowerCase(); + if (StringUtils.endsWith(lowerCaseUrl, "?")) { + lowerCaseUrl = lowerCaseUrl.slice(0, -1); + } + else if (StringUtils.endsWith(lowerCaseUrl, "?/")) { + lowerCaseUrl = lowerCaseUrl.slice(0, -2); + } + if (!StringUtils.endsWith(lowerCaseUrl, "/")) { + lowerCaseUrl += "/"; + } + return lowerCaseUrl; +} +/** + * Parses hash string from given string. Returns empty string if no hash symbol is found. + * @param hashString + */ +function stripLeadingHashOrQuery(responseString) { + if (responseString.startsWith("#/")) { + return responseString.substring(2); + } + else if (responseString.startsWith("#") || + responseString.startsWith("?")) { + return responseString.substring(1); + } + return responseString; +} +/** + * Returns URL hash as server auth code response object. + */ +function getDeserializedResponse(responseString) { + // Check if given hash is empty + if (!responseString || responseString.indexOf("=") < 0) { + return null; + } + try { + // Strip the # or ? symbol if present + const normalizedResponse = stripLeadingHashOrQuery(responseString); + // If # symbol was not present, above will return empty string, so give original hash value + const deserializedHash = Object.fromEntries(new URLSearchParams(normalizedResponse)); + // Check for known response properties + if (deserializedHash.code || + deserializedHash.ear_jwe || + deserializedHash.error || + deserializedHash.error_description || + deserializedHash.state) { + return deserializedHash; + } + } + catch (e) { + throw createClientAuthError(hashNotDeserialized); + } + return null; +} +/** + * Utility to create a URL from the params map + */ +function mapToQueryString(parameters, encodeExtraParams = true, extraQueryParameters) { + const queryParameterArray = new Array(); + parameters.forEach((value, key) => { + if (!encodeExtraParams && + extraQueryParameters && + key in extraQueryParameters) { + queryParameterArray.push(`${key}=${value}`); + } + else { + queryParameterArray.push(`${key}=${encodeURIComponent(value)}`); + } + }); + return queryParameterArray.join("&"); +} +/** + * Normalizes URLs for comparison by removing hash, canonicalizing, + * and ensuring consistent URL encoding in query parameters. + * This fixes redirect loops when URLs contain encoded characters like apostrophes (%27). + * @param url - URL to normalize + * @returns Normalized URL string for comparison + */ +function normalizeUrlForComparison(url) { + if (!url) { + return url; + } + // Remove hash first + const urlWithoutHash = url.split("#")[0]; + try { + // Parse the URL to handle encoding consistently + const urlObj = new URL(urlWithoutHash); + /* + * Reconstruct the URL with properly decoded query parameters + * This ensures that %27 and ' are treated as equivalent + */ + const normalizedUrl = urlObj.origin + urlObj.pathname + urlObj.search; + // Apply canonicalization logic inline to avoid circular dependency + return canonicalizeUrl(normalizedUrl); + } + catch (e) { + // Fallback to original logic if URL parsing fails + return canonicalizeUrl(urlWithoutHash); + } +} + +export { getDeserializedResponse, mapToQueryString, normalizeUrlForComparison, stripLeadingHashOrQuery }; +//# sourceMappingURL=UrlUtils.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/cache/CacheHelpers.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/cache/CacheHelpers.mjs new file mode 100644 index 00000000..932ef0a6 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/cache/CacheHelpers.mjs @@ -0,0 +1,42 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { AuthenticationScheme, CredentialType } from '@azure/msal-common/node'; +import { CACHE } from '../utils/Constants.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +function generateCredentialKey(credential) { + const familyId = (credential.credentialType === CredentialType.REFRESH_TOKEN && + credential.familyId) || + credential.clientId; + const scheme = credential.tokenType && + credential.tokenType.toLowerCase() !== + AuthenticationScheme.BEARER.toLowerCase() + ? credential.tokenType.toLowerCase() + : ""; + const credentialKey = [ + credential.homeAccountId, + credential.environment, + credential.credentialType, + familyId, + credential.realm || "", + credential.target || "", + credential.requestedClaimsHash || "", + scheme, + ]; + return credentialKey.join(CACHE.KEY_SEPARATOR).toLowerCase(); +} +function generateAccountKey(account) { + const homeTenantId = account.homeAccountId.split(".")[1]; + const accountKey = [ + account.homeAccountId, + account.environment, + homeTenantId || account.tenantId || "", + ]; + return accountKey.join(CACHE.KEY_SEPARATOR).toLowerCase(); +} + +export { generateAccountKey, generateCredentialKey }; +//# sourceMappingURL=CacheHelpers.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/cache/NodeStorage.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/cache/NodeStorage.mjs new file mode 100644 index 00000000..c629848f --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/cache/NodeStorage.mjs @@ -0,0 +1,429 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { CacheManager, AccountEntity, CacheHelpers } from '@azure/msal-common/node'; +import { Deserializer } from './serializer/Deserializer.mjs'; +import { Serializer } from './serializer/Serializer.mjs'; +import { StubPerformanceClient } from '@azure/msal-common'; +import { generateCredentialKey, generateAccountKey } from './CacheHelpers.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * This class implements Storage for node, reading cache from user specified storage location or an extension library + * @public + */ +class NodeStorage extends CacheManager { + constructor(logger, clientId, cryptoImpl, staticAuthorityOptions) { + super(clientId, cryptoImpl, logger, new StubPerformanceClient(), staticAuthorityOptions); + this.cache = {}; + this.changeEmitters = []; + this.logger = logger; + } + /** + * Queue up callbacks + * @param func - a callback function for cache change indication + */ + registerChangeEmitter(func) { + this.changeEmitters.push(func); + } + /** + * Invoke the callback when cache changes + */ + emitChange() { + this.changeEmitters.forEach((func) => func.call(null)); + } + /** + * Converts cacheKVStore to InMemoryCache + * @param cache - key value store + */ + cacheToInMemoryCache(cache) { + const inMemoryCache = { + accounts: {}, + idTokens: {}, + accessTokens: {}, + refreshTokens: {}, + appMetadata: {}, + }; + for (const key in cache) { + const value = cache[key]; + if (typeof value !== "object") { + continue; + } + if (value instanceof AccountEntity) { + inMemoryCache.accounts[key] = value; + } + else if (CacheHelpers.isIdTokenEntity(value)) { + inMemoryCache.idTokens[key] = value; + } + else if (CacheHelpers.isAccessTokenEntity(value)) { + inMemoryCache.accessTokens[key] = value; + } + else if (CacheHelpers.isRefreshTokenEntity(value)) { + inMemoryCache.refreshTokens[key] = value; + } + else if (CacheHelpers.isAppMetadataEntity(key, value)) { + inMemoryCache.appMetadata[key] = value; + } + else { + continue; + } + } + return inMemoryCache; + } + /** + * converts inMemoryCache to CacheKVStore + * @param inMemoryCache - kvstore map for inmemory + */ + inMemoryCacheToCache(inMemoryCache) { + // convert in memory cache to a flat Key-Value map + let cache = this.getCache(); + cache = { + ...cache, + ...inMemoryCache.accounts, + ...inMemoryCache.idTokens, + ...inMemoryCache.accessTokens, + ...inMemoryCache.refreshTokens, + ...inMemoryCache.appMetadata, + }; + // convert in memory cache to a flat Key-Value map + return cache; + } + /** + * gets the current in memory cache for the client + */ + getInMemoryCache() { + this.logger.trace("Getting in-memory cache"); + // convert the cache key value store to inMemoryCache + const inMemoryCache = this.cacheToInMemoryCache(this.getCache()); + return inMemoryCache; + } + /** + * sets the current in memory cache for the client + * @param inMemoryCache - key value map in memory + */ + setInMemoryCache(inMemoryCache) { + this.logger.trace("Setting in-memory cache"); + // convert and append the inMemoryCache to cacheKVStore + const cache = this.inMemoryCacheToCache(inMemoryCache); + this.setCache(cache); + this.emitChange(); + } + /** + * get the current cache key-value store + */ + getCache() { + this.logger.trace("Getting cache key-value store"); + return this.cache; + } + /** + * sets the current cache (key value store) + * @param cacheMap - key value map + */ + setCache(cache) { + this.logger.trace("Setting cache key value store"); + this.cache = cache; + // mark change in cache + this.emitChange(); + } + /** + * Gets cache item with given key. + * @param key - lookup key for the cache entry + */ + getItem(key) { + this.logger.tracePii(`Item key: ${key}`); + // read cache + const cache = this.getCache(); + return cache[key]; + } + /** + * Gets cache item with given key-value + * @param key - lookup key for the cache entry + * @param value - value of the cache entry + */ + setItem(key, value) { + this.logger.tracePii(`Item key: ${key}`); + // read cache + const cache = this.getCache(); + cache[key] = value; + // write to cache + this.setCache(cache); + } + generateCredentialKey(credential) { + return generateCredentialKey(credential); + } + generateAccountKey(account) { + return generateAccountKey(account); + } + getAccountKeys() { + const inMemoryCache = this.getInMemoryCache(); + const accountKeys = Object.keys(inMemoryCache.accounts); + return accountKeys; + } + getTokenKeys() { + const inMemoryCache = this.getInMemoryCache(); + const tokenKeys = { + idToken: Object.keys(inMemoryCache.idTokens), + accessToken: Object.keys(inMemoryCache.accessTokens), + refreshToken: Object.keys(inMemoryCache.refreshTokens), + }; + return tokenKeys; + } + /** + * Reads account from cache, builds it into an account entity and returns it. + * @param accountKey - lookup key to fetch cache type AccountEntity + * @returns + */ + getAccount(accountKey) { + const cachedAccount = this.getItem(accountKey); + return cachedAccount + ? Object.assign(new AccountEntity(), this.getItem(accountKey)) + : null; + } + /** + * set account entity + * @param account - cache value to be set of type AccountEntity + */ + async setAccount(account) { + const accountKey = this.generateAccountKey(AccountEntity.getAccountInfo(account)); + this.setItem(accountKey, account); + } + /** + * fetch the idToken credential + * @param idTokenKey - lookup key to fetch cache type IdTokenEntity + */ + getIdTokenCredential(idTokenKey) { + const idToken = this.getItem(idTokenKey); + if (CacheHelpers.isIdTokenEntity(idToken)) { + return idToken; + } + return null; + } + /** + * set idToken credential + * @param idToken - cache value to be set of type IdTokenEntity + */ + async setIdTokenCredential(idToken) { + const idTokenKey = this.generateCredentialKey(idToken); + this.setItem(idTokenKey, idToken); + } + /** + * fetch the accessToken credential + * @param accessTokenKey - lookup key to fetch cache type AccessTokenEntity + */ + getAccessTokenCredential(accessTokenKey) { + const accessToken = this.getItem(accessTokenKey); + if (CacheHelpers.isAccessTokenEntity(accessToken)) { + return accessToken; + } + return null; + } + /** + * set accessToken credential + * @param accessToken - cache value to be set of type AccessTokenEntity + */ + async setAccessTokenCredential(accessToken) { + const accessTokenKey = this.generateCredentialKey(accessToken); + this.setItem(accessTokenKey, accessToken); + } + /** + * fetch the refreshToken credential + * @param refreshTokenKey - lookup key to fetch cache type RefreshTokenEntity + */ + getRefreshTokenCredential(refreshTokenKey) { + const refreshToken = this.getItem(refreshTokenKey); + if (CacheHelpers.isRefreshTokenEntity(refreshToken)) { + return refreshToken; + } + return null; + } + /** + * set refreshToken credential + * @param refreshToken - cache value to be set of type RefreshTokenEntity + */ + async setRefreshTokenCredential(refreshToken) { + const refreshTokenKey = this.generateCredentialKey(refreshToken); + this.setItem(refreshTokenKey, refreshToken); + } + /** + * fetch appMetadata entity from the platform cache + * @param appMetadataKey - lookup key to fetch cache type AppMetadataEntity + */ + getAppMetadata(appMetadataKey) { + const appMetadata = this.getItem(appMetadataKey); + if (CacheHelpers.isAppMetadataEntity(appMetadataKey, appMetadata)) { + return appMetadata; + } + return null; + } + /** + * set appMetadata entity to the platform cache + * @param appMetadata - cache value to be set of type AppMetadataEntity + */ + setAppMetadata(appMetadata) { + const appMetadataKey = CacheHelpers.generateAppMetadataKey(appMetadata); + this.setItem(appMetadataKey, appMetadata); + } + /** + * fetch server telemetry entity from the platform cache + * @param serverTelemetrykey - lookup key to fetch cache type ServerTelemetryEntity + */ + getServerTelemetry(serverTelemetrykey) { + const serverTelemetryEntity = this.getItem(serverTelemetrykey); + if (serverTelemetryEntity && + CacheHelpers.isServerTelemetryEntity(serverTelemetrykey, serverTelemetryEntity)) { + return serverTelemetryEntity; + } + return null; + } + /** + * set server telemetry entity to the platform cache + * @param serverTelemetryKey - lookup key to fetch cache type ServerTelemetryEntity + * @param serverTelemetry - cache value to be set of type ServerTelemetryEntity + */ + setServerTelemetry(serverTelemetryKey, serverTelemetry) { + this.setItem(serverTelemetryKey, serverTelemetry); + } + /** + * fetch authority metadata entity from the platform cache + * @param key - lookup key to fetch cache type AuthorityMetadataEntity + */ + getAuthorityMetadata(key) { + const authorityMetadataEntity = this.getItem(key); + if (authorityMetadataEntity && + CacheHelpers.isAuthorityMetadataEntity(key, authorityMetadataEntity)) { + return authorityMetadataEntity; + } + return null; + } + /** + * Get all authority metadata keys + */ + getAuthorityMetadataKeys() { + return this.getKeys().filter((key) => { + return this.isAuthorityMetadata(key); + }); + } + /** + * set authority metadata entity to the platform cache + * @param key - lookup key to fetch cache type AuthorityMetadataEntity + * @param metadata - cache value to be set of type AuthorityMetadataEntity + */ + setAuthorityMetadata(key, metadata) { + this.setItem(key, metadata); + } + /** + * fetch throttling entity from the platform cache + * @param throttlingCacheKey - lookup key to fetch cache type ThrottlingEntity + */ + getThrottlingCache(throttlingCacheKey) { + const throttlingCache = this.getItem(throttlingCacheKey); + if (throttlingCache && + CacheHelpers.isThrottlingEntity(throttlingCacheKey, throttlingCache)) { + return throttlingCache; + } + return null; + } + /** + * set throttling entity to the platform cache + * @param throttlingCacheKey - lookup key to fetch cache type ThrottlingEntity + * @param throttlingCache - cache value to be set of type ThrottlingEntity + */ + setThrottlingCache(throttlingCacheKey, throttlingCache) { + this.setItem(throttlingCacheKey, throttlingCache); + } + /** + * Removes the cache item from memory with the given key. + * @param key - lookup key to remove a cache entity + * @param inMemory - key value map of the cache + */ + removeItem(key) { + this.logger.tracePii(`Item key: ${key}`); + // read inMemoryCache + let result = false; + const cache = this.getCache(); + if (!!cache[key]) { + delete cache[key]; + result = true; + } + // write to the cache after removal + if (result) { + this.setCache(cache); + this.emitChange(); + } + return result; + } + /** + * Remove account entity from the platform cache if it's outdated + * @param accountKey - lookup key to fetch cache type AccountEntity + */ + removeOutdatedAccount(accountKey) { + this.removeItem(accountKey); + } + /** + * Checks whether key is in cache. + * @param key - look up key for a cache entity + */ + containsKey(key) { + return this.getKeys().includes(key); + } + /** + * Gets all keys in window. + */ + getKeys() { + this.logger.trace("Retrieving all cache keys"); + // read cache + const cache = this.getCache(); + return [...Object.keys(cache)]; + } + /** + * Clears all cache entries created by MSAL (except tokens). + */ + clear() { + this.logger.trace("Clearing cache entries created by MSAL"); + // read inMemoryCache + const cacheKeys = this.getKeys(); + // delete each element + cacheKeys.forEach((key) => { + this.removeItem(key); + }); + this.emitChange(); + } + /** + * Initialize in memory cache from an exisiting cache vault + * @param cache - blob formatted cache (JSON) + */ + static generateInMemoryCache(cache) { + return Deserializer.deserializeAllCache(Deserializer.deserializeJSONBlob(cache)); + } + /** + * retrieves the final JSON + * @param inMemoryCache - itemised cache read from the JSON + */ + static generateJsonCache(inMemoryCache) { + return Serializer.serializeAllCache(inMemoryCache); + } + /** + * Updates a credential's cache key if the current cache key is outdated + */ + updateCredentialCacheKey(currentCacheKey, credential) { + const updatedCacheKey = this.generateCredentialKey(credential); + if (currentCacheKey !== updatedCacheKey) { + const cacheItem = this.getItem(currentCacheKey); + if (cacheItem) { + this.removeItem(currentCacheKey); + this.setItem(updatedCacheKey, cacheItem); + this.logger.verbose(`Updated an outdated ${credential.credentialType} cache key`); + return updatedCacheKey; + } + else { + this.logger.error(`Attempted to update an outdated ${credential.credentialType} cache key but no item matching the outdated key was found in storage`); + } + } + return currentCacheKey; + } +} + +export { NodeStorage }; +//# sourceMappingURL=NodeStorage.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/cache/TokenCache.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/cache/TokenCache.mjs new file mode 100644 index 00000000..359dc66d --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/cache/TokenCache.mjs @@ -0,0 +1,300 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { NodeStorage } from './NodeStorage.mjs'; +import { TokenCacheContext } from '@azure/msal-common/node'; +import { Deserializer } from './serializer/Deserializer.mjs'; +import { Serializer } from './serializer/Serializer.mjs'; +import { CryptoProvider } from '../crypto/CryptoProvider.mjs'; +import { GuidGenerator } from '../crypto/GuidGenerator.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +const defaultSerializedCache = { + Account: {}, + IdToken: {}, + AccessToken: {}, + RefreshToken: {}, + AppMetadata: {}, +}; +/** + * In-memory token cache manager + * @public + */ +class TokenCache { + constructor(storage, logger, cachePlugin) { + this.cacheHasChanged = false; + this.storage = storage; + this.storage.registerChangeEmitter(this.handleChangeEvent.bind(this)); + if (cachePlugin) { + this.persistence = cachePlugin; + } + this.logger = logger; + } + /** + * Set to true if cache state has changed since last time serialize or writeToPersistence was called + */ + hasChanged() { + return this.cacheHasChanged; + } + /** + * Serializes in memory cache to JSON + */ + serialize() { + this.logger.trace("Serializing in-memory cache"); + let finalState = Serializer.serializeAllCache(this.storage.getInMemoryCache()); + // if cacheSnapshot not null or empty, merge + if (this.cacheSnapshot) { + this.logger.trace("Reading cache snapshot from disk"); + finalState = this.mergeState(JSON.parse(this.cacheSnapshot), finalState); + } + else { + this.logger.trace("No cache snapshot to merge"); + } + this.cacheHasChanged = false; + return JSON.stringify(finalState); + } + /** + * Deserializes JSON to in-memory cache. JSON should be in MSAL cache schema format + * @param cache - blob formatted cache + */ + deserialize(cache) { + this.logger.trace("Deserializing JSON to in-memory cache"); + this.cacheSnapshot = cache; + if (this.cacheSnapshot) { + this.logger.trace("Reading cache snapshot from disk"); + const deserializedCache = Deserializer.deserializeAllCache(this.overlayDefaults(JSON.parse(this.cacheSnapshot))); + this.storage.setInMemoryCache(deserializedCache); + } + else { + this.logger.trace("No cache snapshot to deserialize"); + } + } + /** + * Fetches the cache key-value map + */ + getKVStore() { + return this.storage.getCache(); + } + /** + * Gets cache snapshot in CacheKVStore format + */ + getCacheSnapshot() { + const deserializedPersistentStorage = NodeStorage.generateInMemoryCache(this.cacheSnapshot); + return this.storage.inMemoryCacheToCache(deserializedPersistentStorage); + } + /** + * API that retrieves all accounts currently in cache to the user + */ + async getAllAccounts(correlationId = new CryptoProvider().createNewGuid()) { + this.logger.trace("getAllAccounts called"); + let cacheContext; + try { + if (this.persistence) { + cacheContext = new TokenCacheContext(this, false); + await this.persistence.beforeCacheAccess(cacheContext); + } + return this.storage.getAllAccounts({}, correlationId); + } + finally { + if (this.persistence && cacheContext) { + await this.persistence.afterCacheAccess(cacheContext); + } + } + } + /** + * Returns the signed in account matching homeAccountId. + * (the account object is created at the time of successful login) + * or null when no matching account is found + * @param homeAccountId - unique identifier for an account (uid.utid) + */ + async getAccountByHomeId(homeAccountId) { + const allAccounts = await this.getAllAccounts(); + if (homeAccountId && allAccounts && allAccounts.length) { + return (allAccounts.filter((accountObj) => accountObj.homeAccountId === homeAccountId)[0] || null); + } + else { + return null; + } + } + /** + * Returns the signed in account matching localAccountId. + * (the account object is created at the time of successful login) + * or null when no matching account is found + * @param localAccountId - unique identifier of an account (sub/obj when homeAccountId cannot be populated) + */ + async getAccountByLocalId(localAccountId) { + const allAccounts = await this.getAllAccounts(); + if (localAccountId && allAccounts && allAccounts.length) { + return (allAccounts.filter((accountObj) => accountObj.localAccountId === localAccountId)[0] || null); + } + else { + return null; + } + } + /** + * API to remove a specific account and the relevant data from cache + * @param account - AccountInfo passed by the user + */ + async removeAccount(account, correlationId) { + this.logger.trace("removeAccount called"); + let cacheContext; + try { + if (this.persistence) { + cacheContext = new TokenCacheContext(this, true); + await this.persistence.beforeCacheAccess(cacheContext); + } + this.storage.removeAccount(account, correlationId || new GuidGenerator().generateGuid()); + } + finally { + if (this.persistence && cacheContext) { + await this.persistence.afterCacheAccess(cacheContext); + } + } + } + /** + * Overwrites in-memory cache with persistent cache + */ + async overwriteCache() { + if (!this.persistence) { + this.logger.info("No persistence layer specified, cache cannot be overwritten"); + return; + } + this.logger.info("Overwriting in-memory cache with persistent cache"); + this.storage.clear(); + const cacheContext = new TokenCacheContext(this, false); + await this.persistence.beforeCacheAccess(cacheContext); + const cacheSnapshot = this.getCacheSnapshot(); + this.storage.setCache(cacheSnapshot); + await this.persistence.afterCacheAccess(cacheContext); + } + /** + * Called when the cache has changed state. + */ + handleChangeEvent() { + this.cacheHasChanged = true; + } + /** + * Merge in memory cache with the cache snapshot. + * @param oldState - cache before changes + * @param currentState - current cache state in the library + */ + mergeState(oldState, currentState) { + this.logger.trace("Merging in-memory cache with cache snapshot"); + const stateAfterRemoval = this.mergeRemovals(oldState, currentState); + return this.mergeUpdates(stateAfterRemoval, currentState); + } + /** + * Deep update of oldState based on newState values + * @param oldState - cache before changes + * @param newState - updated cache + */ + mergeUpdates(oldState, newState) { + Object.keys(newState).forEach((newKey) => { + const newValue = newState[newKey]; + // if oldState does not contain value but newValue does, add it + if (!oldState.hasOwnProperty(newKey)) { + if (newValue !== null) { + oldState[newKey] = newValue; + } + } + else { + // both oldState and newState contain the key, do deep update + const newValueNotNull = newValue !== null; + const newValueIsObject = typeof newValue === "object"; + const newValueIsNotArray = !Array.isArray(newValue); + const oldStateNotUndefinedOrNull = typeof oldState[newKey] !== "undefined" && + oldState[newKey] !== null; + if (newValueNotNull && + newValueIsObject && + newValueIsNotArray && + oldStateNotUndefinedOrNull) { + this.mergeUpdates(oldState[newKey], newValue); + } + else { + oldState[newKey] = newValue; + } + } + }); + return oldState; + } + /** + * Removes entities in oldState that the were removed from newState. If there are any unknown values in root of + * oldState that are not recognized, they are left untouched. + * @param oldState - cache before changes + * @param newState - updated cache + */ + mergeRemovals(oldState, newState) { + this.logger.trace("Remove updated entries in cache"); + const accounts = oldState.Account + ? this.mergeRemovalsDict(oldState.Account, newState.Account) + : oldState.Account; + const accessTokens = oldState.AccessToken + ? this.mergeRemovalsDict(oldState.AccessToken, newState.AccessToken) + : oldState.AccessToken; + const refreshTokens = oldState.RefreshToken + ? this.mergeRemovalsDict(oldState.RefreshToken, newState.RefreshToken) + : oldState.RefreshToken; + const idTokens = oldState.IdToken + ? this.mergeRemovalsDict(oldState.IdToken, newState.IdToken) + : oldState.IdToken; + const appMetadata = oldState.AppMetadata + ? this.mergeRemovalsDict(oldState.AppMetadata, newState.AppMetadata) + : oldState.AppMetadata; + return { + ...oldState, + Account: accounts, + AccessToken: accessTokens, + RefreshToken: refreshTokens, + IdToken: idTokens, + AppMetadata: appMetadata, + }; + } + /** + * Helper to merge new cache with the old one + * @param oldState - cache before changes + * @param newState - updated cache + */ + mergeRemovalsDict(oldState, newState) { + const finalState = { ...oldState }; + Object.keys(oldState).forEach((oldKey) => { + if (!newState || !newState.hasOwnProperty(oldKey)) { + delete finalState[oldKey]; + } + }); + return finalState; + } + /** + * Helper to overlay as a part of cache merge + * @param passedInCache - cache read from the blob + */ + overlayDefaults(passedInCache) { + this.logger.trace("Overlaying input cache with the default cache"); + return { + Account: { + ...defaultSerializedCache.Account, + ...passedInCache.Account, + }, + IdToken: { + ...defaultSerializedCache.IdToken, + ...passedInCache.IdToken, + }, + AccessToken: { + ...defaultSerializedCache.AccessToken, + ...passedInCache.AccessToken, + }, + RefreshToken: { + ...defaultSerializedCache.RefreshToken, + ...passedInCache.RefreshToken, + }, + AppMetadata: { + ...defaultSerializedCache.AppMetadata, + ...passedInCache.AppMetadata, + }, + }; + } +} + +export { TokenCache }; +//# sourceMappingURL=TokenCache.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/cache/distributed/DistributedCachePlugin.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/cache/distributed/DistributedCachePlugin.mjs new file mode 100644 index 00000000..c6af24fb --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/cache/distributed/DistributedCachePlugin.mjs @@ -0,0 +1,49 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { AccountEntity } from '@azure/msal-common/node'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * Cache plugin that serializes data to the cache and deserializes data from the cache + * @public + */ +class DistributedCachePlugin { + constructor(client, partitionManager) { + this.client = client; + this.partitionManager = partitionManager; + } + /** + * Deserializes the cache before accessing it + * @param cacheContext - TokenCacheContext + */ + async beforeCacheAccess(cacheContext) { + const partitionKey = await this.partitionManager.getKey(); + const cacheData = await this.client.get(partitionKey); + cacheContext.tokenCache.deserialize(cacheData); + } + /** + * Serializes the cache after accessing it + * @param cacheContext - TokenCacheContext + */ + async afterCacheAccess(cacheContext) { + if (cacheContext.cacheHasChanged) { + const kvStore = cacheContext.tokenCache.getKVStore(); + const accountEntities = Object.values(kvStore).filter((value) => AccountEntity.isAccountEntity(value)); + let partitionKey; + if (accountEntities.length > 0) { + const accountEntity = accountEntities[0]; + partitionKey = await this.partitionManager.extractKey(accountEntity); + } + else { + partitionKey = await this.partitionManager.getKey(); + } + await this.client.set(partitionKey, cacheContext.tokenCache.serialize()); + } + } +} + +export { DistributedCachePlugin }; +//# sourceMappingURL=DistributedCachePlugin.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/cache/serializer/Deserializer.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/cache/serializer/Deserializer.mjs new file mode 100644 index 00000000..4d75a39d --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/cache/serializer/Deserializer.mjs @@ -0,0 +1,179 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { AccountEntity, CacheManager } from '@azure/msal-common/node'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * This class deserializes cache entities read from the file into in-memory object types defined internally + * @internal + */ +class Deserializer { + /** + * Parse the JSON blob in memory and deserialize the content + * @param cachedJson - JSON blob cache + */ + static deserializeJSONBlob(jsonFile) { + const deserializedCache = !jsonFile ? {} : JSON.parse(jsonFile); + return deserializedCache; + } + /** + * Deserializes accounts to AccountEntity objects + * @param accounts - accounts of type SerializedAccountEntity + */ + static deserializeAccounts(accounts) { + const accountObjects = {}; + if (accounts) { + Object.keys(accounts).map(function (key) { + const serializedAcc = accounts[key]; + const mappedAcc = { + homeAccountId: serializedAcc.home_account_id, + environment: serializedAcc.environment, + realm: serializedAcc.realm, + localAccountId: serializedAcc.local_account_id, + username: serializedAcc.username, + authorityType: serializedAcc.authority_type, + name: serializedAcc.name, + clientInfo: serializedAcc.client_info, + lastModificationTime: serializedAcc.last_modification_time, + lastModificationApp: serializedAcc.last_modification_app, + tenantProfiles: serializedAcc.tenantProfiles?.map((serializedTenantProfile) => { + return JSON.parse(serializedTenantProfile); + }), + lastUpdatedAt: Date.now().toString(), + }; + const account = new AccountEntity(); + CacheManager.toObject(account, mappedAcc); + accountObjects[key] = account; + }); + } + return accountObjects; + } + /** + * Deserializes id tokens to IdTokenEntity objects + * @param idTokens - credentials of type SerializedIdTokenEntity + */ + static deserializeIdTokens(idTokens) { + const idObjects = {}; + if (idTokens) { + Object.keys(idTokens).map(function (key) { + const serializedIdT = idTokens[key]; + const idToken = { + homeAccountId: serializedIdT.home_account_id, + environment: serializedIdT.environment, + credentialType: serializedIdT.credential_type, + clientId: serializedIdT.client_id, + secret: serializedIdT.secret, + realm: serializedIdT.realm, + lastUpdatedAt: Date.now().toString(), + }; + idObjects[key] = idToken; + }); + } + return idObjects; + } + /** + * Deserializes access tokens to AccessTokenEntity objects + * @param accessTokens - access tokens of type SerializedAccessTokenEntity + */ + static deserializeAccessTokens(accessTokens) { + const atObjects = {}; + if (accessTokens) { + Object.keys(accessTokens).map(function (key) { + const serializedAT = accessTokens[key]; + const accessToken = { + homeAccountId: serializedAT.home_account_id, + environment: serializedAT.environment, + credentialType: serializedAT.credential_type, + clientId: serializedAT.client_id, + secret: serializedAT.secret, + realm: serializedAT.realm, + target: serializedAT.target, + cachedAt: serializedAT.cached_at, + expiresOn: serializedAT.expires_on, + extendedExpiresOn: serializedAT.extended_expires_on, + refreshOn: serializedAT.refresh_on, + keyId: serializedAT.key_id, + tokenType: serializedAT.token_type, + requestedClaims: serializedAT.requestedClaims, + requestedClaimsHash: serializedAT.requestedClaimsHash, + userAssertionHash: serializedAT.userAssertionHash, + lastUpdatedAt: Date.now().toString(), + }; + atObjects[key] = accessToken; + }); + } + return atObjects; + } + /** + * Deserializes refresh tokens to RefreshTokenEntity objects + * @param refreshTokens - refresh tokens of type SerializedRefreshTokenEntity + */ + static deserializeRefreshTokens(refreshTokens) { + const rtObjects = {}; + if (refreshTokens) { + Object.keys(refreshTokens).map(function (key) { + const serializedRT = refreshTokens[key]; + const refreshToken = { + homeAccountId: serializedRT.home_account_id, + environment: serializedRT.environment, + credentialType: serializedRT.credential_type, + clientId: serializedRT.client_id, + secret: serializedRT.secret, + familyId: serializedRT.family_id, + target: serializedRT.target, + realm: serializedRT.realm, + lastUpdatedAt: Date.now().toString(), + }; + rtObjects[key] = refreshToken; + }); + } + return rtObjects; + } + /** + * Deserializes appMetadata to AppMetaData objects + * @param appMetadata - app metadata of type SerializedAppMetadataEntity + */ + static deserializeAppMetadata(appMetadata) { + const appMetadataObjects = {}; + if (appMetadata) { + Object.keys(appMetadata).map(function (key) { + const serializedAmdt = appMetadata[key]; + appMetadataObjects[key] = { + clientId: serializedAmdt.client_id, + environment: serializedAmdt.environment, + familyId: serializedAmdt.family_id, + }; + }); + } + return appMetadataObjects; + } + /** + * Deserialize an inMemory Cache + * @param jsonCache - JSON blob cache + */ + static deserializeAllCache(jsonCache) { + return { + accounts: jsonCache.Account + ? this.deserializeAccounts(jsonCache.Account) + : {}, + idTokens: jsonCache.IdToken + ? this.deserializeIdTokens(jsonCache.IdToken) + : {}, + accessTokens: jsonCache.AccessToken + ? this.deserializeAccessTokens(jsonCache.AccessToken) + : {}, + refreshTokens: jsonCache.RefreshToken + ? this.deserializeRefreshTokens(jsonCache.RefreshToken) + : {}, + appMetadata: jsonCache.AppMetadata + ? this.deserializeAppMetadata(jsonCache.AppMetadata) + : {}, + }; + } +} + +export { Deserializer }; +//# sourceMappingURL=Deserializer.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/cache/serializer/Serializer.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/cache/serializer/Serializer.mjs new file mode 100644 index 00000000..c548cf6f --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/cache/serializer/Serializer.mjs @@ -0,0 +1,146 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * This class serializes cache entities to be saved into in-memory object types defined internally + * @internal + */ +class Serializer { + /** + * serialize the JSON blob + * @param data - JSON blob cache + */ + static serializeJSONBlob(data) { + return JSON.stringify(data); + } + /** + * Serialize Accounts + * @param accCache - cache of accounts + */ + static serializeAccounts(accCache) { + const accounts = {}; + Object.keys(accCache).map(function (key) { + const accountEntity = accCache[key]; + accounts[key] = { + home_account_id: accountEntity.homeAccountId, + environment: accountEntity.environment, + realm: accountEntity.realm, + local_account_id: accountEntity.localAccountId, + username: accountEntity.username, + authority_type: accountEntity.authorityType, + name: accountEntity.name, + client_info: accountEntity.clientInfo, + last_modification_time: accountEntity.lastModificationTime, + last_modification_app: accountEntity.lastModificationApp, + tenantProfiles: accountEntity.tenantProfiles?.map((tenantProfile) => { + return JSON.stringify(tenantProfile); + }), + }; + }); + return accounts; + } + /** + * Serialize IdTokens + * @param idTCache - cache of ID tokens + */ + static serializeIdTokens(idTCache) { + const idTokens = {}; + Object.keys(idTCache).map(function (key) { + const idTEntity = idTCache[key]; + idTokens[key] = { + home_account_id: idTEntity.homeAccountId, + environment: idTEntity.environment, + credential_type: idTEntity.credentialType, + client_id: idTEntity.clientId, + secret: idTEntity.secret, + realm: idTEntity.realm, + }; + }); + return idTokens; + } + /** + * Serializes AccessTokens + * @param atCache - cache of access tokens + */ + static serializeAccessTokens(atCache) { + const accessTokens = {}; + Object.keys(atCache).map(function (key) { + const atEntity = atCache[key]; + accessTokens[key] = { + home_account_id: atEntity.homeAccountId, + environment: atEntity.environment, + credential_type: atEntity.credentialType, + client_id: atEntity.clientId, + secret: atEntity.secret, + realm: atEntity.realm, + target: atEntity.target, + cached_at: atEntity.cachedAt, + expires_on: atEntity.expiresOn, + extended_expires_on: atEntity.extendedExpiresOn, + refresh_on: atEntity.refreshOn, + key_id: atEntity.keyId, + token_type: atEntity.tokenType, + requestedClaims: atEntity.requestedClaims, + requestedClaimsHash: atEntity.requestedClaimsHash, + userAssertionHash: atEntity.userAssertionHash, + }; + }); + return accessTokens; + } + /** + * Serialize refreshTokens + * @param rtCache - cache of refresh tokens + */ + static serializeRefreshTokens(rtCache) { + const refreshTokens = {}; + Object.keys(rtCache).map(function (key) { + const rtEntity = rtCache[key]; + refreshTokens[key] = { + home_account_id: rtEntity.homeAccountId, + environment: rtEntity.environment, + credential_type: rtEntity.credentialType, + client_id: rtEntity.clientId, + secret: rtEntity.secret, + family_id: rtEntity.familyId, + target: rtEntity.target, + realm: rtEntity.realm, + }; + }); + return refreshTokens; + } + /** + * Serialize amdtCache + * @param amdtCache - cache of app metadata + */ + static serializeAppMetadata(amdtCache) { + const appMetadata = {}; + Object.keys(amdtCache).map(function (key) { + const amdtEntity = amdtCache[key]; + appMetadata[key] = { + client_id: amdtEntity.clientId, + environment: amdtEntity.environment, + family_id: amdtEntity.familyId, + }; + }); + return appMetadata; + } + /** + * Serialize the cache + * @param inMemCache - itemised cache read from the JSON + */ + static serializeAllCache(inMemCache) { + return { + Account: this.serializeAccounts(inMemCache.accounts), + IdToken: this.serializeIdTokens(inMemCache.idTokens), + AccessToken: this.serializeAccessTokens(inMemCache.accessTokens), + RefreshToken: this.serializeRefreshTokens(inMemCache.refreshTokens), + AppMetadata: this.serializeAppMetadata(inMemCache.appMetadata), + }; + } +} + +export { Serializer }; +//# sourceMappingURL=Serializer.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/client/ClientApplication.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/client/ClientApplication.mjs new file mode 100644 index 00000000..eb46b615 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/client/ClientApplication.mjs @@ -0,0 +1,385 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { Logger, buildStaticAuthorityOptions, AuthenticationScheme, AuthorizationCodeClient, AuthError, RefreshTokenClient, SilentFlowClient, ClientAuthError, ClientAuthErrorCodes, OIDC_DEFAULT_SCOPES, CacheOutcome, createClientAuthError, Constants, getClientAssertion, StringUtils, ServerTelemetryManager, Authority, AuthorityFactory, ResponseMode } from '@azure/msal-common/node'; +import { buildAppConfiguration } from '../config/Configuration.mjs'; +import { CryptoProvider } from '../crypto/CryptoProvider.mjs'; +import { NodeStorage } from '../cache/NodeStorage.mjs'; +import { ApiId, Constants as Constants$1 } from '../utils/Constants.mjs'; +import { TokenCache } from '../cache/TokenCache.mjs'; +import { ClientAssertion } from './ClientAssertion.mjs'; +import { name, version } from '../packageMetadata.mjs'; +import { NodeAuthError } from '../error/NodeAuthError.mjs'; +import { UsernamePasswordClient } from './UsernamePasswordClient.mjs'; +import { getAuthCodeRequestUrl } from '../protocol/Authorize.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * Base abstract class for all ClientApplications - public and confidential + * @public + */ +class ClientApplication { + /** + * Constructor for the ClientApplication + */ + constructor(configuration) { + this.config = buildAppConfiguration(configuration); + this.cryptoProvider = new CryptoProvider(); + this.logger = new Logger(this.config.system.loggerOptions, name, version); + this.storage = new NodeStorage(this.logger, this.config.auth.clientId, this.cryptoProvider, buildStaticAuthorityOptions(this.config.auth)); + this.tokenCache = new TokenCache(this.storage, this.logger, this.config.cache.cachePlugin); + } + /** + * Creates the URL of the authorization request, letting the user input credentials and consent to the + * application. The URL targets the /authorize endpoint of the authority configured in the + * application object. + * + * Once the user inputs their credentials and consents, the authority will send a response to the redirect URI + * sent in the request and should contain an authorization code, which can then be used to acquire tokens via + * `acquireTokenByCode(AuthorizationCodeRequest)`. + */ + async getAuthCodeUrl(request) { + this.logger.info("getAuthCodeUrl called", request.correlationId); + const validRequest = { + ...request, + ...(await this.initializeBaseRequest(request)), + responseMode: request.responseMode || ResponseMode.QUERY, + authenticationScheme: AuthenticationScheme.BEARER, + state: request.state || "", + nonce: request.nonce || "", + }; + const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, undefined, request.azureCloudOptions); + return getAuthCodeRequestUrl(this.config, discoveredAuthority, validRequest, this.logger); + } + /** + * Acquires a token by exchanging the Authorization Code received from the first step of OAuth2.0 + * Authorization Code flow. + * + * `getAuthCodeUrl(AuthorizationCodeUrlRequest)` can be used to create the URL for the first step of OAuth2.0 + * Authorization Code flow. Ensure that values for redirectUri and scopes in AuthorizationCodeUrlRequest and + * AuthorizationCodeRequest are the same. + */ + async acquireTokenByCode(request, authCodePayLoad) { + this.logger.info("acquireTokenByCode called"); + if (request.state && authCodePayLoad) { + this.logger.info("acquireTokenByCode - validating state"); + this.validateState(request.state, authCodePayLoad.state || ""); + // eslint-disable-next-line no-param-reassign + authCodePayLoad = { ...authCodePayLoad, state: "" }; + } + const validRequest = { + ...request, + ...(await this.initializeBaseRequest(request)), + authenticationScheme: AuthenticationScheme.BEARER, + }; + const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByCode, validRequest.correlationId); + try { + const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, undefined, request.azureCloudOptions); + const authClientConfig = await this.buildOauthClientConfiguration(discoveredAuthority, validRequest.correlationId, validRequest.redirectUri, serverTelemetryManager); + const authorizationCodeClient = new AuthorizationCodeClient(authClientConfig); + this.logger.verbose("Auth code client created", validRequest.correlationId); + return await authorizationCodeClient.acquireToken(validRequest, authCodePayLoad); + } + catch (e) { + if (e instanceof AuthError) { + e.setCorrelationId(validRequest.correlationId); + } + serverTelemetryManager.cacheFailedRequest(e); + throw e; + } + } + /** + * Acquires a token by exchanging the refresh token provided for a new set of tokens. + * + * This API is provided only for scenarios where you would like to migrate from ADAL to MSAL. Otherwise, it is + * recommended that you use `acquireTokenSilent()` for silent scenarios. When using `acquireTokenSilent()`, MSAL will + * handle the caching and refreshing of tokens automatically. + */ + async acquireTokenByRefreshToken(request) { + this.logger.info("acquireTokenByRefreshToken called", request.correlationId); + const validRequest = { + ...request, + ...(await this.initializeBaseRequest(request)), + authenticationScheme: AuthenticationScheme.BEARER, + }; + const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByRefreshToken, validRequest.correlationId); + try { + const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, undefined, request.azureCloudOptions); + const refreshTokenClientConfig = await this.buildOauthClientConfiguration(discoveredAuthority, validRequest.correlationId, validRequest.redirectUri || "", serverTelemetryManager); + const refreshTokenClient = new RefreshTokenClient(refreshTokenClientConfig); + this.logger.verbose("Refresh token client created", validRequest.correlationId); + return await refreshTokenClient.acquireToken(validRequest); + } + catch (e) { + if (e instanceof AuthError) { + e.setCorrelationId(validRequest.correlationId); + } + serverTelemetryManager.cacheFailedRequest(e); + throw e; + } + } + /** + * Acquires a token silently when a user specifies the account the token is requested for. + * + * This API expects the user to provide an account object and looks into the cache to retrieve the token if present. + * There is also an optional "forceRefresh" boolean the user can send to bypass the cache for access_token and id_token. + * In case the refresh_token is expired or not found, an error is thrown + * and the guidance is for the user to call any interactive token acquisition API (eg: `acquireTokenByCode()`). + */ + async acquireTokenSilent(request) { + const validRequest = { + ...request, + ...(await this.initializeBaseRequest(request)), + forceRefresh: request.forceRefresh || false, + }; + const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenSilent, validRequest.correlationId, validRequest.forceRefresh); + try { + const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, undefined, request.azureCloudOptions); + const clientConfiguration = await this.buildOauthClientConfiguration(discoveredAuthority, validRequest.correlationId, validRequest.redirectUri || "", serverTelemetryManager); + const silentFlowClient = new SilentFlowClient(clientConfiguration); + this.logger.verbose("Silent flow client created", validRequest.correlationId); + try { + // always overwrite the in-memory cache with the persistence cache (if it exists) before a cache lookup + await this.tokenCache.overwriteCache(); + return await this.acquireCachedTokenSilent(validRequest, silentFlowClient, clientConfiguration); + } + catch (error) { + if (error instanceof ClientAuthError && + error.errorCode === + ClientAuthErrorCodes.tokenRefreshRequired) { + const refreshTokenClient = new RefreshTokenClient(clientConfiguration); + return refreshTokenClient.acquireTokenByRefreshToken(validRequest); + } + throw error; + } + } + catch (error) { + if (error instanceof AuthError) { + error.setCorrelationId(validRequest.correlationId); + } + serverTelemetryManager.cacheFailedRequest(error); + throw error; + } + } + async acquireCachedTokenSilent(validRequest, silentFlowClient, clientConfiguration) { + const [authResponse, cacheOutcome] = await silentFlowClient.acquireCachedToken({ + ...validRequest, + scopes: validRequest.scopes?.length + ? validRequest.scopes + : [...OIDC_DEFAULT_SCOPES], + }); + if (cacheOutcome === CacheOutcome.PROACTIVELY_REFRESHED) { + this.logger.info("ClientApplication:acquireCachedTokenSilent - Cached access token's refreshOn property has been exceeded'. It's not expired, but must be refreshed."); + // refresh the access token in the background + const refreshTokenClient = new RefreshTokenClient(clientConfiguration); + try { + await refreshTokenClient.acquireTokenByRefreshToken(validRequest); + } + catch { + // do nothing, this is running in the background and no action is to be taken upon success or failure + } + } + // return the cached token + return authResponse; + } + /** + * Acquires tokens with password grant by exchanging client applications username and password for credentials + * + * The latest OAuth 2.0 Security Best Current Practice disallows the password grant entirely. + * More details on this recommendation at https://tools.ietf.org/html/draft-ietf-oauth-security-topics-13#section-3.4 + * Microsoft's documentation and recommendations are at: + * https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-authentication-flows#usernamepassword + * + * @param request - UsenamePasswordRequest + * @deprecated - Use a more secure flow instead + */ + async acquireTokenByUsernamePassword(request) { + this.logger.info("acquireTokenByUsernamePassword called", request.correlationId); + const validRequest = { + ...request, + ...(await this.initializeBaseRequest(request)), + }; + const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByUsernamePassword, validRequest.correlationId); + try { + const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, undefined, request.azureCloudOptions); + const usernamePasswordClientConfig = await this.buildOauthClientConfiguration(discoveredAuthority, validRequest.correlationId, "", serverTelemetryManager); + const usernamePasswordClient = new UsernamePasswordClient(usernamePasswordClientConfig); + this.logger.verbose("Username password client created", validRequest.correlationId); + return await usernamePasswordClient.acquireToken(validRequest); + } + catch (e) { + if (e instanceof AuthError) { + e.setCorrelationId(validRequest.correlationId); + } + serverTelemetryManager.cacheFailedRequest(e); + throw e; + } + } + /** + * Gets the token cache for the application. + */ + getTokenCache() { + this.logger.info("getTokenCache called"); + return this.tokenCache; + } + /** + * Validates OIDC state by comparing the user cached state with the state received from the server. + * + * This API is provided for scenarios where you would use OAuth2.0 state parameter to mitigate against + * CSRF attacks. + * For more information about state, visit https://datatracker.ietf.org/doc/html/rfc6819#section-3.6. + * @param state - Unique GUID generated by the user that is cached by the user and sent to the server during the first leg of the flow + * @param cachedState - This string is sent back by the server with the authorization code + */ + validateState(state, cachedState) { + if (!state) { + throw NodeAuthError.createStateNotFoundError(); + } + if (state !== cachedState) { + throw createClientAuthError(ClientAuthErrorCodes.stateMismatch); + } + } + /** + * Returns the logger instance + */ + getLogger() { + return this.logger; + } + /** + * Replaces the default logger set in configurations with new Logger with new configurations + * @param logger - Logger instance + */ + setLogger(logger) { + this.logger = logger; + } + /** + * Builds the common configuration to be passed to the common component based on the platform configurarion + * @param authority - user passed authority in configuration + * @param serverTelemetryManager - initializes servertelemetry if passed + */ + async buildOauthClientConfiguration(discoveredAuthority, requestCorrelationId, redirectUri, serverTelemetryManager) { + this.logger.verbose("buildOauthClientConfiguration called", requestCorrelationId); + this.logger.info(`Building oauth client configuration with the following authority: ${discoveredAuthority.tokenEndpoint}.`, requestCorrelationId); + serverTelemetryManager?.updateRegionDiscoveryMetadata(discoveredAuthority.regionDiscoveryMetadata); + const clientConfiguration = { + authOptions: { + clientId: this.config.auth.clientId, + authority: discoveredAuthority, + clientCapabilities: this.config.auth.clientCapabilities, + redirectUri, + }, + loggerOptions: { + logLevel: this.config.system.loggerOptions.logLevel, + loggerCallback: this.config.system.loggerOptions.loggerCallback, + piiLoggingEnabled: this.config.system.loggerOptions.piiLoggingEnabled, + correlationId: requestCorrelationId, + }, + cacheOptions: { + claimsBasedCachingEnabled: this.config.cache.claimsBasedCachingEnabled, + }, + cryptoInterface: this.cryptoProvider, + networkInterface: this.config.system.networkClient, + storageInterface: this.storage, + serverTelemetryManager: serverTelemetryManager, + clientCredentials: { + clientSecret: this.clientSecret, + clientAssertion: await this.getClientAssertion(discoveredAuthority), + }, + libraryInfo: { + sku: Constants$1.MSAL_SKU, + version: version, + cpu: process.arch || Constants.EMPTY_STRING, + os: process.platform || Constants.EMPTY_STRING, + }, + telemetry: this.config.telemetry, + persistencePlugin: this.config.cache.cachePlugin, + serializableCache: this.tokenCache, + }; + return clientConfiguration; + } + async getClientAssertion(authority) { + if (this.developerProvidedClientAssertion) { + this.clientAssertion = ClientAssertion.fromAssertion(await getClientAssertion(this.developerProvidedClientAssertion, this.config.auth.clientId, authority.tokenEndpoint)); + } + return (this.clientAssertion && { + assertion: this.clientAssertion.getJwt(this.cryptoProvider, this.config.auth.clientId, authority.tokenEndpoint), + assertionType: Constants$1.JWT_BEARER_ASSERTION_TYPE, + }); + } + /** + * Generates a request with the default scopes & generates a correlationId. + * @param authRequest - BaseAuthRequest for initialization + */ + async initializeBaseRequest(authRequest) { + this.logger.verbose("initializeRequestScopes called", authRequest.correlationId); + // Default authenticationScheme to Bearer, log that POP isn't supported yet + if (authRequest.authenticationScheme && + authRequest.authenticationScheme === AuthenticationScheme.POP) { + this.logger.verbose("Authentication Scheme 'pop' is not supported yet, setting Authentication Scheme to 'Bearer' for request", authRequest.correlationId); + } + authRequest.authenticationScheme = AuthenticationScheme.BEARER; + // Set requested claims hash if claims-based caching is enabled and claims were requested + if (this.config.cache.claimsBasedCachingEnabled && + authRequest.claims && + // Checks for empty stringified object "{}" which doesn't qualify as requested claims + !StringUtils.isEmptyObj(authRequest.claims)) { + authRequest.requestedClaimsHash = + await this.cryptoProvider.hashString(authRequest.claims); + } + return { + ...authRequest, + scopes: [ + ...((authRequest && authRequest.scopes) || []), + ...OIDC_DEFAULT_SCOPES, + ], + correlationId: (authRequest && authRequest.correlationId) || + this.cryptoProvider.createNewGuid(), + authority: authRequest.authority || this.config.auth.authority, + }; + } + /** + * Initializes the server telemetry payload + * @param apiId - Id for a specific request + * @param correlationId - GUID + * @param forceRefresh - boolean to indicate network call + */ + initializeServerTelemetryManager(apiId, correlationId, forceRefresh) { + const telemetryPayload = { + clientId: this.config.auth.clientId, + correlationId: correlationId, + apiId: apiId, + forceRefresh: forceRefresh || false, + }; + return new ServerTelemetryManager(telemetryPayload, this.storage); + } + /** + * Create authority instance. If authority not passed in request, default to authority set on the application + * object. If no authority set in application object, then default to common authority. + * @param authorityString - authority from user configuration + */ + async createAuthority(authorityString, requestCorrelationId, azureRegionConfiguration, azureCloudOptions) { + this.logger.verbose("createAuthority called", requestCorrelationId); + // build authority string based on auth params - azureCloudInstance is prioritized if provided + const authorityUrl = Authority.generateAuthority(authorityString, azureCloudOptions || this.config.auth.azureCloudOptions); + const authorityOptions = { + protocolMode: this.config.auth.protocolMode, + knownAuthorities: this.config.auth.knownAuthorities, + cloudDiscoveryMetadata: this.config.auth.cloudDiscoveryMetadata, + authorityMetadata: this.config.auth.authorityMetadata, + azureRegionConfiguration, + skipAuthorityMetadataCache: this.config.auth.skipAuthorityMetadataCache, + }; + return AuthorityFactory.createDiscoveredInstance(authorityUrl, this.config.system.networkClient, this.storage, authorityOptions, this.logger, requestCorrelationId); + } + /** + * Clear the cache + */ + clearCache() { + this.storage.clear(); + } +} + +export { ClientApplication }; +//# sourceMappingURL=ClientApplication.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/client/ClientAssertion.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/client/ClientAssertion.mjs new file mode 100644 index 00000000..758c1148 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/client/ClientAssertion.mjs @@ -0,0 +1,153 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import jwt from 'jsonwebtoken'; +import { createClientAuthError, ClientAuthErrorCodes, TimeUtils, EncodingTypes, Constants } from '@azure/msal-common/node'; +import { EncodingUtils } from '../utils/EncodingUtils.mjs'; +import { JwtConstants } from '../utils/Constants.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * Client assertion of type jwt-bearer used in confidential client flows + * @public + */ +class ClientAssertion { + /** + * Initialize the ClientAssertion class from the clientAssertion passed by the user + * @param assertion - refer https://tools.ietf.org/html/rfc7521 + */ + static fromAssertion(assertion) { + const clientAssertion = new ClientAssertion(); + clientAssertion.jwt = assertion; + return clientAssertion; + } + /** + * @deprecated Use fromCertificateWithSha256Thumbprint instead, with a SHA-256 thumprint + * Initialize the ClientAssertion class from the certificate passed by the user + * @param thumbprint - identifier of a certificate + * @param privateKey - secret key + * @param publicCertificate - electronic document provided to prove the ownership of the public key + */ + static fromCertificate(thumbprint, privateKey, publicCertificate) { + const clientAssertion = new ClientAssertion(); + clientAssertion.privateKey = privateKey; + clientAssertion.thumbprint = thumbprint; + clientAssertion.useSha256 = false; + if (publicCertificate) { + clientAssertion.publicCertificate = + this.parseCertificate(publicCertificate); + } + return clientAssertion; + } + /** + * Initialize the ClientAssertion class from the certificate passed by the user + * @param thumbprint - identifier of a certificate + * @param privateKey - secret key + * @param publicCertificate - electronic document provided to prove the ownership of the public key + */ + static fromCertificateWithSha256Thumbprint(thumbprint, privateKey, publicCertificate) { + const clientAssertion = new ClientAssertion(); + clientAssertion.privateKey = privateKey; + clientAssertion.thumbprint = thumbprint; + clientAssertion.useSha256 = true; + if (publicCertificate) { + clientAssertion.publicCertificate = + this.parseCertificate(publicCertificate); + } + return clientAssertion; + } + /** + * Update JWT for certificate based clientAssertion, if passed by the user, uses it as is + * @param cryptoProvider - library's crypto helper + * @param issuer - iss claim + * @param jwtAudience - aud claim + */ + getJwt(cryptoProvider, issuer, jwtAudience) { + // if assertion was created from certificate, check if jwt is expired and create new one. + if (this.privateKey && this.thumbprint) { + if (this.jwt && + !this.isExpired() && + issuer === this.issuer && + jwtAudience === this.jwtAudience) { + return this.jwt; + } + return this.createJwt(cryptoProvider, issuer, jwtAudience); + } + /* + * if assertion was created by caller, then we just append it. It is up to the caller to + * ensure that it contains necessary claims and that it is not expired. + */ + if (this.jwt) { + return this.jwt; + } + throw createClientAuthError(ClientAuthErrorCodes.invalidAssertion); + } + /** + * JWT format and required claims specified: https://tools.ietf.org/html/rfc7523#section-3 + */ + createJwt(cryptoProvider, issuer, jwtAudience) { + this.issuer = issuer; + this.jwtAudience = jwtAudience; + const issuedAt = TimeUtils.nowSeconds(); + this.expirationTime = issuedAt + 600; + const algorithm = this.useSha256 + ? JwtConstants.PSS_256 + : JwtConstants.RSA_256; + const header = { + alg: algorithm, + }; + const thumbprintHeader = this.useSha256 + ? JwtConstants.X5T_256 + : JwtConstants.X5T; + Object.assign(header, { + [thumbprintHeader]: EncodingUtils.base64EncodeUrl(this.thumbprint, EncodingTypes.HEX), + }); + if (this.publicCertificate) { + Object.assign(header, { + [JwtConstants.X5C]: this.publicCertificate, + }); + } + const payload = { + [JwtConstants.AUDIENCE]: this.jwtAudience, + [JwtConstants.EXPIRATION_TIME]: this.expirationTime, + [JwtConstants.ISSUER]: this.issuer, + [JwtConstants.SUBJECT]: this.issuer, + [JwtConstants.NOT_BEFORE]: issuedAt, + [JwtConstants.JWT_ID]: cryptoProvider.createNewGuid(), + }; + this.jwt = jwt.sign(payload, this.privateKey, { header }); + return this.jwt; + } + /** + * Utility API to check expiration + */ + isExpired() { + return this.expirationTime < TimeUtils.nowSeconds(); + } + /** + * Extracts the raw certs from a given certificate string and returns them in an array. + * @param publicCertificate - electronic document provided to prove the ownership of the public key + */ + static parseCertificate(publicCertificate) { + /** + * This is regex to identify the certs in a given certificate string. + * We want to look for the contents between the BEGIN and END certificate strings, without the associated newlines. + * The information in parens "(.+?)" is the capture group to represent the cert we want isolated. + * "." means any string character, "+" means match 1 or more times, and "?" means the shortest match. + * The "g" at the end of the regex means search the string globally, and the "s" enables the "." to match newlines. + */ + const regexToFindCerts = /-----BEGIN CERTIFICATE-----\r*\n(.+?)\r*\n-----END CERTIFICATE-----/gs; + const certs = []; + let matches; + while ((matches = regexToFindCerts.exec(publicCertificate)) !== null) { + // matches[1] represents the first parens capture group in the regex. + certs.push(matches[1].replace(/\r*\n/g, Constants.EMPTY_STRING)); + } + return certs; + } +} + +export { ClientAssertion }; +//# sourceMappingURL=ClientAssertion.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/client/ClientCredentialClient.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/client/ClientCredentialClient.mjs new file mode 100644 index 00000000..2c0bd208 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/client/ClientCredentialClient.mjs @@ -0,0 +1,202 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { BaseClient, CacheOutcome, TokenCacheContext, ScopeSet, TimeUtils, DEFAULT_TOKEN_RENEWAL_OFFSET_SEC, ResponseHandler, CredentialType, Constants, createClientAuthError, ClientAuthErrorCodes, UrlString, RequestParameterBuilder, GrantType, getClientAssertion, StringUtils, UrlUtils, AuthenticationScheme } from '@azure/msal-common/node'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * OAuth2.0 client credential grant + * @public + */ +class ClientCredentialClient extends BaseClient { + constructor(configuration, appTokenProvider) { + super(configuration); + this.appTokenProvider = appTokenProvider; + } + /** + * Public API to acquire a token with ClientCredential Flow for Confidential clients + * @param request - CommonClientCredentialRequest provided by the developer + */ + async acquireToken(request) { + if (request.skipCache || request.claims) { + return this.executeTokenRequest(request, this.authority); + } + const [cachedAuthenticationResult, lastCacheOutcome] = await this.getCachedAuthenticationResult(request, this.config, this.cryptoUtils, this.authority, this.cacheManager, this.serverTelemetryManager); + if (cachedAuthenticationResult) { + // if the token is not expired but must be refreshed; get a new one in the background + if (lastCacheOutcome === CacheOutcome.PROACTIVELY_REFRESHED) { + this.logger.info("ClientCredentialClient:getCachedAuthenticationResult - Cached access token's refreshOn property has been exceeded'. It's not expired, but must be refreshed."); + // refresh the access token in the background + const refreshAccessToken = true; + await this.executeTokenRequest(request, this.authority, refreshAccessToken); + } + // return the cached token + return cachedAuthenticationResult; + } + else { + return this.executeTokenRequest(request, this.authority); + } + } + /** + * looks up cache if the tokens are cached already + */ + async getCachedAuthenticationResult(request, config, cryptoUtils, authority, cacheManager, serverTelemetryManager) { + const clientConfiguration = config; + const managedIdentityConfiguration = config; + let lastCacheOutcome = CacheOutcome.NOT_APPLICABLE; + // read the user-supplied cache into memory, if applicable + let cacheContext; + if (clientConfiguration.serializableCache && + clientConfiguration.persistencePlugin) { + cacheContext = new TokenCacheContext(clientConfiguration.serializableCache, false); + await clientConfiguration.persistencePlugin.beforeCacheAccess(cacheContext); + } + const cachedAccessToken = this.readAccessTokenFromCache(authority, managedIdentityConfiguration.managedIdentityId?.id || + clientConfiguration.authOptions.clientId, new ScopeSet(request.scopes || []), cacheManager, request.correlationId); + if (clientConfiguration.serializableCache && + clientConfiguration.persistencePlugin && + cacheContext) { + await clientConfiguration.persistencePlugin.afterCacheAccess(cacheContext); + } + // must refresh due to non-existent access_token + if (!cachedAccessToken) { + serverTelemetryManager?.setCacheOutcome(CacheOutcome.NO_CACHED_ACCESS_TOKEN); + return [null, CacheOutcome.NO_CACHED_ACCESS_TOKEN]; + } + // must refresh due to the expires_in value + if (TimeUtils.isTokenExpired(cachedAccessToken.expiresOn, clientConfiguration.systemOptions?.tokenRenewalOffsetSeconds || + DEFAULT_TOKEN_RENEWAL_OFFSET_SEC)) { + serverTelemetryManager?.setCacheOutcome(CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED); + return [null, CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED]; + } + // must refresh (in the background) due to the refresh_in value + if (cachedAccessToken.refreshOn && + TimeUtils.isTokenExpired(cachedAccessToken.refreshOn.toString(), 0)) { + lastCacheOutcome = CacheOutcome.PROACTIVELY_REFRESHED; + serverTelemetryManager?.setCacheOutcome(CacheOutcome.PROACTIVELY_REFRESHED); + } + return [ + await ResponseHandler.generateAuthenticationResult(cryptoUtils, authority, { + account: null, + idToken: null, + accessToken: cachedAccessToken, + refreshToken: null, + appMetadata: null, + }, true, request), + lastCacheOutcome, + ]; + } + /** + * Reads access token from the cache + */ + readAccessTokenFromCache(authority, id, scopeSet, cacheManager, correlationId) { + const accessTokenFilter = { + homeAccountId: Constants.EMPTY_STRING, + environment: authority.canonicalAuthorityUrlComponents.HostNameAndPort, + credentialType: CredentialType.ACCESS_TOKEN, + clientId: id, + realm: authority.tenant, + target: ScopeSet.createSearchScopes(scopeSet.asArray()), + }; + const accessTokens = cacheManager.getAccessTokensByFilter(accessTokenFilter, correlationId); + if (accessTokens.length < 1) { + return null; + } + else if (accessTokens.length > 1) { + throw createClientAuthError(ClientAuthErrorCodes.multipleMatchingTokens); + } + return accessTokens[0]; + } + /** + * Makes a network call to request the token from the service + * @param request - CommonClientCredentialRequest provided by the developer + * @param authority - authority object + */ + async executeTokenRequest(request, authority, refreshAccessToken) { + let serverTokenResponse; + let reqTimestamp; + if (this.appTokenProvider) { + this.logger.info("Using appTokenProvider extensibility."); + const appTokenPropviderParameters = { + correlationId: request.correlationId, + tenantId: this.config.authOptions.authority.tenant, + scopes: request.scopes, + claims: request.claims, + }; + reqTimestamp = TimeUtils.nowSeconds(); + const appTokenProviderResult = await this.appTokenProvider(appTokenPropviderParameters); + serverTokenResponse = { + access_token: appTokenProviderResult.accessToken, + expires_in: appTokenProviderResult.expiresInSeconds, + refresh_in: appTokenProviderResult.refreshInSeconds, + token_type: AuthenticationScheme.BEARER, + }; + } + else { + const queryParametersString = this.createTokenQueryParameters(request); + const endpoint = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString); + const requestBody = await this.createTokenRequestBody(request); + const headers = this.createTokenRequestHeaders(); + const thumbprint = { + clientId: this.config.authOptions.clientId, + authority: request.authority, + scopes: request.scopes, + claims: request.claims, + authenticationScheme: request.authenticationScheme, + resourceRequestMethod: request.resourceRequestMethod, + resourceRequestUri: request.resourceRequestUri, + shrClaims: request.shrClaims, + sshKid: request.sshKid, + }; + this.logger.info("Sending token request to endpoint: " + authority.tokenEndpoint); + reqTimestamp = TimeUtils.nowSeconds(); + const response = await this.executePostToTokenEndpoint(endpoint, requestBody, headers, thumbprint, request.correlationId); + serverTokenResponse = response.body; + serverTokenResponse.status = response.status; + } + const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.config.serializableCache, this.config.persistencePlugin); + responseHandler.validateTokenResponse(serverTokenResponse, refreshAccessToken); + const tokenResponse = await responseHandler.handleServerTokenResponse(serverTokenResponse, this.authority, reqTimestamp, request); + return tokenResponse; + } + /** + * generate the request to the server in the acceptable format + * @param request - CommonClientCredentialRequest provided by the developer + */ + async createTokenRequestBody(request) { + const parameters = new Map(); + RequestParameterBuilder.addClientId(parameters, this.config.authOptions.clientId); + RequestParameterBuilder.addScopes(parameters, request.scopes, false); + RequestParameterBuilder.addGrantType(parameters, GrantType.CLIENT_CREDENTIALS_GRANT); + RequestParameterBuilder.addLibraryInfo(parameters, this.config.libraryInfo); + RequestParameterBuilder.addApplicationTelemetry(parameters, this.config.telemetry.application); + RequestParameterBuilder.addThrottling(parameters); + if (this.serverTelemetryManager) { + RequestParameterBuilder.addServerTelemetry(parameters, this.serverTelemetryManager); + } + const correlationId = request.correlationId || + this.config.cryptoInterface.createNewGuid(); + RequestParameterBuilder.addCorrelationId(parameters, correlationId); + if (this.config.clientCredentials.clientSecret) { + RequestParameterBuilder.addClientSecret(parameters, this.config.clientCredentials.clientSecret); + } + // Use clientAssertion from request, fallback to client assertion in base configuration + const clientAssertion = request.clientAssertion || + this.config.clientCredentials.clientAssertion; + if (clientAssertion) { + RequestParameterBuilder.addClientAssertion(parameters, await getClientAssertion(clientAssertion.assertion, this.config.authOptions.clientId, request.resourceRequestUri)); + RequestParameterBuilder.addClientAssertionType(parameters, clientAssertion.assertionType); + } + if (!StringUtils.isEmptyObj(request.claims) || + (this.config.authOptions.clientCapabilities && + this.config.authOptions.clientCapabilities.length > 0)) { + RequestParameterBuilder.addClaims(parameters, request.claims, this.config.authOptions.clientCapabilities); + } + return UrlUtils.mapToQueryString(parameters); + } +} + +export { ClientCredentialClient }; +//# sourceMappingURL=ClientCredentialClient.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/client/ConfidentialClientApplication.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/client/ConfidentialClientApplication.mjs new file mode 100644 index 00000000..72c7b350 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/client/ConfidentialClientApplication.mjs @@ -0,0 +1,194 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { ClientApplication } from './ClientApplication.mjs'; +import { ClientAssertion } from './ClientAssertion.mjs'; +import { Constants, MSAL_FORCE_REGION, REGION_ENVIRONMENT_VARIABLE, ApiId } from '../utils/Constants.mjs'; +import { createClientAuthError, ClientAuthErrorCodes, getClientAssertion, OIDC_DEFAULT_SCOPES, UrlString, AADAuthorityConstants, AuthError } from '@azure/msal-common/node'; +import { ClientCredentialClient } from './ClientCredentialClient.mjs'; +import { OnBehalfOfClient } from './OnBehalfOfClient.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +// AADAuthorityConstants +/** + * This class is to be used to acquire tokens for confidential client applications (webApp, webAPI). Confidential client applications + * will configure application secrets, client certificates/assertions as applicable + * @public + */ +class ConfidentialClientApplication extends ClientApplication { + /** + * Constructor for the ConfidentialClientApplication + * + * Required attributes in the Configuration object are: + * - clientID: the application ID of your application. You can obtain one by registering your application with our application registration portal + * - authority: the authority URL for your application. + * - client credential: Must set either client secret, certificate, or assertion for confidential clients. You can obtain a client secret from the application registration portal. + * + * In Azure AD, authority is a URL indicating of the form https://login.microsoftonline.com/\{Enter_the_Tenant_Info_Here\}. + * If your application supports Accounts in one organizational directory, replace "Enter_the_Tenant_Info_Here" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com). + * If your application supports Accounts in any organizational directory, replace "Enter_the_Tenant_Info_Here" value with organizations. + * If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace "Enter_the_Tenant_Info_Here" value with common. + * To restrict support to Personal Microsoft accounts only, replace "Enter_the_Tenant_Info_Here" value with consumers. + * + * In Azure B2C, authority is of the form https://\{instance\}/tfp/\{tenant\}/\{policyName\}/ + * Full B2C functionality will be available in this library in future versions. + * + * @param Configuration - configuration object for the MSAL ConfidentialClientApplication instance + */ + constructor(configuration) { + super(configuration); + const clientSecretNotEmpty = !!this.config.auth.clientSecret; + const clientAssertionNotEmpty = !!this.config.auth.clientAssertion; + const certificateNotEmpty = (!!this.config.auth.clientCertificate?.thumbprint || + !!this.config.auth.clientCertificate?.thumbprintSha256) && + !!this.config.auth.clientCertificate?.privateKey; + /* + * If app developer configures this callback, they don't need a credential + * i.e. AzureSDK can get token from Managed Identity without a cert / secret + */ + if (this.appTokenProvider) { + return; + } + // Check that at most one credential is set on the application + if ((clientSecretNotEmpty && clientAssertionNotEmpty) || + (clientAssertionNotEmpty && certificateNotEmpty) || + (clientSecretNotEmpty && certificateNotEmpty)) { + throw createClientAuthError(ClientAuthErrorCodes.invalidClientCredential); + } + if (this.config.auth.clientSecret) { + this.clientSecret = this.config.auth.clientSecret; + return; + } + if (this.config.auth.clientAssertion) { + this.developerProvidedClientAssertion = + this.config.auth.clientAssertion; + return; + } + if (!certificateNotEmpty) { + throw createClientAuthError(ClientAuthErrorCodes.invalidClientCredential); + } + else { + this.clientAssertion = !!this.config.auth.clientCertificate + .thumbprintSha256 + ? ClientAssertion.fromCertificateWithSha256Thumbprint(this.config.auth.clientCertificate.thumbprintSha256, this.config.auth.clientCertificate.privateKey, this.config.auth.clientCertificate.x5c) + : ClientAssertion.fromCertificate( + // guaranteed to be a string, due to prior error checking in this function + this.config.auth.clientCertificate.thumbprint, this.config.auth.clientCertificate.privateKey, this.config.auth.clientCertificate.x5c); + } + this.appTokenProvider = undefined; + } + /** + * This extensibility point only works for the client_credential flow, i.e. acquireTokenByClientCredential and + * is meant for Azure SDK to enhance Managed Identity support. + * + * @param IAppTokenProvider - Extensibility interface, which allows the app developer to return a token from a custom source. + */ + SetAppTokenProvider(provider) { + this.appTokenProvider = provider; + } + /** + * Acquires tokens from the authority for the application (not for an end user). + */ + async acquireTokenByClientCredential(request) { + this.logger.info("acquireTokenByClientCredential called", request.correlationId); + // If there is a client assertion present in the request, it overrides the one present in the client configuration + let clientAssertion; + if (request.clientAssertion) { + clientAssertion = { + assertion: await getClientAssertion(request.clientAssertion, this.config.auth.clientId + // tokenEndpoint will be undefined. resourceRequestUri is omitted in ClientCredentialRequest + ), + assertionType: Constants.JWT_BEARER_ASSERTION_TYPE, + }; + } + const baseRequest = await this.initializeBaseRequest(request); + // valid base request should not contain oidc scopes in this grant type + const validBaseRequest = { + ...baseRequest, + scopes: baseRequest.scopes.filter((scope) => !OIDC_DEFAULT_SCOPES.includes(scope)), + }; + const validRequest = { + ...request, + ...validBaseRequest, + clientAssertion, + }; + /* + * valid request should not have "common" or "organizations" in lieu of the tenant_id in the authority in the auth configuration + * example authority: "https://login.microsoftonline.com/TenantId", + */ + const authority = new UrlString(validRequest.authority); + const tenantId = authority.getUrlComponents().PathSegments[0]; + if (Object.values(AADAuthorityConstants).includes(tenantId)) { + throw createClientAuthError(ClientAuthErrorCodes.missingTenantIdError); + } + /* + * if this env variable is set, and the developer provided region isn't defined and isn't "DisableMsalForceRegion", + * MSAL shall opt-in to ESTS-R with the value of this variable + */ + const ENV_MSAL_FORCE_REGION = process.env[MSAL_FORCE_REGION]; + let region; + if (validRequest.azureRegion !== "DisableMsalForceRegion") { + if (!validRequest.azureRegion && ENV_MSAL_FORCE_REGION) { + region = ENV_MSAL_FORCE_REGION; + } + else { + region = validRequest.azureRegion; + } + } + const azureRegionConfiguration = { + azureRegion: region, + environmentRegion: process.env[REGION_ENVIRONMENT_VARIABLE], + }; + const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByClientCredential, validRequest.correlationId, validRequest.skipCache); + try { + const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, azureRegionConfiguration, request.azureCloudOptions); + const clientCredentialConfig = await this.buildOauthClientConfiguration(discoveredAuthority, validRequest.correlationId, "", serverTelemetryManager); + const clientCredentialClient = new ClientCredentialClient(clientCredentialConfig, this.appTokenProvider); + this.logger.verbose("Client credential client created", validRequest.correlationId); + return await clientCredentialClient.acquireToken(validRequest); + } + catch (e) { + if (e instanceof AuthError) { + e.setCorrelationId(validRequest.correlationId); + } + serverTelemetryManager.cacheFailedRequest(e); + throw e; + } + } + /** + * Acquires tokens from the authority for the application. + * + * Used in scenarios where the current app is a middle-tier service which was called with a token + * representing an end user. The current app can use the token (oboAssertion) to request another + * token to access downstream web API, on behalf of that user. + * + * The current middle-tier app has no user interaction to obtain consent. + * See how to gain consent upfront for your middle-tier app from this article. + * https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow#gaining-consent-for-the-middle-tier-application + */ + async acquireTokenOnBehalfOf(request) { + this.logger.info("acquireTokenOnBehalfOf called", request.correlationId); + const validRequest = { + ...request, + ...(await this.initializeBaseRequest(request)), + }; + try { + const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, undefined, request.azureCloudOptions); + const onBehalfOfConfig = await this.buildOauthClientConfiguration(discoveredAuthority, validRequest.correlationId, "", undefined); + const oboClient = new OnBehalfOfClient(onBehalfOfConfig); + this.logger.verbose("On behalf of client created", validRequest.correlationId); + return await oboClient.acquireToken(validRequest); + } + catch (e) { + if (e instanceof AuthError) { + e.setCorrelationId(validRequest.correlationId); + } + throw e; + } + } +} + +export { ConfidentialClientApplication }; +//# sourceMappingURL=ConfidentialClientApplication.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/client/DeviceCodeClient.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/client/DeviceCodeClient.mjs new file mode 100644 index 00000000..5722f8f4 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/client/DeviceCodeClient.mjs @@ -0,0 +1,218 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { BaseClient, TimeUtils, ResponseHandler, UrlString, RequestParameterBuilder, UrlUtils, createClientAuthError, ClientAuthErrorCodes, Constants, createAuthError, AuthErrorCodes, GrantType, StringUtils } from '@azure/msal-common/node'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * OAuth2.0 Device code client + * @public + */ +class DeviceCodeClient extends BaseClient { + constructor(configuration) { + super(configuration); + } + /** + * Gets device code from device code endpoint, calls back to with device code response, and + * polls token endpoint to exchange device code for tokens + * @param request - developer provided CommonDeviceCodeRequest + */ + async acquireToken(request) { + const deviceCodeResponse = await this.getDeviceCode(request); + request.deviceCodeCallback(deviceCodeResponse); + const reqTimestamp = TimeUtils.nowSeconds(); + const response = await this.acquireTokenWithDeviceCode(request, deviceCodeResponse); + const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.config.serializableCache, this.config.persistencePlugin); + // Validate response. This function throws a server error if an error is returned by the server. + responseHandler.validateTokenResponse(response); + return responseHandler.handleServerTokenResponse(response, this.authority, reqTimestamp, request); + } + /** + * Creates device code request and executes http GET + * @param request - developer provided CommonDeviceCodeRequest + */ + async getDeviceCode(request) { + const queryParametersString = this.createExtraQueryParameters(request); + const endpoint = UrlString.appendQueryString(this.authority.deviceCodeEndpoint, queryParametersString); + const queryString = this.createQueryString(request); + const headers = this.createTokenRequestHeaders(); + const thumbprint = { + clientId: this.config.authOptions.clientId, + authority: request.authority, + scopes: request.scopes, + claims: request.claims, + authenticationScheme: request.authenticationScheme, + resourceRequestMethod: request.resourceRequestMethod, + resourceRequestUri: request.resourceRequestUri, + shrClaims: request.shrClaims, + sshKid: request.sshKid, + }; + return this.executePostRequestToDeviceCodeEndpoint(endpoint, queryString, headers, thumbprint, request.correlationId); + } + /** + * Creates query string for the device code request + * @param request - developer provided CommonDeviceCodeRequest + */ + createExtraQueryParameters(request) { + const parameters = new Map(); + if (request.extraQueryParameters) { + RequestParameterBuilder.addExtraQueryParameters(parameters, request.extraQueryParameters); + } + return UrlUtils.mapToQueryString(parameters); + } + /** + * Executes POST request to device code endpoint + * @param deviceCodeEndpoint - token endpoint + * @param queryString - string to be used in the body of the request + * @param headers - headers for the request + * @param thumbprint - unique request thumbprint + * @param correlationId - correlation id to be used in the request + */ + async executePostRequestToDeviceCodeEndpoint(deviceCodeEndpoint, queryString, headers, thumbprint, correlationId) { + const { body: { user_code: userCode, device_code: deviceCode, verification_uri: verificationUri, expires_in: expiresIn, interval, message, }, } = await this.sendPostRequest(thumbprint, deviceCodeEndpoint, { + body: queryString, + headers: headers, + }, correlationId); + return { + userCode, + deviceCode, + verificationUri, + expiresIn, + interval, + message, + }; + } + /** + * Create device code endpoint query parameters and returns string + * @param request - developer provided CommonDeviceCodeRequest + */ + createQueryString(request) { + const parameters = new Map(); + RequestParameterBuilder.addScopes(parameters, request.scopes); + RequestParameterBuilder.addClientId(parameters, this.config.authOptions.clientId); + if (request.extraQueryParameters) { + RequestParameterBuilder.addExtraQueryParameters(parameters, request.extraQueryParameters); + } + if (request.claims || + (this.config.authOptions.clientCapabilities && + this.config.authOptions.clientCapabilities.length > 0)) { + RequestParameterBuilder.addClaims(parameters, request.claims, this.config.authOptions.clientCapabilities); + } + return UrlUtils.mapToQueryString(parameters); + } + /** + * Breaks the polling with specific conditions + * @param deviceCodeExpirationTime - expiration time for the device code request + * @param userSpecifiedTimeout - developer provided timeout, to be compared against deviceCodeExpirationTime + * @param userSpecifiedCancelFlag - boolean indicating the developer would like to cancel the request + */ + continuePolling(deviceCodeExpirationTime, userSpecifiedTimeout, userSpecifiedCancelFlag) { + if (userSpecifiedCancelFlag) { + this.logger.error("Token request cancelled by setting DeviceCodeRequest.cancel = true"); + throw createClientAuthError(ClientAuthErrorCodes.deviceCodePollingCancelled); + } + else if (userSpecifiedTimeout && + userSpecifiedTimeout < deviceCodeExpirationTime && + TimeUtils.nowSeconds() > userSpecifiedTimeout) { + this.logger.error(`User defined timeout for device code polling reached. The timeout was set for ${userSpecifiedTimeout}`); + throw createClientAuthError(ClientAuthErrorCodes.userTimeoutReached); + } + else if (TimeUtils.nowSeconds() > deviceCodeExpirationTime) { + if (userSpecifiedTimeout) { + this.logger.verbose(`User specified timeout ignored as the device code has expired before the timeout elapsed. The user specified timeout was set for ${userSpecifiedTimeout}`); + } + this.logger.error(`Device code expired. Expiration time of device code was ${deviceCodeExpirationTime}`); + throw createClientAuthError(ClientAuthErrorCodes.deviceCodeExpired); + } + return true; + } + /** + * Creates token request with device code response and polls token endpoint at interval set by the device code response + * @param request - developer provided CommonDeviceCodeRequest + * @param deviceCodeResponse - DeviceCodeResponse returned by the security token service device code endpoint + */ + async acquireTokenWithDeviceCode(request, deviceCodeResponse) { + const queryParametersString = this.createTokenQueryParameters(request); + const endpoint = UrlString.appendQueryString(this.authority.tokenEndpoint, queryParametersString); + const requestBody = this.createTokenRequestBody(request, deviceCodeResponse); + const headers = this.createTokenRequestHeaders(); + const userSpecifiedTimeout = request.timeout + ? TimeUtils.nowSeconds() + request.timeout + : undefined; + const deviceCodeExpirationTime = TimeUtils.nowSeconds() + deviceCodeResponse.expiresIn; + const pollingIntervalMilli = deviceCodeResponse.interval * 1000; + /* + * Poll token endpoint while (device code is not expired AND operation has not been cancelled by + * setting CancellationToken.cancel = true). POST request is sent at interval set by pollingIntervalMilli + */ + while (this.continuePolling(deviceCodeExpirationTime, userSpecifiedTimeout, request.cancel)) { + const thumbprint = { + clientId: this.config.authOptions.clientId, + authority: request.authority, + scopes: request.scopes, + claims: request.claims, + authenticationScheme: request.authenticationScheme, + resourceRequestMethod: request.resourceRequestMethod, + resourceRequestUri: request.resourceRequestUri, + shrClaims: request.shrClaims, + sshKid: request.sshKid, + }; + const response = await this.executePostToTokenEndpoint(endpoint, requestBody, headers, thumbprint, request.correlationId); + if (response.body && response.body.error) { + // user authorization is pending. Sleep for polling interval and try again + if (response.body.error === Constants.AUTHORIZATION_PENDING) { + this.logger.info("Authorization pending. Continue polling."); + await TimeUtils.delay(pollingIntervalMilli); + } + else { + // for any other error, throw + this.logger.info("Unexpected error in polling from the server"); + throw createAuthError(AuthErrorCodes.postRequestFailed, response.body.error); + } + } + else { + this.logger.verbose("Authorization completed successfully. Polling stopped."); + return response.body; + } + } + /* + * The above code should've thrown by this point, but to satisfy TypeScript, + * and in the rare case the conditionals in continuePolling() may not catch everything... + */ + this.logger.error("Polling stopped for unknown reasons."); + throw createClientAuthError(ClientAuthErrorCodes.deviceCodeUnknownError); + } + /** + * Creates query parameters and converts to string. + * @param request - developer provided CommonDeviceCodeRequest + * @param deviceCodeResponse - DeviceCodeResponse returned by the security token service device code endpoint + */ + createTokenRequestBody(request, deviceCodeResponse) { + const parameters = new Map(); + RequestParameterBuilder.addScopes(parameters, request.scopes); + RequestParameterBuilder.addClientId(parameters, this.config.authOptions.clientId); + RequestParameterBuilder.addGrantType(parameters, GrantType.DEVICE_CODE_GRANT); + RequestParameterBuilder.addDeviceCode(parameters, deviceCodeResponse.deviceCode); + const correlationId = request.correlationId || + this.config.cryptoInterface.createNewGuid(); + RequestParameterBuilder.addCorrelationId(parameters, correlationId); + RequestParameterBuilder.addClientInfo(parameters); + RequestParameterBuilder.addLibraryInfo(parameters, this.config.libraryInfo); + RequestParameterBuilder.addApplicationTelemetry(parameters, this.config.telemetry.application); + RequestParameterBuilder.addThrottling(parameters); + if (this.serverTelemetryManager) { + RequestParameterBuilder.addServerTelemetry(parameters, this.serverTelemetryManager); + } + if (!StringUtils.isEmptyObj(request.claims) || + (this.config.authOptions.clientCapabilities && + this.config.authOptions.clientCapabilities.length > 0)) { + RequestParameterBuilder.addClaims(parameters, request.claims, this.config.authOptions.clientCapabilities); + } + return UrlUtils.mapToQueryString(parameters); + } +} + +export { DeviceCodeClient }; +//# sourceMappingURL=DeviceCodeClient.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentityApplication.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentityApplication.mjs new file mode 100644 index 00000000..509701fc --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentityApplication.mjs @@ -0,0 +1,134 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { Logger, DEFAULT_CRYPTO_IMPLEMENTATION, Constants, Authority, ProtocolMode, createClientConfigurationError, ClientConfigurationErrorCodes, EncodingTypes, CacheOutcome } from '@azure/msal-common/node'; +import { buildManagedIdentityConfiguration } from '../config/Configuration.mjs'; +import { name, version } from '../packageMetadata.mjs'; +import { CryptoProvider } from '../crypto/CryptoProvider.mjs'; +import { ClientCredentialClient } from './ClientCredentialClient.mjs'; +import { ManagedIdentityClient } from './ManagedIdentityClient.mjs'; +import { NodeStorage } from '../cache/NodeStorage.mjs'; +import { DEFAULT_AUTHORITY_FOR_MANAGED_IDENTITY, ManagedIdentitySourceNames } from '../utils/Constants.mjs'; +import { HashUtils } from '../crypto/HashUtils.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +const SOURCES_THAT_SUPPORT_TOKEN_REVOCATION = [ManagedIdentitySourceNames.SERVICE_FABRIC]; +/** + * Class to initialize a managed identity and identify the service + * @public + */ +class ManagedIdentityApplication { + constructor(configuration) { + // undefined config means the managed identity is system-assigned + this.config = buildManagedIdentityConfiguration(configuration || {}); + this.logger = new Logger(this.config.system.loggerOptions, name, version); + const fakeStatusAuthorityOptions = { + canonicalAuthority: Constants.DEFAULT_AUTHORITY, + }; + if (!ManagedIdentityApplication.nodeStorage) { + ManagedIdentityApplication.nodeStorage = new NodeStorage(this.logger, this.config.managedIdentityId.id, DEFAULT_CRYPTO_IMPLEMENTATION, fakeStatusAuthorityOptions); + } + this.networkClient = this.config.system.networkClient; + this.cryptoProvider = new CryptoProvider(); + const fakeAuthorityOptions = { + protocolMode: ProtocolMode.AAD, + knownAuthorities: [DEFAULT_AUTHORITY_FOR_MANAGED_IDENTITY], + cloudDiscoveryMetadata: "", + authorityMetadata: "", + }; + this.fakeAuthority = new Authority(DEFAULT_AUTHORITY_FOR_MANAGED_IDENTITY, this.networkClient, ManagedIdentityApplication.nodeStorage, fakeAuthorityOptions, this.logger, this.cryptoProvider.createNewGuid(), // correlationID + undefined, true); + this.fakeClientCredentialClient = new ClientCredentialClient({ + authOptions: { + clientId: this.config.managedIdentityId.id, + authority: this.fakeAuthority, + }, + }); + this.managedIdentityClient = new ManagedIdentityClient(this.logger, ManagedIdentityApplication.nodeStorage, this.networkClient, this.cryptoProvider, this.config.disableInternalRetries); + this.hashUtils = new HashUtils(); + } + /** + * Acquire an access token from the cache or the managed identity + * @param managedIdentityRequest - the ManagedIdentityRequestParams object passed in by the developer + * @returns the access token + */ + async acquireToken(managedIdentityRequestParams) { + if (!managedIdentityRequestParams.resource) { + throw createClientConfigurationError(ClientConfigurationErrorCodes.urlEmptyError); + } + const managedIdentityRequest = { + forceRefresh: managedIdentityRequestParams.forceRefresh, + resource: managedIdentityRequestParams.resource.replace("/.default", ""), + scopes: [ + managedIdentityRequestParams.resource.replace("/.default", ""), + ], + authority: this.fakeAuthority.canonicalAuthority, + correlationId: this.cryptoProvider.createNewGuid(), + claims: managedIdentityRequestParams.claims, + clientCapabilities: this.config.clientCapabilities, + }; + if (managedIdentityRequest.forceRefresh) { + return this.acquireTokenFromManagedIdentity(managedIdentityRequest, this.config.managedIdentityId, this.fakeAuthority); + } + const [cachedAuthenticationResult, lastCacheOutcome] = await this.fakeClientCredentialClient.getCachedAuthenticationResult(managedIdentityRequest, this.config, this.cryptoProvider, this.fakeAuthority, ManagedIdentityApplication.nodeStorage); + /* + * Check if claims are present in the managed identity request. + * If so, the cached token will not be used. + */ + if (managedIdentityRequest.claims) { + const sourceName = this.managedIdentityClient.getManagedIdentitySource(); + /* + * Check if there is a cached token and if the Managed Identity source supports token revocation. + * If so, hash the cached access token and add it to the request. + */ + if (cachedAuthenticationResult && + SOURCES_THAT_SUPPORT_TOKEN_REVOCATION.includes(sourceName)) { + const revokedTokenSha256Hash = this.hashUtils + .sha256(cachedAuthenticationResult.accessToken) + .toString(EncodingTypes.HEX); + managedIdentityRequest.revokedTokenSha256Hash = + revokedTokenSha256Hash; + } + return this.acquireTokenFromManagedIdentity(managedIdentityRequest, this.config.managedIdentityId, this.fakeAuthority); + } + if (cachedAuthenticationResult) { + // if the token is not expired but must be refreshed; get a new one in the background + if (lastCacheOutcome === CacheOutcome.PROACTIVELY_REFRESHED) { + this.logger.info("ClientCredentialClient:getCachedAuthenticationResult - Cached access token's refreshOn property has been exceeded'. It's not expired, but must be refreshed."); + // force refresh; will run in the background + const refreshAccessToken = true; + await this.acquireTokenFromManagedIdentity(managedIdentityRequest, this.config.managedIdentityId, this.fakeAuthority, refreshAccessToken); + } + return cachedAuthenticationResult; + } + else { + return this.acquireTokenFromManagedIdentity(managedIdentityRequest, this.config.managedIdentityId, this.fakeAuthority); + } + } + /** + * Acquires a token from a managed identity endpoint. + * + * @param managedIdentityRequest - The request object containing parameters for the managed identity token request. + * @param managedIdentityId - The identifier for the managed identity (e.g., client ID or resource ID). + * @param fakeAuthority - A placeholder authority used for the token request. + * @param refreshAccessToken - Optional flag indicating whether to force a refresh of the access token. + * @returns A promise that resolves to an AuthenticationResult containing the acquired token and related information. + */ + async acquireTokenFromManagedIdentity(managedIdentityRequest, managedIdentityId, fakeAuthority, refreshAccessToken) { + // make a network call to the managed identity + return this.managedIdentityClient.sendManagedIdentityTokenRequest(managedIdentityRequest, managedIdentityId, fakeAuthority, refreshAccessToken); + } + /** + * Determine the Managed Identity Source based on available environment variables. This API is consumed by Azure Identity SDK. + * @returns ManagedIdentitySourceNames - The Managed Identity source's name + */ + getManagedIdentitySource() { + return (ManagedIdentityClient.sourceName || + this.managedIdentityClient.getManagedIdentitySource()); + } +} + +export { ManagedIdentityApplication }; +//# sourceMappingURL=ManagedIdentityApplication.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentityClient.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentityClient.mjs new file mode 100644 index 00000000..eecd866d --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentityClient.mjs @@ -0,0 +1,79 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { AppService } from './ManagedIdentitySources/AppService.mjs'; +import { AzureArc } from './ManagedIdentitySources/AzureArc.mjs'; +import { CloudShell } from './ManagedIdentitySources/CloudShell.mjs'; +import { Imds } from './ManagedIdentitySources/Imds.mjs'; +import { ServiceFabric } from './ManagedIdentitySources/ServiceFabric.mjs'; +import { createManagedIdentityError } from '../error/ManagedIdentityError.mjs'; +import { ManagedIdentitySourceNames } from '../utils/Constants.mjs'; +import { MachineLearning } from './ManagedIdentitySources/MachineLearning.mjs'; +import { unableToCreateSource } from '../error/ManagedIdentityErrorCodes.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/* + * Class to initialize a managed identity and identify the service. + * Original source of code: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/ManagedIdentityClient.cs + */ +class ManagedIdentityClient { + constructor(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries) { + this.logger = logger; + this.nodeStorage = nodeStorage; + this.networkClient = networkClient; + this.cryptoProvider = cryptoProvider; + this.disableInternalRetries = disableInternalRetries; + } + async sendManagedIdentityTokenRequest(managedIdentityRequest, managedIdentityId, fakeAuthority, refreshAccessToken) { + if (!ManagedIdentityClient.identitySource) { + ManagedIdentityClient.identitySource = + this.selectManagedIdentitySource(this.logger, this.nodeStorage, this.networkClient, this.cryptoProvider, this.disableInternalRetries, managedIdentityId); + } + return ManagedIdentityClient.identitySource.acquireTokenWithManagedIdentity(managedIdentityRequest, managedIdentityId, fakeAuthority, refreshAccessToken); + } + allEnvironmentVariablesAreDefined(environmentVariables) { + return Object.values(environmentVariables).every((environmentVariable) => { + return environmentVariable !== undefined; + }); + } + /** + * Determine the Managed Identity Source based on available environment variables. This API is consumed by ManagedIdentityApplication's getManagedIdentitySource. + * @returns ManagedIdentitySourceNames - The Managed Identity source's name + */ + getManagedIdentitySource() { + ManagedIdentityClient.sourceName = + this.allEnvironmentVariablesAreDefined(ServiceFabric.getEnvironmentVariables()) + ? ManagedIdentitySourceNames.SERVICE_FABRIC + : this.allEnvironmentVariablesAreDefined(AppService.getEnvironmentVariables()) + ? ManagedIdentitySourceNames.APP_SERVICE + : this.allEnvironmentVariablesAreDefined(MachineLearning.getEnvironmentVariables()) + ? ManagedIdentitySourceNames.MACHINE_LEARNING + : this.allEnvironmentVariablesAreDefined(CloudShell.getEnvironmentVariables()) + ? ManagedIdentitySourceNames.CLOUD_SHELL + : this.allEnvironmentVariablesAreDefined(AzureArc.getEnvironmentVariables()) + ? ManagedIdentitySourceNames.AZURE_ARC + : ManagedIdentitySourceNames.DEFAULT_TO_IMDS; + return ManagedIdentityClient.sourceName; + } + /** + * Tries to create a managed identity source for all sources + * @returns the managed identity Source + */ + selectManagedIdentitySource(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, managedIdentityId) { + const source = ServiceFabric.tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, managedIdentityId) || + AppService.tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries) || + MachineLearning.tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries) || + CloudShell.tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, managedIdentityId) || + AzureArc.tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, managedIdentityId) || + Imds.tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries); + if (!source) { + throw createManagedIdentityError(unableToCreateSource); + } + return source; + } +} + +export { ManagedIdentityClient }; +//# sourceMappingURL=ManagedIdentityClient.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/AppService.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/AppService.mjs new file mode 100644 index 00000000..0dd165fa --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/AppService.mjs @@ -0,0 +1,109 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { BaseManagedIdentitySource } from './BaseManagedIdentitySource.mjs'; +import { ManagedIdentityEnvironmentVariableNames, ManagedIdentitySourceNames, ManagedIdentityHeaders, ManagedIdentityQueryParameters, ManagedIdentityIdType, HttpMethod } from '../../utils/Constants.mjs'; +import { ManagedIdentityRequestParameters } from '../../config/ManagedIdentityRequestParameters.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +// MSI Constants. Docs for MSI are available here https://docs.microsoft.com/azure/app-service/overview-managed-identity +const APP_SERVICE_MSI_API_VERSION = "2019-08-01"; +/** + * Azure App Service Managed Identity Source implementation. + * + * This class provides managed identity authentication for applications running in Azure App Service. + * It uses the local metadata service endpoint available within App Service environments to obtain + * access tokens without requiring explicit credentials. + * + * Original source of code: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/AppServiceManagedIdentitySource.cs + */ +class AppService extends BaseManagedIdentitySource { + /** + * Creates a new instance of the AppService managed identity source. + * + * @param logger - Logger instance for diagnostic output + * @param nodeStorage - Node.js storage implementation for caching + * @param networkClient - Network client for making HTTP requests + * @param cryptoProvider - Cryptographic operations provider + * @param disableInternalRetries - Whether to disable internal retry logic + * @param identityEndpoint - The App Service identity endpoint URL + * @param identityHeader - The secret header value required for authentication + */ + constructor(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint, identityHeader) { + super(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries); + this.identityEndpoint = identityEndpoint; + this.identityHeader = identityHeader; + } + /** + * Retrieves the required environment variables for App Service managed identity. + * + * App Service managed identity requires two environment variables: + * - IDENTITY_ENDPOINT: The URL of the local metadata service + * - IDENTITY_HEADER: A secret header value for authentication + * + * @returns An array containing [identityEndpoint, identityHeader] values from environment variables. + * Either value may be undefined if the environment variable is not set. + */ + static getEnvironmentVariables() { + const identityEndpoint = process.env[ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT]; + const identityHeader = process.env[ManagedIdentityEnvironmentVariableNames.IDENTITY_HEADER]; + return [identityEndpoint, identityHeader]; + } + /** + * Attempts to create an AppService managed identity source if the environment supports it. + * + * This method checks for the presence of required environment variables and validates + * the identity endpoint URL. If the environment is not suitable for App Service managed + * identity (missing environment variables or invalid endpoint), it returns null. + * + * @param logger - Logger instance for diagnostic output + * @param nodeStorage - Node.js storage implementation for caching + * @param networkClient - Network client for making HTTP requests + * @param cryptoProvider - Cryptographic operations provider + * @param disableInternalRetries - Whether to disable internal retry logic + * + * @returns A new AppService instance if the environment is suitable, null otherwise + */ + static tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries) { + const [identityEndpoint, identityHeader] = AppService.getEnvironmentVariables(); + // if either of the identity endpoint or identity header variables are undefined, this MSI provider is unavailable. + if (!identityEndpoint || !identityHeader) { + logger.info(`[Managed Identity] ${ManagedIdentitySourceNames.APP_SERVICE} managed identity is unavailable because one or both of the '${ManagedIdentityEnvironmentVariableNames.IDENTITY_HEADER}' and '${ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT}' environment variables are not defined.`); + return null; + } + const validatedIdentityEndpoint = AppService.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT, identityEndpoint, ManagedIdentitySourceNames.APP_SERVICE, logger); + logger.info(`[Managed Identity] Environment variables validation passed for ${ManagedIdentitySourceNames.APP_SERVICE} managed identity. Endpoint URI: ${validatedIdentityEndpoint}. Creating ${ManagedIdentitySourceNames.APP_SERVICE} managed identity.`); + return new AppService(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint, identityHeader); + } + /** + * Creates a managed identity token request for the App Service environment. + * + * This method constructs an HTTP GET request to the App Service identity endpoint + * with the required headers, query parameters, and managed identity configuration. + * The request includes the secret header for authentication and appropriate API version. + * + * @param resource - The target resource/scope for which to request an access token (e.g., "https://graph.microsoft.com/.default") + * @param managedIdentityId - The managed identity configuration specifying whether to use system-assigned or user-assigned identity + * + * @returns A configured ManagedIdentityRequestParameters object ready for network execution + */ + createRequest(resource, managedIdentityId) { + const request = new ManagedIdentityRequestParameters(HttpMethod.GET, this.identityEndpoint); + request.headers[ManagedIdentityHeaders.APP_SERVICE_SECRET_HEADER_NAME] = + this.identityHeader; + request.queryParameters[ManagedIdentityQueryParameters.API_VERSION] = + APP_SERVICE_MSI_API_VERSION; + request.queryParameters[ManagedIdentityQueryParameters.RESOURCE] = + resource; + if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) { + request.queryParameters[this.getManagedIdentityUserAssignedIdQueryParameterKey(managedIdentityId.idType)] = managedIdentityId.id; + } + // bodyParameters calculated in BaseManagedIdentity.acquireTokenWithManagedIdentity + return request; + } +} + +export { AppService }; +//# sourceMappingURL=AppService.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/AzureArc.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/AzureArc.mjs new file mode 100644 index 00000000..ba1fd627 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/AzureArc.mjs @@ -0,0 +1,248 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { HttpStatus, EncodingTypes, AuthError, createClientAuthError, ClientAuthErrorCodes } from '@azure/msal-common/node'; +import { ManagedIdentityRequestParameters } from '../../config/ManagedIdentityRequestParameters.mjs'; +import { BaseManagedIdentitySource } from './BaseManagedIdentitySource.mjs'; +import { createManagedIdentityError } from '../../error/ManagedIdentityError.mjs'; +import { ManagedIdentityEnvironmentVariableNames, ManagedIdentitySourceNames, ManagedIdentityIdType, HttpMethod, ManagedIdentityHeaders, ManagedIdentityQueryParameters, AZURE_ARC_SECRET_FILE_MAX_SIZE_BYTES } from '../../utils/Constants.mjs'; +import { accessSync, constants, statSync, readFileSync } from 'fs'; +import path from 'path'; +import { unableToCreateAzureArc, wwwAuthenticateHeaderMissing, wwwAuthenticateHeaderUnsupportedFormat, platformNotSupported, invalidFileExtension, invalidFilePath, unableToReadSecretFile, invalidSecret } from '../../error/ManagedIdentityErrorCodes.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +const ARC_API_VERSION = "2019-11-01"; +const DEFAULT_AZURE_ARC_IDENTITY_ENDPOINT = "http://127.0.0.1:40342/metadata/identity/oauth2/token"; +const HIMDS_EXECUTABLE_HELPER_STRING = "N/A: himds executable exists"; +const SUPPORTED_AZURE_ARC_PLATFORMS = { + win32: `${process.env["ProgramData"]}\\AzureConnectedMachineAgent\\Tokens\\`, + linux: "/var/opt/azcmagent/tokens/", +}; +const AZURE_ARC_FILE_DETECTION = { + win32: `${process.env["ProgramFiles"]}\\AzureConnectedMachineAgent\\himds.exe`, + linux: "/opt/azcmagent/bin/himds", +}; +/** + * Azure Arc managed identity source implementation for acquiring tokens from Azure Arc-enabled servers. + * + * This class provides managed identity authentication for applications running on Azure Arc-enabled servers + * by communicating with the local Hybrid Instance Metadata Service (HIMDS). It supports both environment + * variable-based configuration and automatic detection through the HIMDS executable. + * + * Original source of code: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/AzureArcManagedIdentitySource.cs + */ +class AzureArc extends BaseManagedIdentitySource { + /** + * Creates a new instance of the AzureArc managed identity source. + * + * @param logger - Logger instance for capturing telemetry and diagnostic information + * @param nodeStorage - Storage implementation for caching tokens and metadata + * @param networkClient - Network client for making HTTP requests to the identity endpoint + * @param cryptoProvider - Cryptographic operations provider for token validation and encryption + * @param disableInternalRetries - Flag to disable automatic retry logic for failed requests + * @param identityEndpoint - The Azure Arc identity endpoint URL for token requests + */ + constructor(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint) { + super(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries); + this.identityEndpoint = identityEndpoint; + } + /** + * Retrieves and validates Azure Arc environment variables for managed identity configuration. + * + * This method checks for IDENTITY_ENDPOINT and IMDS_ENDPOINT environment variables. + * If either is missing, it attempts to detect the Azure Arc environment by checking for + * the HIMDS executable at platform-specific paths. On successful detection, it returns + * the default identity endpoint and a helper string indicating file-based detection. + * + * @returns An array containing [identityEndpoint, imdsEndpoint] where both values are + * strings if Azure Arc is available, or undefined if not available. + */ + static getEnvironmentVariables() { + let identityEndpoint = process.env[ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT]; + let imdsEndpoint = process.env[ManagedIdentityEnvironmentVariableNames.IMDS_ENDPOINT]; + // if either of the identity or imds endpoints are undefined, check if the himds executable exists + if (!identityEndpoint || !imdsEndpoint) { + // get the expected Windows or Linux file path of the himds executable + const fileDetectionPath = AZURE_ARC_FILE_DETECTION[process.platform]; + try { + /* + * check if the himds executable exists and its permissions allow it to be read + * returns undefined if true, throws an error otherwise + */ + accessSync(fileDetectionPath, constants.F_OK | constants.R_OK); + identityEndpoint = DEFAULT_AZURE_ARC_IDENTITY_ENDPOINT; + imdsEndpoint = HIMDS_EXECUTABLE_HELPER_STRING; + } + catch (err) { + /* + * do nothing + * accessSync returns undefined on success, and throws an error on failure + */ + } + } + return [identityEndpoint, imdsEndpoint]; + } + /** + * Attempts to create an AzureArc managed identity source instance. + * + * Validates the Azure Arc environment by checking environment variables + * and performing file-based detection. It ensures that only system-assigned managed identities + * are supported for Azure Arc scenarios. The method performs comprehensive validation of + * endpoint URLs and logs detailed information about the detection process. + * + * @param logger - Logger instance for capturing creation and validation steps + * @param nodeStorage - Storage implementation for the managed identity source + * @param networkClient - Network client for HTTP communication + * @param cryptoProvider - Cryptographic operations provider + * @param disableInternalRetries - Whether to disable automatic retry mechanisms + * @param managedIdentityId - The managed identity configuration, must be system-assigned + * + * @returns AzureArc instance if the environment supports Azure Arc managed identity, null otherwise + * + * @throws {ManagedIdentityError} When a user-assigned managed identity is specified (not supported for Azure Arc) + */ + static tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, managedIdentityId) { + const [identityEndpoint, imdsEndpoint] = AzureArc.getEnvironmentVariables(); + // if either of the identity or imds endpoints are undefined (even after himds file detection) + if (!identityEndpoint || !imdsEndpoint) { + logger.info(`[Managed Identity] ${ManagedIdentitySourceNames.AZURE_ARC} managed identity is unavailable through environment variables because one or both of '${ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT}' and '${ManagedIdentityEnvironmentVariableNames.IMDS_ENDPOINT}' are not defined. ${ManagedIdentitySourceNames.AZURE_ARC} managed identity is also unavailable through file detection.`); + return null; + } + // check if the imds endpoint is set to the default for file detection + if (imdsEndpoint === HIMDS_EXECUTABLE_HELPER_STRING) { + logger.info(`[Managed Identity] ${ManagedIdentitySourceNames.AZURE_ARC} managed identity is available through file detection. Defaulting to known ${ManagedIdentitySourceNames.AZURE_ARC} endpoint: ${DEFAULT_AZURE_ARC_IDENTITY_ENDPOINT}. Creating ${ManagedIdentitySourceNames.AZURE_ARC} managed identity.`); + } + else { + // otherwise, both the identity and imds endpoints are defined without file detection; validate them + const validatedIdentityEndpoint = AzureArc.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT, identityEndpoint, ManagedIdentitySourceNames.AZURE_ARC, logger); + // remove trailing slash + validatedIdentityEndpoint.endsWith("/") + ? validatedIdentityEndpoint.slice(0, -1) + : validatedIdentityEndpoint; + AzureArc.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.IMDS_ENDPOINT, imdsEndpoint, ManagedIdentitySourceNames.AZURE_ARC, logger); + logger.info(`[Managed Identity] Environment variables validation passed for ${ManagedIdentitySourceNames.AZURE_ARC} managed identity. Endpoint URI: ${validatedIdentityEndpoint}. Creating ${ManagedIdentitySourceNames.AZURE_ARC} managed identity.`); + } + if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) { + throw createManagedIdentityError(unableToCreateAzureArc); + } + return new AzureArc(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint); + } + /** + * Creates a properly formatted HTTP request for acquiring tokens from the Azure Arc identity endpoint. + * + * This method constructs a GET request to the Azure Arc HIMDS endpoint with the required metadata header + * and query parameters. The endpoint URL is normalized to use 127.0.0.1 instead of localhost for + * consistency. Additional body parameters are calculated by the base class during token acquisition. + * + * @param resource - The target resource/scope for which to request an access token (e.g., "https://graph.microsoft.com/.default") + * + * @returns A configured ManagedIdentityRequestParameters object ready for network execution + */ + createRequest(resource) { + const request = new ManagedIdentityRequestParameters(HttpMethod.GET, this.identityEndpoint.replace("localhost", "127.0.0.1")); + request.headers[ManagedIdentityHeaders.METADATA_HEADER_NAME] = "true"; + request.queryParameters[ManagedIdentityQueryParameters.API_VERSION] = + ARC_API_VERSION; + request.queryParameters[ManagedIdentityQueryParameters.RESOURCE] = + resource; + // bodyParameters calculated in BaseManagedIdentity.acquireTokenWithManagedIdentity + return request; + } + /** + * Processes the server response and handles Azure Arc-specific authentication challenges. + * + * This method implements the Azure Arc authentication flow which may require reading a secret file + * for authorization. When the initial request returns HTTP 401 Unauthorized, it extracts the file + * path from the WWW-Authenticate header, validates the file location and size, reads the secret, + * and retries the request with Basic authentication. The method includes comprehensive security + * validations to prevent path traversal and ensure file integrity. + * + * @param originalResponse - The initial HTTP response from the identity endpoint + * @param networkClient - Network client for making the retry request if needed + * @param networkRequest - The original request parameters (modified with auth header for retry) + * @param networkRequestOptions - Additional options for network requests + * + * @returns A promise that resolves to the server token response with access token and metadata + * + * @throws {ManagedIdentityError} When: + * - WWW-Authenticate header is missing or has unsupported format + * - Platform is not supported (not Windows or Linux) + * - Secret file has invalid extension (not .key) + * - Secret file path doesn't match expected platform path + * - Secret file cannot be read or is too large (>4096 bytes) + * @throws {ClientAuthError} When network errors occur during retry request + */ + async getServerTokenResponseAsync(originalResponse, networkClient, networkRequest, networkRequestOptions) { + let retryResponse; + if (originalResponse.status === HttpStatus.UNAUTHORIZED) { + const wwwAuthHeader = originalResponse.headers["www-authenticate"]; + if (!wwwAuthHeader) { + throw createManagedIdentityError(wwwAuthenticateHeaderMissing); + } + if (!wwwAuthHeader.includes("Basic realm=")) { + throw createManagedIdentityError(wwwAuthenticateHeaderUnsupportedFormat); + } + const secretFilePath = wwwAuthHeader.split("Basic realm=")[1]; + // throw an error if the managed identity application is not being run on Windows or Linux + if (!SUPPORTED_AZURE_ARC_PLATFORMS.hasOwnProperty(process.platform)) { + throw createManagedIdentityError(platformNotSupported); + } + // get the expected Windows or Linux file path + const expectedSecretFilePath = SUPPORTED_AZURE_ARC_PLATFORMS[process.platform]; + // throw an error if the file in the file path is not a .key file + const fileName = path.basename(secretFilePath); + if (!fileName.endsWith(".key")) { + throw createManagedIdentityError(invalidFileExtension); + } + /* + * throw an error if the file path from the www-authenticate header does not match the + * expected file path for the platform (Windows or Linux) the managed identity application + * is running on + */ + if (expectedSecretFilePath + fileName !== secretFilePath) { + throw createManagedIdentityError(invalidFilePath); + } + let secretFileSize; + // attempt to get the secret file's size, in bytes + try { + secretFileSize = await statSync(secretFilePath).size; + } + catch (e) { + throw createManagedIdentityError(unableToReadSecretFile); + } + // throw an error if the secret file's size is greater than 4096 bytes + if (secretFileSize > AZURE_ARC_SECRET_FILE_MAX_SIZE_BYTES) { + throw createManagedIdentityError(invalidSecret); + } + // attempt to read the contents of the secret file + let secret; + try { + secret = readFileSync(secretFilePath, EncodingTypes.UTF8); + } + catch (e) { + throw createManagedIdentityError(unableToReadSecretFile); + } + const authHeaderValue = `Basic ${secret}`; + this.logger.info(`[Managed Identity] Adding authorization header to the request.`); + networkRequest.headers[ManagedIdentityHeaders.AUTHORIZATION_HEADER_NAME] = authHeaderValue; + try { + retryResponse = + await networkClient.sendGetRequestAsync(networkRequest.computeUri(), networkRequestOptions); + } + catch (error) { + if (error instanceof AuthError) { + throw error; + } + else { + throw createClientAuthError(ClientAuthErrorCodes.networkError); + } + } + } + return this.getServerTokenResponse(retryResponse || originalResponse); + } +} + +export { ARC_API_VERSION, AZURE_ARC_FILE_DETECTION, AzureArc, DEFAULT_AZURE_ARC_IDENTITY_ENDPOINT, SUPPORTED_AZURE_ARC_PLATFORMS }; +//# sourceMappingURL=AzureArc.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/BaseManagedIdentitySource.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/BaseManagedIdentitySource.mjs new file mode 100644 index 00000000..8fcd2e96 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/BaseManagedIdentitySource.mjs @@ -0,0 +1,244 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { TimeUtils, Constants, HeaderNames, AuthError, createClientAuthError, ClientAuthErrorCodes, ResponseHandler, UrlString } from '@azure/msal-common/node'; +import { ManagedIdentityQueryParameters, HttpMethod, ManagedIdentityIdType } from '../../utils/Constants.mjs'; +import { createManagedIdentityError } from '../../error/ManagedIdentityError.mjs'; +import { isIso8601 } from '../../utils/TimeUtils.mjs'; +import { HttpClientWithRetries } from '../../network/HttpClientWithRetries.mjs'; +import { invalidManagedIdentityIdType, MsiEnvironmentVariableUrlMalformedErrorCodes } from '../../error/ManagedIdentityErrorCodes.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * Managed Identity User Assigned Id Query Parameter Names + */ +const ManagedIdentityUserAssignedIdQueryParameterNames = { + MANAGED_IDENTITY_CLIENT_ID_2017: "clientid", + MANAGED_IDENTITY_CLIENT_ID: "client_id", + MANAGED_IDENTITY_OBJECT_ID: "object_id", + MANAGED_IDENTITY_RESOURCE_ID_IMDS: "msi_res_id", + MANAGED_IDENTITY_RESOURCE_ID_NON_IMDS: "mi_res_id", +}; +/** + * Base class for all Managed Identity sources. Provides common functionality for + * authenticating with Azure Managed Identity endpoints across different Azure services + * including IMDS, App Service, Azure Arc, Service Fabric, Cloud Shell, and Machine Learning. + * + * This abstract class handles token acquisition, response processing, and network communication + * while allowing concrete implementations to define source-specific request creation logic. + */ +class BaseManagedIdentitySource { + /** + * Creates an instance of BaseManagedIdentitySource. + * + * @param logger - Logger instance for diagnostic information + * @param nodeStorage - Storage interface for caching tokens + * @param networkClient - Network client for making HTTP requests + * @param cryptoProvider - Cryptographic provider for token operations + * @param disableInternalRetries - Whether to disable automatic retry logic + */ + constructor(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries) { + this.logger = logger; + this.nodeStorage = nodeStorage; + this.networkClient = networkClient; + this.cryptoProvider = cryptoProvider; + this.disableInternalRetries = disableInternalRetries; + } + /** + * Processes the network response and converts it to a standardized server token response. + * This async version allows for source-specific response processing logic while maintaining + * backward compatibility with the synchronous version. + * + * @param response - The network response containing the managed identity token + * @param _networkClient - Network client used for the request (unused in base implementation) + * @param _networkRequest - The original network request parameters (unused in base implementation) + * @param _networkRequestOptions - The network request options (unused in base implementation) + * + * @returns Promise resolving to a standardized server authorization token response + */ + async getServerTokenResponseAsync(response, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _networkClient, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _networkRequest, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _networkRequestOptions) { + return this.getServerTokenResponse(response); + } + /** + * Converts a managed identity token response to a standardized server authorization token response. + * Handles time format conversion, expiration calculation, and error mapping to ensure + * compatibility with the MSAL response handling pipeline. + * + * @param response - The network response containing the managed identity token + * + * @returns Standardized server authorization token response with normalized fields + */ + getServerTokenResponse(response) { + let refreshIn, expiresIn; + if (response.body.expires_on) { + // if the expires_on field in the response body is a string and in ISO 8601 format, convert it to a Unix timestamp (seconds since epoch) + if (isIso8601(response.body.expires_on)) { + response.body.expires_on = + new Date(response.body.expires_on).getTime() / 1000; + } + expiresIn = response.body.expires_on - TimeUtils.nowSeconds(); + // compute refresh_in as 1/2 of expires_in, but only if expires_in > 2h + if (expiresIn > 2 * 3600) { + refreshIn = expiresIn / 2; + } + } + const serverTokenResponse = { + status: response.status, + // success + access_token: response.body.access_token, + expires_in: expiresIn, + scope: response.body.resource, + token_type: response.body.token_type, + refresh_in: refreshIn, + // error + correlation_id: response.body.correlation_id || response.body.correlationId, + error: typeof response.body.error === "string" + ? response.body.error + : response.body.error?.code, + error_description: response.body.message || + (typeof response.body.error === "string" + ? response.body.error_description + : response.body.error?.message), + error_codes: response.body.error_codes, + timestamp: response.body.timestamp, + trace_id: response.body.trace_id, + }; + return serverTokenResponse; + } + /** + * Acquires an access token using the managed identity endpoint for the specified resource. + * This is the primary method for token acquisition, handling the complete flow from + * request creation through response processing and token caching. + * + * @param managedIdentityRequest - The managed identity request containing resource and optional parameters + * @param managedIdentityId - The managed identity configuration (system or user-assigned) + * @param fakeAuthority - Authority instance used for token caching (managed identity uses a placeholder authority) + * @param refreshAccessToken - Whether this is a token refresh operation + * + * @returns Promise resolving to an authentication result containing the access token and metadata + * + * @throws {AuthError} When network requests fail or token validation fails + * @throws {ClientAuthError} When network errors occur during the request + */ + async acquireTokenWithManagedIdentity(managedIdentityRequest, managedIdentityId, fakeAuthority, refreshAccessToken) { + const networkRequest = this.createRequest(managedIdentityRequest.resource, managedIdentityId); + if (managedIdentityRequest.revokedTokenSha256Hash) { + this.logger.info(`[Managed Identity] The following claims are present in the request: ${managedIdentityRequest.claims}`); + networkRequest.queryParameters[ManagedIdentityQueryParameters.SHA256_TOKEN_TO_REFRESH] = managedIdentityRequest.revokedTokenSha256Hash; + } + if (managedIdentityRequest.clientCapabilities?.length) { + const clientCapabilities = managedIdentityRequest.clientCapabilities.toString(); + this.logger.info(`[Managed Identity] The following client capabilities are present in the request: ${clientCapabilities}`); + networkRequest.queryParameters[ManagedIdentityQueryParameters.XMS_CC] = clientCapabilities; + } + const headers = networkRequest.headers; + headers[HeaderNames.CONTENT_TYPE] = Constants.URL_FORM_CONTENT_TYPE; + const networkRequestOptions = { headers }; + if (Object.keys(networkRequest.bodyParameters).length) { + networkRequestOptions.body = + networkRequest.computeParametersBodyString(); + } + /** + * Initializes the network client helper based on the retry policy configuration. + * If internal retries are disabled, it uses the provided network client directly. + * Otherwise, it wraps the network client with an HTTP client that supports retries. + */ + const networkClientHelper = this.disableInternalRetries + ? this.networkClient + : new HttpClientWithRetries(this.networkClient, networkRequest.retryPolicy, this.logger); + const reqTimestamp = TimeUtils.nowSeconds(); + let response; + try { + // Sources that send POST requests: Cloud Shell + if (networkRequest.httpMethod === HttpMethod.POST) { + response = + await networkClientHelper.sendPostRequestAsync(networkRequest.computeUri(), networkRequestOptions); + // Sources that send GET requests: App Service, Azure Arc, IMDS, Service Fabric + } + else { + response = + await networkClientHelper.sendGetRequestAsync(networkRequest.computeUri(), networkRequestOptions); + } + } + catch (error) { + if (error instanceof AuthError) { + throw error; + } + else { + throw createClientAuthError(ClientAuthErrorCodes.networkError); + } + } + const responseHandler = new ResponseHandler(managedIdentityId.id, this.nodeStorage, this.cryptoProvider, this.logger, null, null); + const serverTokenResponse = await this.getServerTokenResponseAsync(response, networkClientHelper, networkRequest, networkRequestOptions); + responseHandler.validateTokenResponse(serverTokenResponse, refreshAccessToken); + // caches the token + return responseHandler.handleServerTokenResponse(serverTokenResponse, fakeAuthority, reqTimestamp, managedIdentityRequest); + } + /** + * Determines the appropriate query parameter name for user-assigned managed identity + * based on the identity type, API version, and endpoint characteristics. + * Different Azure services and API versions use different parameter names for the same identity types. + * + * @param managedIdentityIdType - The type of user-assigned managed identity (client ID, object ID, or resource ID) + * @param isImds - Whether the request is being made to the IMDS (Instance Metadata Service) endpoint + * @param usesApi2017 - Whether the endpoint uses the 2017-09-01 API version (affects client ID parameter name) + * + * @returns The correct query parameter name for the specified identity type and endpoint + * + * @throws {ManagedIdentityError} When an invalid managed identity ID type is provided + */ + getManagedIdentityUserAssignedIdQueryParameterKey(managedIdentityIdType, isImds, usesApi2017) { + switch (managedIdentityIdType) { + case ManagedIdentityIdType.USER_ASSIGNED_CLIENT_ID: + this.logger.info(`[Managed Identity] [API version ${usesApi2017 ? "2017+" : "2019+"}] Adding user assigned client id to the request.`); + // The Machine Learning source uses the 2017-09-01 API version, which uses "clientid" instead of "client_id" + return usesApi2017 + ? ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_CLIENT_ID_2017 + : ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_CLIENT_ID; + case ManagedIdentityIdType.USER_ASSIGNED_RESOURCE_ID: + this.logger.info("[Managed Identity] Adding user assigned resource id to the request."); + return isImds + ? ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_RESOURCE_ID_IMDS + : ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_RESOURCE_ID_NON_IMDS; + case ManagedIdentityIdType.USER_ASSIGNED_OBJECT_ID: + this.logger.info("[Managed Identity] Adding user assigned object id to the request."); + return ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_OBJECT_ID; + default: + throw createManagedIdentityError(invalidManagedIdentityIdType); + } + } +} +/** + * Validates and normalizes an environment variable containing a URL string. + * This static utility method ensures that environment variables used for managed identity + * endpoints contain properly formatted URLs and provides informative error messages when validation fails. + * + * @param envVariableStringName - The name of the environment variable being validated (for error reporting) + * @param envVariable - The environment variable value containing the URL string + * @param sourceName - The name of the managed identity source (for error reporting) + * @param logger - Logger instance for diagnostic information + * + * @returns The validated and normalized URL string + * + * @throws {ManagedIdentityError} When the environment variable contains a malformed URL + */ +BaseManagedIdentitySource.getValidatedEnvVariableUrlString = (envVariableStringName, envVariable, sourceName, logger) => { + try { + return new UrlString(envVariable).urlString; + } + catch (error) { + logger.info(`[Managed Identity] ${sourceName} managed identity is unavailable because the '${envVariableStringName}' environment variable is malformed.`); + throw createManagedIdentityError(MsiEnvironmentVariableUrlMalformedErrorCodes[envVariableStringName]); + } +}; + +export { BaseManagedIdentitySource, ManagedIdentityUserAssignedIdQueryParameterNames }; +//# sourceMappingURL=BaseManagedIdentitySource.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/CloudShell.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/CloudShell.mjs new file mode 100644 index 00000000..8489cb1a --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/CloudShell.mjs @@ -0,0 +1,103 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { ManagedIdentityRequestParameters } from '../../config/ManagedIdentityRequestParameters.mjs'; +import { BaseManagedIdentitySource } from './BaseManagedIdentitySource.mjs'; +import { ManagedIdentityEnvironmentVariableNames, ManagedIdentitySourceNames, ManagedIdentityIdType, ManagedIdentityHeaders, ManagedIdentityQueryParameters, HttpMethod } from '../../utils/Constants.mjs'; +import { createManagedIdentityError } from '../../error/ManagedIdentityError.mjs'; +import { unableToCreateCloudShell } from '../../error/ManagedIdentityErrorCodes.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * Azure Cloud Shell managed identity source implementation. + * + * This class handles authentication for applications running in Azure Cloud Shell environment. + * Cloud Shell provides a browser-accessible shell for managing Azure resources and includes + * a pre-configured managed identity for authentication. + * + * Original source of code: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/CloudShellManagedIdentitySource.cs + */ +class CloudShell extends BaseManagedIdentitySource { + /** + * Creates a new CloudShell managed identity source instance. + * + * @param logger - Logger instance for diagnostic logging + * @param nodeStorage - Node.js storage implementation for caching + * @param networkClient - HTTP client for making requests to the managed identity endpoint + * @param cryptoProvider - Cryptographic operations provider + * @param disableInternalRetries - Whether to disable automatic retry logic for failed requests + * @param msiEndpoint - The MSI endpoint URL obtained from environment variables + */ + constructor(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, msiEndpoint) { + super(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries); + this.msiEndpoint = msiEndpoint; + } + /** + * Retrieves the required environment variables for Cloud Shell managed identity. + * + * Cloud Shell requires the MSI_ENDPOINT environment variable to be set, which + * contains the URL of the managed identity service endpoint. + * + * @returns An array containing the MSI_ENDPOINT environment variable value (or undefined if not set) + */ + static getEnvironmentVariables() { + const msiEndpoint = process.env[ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT]; + return [msiEndpoint]; + } + /** + * Attempts to create a CloudShell managed identity source instance. + * + * This method validates that the required environment variables are present and + * creates a CloudShell instance if the environment is properly configured. + * Cloud Shell only supports system-assigned managed identities. + * + * @param logger - Logger instance for diagnostic logging + * @param nodeStorage - Node.js storage implementation for caching + * @param networkClient - HTTP client for making requests + * @param cryptoProvider - Cryptographic operations provider + * @param disableInternalRetries - Whether to disable automatic retry logic + * @param managedIdentityId - The managed identity configuration (must be system-assigned) + * + * @returns A CloudShell instance if the environment is valid, null otherwise + * + * @throws {ManagedIdentityError} When a user-assigned managed identity is requested, + * as Cloud Shell only supports system-assigned identities + */ + static tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, managedIdentityId) { + const [msiEndpoint] = CloudShell.getEnvironmentVariables(); + // if the msi endpoint environment variable is undefined, this MSI provider is unavailable. + if (!msiEndpoint) { + logger.info(`[Managed Identity] ${ManagedIdentitySourceNames.CLOUD_SHELL} managed identity is unavailable because the '${ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT} environment variable is not defined.`); + return null; + } + const validatedMsiEndpoint = CloudShell.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT, msiEndpoint, ManagedIdentitySourceNames.CLOUD_SHELL, logger); + logger.info(`[Managed Identity] Environment variable validation passed for ${ManagedIdentitySourceNames.CLOUD_SHELL} managed identity. Endpoint URI: ${validatedMsiEndpoint}. Creating ${ManagedIdentitySourceNames.CLOUD_SHELL} managed identity.`); + if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) { + throw createManagedIdentityError(unableToCreateCloudShell); + } + return new CloudShell(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, msiEndpoint); + } + /** + * Creates an HTTP request to acquire an access token from the Cloud Shell managed identity endpoint. + * + * This method constructs a POST request to the MSI endpoint with the required headers and + * body parameters for Cloud Shell authentication. The request includes the target resource + * for which the access token is being requested. + * + * @param resource - The target resource/scope for which to request an access token (e.g., "https://graph.microsoft.com/.default") + * + * @returns A configured ManagedIdentityRequestParameters object ready for network execution + */ + createRequest(resource) { + const request = new ManagedIdentityRequestParameters(HttpMethod.POST, this.msiEndpoint); + request.headers[ManagedIdentityHeaders.METADATA_HEADER_NAME] = "true"; + request.bodyParameters[ManagedIdentityQueryParameters.RESOURCE] = + resource; + return request; + } +} + +export { CloudShell }; +//# sourceMappingURL=CloudShell.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/Imds.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/Imds.mjs new file mode 100644 index 00000000..002c4764 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/Imds.mjs @@ -0,0 +1,108 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { ManagedIdentityRequestParameters } from '../../config/ManagedIdentityRequestParameters.mjs'; +import { BaseManagedIdentitySource } from './BaseManagedIdentitySource.mjs'; +import { ManagedIdentityEnvironmentVariableNames, ManagedIdentitySourceNames, ManagedIdentityHeaders, ManagedIdentityQueryParameters, ManagedIdentityIdType, HttpMethod } from '../../utils/Constants.mjs'; +import { ImdsRetryPolicy } from '../../retry/ImdsRetryPolicy.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +// Documentation for IMDS is available at https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/how-to-use-vm-token#get-a-token-using-http +const IMDS_TOKEN_PATH = "/metadata/identity/oauth2/token"; +const DEFAULT_IMDS_ENDPOINT = `http://169.254.169.254${IMDS_TOKEN_PATH}`; +const IMDS_API_VERSION = "2018-02-01"; +/** + * Managed Identity source implementation for Azure Instance Metadata Service (IMDS). + * + * IMDS is available on Azure Virtual Machines and Virtual Machine Scale Sets and provides + * a REST endpoint to obtain OAuth tokens for managed identities. This implementation + * handles both system-assigned and user-assigned managed identities. + * + * Original source of code: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/ImdsManagedIdentitySource.cs + */ +class Imds extends BaseManagedIdentitySource { + /** + * Constructs an Imds instance with the specified configuration. + * + * @param logger - Logger instance for recording debug information and errors + * @param nodeStorage - NodeStorage instance used for token caching operations + * @param networkClient - Network client implementation for making HTTP requests to IMDS + * @param cryptoProvider - CryptoProvider for generating correlation IDs and other cryptographic operations + * @param disableInternalRetries - When true, disables the built-in retry logic for IMDS requests + * @param identityEndpoint - The complete IMDS endpoint URL including the token path + */ + constructor(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint) { + super(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries); + this.identityEndpoint = identityEndpoint; + } + /** + * Creates an Imds instance with the appropriate endpoint configuration. + * + * This method checks for the presence of the AZURE_POD_IDENTITY_AUTHORITY_HOST environment + * variable, which is used in Azure Kubernetes Service (AKS) environments with Azure AD + * Pod Identity. If found, it uses that endpoint; otherwise, it falls back to the standard + * IMDS endpoint (169.254.169.254). + * + * @param logger - Logger instance for recording endpoint discovery and validation + * @param nodeStorage - NodeStorage instance for token caching + * @param networkClient - Network client for HTTP requests + * @param cryptoProvider - CryptoProvider for cryptographic operations + * @param disableInternalRetries - Whether to disable built-in retry logic + * + * @returns A configured Imds instance ready to make token requests + */ + static tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries) { + let validatedIdentityEndpoint; + if (process.env[ManagedIdentityEnvironmentVariableNames + .AZURE_POD_IDENTITY_AUTHORITY_HOST]) { + logger.info(`[Managed Identity] Environment variable ${ManagedIdentityEnvironmentVariableNames.AZURE_POD_IDENTITY_AUTHORITY_HOST} for ${ManagedIdentitySourceNames.IMDS} returned endpoint: ${process.env[ManagedIdentityEnvironmentVariableNames + .AZURE_POD_IDENTITY_AUTHORITY_HOST]}`); + validatedIdentityEndpoint = Imds.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.AZURE_POD_IDENTITY_AUTHORITY_HOST, `${process.env[ManagedIdentityEnvironmentVariableNames + .AZURE_POD_IDENTITY_AUTHORITY_HOST]}${IMDS_TOKEN_PATH}`, ManagedIdentitySourceNames.IMDS, logger); + } + else { + logger.info(`[Managed Identity] Unable to find ${ManagedIdentityEnvironmentVariableNames.AZURE_POD_IDENTITY_AUTHORITY_HOST} environment variable for ${ManagedIdentitySourceNames.IMDS}, using the default endpoint.`); + validatedIdentityEndpoint = DEFAULT_IMDS_ENDPOINT; + } + return new Imds(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, validatedIdentityEndpoint); + } + /** + * Creates a properly configured HTTP request for acquiring an access token from IMDS. + * + * This method builds a complete request object with all necessary headers, query parameters, + * and retry policies required by the Azure Instance Metadata Service. + * + * Key request components: + * - HTTP GET method to the IMDS token endpoint + * - Metadata header set to "true" (required by IMDS) + * - API version parameter (currently "2018-02-01") + * - Resource parameter specifying the target audience + * - Identity-specific parameters for user-assigned managed identities + * - IMDS-specific retry policy + * + * @param resource - The target resource/scope for which to request an access token (e.g., "https://graph.microsoft.com/.default") + * @param managedIdentityId - The managed identity configuration specifying whether to use system-assigned or user-assigned identity + * + * @returns A configured ManagedIdentityRequestParameters object ready for network execution + */ + createRequest(resource, managedIdentityId) { + const request = new ManagedIdentityRequestParameters(HttpMethod.GET, this.identityEndpoint); + request.headers[ManagedIdentityHeaders.METADATA_HEADER_NAME] = "true"; + request.queryParameters[ManagedIdentityQueryParameters.API_VERSION] = + IMDS_API_VERSION; + request.queryParameters[ManagedIdentityQueryParameters.RESOURCE] = + resource; + if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) { + request.queryParameters[this.getManagedIdentityUserAssignedIdQueryParameterKey(managedIdentityId.idType, true // indicates source is IMDS + )] = managedIdentityId.id; + } + // The bodyParameters are calculated in BaseManagedIdentity.acquireTokenWithManagedIdentity. + request.retryPolicy = new ImdsRetryPolicy(); + return request; + } +} + +export { Imds }; +//# sourceMappingURL=Imds.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/MachineLearning.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/MachineLearning.mjs new file mode 100644 index 00000000..e1312511 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/MachineLearning.mjs @@ -0,0 +1,128 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { BaseManagedIdentitySource, ManagedIdentityUserAssignedIdQueryParameterNames } from './BaseManagedIdentitySource.mjs'; +import { ManagedIdentityEnvironmentVariableNames, ManagedIdentitySourceNames, ManagedIdentityHeaders, ManagedIdentityQueryParameters, ManagedIdentityIdType, HttpMethod } from '../../utils/Constants.mjs'; +import { ManagedIdentityRequestParameters } from '../../config/ManagedIdentityRequestParameters.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +const MACHINE_LEARNING_MSI_API_VERSION = "2017-09-01"; +const MANAGED_IDENTITY_MACHINE_LEARNING_UNSUPPORTED_ID_TYPE_ERROR = `Only client id is supported for user-assigned managed identity in ${ManagedIdentitySourceNames.MACHINE_LEARNING}.`; // referenced in unit test +/** + * Machine Learning Managed Identity Source implementation for Azure Machine Learning environments. + * + * This class handles managed identity authentication specifically for Azure Machine Learning services. + * It supports both system-assigned and user-assigned managed identities, using the MSI_ENDPOINT + * and MSI_SECRET environment variables that are automatically provided in Azure ML environments. + */ +class MachineLearning extends BaseManagedIdentitySource { + /** + * Creates a new MachineLearning managed identity source instance. + * + * @param logger - Logger instance for diagnostic information + * @param nodeStorage - Node storage implementation for caching + * @param networkClient - Network client for making HTTP requests + * @param cryptoProvider - Cryptographic operations provider + * @param disableInternalRetries - Whether to disable automatic request retries + * @param msiEndpoint - The MSI endpoint URL from environment variables + * @param secret - The MSI secret from environment variables + */ + constructor(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, msiEndpoint, secret) { + super(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries); + this.msiEndpoint = msiEndpoint; + this.secret = secret; + } + /** + * Retrieves the required environment variables for Azure Machine Learning managed identity. + * + * This method checks for the presence of MSI_ENDPOINT and MSI_SECRET environment variables + * that are automatically set by the Azure Machine Learning platform when managed identity + * is enabled for the compute instance or cluster. + * + * @returns An array containing [msiEndpoint, secret] where either value may be undefined + * if the corresponding environment variable is not set + */ + static getEnvironmentVariables() { + const msiEndpoint = process.env[ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT]; + const secret = process.env[ManagedIdentityEnvironmentVariableNames.MSI_SECRET]; + return [msiEndpoint, secret]; + } + /** + * Attempts to create a MachineLearning managed identity source. + * + * This method validates the Azure Machine Learning environment by checking for the required + * MSI_ENDPOINT and MSI_SECRET environment variables. If both are present and valid, + * it creates and returns a MachineLearning instance. If either is missing or invalid, + * it returns null, indicating that this managed identity source is not available + * in the current environment. + * + * @param logger - Logger instance for diagnostic information + * @param nodeStorage - Node storage implementation for caching + * @param networkClient - Network client for making HTTP requests + * @param cryptoProvider - Cryptographic operations provider + * @param disableInternalRetries - Whether to disable automatic request retries + * + * @returns A new MachineLearning instance if the environment is valid, null otherwise + */ + static tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries) { + const [msiEndpoint, secret] = MachineLearning.getEnvironmentVariables(); + // if either of the MSI endpoint or MSI secret variables are undefined, this MSI provider is unavailable. + if (!msiEndpoint || !secret) { + logger.info(`[Managed Identity] ${ManagedIdentitySourceNames.MACHINE_LEARNING} managed identity is unavailable because one or both of the '${ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT}' and '${ManagedIdentityEnvironmentVariableNames.MSI_SECRET}' environment variables are not defined.`); + return null; + } + const validatedMsiEndpoint = MachineLearning.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT, msiEndpoint, ManagedIdentitySourceNames.MACHINE_LEARNING, logger); + logger.info(`[Managed Identity] Environment variables validation passed for ${ManagedIdentitySourceNames.MACHINE_LEARNING} managed identity. Endpoint URI: ${validatedMsiEndpoint}. Creating ${ManagedIdentitySourceNames.MACHINE_LEARNING} managed identity.`); + return new MachineLearning(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, msiEndpoint, secret); + } + /** + * Creates a managed identity token request for Azure Machine Learning environments. + * + * This method constructs the HTTP request parameters needed to acquire an access token + * from the Azure Machine Learning managed identity endpoint. It handles both system-assigned + * and user-assigned managed identities with specific logic for each type: + * + * - System-assigned: Uses the DEFAULT_IDENTITY_CLIENT_ID environment variable + * - User-assigned: Only supports client ID-based identification (not object ID or resource ID) + * + * The request uses the 2017-09-01 API version and includes the required secret header + * for authentication with the MSI endpoint. + * + * @param resource - The target resource/scope for which to request an access token (e.g., "https://graph.microsoft.com/.default") + * @param managedIdentityId - The managed identity configuration specifying whether to use system-assigned or user-assigned identity + * + * @returns A configured ManagedIdentityRequestParameters object ready for network execution + * + * @throws Error if an unsupported managed identity ID type is specified (only client ID is supported for user-assigned) + */ + createRequest(resource, managedIdentityId) { + const request = new ManagedIdentityRequestParameters(HttpMethod.GET, this.msiEndpoint); + request.headers[ManagedIdentityHeaders.METADATA_HEADER_NAME] = "true"; + request.headers[ManagedIdentityHeaders.ML_AND_SF_SECRET_HEADER_NAME] = + this.secret; + request.queryParameters[ManagedIdentityQueryParameters.API_VERSION] = + MACHINE_LEARNING_MSI_API_VERSION; + request.queryParameters[ManagedIdentityQueryParameters.RESOURCE] = + resource; + if (managedIdentityId.idType === ManagedIdentityIdType.SYSTEM_ASSIGNED) { + request.queryParameters[ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_CLIENT_ID_2017] = process.env[ManagedIdentityEnvironmentVariableNames + .DEFAULT_IDENTITY_CLIENT_ID]; // this environment variable is always set in an Azure Machine Learning source + } + else if (managedIdentityId.idType === + ManagedIdentityIdType.USER_ASSIGNED_CLIENT_ID) { + request.queryParameters[this.getManagedIdentityUserAssignedIdQueryParameterKey(managedIdentityId.idType, false, // isIMDS + true // uses2017API + )] = managedIdentityId.id; + } + else { + throw new Error(MANAGED_IDENTITY_MACHINE_LEARNING_UNSUPPORTED_ID_TYPE_ERROR); + } + // bodyParameters calculated in BaseManagedIdentity.acquireTokenWithManagedIdentity + return request; + } +} + +export { MANAGED_IDENTITY_MACHINE_LEARNING_UNSUPPORTED_ID_TYPE_ERROR, MachineLearning }; +//# sourceMappingURL=MachineLearning.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/ServiceFabric.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/ServiceFabric.mjs new file mode 100644 index 00000000..dbe1e7aa --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/ServiceFabric.mjs @@ -0,0 +1,122 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { ManagedIdentityRequestParameters } from '../../config/ManagedIdentityRequestParameters.mjs'; +import { BaseManagedIdentitySource } from './BaseManagedIdentitySource.mjs'; +import { ManagedIdentityEnvironmentVariableNames, ManagedIdentitySourceNames, ManagedIdentityIdType, ManagedIdentityHeaders, ManagedIdentityQueryParameters, HttpMethod } from '../../utils/Constants.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +const SERVICE_FABRIC_MSI_API_VERSION = "2019-07-01-preview"; +/** + * Original source of code: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/ServiceFabricManagedIdentitySource.cs + */ +class ServiceFabric extends BaseManagedIdentitySource { + /** + * Constructs a new ServiceFabric managed identity source for acquiring tokens from Azure Service Fabric clusters. + * + * Service Fabric managed identity allows applications running in Service Fabric clusters to authenticate + * without storing credentials in code. This source handles token acquisition using the Service Fabric + * Managed Identity Token Service (MITS). + * + * @param logger - Logger instance for logging authentication events and debugging information + * @param nodeStorage - NodeStorage instance for caching tokens and other authentication artifacts + * @param networkClient - Network client for making HTTP requests to the Service Fabric identity endpoint + * @param cryptoProvider - Crypto provider for cryptographic operations like token validation + * @param disableInternalRetries - Whether to disable internal retry logic for failed requests + * @param identityEndpoint - The Service Fabric managed identity endpoint URL + * @param identityHeader - The Service Fabric managed identity secret header value + */ + constructor(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint, identityHeader) { + super(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries); + this.identityEndpoint = identityEndpoint; + this.identityHeader = identityHeader; + } + /** + * Retrieves the environment variables required for Service Fabric managed identity authentication. + * + * Service Fabric managed identity requires three specific environment variables to be set by the + * Service Fabric runtime: + * - IDENTITY_ENDPOINT: The endpoint URL for the Managed Identity Token Service (MITS) + * - IDENTITY_HEADER: A secret value used for authentication with the MITS + * - IDENTITY_SERVER_THUMBPRINT: The thumbprint of the MITS server certificate for secure communication + * + * @returns An array containing the identity endpoint, identity header, and identity server thumbprint values. + * Elements will be undefined if the corresponding environment variables are not set. + */ + static getEnvironmentVariables() { + const identityEndpoint = process.env[ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT]; + const identityHeader = process.env[ManagedIdentityEnvironmentVariableNames.IDENTITY_HEADER]; + const identityServerThumbprint = process.env[ManagedIdentityEnvironmentVariableNames + .IDENTITY_SERVER_THUMBPRINT]; + return [identityEndpoint, identityHeader, identityServerThumbprint]; + } + /** + * Attempts to create a ServiceFabric managed identity source if the runtime environment supports it. + * + * Checks for the presence of all required Service Fabric environment variables + * and validates the endpoint URL format. It will only create a ServiceFabric instance if the application + * is running in a properly configured Service Fabric cluster with managed identity enabled. + * + * Note: User-assigned managed identities must be configured at the cluster level, not at runtime. + * This method will log a warning if a user-assigned identity is requested. + * + * @param logger - Logger instance for logging creation events and validation results + * @param nodeStorage - NodeStorage instance for caching tokens and authentication artifacts + * @param networkClient - Network client for making HTTP requests to the identity endpoint + * @param cryptoProvider - Crypto provider for cryptographic operations + * @param disableInternalRetries - Whether to disable internal retry logic for failed requests + * @param managedIdentityId - Managed identity identifier specifying system-assigned or user-assigned identity + * + * @returns A ServiceFabric instance if all environment variables are valid and present, otherwise null + */ + static tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, managedIdentityId) { + const [identityEndpoint, identityHeader, identityServerThumbprint] = ServiceFabric.getEnvironmentVariables(); + if (!identityEndpoint || !identityHeader || !identityServerThumbprint) { + logger.info(`[Managed Identity] ${ManagedIdentitySourceNames.SERVICE_FABRIC} managed identity is unavailable because one or all of the '${ManagedIdentityEnvironmentVariableNames.IDENTITY_HEADER}', '${ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT}' or '${ManagedIdentityEnvironmentVariableNames.IDENTITY_SERVER_THUMBPRINT}' environment variables are not defined.`); + return null; + } + const validatedIdentityEndpoint = ServiceFabric.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT, identityEndpoint, ManagedIdentitySourceNames.SERVICE_FABRIC, logger); + logger.info(`[Managed Identity] Environment variables validation passed for ${ManagedIdentitySourceNames.SERVICE_FABRIC} managed identity. Endpoint URI: ${validatedIdentityEndpoint}. Creating ${ManagedIdentitySourceNames.SERVICE_FABRIC} managed identity.`); + if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) { + logger.warning(`[Managed Identity] ${ManagedIdentitySourceNames.SERVICE_FABRIC} user assigned managed identity is configured in the cluster, not during runtime. See also: https://learn.microsoft.com/en-us/azure/service-fabric/configure-existing-cluster-enable-managed-identity-token-service.`); + } + return new ServiceFabric(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint, identityHeader); + } + /** + * Creates HTTP request parameters for acquiring an access token from the Service Fabric Managed Identity Token Service (MITS). + * + * This method constructs a properly formatted HTTP GET request that includes: + * - The secret header for authentication with MITS + * - API version parameter for the Service Fabric MSI endpoint + * - Resource parameter specifying the target Azure service + * - Optional identity parameters for user-assigned managed identities + * + * The request follows the Service Fabric managed identity protocol and uses the 2019-07-01-preview API version. + * For user-assigned identities, the appropriate query parameter (client_id, object_id, or resource_id) is added + * based on the identity type. + * + * @param resource - The Azure resource URI for which the access token is requested (e.g., "https://vault.azure.net/") + * @param managedIdentityId - The managed identity configuration specifying system-assigned or user-assigned identity details + * + * @returns A configured ManagedIdentityRequestParameters object ready for network execution + */ + createRequest(resource, managedIdentityId) { + const request = new ManagedIdentityRequestParameters(HttpMethod.GET, this.identityEndpoint); + request.headers[ManagedIdentityHeaders.ML_AND_SF_SECRET_HEADER_NAME] = + this.identityHeader; + request.queryParameters[ManagedIdentityQueryParameters.API_VERSION] = + SERVICE_FABRIC_MSI_API_VERSION; + request.queryParameters[ManagedIdentityQueryParameters.RESOURCE] = + resource; + if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) { + request.queryParameters[this.getManagedIdentityUserAssignedIdQueryParameterKey(managedIdentityId.idType)] = managedIdentityId.id; + } + // bodyParameters calculated in BaseManagedIdentity.acquireTokenWithManagedIdentity + return request; + } +} + +export { ServiceFabric }; +//# sourceMappingURL=ServiceFabric.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/client/OnBehalfOfClient.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/client/OnBehalfOfClient.mjs new file mode 100644 index 00000000..dafa0be0 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/client/OnBehalfOfClient.mjs @@ -0,0 +1,210 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { BaseClient, ScopeSet, CacheOutcome, createClientAuthError, ClientAuthErrorCodes, TimeUtils, AuthToken, Constants, ResponseHandler, CredentialType, AuthenticationScheme, UrlString, RequestParameterBuilder, GrantType, AADServerParamKeys, getClientAssertion, UrlUtils } from '@azure/msal-common/node'; +import { EncodingUtils } from '../utils/EncodingUtils.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * On-Behalf-Of client + * @public + */ +class OnBehalfOfClient extends BaseClient { + constructor(configuration) { + super(configuration); + } + /** + * Public API to acquire tokens with on behalf of flow + * @param request - developer provided CommonOnBehalfOfRequest + */ + async acquireToken(request) { + this.scopeSet = new ScopeSet(request.scopes || []); + // generate the user_assertion_hash for OBOAssertion + this.userAssertionHash = await this.cryptoUtils.hashString(request.oboAssertion); + if (request.skipCache || request.claims) { + return this.executeTokenRequest(request, this.authority, this.userAssertionHash); + } + try { + return await this.getCachedAuthenticationResult(request); + } + catch (e) { + // Any failure falls back to interactive request, once we implement distributed cache, we plan to handle `createRefreshRequiredError` to refresh using the RT + return await this.executeTokenRequest(request, this.authority, this.userAssertionHash); + } + } + /** + * look up cache for tokens + * Find idtoken in the cache + * Find accessToken based on user assertion and account info in the cache + * Please note we are not yet supported OBO tokens refreshed with long lived RT. User will have to send a new assertion if the current access token expires + * This is to prevent security issues when the assertion changes over time, however, longlived RT helps retaining the session + * @param request - developer provided CommonOnBehalfOfRequest + */ + async getCachedAuthenticationResult(request) { + // look in the cache for the access_token which matches the incoming_assertion + const cachedAccessToken = this.readAccessTokenFromCacheForOBO(this.config.authOptions.clientId, request); + if (!cachedAccessToken) { + // Must refresh due to non-existent access_token. + this.serverTelemetryManager?.setCacheOutcome(CacheOutcome.NO_CACHED_ACCESS_TOKEN); + this.logger.info("SilentFlowClient:acquireCachedToken - No access token found in cache for the given properties."); + throw createClientAuthError(ClientAuthErrorCodes.tokenRefreshRequired); + } + else if (TimeUtils.isTokenExpired(cachedAccessToken.expiresOn, this.config.systemOptions.tokenRenewalOffsetSeconds)) { + // Access token expired, will need to renewed + this.serverTelemetryManager?.setCacheOutcome(CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED); + this.logger.info(`OnbehalfofFlow:getCachedAuthenticationResult - Cached access token is expired or will expire within ${this.config.systemOptions.tokenRenewalOffsetSeconds} seconds.`); + throw createClientAuthError(ClientAuthErrorCodes.tokenRefreshRequired); + } + // fetch the idToken from cache + const cachedIdToken = this.readIdTokenFromCacheForOBO(cachedAccessToken.homeAccountId, request.correlationId); + let idTokenClaims; + let cachedAccount = null; + if (cachedIdToken) { + idTokenClaims = AuthToken.extractTokenClaims(cachedIdToken.secret, EncodingUtils.base64Decode); + const localAccountId = idTokenClaims.oid || idTokenClaims.sub; + const accountInfo = { + homeAccountId: cachedIdToken.homeAccountId, + environment: cachedIdToken.environment, + tenantId: cachedIdToken.realm, + username: Constants.EMPTY_STRING, + localAccountId: localAccountId || Constants.EMPTY_STRING, + }; + cachedAccount = this.cacheManager.getAccount(this.cacheManager.generateAccountKey(accountInfo), request.correlationId); + } + // increment telemetry cache hit counter + if (this.config.serverTelemetryManager) { + this.config.serverTelemetryManager.incrementCacheHits(); + } + return ResponseHandler.generateAuthenticationResult(this.cryptoUtils, this.authority, { + account: cachedAccount, + accessToken: cachedAccessToken, + idToken: cachedIdToken, + refreshToken: null, + appMetadata: null, + }, true, request, idTokenClaims); + } + /** + * read idtoken from cache, this is a specific implementation for OBO as the requirements differ from a generic lookup in the cacheManager + * Certain use cases of OBO flow do not expect an idToken in the cache/or from the service + * @param atHomeAccountId - account id + */ + readIdTokenFromCacheForOBO(atHomeAccountId, correlationId) { + const idTokenFilter = { + homeAccountId: atHomeAccountId, + environment: this.authority.canonicalAuthorityUrlComponents.HostNameAndPort, + credentialType: CredentialType.ID_TOKEN, + clientId: this.config.authOptions.clientId, + realm: this.authority.tenant, + }; + const idTokenMap = this.cacheManager.getIdTokensByFilter(idTokenFilter, correlationId); + // When acquiring a token on behalf of an application, there might not be an id token in the cache + if (Object.values(idTokenMap).length < 1) { + return null; + } + return Object.values(idTokenMap)[0]; + } + /** + * Fetches the cached access token based on incoming assertion + * @param clientId - client id + * @param request - developer provided CommonOnBehalfOfRequest + */ + readAccessTokenFromCacheForOBO(clientId, request) { + const authScheme = request.authenticationScheme || AuthenticationScheme.BEARER; + /* + * Distinguish between Bearer and PoP/SSH token cache types + * Cast to lowercase to handle "bearer" from ADFS + */ + const credentialType = authScheme && + authScheme.toLowerCase() !== + AuthenticationScheme.BEARER.toLowerCase() + ? CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME + : CredentialType.ACCESS_TOKEN; + const accessTokenFilter = { + credentialType: credentialType, + clientId, + target: ScopeSet.createSearchScopes(this.scopeSet.asArray()), + tokenType: authScheme, + keyId: request.sshKid, + requestedClaimsHash: request.requestedClaimsHash, + userAssertionHash: this.userAssertionHash, + }; + const accessTokens = this.cacheManager.getAccessTokensByFilter(accessTokenFilter, request.correlationId); + const numAccessTokens = accessTokens.length; + if (numAccessTokens < 1) { + return null; + } + else if (numAccessTokens > 1) { + throw createClientAuthError(ClientAuthErrorCodes.multipleMatchingTokens); + } + return accessTokens[0]; + } + /** + * Make a network call to the server requesting credentials + * @param request - developer provided CommonOnBehalfOfRequest + * @param authority - authority object + */ + async executeTokenRequest(request, authority, userAssertionHash) { + const queryParametersString = this.createTokenQueryParameters(request); + const endpoint = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString); + const requestBody = await this.createTokenRequestBody(request); + const headers = this.createTokenRequestHeaders(); + const thumbprint = { + clientId: this.config.authOptions.clientId, + authority: request.authority, + scopes: request.scopes, + claims: request.claims, + authenticationScheme: request.authenticationScheme, + resourceRequestMethod: request.resourceRequestMethod, + resourceRequestUri: request.resourceRequestUri, + shrClaims: request.shrClaims, + sshKid: request.sshKid, + }; + const reqTimestamp = TimeUtils.nowSeconds(); + const response = await this.executePostToTokenEndpoint(endpoint, requestBody, headers, thumbprint, request.correlationId); + const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.config.serializableCache, this.config.persistencePlugin); + responseHandler.validateTokenResponse(response.body); + const tokenResponse = await responseHandler.handleServerTokenResponse(response.body, this.authority, reqTimestamp, request, undefined, userAssertionHash); + return tokenResponse; + } + /** + * generate a server request in accepable format + * @param request - developer provided CommonOnBehalfOfRequest + */ + async createTokenRequestBody(request) { + const parameters = new Map(); + RequestParameterBuilder.addClientId(parameters, this.config.authOptions.clientId); + RequestParameterBuilder.addScopes(parameters, request.scopes); + RequestParameterBuilder.addGrantType(parameters, GrantType.JWT_BEARER); + RequestParameterBuilder.addClientInfo(parameters); + RequestParameterBuilder.addLibraryInfo(parameters, this.config.libraryInfo); + RequestParameterBuilder.addApplicationTelemetry(parameters, this.config.telemetry.application); + RequestParameterBuilder.addThrottling(parameters); + if (this.serverTelemetryManager) { + RequestParameterBuilder.addServerTelemetry(parameters, this.serverTelemetryManager); + } + const correlationId = request.correlationId || + this.config.cryptoInterface.createNewGuid(); + RequestParameterBuilder.addCorrelationId(parameters, correlationId); + RequestParameterBuilder.addRequestTokenUse(parameters, AADServerParamKeys.ON_BEHALF_OF); + RequestParameterBuilder.addOboAssertion(parameters, request.oboAssertion); + if (this.config.clientCredentials.clientSecret) { + RequestParameterBuilder.addClientSecret(parameters, this.config.clientCredentials.clientSecret); + } + const clientAssertion = this.config.clientCredentials.clientAssertion; + if (clientAssertion) { + RequestParameterBuilder.addClientAssertion(parameters, await getClientAssertion(clientAssertion.assertion, this.config.authOptions.clientId, request.resourceRequestUri)); + RequestParameterBuilder.addClientAssertionType(parameters, clientAssertion.assertionType); + } + if (request.claims || + (this.config.authOptions.clientCapabilities && + this.config.authOptions.clientCapabilities.length > 0)) { + RequestParameterBuilder.addClaims(parameters, request.claims, this.config.authOptions.clientCapabilities); + } + return UrlUtils.mapToQueryString(parameters); + } +} + +export { OnBehalfOfClient }; +//# sourceMappingURL=OnBehalfOfClient.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/client/PublicClientApplication.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/client/PublicClientApplication.mjs new file mode 100644 index 00000000..ebace534 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/client/PublicClientApplication.mjs @@ -0,0 +1,266 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { Constants, ApiId, LOOPBACK_SERVER_CONSTANTS } from '../utils/Constants.mjs'; +import { ServerTelemetryManager, AuthError, OIDC_DEFAULT_SCOPES, CodeChallengeMethodValues, ResponseMode, ServerError, Constants as Constants$1, AADServerParamKeys } from '@azure/msal-common/node'; +import { ClientApplication } from './ClientApplication.mjs'; +import { NodeAuthError, NodeAuthErrorMessage } from '../error/NodeAuthError.mjs'; +import { LoopbackClient } from '../network/LoopbackClient.mjs'; +import { DeviceCodeClient } from './DeviceCodeClient.mjs'; +import { version } from '../packageMetadata.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * This class is to be used to acquire tokens for public client applications (desktop, mobile). Public client applications + * are not trusted to safely store application secrets, and therefore can only request tokens in the name of an user. + * @public + */ +class PublicClientApplication extends ClientApplication { + /** + * Important attributes in the Configuration object for auth are: + * - clientID: the application ID of your application. You can obtain one by registering your application with our Application registration portal. + * - authority: the authority URL for your application. + * + * AAD authorities are of the form https://login.microsoftonline.com/\{Enter_the_Tenant_Info_Here\}. + * - If your application supports Accounts in one organizational directory, replace "Enter_the_Tenant_Info_Here" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com). + * - If your application supports Accounts in any organizational directory, replace "Enter_the_Tenant_Info_Here" value with organizations. + * - If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace "Enter_the_Tenant_Info_Here" value with common. + * - To restrict support to Personal Microsoft accounts only, replace "Enter_the_Tenant_Info_Here" value with consumers. + * + * Azure B2C authorities are of the form https://\{instance\}/\{tenant\}/\{policy\}. Each policy is considered + * its own authority. You will have to set the all of the knownAuthorities at the time of the client application + * construction. + * + * ADFS authorities are of the form https://\{instance\}/adfs. + */ + constructor(configuration) { + super(configuration); + if (this.config.broker.nativeBrokerPlugin) { + if (this.config.broker.nativeBrokerPlugin.isBrokerAvailable) { + this.nativeBrokerPlugin = this.config.broker.nativeBrokerPlugin; + this.nativeBrokerPlugin.setLogger(this.config.system.loggerOptions); + } + else { + this.logger.warning("NativeBroker implementation was provided but the broker is unavailable."); + } + } + this.skus = ServerTelemetryManager.makeExtraSkuString({ + libraryName: Constants.MSAL_SKU, + libraryVersion: version, + }); + } + /** + * Acquires a token from the authority using OAuth2.0 device code flow. + * This flow is designed for devices that do not have access to a browser or have input constraints. + * The authorization server issues a DeviceCode object with a verification code, an end-user code, + * and the end-user verification URI. The DeviceCode object is provided through a callback, and the end-user should be + * instructed to use another device to navigate to the verification URI to input credentials. + * Since the client cannot receive incoming requests, it polls the authorization server repeatedly + * until the end-user completes input of credentials. + */ + async acquireTokenByDeviceCode(request) { + this.logger.info("acquireTokenByDeviceCode called", request.correlationId); + const validRequest = Object.assign(request, await this.initializeBaseRequest(request)); + const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByDeviceCode, validRequest.correlationId); + try { + const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, undefined, request.azureCloudOptions); + const deviceCodeConfig = await this.buildOauthClientConfiguration(discoveredAuthority, validRequest.correlationId, "", serverTelemetryManager); + const deviceCodeClient = new DeviceCodeClient(deviceCodeConfig); + this.logger.verbose("Device code client created", validRequest.correlationId); + return await deviceCodeClient.acquireToken(validRequest); + } + catch (e) { + if (e instanceof AuthError) { + e.setCorrelationId(validRequest.correlationId); + } + serverTelemetryManager.cacheFailedRequest(e); + throw e; + } + } + /** + * Acquires a token interactively via the browser by requesting an authorization code then exchanging it for a token. + */ + async acquireTokenInteractive(request) { + const correlationId = request.correlationId || this.cryptoProvider.createNewGuid(); + this.logger.trace("acquireTokenInteractive called", correlationId); + const { openBrowser, successTemplate, errorTemplate, windowHandle, loopbackClient: customLoopbackClient, ...remainingProperties } = request; + if (this.nativeBrokerPlugin) { + const brokerRequest = { + ...remainingProperties, + clientId: this.config.auth.clientId, + scopes: request.scopes || OIDC_DEFAULT_SCOPES, + redirectUri: request.redirectUri || "", + authority: request.authority || this.config.auth.authority, + correlationId: correlationId, + extraParameters: { + ...remainingProperties.extraQueryParameters, + ...remainingProperties.tokenQueryParameters, + [AADServerParamKeys.X_CLIENT_EXTRA_SKU]: this.skus, + }, + accountId: remainingProperties.account?.nativeAccountId, + }; + return this.nativeBrokerPlugin.acquireTokenInteractive(brokerRequest, windowHandle); + } + if (request.redirectUri) { + // If its not a broker fallback scenario, we throw a error + if (!this.config.broker.nativeBrokerPlugin) { + throw NodeAuthError.createRedirectUriNotSupportedError(); + } + // If a redirect URI is provided for a broker flow but MSAL runtime startup failed, we fall back to the browser flow and will ignore the redirect URI provided for the broker flow + request.redirectUri = ""; + } + const { verifier, challenge } = await this.cryptoProvider.generatePkceCodes(); + const loopbackClient = customLoopbackClient || new LoopbackClient(); + let authCodeResponse = {}; + let authCodeListenerError = null; + try { + const authCodeListener = loopbackClient + .listenForAuthCode(successTemplate, errorTemplate) + .then((response) => { + authCodeResponse = response; + }) + .catch((e) => { + // Store the promise instead of throwing so we can control when its thrown + authCodeListenerError = e; + }); + // Wait for server to be listening + const redirectUri = await this.waitForRedirectUri(loopbackClient); + const validRequest = { + ...remainingProperties, + correlationId: correlationId, + scopes: request.scopes || OIDC_DEFAULT_SCOPES, + redirectUri: redirectUri, + responseMode: ResponseMode.QUERY, + codeChallenge: challenge, + codeChallengeMethod: CodeChallengeMethodValues.S256, + }; + const authCodeUrl = await this.getAuthCodeUrl(validRequest); + await openBrowser(authCodeUrl); + await authCodeListener; + if (authCodeListenerError) { + throw authCodeListenerError; + } + if (authCodeResponse.error) { + throw new ServerError(authCodeResponse.error, authCodeResponse.error_description, authCodeResponse.suberror); + } + else if (!authCodeResponse.code) { + throw NodeAuthError.createNoAuthCodeInResponseError(); + } + const clientInfo = authCodeResponse.client_info; + const tokenRequest = { + code: authCodeResponse.code, + codeVerifier: verifier, + clientInfo: clientInfo || Constants$1.EMPTY_STRING, + ...validRequest, + }; + return await this.acquireTokenByCode(tokenRequest); // Await this so the server doesn't close prematurely + } + finally { + loopbackClient.closeServer(); + } + } + /** + * Returns a token retrieved either from the cache or by exchanging the refresh token for a fresh access token. If brokering is enabled the token request will be serviced by the broker. + * @param request - developer provided SilentFlowRequest + * @returns + */ + async acquireTokenSilent(request) { + const correlationId = request.correlationId || this.cryptoProvider.createNewGuid(); + this.logger.trace("acquireTokenSilent called", correlationId); + if (this.nativeBrokerPlugin) { + const brokerRequest = { + ...request, + clientId: this.config.auth.clientId, + scopes: request.scopes || OIDC_DEFAULT_SCOPES, + redirectUri: request.redirectUri || "", + authority: request.authority || this.config.auth.authority, + correlationId: correlationId, + extraParameters: { + ...request.tokenQueryParameters, + [AADServerParamKeys.X_CLIENT_EXTRA_SKU]: this.skus, + }, + accountId: request.account.nativeAccountId, + forceRefresh: request.forceRefresh || false, + }; + return this.nativeBrokerPlugin.acquireTokenSilent(brokerRequest); + } + if (request.redirectUri) { + // If its not a broker fallback scenario, we throw a error + if (!this.config.broker.nativeBrokerPlugin) { + throw NodeAuthError.createRedirectUriNotSupportedError(); + } + request.redirectUri = ""; + } + return super.acquireTokenSilent(request); + } + /** + * Removes cache artifacts associated with the given account + * @param request - developer provided SignOutRequest + * @returns + */ + async signOut(request) { + if (this.nativeBrokerPlugin && request.account.nativeAccountId) { + const signoutRequest = { + clientId: this.config.auth.clientId, + accountId: request.account.nativeAccountId, + correlationId: request.correlationId || + this.cryptoProvider.createNewGuid(), + }; + await this.nativeBrokerPlugin.signOut(signoutRequest); + } + await this.getTokenCache().removeAccount(request.account, request.correlationId); + } + /** + * Returns all cached accounts for this application. If brokering is enabled this request will be serviced by the broker. + * @returns + */ + async getAllAccounts() { + if (this.nativeBrokerPlugin) { + const correlationId = this.cryptoProvider.createNewGuid(); + return this.nativeBrokerPlugin.getAllAccounts(this.config.auth.clientId, correlationId); + } + return this.getTokenCache().getAllAccounts(); + } + /** + * Attempts to retrieve the redirectUri from the loopback server. If the loopback server does not start listening for requests within the timeout this will throw. + * @param loopbackClient - developer provided custom loopback server implementation + * @returns + */ + async waitForRedirectUri(loopbackClient) { + return new Promise((resolve, reject) => { + let ticks = 0; + const id = setInterval(() => { + if (LOOPBACK_SERVER_CONSTANTS.TIMEOUT_MS / + LOOPBACK_SERVER_CONSTANTS.INTERVAL_MS < + ticks) { + clearInterval(id); + reject(NodeAuthError.createLoopbackServerTimeoutError()); + return; + } + try { + const r = loopbackClient.getRedirectUri(); + clearInterval(id); + resolve(r); + return; + } + catch (e) { + if (e instanceof AuthError && + e.errorCode === + NodeAuthErrorMessage.noLoopbackServerExists.code) { + // Loopback server is not listening yet + ticks++; + return; + } + clearInterval(id); + reject(e); + return; + } + }, LOOPBACK_SERVER_CONSTANTS.INTERVAL_MS); + }); + } +} + +export { PublicClientApplication }; +//# sourceMappingURL=PublicClientApplication.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/client/UsernamePasswordClient.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/client/UsernamePasswordClient.mjs new file mode 100644 index 00000000..f0bfbb3c --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/client/UsernamePasswordClient.mjs @@ -0,0 +1,104 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { BaseClient, TimeUtils, ResponseHandler, UrlString, CcsCredentialType, RequestParameterBuilder, OAuthResponseType, GrantType, getClientAssertion, StringUtils, UrlUtils } from '@azure/msal-common/node'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * Oauth2.0 Password grant client + * Note: We are only supporting public clients for password grant and for purely testing purposes + * @public + * @deprecated - Use a more secure flow instead + */ +class UsernamePasswordClient extends BaseClient { + constructor(configuration) { + super(configuration); + } + /** + * API to acquire a token by passing the username and password to the service in exchage of credentials + * password_grant + * @param request - CommonUsernamePasswordRequest + */ + async acquireToken(request) { + this.logger.info("in acquireToken call in username-password client"); + const reqTimestamp = TimeUtils.nowSeconds(); + const response = await this.executeTokenRequest(this.authority, request); + const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.config.serializableCache, this.config.persistencePlugin); + // Validate response. This function throws a server error if an error is returned by the server. + responseHandler.validateTokenResponse(response.body); + const tokenResponse = responseHandler.handleServerTokenResponse(response.body, this.authority, reqTimestamp, request); + return tokenResponse; + } + /** + * Executes POST request to token endpoint + * @param authority - authority object + * @param request - CommonUsernamePasswordRequest provided by the developer + */ + async executeTokenRequest(authority, request) { + const queryParametersString = this.createTokenQueryParameters(request); + const endpoint = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString); + const requestBody = await this.createTokenRequestBody(request); + const headers = this.createTokenRequestHeaders({ + credential: request.username, + type: CcsCredentialType.UPN, + }); + const thumbprint = { + clientId: this.config.authOptions.clientId, + authority: authority.canonicalAuthority, + scopes: request.scopes, + claims: request.claims, + authenticationScheme: request.authenticationScheme, + resourceRequestMethod: request.resourceRequestMethod, + resourceRequestUri: request.resourceRequestUri, + shrClaims: request.shrClaims, + sshKid: request.sshKid, + }; + return this.executePostToTokenEndpoint(endpoint, requestBody, headers, thumbprint, request.correlationId); + } + /** + * Generates a map for all the params to be sent to the service + * @param request - CommonUsernamePasswordRequest provided by the developer + */ + async createTokenRequestBody(request) { + const parameters = new Map(); + RequestParameterBuilder.addClientId(parameters, this.config.authOptions.clientId); + RequestParameterBuilder.addUsername(parameters, request.username); + RequestParameterBuilder.addPassword(parameters, request.password); + RequestParameterBuilder.addScopes(parameters, request.scopes); + RequestParameterBuilder.addResponseType(parameters, OAuthResponseType.IDTOKEN_TOKEN); + RequestParameterBuilder.addGrantType(parameters, GrantType.RESOURCE_OWNER_PASSWORD_GRANT); + RequestParameterBuilder.addClientInfo(parameters); + RequestParameterBuilder.addLibraryInfo(parameters, this.config.libraryInfo); + RequestParameterBuilder.addApplicationTelemetry(parameters, this.config.telemetry.application); + RequestParameterBuilder.addThrottling(parameters); + if (this.serverTelemetryManager) { + RequestParameterBuilder.addServerTelemetry(parameters, this.serverTelemetryManager); + } + const correlationId = request.correlationId || + this.config.cryptoInterface.createNewGuid(); + RequestParameterBuilder.addCorrelationId(parameters, correlationId); + if (this.config.clientCredentials.clientSecret) { + RequestParameterBuilder.addClientSecret(parameters, this.config.clientCredentials.clientSecret); + } + const clientAssertion = this.config.clientCredentials.clientAssertion; + if (clientAssertion) { + RequestParameterBuilder.addClientAssertion(parameters, await getClientAssertion(clientAssertion.assertion, this.config.authOptions.clientId, request.resourceRequestUri)); + RequestParameterBuilder.addClientAssertionType(parameters, clientAssertion.assertionType); + } + if (!StringUtils.isEmptyObj(request.claims) || + (this.config.authOptions.clientCapabilities && + this.config.authOptions.clientCapabilities.length > 0)) { + RequestParameterBuilder.addClaims(parameters, request.claims, this.config.authOptions.clientCapabilities); + } + if (this.config.systemOptions.preventCorsPreflight && + request.username) { + RequestParameterBuilder.addCcsUpn(parameters, request.username); + } + return UrlUtils.mapToQueryString(parameters); + } +} + +export { UsernamePasswordClient }; +//# sourceMappingURL=UsernamePasswordClient.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/config/Configuration.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/config/Configuration.mjs new file mode 100644 index 00000000..bbefceb6 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/config/Configuration.mjs @@ -0,0 +1,114 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { Constants, LogLevel, AzureCloudInstance, ProtocolMode } from '@azure/msal-common/node'; +import { HttpClient } from '../network/HttpClient.mjs'; +import { ManagedIdentityId } from './ManagedIdentityId.mjs'; +import { NodeAuthError } from '../error/NodeAuthError.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +const DEFAULT_AUTH_OPTIONS = { + clientId: Constants.EMPTY_STRING, + authority: Constants.DEFAULT_AUTHORITY, + clientSecret: Constants.EMPTY_STRING, + clientAssertion: Constants.EMPTY_STRING, + clientCertificate: { + thumbprint: Constants.EMPTY_STRING, + thumbprintSha256: Constants.EMPTY_STRING, + privateKey: Constants.EMPTY_STRING, + x5c: Constants.EMPTY_STRING, + }, + knownAuthorities: [], + cloudDiscoveryMetadata: Constants.EMPTY_STRING, + authorityMetadata: Constants.EMPTY_STRING, + clientCapabilities: [], + protocolMode: ProtocolMode.AAD, + azureCloudOptions: { + azureCloudInstance: AzureCloudInstance.None, + tenant: Constants.EMPTY_STRING, + }, + skipAuthorityMetadataCache: false, + encodeExtraQueryParams: false, +}; +const DEFAULT_CACHE_OPTIONS = { + claimsBasedCachingEnabled: false, +}; +const DEFAULT_LOGGER_OPTIONS = { + loggerCallback: () => { + // allow users to not set logger call back + }, + piiLoggingEnabled: false, + logLevel: LogLevel.Info, +}; +const DEFAULT_SYSTEM_OPTIONS = { + loggerOptions: DEFAULT_LOGGER_OPTIONS, + networkClient: new HttpClient(), + proxyUrl: Constants.EMPTY_STRING, + customAgentOptions: {}, + disableInternalRetries: false, +}; +const DEFAULT_TELEMETRY_OPTIONS = { + application: { + appName: Constants.EMPTY_STRING, + appVersion: Constants.EMPTY_STRING, + }, +}; +/** + * Sets the default options when not explicitly configured from app developer + * + * @param auth - Authentication options + * @param cache - Cache options + * @param system - System options + * @param telemetry - Telemetry options + * + * @returns Configuration + * @internal + */ +function buildAppConfiguration({ auth, broker, cache, system, telemetry, }) { + const systemOptions = { + ...DEFAULT_SYSTEM_OPTIONS, + networkClient: new HttpClient(system?.proxyUrl, system?.customAgentOptions), + loggerOptions: system?.loggerOptions || DEFAULT_LOGGER_OPTIONS, + disableInternalRetries: system?.disableInternalRetries || false, + }; + // if client certificate was provided, ensure that at least one of the SHA-1 or SHA-256 thumbprints were provided + if (!!auth.clientCertificate && + !!!auth.clientCertificate.thumbprint && + !!!auth.clientCertificate.thumbprintSha256) { + throw NodeAuthError.createStateNotFoundError(); + } + return { + auth: { ...DEFAULT_AUTH_OPTIONS, ...auth }, + broker: { ...broker }, + cache: { ...DEFAULT_CACHE_OPTIONS, ...cache }, + system: { ...systemOptions, ...system }, + telemetry: { ...DEFAULT_TELEMETRY_OPTIONS, ...telemetry }, + }; +} +function buildManagedIdentityConfiguration({ clientCapabilities, managedIdentityIdParams, system, }) { + const managedIdentityId = new ManagedIdentityId(managedIdentityIdParams); + const loggerOptions = system?.loggerOptions || DEFAULT_LOGGER_OPTIONS; + let networkClient; + // use developer provided network client if passed in + if (system?.networkClient) { + networkClient = system.networkClient; + // otherwise, create a new one + } + else { + networkClient = new HttpClient(system?.proxyUrl, system?.customAgentOptions); + } + return { + clientCapabilities: clientCapabilities || [], + managedIdentityId: managedIdentityId, + system: { + loggerOptions, + networkClient, + }, + disableInternalRetries: system?.disableInternalRetries || false, + }; +} + +export { buildAppConfiguration, buildManagedIdentityConfiguration }; +//# sourceMappingURL=Configuration.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/config/ManagedIdentityId.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/config/ManagedIdentityId.mjs new file mode 100644 index 00000000..2f1a5ed2 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/config/ManagedIdentityId.mjs @@ -0,0 +1,57 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { createManagedIdentityError } from '../error/ManagedIdentityError.mjs'; +import { ManagedIdentityIdType, DEFAULT_MANAGED_IDENTITY_ID } from '../utils/Constants.mjs'; +import { invalidManagedIdentityIdType } from '../error/ManagedIdentityErrorCodes.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +class ManagedIdentityId { + get id() { + return this._id; + } + set id(value) { + this._id = value; + } + get idType() { + return this._idType; + } + set idType(value) { + this._idType = value; + } + constructor(managedIdentityIdParams) { + const userAssignedClientId = managedIdentityIdParams?.userAssignedClientId; + const userAssignedResourceId = managedIdentityIdParams?.userAssignedResourceId; + const userAssignedObjectId = managedIdentityIdParams?.userAssignedObjectId; + if (userAssignedClientId) { + if (userAssignedResourceId || userAssignedObjectId) { + throw createManagedIdentityError(invalidManagedIdentityIdType); + } + this.id = userAssignedClientId; + this.idType = ManagedIdentityIdType.USER_ASSIGNED_CLIENT_ID; + } + else if (userAssignedResourceId) { + if (userAssignedClientId || userAssignedObjectId) { + throw createManagedIdentityError(invalidManagedIdentityIdType); + } + this.id = userAssignedResourceId; + this.idType = ManagedIdentityIdType.USER_ASSIGNED_RESOURCE_ID; + } + else if (userAssignedObjectId) { + if (userAssignedClientId || userAssignedResourceId) { + throw createManagedIdentityError(invalidManagedIdentityIdType); + } + this.id = userAssignedObjectId; + this.idType = ManagedIdentityIdType.USER_ASSIGNED_OBJECT_ID; + } + else { + this.id = DEFAULT_MANAGED_IDENTITY_ID; + this.idType = ManagedIdentityIdType.SYSTEM_ASSIGNED; + } + } +} + +export { ManagedIdentityId }; +//# sourceMappingURL=ManagedIdentityId.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/config/ManagedIdentityRequestParameters.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/config/ManagedIdentityRequestParameters.mjs new file mode 100644 index 00000000..405b78ad --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/config/ManagedIdentityRequestParameters.mjs @@ -0,0 +1,38 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { RequestParameterBuilder, UrlUtils, UrlString } from '@azure/msal-common/node'; +import { DefaultManagedIdentityRetryPolicy } from '../retry/DefaultManagedIdentityRetryPolicy.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +class ManagedIdentityRequestParameters { + constructor(httpMethod, endpoint, retryPolicy) { + this.httpMethod = httpMethod; + this._baseEndpoint = endpoint; + this.headers = {}; + this.bodyParameters = {}; + this.queryParameters = {}; + this.retryPolicy = + retryPolicy || new DefaultManagedIdentityRetryPolicy(); + } + computeUri() { + const parameters = new Map(); + if (this.queryParameters) { + RequestParameterBuilder.addExtraQueryParameters(parameters, this.queryParameters); + } + const queryParametersString = UrlUtils.mapToQueryString(parameters); + return UrlString.appendQueryString(this._baseEndpoint, queryParametersString); + } + computeParametersBodyString() { + const parameters = new Map(); + if (this.bodyParameters) { + RequestParameterBuilder.addExtraQueryParameters(parameters, this.bodyParameters); + } + return UrlUtils.mapToQueryString(parameters); + } +} + +export { ManagedIdentityRequestParameters }; +//# sourceMappingURL=ManagedIdentityRequestParameters.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/crypto/CryptoProvider.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/crypto/CryptoProvider.mjs new file mode 100644 index 00000000..7ef24091 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/crypto/CryptoProvider.mjs @@ -0,0 +1,100 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { EncodingTypes } from '@azure/msal-common/node'; +import { GuidGenerator } from './GuidGenerator.mjs'; +import { EncodingUtils } from '../utils/EncodingUtils.mjs'; +import { PkceGenerator } from './PkceGenerator.mjs'; +import { HashUtils } from './HashUtils.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * This class implements MSAL node's crypto interface, which allows it to perform base64 encoding and decoding, generating cryptographically random GUIDs and + * implementing Proof Key for Code Exchange specs for the OAuth Authorization Code Flow using PKCE (rfc here: https://tools.ietf.org/html/rfc7636). + * @public + */ +class CryptoProvider { + constructor() { + // Browser crypto needs to be validated first before any other classes can be set. + this.pkceGenerator = new PkceGenerator(); + this.guidGenerator = new GuidGenerator(); + this.hashUtils = new HashUtils(); + } + /** + * base64 URL safe encoded string + */ + base64UrlEncode() { + throw new Error("Method not implemented."); + } + /** + * Stringifies and base64Url encodes input public key + * @param inputKid - public key id + * @returns Base64Url encoded public key + */ + encodeKid() { + throw new Error("Method not implemented."); + } + /** + * Creates a new random GUID - used to populate state and nonce. + * @returns string (GUID) + */ + createNewGuid() { + return this.guidGenerator.generateGuid(); + } + /** + * Encodes input string to base64. + * @param input - string to be encoded + */ + base64Encode(input) { + return EncodingUtils.base64Encode(input); + } + /** + * Decodes input string from base64. + * @param input - string to be decoded + */ + base64Decode(input) { + return EncodingUtils.base64Decode(input); + } + /** + * Generates PKCE codes used in Authorization Code Flow. + */ + generatePkceCodes() { + return this.pkceGenerator.generatePkceCodes(); + } + /** + * Generates a keypair, stores it and returns a thumbprint - not yet implemented for node + */ + getPublicKeyThumbprint() { + throw new Error("Method not implemented."); + } + /** + * Removes cryptographic keypair from key store matching the keyId passed in + * @param kid - public key id + */ + removeTokenBindingKey() { + throw new Error("Method not implemented."); + } + /** + * Removes all cryptographic keys from Keystore + */ + clearKeystore() { + throw new Error("Method not implemented."); + } + /** + * Signs the given object as a jwt payload with private key retrieved by given kid - currently not implemented for node + */ + signJwt() { + throw new Error("Method not implemented."); + } + /** + * Returns the SHA-256 hash of an input string + */ + async hashString(plainText) { + return EncodingUtils.base64EncodeUrl(this.hashUtils.sha256(plainText).toString(EncodingTypes.BASE64), EncodingTypes.BASE64); + } +} + +export { CryptoProvider }; +//# sourceMappingURL=CryptoProvider.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/crypto/GuidGenerator.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/crypto/GuidGenerator.mjs new file mode 100644 index 00000000..bc0ffae7 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/crypto/GuidGenerator.mjs @@ -0,0 +1,29 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { v4 } from 'uuid'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +class GuidGenerator { + /** + * + * RFC4122: The version 4 UUID is meant for generating UUIDs from truly-random or pseudo-random numbers. + * uuidv4 generates guids from cryprtographically-string random + */ + generateGuid() { + return v4(); + } + /** + * verifies if a string is GUID + * @param guid + */ + isGuid(guid) { + const regexGuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; + return regexGuid.test(guid); + } +} + +export { GuidGenerator }; +//# sourceMappingURL=GuidGenerator.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/crypto/HashUtils.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/crypto/HashUtils.mjs new file mode 100644 index 00000000..00b58181 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/crypto/HashUtils.mjs @@ -0,0 +1,21 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { Hash } from '../utils/Constants.mjs'; +import crypto from 'crypto'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +class HashUtils { + /** + * generate 'SHA256' hash + * @param buffer + */ + sha256(buffer) { + return crypto.createHash(Hash.SHA256).update(buffer).digest(); + } +} + +export { HashUtils }; +//# sourceMappingURL=HashUtils.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/crypto/PkceGenerator.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/crypto/PkceGenerator.mjs new file mode 100644 index 00000000..f70ba56d --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/crypto/PkceGenerator.mjs @@ -0,0 +1,60 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { EncodingTypes, Constants } from '@azure/msal-common/node'; +import { RANDOM_OCTET_SIZE, CharSet } from '../utils/Constants.mjs'; +import { EncodingUtils } from '../utils/EncodingUtils.mjs'; +import { HashUtils } from './HashUtils.mjs'; +import crypto from 'crypto'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * https://tools.ietf.org/html/rfc7636#page-8 + */ +class PkceGenerator { + constructor() { + this.hashUtils = new HashUtils(); + } + /** + * generates the codeVerfier and the challenge from the codeVerfier + * reference: https://tools.ietf.org/html/rfc7636#section-4.1 and https://tools.ietf.org/html/rfc7636#section-4.2 + */ + async generatePkceCodes() { + const verifier = this.generateCodeVerifier(); + const challenge = this.generateCodeChallengeFromVerifier(verifier); + return { verifier, challenge }; + } + /** + * generates the codeVerfier; reference: https://tools.ietf.org/html/rfc7636#section-4.1 + */ + generateCodeVerifier() { + const charArr = []; + const maxNumber = 256 - (256 % CharSet.CV_CHARSET.length); + while (charArr.length <= RANDOM_OCTET_SIZE) { + const byte = crypto.randomBytes(1)[0]; + if (byte >= maxNumber) { + /* + * Ignore this number to maintain randomness. + * Including it would result in an unequal distribution of characters after doing the modulo + */ + continue; + } + const index = byte % CharSet.CV_CHARSET.length; + charArr.push(CharSet.CV_CHARSET[index]); + } + const verifier = charArr.join(Constants.EMPTY_STRING); + return EncodingUtils.base64EncodeUrl(verifier); + } + /** + * generate the challenge from the codeVerfier; reference: https://tools.ietf.org/html/rfc7636#section-4.2 + * @param codeVerifier + */ + generateCodeChallengeFromVerifier(codeVerifier) { + return EncodingUtils.base64EncodeUrl(this.hashUtils.sha256(codeVerifier).toString(EncodingTypes.BASE64), EncodingTypes.BASE64); + } +} + +export { PkceGenerator }; +//# sourceMappingURL=PkceGenerator.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/error/ManagedIdentityError.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/error/ManagedIdentityError.mjs new file mode 100644 index 00000000..0f5fd694 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/error/ManagedIdentityError.mjs @@ -0,0 +1,50 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { AuthError } from '@azure/msal-common/node'; +import { wwwAuthenticateHeaderUnsupportedFormat, wwwAuthenticateHeaderMissing, userAssignedNotAvailableAtRuntime, unableToReadSecretFile, unableToCreateSource, unableToCreateCloudShell, unableToCreateAzureArc, networkUnavailable, MsiEnvironmentVariableUrlMalformedErrorCodes, missingId, platformNotSupported, invalidSecret, invalidManagedIdentityIdType, invalidFilePath, invalidFileExtension } from './ManagedIdentityErrorCodes.mjs'; +import { ManagedIdentityEnvironmentVariableNames } from '../utils/Constants.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * ManagedIdentityErrorMessage class containing string constants used by error codes and messages. + */ +const ManagedIdentityErrorMessages = { + [invalidFileExtension]: "The file path in the WWW-Authenticate header does not contain a .key file.", + [invalidFilePath]: "The file path in the WWW-Authenticate header is not in a valid Windows or Linux Format.", + [invalidManagedIdentityIdType]: "More than one ManagedIdentityIdType was provided.", + [invalidSecret]: "The secret in the file on the file path in the WWW-Authenticate header is greater than 4096 bytes.", + [platformNotSupported]: "The platform is not supported by Azure Arc. Azure Arc only supports Windows and Linux.", + [missingId]: "A ManagedIdentityId id was not provided.", + [MsiEnvironmentVariableUrlMalformedErrorCodes + .AZURE_POD_IDENTITY_AUTHORITY_HOST]: `The Managed Identity's '${ManagedIdentityEnvironmentVariableNames.AZURE_POD_IDENTITY_AUTHORITY_HOST}' environment variable is malformed.`, + [MsiEnvironmentVariableUrlMalformedErrorCodes + .IDENTITY_ENDPOINT]: `The Managed Identity's '${ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT}' environment variable is malformed.`, + [MsiEnvironmentVariableUrlMalformedErrorCodes + .IMDS_ENDPOINT]: `The Managed Identity's '${ManagedIdentityEnvironmentVariableNames.IMDS_ENDPOINT}' environment variable is malformed.`, + [MsiEnvironmentVariableUrlMalformedErrorCodes + .MSI_ENDPOINT]: `The Managed Identity's '${ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT}' environment variable is malformed.`, + [networkUnavailable]: "Authentication unavailable. The request to the managed identity endpoint timed out.", + [unableToCreateAzureArc]: "Azure Arc Managed Identities can only be system assigned.", + [unableToCreateCloudShell]: "Cloud Shell Managed Identities can only be system assigned.", + [unableToCreateSource]: "Unable to create a Managed Identity source based on environment variables.", + [unableToReadSecretFile]: "Unable to read the secret file.", + [userAssignedNotAvailableAtRuntime]: "Service Fabric user assigned managed identity ClientId or ResourceId is not configurable at runtime.", + [wwwAuthenticateHeaderMissing]: "A 401 response was received form the Azure Arc Managed Identity, but the www-authenticate header is missing.", + [wwwAuthenticateHeaderUnsupportedFormat]: "A 401 response was received form the Azure Arc Managed Identity, but the www-authenticate header is in an unsupported format.", +}; +class ManagedIdentityError extends AuthError { + constructor(errorCode) { + super(errorCode, ManagedIdentityErrorMessages[errorCode]); + this.name = "ManagedIdentityError"; + Object.setPrototypeOf(this, ManagedIdentityError.prototype); + } +} +function createManagedIdentityError(errorCode) { + return new ManagedIdentityError(errorCode); +} + +export { ManagedIdentityError, ManagedIdentityErrorMessages, createManagedIdentityError }; +//# sourceMappingURL=ManagedIdentityError.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/error/ManagedIdentityErrorCodes.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/error/ManagedIdentityErrorCodes.mjs new file mode 100644 index 00000000..df098d74 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/error/ManagedIdentityErrorCodes.mjs @@ -0,0 +1,31 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { ManagedIdentityEnvironmentVariableNames } from '../utils/Constants.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +const invalidFileExtension = "invalid_file_extension"; +const invalidFilePath = "invalid_file_path"; +const invalidManagedIdentityIdType = "invalid_managed_identity_id_type"; +const invalidSecret = "invalid_secret"; +const missingId = "missing_client_id"; +const networkUnavailable = "network_unavailable"; +const platformNotSupported = "platform_not_supported"; +const unableToCreateAzureArc = "unable_to_create_azure_arc"; +const unableToCreateCloudShell = "unable_to_create_cloud_shell"; +const unableToCreateSource = "unable_to_create_source"; +const unableToReadSecretFile = "unable_to_read_secret_file"; +const userAssignedNotAvailableAtRuntime = "user_assigned_not_available_at_runtime"; +const wwwAuthenticateHeaderMissing = "www_authenticate_header_missing"; +const wwwAuthenticateHeaderUnsupportedFormat = "www_authenticate_header_unsupported_format"; +const MsiEnvironmentVariableUrlMalformedErrorCodes = { + [ManagedIdentityEnvironmentVariableNames.AZURE_POD_IDENTITY_AUTHORITY_HOST]: "azure_pod_identity_authority_host_url_malformed", + [ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT]: "identity_endpoint_url_malformed", + [ManagedIdentityEnvironmentVariableNames.IMDS_ENDPOINT]: "imds_endpoint_url_malformed", + [ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT]: "msi_endpoint_url_malformed", +}; + +export { MsiEnvironmentVariableUrlMalformedErrorCodes, invalidFileExtension, invalidFilePath, invalidManagedIdentityIdType, invalidSecret, missingId, networkUnavailable, platformNotSupported, unableToCreateAzureArc, unableToCreateCloudShell, unableToCreateSource, unableToReadSecretFile, userAssignedNotAvailableAtRuntime, wwwAuthenticateHeaderMissing, wwwAuthenticateHeaderUnsupportedFormat }; +//# sourceMappingURL=ManagedIdentityErrorCodes.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/error/NodeAuthError.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/error/NodeAuthError.mjs new file mode 100644 index 00000000..017aee1e --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/error/NodeAuthError.mjs @@ -0,0 +1,112 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { AuthError } from '@azure/msal-common/node'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * NodeAuthErrorMessage class containing string constants used by error codes and messages. + */ +const NodeAuthErrorMessage = { + invalidLoopbackAddressType: { + code: "invalid_loopback_server_address_type", + desc: "Loopback server address is not type string. This is unexpected.", + }, + unableToLoadRedirectUri: { + code: "unable_to_load_redirectUrl", + desc: "Loopback server callback was invoked without a url. This is unexpected.", + }, + noAuthCodeInResponse: { + code: "no_auth_code_in_response", + desc: "No auth code found in the server response. Please check your network trace to determine what happened.", + }, + noLoopbackServerExists: { + code: "no_loopback_server_exists", + desc: "No loopback server exists yet.", + }, + loopbackServerAlreadyExists: { + code: "loopback_server_already_exists", + desc: "Loopback server already exists. Cannot create another.", + }, + loopbackServerTimeout: { + code: "loopback_server_timeout", + desc: "Timed out waiting for auth code listener to be registered.", + }, + stateNotFoundError: { + code: "state_not_found", + desc: "State not found. Please verify that the request originated from msal.", + }, + thumbprintMissing: { + code: "thumbprint_missing_from_client_certificate", + desc: "Client certificate does not contain a SHA-1 or SHA-256 thumbprint.", + }, + redirectUriNotSupported: { + code: "redirect_uri_not_supported", + desc: "RedirectUri is not supported in this scenario. Please remove redirectUri from the request.", + }, +}; +class NodeAuthError extends AuthError { + constructor(errorCode, errorMessage) { + super(errorCode, errorMessage); + this.name = "NodeAuthError"; + } + /** + * Creates an error thrown if loopback server address is of type string. + */ + static createInvalidLoopbackAddressTypeError() { + return new NodeAuthError(NodeAuthErrorMessage.invalidLoopbackAddressType.code, `${NodeAuthErrorMessage.invalidLoopbackAddressType.desc}`); + } + /** + * Creates an error thrown if the loopback server is unable to get a url. + */ + static createUnableToLoadRedirectUrlError() { + return new NodeAuthError(NodeAuthErrorMessage.unableToLoadRedirectUri.code, `${NodeAuthErrorMessage.unableToLoadRedirectUri.desc}`); + } + /** + * Creates an error thrown if the server response does not contain an auth code. + */ + static createNoAuthCodeInResponseError() { + return new NodeAuthError(NodeAuthErrorMessage.noAuthCodeInResponse.code, `${NodeAuthErrorMessage.noAuthCodeInResponse.desc}`); + } + /** + * Creates an error thrown if the loopback server has not been spun up yet. + */ + static createNoLoopbackServerExistsError() { + return new NodeAuthError(NodeAuthErrorMessage.noLoopbackServerExists.code, `${NodeAuthErrorMessage.noLoopbackServerExists.desc}`); + } + /** + * Creates an error thrown if a loopback server already exists when attempting to create another one. + */ + static createLoopbackServerAlreadyExistsError() { + return new NodeAuthError(NodeAuthErrorMessage.loopbackServerAlreadyExists.code, `${NodeAuthErrorMessage.loopbackServerAlreadyExists.desc}`); + } + /** + * Creates an error thrown if the loopback server times out registering the auth code listener. + */ + static createLoopbackServerTimeoutError() { + return new NodeAuthError(NodeAuthErrorMessage.loopbackServerTimeout.code, `${NodeAuthErrorMessage.loopbackServerTimeout.desc}`); + } + /** + * Creates an error thrown when the state is not present. + */ + static createStateNotFoundError() { + return new NodeAuthError(NodeAuthErrorMessage.stateNotFoundError.code, NodeAuthErrorMessage.stateNotFoundError.desc); + } + /** + * Creates an error thrown when client certificate was provided, but neither the SHA-1 or SHA-256 thumbprints were provided + */ + static createThumbprintMissingError() { + return new NodeAuthError(NodeAuthErrorMessage.thumbprintMissing.code, NodeAuthErrorMessage.thumbprintMissing.desc); + } + /** + * Creates an error thrown when redirectUri is provided in an unsupported scenario + */ + static createRedirectUriNotSupportedError() { + return new NodeAuthError(NodeAuthErrorMessage.redirectUriNotSupported.code, NodeAuthErrorMessage.redirectUriNotSupported.desc); + } +} + +export { NodeAuthError, NodeAuthErrorMessage }; +//# sourceMappingURL=NodeAuthError.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/index.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/index.mjs new file mode 100644 index 00000000..ca192382 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/index.mjs @@ -0,0 +1,20 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import * as internals from './internals.mjs'; +export { internals }; +export { PublicClientApplication } from './client/PublicClientApplication.mjs'; +export { ConfidentialClientApplication } from './client/ConfidentialClientApplication.mjs'; +export { ClientApplication } from './client/ClientApplication.mjs'; +export { ClientCredentialClient } from './client/ClientCredentialClient.mjs'; +export { DeviceCodeClient } from './client/DeviceCodeClient.mjs'; +export { OnBehalfOfClient } from './client/OnBehalfOfClient.mjs'; +export { ManagedIdentityApplication } from './client/ManagedIdentityApplication.mjs'; +export { UsernamePasswordClient } from './client/UsernamePasswordClient.mjs'; +export { ClientAssertion } from './client/ClientAssertion.mjs'; +export { TokenCache } from './cache/TokenCache.mjs'; +export { DistributedCachePlugin } from './cache/distributed/DistributedCachePlugin.mjs'; +export { ManagedIdentitySourceNames } from './utils/Constants.mjs'; +export { CryptoProvider } from './crypto/CryptoProvider.mjs'; +export { AuthError, AuthErrorCodes, AuthErrorMessage, AzureCloudInstance, ClientAuthError, ClientAuthErrorCodes, ClientAuthErrorMessage, ClientConfigurationError, ClientConfigurationErrorCodes, ClientConfigurationErrorMessage, InteractionRequiredAuthError, InteractionRequiredAuthErrorCodes, InteractionRequiredAuthErrorMessage, LogLevel, Logger, PromptValue, ProtocolMode, ResponseMode, ServerError, TokenCacheContext } from '@azure/msal-common/node'; +export { version } from './packageMetadata.mjs'; +//# sourceMappingURL=index.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/internals.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/internals.mjs new file mode 100644 index 00000000..05413102 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/internals.mjs @@ -0,0 +1,14 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +export { Serializer } from './cache/serializer/Serializer.mjs'; +export { Deserializer } from './cache/serializer/Deserializer.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * Warning: This set of exports is purely intended to be used by other MSAL libraries, and should be considered potentially unstable. We strongly discourage using them directly, you do so at your own risk. + * Breaking changes to these APIs will be shipped under a minor version, instead of a major version. + */ +//# sourceMappingURL=internals.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/network/HttpClient.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/network/HttpClient.mjs new file mode 100644 index 00000000..7b0669ec --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/network/HttpClient.mjs @@ -0,0 +1,292 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { HttpStatus } from '@azure/msal-common/node'; +import { ProxyStatus, Constants, HttpMethod } from '../utils/Constants.mjs'; +import { NetworkUtils } from '../utils/NetworkUtils.mjs'; +import http from 'http'; +import https from 'https'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * This class implements the API for network requests. + */ +class HttpClient { + constructor(proxyUrl, customAgentOptions) { + this.proxyUrl = proxyUrl || ""; + this.customAgentOptions = customAgentOptions || {}; + } + /** + * Http Get request + * @param url + * @param options + */ + async sendGetRequestAsync(url, options, timeout) { + if (this.proxyUrl) { + return networkRequestViaProxy(url, this.proxyUrl, HttpMethod.GET, options, this.customAgentOptions, timeout); + } + else { + return networkRequestViaHttps(url, HttpMethod.GET, options, this.customAgentOptions, timeout); + } + } + /** + * Http Post request + * @param url + * @param options + */ + async sendPostRequestAsync(url, options) { + if (this.proxyUrl) { + return networkRequestViaProxy(url, this.proxyUrl, HttpMethod.POST, options, this.customAgentOptions); + } + else { + return networkRequestViaHttps(url, HttpMethod.POST, options, this.customAgentOptions); + } + } +} +const networkRequestViaProxy = (destinationUrlString, proxyUrlString, httpMethod, options, agentOptions, timeout) => { + const destinationUrl = new URL(destinationUrlString); + const proxyUrl = new URL(proxyUrlString); + // "method: connect" must be used to establish a connection to the proxy + const headers = options?.headers || {}; + const tunnelRequestOptions = { + host: proxyUrl.hostname, + port: proxyUrl.port, + method: "CONNECT", + path: destinationUrl.hostname, + headers: headers, + }; + if (agentOptions && Object.keys(agentOptions).length) { + tunnelRequestOptions.agent = new http.Agent(agentOptions); + } + // compose a request string for the socket + let postRequestStringContent = ""; + if (httpMethod === HttpMethod.POST) { + const body = options?.body || ""; + postRequestStringContent = + "Content-Type: application/x-www-form-urlencoded\r\n" + + `Content-Length: ${body.length}\r\n` + + `\r\n${body}`; + } + else { + // optional timeout is only for get requests (regionDiscovery, for example) + if (timeout) { + tunnelRequestOptions.timeout = timeout; + } + } + const outgoingRequestString = `${httpMethod.toUpperCase()} ${destinationUrl.href} HTTP/1.1\r\n` + + `Host: ${destinationUrl.host}\r\n` + + "Connection: close\r\n" + + postRequestStringContent + + "\r\n"; + return new Promise((resolve, reject) => { + const request = http.request(tunnelRequestOptions); + if (timeout) { + request.on("timeout", () => { + request.destroy(); + reject(new Error("Request time out")); + }); + } + request.end(); + // establish connection to the proxy + request.on("connect", (response, socket) => { + const proxyStatusCode = response?.statusCode || ProxyStatus.SERVER_ERROR; + if (proxyStatusCode < ProxyStatus.SUCCESS_RANGE_START || + proxyStatusCode > ProxyStatus.SUCCESS_RANGE_END) { + request.destroy(); + socket.destroy(); + reject(new Error(`Error connecting to proxy. Http status code: ${response.statusCode}. Http status message: ${response?.statusMessage || "Unknown"}`)); + } + // make a request over an HTTP tunnel + socket.write(outgoingRequestString); + const data = []; + socket.on("data", (chunk) => { + data.push(chunk); + }); + socket.on("end", () => { + // combine all received buffer streams into one buffer, and then into a string + const dataString = Buffer.concat([...data]).toString(); + // separate each line into it's own entry in an arry + const dataStringArray = dataString.split("\r\n"); + // the first entry will contain the statusCode and statusMessage + const httpStatusCode = parseInt(dataStringArray[0].split(" ")[1]); + // remove "HTTP/1.1" and the status code to get the status message + const statusMessage = dataStringArray[0] + .split(" ") + .slice(2) + .join(" "); + // the last entry will contain the body + const body = dataStringArray[dataStringArray.length - 1]; + // everything in between the first and last entries are the headers + const headersArray = dataStringArray.slice(1, dataStringArray.length - 2); + // build an object out of all the headers + const entries = new Map(); + headersArray.forEach((header) => { + /** + * the header might look like "Content-Length: 1531", but that is just a string + * it needs to be converted to a key/value pair + * split the string at the first instance of ":" + * there may be more than one ":" if the value of the header is supposed to be a JSON object + */ + const headerKeyValue = header.split(new RegExp(/:\s(.*)/s)); + const headerKey = headerKeyValue[0]; + let headerValue = headerKeyValue[1]; + // check if the value of the header is supposed to be a JSON object + try { + const object = JSON.parse(headerValue); + // if it is, then convert it from a string to a JSON object + if (object && typeof object === "object") { + headerValue = object; + } + } + catch (e) { + // otherwise, leave it as a string + } + entries.set(headerKey, headerValue); + }); + const headers = Object.fromEntries(entries); + const parsedHeaders = headers; + const networkResponse = NetworkUtils.getNetworkResponse(parsedHeaders, parseBody(httpStatusCode, statusMessage, parsedHeaders, body), httpStatusCode); + if ((httpStatusCode < HttpStatus.SUCCESS_RANGE_START || + httpStatusCode > HttpStatus.SUCCESS_RANGE_END) && + // do not destroy the request for the device code flow + networkResponse.body["error"] !== + Constants.AUTHORIZATION_PENDING) { + request.destroy(); + } + resolve(networkResponse); + }); + socket.on("error", (chunk) => { + request.destroy(); + socket.destroy(); + reject(new Error(chunk.toString())); + }); + }); + request.on("error", (chunk) => { + request.destroy(); + reject(new Error(chunk.toString())); + }); + }); +}; +const networkRequestViaHttps = (urlString, httpMethod, options, agentOptions, timeout) => { + const isPostRequest = httpMethod === HttpMethod.POST; + const body = options?.body || ""; + const url = new URL(urlString); + const headers = options?.headers || {}; + const customOptions = { + method: httpMethod, + headers: headers, + ...NetworkUtils.urlToHttpOptions(url), + }; + if (agentOptions && Object.keys(agentOptions).length) { + customOptions.agent = new https.Agent(agentOptions); + } + if (isPostRequest) { + // needed for post request to work + customOptions.headers = { + ...customOptions.headers, + "Content-Length": body.length, + }; + } + else { + // optional timeout is only for get requests (regionDiscovery, for example) + if (timeout) { + customOptions.timeout = timeout; + } + } + return new Promise((resolve, reject) => { + let request; + // managed identity sources use http instead of https + if (customOptions.protocol === "http:") { + request = http.request(customOptions); + } + else { + request = https.request(customOptions); + } + if (isPostRequest) { + request.write(body); + } + if (timeout) { + request.on("timeout", () => { + request.destroy(); + reject(new Error("Request time out")); + }); + } + request.end(); + request.on("response", (response) => { + const headers = response.headers; + const statusCode = response.statusCode; + const statusMessage = response.statusMessage; + const data = []; + response.on("data", (chunk) => { + data.push(chunk); + }); + response.on("end", () => { + // combine all received buffer streams into one buffer, and then into a string + const body = Buffer.concat([...data]).toString(); + const parsedHeaders = headers; + const networkResponse = NetworkUtils.getNetworkResponse(parsedHeaders, parseBody(statusCode, statusMessage, parsedHeaders, body), statusCode); + if ((statusCode < HttpStatus.SUCCESS_RANGE_START || + statusCode > HttpStatus.SUCCESS_RANGE_END) && + // do not destroy the request for the device code flow + networkResponse.body["error"] !== + Constants.AUTHORIZATION_PENDING) { + request.destroy(); + } + resolve(networkResponse); + }); + }); + request.on("error", (chunk) => { + request.destroy(); + reject(new Error(chunk.toString())); + }); + }); +}; +/** + * Check if extra parsing is needed on the repsonse from the server + * @param statusCode {number} the status code of the response from the server + * @param statusMessage {string | undefined} the status message of the response from the server + * @param headers {Record} the headers of the response from the server + * @param body {string} the body from the response of the server + * @returns {Object} JSON parsed body or error object + */ +const parseBody = (statusCode, statusMessage, headers, body) => { + /* + * Informational responses (100 – 199) + * Successful responses (200 – 299) + * Redirection messages (300 – 399) + * Client error responses (400 – 499) + * Server error responses (500 – 599) + */ + let parsedBody; + try { + parsedBody = JSON.parse(body); + } + catch (error) { + let errorType; + let errorDescriptionHelper; + if (statusCode >= HttpStatus.CLIENT_ERROR_RANGE_START && + statusCode <= HttpStatus.CLIENT_ERROR_RANGE_END) { + errorType = "client_error"; + errorDescriptionHelper = "A client"; + } + else if (statusCode >= HttpStatus.SERVER_ERROR_RANGE_START && + statusCode <= HttpStatus.SERVER_ERROR_RANGE_END) { + errorType = "server_error"; + errorDescriptionHelper = "A server"; + } + else { + errorType = "unknown_error"; + errorDescriptionHelper = "An unknown"; + } + parsedBody = { + error: errorType, + error_description: `${errorDescriptionHelper} error occured.\nHttp status code: ${statusCode}\nHttp status message: ${statusMessage || "Unknown"}\nHeaders: ${JSON.stringify(headers)}`, + }; + } + return parsedBody; +}; + +export { HttpClient }; +//# sourceMappingURL=HttpClient.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/network/HttpClientWithRetries.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/network/HttpClientWithRetries.mjs new file mode 100644 index 00000000..7ba67357 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/network/HttpClientWithRetries.mjs @@ -0,0 +1,46 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { HeaderNames } from '@azure/msal-common/node'; +import { HttpMethod } from '../utils/Constants.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +class HttpClientWithRetries { + constructor(httpClientNoRetries, retryPolicy, logger) { + this.httpClientNoRetries = httpClientNoRetries; + this.retryPolicy = retryPolicy; + this.logger = logger; + } + async sendNetworkRequestAsyncHelper(httpMethod, url, options) { + if (httpMethod === HttpMethod.GET) { + return this.httpClientNoRetries.sendGetRequestAsync(url, options); + } + else { + return this.httpClientNoRetries.sendPostRequestAsync(url, options); + } + } + async sendNetworkRequestAsync(httpMethod, url, options) { + // the underlying network module (custom or HttpClient) will make the call + let response = await this.sendNetworkRequestAsyncHelper(httpMethod, url, options); + if ("isNewRequest" in this.retryPolicy) { + this.retryPolicy.isNewRequest = true; + } + let currentRetry = 0; + while (await this.retryPolicy.pauseForRetry(response.status, currentRetry, this.logger, response.headers[HeaderNames.RETRY_AFTER])) { + response = await this.sendNetworkRequestAsyncHelper(httpMethod, url, options); + currentRetry++; + } + return response; + } + async sendGetRequestAsync(url, options) { + return this.sendNetworkRequestAsync(HttpMethod.GET, url, options); + } + async sendPostRequestAsync(url, options) { + return this.sendNetworkRequestAsync(HttpMethod.POST, url, options); + } +} + +export { HttpClientWithRetries }; +//# sourceMappingURL=HttpClientWithRetries.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/network/LoopbackClient.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/network/LoopbackClient.mjs new file mode 100644 index 00000000..26e2647e --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/network/LoopbackClient.mjs @@ -0,0 +1,92 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { Constants, UrlUtils, HttpStatus } from '@azure/msal-common/node'; +import http from 'http'; +import { NodeAuthError } from '../error/NodeAuthError.mjs'; +import { Constants as Constants$1 } from '../utils/Constants.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +class LoopbackClient { + /** + * Spins up a loopback server which returns the server response when the localhost redirectUri is hit + * @param successTemplate + * @param errorTemplate + * @returns + */ + async listenForAuthCode(successTemplate, errorTemplate) { + if (this.server) { + throw NodeAuthError.createLoopbackServerAlreadyExistsError(); + } + return new Promise((resolve, reject) => { + this.server = http.createServer((req, res) => { + const url = req.url; + if (!url) { + res.end(errorTemplate || + "Error occurred loading redirectUrl"); + reject(NodeAuthError.createUnableToLoadRedirectUrlError()); + return; + } + else if (url === Constants.FORWARD_SLASH) { + res.end(successTemplate || + "Auth code was successfully acquired. You can close this window now."); + return; + } + const redirectUri = this.getRedirectUri(); + const parsedUrl = new URL(url, redirectUri); + const authCodeResponse = UrlUtils.getDeserializedResponse(parsedUrl.search) || + {}; + if (authCodeResponse.code) { + res.writeHead(HttpStatus.REDIRECT, { + location: redirectUri, + }); // Prevent auth code from being saved in the browser history + res.end(); + } + if (authCodeResponse.error) { + res.end(errorTemplate || + `Error occurred: ${authCodeResponse.error}`); + } + resolve(authCodeResponse); + }); + this.server.listen(0, "127.0.0.1"); // Listen on any available port + }); + } + /** + * Get the port that the loopback server is running on + * @returns + */ + getRedirectUri() { + if (!this.server || !this.server.listening) { + throw NodeAuthError.createNoLoopbackServerExistsError(); + } + const address = this.server.address(); + if (!address || typeof address === "string" || !address.port) { + this.closeServer(); + throw NodeAuthError.createInvalidLoopbackAddressTypeError(); + } + const port = address && address.port; + return `${Constants$1.HTTP_PROTOCOL}${Constants$1.LOCALHOST}:${port}`; + } + /** + * Close the loopback server + */ + closeServer() { + if (this.server) { + // Only stops accepting new connections, server will close once open/idle connections are closed. + this.server.close(); + if (typeof this.server.closeAllConnections === "function") { + /* + * Close open/idle connections. This API is available in Node versions 18.2 and higher + */ + this.server.closeAllConnections(); + } + this.server.unref(); + this.server = undefined; + } + } +} + +export { LoopbackClient }; +//# sourceMappingURL=LoopbackClient.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/packageMetadata.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/packageMetadata.mjs new file mode 100644 index 00000000..eeb69fb4 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/packageMetadata.mjs @@ -0,0 +1,8 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +/* eslint-disable header/header */ +const name = "@azure/msal-node"; +const version = "3.8.1"; + +export { name, version }; +//# sourceMappingURL=packageMetadata.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/protocol/Authorize.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/protocol/Authorize.mjs new file mode 100644 index 00000000..85e90a92 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/protocol/Authorize.mjs @@ -0,0 +1,43 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { AuthorizeProtocol, RequestParameterBuilder, ProtocolMode, OAuthResponseType } from '@azure/msal-common/node'; +import { Constants } from '../utils/Constants.mjs'; +import { version } from '../packageMetadata.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * Constructs the full /authorize URL with request parameters + * @param config + * @param authority + * @param request + * @param logger + * @returns + */ +function getAuthCodeRequestUrl(config, authority, request, logger) { + const parameters = AuthorizeProtocol.getStandardAuthorizeRequestParameters({ + ...config.auth, + authority: authority, + redirectUri: request.redirectUri || "", + }, request, logger); + RequestParameterBuilder.addLibraryInfo(parameters, { + sku: Constants.MSAL_SKU, + version: version, + cpu: process.arch || "", + os: process.platform || "", + }); + if (config.auth.protocolMode !== ProtocolMode.OIDC) { + RequestParameterBuilder.addApplicationTelemetry(parameters, config.telemetry.application); + } + RequestParameterBuilder.addResponseType(parameters, OAuthResponseType.CODE); + if (request.codeChallenge && request.codeChallengeMethod) { + RequestParameterBuilder.addCodeChallengeParams(parameters, request.codeChallenge, request.codeChallengeMethod); + } + RequestParameterBuilder.addExtraQueryParameters(parameters, request.extraQueryParameters || {}); + return AuthorizeProtocol.getAuthorizeUrl(authority, parameters, config.auth.encodeExtraQueryParams, request.extraQueryParameters); +} + +export { getAuthCodeRequestUrl }; +//# sourceMappingURL=Authorize.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/retry/DefaultManagedIdentityRetryPolicy.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/retry/DefaultManagedIdentityRetryPolicy.mjs new file mode 100644 index 00000000..67372a64 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/retry/DefaultManagedIdentityRetryPolicy.mjs @@ -0,0 +1,49 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { HttpStatus } from '@azure/msal-common'; +import { LinearRetryStrategy } from './LinearRetryStrategy.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +const DEFAULT_MANAGED_IDENTITY_MAX_RETRIES = 3; // referenced in unit test +const DEFAULT_MANAGED_IDENTITY_RETRY_DELAY_MS = 1000; +const DEFAULT_MANAGED_IDENTITY_HTTP_STATUS_CODES_TO_RETRY_ON = [ + HttpStatus.NOT_FOUND, + HttpStatus.REQUEST_TIMEOUT, + HttpStatus.TOO_MANY_REQUESTS, + HttpStatus.SERVER_ERROR, + HttpStatus.SERVICE_UNAVAILABLE, + HttpStatus.GATEWAY_TIMEOUT, +]; +class DefaultManagedIdentityRetryPolicy { + constructor() { + this.linearRetryStrategy = new LinearRetryStrategy(); + } + /* + * this is defined here as a static variable despite being defined as a constant outside of the + * class because it needs to be overridden in the unit tests so that the unit tests run faster + */ + static get DEFAULT_MANAGED_IDENTITY_RETRY_DELAY_MS() { + return DEFAULT_MANAGED_IDENTITY_RETRY_DELAY_MS; + } + async pauseForRetry(httpStatusCode, currentRetry, logger, retryAfterHeader) { + if (DEFAULT_MANAGED_IDENTITY_HTTP_STATUS_CODES_TO_RETRY_ON.includes(httpStatusCode) && + currentRetry < DEFAULT_MANAGED_IDENTITY_MAX_RETRIES) { + const retryAfterDelay = this.linearRetryStrategy.calculateDelay(retryAfterHeader, DefaultManagedIdentityRetryPolicy.DEFAULT_MANAGED_IDENTITY_RETRY_DELAY_MS); + logger.verbose(`Retrying request in ${retryAfterDelay}ms (retry attempt: ${currentRetry + 1})`); + // pause execution for the calculated delay + await new Promise((resolve) => { + // retryAfterHeader value of 0 evaluates to false, and DEFAULT_MANAGED_IDENTITY_RETRY_DELAY_MS will be used + return setTimeout(resolve, retryAfterDelay); + }); + return true; + } + // if the status code is not retriable or max retries have been reached, do not retry + return false; + } +} + +export { DEFAULT_MANAGED_IDENTITY_MAX_RETRIES, DefaultManagedIdentityRetryPolicy }; +//# sourceMappingURL=DefaultManagedIdentityRetryPolicy.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/retry/ExponentialRetryStrategy.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/retry/ExponentialRetryStrategy.mjs new file mode 100644 index 00000000..298d2aa4 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/retry/ExponentialRetryStrategy.mjs @@ -0,0 +1,40 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +class ExponentialRetryStrategy { + constructor(minExponentialBackoff, maxExponentialBackoff, exponentialDeltaBackoff) { + this.minExponentialBackoff = minExponentialBackoff; + this.maxExponentialBackoff = maxExponentialBackoff; + this.exponentialDeltaBackoff = exponentialDeltaBackoff; + } + /** + * Calculates the exponential delay based on the current retry attempt. + * + * @param {number} currentRetry - The current retry attempt number. + * @returns {number} - The calculated exponential delay in milliseconds. + * + * The delay is calculated using the formula: + * - If `currentRetry` is 0, it returns the minimum backoff time. + * - Otherwise, it calculates the delay as the minimum of: + * - `(2^(currentRetry - 1)) * deltaBackoff` + * - `maxBackoff` + * + * This ensures that the delay increases exponentially with each retry attempt, + * but does not exceed the maximum backoff time. + */ + calculateDelay(currentRetry) { + // Attempt 1 + if (currentRetry === 0) { + return this.minExponentialBackoff; + } + // Attempt 2+ + const exponentialDelay = Math.min(Math.pow(2, currentRetry - 1) * this.exponentialDeltaBackoff, this.maxExponentialBackoff); + return exponentialDelay; + } +} + +export { ExponentialRetryStrategy }; +//# sourceMappingURL=ExponentialRetryStrategy.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/retry/ImdsRetryPolicy.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/retry/ImdsRetryPolicy.mjs new file mode 100644 index 00000000..92633d46 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/retry/ImdsRetryPolicy.mjs @@ -0,0 +1,90 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { HttpStatus } from '@azure/msal-common'; +import { ExponentialRetryStrategy } from './ExponentialRetryStrategy.mjs'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +const HTTP_STATUS_400_CODES_FOR_EXPONENTIAL_STRATEGY = [ + HttpStatus.NOT_FOUND, + HttpStatus.REQUEST_TIMEOUT, + HttpStatus.GONE, + HttpStatus.TOO_MANY_REQUESTS, +]; +const EXPONENTIAL_STRATEGY_NUM_RETRIES = 3; +const LINEAR_STRATEGY_NUM_RETRIES = 7; +const MIN_EXPONENTIAL_BACKOFF_MS = 1000; +const MAX_EXPONENTIAL_BACKOFF_MS = 4000; +const EXPONENTIAL_DELTA_BACKOFF_MS = 2000; +const HTTP_STATUS_GONE_RETRY_AFTER_MS = 10 * 1000; // 10 seconds +class ImdsRetryPolicy { + constructor() { + this.exponentialRetryStrategy = new ExponentialRetryStrategy(ImdsRetryPolicy.MIN_EXPONENTIAL_BACKOFF_MS, ImdsRetryPolicy.MAX_EXPONENTIAL_BACKOFF_MS, ImdsRetryPolicy.EXPONENTIAL_DELTA_BACKOFF_MS); + } + /* + * these are defined here as static variables despite being defined as constants outside of the + * class because they need to be overridden in the unit tests so that the unit tests run faster + */ + static get MIN_EXPONENTIAL_BACKOFF_MS() { + return MIN_EXPONENTIAL_BACKOFF_MS; + } + static get MAX_EXPONENTIAL_BACKOFF_MS() { + return MAX_EXPONENTIAL_BACKOFF_MS; + } + static get EXPONENTIAL_DELTA_BACKOFF_MS() { + return EXPONENTIAL_DELTA_BACKOFF_MS; + } + static get HTTP_STATUS_GONE_RETRY_AFTER_MS() { + return HTTP_STATUS_GONE_RETRY_AFTER_MS; + } + set isNewRequest(value) { + this._isNewRequest = value; + } + /** + * Pauses execution for a calculated delay before retrying a request. + * + * @param httpStatusCode - The HTTP status code of the response. + * @param currentRetry - The current retry attempt number. + * @param retryAfterHeader - The value of the "retry-after" header from the response. + * @returns A promise that resolves to a boolean indicating whether a retry should be attempted. + */ + async pauseForRetry(httpStatusCode, currentRetry, logger) { + if (this._isNewRequest) { + this._isNewRequest = false; + // calculate the maxRetries based on the status code, once per request + this.maxRetries = + httpStatusCode === HttpStatus.GONE + ? LINEAR_STRATEGY_NUM_RETRIES + : EXPONENTIAL_STRATEGY_NUM_RETRIES; + } + /** + * (status code is one of the retriable 400 status code + * or + * status code is >= 500 and <= 599) + * and + * current count of retries is less than the max number of retries + */ + if ((HTTP_STATUS_400_CODES_FOR_EXPONENTIAL_STRATEGY.includes(httpStatusCode) || + (httpStatusCode >= HttpStatus.SERVER_ERROR_RANGE_START && + httpStatusCode <= HttpStatus.SERVER_ERROR_RANGE_END && + currentRetry < this.maxRetries)) && + currentRetry < this.maxRetries) { + const retryAfterDelay = httpStatusCode === HttpStatus.GONE + ? ImdsRetryPolicy.HTTP_STATUS_GONE_RETRY_AFTER_MS + : this.exponentialRetryStrategy.calculateDelay(currentRetry); + logger.verbose(`Retrying request in ${retryAfterDelay}ms (retry attempt: ${currentRetry + 1})`); + // pause execution for the calculated delay + await new Promise((resolve) => { + return setTimeout(resolve, retryAfterDelay); + }); + return true; + } + // if the status code is not retriable or max retries have been reached, do not retry + return false; + } +} + +export { ImdsRetryPolicy }; +//# sourceMappingURL=ImdsRetryPolicy.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/retry/LinearRetryStrategy.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/retry/LinearRetryStrategy.mjs new file mode 100644 index 00000000..dbc73b05 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/retry/LinearRetryStrategy.mjs @@ -0,0 +1,36 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +class LinearRetryStrategy { + /** + * Calculates the number of milliseconds to sleep based on the `retry-after` HTTP header. + * + * @param retryHeader - The value of the `retry-after` HTTP header. This can be either a number of seconds + * or an HTTP date string. + * @returns The number of milliseconds to sleep before retrying the request. If the `retry-after` header is not + * present or cannot be parsed, returns 0. + */ + calculateDelay(retryHeader, minimumDelay) { + if (!retryHeader) { + return minimumDelay; + } + // retry-after header is in seconds + let millisToSleep = Math.round(parseFloat(retryHeader) * 1000); + /* + * retry-after header is in HTTP Date format + * , :: GMT + */ + if (isNaN(millisToSleep)) { + // .valueOf() is needed to subtract dates in TypeScript + millisToSleep = + new Date(retryHeader).valueOf() - new Date().valueOf(); + } + return Math.max(minimumDelay, millisToSleep); + } +} + +export { LinearRetryStrategy }; +//# sourceMappingURL=LinearRetryStrategy.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/utils/Constants.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/utils/Constants.mjs new file mode 100644 index 00000000..2fb43923 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/utils/Constants.mjs @@ -0,0 +1,153 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { HttpStatus } from '@azure/msal-common/node'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +// MSI Constants. Docs for MSI are available here https://docs.microsoft.com/azure/app-service/overview-managed-identity +const DEFAULT_MANAGED_IDENTITY_ID = "system_assigned_managed_identity"; +const MANAGED_IDENTITY_DEFAULT_TENANT = "managed_identity"; +const DEFAULT_AUTHORITY_FOR_MANAGED_IDENTITY = `https://login.microsoftonline.com/${MANAGED_IDENTITY_DEFAULT_TENANT}/`; +/** + * Managed Identity Headers - used in network requests + */ +const ManagedIdentityHeaders = { + AUTHORIZATION_HEADER_NAME: "Authorization", + METADATA_HEADER_NAME: "Metadata", + APP_SERVICE_SECRET_HEADER_NAME: "X-IDENTITY-HEADER", + ML_AND_SF_SECRET_HEADER_NAME: "secret", +}; +/** + * Managed Identity Query Parameters - used in network requests + */ +const ManagedIdentityQueryParameters = { + API_VERSION: "api-version", + RESOURCE: "resource", + SHA256_TOKEN_TO_REFRESH: "token_sha256_to_refresh", + XMS_CC: "xms_cc", +}; +/** + * Managed Identity Environment Variable Names + */ +const ManagedIdentityEnvironmentVariableNames = { + AZURE_POD_IDENTITY_AUTHORITY_HOST: "AZURE_POD_IDENTITY_AUTHORITY_HOST", + DEFAULT_IDENTITY_CLIENT_ID: "DEFAULT_IDENTITY_CLIENT_ID", + IDENTITY_ENDPOINT: "IDENTITY_ENDPOINT", + IDENTITY_HEADER: "IDENTITY_HEADER", + IDENTITY_SERVER_THUMBPRINT: "IDENTITY_SERVER_THUMBPRINT", + IMDS_ENDPOINT: "IMDS_ENDPOINT", + MSI_ENDPOINT: "MSI_ENDPOINT", + MSI_SECRET: "MSI_SECRET", +}; +/** + * Managed Identity Source Names + * @public + */ +const ManagedIdentitySourceNames = { + APP_SERVICE: "AppService", + AZURE_ARC: "AzureArc", + CLOUD_SHELL: "CloudShell", + DEFAULT_TO_IMDS: "DefaultToImds", + IMDS: "Imds", + MACHINE_LEARNING: "MachineLearning", + SERVICE_FABRIC: "ServiceFabric", +}; +/** + * Managed Identity Ids + */ +const ManagedIdentityIdType = { + SYSTEM_ASSIGNED: "system-assigned", + USER_ASSIGNED_CLIENT_ID: "user-assigned-client-id", + USER_ASSIGNED_RESOURCE_ID: "user-assigned-resource-id", + USER_ASSIGNED_OBJECT_ID: "user-assigned-object-id", +}; +/** + * http methods + */ +const HttpMethod = { + GET: "get", + POST: "post", +}; +const ProxyStatus = { + SUCCESS_RANGE_START: HttpStatus.SUCCESS_RANGE_START, + SUCCESS_RANGE_END: HttpStatus.SUCCESS_RANGE_END, + SERVER_ERROR: HttpStatus.SERVER_ERROR, +}; +/** + * Constants used for region discovery + */ +const REGION_ENVIRONMENT_VARIABLE = "REGION_NAME"; +const MSAL_FORCE_REGION = "MSAL_FORCE_REGION"; +/** + * Constant used for PKCE + */ +const RANDOM_OCTET_SIZE = 32; +/** + * Constants used in PKCE + */ +const Hash = { + SHA256: "sha256", +}; +/** + * Constants for encoding schemes + */ +const CharSet = { + CV_CHARSET: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~", +}; +/** + * Cache Constants + */ +const CACHE = { + KEY_SEPARATOR: "-", +}; +/** + * Constants + */ +const Constants = { + MSAL_SKU: "msal.js.node", + JWT_BEARER_ASSERTION_TYPE: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", + AUTHORIZATION_PENDING: "authorization_pending", + HTTP_PROTOCOL: "http://", + LOCALHOST: "localhost", +}; +/** + * API Codes for Telemetry purposes. + * Before adding a new code you must claim it in the MSAL Telemetry tracker as these number spaces are shared across all MSALs + * 0-99 Silent Flow + * 600-699 Device Code Flow + * 800-899 Auth Code Flow + */ +const ApiId = { + acquireTokenSilent: 62, + acquireTokenByUsernamePassword: 371, + acquireTokenByDeviceCode: 671, + acquireTokenByClientCredential: 771, + acquireTokenByCode: 871, + acquireTokenByRefreshToken: 872, +}; +/** + * JWT constants + */ +const JwtConstants = { + RSA_256: "RS256", + PSS_256: "PS256", + X5T_256: "x5t#S256", + X5T: "x5t", + X5C: "x5c", + AUDIENCE: "aud", + EXPIRATION_TIME: "exp", + ISSUER: "iss", + SUBJECT: "sub", + NOT_BEFORE: "nbf", + JWT_ID: "jti", +}; +const LOOPBACK_SERVER_CONSTANTS = { + INTERVAL_MS: 100, + TIMEOUT_MS: 5000, +}; +const AZURE_ARC_SECRET_FILE_MAX_SIZE_BYTES = 4096; // 4 KB + +export { AZURE_ARC_SECRET_FILE_MAX_SIZE_BYTES, ApiId, CACHE, CharSet, Constants, DEFAULT_AUTHORITY_FOR_MANAGED_IDENTITY, DEFAULT_MANAGED_IDENTITY_ID, Hash, HttpMethod, JwtConstants, LOOPBACK_SERVER_CONSTANTS, MANAGED_IDENTITY_DEFAULT_TENANT, MSAL_FORCE_REGION, ManagedIdentityEnvironmentVariableNames, ManagedIdentityHeaders, ManagedIdentityIdType, ManagedIdentityQueryParameters, ManagedIdentitySourceNames, ProxyStatus, RANDOM_OCTET_SIZE, REGION_ENVIRONMENT_VARIABLE }; +//# sourceMappingURL=Constants.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/utils/EncodingUtils.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/utils/EncodingUtils.mjs new file mode 100644 index 00000000..8a87a890 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/utils/EncodingUtils.mjs @@ -0,0 +1,51 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +import { EncodingTypes, Constants } from '@azure/msal-common/node'; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +class EncodingUtils { + /** + * 'utf8': Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8. + * 'base64': Base64 encoding. + * + * @param str text + */ + static base64Encode(str, encoding) { + return Buffer.from(str, encoding).toString(EncodingTypes.BASE64); + } + /** + * encode a URL + * @param str + */ + static base64EncodeUrl(str, encoding) { + return EncodingUtils.base64Encode(str, encoding) + .replace(/=/g, Constants.EMPTY_STRING) + .replace(/\+/g, "-") + .replace(/\//g, "_"); + } + /** + * 'utf8': Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8. + * 'base64': Base64 encoding. + * + * @param base64Str Base64 encoded text + */ + static base64Decode(base64Str) { + return Buffer.from(base64Str, EncodingTypes.BASE64).toString("utf8"); + } + /** + * @param base64Str Base64 encoded Url + */ + static base64DecodeUrl(base64Str) { + let str = base64Str.replace(/-/g, "+").replace(/_/g, "/"); + while (str.length % 4) { + str += "="; + } + return EncodingUtils.base64Decode(str); + } +} + +export { EncodingUtils }; +//# sourceMappingURL=EncodingUtils.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/utils/NetworkUtils.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/utils/NetworkUtils.mjs new file mode 100644 index 00000000..5f8de210 --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/utils/NetworkUtils.mjs @@ -0,0 +1,43 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +class NetworkUtils { + static getNetworkResponse(headers, body, statusCode) { + return { + headers: headers, + body: body, + status: statusCode, + }; + } + /* + * Utility function that converts a URL object into an ordinary options object as expected by the + * http.request and https.request APIs. + * https://github.com/nodejs/node/blob/main/lib/internal/url.js#L1090 + */ + static urlToHttpOptions(url) { + const options = { + protocol: url.protocol, + hostname: url.hostname && url.hostname.startsWith("[") + ? url.hostname.slice(1, -1) + : url.hostname, + hash: url.hash, + search: url.search, + pathname: url.pathname, + path: `${url.pathname || ""}${url.search || ""}`, + href: url.href, + }; + if (url.port !== "") { + options.port = Number(url.port); + } + if (url.username || url.password) { + options.auth = `${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`; + } + return options; + } +} + +export { NetworkUtils }; +//# sourceMappingURL=NetworkUtils.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/utils/TimeUtils.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/utils/TimeUtils.mjs new file mode 100644 index 00000000..6e3328dd --- /dev/null +++ b/claude-code-source/node_modules/@azure/msal-node/dist/utils/TimeUtils.mjs @@ -0,0 +1,23 @@ +/*! @azure/msal-node v3.8.1 2025-10-29 */ +'use strict'; +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * @internal + * Checks if a given date string is in ISO 8601 format. + * + * @param dateString - The date string to be checked. + * @returns boolean - Returns true if the date string is in ISO 8601 format, otherwise false. + */ +function isIso8601(dateString) { + if (typeof dateString !== "string") { + return false; + } + const date = new Date(dateString); + return !isNaN(date.getTime()) && date.toISOString() === dateString; +} + +export { isIso8601 }; +//# sourceMappingURL=TimeUtils.mjs.map diff --git a/claude-code-source/node_modules/@commander-js/extra-typings/esm.mjs b/claude-code-source/node_modules/@commander-js/extra-typings/esm.mjs new file mode 100644 index 00000000..cfb03d5c --- /dev/null +++ b/claude-code-source/node_modules/@commander-js/extra-typings/esm.mjs @@ -0,0 +1,16 @@ +import extraTypingsCommander from './index.js'; + +// wrapper to provide named exports for ESM. +export const { + program, + createCommand, + createArgument, + createOption, + CommanderError, + InvalidArgumentError, + InvalidOptionArgumentError, // deprecated old name + Command, + Argument, + Option, + Help, +} = extraTypingsCommander; diff --git a/claude-code-source/node_modules/@commander-js/extra-typings/index.js b/claude-code-source/node_modules/@commander-js/extra-typings/index.js new file mode 100644 index 00000000..2dbceeed --- /dev/null +++ b/claude-code-source/node_modules/@commander-js/extra-typings/index.js @@ -0,0 +1,28 @@ +const commander = require('commander'); + +exports = module.exports = {}; + +// Return a different global program than commander, +// and don't also return it as default export. +exports.program = new commander.Command(); + +/** + * Expose classes. The FooT versions are just types, so return Commander original implementations! + */ + +exports.Argument = commander.Argument; +exports.Command = commander.Command; +exports.CommanderError = commander.CommanderError; +exports.Help = commander.Help; +exports.InvalidArgumentError = commander.InvalidArgumentError; +exports.InvalidOptionArgumentError = commander.InvalidArgumentError; // Deprecated +exports.Option = commander.Option; + +// In Commander, the create routines end up being aliases for the matching +// methods on the global program due to the (deprecated) legacy default export. +// Here we roll our own, the way Commander might in future. +exports.createCommand = (name) => new commander.Command(name); +exports.createOption = (flags, description) => + new commander.Option(flags, description); +exports.createArgument = (name, description) => + new commander.Argument(name, description); diff --git a/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/GrowthBook.mjs b/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/GrowthBook.mjs new file mode 100644 index 00000000..b902a53d --- /dev/null +++ b/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/GrowthBook.mjs @@ -0,0 +1,829 @@ +import mutate from "dom-mutator"; +import { decrypt, getAutoExperimentChangeType, isURLTargeted, loadSDKVersion, mergeQueryStrings, promiseTimeout } from "./util.mjs"; +import { configureCache, refreshFeatures, startStreaming, unsubscribe } from "./feature-repository.mjs"; +import { runExperiment, evalFeature as _evalFeature, getExperimentResult, getAllStickyBucketAssignmentDocs, decryptPayload, getApiHosts, getExperimentDedupeKey, getStickyBucketAttributes } from "./core.mjs"; +const isBrowser = typeof window !== "undefined" && typeof document !== "undefined"; +const SDK_VERSION = loadSDKVersion(); +export class GrowthBook { + // context is technically private, but some tools depend on it so we can't mangle the name + + // Properties and methods that start with "_" are mangled by Terser (saves ~150 bytes) + + constructor(options) { + options = options || {}; + // These properties are all initialized in the constructor instead of above + // This saves ~80 bytes in the final output + this.version = SDK_VERSION; + this._options = this.context = options; + this._renderer = options.renderer || null; + this._trackedExperiments = new Set(); + this._completedChangeIds = new Set(); + this._trackedFeatures = {}; + this.debug = !!options.debug; + this._subscriptions = new Set(); + this.ready = false; + this._assigned = new Map(); + this._activeAutoExperiments = new Map(); + this._triggeredExpKeys = new Set(); + this._initialized = false; + this._redirectedUrl = ""; + this._deferredTrackingCalls = new Map(); + this._autoExperimentsAllowed = !options.disableExperimentsOnLoad; + this._destroyCallbacks = []; + this.logs = []; + this.log = this.log.bind(this); + this._saveDeferredTrack = this._saveDeferredTrack.bind(this); + this._fireSubscriptions = this._fireSubscriptions.bind(this); + this._recordChangedId = this._recordChangedId.bind(this); + if (options.remoteEval) { + if (options.decryptionKey) { + throw new Error("Encryption is not available for remoteEval"); + } + if (!options.clientKey) { + throw new Error("Missing clientKey"); + } + let isGbHost = false; + try { + isGbHost = !!new URL(options.apiHost || "").hostname.match(/growthbook\.io$/i); + } catch (e) { + // ignore invalid URLs + } + if (isGbHost) { + throw new Error("Cannot use remoteEval on GrowthBook Cloud"); + } + } else { + if (options.cacheKeyAttributes) { + throw new Error("cacheKeyAttributes are only used for remoteEval"); + } + } + if (options.stickyBucketService) { + const s = options.stickyBucketService; + this._saveStickyBucketAssignmentDoc = doc => { + return s.saveAssignments(doc); + }; + } + if (options.plugins) { + for (const plugin of options.plugins) { + plugin(this); + } + } + if (options.features) { + this.ready = true; + } + if (isBrowser && options.enableDevMode) { + window._growthbook = this; + document.dispatchEvent(new Event("gbloaded")); + } + if (options.experiments) { + this.ready = true; + this._updateAllAutoExperiments(); + } + + // Hydrate sticky bucket service + if (this._options.stickyBucketService && this._options.stickyBucketAssignmentDocs) { + for (const key in this._options.stickyBucketAssignmentDocs) { + const doc = this._options.stickyBucketAssignmentDocs[key]; + if (doc) { + this._options.stickyBucketService.saveAssignments(doc).catch(() => { + // Ignore hydration errors + }); + } + } + } + + // Legacy - passing in features/experiments into the constructor instead of using init + if (this.ready) { + this.refreshStickyBuckets(this.getPayload()); + } + } + async setPayload(payload) { + this._payload = payload; + const data = await decryptPayload(payload, this._options.decryptionKey); + this._decryptedPayload = data; + await this.refreshStickyBuckets(data); + if (data.features) { + this._options.features = data.features; + } + if (data.savedGroups) { + this._options.savedGroups = data.savedGroups; + } + if (data.experiments) { + this._options.experiments = data.experiments; + this._updateAllAutoExperiments(); + } + this.ready = true; + this._render(); + } + initSync(options) { + this._initialized = true; + const payload = options.payload; + if (payload.encryptedExperiments || payload.encryptedFeatures) { + throw new Error("initSync does not support encrypted payloads"); + } + if (this._options.stickyBucketService && !this._options.stickyBucketAssignmentDocs) { + this._options.stickyBucketAssignmentDocs = this.generateStickyBucketAssignmentDocsSync(this._options.stickyBucketService, payload); + } + this._payload = payload; + this._decryptedPayload = payload; + if (payload.features) { + this._options.features = payload.features; + } + if (payload.experiments) { + this._options.experiments = payload.experiments; + this._updateAllAutoExperiments(); + } + this.ready = true; + startStreaming(this, options); + return this; + } + async init(options) { + this._initialized = true; + options = options || {}; + if (options.cacheSettings) { + configureCache(options.cacheSettings); + } + if (options.payload) { + await this.setPayload(options.payload); + startStreaming(this, options); + return { + success: true, + source: "init" + }; + } else { + const { + data, + ...res + } = await this._refresh({ + ...options, + allowStale: true + }); + startStreaming(this, options); + await this.setPayload(data || {}); + return res; + } + } + + /** @deprecated Use {@link init} */ + async loadFeatures(options) { + options = options || {}; + await this.init({ + skipCache: options.skipCache, + timeout: options.timeout, + streaming: (this._options.backgroundSync ?? true) && (options.autoRefresh || this._options.subscribeToChanges) + }); + } + async refreshFeatures(options) { + const res = await this._refresh({ + ...(options || {}), + allowStale: false + }); + if (res.data) { + await this.setPayload(res.data); + } + } + getApiInfo() { + return [this.getApiHosts().apiHost, this.getClientKey()]; + } + getApiHosts() { + return getApiHosts(this._options); + } + getClientKey() { + return this._options.clientKey || ""; + } + getPayload() { + return this._payload || { + features: this.getFeatures(), + experiments: this.getExperiments() + }; + } + getDecryptedPayload() { + return this._decryptedPayload || this.getPayload(); + } + isRemoteEval() { + return this._options.remoteEval || false; + } + getCacheKeyAttributes() { + return this._options.cacheKeyAttributes; + } + async _refresh(_ref) { + let { + timeout, + skipCache, + allowStale, + streaming + } = _ref; + if (!this._options.clientKey) { + throw new Error("Missing clientKey"); + } + // Trigger refresh in feature repository + return refreshFeatures({ + instance: this, + timeout, + skipCache: skipCache || this._options.disableCache, + allowStale, + backgroundSync: streaming ?? this._options.backgroundSync ?? true + }); + } + _render() { + if (this._renderer) { + try { + this._renderer(); + } catch (e) { + console.error("Failed to render", e); + } + } + } + + /** @deprecated Use {@link setPayload} */ + setFeatures(features) { + this._options.features = features; + this.ready = true; + this._render(); + } + + /** @deprecated Use {@link setPayload} */ + async setEncryptedFeatures(encryptedString, decryptionKey, subtle) { + const featuresJSON = await decrypt(encryptedString, decryptionKey || this._options.decryptionKey, subtle); + this.setFeatures(JSON.parse(featuresJSON)); + } + + /** @deprecated Use {@link setPayload} */ + setExperiments(experiments) { + this._options.experiments = experiments; + this.ready = true; + this._updateAllAutoExperiments(); + } + + /** @deprecated Use {@link setPayload} */ + async setEncryptedExperiments(encryptedString, decryptionKey, subtle) { + const experimentsJSON = await decrypt(encryptedString, decryptionKey || this._options.decryptionKey, subtle); + this.setExperiments(JSON.parse(experimentsJSON)); + } + async setAttributes(attributes) { + this._options.attributes = attributes; + if (this._options.stickyBucketService) { + await this.refreshStickyBuckets(); + } + if (this._options.remoteEval) { + await this._refreshForRemoteEval(); + return; + } + this._render(); + this._updateAllAutoExperiments(); + } + async updateAttributes(attributes) { + return this.setAttributes({ + ...this._options.attributes, + ...attributes + }); + } + async setAttributeOverrides(overrides) { + this._options.attributeOverrides = overrides; + if (this._options.stickyBucketService) { + await this.refreshStickyBuckets(); + } + if (this._options.remoteEval) { + await this._refreshForRemoteEval(); + return; + } + this._render(); + this._updateAllAutoExperiments(); + } + async setForcedVariations(vars) { + this._options.forcedVariations = vars || {}; + if (this._options.remoteEval) { + await this._refreshForRemoteEval(); + return; + } + this._render(); + this._updateAllAutoExperiments(); + } + + // eslint-disable-next-line + setForcedFeatures(map) { + this._options.forcedFeatureValues = map; + this._render(); + } + async setURL(url) { + if (url === this._options.url) return; + this._options.url = url; + this._redirectedUrl = ""; + if (this._options.remoteEval) { + await this._refreshForRemoteEval(); + this._updateAllAutoExperiments(true); + return; + } + this._updateAllAutoExperiments(true); + } + getAttributes() { + return { + ...this._options.attributes, + ...this._options.attributeOverrides + }; + } + getForcedVariations() { + return this._options.forcedVariations || {}; + } + getForcedFeatures() { + // eslint-disable-next-line + return this._options.forcedFeatureValues || new Map(); + } + getStickyBucketAssignmentDocs() { + return this._options.stickyBucketAssignmentDocs || {}; + } + getUrl() { + return this._options.url || ""; + } + getFeatures() { + return this._options.features || {}; + } + getExperiments() { + return this._options.experiments || []; + } + getCompletedChangeIds() { + return Array.from(this._completedChangeIds); + } + subscribe(cb) { + this._subscriptions.add(cb); + return () => { + this._subscriptions.delete(cb); + }; + } + async _refreshForRemoteEval() { + if (!this._options.remoteEval) return; + if (!this._initialized) return; + const res = await this._refresh({ + allowStale: false + }); + if (res.data) { + await this.setPayload(res.data); + } + } + getAllResults() { + return new Map(this._assigned); + } + onDestroy(cb) { + this._destroyCallbacks.push(cb); + } + isDestroyed() { + return !!this._destroyed; + } + destroy() { + this._destroyed = true; + + // Custom callbacks + // Do this first in case it needs access to the below data that is cleared + this._destroyCallbacks.forEach(cb => { + try { + cb(); + } catch (e) { + console.error(e); + } + }); + + // Release references to save memory + this._subscriptions.clear(); + this._assigned.clear(); + this._trackedExperiments.clear(); + this._completedChangeIds.clear(); + this._deferredTrackingCalls.clear(); + this._trackedFeatures = {}; + this._destroyCallbacks = []; + this._payload = undefined; + this._saveStickyBucketAssignmentDoc = undefined; + unsubscribe(this); + this.logs = []; + if (isBrowser && window._growthbook === this) { + delete window._growthbook; + } + + // Undo any active auto experiments + this._activeAutoExperiments.forEach(exp => { + exp.undo(); + }); + this._activeAutoExperiments.clear(); + this._triggeredExpKeys.clear(); + } + setRenderer(renderer) { + this._renderer = renderer; + } + forceVariation(key, variation) { + this._options.forcedVariations = this._options.forcedVariations || {}; + this._options.forcedVariations[key] = variation; + if (this._options.remoteEval) { + this._refreshForRemoteEval(); + return; + } + this._updateAllAutoExperiments(); + this._render(); + } + run(experiment) { + const { + result + } = runExperiment(experiment, null, this._getEvalContext()); + this._fireSubscriptions(experiment, result); + return result; + } + triggerExperiment(key) { + this._triggeredExpKeys.add(key); + if (!this._options.experiments) return null; + const experiments = this._options.experiments.filter(exp => exp.key === key); + return experiments.map(exp => { + return this._runAutoExperiment(exp); + }).filter(res => res !== null); + } + triggerAutoExperiments() { + this._autoExperimentsAllowed = true; + this._updateAllAutoExperiments(true); + } + _getEvalContext() { + return { + user: this._getUserContext(), + global: this._getGlobalContext(), + stack: { + evaluatedFeatures: new Set() + } + }; + } + _getUserContext() { + return { + attributes: this._options.user ? { + ...this._options.user, + ...this._options.attributes + } : this._options.attributes, + enableDevMode: this._options.enableDevMode, + blockedChangeIds: this._options.blockedChangeIds, + stickyBucketAssignmentDocs: this._options.stickyBucketAssignmentDocs, + url: this._getContextUrl(), + forcedVariations: this._options.forcedVariations, + forcedFeatureValues: this._options.forcedFeatureValues, + attributeOverrides: this._options.attributeOverrides, + saveStickyBucketAssignmentDoc: this._saveStickyBucketAssignmentDoc, + trackingCallback: this._options.trackingCallback, + onFeatureUsage: this._options.onFeatureUsage, + devLogs: this.logs, + trackedExperiments: this._trackedExperiments, + trackedFeatureUsage: this._trackedFeatures + }; + } + _getGlobalContext() { + return { + features: this._options.features, + experiments: this._options.experiments, + log: this.log, + enabled: this._options.enabled, + qaMode: this._options.qaMode, + savedGroups: this._options.savedGroups, + groups: this._options.groups, + overrides: this._options.overrides, + onExperimentEval: this._subscriptions.size > 0 ? this._fireSubscriptions : undefined, + recordChangeId: this._recordChangedId, + saveDeferredTrack: this._saveDeferredTrack, + eventLogger: this._options.eventLogger + }; + } + _runAutoExperiment(experiment, forceRerun) { + const existing = this._activeAutoExperiments.get(experiment); + + // If this is a manual experiment and it's not already running, skip + if (experiment.manual && !this._triggeredExpKeys.has(experiment.key) && !existing) return null; + + // Check if this particular experiment is blocked by options settings + // For example, if all visualEditor experiments are disabled + const isBlocked = this._isAutoExperimentBlockedByContext(experiment); + if (isBlocked) { + process.env.NODE_ENV !== "production" && this.log("Auto experiment blocked", { + id: experiment.key + }); + } + let result; + let trackingCall; + // Run the experiment (if blocked exclude) + if (isBlocked) { + result = getExperimentResult(this._getEvalContext(), experiment, -1, false, ""); + } else { + ({ + result, + trackingCall + } = runExperiment(experiment, null, this._getEvalContext())); + this._fireSubscriptions(experiment, result); + } + + // A hash to quickly tell if the assigned value changed + const valueHash = JSON.stringify(result.value); + + // If the changes are already active, no need to re-apply them + if (!forceRerun && result.inExperiment && existing && existing.valueHash === valueHash) { + return result; + } + + // Undo any existing changes + if (existing) this._undoActiveAutoExperiment(experiment); + + // Apply new changes + if (result.inExperiment) { + const changeType = getAutoExperimentChangeType(experiment); + if (changeType === "redirect" && result.value.urlRedirect && experiment.urlPatterns) { + const url = experiment.persistQueryString ? mergeQueryStrings(this._getContextUrl(), result.value.urlRedirect) : result.value.urlRedirect; + if (isURLTargeted(url, experiment.urlPatterns)) { + this.log("Skipping redirect because original URL matches redirect URL", { + id: experiment.key + }); + return result; + } + this._redirectedUrl = url; + const { + navigate, + delay + } = this._getNavigateFunction(); + if (navigate) { + if (isBrowser) { + // Wait for the possibly-async tracking callback, bound by min and max delays + Promise.all([...(trackingCall ? [promiseTimeout(trackingCall, this._options.maxNavigateDelay ?? 1000)] : []), new Promise(resolve => window.setTimeout(resolve, this._options.navigateDelay ?? delay))]).then(() => { + try { + navigate(url); + } catch (e) { + console.error(e); + } + }); + } else { + try { + navigate(url); + } catch (e) { + console.error(e); + } + } + } + } else if (changeType === "visual") { + const undo = this._options.applyDomChangesCallback ? this._options.applyDomChangesCallback(result.value) : this._applyDOMChanges(result.value); + if (undo) { + this._activeAutoExperiments.set(experiment, { + undo, + valueHash + }); + } + } + } + return result; + } + _undoActiveAutoExperiment(exp) { + const data = this._activeAutoExperiments.get(exp); + if (data) { + data.undo(); + this._activeAutoExperiments.delete(exp); + } + } + _updateAllAutoExperiments(forceRerun) { + if (!this._autoExperimentsAllowed) return; + const experiments = this._options.experiments || []; + + // Stop any experiments that are no longer defined + const keys = new Set(experiments); + this._activeAutoExperiments.forEach((v, k) => { + if (!keys.has(k)) { + v.undo(); + this._activeAutoExperiments.delete(k); + } + }); + + // Re-run all new/updated experiments + for (const exp of experiments) { + const result = this._runAutoExperiment(exp, forceRerun); + + // Once you're in a redirect experiment, break out of the loop and don't run any further experiments + if (result !== null && result !== void 0 && result.inExperiment && getAutoExperimentChangeType(exp) === "redirect") { + break; + } + } + } + _fireSubscriptions(experiment, result) { + const key = experiment.key; + + // If assigned variation has changed, fire subscriptions + const prev = this._assigned.get(key); + // TODO: what if the experiment definition has changed? + if (!prev || prev.result.inExperiment !== result.inExperiment || prev.result.variationId !== result.variationId) { + this._assigned.set(key, { + experiment, + result + }); + this._subscriptions.forEach(cb => { + try { + cb(experiment, result); + } catch (e) { + console.error(e); + } + }); + } + } + _recordChangedId(id) { + this._completedChangeIds.add(id); + } + isOn(key) { + return this.evalFeature(key).on; + } + isOff(key) { + return this.evalFeature(key).off; + } + getFeatureValue(key, defaultValue) { + const value = this.evalFeature(key).value; + return value === null ? defaultValue : value; + } + + /** + * @deprecated Use {@link evalFeature} + * @param id + */ + // eslint-disable-next-line + feature(id) { + return this.evalFeature(id); + } + evalFeature(id) { + return _evalFeature(id, this._getEvalContext()); + } + log(msg, ctx) { + if (!this.debug) return; + if (this._options.log) this._options.log(msg, ctx);else console.log(msg, ctx); + } + getDeferredTrackingCalls() { + return Array.from(this._deferredTrackingCalls.values()); + } + setDeferredTrackingCalls(calls) { + this._deferredTrackingCalls = new Map(calls.filter(c => c && c.experiment && c.result).map(c => { + return [getExperimentDedupeKey(c.experiment, c.result), c]; + })); + } + async fireDeferredTrackingCalls() { + if (!this._options.trackingCallback) return; + const promises = []; + this._deferredTrackingCalls.forEach(call => { + if (!call || !call.experiment || !call.result) { + console.error("Invalid deferred tracking call", { + call: call + }); + } else { + promises.push(this._options.trackingCallback(call.experiment, call.result)); + } + }); + this._deferredTrackingCalls.clear(); + await Promise.all(promises); + } + setTrackingCallback(callback) { + this._options.trackingCallback = callback; + this.fireDeferredTrackingCalls(); + } + setEventLogger(logger) { + this._options.eventLogger = logger; + } + async logEvent(eventName, properties) { + if (this._destroyed) { + console.error("Cannot log event to destroyed GrowthBook instance"); + return; + } + if (this._options.enableDevMode) { + this.logs.push({ + eventName, + properties, + timestamp: Date.now().toString(), + logType: "event" + }); + } + if (this._options.eventLogger) { + try { + await this._options.eventLogger(eventName, properties || {}, this._getUserContext()); + } catch (e) { + console.error(e); + } + } else { + console.error("No event logger configured"); + } + } + _saveDeferredTrack(data) { + this._deferredTrackingCalls.set(getExperimentDedupeKey(data.experiment, data.result), data); + } + _getContextUrl() { + return this._options.url || (isBrowser ? window.location.href : ""); + } + _isAutoExperimentBlockedByContext(experiment) { + const changeType = getAutoExperimentChangeType(experiment); + if (changeType === "visual") { + if (this._options.disableVisualExperiments) return true; + if (this._options.disableJsInjection) { + if (experiment.variations.some(v => v.js)) { + return true; + } + } + } else if (changeType === "redirect") { + if (this._options.disableUrlRedirectExperiments) return true; + + // Validate URLs + try { + const current = new URL(this._getContextUrl()); + for (const v of experiment.variations) { + if (!v || !v.urlRedirect) continue; + const url = new URL(v.urlRedirect); + + // If we're blocking cross origin redirects, block if the protocol or host is different + if (this._options.disableCrossOriginUrlRedirectExperiments) { + if (url.protocol !== current.protocol) return true; + if (url.host !== current.host) return true; + } + } + } catch (e) { + // Problem parsing one of the URLs + this.log("Error parsing current or redirect URL", { + id: experiment.key, + error: e + }); + return true; + } + } else { + // Block any unknown changeTypes + return true; + } + if (experiment.changeId && (this._options.blockedChangeIds || []).includes(experiment.changeId)) { + return true; + } + return false; + } + getRedirectUrl() { + return this._redirectedUrl; + } + _getNavigateFunction() { + if (this._options.navigate) { + return { + navigate: this._options.navigate, + delay: 0 + }; + } else if (isBrowser) { + return { + navigate: url => { + window.location.replace(url); + }, + delay: 100 + }; + } + return { + navigate: null, + delay: 0 + }; + } + _applyDOMChanges(changes) { + if (!isBrowser) return; + const undo = []; + if (changes.css) { + const s = document.createElement("style"); + s.innerHTML = changes.css; + document.head.appendChild(s); + undo.push(() => s.remove()); + } + if (changes.js) { + const script = document.createElement("script"); + script.innerHTML = changes.js; + if (this._options.jsInjectionNonce) { + script.nonce = this._options.jsInjectionNonce; + } + document.head.appendChild(script); + undo.push(() => script.remove()); + } + if (changes.domMutations) { + changes.domMutations.forEach(mutation => { + undo.push(mutate.declarative(mutation).revert); + }); + } + return () => { + undo.forEach(fn => fn()); + }; + } + async refreshStickyBuckets(data) { + if (this._options.stickyBucketService) { + const ctx = this._getEvalContext(); + const docs = await getAllStickyBucketAssignmentDocs(ctx, this._options.stickyBucketService, data); + this._options.stickyBucketAssignmentDocs = docs; + } + } + generateStickyBucketAssignmentDocsSync(stickyBucketService, payload) { + if (!("getAllAssignmentsSync" in stickyBucketService)) { + console.error("generating StickyBucketAssignmentDocs docs requires StickyBucketServiceSync"); + return; + } + const ctx = this._getEvalContext(); + const attributes = getStickyBucketAttributes(ctx, payload); + return stickyBucketService.getAllAssignmentsSync(attributes); + } + inDevMode() { + return !!this._options.enableDevMode; + } +} +export async function prefetchPayload(options) { + // Create a temporary instance, just to fetch the payload + const instance = new GrowthBook(options); + await refreshFeatures({ + instance, + skipCache: options.skipCache, + allowStale: false, + backgroundSync: options.streaming + }); + instance.destroy(); +} +//# sourceMappingURL=GrowthBook.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/core.mjs b/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/core.mjs new file mode 100644 index 00000000..680d131f --- /dev/null +++ b/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/core.mjs @@ -0,0 +1,879 @@ +import { evalCondition } from "./mongrule.mjs"; +import { chooseVariation, decrypt, getBucketRanges, getQueryStringOverride, getUrlRegExp, hash, inNamespace, inRange, isIncluded, isURLTargeted, toString } from "./util.mjs"; +export const EVENT_FEATURE_EVALUATED = "Feature Evaluated"; +export const EVENT_EXPERIMENT_VIEWED = "Experiment Viewed"; +function getForcedFeatureValues(ctx) { + // Merge user and global values + const ret = new Map(); + if (ctx.global.forcedFeatureValues) { + ctx.global.forcedFeatureValues.forEach((v, k) => ret.set(k, v)); + } + if (ctx.user.forcedFeatureValues) { + ctx.user.forcedFeatureValues.forEach((v, k) => ret.set(k, v)); + } + return ret; +} +function getForcedVariations(ctx) { + // Merge user and global values + if (ctx.global.forcedVariations && ctx.user.forcedVariations) { + return { + ...ctx.global.forcedVariations, + ...ctx.user.forcedVariations + }; + } else if (ctx.global.forcedVariations) { + return ctx.global.forcedVariations; + } else if (ctx.user.forcedVariations) { + return ctx.user.forcedVariations; + } else { + return {}; + } +} +async function safeCall(fn) { + try { + await fn(); + } catch (e) { + // Do nothing + } +} +function onExperimentViewed(ctx, experiment, result) { + // Make sure a tracking callback is only fired once per unique experiment + if (ctx.user.trackedExperiments) { + const k = getExperimentDedupeKey(experiment, result); + if (ctx.user.trackedExperiments.has(k)) { + return []; + } + ctx.user.trackedExperiments.add(k); + } + if (ctx.user.enableDevMode && ctx.user.devLogs) { + ctx.user.devLogs.push({ + experiment, + result, + timestamp: Date.now().toString(), + logType: "experiment" + }); + } + const calls = []; + if (ctx.global.trackingCallback) { + const cb = ctx.global.trackingCallback; + calls.push(safeCall(() => cb(experiment, result, ctx.user))); + } + if (ctx.user.trackingCallback) { + const cb = ctx.user.trackingCallback; + calls.push(safeCall(() => cb(experiment, result))); + } + if (ctx.global.eventLogger) { + const cb = ctx.global.eventLogger; + calls.push(safeCall(() => cb(EVENT_EXPERIMENT_VIEWED, { + experimentId: experiment.key, + variationId: result.key, + hashAttribute: result.hashAttribute, + hashValue: result.hashValue + }, ctx.user))); + } + return calls; +} +function onFeatureUsage(ctx, key, ret) { + // Only track a feature once, unless the assigned value changed + if (ctx.user.trackedFeatureUsage) { + const stringifiedValue = JSON.stringify(ret.value); + if (ctx.user.trackedFeatureUsage[key] === stringifiedValue) return; + ctx.user.trackedFeatureUsage[key] = stringifiedValue; + if (ctx.user.enableDevMode && ctx.user.devLogs) { + ctx.user.devLogs.push({ + featureKey: key, + result: ret, + timestamp: Date.now().toString(), + logType: "feature" + }); + } + } + if (ctx.global.onFeatureUsage) { + const cb = ctx.global.onFeatureUsage; + safeCall(() => cb(key, ret, ctx.user)); + } + if (ctx.user.onFeatureUsage) { + const cb = ctx.user.onFeatureUsage; + safeCall(() => cb(key, ret)); + } + if (ctx.global.eventLogger) { + const cb = ctx.global.eventLogger; + safeCall(() => cb(EVENT_FEATURE_EVALUATED, { + feature: key, + source: ret.source, + value: ret.value, + ruleId: ret.source === "defaultValue" ? "$default" : ret.ruleId || "", + variationId: ret.experimentResult ? ret.experimentResult.key : "" + }, ctx.user)); + } +} +export function evalFeature(id, ctx) { + if (ctx.stack.evaluatedFeatures.has(id)) { + process.env.NODE_ENV !== "production" && ctx.global.log(`evalFeature: circular dependency detected: ${ctx.stack.id} -> ${id}`, { + from: ctx.stack.id, + to: id + }); + return getFeatureResult(ctx, id, null, "cyclicPrerequisite"); + } + ctx.stack.evaluatedFeatures.add(id); + ctx.stack.id = id; + + // Global override + const forcedValues = getForcedFeatureValues(ctx); + if (forcedValues.has(id)) { + process.env.NODE_ENV !== "production" && ctx.global.log("Global override", { + id, + value: forcedValues.get(id) + }); + return getFeatureResult(ctx, id, forcedValues.get(id), "override"); + } + + // Unknown feature id + if (!ctx.global.features || !ctx.global.features[id]) { + process.env.NODE_ENV !== "production" && ctx.global.log("Unknown feature", { + id + }); + return getFeatureResult(ctx, id, null, "unknownFeature"); + } + + // Get the feature + const feature = ctx.global.features[id]; + + // Loop through the rules + if (feature.rules) { + const evaluatedFeatures = new Set(ctx.stack.evaluatedFeatures); + rules: for (const rule of feature.rules) { + // If there are prerequisite flag(s), evaluate them + if (rule.parentConditions) { + for (const parentCondition of rule.parentConditions) { + ctx.stack.evaluatedFeatures = new Set(evaluatedFeatures); + const parentResult = evalFeature(parentCondition.id, ctx); + // break out for cyclic prerequisites + if (parentResult.source === "cyclicPrerequisite") { + return getFeatureResult(ctx, id, null, "cyclicPrerequisite"); + } + const evalObj = { + value: parentResult.value + }; + const evaled = evalCondition(evalObj, parentCondition.condition || {}); + if (!evaled) { + // blocking prerequisite eval failed: feature evaluation fails + if (parentCondition.gate) { + process.env.NODE_ENV !== "production" && ctx.global.log("Feature blocked by prerequisite", { + id, + rule + }); + return getFeatureResult(ctx, id, null, "prerequisite"); + } + // non-blocking prerequisite eval failed: break out of parentConditions loop, jump to the next rule + process.env.NODE_ENV !== "production" && ctx.global.log("Skip rule because prerequisite evaluation fails", { + id, + rule + }); + continue rules; + } + } + } + + // If there are filters for who is included (e.g. namespaces) + if (rule.filters && isFilteredOut(rule.filters, ctx)) { + process.env.NODE_ENV !== "production" && ctx.global.log("Skip rule because of filters", { + id, + rule + }); + continue; + } + + // Feature value is being forced + if ("force" in rule) { + // If it's a conditional rule, skip if the condition doesn't pass + if (rule.condition && !conditionPasses(rule.condition, ctx)) { + process.env.NODE_ENV !== "production" && ctx.global.log("Skip rule because of condition ff", { + id, + rule + }); + continue; + } + + // If this is a percentage rollout, skip if not included + if (!isIncludedInRollout(ctx, rule.seed || id, rule.hashAttribute, ctx.user.saveStickyBucketAssignmentDoc && !rule.disableStickyBucketing ? rule.fallbackAttribute : undefined, rule.range, rule.coverage, rule.hashVersion)) { + process.env.NODE_ENV !== "production" && ctx.global.log("Skip rule because user not included in rollout", { + id, + rule + }); + continue; + } + process.env.NODE_ENV !== "production" && ctx.global.log("Force value from rule", { + id, + rule + }); + + // If this was a remotely evaluated experiment, fire the tracking callbacks + if (rule.tracks) { + rule.tracks.forEach(t => { + const calls = onExperimentViewed(ctx, t.experiment, t.result); + if (!calls.length && ctx.global.saveDeferredTrack) { + ctx.global.saveDeferredTrack({ + experiment: t.experiment, + result: t.result + }); + } + }); + } + return getFeatureResult(ctx, id, rule.force, "force", rule.id); + } + if (!rule.variations) { + process.env.NODE_ENV !== "production" && ctx.global.log("Skip invalid rule", { + id, + rule + }); + continue; + } + + // For experiment rules, run an experiment + const exp = { + variations: rule.variations, + key: rule.key || id + }; + if ("coverage" in rule) exp.coverage = rule.coverage; + if (rule.weights) exp.weights = rule.weights; + if (rule.hashAttribute) exp.hashAttribute = rule.hashAttribute; + if (rule.fallbackAttribute) exp.fallbackAttribute = rule.fallbackAttribute; + if (rule.disableStickyBucketing) exp.disableStickyBucketing = rule.disableStickyBucketing; + if (rule.bucketVersion !== undefined) exp.bucketVersion = rule.bucketVersion; + if (rule.minBucketVersion !== undefined) exp.minBucketVersion = rule.minBucketVersion; + if (rule.namespace) exp.namespace = rule.namespace; + if (rule.meta) exp.meta = rule.meta; + if (rule.ranges) exp.ranges = rule.ranges; + if (rule.name) exp.name = rule.name; + if (rule.phase) exp.phase = rule.phase; + if (rule.seed) exp.seed = rule.seed; + if (rule.hashVersion) exp.hashVersion = rule.hashVersion; + if (rule.filters) exp.filters = rule.filters; + if (rule.condition) exp.condition = rule.condition; + + // Only return a value if the user is part of the experiment + const { + result + } = runExperiment(exp, id, ctx); + ctx.global.onExperimentEval && ctx.global.onExperimentEval(exp, result); + if (result.inExperiment && !result.passthrough) { + return getFeatureResult(ctx, id, result.value, "experiment", rule.id, exp, result); + } + } + } + process.env.NODE_ENV !== "production" && ctx.global.log("Use default value", { + id, + value: feature.defaultValue + }); + + // Fall back to using the default value + return getFeatureResult(ctx, id, feature.defaultValue === undefined ? null : feature.defaultValue, "defaultValue"); +} +export function runExperiment(experiment, featureId, ctx) { + const key = experiment.key; + const numVariations = experiment.variations.length; + + // 1. If experiment has less than 2 variations, return immediately + if (numVariations < 2) { + process.env.NODE_ENV !== "production" && ctx.global.log("Invalid experiment", { + id: key + }); + return { + result: getExperimentResult(ctx, experiment, -1, false, featureId) + }; + } + + // 2. If the context is disabled, return immediately + if (ctx.global.enabled === false || ctx.user.enabled === false) { + process.env.NODE_ENV !== "production" && ctx.global.log("Context disabled", { + id: key + }); + return { + result: getExperimentResult(ctx, experiment, -1, false, featureId) + }; + } + + // 2.5. Merge in experiment overrides from the context + experiment = mergeOverrides(experiment, ctx); + + // 2.6 New, more powerful URL targeting + if (experiment.urlPatterns && !isURLTargeted(ctx.user.url || "", experiment.urlPatterns)) { + process.env.NODE_ENV !== "production" && ctx.global.log("Skip because of url targeting", { + id: key + }); + return { + result: getExperimentResult(ctx, experiment, -1, false, featureId) + }; + } + + // 3. If a variation is forced from a querystring, return the forced variation + const qsOverride = getQueryStringOverride(key, ctx.user.url || "", numVariations); + if (qsOverride !== null) { + process.env.NODE_ENV !== "production" && ctx.global.log("Force via querystring", { + id: key, + variation: qsOverride + }); + return { + result: getExperimentResult(ctx, experiment, qsOverride, false, featureId) + }; + } + + // 4. If a variation is forced in the context, return the forced variation + const forcedVariations = getForcedVariations(ctx); + if (key in forcedVariations) { + const variation = forcedVariations[key]; + process.env.NODE_ENV !== "production" && ctx.global.log("Force via dev tools", { + id: key, + variation + }); + return { + result: getExperimentResult(ctx, experiment, variation, false, featureId) + }; + } + + // 5. Exclude if a draft experiment or not active + if (experiment.status === "draft" || experiment.active === false) { + process.env.NODE_ENV !== "production" && ctx.global.log("Skip because inactive", { + id: key + }); + return { + result: getExperimentResult(ctx, experiment, -1, false, featureId) + }; + } + + // 6. Get the hash attribute and return if empty + const { + hashAttribute, + hashValue + } = getHashAttribute(ctx, experiment.hashAttribute, ctx.user.saveStickyBucketAssignmentDoc && !experiment.disableStickyBucketing ? experiment.fallbackAttribute : undefined); + if (!hashValue) { + process.env.NODE_ENV !== "production" && ctx.global.log("Skip because missing hashAttribute", { + id: key + }); + return { + result: getExperimentResult(ctx, experiment, -1, false, featureId) + }; + } + let assigned = -1; + let foundStickyBucket = false; + let stickyBucketVersionIsBlocked = false; + if (ctx.user.saveStickyBucketAssignmentDoc && !experiment.disableStickyBucketing) { + const { + variation, + versionIsBlocked + } = getStickyBucketVariation({ + ctx, + expKey: experiment.key, + expBucketVersion: experiment.bucketVersion, + expHashAttribute: experiment.hashAttribute, + expFallbackAttribute: experiment.fallbackAttribute, + expMinBucketVersion: experiment.minBucketVersion, + expMeta: experiment.meta + }); + foundStickyBucket = variation >= 0; + assigned = variation; + stickyBucketVersionIsBlocked = !!versionIsBlocked; + } + + // Some checks are not needed if we already have a sticky bucket + if (!foundStickyBucket) { + // 7. Exclude if user is filtered out (used to be called "namespace") + if (experiment.filters) { + if (isFilteredOut(experiment.filters, ctx)) { + process.env.NODE_ENV !== "production" && ctx.global.log("Skip because of filters", { + id: key + }); + return { + result: getExperimentResult(ctx, experiment, -1, false, featureId) + }; + } + } else if (experiment.namespace && !inNamespace(hashValue, experiment.namespace)) { + process.env.NODE_ENV !== "production" && ctx.global.log("Skip because of namespace", { + id: key + }); + return { + result: getExperimentResult(ctx, experiment, -1, false, featureId) + }; + } + + // 7.5. Exclude if experiment.include returns false or throws + if (experiment.include && !isIncluded(experiment.include)) { + process.env.NODE_ENV !== "production" && ctx.global.log("Skip because of include function", { + id: key + }); + return { + result: getExperimentResult(ctx, experiment, -1, false, featureId) + }; + } + + // 8. Exclude if condition is false + if (experiment.condition && !conditionPasses(experiment.condition, ctx)) { + process.env.NODE_ENV !== "production" && ctx.global.log("Skip because of condition exp", { + id: key + }); + return { + result: getExperimentResult(ctx, experiment, -1, false, featureId) + }; + } + + // 8.05. Exclude if prerequisites are not met + if (experiment.parentConditions) { + const evaluatedFeatures = new Set(ctx.stack.evaluatedFeatures); + for (const parentCondition of experiment.parentConditions) { + ctx.stack.evaluatedFeatures = new Set(evaluatedFeatures); + const parentResult = evalFeature(parentCondition.id, ctx); + // break out for cyclic prerequisites + if (parentResult.source === "cyclicPrerequisite") { + return { + result: getExperimentResult(ctx, experiment, -1, false, featureId) + }; + } + const evalObj = { + value: parentResult.value + }; + if (!evalCondition(evalObj, parentCondition.condition || {})) { + process.env.NODE_ENV !== "production" && ctx.global.log("Skip because prerequisite evaluation fails", { + id: key + }); + return { + result: getExperimentResult(ctx, experiment, -1, false, featureId) + }; + } + } + } + + // 8.1. Exclude if user is not in a required group + if (experiment.groups && !hasGroupOverlap(experiment.groups, ctx)) { + process.env.NODE_ENV !== "production" && ctx.global.log("Skip because of groups", { + id: key + }); + return { + result: getExperimentResult(ctx, experiment, -1, false, featureId) + }; + } + } + + // 8.2. Old style URL targeting + if (experiment.url && !urlIsValid(experiment.url, ctx)) { + process.env.NODE_ENV !== "production" && ctx.global.log("Skip because of url", { + id: key + }); + return { + result: getExperimentResult(ctx, experiment, -1, false, featureId) + }; + } + + // 9. Get the variation from the sticky bucket or get bucket ranges and choose variation + const n = hash(experiment.seed || key, hashValue, experiment.hashVersion || 1); + if (n === null) { + process.env.NODE_ENV !== "production" && ctx.global.log("Skip because of invalid hash version", { + id: key + }); + return { + result: getExperimentResult(ctx, experiment, -1, false, featureId) + }; + } + if (!foundStickyBucket) { + const ranges = experiment.ranges || getBucketRanges(numVariations, experiment.coverage === undefined ? 1 : experiment.coverage, experiment.weights); + assigned = chooseVariation(n, ranges); + } + + // 9.5 Unenroll if any prior sticky buckets are blocked by version + if (stickyBucketVersionIsBlocked) { + process.env.NODE_ENV !== "production" && ctx.global.log("Skip because sticky bucket version is blocked", { + id: key + }); + return { + result: getExperimentResult(ctx, experiment, -1, false, featureId, undefined, true) + }; + } + + // 10. Return if not in experiment + if (assigned < 0) { + process.env.NODE_ENV !== "production" && ctx.global.log("Skip because of coverage", { + id: key + }); + return { + result: getExperimentResult(ctx, experiment, -1, false, featureId) + }; + } + + // 11. Experiment has a forced variation + if ("force" in experiment) { + process.env.NODE_ENV !== "production" && ctx.global.log("Force variation", { + id: key, + variation: experiment.force + }); + return { + result: getExperimentResult(ctx, experiment, experiment.force === undefined ? -1 : experiment.force, false, featureId) + }; + } + + // 12. Exclude if in QA mode + if (ctx.global.qaMode || ctx.user.qaMode) { + process.env.NODE_ENV !== "production" && ctx.global.log("Skip because QA mode", { + id: key + }); + return { + result: getExperimentResult(ctx, experiment, -1, false, featureId) + }; + } + + // 12.5. Exclude if experiment is stopped + if (experiment.status === "stopped") { + process.env.NODE_ENV !== "production" && ctx.global.log("Skip because stopped", { + id: key + }); + return { + result: getExperimentResult(ctx, experiment, -1, false, featureId) + }; + } + + // 13. Build the result object + const result = getExperimentResult(ctx, experiment, assigned, true, featureId, n, foundStickyBucket); + + // 13.5. Persist sticky bucket + if (ctx.user.saveStickyBucketAssignmentDoc && !experiment.disableStickyBucketing) { + const { + changed, + key: attrKey, + doc + } = generateStickyBucketAssignmentDoc(ctx, hashAttribute, toString(hashValue), { + [getStickyBucketExperimentKey(experiment.key, experiment.bucketVersion)]: result.key + }); + if (changed) { + // update local docs + ctx.user.stickyBucketAssignmentDocs = ctx.user.stickyBucketAssignmentDocs || {}; + ctx.user.stickyBucketAssignmentDocs[attrKey] = doc; + // save doc + ctx.user.saveStickyBucketAssignmentDoc(doc); + } + } + + // 14. Fire the tracking callback(s) + // Store the promise in case we're awaiting it (ex: browser url redirects) + const trackingCalls = onExperimentViewed(ctx, experiment, result); + if (trackingCalls.length === 0 && ctx.global.saveDeferredTrack) { + ctx.global.saveDeferredTrack({ + experiment, + result + }); + } + const trackingCall = !trackingCalls.length ? undefined : trackingCalls.length === 1 ? trackingCalls[0] : Promise.all(trackingCalls).then(() => {}); + + // 14.1 Keep track of completed changeIds + "changeId" in experiment && experiment.changeId && ctx.global.recordChangeId && ctx.global.recordChangeId(experiment.changeId); + + // 15. Return the result + process.env.NODE_ENV !== "production" && ctx.global.log("In experiment", { + id: key, + variation: result.variationId + }); + return { + result, + trackingCall + }; +} +function getFeatureResult(ctx, key, value, source, ruleId, experiment, result) { + const ret = { + value, + on: !!value, + off: !value, + source, + ruleId: ruleId || "" + }; + if (experiment) ret.experiment = experiment; + if (result) ret.experimentResult = result; + + // Track the usage of this feature in real-time + if (source !== "override") { + onFeatureUsage(ctx, key, ret); + } + return ret; +} +function getAttributes(ctx) { + return { + ...ctx.user.attributes, + ...ctx.user.attributeOverrides + }; +} +function conditionPasses(condition, ctx) { + return evalCondition(getAttributes(ctx), condition, ctx.global.savedGroups || {}); +} +function isFilteredOut(filters, ctx) { + return filters.some(filter => { + const { + hashValue + } = getHashAttribute(ctx, filter.attribute); + if (!hashValue) return true; + const n = hash(filter.seed, hashValue, filter.hashVersion || 2); + if (n === null) return true; + return !filter.ranges.some(r => inRange(n, r)); + }); +} +function isIncludedInRollout(ctx, seed, hashAttribute, fallbackAttribute, range, coverage, hashVersion) { + if (!range && coverage === undefined) return true; + if (!range && coverage === 0) return false; + const { + hashValue + } = getHashAttribute(ctx, hashAttribute, fallbackAttribute); + if (!hashValue) { + return false; + } + const n = hash(seed, hashValue, hashVersion || 1); + if (n === null) return false; + return range ? inRange(n, range) : coverage !== undefined ? n <= coverage : true; +} +export function getExperimentResult(ctx, experiment, variationIndex, hashUsed, featureId, bucket, stickyBucketUsed) { + let inExperiment = true; + // If assigned variation is not valid, use the baseline and mark the user as not in the experiment + if (variationIndex < 0 || variationIndex >= experiment.variations.length) { + variationIndex = 0; + inExperiment = false; + } + const { + hashAttribute, + hashValue + } = getHashAttribute(ctx, experiment.hashAttribute, ctx.user.saveStickyBucketAssignmentDoc && !experiment.disableStickyBucketing ? experiment.fallbackAttribute : undefined); + const meta = experiment.meta ? experiment.meta[variationIndex] : {}; + const res = { + key: meta.key || "" + variationIndex, + featureId, + inExperiment, + hashUsed, + variationId: variationIndex, + value: experiment.variations[variationIndex], + hashAttribute, + hashValue, + stickyBucketUsed: !!stickyBucketUsed + }; + if (meta.name) res.name = meta.name; + if (bucket !== undefined) res.bucket = bucket; + if (meta.passthrough) res.passthrough = meta.passthrough; + return res; +} +function mergeOverrides(experiment, ctx) { + const key = experiment.key; + const o = ctx.global.overrides; + if (o && o[key]) { + experiment = Object.assign({}, experiment, o[key]); + if (typeof experiment.url === "string") { + experiment.url = getUrlRegExp( + // eslint-disable-next-line + experiment.url); + } + } + return experiment; +} +export function getHashAttribute(ctx, attr, fallback) { + let hashAttribute = attr || "id"; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let hashValue = ""; + const attributes = getAttributes(ctx); + if (attributes[hashAttribute]) { + hashValue = attributes[hashAttribute]; + } + + // if no match, try fallback + if (!hashValue && fallback) { + if (attributes[fallback]) { + hashValue = attributes[fallback]; + } + if (hashValue) { + hashAttribute = fallback; + } + } + return { + hashAttribute, + hashValue + }; +} +function urlIsValid(urlRegex, ctx) { + const url = ctx.user.url; + if (!url) return false; + const pathOnly = url.replace(/^https?:\/\//, "").replace(/^[^/]*\//, "/"); + if (urlRegex.test(url)) return true; + if (urlRegex.test(pathOnly)) return true; + return false; +} +function hasGroupOverlap(expGroups, ctx) { + const groups = ctx.global.groups || {}; + for (let i = 0; i < expGroups.length; i++) { + if (groups[expGroups[i]]) return true; + } + return false; +} +function getStickyBucketVariation(_ref) { + let { + ctx, + expKey, + expBucketVersion, + expHashAttribute, + expFallbackAttribute, + expMinBucketVersion, + expMeta + } = _ref; + expBucketVersion = expBucketVersion || 0; + expMinBucketVersion = expMinBucketVersion || 0; + expHashAttribute = expHashAttribute || "id"; + expMeta = expMeta || []; + const id = getStickyBucketExperimentKey(expKey, expBucketVersion); + const assignments = getStickyBucketAssignments(ctx, expHashAttribute, expFallbackAttribute); + + // users with any blocked bucket version (0 to minExperimentBucketVersion) are excluded from the test + if (expMinBucketVersion > 0) { + for (let i = 0; i <= expMinBucketVersion; i++) { + const blockedKey = getStickyBucketExperimentKey(expKey, i); + if (assignments[blockedKey] !== undefined) { + return { + variation: -1, + versionIsBlocked: true + }; + } + } + } + const variationKey = assignments[id]; + if (variationKey === undefined) + // no assignment found + return { + variation: -1 + }; + const variation = expMeta.findIndex(m => m.key === variationKey); + if (variation < 0) + // invalid assignment, treat as "no assignment found" + return { + variation: -1 + }; + return { + variation + }; +} +function getStickyBucketExperimentKey(experimentKey, experimentBucketVersion) { + experimentBucketVersion = experimentBucketVersion || 0; + return `${experimentKey}__${experimentBucketVersion}`; +} +export function getStickyBucketAttributeKey(attributeName, attributeValue) { + return `${attributeName}||${attributeValue}`; +} +function getStickyBucketAssignments(ctx, expHashAttribute, expFallbackAttribute) { + if (!ctx.user.stickyBucketAssignmentDocs) return {}; + const { + hashAttribute, + hashValue + } = getHashAttribute(ctx, expHashAttribute); + const hashKey = getStickyBucketAttributeKey(hashAttribute, toString(hashValue)); + const { + hashAttribute: fallbackAttribute, + hashValue: fallbackValue + } = getHashAttribute(ctx, expFallbackAttribute); + const fallbackKey = fallbackValue ? getStickyBucketAttributeKey(fallbackAttribute, toString(fallbackValue)) : null; + const assignments = {}; + if (fallbackKey && ctx.user.stickyBucketAssignmentDocs[fallbackKey]) { + Object.assign(assignments, ctx.user.stickyBucketAssignmentDocs[fallbackKey].assignments || {}); + } + if (ctx.user.stickyBucketAssignmentDocs[hashKey]) { + Object.assign(assignments, ctx.user.stickyBucketAssignmentDocs[hashKey].assignments || {}); + } + return assignments; +} +function generateStickyBucketAssignmentDoc(ctx, attributeName, attributeValue, assignments) { + const key = getStickyBucketAttributeKey(attributeName, attributeValue); + const existingAssignments = ctx.user.stickyBucketAssignmentDocs && ctx.user.stickyBucketAssignmentDocs[key] ? ctx.user.stickyBucketAssignmentDocs[key].assignments || {} : {}; + const newAssignments = { + ...existingAssignments, + ...assignments + }; + const changed = JSON.stringify(existingAssignments) !== JSON.stringify(newAssignments); + return { + key, + doc: { + attributeName, + attributeValue, + assignments: newAssignments + }, + changed + }; +} +function deriveStickyBucketIdentifierAttributes(ctx, data) { + const attributes = new Set(); + const features = data && data.features ? data.features : ctx.global.features || {}; + const experiments = data && data.experiments ? data.experiments : ctx.global.experiments || []; + Object.keys(features).forEach(id => { + const feature = features[id]; + if (feature.rules) { + for (const rule of feature.rules) { + if (rule.variations) { + attributes.add(rule.hashAttribute || "id"); + if (rule.fallbackAttribute) { + attributes.add(rule.fallbackAttribute); + } + } + } + } + }); + experiments.map(experiment => { + attributes.add(experiment.hashAttribute || "id"); + if (experiment.fallbackAttribute) { + attributes.add(experiment.fallbackAttribute); + } + }); + return Array.from(attributes); +} +export async function getAllStickyBucketAssignmentDocs(ctx, stickyBucketService, data) { + const attributes = getStickyBucketAttributes(ctx, data); + return stickyBucketService.getAllAssignments(attributes); +} +export function getStickyBucketAttributes(ctx, data) { + const attributes = {}; + const stickyBucketIdentifierAttributes = deriveStickyBucketIdentifierAttributes(ctx, data); + stickyBucketIdentifierAttributes.forEach(attr => { + const { + hashValue + } = getHashAttribute(ctx, attr); + attributes[attr] = toString(hashValue); + }); + return attributes; +} +export async function decryptPayload(data, decryptionKey, subtle) { + data = { + ...data + }; + if (data.encryptedFeatures) { + try { + data.features = JSON.parse(await decrypt(data.encryptedFeatures, decryptionKey, subtle)); + } catch (e) { + console.error(e); + } + delete data.encryptedFeatures; + } + if (data.encryptedExperiments) { + try { + data.experiments = JSON.parse(await decrypt(data.encryptedExperiments, decryptionKey, subtle)); + } catch (e) { + console.error(e); + } + delete data.encryptedExperiments; + } + if (data.encryptedSavedGroups) { + try { + data.savedGroups = JSON.parse(await decrypt(data.encryptedSavedGroups, decryptionKey, subtle)); + } catch (e) { + console.error(e); + } + delete data.encryptedSavedGroups; + } + return data; +} +export function getApiHosts(options) { + const defaultHost = options.apiHost || "https://cdn.growthbook.io"; + return { + apiHost: defaultHost.replace(/\/*$/, ""), + streamingHost: (options.streamingHost || defaultHost).replace(/\/*$/, ""), + apiRequestHeaders: options.apiHostRequestHeaders, + streamingHostRequestHeaders: options.streamingHostRequestHeaders + }; +} +export function getExperimentDedupeKey(experiment, result) { + return result.hashAttribute + result.hashValue + experiment.key + result.variationId; +} +//# sourceMappingURL=core.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/feature-repository.mjs b/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/feature-repository.mjs new file mode 100644 index 00000000..65770931 --- /dev/null +++ b/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/feature-repository.mjs @@ -0,0 +1,488 @@ +import { getPolyfills, promiseTimeout } from "./util.mjs"; +// Config settings +const cacheSettings = { + // Consider a fetch stale after 1 minute + staleTTL: 1000 * 60, + // Max time to keep a fetch in cache (4 hours default) + maxAge: 1000 * 60 * 60 * 4, + cacheKey: "gbFeaturesCache", + backgroundSync: true, + maxEntries: 10, + disableIdleStreams: false, + idleStreamInterval: 20000, + disableCache: false +}; +const polyfills = getPolyfills(); +export const helpers = { + fetchFeaturesCall: _ref => { + let { + host, + clientKey, + headers + } = _ref; + return polyfills.fetch(`${host}/api/features/${clientKey}`, { + headers + }); + }, + fetchRemoteEvalCall: _ref2 => { + let { + host, + clientKey, + payload, + headers + } = _ref2; + const options = { + method: "POST", + headers: { + "Content-Type": "application/json", + ...headers + }, + body: JSON.stringify(payload) + }; + return polyfills.fetch(`${host}/api/eval/${clientKey}`, options); + }, + eventSourceCall: _ref3 => { + let { + host, + clientKey, + headers + } = _ref3; + if (headers) { + return new polyfills.EventSource(`${host}/sub/${clientKey}`, { + headers + }); + } + return new polyfills.EventSource(`${host}/sub/${clientKey}`); + }, + startIdleListener: () => { + let idleTimeout; + const isBrowser = typeof window !== "undefined" && typeof document !== "undefined"; + if (!isBrowser) return; + const onVisibilityChange = () => { + if (document.visibilityState === "visible") { + window.clearTimeout(idleTimeout); + onVisible(); + } else if (document.visibilityState === "hidden") { + idleTimeout = window.setTimeout(onHidden, cacheSettings.idleStreamInterval); + } + }; + document.addEventListener("visibilitychange", onVisibilityChange); + return () => document.removeEventListener("visibilitychange", onVisibilityChange); + }, + stopIdleListener: () => { + // No-op, replaced by startIdleListener + } +}; +try { + if (globalThis.localStorage) { + polyfills.localStorage = globalThis.localStorage; + } +} catch (e) { + // Ignore localStorage errors +} + +// Global state +const subscribedInstances = new Map(); +let cacheInitialized = false; +const cache = new Map(); +const activeFetches = new Map(); +const streams = new Map(); +const supportsSSE = new Set(); + +// Public functions +export function setPolyfills(overrides) { + Object.assign(polyfills, overrides); +} +export function configureCache(overrides) { + Object.assign(cacheSettings, overrides); + if (!cacheSettings.backgroundSync) { + clearAutoRefresh(); + } +} +export async function clearCache() { + cache.clear(); + activeFetches.clear(); + clearAutoRefresh(); + cacheInitialized = false; + await updatePersistentCache(); +} + +// Get or fetch features and refresh the SDK instance +export async function refreshFeatures(_ref4) { + let { + instance, + timeout, + skipCache, + allowStale, + backgroundSync + } = _ref4; + if (!backgroundSync) { + cacheSettings.backgroundSync = false; + } + return fetchFeaturesWithCache({ + instance, + allowStale, + timeout, + skipCache + }); +} + +// Subscribe a GrowthBook instance to feature changes +function subscribe(instance) { + const key = getKey(instance); + const subs = subscribedInstances.get(key) || new Set(); + subs.add(instance); + subscribedInstances.set(key, subs); +} +export function unsubscribe(instance) { + subscribedInstances.forEach(s => s.delete(instance)); +} +export function onHidden() { + streams.forEach(channel => { + if (!channel) return; + channel.state = "idle"; + disableChannel(channel); + }); +} +export function onVisible() { + streams.forEach(channel => { + if (!channel) return; + if (channel.state !== "idle") return; + enableChannel(channel); + }); +} + +// Private functions + +async function updatePersistentCache() { + try { + if (!polyfills.localStorage) return; + await polyfills.localStorage.setItem(cacheSettings.cacheKey, JSON.stringify(Array.from(cache.entries()))); + } catch (e) { + // Ignore localStorage errors + } +} + +// SWR wrapper for fetching features. May indirectly or directly start SSE streaming. +async function fetchFeaturesWithCache(_ref5) { + let { + instance, + allowStale, + timeout, + skipCache + } = _ref5; + const key = getKey(instance); + const cacheKey = getCacheKey(instance); + const now = new Date(); + const minStaleAt = new Date(now.getTime() - cacheSettings.maxAge + cacheSettings.staleTTL); + await initializeCache(); + const existing = !cacheSettings.disableCache && !skipCache ? cache.get(cacheKey) : undefined; + if (existing && (allowStale || existing.staleAt > now) && existing.staleAt > minStaleAt) { + // Restore from cache whether SSE is supported + if (existing.sse) supportsSSE.add(key); + + // Reload features in the background if stale + if (existing.staleAt < now) { + fetchFeatures(instance); + } + // Otherwise, if we don't need to refresh now, start a background sync + else { + startAutoRefresh(instance); + } + return { + data: existing.data, + success: true, + source: "cache" + }; + } else { + const res = await promiseTimeout(fetchFeatures(instance), timeout); + return res || { + data: null, + success: false, + source: "timeout", + error: new Error("Timeout") + }; + } +} +function getKey(instance) { + const [apiHost, clientKey] = instance.getApiInfo(); + return `${apiHost}||${clientKey}`; +} +function getCacheKey(instance) { + const baseKey = getKey(instance); + if (!("isRemoteEval" in instance) || !instance.isRemoteEval()) return baseKey; + const attributes = instance.getAttributes(); + const cacheKeyAttributes = instance.getCacheKeyAttributes() || Object.keys(instance.getAttributes()); + const ca = {}; + cacheKeyAttributes.forEach(key => { + ca[key] = attributes[key]; + }); + const fv = instance.getForcedVariations(); + const url = instance.getUrl(); + return `${baseKey}||${JSON.stringify({ + ca, + fv, + url + })}`; +} + +// Populate cache from localStorage (if available) +async function initializeCache() { + if (cacheInitialized) return; + cacheInitialized = true; + try { + if (polyfills.localStorage) { + const value = await polyfills.localStorage.getItem(cacheSettings.cacheKey); + if (!cacheSettings.disableCache && value) { + const parsed = JSON.parse(value); + if (parsed && Array.isArray(parsed)) { + parsed.forEach(_ref6 => { + let [key, data] = _ref6; + cache.set(key, { + ...data, + staleAt: new Date(data.staleAt) + }); + }); + } + cleanupCache(); + } + } + } catch (e) { + // Ignore localStorage errors + } + if (!cacheSettings.disableIdleStreams) { + const cleanupFn = helpers.startIdleListener(); + if (cleanupFn) { + helpers.stopIdleListener = cleanupFn; + } + } +} + +// Enforce the maxEntries limit +function cleanupCache() { + const entriesWithTimestamps = Array.from(cache.entries()).map(_ref7 => { + let [key, value] = _ref7; + return { + key, + staleAt: value.staleAt.getTime() + }; + }).sort((a, b) => a.staleAt - b.staleAt); + const entriesToRemoveCount = Math.min(Math.max(0, cache.size - cacheSettings.maxEntries), cache.size); + for (let i = 0; i < entriesToRemoveCount; i++) { + cache.delete(entriesWithTimestamps[i].key); + } +} + +// Called whenever new features are fetched from the API +function onNewFeatureData(key, cacheKey, data) { + // If contents haven't changed, ignore the update, extend the stale TTL + const version = data.dateUpdated || ""; + const staleAt = new Date(Date.now() + cacheSettings.staleTTL); + const existing = !cacheSettings.disableCache ? cache.get(cacheKey) : undefined; + if (existing && version && existing.version === version) { + existing.staleAt = staleAt; + updatePersistentCache(); + return; + } + if (!cacheSettings.disableCache) { + // Update in-memory cache + cache.set(cacheKey, { + data, + version, + staleAt, + sse: supportsSSE.has(key) + }); + cleanupCache(); + } + // Update local storage (don't await this, just update asynchronously) + updatePersistentCache(); + + // Update features for all subscribed GrowthBook instances + const instances = subscribedInstances.get(key); + instances && instances.forEach(instance => refreshInstance(instance, data)); +} +async function refreshInstance(instance, data) { + await instance.setPayload(data || instance.getPayload()); +} + +// Fetch the features payload from helper function or from in-mem injected payload +async function fetchFeatures(instance) { + const { + apiHost, + apiRequestHeaders + } = instance.getApiHosts(); + const clientKey = instance.getClientKey(); + const remoteEval = "isRemoteEval" in instance && instance.isRemoteEval(); + const key = getKey(instance); + const cacheKey = getCacheKey(instance); + let promise = activeFetches.get(cacheKey); + if (!promise) { + const fetcher = remoteEval ? helpers.fetchRemoteEvalCall({ + host: apiHost, + clientKey, + payload: { + attributes: instance.getAttributes(), + forcedVariations: instance.getForcedVariations(), + forcedFeatures: Array.from(instance.getForcedFeatures().entries()), + url: instance.getUrl() + }, + headers: apiRequestHeaders + }) : helpers.fetchFeaturesCall({ + host: apiHost, + clientKey, + headers: apiRequestHeaders + }); + + // TODO: auto-retry if status code indicates a temporary error + promise = fetcher.then(res => { + if (!res.ok) { + throw new Error(`HTTP error: ${res.status}`); + } + if (res.headers.get("x-sse-support") === "enabled") { + supportsSSE.add(key); + } + return res.json(); + }).then(data => { + onNewFeatureData(key, cacheKey, data); + startAutoRefresh(instance); + activeFetches.delete(cacheKey); + return { + data, + success: true, + source: "network" + }; + }).catch(e => { + process.env.NODE_ENV !== "production" && instance.log("Error fetching features", { + apiHost, + clientKey, + error: e ? e.message : null + }); + activeFetches.delete(cacheKey); + return { + data: null, + source: "error", + success: false, + error: e + }; + }); + activeFetches.set(cacheKey, promise); + } + return promise; +} + +// Start SSE streaming, listens to feature payload changes and triggers a refresh or re-fetch +function startAutoRefresh(instance) { + let forceSSE = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + const key = getKey(instance); + const cacheKey = getCacheKey(instance); + const { + streamingHost, + streamingHostRequestHeaders + } = instance.getApiHosts(); + const clientKey = instance.getClientKey(); + if (forceSSE) { + supportsSSE.add(key); + } + if (cacheSettings.backgroundSync && supportsSSE.has(key) && polyfills.EventSource) { + if (streams.has(key)) return; + const channel = { + src: null, + host: streamingHost, + clientKey, + headers: streamingHostRequestHeaders, + cb: event => { + try { + if (event.type === "features-updated") { + const instances = subscribedInstances.get(key); + instances && instances.forEach(instance => { + fetchFeatures(instance); + }); + } else if (event.type === "features") { + const json = JSON.parse(event.data); + onNewFeatureData(key, cacheKey, json); + } + // Reset error count on success + channel.errors = 0; + } catch (e) { + process.env.NODE_ENV !== "production" && instance.log("SSE Error", { + streamingHost, + clientKey, + error: e ? e.message : null + }); + onSSEError(channel); + } + }, + errors: 0, + state: "active" + }; + streams.set(key, channel); + enableChannel(channel); + } +} +function onSSEError(channel) { + if (channel.state === "idle") return; + channel.errors++; + if (channel.errors > 3 || channel.src && channel.src.readyState === 2) { + // exponential backoff after 4 errors, with jitter + const delay = Math.pow(3, channel.errors - 3) * (1000 + Math.random() * 1000); + disableChannel(channel); + setTimeout(() => { + if (["idle", "active"].includes(channel.state)) return; + enableChannel(channel); + }, Math.min(delay, 300000)); // 5 minutes max + } +} + +function disableChannel(channel) { + if (!channel.src) return; + channel.src.onopen = null; + channel.src.onerror = null; + channel.src.close(); + channel.src = null; + if (channel.state === "active") { + channel.state = "disabled"; + } +} +function enableChannel(channel) { + channel.src = helpers.eventSourceCall({ + host: channel.host, + clientKey: channel.clientKey, + headers: channel.headers + }); + channel.state = "active"; + channel.src.addEventListener("features", channel.cb); + channel.src.addEventListener("features-updated", channel.cb); + channel.src.onerror = () => onSSEError(channel); + channel.src.onopen = () => { + channel.errors = 0; + }; +} +function destroyChannel(channel, key) { + disableChannel(channel); + streams.delete(key); +} +function clearAutoRefresh() { + // Clear list of which keys are auto-updated + supportsSSE.clear(); + + // Stop listening for any SSE events + streams.forEach(destroyChannel); + + // Remove all references to GrowthBook instances + subscribedInstances.clear(); + + // Run the idle stream cleanup function + helpers.stopIdleListener(); +} +export function startStreaming(instance, options) { + if (options.streaming) { + if (!instance.getClientKey()) { + throw new Error("Must specify clientKey to enable streaming"); + } + if (options.payload) { + startAutoRefresh(instance, true); + } + subscribe(instance); + } +} +//# sourceMappingURL=feature-repository.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/index.mjs b/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/index.mjs new file mode 100644 index 00000000..9344a239 --- /dev/null +++ b/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/index.mjs @@ -0,0 +1,8 @@ +export { setPolyfills, clearCache, configureCache, helpers, onVisible, onHidden } from "./feature-repository.mjs"; +export { GrowthBook, prefetchPayload } from "./GrowthBook.mjs"; +export { GrowthBookClient as GrowthBookMultiUser, GrowthBookClient, UserScopedGrowthBook } from "./GrowthBookClient.mjs"; +export { StickyBucketService, StickyBucketServiceSync, LocalStorageStickyBucketService, ExpressCookieStickyBucketService, BrowserCookieStickyBucketService, RedisStickyBucketService } from "./sticky-bucket-service.mjs"; +export { evalCondition } from "./mongrule.mjs"; +export { isURLTargeted, getPolyfills, getAutoExperimentChangeType, paddedVersionString } from "./util.mjs"; +export { EVENT_EXPERIMENT_VIEWED, EVENT_FEATURE_EVALUATED } from "./core.mjs"; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/mongrule.mjs b/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/mongrule.mjs new file mode 100644 index 00000000..d7a62b07 --- /dev/null +++ b/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/mongrule.mjs @@ -0,0 +1,214 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ + +import { paddedVersionString } from "./util.mjs"; +const _regexCache = {}; + +// The top-level condition evaluation function +export function evalCondition(obj, condition, +// Must be included for `condition` to correctly evaluate group Operators +savedGroups) { + savedGroups = savedGroups || {}; + // Condition is an object, keys are either specific operators or object paths + // values are either arguments for operators or conditions for paths + for (const [k, v] of Object.entries(condition)) { + switch (k) { + case "$or": + if (!evalOr(obj, v, savedGroups)) return false; + break; + case "$nor": + if (evalOr(obj, v, savedGroups)) return false; + break; + case "$and": + if (!evalAnd(obj, v, savedGroups)) return false; + break; + case "$not": + if (evalCondition(obj, v, savedGroups)) return false; + break; + default: + if (!evalConditionValue(v, getPath(obj, k), savedGroups)) return false; + } + } + return true; +} + +// Return value at dot-separated path of an object +function getPath(obj, path) { + const parts = path.split("."); + let current = obj; + for (let i = 0; i < parts.length; i++) { + if (current && typeof current === "object" && parts[i] in current) { + current = current[parts[i]]; + } else { + return null; + } + } + return current; +} + +// Transform a regex string into a real RegExp object +function getRegex(regex) { + if (!_regexCache[regex]) { + _regexCache[regex] = new RegExp(regex.replace(/([^\\])\//g, "$1\\/")); + } + return _regexCache[regex]; +} + +// Evaluate a single value against a condition +function evalConditionValue(condition, value, savedGroups) { + // Simple equality comparisons + if (typeof condition === "string") { + return value + "" === condition; + } + if (typeof condition === "number") { + return value * 1 === condition; + } + if (typeof condition === "boolean") { + return value !== null && !!value === condition; + } + if (condition === null) { + return value === null; + } + if (Array.isArray(condition) || !isOperatorObject(condition)) { + return JSON.stringify(value) === JSON.stringify(condition); + } + + // This is a special operator condition and we should evaluate each one separately + for (const op in condition) { + if (!evalOperatorCondition(op, value, condition[op], savedGroups)) { + return false; + } + } + return true; +} + +// If the object has only keys that start with '$' +function isOperatorObject(obj) { + const keys = Object.keys(obj); + return keys.length > 0 && keys.filter(k => k[0] === "$").length === keys.length; +} + +// Return the data type of a value +function getType(v) { + if (v === null) return "null"; + if (Array.isArray(v)) return "array"; + const t = typeof v; + if (["string", "number", "boolean", "object", "undefined"].includes(t)) { + return t; + } + return "unknown"; +} + +// At least one element of actual must match the expected condition/value +function elemMatch(actual, expected, savedGroups) { + if (!Array.isArray(actual)) return false; + const check = isOperatorObject(expected) ? v => evalConditionValue(expected, v, savedGroups) : v => evalCondition(v, expected, savedGroups); + for (let i = 0; i < actual.length; i++) { + if (actual[i] && check(actual[i])) { + return true; + } + } + return false; +} +function isIn(actual, expected) { + // Do an intersection if attribute is an array + if (Array.isArray(actual)) { + return actual.some(el => expected.includes(el)); + } + return expected.includes(actual); +} + +// Evaluate a single operator condition +function evalOperatorCondition(operator, actual, expected, savedGroups) { + switch (operator) { + case "$veq": + return paddedVersionString(actual) === paddedVersionString(expected); + case "$vne": + return paddedVersionString(actual) !== paddedVersionString(expected); + case "$vgt": + return paddedVersionString(actual) > paddedVersionString(expected); + case "$vgte": + return paddedVersionString(actual) >= paddedVersionString(expected); + case "$vlt": + return paddedVersionString(actual) < paddedVersionString(expected); + case "$vlte": + return paddedVersionString(actual) <= paddedVersionString(expected); + case "$eq": + return actual === expected; + case "$ne": + return actual !== expected; + case "$lt": + return actual < expected; + case "$lte": + return actual <= expected; + case "$gt": + return actual > expected; + case "$gte": + return actual >= expected; + case "$exists": + // Using `!=` and `==` instead of strict checks so it also matches for undefined + return expected ? actual != null : actual == null; + case "$in": + if (!Array.isArray(expected)) return false; + return isIn(actual, expected); + case "$inGroup": + return isIn(actual, savedGroups[expected] || []); + case "$notInGroup": + return !isIn(actual, savedGroups[expected] || []); + case "$nin": + if (!Array.isArray(expected)) return false; + return !isIn(actual, expected); + case "$not": + return !evalConditionValue(expected, actual, savedGroups); + case "$size": + if (!Array.isArray(actual)) return false; + return evalConditionValue(expected, actual.length, savedGroups); + case "$elemMatch": + return elemMatch(actual, expected, savedGroups); + case "$all": + if (!Array.isArray(actual)) return false; + for (let i = 0; i < expected.length; i++) { + let passed = false; + for (let j = 0; j < actual.length; j++) { + if (evalConditionValue(expected[i], actual[j], savedGroups)) { + passed = true; + break; + } + } + if (!passed) return false; + } + return true; + case "$regex": + try { + return getRegex(expected).test(actual); + } catch (e) { + return false; + } + case "$type": + return getType(actual) === expected; + default: + console.error("Unknown operator: " + operator); + return false; + } +} + +// Recursive $or rule +function evalOr(obj, conditions, savedGroups) { + if (!conditions.length) return true; + for (let i = 0; i < conditions.length; i++) { + if (evalCondition(obj, conditions[i], savedGroups)) { + return true; + } + } + return false; +} + +// Recursive $and rule +function evalAnd(obj, conditions, savedGroups) { + for (let i = 0; i < conditions.length; i++) { + if (!evalCondition(obj, conditions[i], savedGroups)) { + return false; + } + } + return true; +} +//# sourceMappingURL=mongrule.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/util.mjs b/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/util.mjs new file mode 100644 index 00000000..44dd9a6f --- /dev/null +++ b/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/util.mjs @@ -0,0 +1,312 @@ +const polyfills = { + fetch: globalThis.fetch ? globalThis.fetch.bind(globalThis) : undefined, + SubtleCrypto: globalThis.crypto ? globalThis.crypto.subtle : undefined, + EventSource: globalThis.EventSource +}; +export function getPolyfills() { + return polyfills; +} +function hashFnv32a(str) { + let hval = 0x811c9dc5; + const l = str.length; + for (let i = 0; i < l; i++) { + hval ^= str.charCodeAt(i); + hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24); + } + return hval >>> 0; +} +export function hash(seed, value, version) { + // New unbiased hashing algorithm + if (version === 2) { + return hashFnv32a(hashFnv32a(seed + value) + "") % 10000 / 10000; + } + // Original biased hashing algorithm (keep for backwards compatibility) + if (version === 1) { + return hashFnv32a(value + seed) % 1000 / 1000; + } + + // Unknown hash version + return null; +} +export function getEqualWeights(n) { + if (n <= 0) return []; + return new Array(n).fill(1 / n); +} +export function inRange(n, range) { + return n >= range[0] && n < range[1]; +} +export function inNamespace(hashValue, namespace) { + const n = hash("__" + namespace[0], hashValue, 1); + if (n === null) return false; + return n >= namespace[1] && n < namespace[2]; +} +export function chooseVariation(n, ranges) { + for (let i = 0; i < ranges.length; i++) { + if (inRange(n, ranges[i])) { + return i; + } + } + return -1; +} +export function getUrlRegExp(regexString) { + try { + const escaped = regexString.replace(/([^\\])\//g, "$1\\/"); + return new RegExp(escaped); + } catch (e) { + console.error(e); + return undefined; + } +} +export function isURLTargeted(url, targets) { + if (!targets.length) return false; + let hasIncludeRules = false; + let isIncluded = false; + for (let i = 0; i < targets.length; i++) { + const match = _evalURLTarget(url, targets[i].type, targets[i].pattern); + if (targets[i].include === false) { + if (match) return false; + } else { + hasIncludeRules = true; + if (match) isIncluded = true; + } + } + return isIncluded || !hasIncludeRules; +} +function _evalSimpleUrlPart(actual, pattern, isPath) { + try { + // Escape special regex characters and change wildcard `_____` to `.*` + let escaped = pattern.replace(/[*.+?^${}()|[\]\\]/g, "\\$&").replace(/_____/g, ".*"); + if (isPath) { + // When matching pathname, make leading/trailing slashes optional + escaped = "\\/?" + escaped.replace(/(^\/|\/$)/g, "") + "\\/?"; + } + const regex = new RegExp("^" + escaped + "$", "i"); + return regex.test(actual); + } catch (e) { + return false; + } +} +function _evalSimpleUrlTarget(actual, pattern) { + try { + // If a protocol is missing, but a host is specified, add `https://` to the front + // Use "_____" as the wildcard since `*` is not a valid hostname in some browsers + const expected = new URL(pattern.replace(/^([^:/?]*)\./i, "https://$1.").replace(/\*/g, "_____"), "https://_____"); + + // Compare each part of the URL separately + const comps = [[actual.host, expected.host, false], [actual.pathname, expected.pathname, true]]; + // We only want to compare hashes if it's explicitly being targeted + if (expected.hash) { + comps.push([actual.hash, expected.hash, false]); + } + expected.searchParams.forEach((v, k) => { + comps.push([actual.searchParams.get(k) || "", v, false]); + }); + + // If any comparisons fail, the whole thing fails + return !comps.some(data => !_evalSimpleUrlPart(data[0], data[1], data[2])); + } catch (e) { + return false; + } +} +function _evalURLTarget(url, type, pattern) { + try { + const parsed = new URL(url, "https://_"); + if (type === "regex") { + const regex = getUrlRegExp(pattern); + if (!regex) return false; + return regex.test(parsed.href) || regex.test(parsed.href.substring(parsed.origin.length)); + } else if (type === "simple") { + return _evalSimpleUrlTarget(parsed, pattern); + } + return false; + } catch (e) { + return false; + } +} +export function getBucketRanges(numVariations, coverage, weights) { + coverage = coverage === undefined ? 1 : coverage; + + // Make sure coverage is within bounds + if (coverage < 0) { + if (process.env.NODE_ENV !== "production") { + console.error("Experiment.coverage must be greater than or equal to 0"); + } + coverage = 0; + } else if (coverage > 1) { + if (process.env.NODE_ENV !== "production") { + console.error("Experiment.coverage must be less than or equal to 1"); + } + coverage = 1; + } + + // Default to equal weights if missing or invalid + const equal = getEqualWeights(numVariations); + weights = weights || equal; + if (weights.length !== numVariations) { + if (process.env.NODE_ENV !== "production") { + console.error("Experiment.weights array must be the same length as Experiment.variations"); + } + weights = equal; + } + + // If weights don't add up to 1 (or close to it), default to equal weights + const totalWeight = weights.reduce((w, sum) => sum + w, 0); + if (totalWeight < 0.99 || totalWeight > 1.01) { + if (process.env.NODE_ENV !== "production") { + console.error("Experiment.weights must add up to 1"); + } + weights = equal; + } + + // Covert weights to ranges + let cumulative = 0; + return weights.map(w => { + const start = cumulative; + cumulative += w; + return [start, start + coverage * w]; + }); +} +export function getQueryStringOverride(id, url, numVariations) { + if (!url) { + return null; + } + const search = url.split("?")[1]; + if (!search) { + return null; + } + const match = search.replace(/#.*/, "") // Get rid of anchor + .split("&") // Split into key/value pairs + .map(kv => kv.split("=", 2)).filter(_ref => { + let [k] = _ref; + return k === id; + }) // Look for key that matches the experiment id + .map(_ref2 => { + let [, v] = _ref2; + return parseInt(v); + }); // Parse the value into an integer + + if (match.length > 0 && match[0] >= 0 && match[0] < numVariations) return match[0]; + return null; +} +export function isIncluded(include) { + try { + return include(); + } catch (e) { + console.error(e); + return false; + } +} +const base64ToBuf = b => Uint8Array.from(atob(b), c => c.charCodeAt(0)); +export async function decrypt(encryptedString, decryptionKey, subtle) { + decryptionKey = decryptionKey || ""; + subtle = subtle || globalThis.crypto && globalThis.crypto.subtle || polyfills.SubtleCrypto; + if (!subtle) { + throw new Error("No SubtleCrypto implementation found"); + } + try { + const key = await subtle.importKey("raw", base64ToBuf(decryptionKey), { + name: "AES-CBC", + length: 128 + }, true, ["encrypt", "decrypt"]); + const [iv, cipherText] = encryptedString.split("."); + const plainTextBuffer = await subtle.decrypt({ + name: "AES-CBC", + iv: base64ToBuf(iv) + }, key, base64ToBuf(cipherText)); + return new TextDecoder().decode(plainTextBuffer); + } catch (e) { + throw new Error("Failed to decrypt"); + } +} + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export function toString(input) { + if (typeof input === "string") return input; + return JSON.stringify(input); +} + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export function paddedVersionString(input) { + if (typeof input === "number") { + input = input + ""; + } + if (!input || typeof input !== "string") { + input = "0"; + } + // Remove build info and leading `v` if any + // Split version into parts (both core version numbers and pre-release tags) + // "v1.2.3-rc.1+build123" -> ["1","2","3","rc","1"] + const parts = input.replace(/(^v|\+.*$)/g, "").split(/[-.]/); + + // If it's SemVer without a pre-release, add `~` to the end + // ["1","0","0"] -> ["1","0","0","~"] + // "~" is the largest ASCII character, so this will make "1.0.0" greater than "1.0.0-beta" for example + if (parts.length === 3) { + parts.push("~"); + } + + // Left pad each numeric part with spaces so string comparisons will work ("9">"10", but " 9"<"10") + // Then, join back together into a single string + return parts.map(v => v.match(/^[0-9]+$/) ? v.padStart(5, " ") : v).join("-"); +} +export function loadSDKVersion() { + let version; + try { + // @ts-expect-error right-hand value to be replaced by build with string literal + version = "1.6.1"; + } catch (e) { + version = ""; + } + return version; +} +export function mergeQueryStrings(oldUrl, newUrl) { + let currUrl; + let redirectUrl; + try { + currUrl = new URL(oldUrl); + redirectUrl = new URL(newUrl); + } catch (e) { + console.error(`Unable to merge query strings: ${e}`); + return newUrl; + } + currUrl.searchParams.forEach((value, key) => { + // skip if search param already exists in redirectUrl + if (redirectUrl.searchParams.has(key)) { + return; + } + redirectUrl.searchParams.set(key, value); + }); + return redirectUrl.toString(); +} +function isObj(x) { + return typeof x === "object" && x !== null; +} +export function getAutoExperimentChangeType(exp) { + if (exp.urlPatterns && exp.variations.some(variation => isObj(variation) && "urlRedirect" in variation)) { + return "redirect"; + } else if (exp.variations.some(variation => isObj(variation) && (variation.domMutations || "js" in variation || "css" in variation))) { + return "visual"; + } + return "unknown"; +} + +// Guarantee the promise always resolves within {timeout} ms +// Resolved value will be `null` when there's an error or it takes too long +// Note: The promise will continue running in the background, even if the timeout is hit +export async function promiseTimeout(promise, timeout) { + return new Promise(resolve => { + let resolved = false; + let timer; + const finish = data => { + if (resolved) return; + resolved = true; + timer && clearTimeout(timer); + resolve(data || null); + }; + if (timeout) { + timer = setTimeout(() => finish(), timeout); + } + promise.then(data => finish(data)).catch(() => finish()); + }); +} +//# sourceMappingURL=util.mjs.map diff --git a/claude-code-source/node_modules/@inquirer/confirm/dist/esm/index.mjs b/claude-code-source/node_modules/@inquirer/confirm/dist/esm/index.mjs new file mode 100644 index 00000000..ec2dcf79 --- /dev/null +++ b/claude-code-source/node_modules/@inquirer/confirm/dist/esm/index.mjs @@ -0,0 +1,33 @@ +import { createPrompt, useState, useKeypress, isEnterKey, usePrefix, makeTheme, } from '@inquirer/core'; +export default createPrompt((config, done) => { + const { transformer = (answer) => (answer ? 'yes' : 'no') } = config; + const [status, setStatus] = useState('idle'); + const [value, setValue] = useState(''); + const theme = makeTheme(config.theme); + const prefix = usePrefix({ status, theme }); + useKeypress((key, rl) => { + if (isEnterKey(key)) { + let answer = config.default !== false; + if (/^(y|yes)/i.test(value)) + answer = true; + else if (/^(n|no)/i.test(value)) + answer = false; + setValue(transformer(answer)); + setStatus('done'); + done(answer); + } + else { + setValue(rl.line); + } + }); + let formattedValue = value; + let defaultValue = ''; + if (status === 'done') { + formattedValue = theme.style.answer(value); + } + else { + defaultValue = ` ${theme.style.defaultAnswer(config.default === false ? 'y/N' : 'Y/n')}`; + } + const message = theme.style.message(config.message, status); + return `${prefix} ${message}${defaultValue} ${formattedValue}`; +}); diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/index.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/index.mjs new file mode 100644 index 00000000..772ef6c0 --- /dev/null +++ b/claude-code-source/node_modules/@inquirer/core/dist/esm/index.mjs @@ -0,0 +1,12 @@ +export * from './lib/key.mjs'; +export * from './lib/errors.mjs'; +export { usePrefix } from './lib/use-prefix.mjs'; +export { useState } from './lib/use-state.mjs'; +export { useEffect } from './lib/use-effect.mjs'; +export { useMemo } from './lib/use-memo.mjs'; +export { useRef } from './lib/use-ref.mjs'; +export { useKeypress } from './lib/use-keypress.mjs'; +export { makeTheme } from './lib/make-theme.mjs'; +export { usePagination } from './lib/pagination/use-pagination.mjs'; +export { createPrompt } from './lib/create-prompt.mjs'; +export { Separator } from './lib/Separator.mjs'; diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/Separator.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/Separator.mjs new file mode 100644 index 00000000..f0d8409a --- /dev/null +++ b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/Separator.mjs @@ -0,0 +1,21 @@ +import colors from 'yoctocolors-cjs'; +import figures from '@inquirer/figures'; +/** + * Separator object + * Used to space/separate choices group + */ +export class Separator { + separator = colors.dim(Array.from({ length: 15 }).join(figures.line)); + type = 'separator'; + constructor(separator) { + if (separator) { + this.separator = separator; + } + } + static isSeparator(choice) { + return Boolean(choice && + typeof choice === 'object' && + 'type' in choice && + choice.type === 'separator'); + } +} diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/create-prompt.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/create-prompt.mjs new file mode 100644 index 00000000..379e2dd6 --- /dev/null +++ b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/create-prompt.mjs @@ -0,0 +1,84 @@ +import * as readline from 'node:readline'; +import { AsyncResource } from 'node:async_hooks'; +import MuteStream from 'mute-stream'; +import { onExit as onSignalExit } from 'signal-exit'; +import ScreenManager from './screen-manager.mjs'; +import { PromisePolyfill } from './promise-polyfill.mjs'; +import { withHooks, effectScheduler } from './hook-engine.mjs'; +import { AbortPromptError, CancelPromptError, ExitPromptError } from './errors.mjs'; +export function createPrompt(view) { + const prompt = (config, context = {}) => { + // Default `input` to stdin + const { input = process.stdin, signal } = context; + const cleanups = new Set(); + // Add mute capabilities to the output + const output = new MuteStream(); + output.pipe(context.output ?? process.stdout); + const rl = readline.createInterface({ + terminal: true, + input, + output, + }); + const screen = new ScreenManager(rl); + const { promise, resolve, reject } = PromisePolyfill.withResolver(); + /** @deprecated pass an AbortSignal in the context options instead. See {@link https://github.com/SBoudrias/Inquirer.js#canceling-prompt} */ + const cancel = () => reject(new CancelPromptError()); + if (signal) { + const abort = () => reject(new AbortPromptError({ cause: signal.reason })); + if (signal.aborted) { + abort(); + return Object.assign(promise, { cancel }); + } + signal.addEventListener('abort', abort); + cleanups.add(() => signal.removeEventListener('abort', abort)); + } + cleanups.add(onSignalExit((code, signal) => { + reject(new ExitPromptError(`User force closed the prompt with ${code} ${signal}`)); + })); + // Re-renders only happen when the state change; but the readline cursor could change position + // and that also requires a re-render (and a manual one because we mute the streams). + // We set the listener after the initial workLoop to avoid a double render if render triggered + // by a state change sets the cursor to the right position. + const checkCursorPos = () => screen.checkCursorPos(); + rl.input.on('keypress', checkCursorPos); + cleanups.add(() => rl.input.removeListener('keypress', checkCursorPos)); + return withHooks(rl, (cycle) => { + // The close event triggers immediately when the user press ctrl+c. SignalExit on the other hand + // triggers after the process is done (which happens after timeouts are done triggering.) + // We triggers the hooks cleanup phase on rl `close` so active timeouts can be cleared. + const hooksCleanup = AsyncResource.bind(() => effectScheduler.clearAll()); + rl.on('close', hooksCleanup); + cleanups.add(() => rl.removeListener('close', hooksCleanup)); + cycle(() => { + try { + const nextView = view(config, (value) => { + setImmediate(() => resolve(value)); + }); + const [content, bottomContent] = typeof nextView === 'string' ? [nextView] : nextView; + screen.render(content, bottomContent); + effectScheduler.run(); + } + catch (error) { + reject(error); + } + }); + return Object.assign(promise + .then((answer) => { + effectScheduler.clearAll(); + return answer; + }, (error) => { + effectScheduler.clearAll(); + throw error; + }) + // Wait for the promise to settle, then cleanup. + .finally(() => { + cleanups.forEach((cleanup) => cleanup()); + screen.done({ clearContent: Boolean(context?.clearPromptOnDone) }); + output.end(); + }) + // Once cleanup is done, let the expose promise resolve/reject to the internal one. + .then(() => promise), { cancel }); + }); + }; + return prompt; +} diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/errors.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/errors.mjs new file mode 100644 index 00000000..153a9363 --- /dev/null +++ b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/errors.mjs @@ -0,0 +1,21 @@ +export class AbortPromptError extends Error { + name = 'AbortPromptError'; + message = 'Prompt was aborted'; + constructor(options) { + super(); + this.cause = options?.cause; + } +} +export class CancelPromptError extends Error { + name = 'CancelPromptError'; + message = 'Prompt was canceled'; +} +export class ExitPromptError extends Error { + name = 'ExitPromptError'; +} +export class HookError extends Error { + name = 'HookError'; +} +export class ValidationError extends Error { + name = 'ValidationError'; +} diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/hook-engine.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/hook-engine.mjs new file mode 100644 index 00000000..b2712e0a --- /dev/null +++ b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/hook-engine.mjs @@ -0,0 +1,110 @@ +/* eslint @typescript-eslint/no-explicit-any: ["off"] */ +import { AsyncLocalStorage, AsyncResource } from 'node:async_hooks'; +import { HookError, ValidationError } from './errors.mjs'; +const hookStorage = new AsyncLocalStorage(); +function createStore(rl) { + const store = { + rl, + hooks: [], + hooksCleanup: [], + hooksEffect: [], + index: 0, + handleChange() { }, + }; + return store; +} +// Run callback in with the hook engine setup. +export function withHooks(rl, cb) { + const store = createStore(rl); + return hookStorage.run(store, () => { + function cycle(render) { + store.handleChange = () => { + store.index = 0; + render(); + }; + store.handleChange(); + } + return cb(cycle); + }); +} +// Safe getStore utility that'll return the store or throw if undefined. +function getStore() { + const store = hookStorage.getStore(); + if (!store) { + throw new HookError('[Inquirer] Hook functions can only be called from within a prompt'); + } + return store; +} +export function readline() { + return getStore().rl; +} +// Merge state updates happening within the callback function to avoid multiple renders. +export function withUpdates(fn) { + const wrapped = (...args) => { + const store = getStore(); + let shouldUpdate = false; + const oldHandleChange = store.handleChange; + store.handleChange = () => { + shouldUpdate = true; + }; + const returnValue = fn(...args); + if (shouldUpdate) { + oldHandleChange(); + } + store.handleChange = oldHandleChange; + return returnValue; + }; + return AsyncResource.bind(wrapped); +} +export function withPointer(cb) { + const store = getStore(); + const { index } = store; + const pointer = { + get() { + return store.hooks[index]; + }, + set(value) { + store.hooks[index] = value; + }, + initialized: index in store.hooks, + }; + const returnValue = cb(pointer); + store.index++; + return returnValue; +} +export function handleChange() { + getStore().handleChange(); +} +export const effectScheduler = { + queue(cb) { + const store = getStore(); + const { index } = store; + store.hooksEffect.push(() => { + store.hooksCleanup[index]?.(); + const cleanFn = cb(readline()); + if (cleanFn != null && typeof cleanFn !== 'function') { + throw new ValidationError('useEffect return value must be a cleanup function or nothing.'); + } + store.hooksCleanup[index] = cleanFn; + }); + }, + run() { + const store = getStore(); + withUpdates(() => { + store.hooksEffect.forEach((effect) => { + effect(); + }); + // Warning: Clean the hooks before exiting the `withUpdates` block. + // Failure to do so means an updates would hit the same effects again. + store.hooksEffect.length = 0; + })(); + }, + clearAll() { + const store = getStore(); + store.hooksCleanup.forEach((cleanFn) => { + cleanFn?.(); + }); + store.hooksEffect.length = 0; + store.hooksCleanup.length = 0; + }, +}; diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/key.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/key.mjs new file mode 100644 index 00000000..a6f25125 --- /dev/null +++ b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/key.mjs @@ -0,0 +1,18 @@ +export const isUpKey = (key) => +// The up key +key.name === 'up' || + // Vim keybinding + key.name === 'k' || + // Emacs keybinding + (key.ctrl && key.name === 'p'); +export const isDownKey = (key) => +// The down key +key.name === 'down' || + // Vim keybinding + key.name === 'j' || + // Emacs keybinding + (key.ctrl && key.name === 'n'); +export const isSpaceKey = (key) => key.name === 'space'; +export const isBackspaceKey = (key) => key.name === 'backspace'; +export const isNumberKey = (key) => '123456789'.includes(key.name); +export const isEnterKey = (key) => key.name === 'enter' || key.name === 'return'; diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/make-theme.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/make-theme.mjs new file mode 100644 index 00000000..504da44e --- /dev/null +++ b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/make-theme.mjs @@ -0,0 +1,30 @@ +import { defaultTheme } from './theme.mjs'; +function isPlainObject(value) { + if (typeof value !== 'object' || value === null) + return false; + let proto = value; + while (Object.getPrototypeOf(proto) !== null) { + proto = Object.getPrototypeOf(proto); + } + return Object.getPrototypeOf(value) === proto; +} +function deepMerge(...objects) { + const output = {}; + for (const obj of objects) { + for (const [key, value] of Object.entries(obj)) { + const prevValue = output[key]; + output[key] = + isPlainObject(prevValue) && isPlainObject(value) + ? deepMerge(prevValue, value) + : value; + } + } + return output; +} +export function makeTheme(...themes) { + const themesToMerge = [ + defaultTheme, + ...themes.filter((theme) => theme != null), + ]; + return deepMerge(...themesToMerge); +} diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/pagination/lines.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/pagination/lines.mjs new file mode 100644 index 00000000..2969033c --- /dev/null +++ b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/pagination/lines.mjs @@ -0,0 +1,59 @@ +import { breakLines } from '../utils.mjs'; +function split(content, width) { + return breakLines(content, width).split('\n'); +} +/** + * Rotates an array of items by an integer number of positions. + * @param {number} count The number of positions to rotate by + * @param {T[]} items The items to rotate + */ +function rotate(count, items) { + const max = items.length; + const offset = ((count % max) + max) % max; + return [...items.slice(offset), ...items.slice(0, offset)]; +} +/** + * Renders a page of items as lines that fit within the given width ensuring + * that the number of lines is not greater than the page size, and the active + * item renders at the provided position, while prioritizing that as many lines + * of the active item get rendered as possible. + */ +export function lines({ items, width, renderItem, active, position: requested, pageSize, }) { + const layouts = items.map((item, index) => ({ + item, + index, + isActive: index === active, + })); + const layoutsInPage = rotate(active - requested, layouts).slice(0, pageSize); + const renderItemAt = (index) => layoutsInPage[index] == null ? [] : split(renderItem(layoutsInPage[index]), width); + // Create a blank array of lines for the page + const pageBuffer = Array.from({ length: pageSize }); + // Render the active item to decide the position + const activeItem = renderItemAt(requested).slice(0, pageSize); + const position = requested + activeItem.length <= pageSize ? requested : pageSize - activeItem.length; + // Add the lines of the active item into the page + pageBuffer.splice(position, activeItem.length, ...activeItem); + // Fill the page under the active item + let bufferPointer = position + activeItem.length; + let layoutPointer = requested + 1; + while (bufferPointer < pageSize && layoutPointer < layoutsInPage.length) { + for (const line of renderItemAt(layoutPointer)) { + pageBuffer[bufferPointer++] = line; + if (bufferPointer >= pageSize) + break; + } + layoutPointer++; + } + // Fill the page over the active item + bufferPointer = position - 1; + layoutPointer = requested - 1; + while (bufferPointer >= 0 && layoutPointer >= 0) { + for (const line of renderItemAt(layoutPointer).reverse()) { + pageBuffer[bufferPointer--] = line; + if (bufferPointer < 0) + break; + } + layoutPointer--; + } + return pageBuffer.filter((line) => typeof line === 'string'); +} diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/pagination/position.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/pagination/position.mjs new file mode 100644 index 00000000..9e3cc2eb --- /dev/null +++ b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/pagination/position.mjs @@ -0,0 +1,27 @@ +/** + * Creates the next position for the active item considering a finite list of + * items to be rendered on a page. + */ +export function finite({ active, pageSize, total, }) { + const middle = Math.floor(pageSize / 2); + if (total <= pageSize || active < middle) + return active; + if (active >= total - middle) + return active + pageSize - total; + return middle; +} +/** + * Creates the next position for the active item considering an infinitely + * looping list of items to be rendered on the page. + */ +export function infinite({ active, lastActive, total, pageSize, pointer, }) { + if (total <= pageSize) + return active; + // Move the position only when the user moves down, and when the + // navigation fits within a single page + if (lastActive < active && active - lastActive < pageSize) { + // Limit it to the middle of the list + return Math.min(Math.floor(pageSize / 2), pointer + active - lastActive); + } + return pointer; +} diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/pagination/use-pagination.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/pagination/use-pagination.mjs new file mode 100644 index 00000000..b8459233 --- /dev/null +++ b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/pagination/use-pagination.mjs @@ -0,0 +1,30 @@ +import { useRef } from '../use-ref.mjs'; +import { readlineWidth } from '../utils.mjs'; +import { lines } from './lines.mjs'; +import { finite, infinite } from './position.mjs'; +export function usePagination({ items, active, renderItem, pageSize, loop = true, }) { + const state = useRef({ position: 0, lastActive: 0 }); + const position = loop + ? infinite({ + active, + lastActive: state.current.lastActive, + total: items.length, + pageSize, + pointer: state.current.position, + }) + : finite({ + active, + total: items.length, + pageSize, + }); + state.current.position = position; + state.current.lastActive = active; + return lines({ + items, + width: readlineWidth(), + renderItem, + active, + position, + pageSize, + }).join('\n'); +} diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/promise-polyfill.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/promise-polyfill.mjs new file mode 100644 index 00000000..621708ee --- /dev/null +++ b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/promise-polyfill.mjs @@ -0,0 +1,14 @@ +// TODO: Remove this class once Node 22 becomes the minimum supported version. +export class PromisePolyfill extends Promise { + // Available starting from Node 22 + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/withResolvers + static withResolver() { + let resolve; + let reject; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve: resolve, reject: reject }; + } +} diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/screen-manager.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/screen-manager.mjs new file mode 100644 index 00000000..40ac8f55 --- /dev/null +++ b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/screen-manager.mjs @@ -0,0 +1,85 @@ +import stripAnsi from 'strip-ansi'; +import ansiEscapes from 'ansi-escapes'; +import { breakLines, readlineWidth } from './utils.mjs'; +const height = (content) => content.split('\n').length; +const lastLine = (content) => content.split('\n').pop() ?? ''; +function cursorDown(n) { + return n > 0 ? ansiEscapes.cursorDown(n) : ''; +} +export default class ScreenManager { + rl; + // These variables are keeping information to allow correct prompt re-rendering + height = 0; + extraLinesUnderPrompt = 0; + cursorPos; + constructor(rl) { + this.rl = rl; + this.rl = rl; + this.cursorPos = rl.getCursorPos(); + } + write(content) { + this.rl.output.unmute(); + this.rl.output.write(content); + this.rl.output.mute(); + } + render(content, bottomContent = '') { + // Write message to screen and setPrompt to control backspace + const promptLine = lastLine(content); + const rawPromptLine = stripAnsi(promptLine); + // Remove the rl.line from our prompt. We can't rely on the content of + // rl.line (mainly because of the password prompt), so just rely on it's + // length. + let prompt = rawPromptLine; + if (this.rl.line.length > 0) { + prompt = prompt.slice(0, -this.rl.line.length); + } + this.rl.setPrompt(prompt); + // SetPrompt will change cursor position, now we can get correct value + this.cursorPos = this.rl.getCursorPos(); + const width = readlineWidth(); + content = breakLines(content, width); + bottomContent = breakLines(bottomContent, width); + // Manually insert an extra line if we're at the end of the line. + // This prevent the cursor from appearing at the beginning of the + // current line. + if (rawPromptLine.length % width === 0) { + content += '\n'; + } + let output = content + (bottomContent ? '\n' + bottomContent : ''); + /** + * Re-adjust the cursor at the correct position. + */ + // We need to consider parts of the prompt under the cursor as part of the bottom + // content in order to correctly cleanup and re-render. + const promptLineUpDiff = Math.floor(rawPromptLine.length / width) - this.cursorPos.rows; + const bottomContentHeight = promptLineUpDiff + (bottomContent ? height(bottomContent) : 0); + // Return cursor to the input position (on top of the bottomContent) + if (bottomContentHeight > 0) + output += ansiEscapes.cursorUp(bottomContentHeight); + // Return cursor to the initial left offset. + output += ansiEscapes.cursorTo(this.cursorPos.cols); + /** + * Render and store state for future re-rendering + */ + this.write(cursorDown(this.extraLinesUnderPrompt) + + ansiEscapes.eraseLines(this.height) + + output); + this.extraLinesUnderPrompt = bottomContentHeight; + this.height = height(output); + } + checkCursorPos() { + const cursorPos = this.rl.getCursorPos(); + if (cursorPos.cols !== this.cursorPos.cols) { + this.write(ansiEscapes.cursorTo(cursorPos.cols)); + this.cursorPos = cursorPos; + } + } + done({ clearContent }) { + this.rl.setPrompt(''); + let output = cursorDown(this.extraLinesUnderPrompt); + output += clearContent ? ansiEscapes.eraseLines(this.height) : '\n'; + output += ansiEscapes.cursorShow; + this.write(output); + this.rl.close(); + } +} diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/theme.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/theme.mjs new file mode 100644 index 00000000..d52a2da8 --- /dev/null +++ b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/theme.mjs @@ -0,0 +1,22 @@ +import colors from 'yoctocolors-cjs'; +import figures from '@inquirer/figures'; +export const defaultTheme = { + prefix: { + idle: colors.blue('?'), + // TODO: use figure + done: colors.green(figures.tick), + }, + spinner: { + interval: 80, + frames: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'].map((frame) => colors.yellow(frame)), + }, + style: { + answer: colors.cyan, + message: colors.bold, + error: (text) => colors.red(`> ${text}`), + defaultAnswer: (text) => colors.dim(`(${text})`), + help: colors.dim, + highlight: colors.cyan, + key: (text) => colors.cyan(colors.bold(`<${text}>`)), + }, +}; diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-effect.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-effect.mjs new file mode 100644 index 00000000..8c30102e --- /dev/null +++ b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-effect.mjs @@ -0,0 +1,11 @@ +import { withPointer, effectScheduler } from './hook-engine.mjs'; +export function useEffect(cb, depArray) { + withPointer((pointer) => { + const oldDeps = pointer.get(); + const hasChanged = !Array.isArray(oldDeps) || depArray.some((dep, i) => !Object.is(dep, oldDeps[i])); + if (hasChanged) { + effectScheduler.queue(cb); + } + pointer.set(depArray); + }); +} diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-keypress.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-keypress.mjs new file mode 100644 index 00000000..2649502f --- /dev/null +++ b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-keypress.mjs @@ -0,0 +1,20 @@ +import { useRef } from './use-ref.mjs'; +import { useEffect } from './use-effect.mjs'; +import { withUpdates } from './hook-engine.mjs'; +export function useKeypress(userHandler) { + const signal = useRef(userHandler); + signal.current = userHandler; + useEffect((rl) => { + let ignore = false; + const handler = withUpdates((_input, event) => { + if (ignore) + return; + void signal.current(event, rl); + }); + rl.input.on('keypress', handler); + return () => { + ignore = true; + rl.input.removeListener('keypress', handler); + }; + }, []); +} diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-memo.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-memo.mjs new file mode 100644 index 00000000..a6558e82 --- /dev/null +++ b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-memo.mjs @@ -0,0 +1,14 @@ +import { withPointer } from './hook-engine.mjs'; +export function useMemo(fn, dependencies) { + return withPointer((pointer) => { + const prev = pointer.get(); + if (!prev || + prev.dependencies.length !== dependencies.length || + prev.dependencies.some((dep, i) => dep !== dependencies[i])) { + const value = fn(); + pointer.set({ value, dependencies }); + return value; + } + return prev.value; + }); +} diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-prefix.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-prefix.mjs new file mode 100644 index 00000000..c849f395 --- /dev/null +++ b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-prefix.mjs @@ -0,0 +1,36 @@ +import { AsyncResource } from 'node:async_hooks'; +import { useState } from './use-state.mjs'; +import { useEffect } from './use-effect.mjs'; +import { makeTheme } from './make-theme.mjs'; +export function usePrefix({ status = 'idle', theme, }) { + const [showLoader, setShowLoader] = useState(false); + const [tick, setTick] = useState(0); + const { prefix, spinner } = makeTheme(theme); + useEffect(() => { + if (status === 'loading') { + let tickInterval; + let inc = -1; + // Delay displaying spinner by 300ms, to avoid flickering + const delayTimeout = setTimeout(AsyncResource.bind(() => { + setShowLoader(true); + tickInterval = setInterval(AsyncResource.bind(() => { + inc = inc + 1; + setTick(inc % spinner.frames.length); + }), spinner.interval); + }), 300); + return () => { + clearTimeout(delayTimeout); + clearInterval(tickInterval); + }; + } + else { + setShowLoader(false); + } + }, [status]); + if (showLoader) { + return spinner.frames[tick]; + } + // There's a delay before we show the loader. So we want to ignore `loading` here, and pass idle instead. + const iconName = status === 'loading' ? 'idle' : status; + return typeof prefix === 'string' ? prefix : prefix[iconName]; +} diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-ref.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-ref.mjs new file mode 100644 index 00000000..69ecc68c --- /dev/null +++ b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-ref.mjs @@ -0,0 +1,4 @@ +import { useState } from './use-state.mjs'; +export function useRef(val) { + return useState({ current: val })[0]; +} diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-state.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-state.mjs new file mode 100644 index 00000000..3629bf09 --- /dev/null +++ b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-state.mjs @@ -0,0 +1,19 @@ +import { withPointer, handleChange } from './hook-engine.mjs'; +export function useState(defaultValue) { + return withPointer((pointer) => { + const setFn = (newValue) => { + // Noop if the value is still the same. + if (pointer.get() !== newValue) { + pointer.set(newValue); + // Trigger re-render + handleChange(); + } + }; + if (pointer.initialized) { + return [pointer.get(), setFn]; + } + const value = typeof defaultValue === 'function' ? defaultValue() : defaultValue; + pointer.set(value); + return [value, setFn]; + }); +} diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/utils.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/utils.mjs new file mode 100644 index 00000000..1e7ae89d --- /dev/null +++ b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/utils.mjs @@ -0,0 +1,25 @@ +import cliWidth from 'cli-width'; +import wrapAnsi from 'wrap-ansi'; +import { readline } from './hook-engine.mjs'; +/** + * Force line returns at specific width. This function is ANSI code friendly and it'll + * ignore invisible codes during width calculation. + * @param {string} content + * @param {number} width + * @return {string} + */ +export function breakLines(content, width) { + return content + .split('\n') + .flatMap((line) => wrapAnsi(line, width, { trim: false, hard: true }) + .split('\n') + .map((str) => str.trimEnd())) + .join('\n'); +} +/** + * Returns the width of the active readline, or 80 as default value. + * @returns {number} + */ +export function readlineWidth() { + return cliWidth({ defaultWidth: 80, output: readline().output }); +} diff --git a/claude-code-source/node_modules/@inquirer/figures/dist/esm/index.js b/claude-code-source/node_modules/@inquirer/figures/dist/esm/index.js new file mode 100644 index 00000000..d43b15e6 --- /dev/null +++ b/claude-code-source/node_modules/@inquirer/figures/dist/esm/index.js @@ -0,0 +1,309 @@ +// process.env dot-notation access prints: +// Property 'TERM' comes from an index signature, so it must be accessed with ['TERM'].ts(4111) +/* eslint dot-notation: ["off"] */ +import process from 'node:process'; +// Ported from is-unicode-supported +function isUnicodeSupported() { + if (process.platform !== 'win32') { + return process.env['TERM'] !== 'linux'; // Linux console (kernel) + } + return (Boolean(process.env['WT_SESSION']) || // Windows Terminal + Boolean(process.env['TERMINUS_SUBLIME']) || // Terminus (<0.2.27) + process.env['ConEmuTask'] === '{cmd::Cmder}' || // ConEmu and cmder + process.env['TERM_PROGRAM'] === 'Terminus-Sublime' || + process.env['TERM_PROGRAM'] === 'vscode' || + process.env['TERM'] === 'xterm-256color' || + process.env['TERM'] === 'alacritty' || + process.env['TERMINAL_EMULATOR'] === 'JetBrains-JediTerm'); +} +// Ported from figures +const common = { + circleQuestionMark: '(?)', + questionMarkPrefix: '(?)', + square: '█', + squareDarkShade: '▓', + squareMediumShade: '▒', + squareLightShade: '░', + squareTop: '▀', + squareBottom: '▄', + squareLeft: '▌', + squareRight: '▐', + squareCenter: '■', + bullet: '●', + dot: '․', + ellipsis: '…', + pointerSmall: '›', + triangleUp: '▲', + triangleUpSmall: '▴', + triangleDown: '▼', + triangleDownSmall: '▾', + triangleLeftSmall: '◂', + triangleRightSmall: '▸', + home: '⌂', + heart: '♥', + musicNote: '♪', + musicNoteBeamed: '♫', + arrowUp: '↑', + arrowDown: '↓', + arrowLeft: '←', + arrowRight: '→', + arrowLeftRight: '↔', + arrowUpDown: '↕', + almostEqual: '≈', + notEqual: '≠', + lessOrEqual: '≤', + greaterOrEqual: '≥', + identical: '≡', + infinity: '∞', + subscriptZero: '₀', + subscriptOne: '₁', + subscriptTwo: '₂', + subscriptThree: '₃', + subscriptFour: '₄', + subscriptFive: '₅', + subscriptSix: '₆', + subscriptSeven: '₇', + subscriptEight: '₈', + subscriptNine: '₉', + oneHalf: '½', + oneThird: '⅓', + oneQuarter: '¼', + oneFifth: '⅕', + oneSixth: '⅙', + oneEighth: '⅛', + twoThirds: '⅔', + twoFifths: '⅖', + threeQuarters: '¾', + threeFifths: '⅗', + threeEighths: '⅜', + fourFifths: '⅘', + fiveSixths: '⅚', + fiveEighths: '⅝', + sevenEighths: '⅞', + line: '─', + lineBold: '━', + lineDouble: '═', + lineDashed0: '┄', + lineDashed1: '┅', + lineDashed2: '┈', + lineDashed3: '┉', + lineDashed4: '╌', + lineDashed5: '╍', + lineDashed6: '╴', + lineDashed7: '╶', + lineDashed8: '╸', + lineDashed9: '╺', + lineDashed10: '╼', + lineDashed11: '╾', + lineDashed12: '−', + lineDashed13: '–', + lineDashed14: '‐', + lineDashed15: '⁃', + lineVertical: '│', + lineVerticalBold: '┃', + lineVerticalDouble: '║', + lineVerticalDashed0: '┆', + lineVerticalDashed1: '┇', + lineVerticalDashed2: '┊', + lineVerticalDashed3: '┋', + lineVerticalDashed4: '╎', + lineVerticalDashed5: '╏', + lineVerticalDashed6: '╵', + lineVerticalDashed7: '╷', + lineVerticalDashed8: '╹', + lineVerticalDashed9: '╻', + lineVerticalDashed10: '╽', + lineVerticalDashed11: '╿', + lineDownLeft: '┐', + lineDownLeftArc: '╮', + lineDownBoldLeftBold: '┓', + lineDownBoldLeft: '┒', + lineDownLeftBold: '┑', + lineDownDoubleLeftDouble: '╗', + lineDownDoubleLeft: '╖', + lineDownLeftDouble: '╕', + lineDownRight: '┌', + lineDownRightArc: '╭', + lineDownBoldRightBold: '┏', + lineDownBoldRight: '┎', + lineDownRightBold: '┍', + lineDownDoubleRightDouble: '╔', + lineDownDoubleRight: '╓', + lineDownRightDouble: '╒', + lineUpLeft: '┘', + lineUpLeftArc: '╯', + lineUpBoldLeftBold: '┛', + lineUpBoldLeft: '┚', + lineUpLeftBold: '┙', + lineUpDoubleLeftDouble: '╝', + lineUpDoubleLeft: '╜', + lineUpLeftDouble: '╛', + lineUpRight: '└', + lineUpRightArc: '╰', + lineUpBoldRightBold: '┗', + lineUpBoldRight: '┖', + lineUpRightBold: '┕', + lineUpDoubleRightDouble: '╚', + lineUpDoubleRight: '╙', + lineUpRightDouble: '╘', + lineUpDownLeft: '┤', + lineUpBoldDownBoldLeftBold: '┫', + lineUpBoldDownBoldLeft: '┨', + lineUpDownLeftBold: '┥', + lineUpBoldDownLeftBold: '┩', + lineUpDownBoldLeftBold: '┪', + lineUpDownBoldLeft: '┧', + lineUpBoldDownLeft: '┦', + lineUpDoubleDownDoubleLeftDouble: '╣', + lineUpDoubleDownDoubleLeft: '╢', + lineUpDownLeftDouble: '╡', + lineUpDownRight: '├', + lineUpBoldDownBoldRightBold: '┣', + lineUpBoldDownBoldRight: '┠', + lineUpDownRightBold: '┝', + lineUpBoldDownRightBold: '┡', + lineUpDownBoldRightBold: '┢', + lineUpDownBoldRight: '┟', + lineUpBoldDownRight: '┞', + lineUpDoubleDownDoubleRightDouble: '╠', + lineUpDoubleDownDoubleRight: '╟', + lineUpDownRightDouble: '╞', + lineDownLeftRight: '┬', + lineDownBoldLeftBoldRightBold: '┳', + lineDownLeftBoldRightBold: '┯', + lineDownBoldLeftRight: '┰', + lineDownBoldLeftBoldRight: '┱', + lineDownBoldLeftRightBold: '┲', + lineDownLeftRightBold: '┮', + lineDownLeftBoldRight: '┭', + lineDownDoubleLeftDoubleRightDouble: '╦', + lineDownDoubleLeftRight: '╥', + lineDownLeftDoubleRightDouble: '╤', + lineUpLeftRight: '┴', + lineUpBoldLeftBoldRightBold: '┻', + lineUpLeftBoldRightBold: '┷', + lineUpBoldLeftRight: '┸', + lineUpBoldLeftBoldRight: '┹', + lineUpBoldLeftRightBold: '┺', + lineUpLeftRightBold: '┶', + lineUpLeftBoldRight: '┵', + lineUpDoubleLeftDoubleRightDouble: '╩', + lineUpDoubleLeftRight: '╨', + lineUpLeftDoubleRightDouble: '╧', + lineUpDownLeftRight: '┼', + lineUpBoldDownBoldLeftBoldRightBold: '╋', + lineUpDownBoldLeftBoldRightBold: '╈', + lineUpBoldDownLeftBoldRightBold: '╇', + lineUpBoldDownBoldLeftRightBold: '╊', + lineUpBoldDownBoldLeftBoldRight: '╉', + lineUpBoldDownLeftRight: '╀', + lineUpDownBoldLeftRight: '╁', + lineUpDownLeftBoldRight: '┽', + lineUpDownLeftRightBold: '┾', + lineUpBoldDownBoldLeftRight: '╂', + lineUpDownLeftBoldRightBold: '┿', + lineUpBoldDownLeftBoldRight: '╃', + lineUpBoldDownLeftRightBold: '╄', + lineUpDownBoldLeftBoldRight: '╅', + lineUpDownBoldLeftRightBold: '╆', + lineUpDoubleDownDoubleLeftDoubleRightDouble: '╬', + lineUpDoubleDownDoubleLeftRight: '╫', + lineUpDownLeftDoubleRightDouble: '╪', + lineCross: '╳', + lineBackslash: '╲', + lineSlash: '╱', +}; +const specialMainSymbols = { + tick: '✔', + info: 'ℹ', + warning: '⚠', + cross: '✘', + squareSmall: '◻', + squareSmallFilled: '◼', + circle: '◯', + circleFilled: '◉', + circleDotted: '◌', + circleDouble: '◎', + circleCircle: 'ⓞ', + circleCross: 'ⓧ', + circlePipe: 'Ⓘ', + radioOn: '◉', + radioOff: '◯', + checkboxOn: '☒', + checkboxOff: '☐', + checkboxCircleOn: 'ⓧ', + checkboxCircleOff: 'Ⓘ', + pointer: '❯', + triangleUpOutline: '△', + triangleLeft: '◀', + triangleRight: '▶', + lozenge: '◆', + lozengeOutline: '◇', + hamburger: '☰', + smiley: '㋡', + mustache: '෴', + star: '★', + play: '▶', + nodejs: '⬢', + oneSeventh: '⅐', + oneNinth: '⅑', + oneTenth: '⅒', +}; +const specialFallbackSymbols = { + tick: '√', + info: 'i', + warning: '‼', + cross: '×', + squareSmall: '□', + squareSmallFilled: '■', + circle: '( )', + circleFilled: '(*)', + circleDotted: '( )', + circleDouble: '( )', + circleCircle: '(○)', + circleCross: '(×)', + circlePipe: '(│)', + radioOn: '(*)', + radioOff: '( )', + checkboxOn: '[×]', + checkboxOff: '[ ]', + checkboxCircleOn: '(×)', + checkboxCircleOff: '( )', + pointer: '>', + triangleUpOutline: '∆', + triangleLeft: '◄', + triangleRight: '►', + lozenge: '♦', + lozengeOutline: '◊', + hamburger: '≡', + smiley: '☺', + mustache: '┌─┐', + star: '✶', + play: '►', + nodejs: '♦', + oneSeventh: '1/7', + oneNinth: '1/9', + oneTenth: '1/10', +}; +export const mainSymbols = { ...common, ...specialMainSymbols }; +export const fallbackSymbols = { + ...common, + ...specialFallbackSymbols, +}; +const shouldUseMain = isUnicodeSupported(); +const figures = shouldUseMain ? mainSymbols : fallbackSymbols; +export default figures; +const replacements = Object.entries(specialMainSymbols); +// On terminals which do not support Unicode symbols, substitute them to other symbols +export const replaceSymbols = (string, { useFallback = !shouldUseMain } = {}) => { + if (useFallback) { + for (const [key, mainSymbol] of replacements) { + const fallbackSymbol = fallbackSymbols[key]; + if (!fallbackSymbol) { + throw new Error(`Unable to find fallback for ${key}`); + } + string = string.replaceAll(mainSymbol, fallbackSymbol); + } + } + return string; +}; diff --git a/claude-code-source/node_modules/@inquirer/input/dist/esm/index.mjs b/claude-code-source/node_modules/@inquirer/input/dist/esm/index.mjs new file mode 100644 index 00000000..48430ace --- /dev/null +++ b/claude-code-source/node_modules/@inquirer/input/dist/esm/index.mjs @@ -0,0 +1,68 @@ +import { createPrompt, useState, useKeypress, usePrefix, isEnterKey, isBackspaceKey, makeTheme, } from '@inquirer/core'; +export default createPrompt((config, done) => { + const { required, validate = () => true } = config; + const theme = makeTheme(config.theme); + const [status, setStatus] = useState('idle'); + const [defaultValue = '', setDefaultValue] = useState(config.default); + const [errorMsg, setError] = useState(); + const [value, setValue] = useState(''); + const prefix = usePrefix({ status, theme }); + useKeypress(async (key, rl) => { + // Ignore keypress while our prompt is doing other processing. + if (status !== 'idle') { + return; + } + if (isEnterKey(key)) { + const answer = value || defaultValue; + setStatus('loading'); + const isValid = required && !answer ? 'You must provide a value' : await validate(answer); + if (isValid === true) { + setValue(answer); + setStatus('done'); + done(answer); + } + else { + // Reset the readline line value to the previous value. On line event, the value + // get cleared, forcing the user to re-enter the value instead of fixing it. + rl.write(value); + setError(isValid || 'You must provide a valid value'); + setStatus('idle'); + } + } + else if (isBackspaceKey(key) && !value) { + setDefaultValue(undefined); + } + else if (key.name === 'tab' && !value) { + setDefaultValue(undefined); + rl.clearLine(0); // Remove the tab character. + rl.write(defaultValue); + setValue(defaultValue); + } + else { + setValue(rl.line); + setError(undefined); + } + }); + const message = theme.style.message(config.message, status); + let formattedValue = value; + if (typeof config.transformer === 'function') { + formattedValue = config.transformer(value, { isFinal: status === 'done' }); + } + else if (status === 'done') { + formattedValue = theme.style.answer(value); + } + let defaultStr; + if (defaultValue && status !== 'done' && !value) { + defaultStr = theme.style.defaultAnswer(defaultValue); + } + let error = ''; + if (errorMsg) { + error = theme.style.error(errorMsg); + } + return [ + [prefix, message, defaultStr, formattedValue] + .filter((v) => v !== undefined) + .join(' '), + error, + ]; +}); diff --git a/claude-code-source/node_modules/@inquirer/prompts/dist/esm/index.mjs b/claude-code-source/node_modules/@inquirer/prompts/dist/esm/index.mjs new file mode 100644 index 00000000..19263757 --- /dev/null +++ b/claude-code-source/node_modules/@inquirer/prompts/dist/esm/index.mjs @@ -0,0 +1,10 @@ +export { default as checkbox, Separator } from '@inquirer/checkbox'; +export { default as editor } from '@inquirer/editor'; +export { default as confirm } from '@inquirer/confirm'; +export { default as input } from '@inquirer/input'; +export { default as number } from '@inquirer/number'; +export { default as expand } from '@inquirer/expand'; +export { default as rawlist } from '@inquirer/rawlist'; +export { default as password } from '@inquirer/password'; +export { default as search } from '@inquirer/search'; +export { default as select } from '@inquirer/select'; diff --git a/claude-code-source/node_modules/@inquirer/select/dist/esm/index.mjs b/claude-code-source/node_modules/@inquirer/select/dist/esm/index.mjs new file mode 100644 index 00000000..8b9cb6da --- /dev/null +++ b/claude-code-source/node_modules/@inquirer/select/dist/esm/index.mjs @@ -0,0 +1,150 @@ +import { createPrompt, useState, useKeypress, usePrefix, usePagination, useRef, useMemo, useEffect, isBackspaceKey, isEnterKey, isUpKey, isDownKey, isNumberKey, Separator, ValidationError, makeTheme, } from '@inquirer/core'; +import colors from 'yoctocolors-cjs'; +import figures from '@inquirer/figures'; +import ansiEscapes from 'ansi-escapes'; +const selectTheme = { + icon: { cursor: figures.pointer }, + style: { + disabled: (text) => colors.dim(`- ${text}`), + description: (text) => colors.cyan(text), + }, + helpMode: 'auto', +}; +function isSelectable(item) { + return !Separator.isSeparator(item) && !item.disabled; +} +function normalizeChoices(choices) { + return choices.map((choice) => { + if (Separator.isSeparator(choice)) + return choice; + if (typeof choice === 'string') { + return { + value: choice, + name: choice, + short: choice, + disabled: false, + }; + } + const name = choice.name ?? String(choice.value); + return { + value: choice.value, + name, + description: choice.description, + short: choice.short ?? name, + disabled: choice.disabled ?? false, + }; + }); +} +export default createPrompt((config, done) => { + const { loop = true, pageSize = 7 } = config; + const firstRender = useRef(true); + const theme = makeTheme(selectTheme, config.theme); + const [status, setStatus] = useState('idle'); + const prefix = usePrefix({ status, theme }); + const searchTimeoutRef = useRef(); + const items = useMemo(() => normalizeChoices(config.choices), [config.choices]); + const bounds = useMemo(() => { + const first = items.findIndex(isSelectable); + const last = items.findLastIndex(isSelectable); + if (first < 0) { + throw new ValidationError('[select prompt] No selectable choices. All choices are disabled.'); + } + return { first, last }; + }, [items]); + const defaultItemIndex = useMemo(() => { + if (!('default' in config)) + return -1; + return items.findIndex((item) => isSelectable(item) && item.value === config.default); + }, [config.default, items]); + const [active, setActive] = useState(defaultItemIndex === -1 ? bounds.first : defaultItemIndex); + // Safe to assume the cursor position always point to a Choice. + const selectedChoice = items[active]; + useKeypress((key, rl) => { + clearTimeout(searchTimeoutRef.current); + if (isEnterKey(key)) { + setStatus('done'); + done(selectedChoice.value); + } + else if (isUpKey(key) || isDownKey(key)) { + rl.clearLine(0); + if (loop || + (isUpKey(key) && active !== bounds.first) || + (isDownKey(key) && active !== bounds.last)) { + const offset = isUpKey(key) ? -1 : 1; + let next = active; + do { + next = (next + offset + items.length) % items.length; + } while (!isSelectable(items[next])); + setActive(next); + } + } + else if (isNumberKey(key)) { + rl.clearLine(0); + const position = Number(key.name) - 1; + const item = items[position]; + if (item != null && isSelectable(item)) { + setActive(position); + } + } + else if (isBackspaceKey(key)) { + rl.clearLine(0); + } + else { + // Default to search + const searchTerm = rl.line.toLowerCase(); + const matchIndex = items.findIndex((item) => { + if (Separator.isSeparator(item) || !isSelectable(item)) + return false; + return item.name.toLowerCase().startsWith(searchTerm); + }); + if (matchIndex >= 0) { + setActive(matchIndex); + } + searchTimeoutRef.current = setTimeout(() => { + rl.clearLine(0); + }, 700); + } + }); + useEffect(() => () => { + clearTimeout(searchTimeoutRef.current); + }, []); + const message = theme.style.message(config.message, status); + let helpTipTop = ''; + let helpTipBottom = ''; + if (theme.helpMode === 'always' || + (theme.helpMode === 'auto' && firstRender.current)) { + firstRender.current = false; + if (items.length > pageSize) { + helpTipBottom = `\n${theme.style.help('(Use arrow keys to reveal more choices)')}`; + } + else { + helpTipTop = theme.style.help('(Use arrow keys)'); + } + } + const page = usePagination({ + items, + active, + renderItem({ item, isActive }) { + if (Separator.isSeparator(item)) { + return ` ${item.separator}`; + } + if (item.disabled) { + const disabledLabel = typeof item.disabled === 'string' ? item.disabled : '(disabled)'; + return theme.style.disabled(`${item.name} ${disabledLabel}`); + } + const color = isActive ? theme.style.highlight : (x) => x; + const cursor = isActive ? theme.icon.cursor : ` `; + return color(`${cursor} ${item.name}`); + }, + pageSize, + loop, + }); + if (status === 'done') { + return `${prefix} ${message} ${theme.style.answer(selectedChoice.short)}`; + } + const choiceDescription = selectedChoice.description + ? `\n${theme.style.description(selectedChoice.description)}` + : ``; + return `${[prefix, message, helpTipTop].filter(Boolean).join(' ')}\n${page}${helpTipBottom}${choiceDescription}${ansiEscapes.cursorHide}`; +}); +export { Separator } from '@inquirer/core'; diff --git a/claude-code-source/node_modules/@js-sdsl/ordered-map/dist/cjs/index.js b/claude-code-source/node_modules/@js-sdsl/ordered-map/dist/cjs/index.js new file mode 100644 index 00000000..575a7fa2 --- /dev/null +++ b/claude-code-source/node_modules/@js-sdsl/ordered-map/dist/cjs/index.js @@ -0,0 +1,795 @@ +"use strict"; + +Object.defineProperty(exports, "t", { + value: true +}); + +class TreeNode { + constructor(t, e, s = 1) { + this.i = undefined; + this.h = undefined; + this.o = undefined; + this.u = t; + this.l = e; + this.p = s; + } + I() { + let t = this; + const e = t.o.o === t; + if (e && t.p === 1) { + t = t.h; + } else if (t.i) { + t = t.i; + while (t.h) { + t = t.h; + } + } else { + if (e) { + return t.o; + } + let s = t.o; + while (s.i === t) { + t = s; + s = t.o; + } + t = s; + } + return t; + } + B() { + let t = this; + if (t.h) { + t = t.h; + while (t.i) { + t = t.i; + } + return t; + } else { + let e = t.o; + while (e.h === t) { + t = e; + e = t.o; + } + if (t.h !== e) { + return e; + } else return t; + } + } + _() { + const t = this.o; + const e = this.h; + const s = e.i; + if (t.o === this) t.o = e; else if (t.i === this) t.i = e; else t.h = e; + e.o = t; + e.i = this; + this.o = e; + this.h = s; + if (s) s.o = this; + return e; + } + g() { + const t = this.o; + const e = this.i; + const s = e.h; + if (t.o === this) t.o = e; else if (t.i === this) t.i = e; else t.h = e; + e.o = t; + e.h = this; + this.o = e; + this.i = s; + if (s) s.o = this; + return e; + } +} + +class TreeNodeEnableIndex extends TreeNode { + constructor() { + super(...arguments); + this.M = 1; + } + _() { + const t = super._(); + this.O(); + t.O(); + return t; + } + g() { + const t = super.g(); + this.O(); + t.O(); + return t; + } + O() { + this.M = 1; + if (this.i) { + this.M += this.i.M; + } + if (this.h) { + this.M += this.h.M; + } + } +} + +class ContainerIterator { + constructor(t = 0) { + this.iteratorType = t; + } + equals(t) { + return this.T === t.T; + } +} + +class Base { + constructor() { + this.m = 0; + } + get length() { + return this.m; + } + size() { + return this.m; + } + empty() { + return this.m === 0; + } +} + +class Container extends Base {} + +function throwIteratorAccessError() { + throw new RangeError("Iterator access denied!"); +} + +class TreeContainer extends Container { + constructor(t = function(t, e) { + if (t < e) return -1; + if (t > e) return 1; + return 0; + }, e = false) { + super(); + this.v = undefined; + this.A = t; + this.enableIndex = e; + this.N = e ? TreeNodeEnableIndex : TreeNode; + this.C = new this.N; + } + R(t, e) { + let s = this.C; + while (t) { + const i = this.A(t.u, e); + if (i < 0) { + t = t.h; + } else if (i > 0) { + s = t; + t = t.i; + } else return t; + } + return s; + } + K(t, e) { + let s = this.C; + while (t) { + const i = this.A(t.u, e); + if (i <= 0) { + t = t.h; + } else { + s = t; + t = t.i; + } + } + return s; + } + L(t, e) { + let s = this.C; + while (t) { + const i = this.A(t.u, e); + if (i < 0) { + s = t; + t = t.h; + } else if (i > 0) { + t = t.i; + } else return t; + } + return s; + } + k(t, e) { + let s = this.C; + while (t) { + const i = this.A(t.u, e); + if (i < 0) { + s = t; + t = t.h; + } else { + t = t.i; + } + } + return s; + } + P(t) { + while (true) { + const e = t.o; + if (e === this.C) return; + if (t.p === 1) { + t.p = 0; + return; + } + if (t === e.i) { + const s = e.h; + if (s.p === 1) { + s.p = 0; + e.p = 1; + if (e === this.v) { + this.v = e._(); + } else e._(); + } else { + if (s.h && s.h.p === 1) { + s.p = e.p; + e.p = 0; + s.h.p = 0; + if (e === this.v) { + this.v = e._(); + } else e._(); + return; + } else if (s.i && s.i.p === 1) { + s.p = 1; + s.i.p = 0; + s.g(); + } else { + s.p = 1; + t = e; + } + } + } else { + const s = e.i; + if (s.p === 1) { + s.p = 0; + e.p = 1; + if (e === this.v) { + this.v = e.g(); + } else e.g(); + } else { + if (s.i && s.i.p === 1) { + s.p = e.p; + e.p = 0; + s.i.p = 0; + if (e === this.v) { + this.v = e.g(); + } else e.g(); + return; + } else if (s.h && s.h.p === 1) { + s.p = 1; + s.h.p = 0; + s._(); + } else { + s.p = 1; + t = e; + } + } + } + } + } + S(t) { + if (this.m === 1) { + this.clear(); + return; + } + let e = t; + while (e.i || e.h) { + if (e.h) { + e = e.h; + while (e.i) e = e.i; + } else { + e = e.i; + } + const s = t.u; + t.u = e.u; + e.u = s; + const i = t.l; + t.l = e.l; + e.l = i; + t = e; + } + if (this.C.i === e) { + this.C.i = e.o; + } else if (this.C.h === e) { + this.C.h = e.o; + } + this.P(e); + let s = e.o; + if (e === s.i) { + s.i = undefined; + } else s.h = undefined; + this.m -= 1; + this.v.p = 0; + if (this.enableIndex) { + while (s !== this.C) { + s.M -= 1; + s = s.o; + } + } + } + U(t) { + const e = typeof t === "number" ? t : undefined; + const s = typeof t === "function" ? t : undefined; + const i = typeof t === "undefined" ? [] : undefined; + let r = 0; + let n = this.v; + const h = []; + while (h.length || n) { + if (n) { + h.push(n); + n = n.i; + } else { + n = h.pop(); + if (r === e) return n; + i && i.push(n); + s && s(n, r, this); + r += 1; + n = n.h; + } + } + return i; + } + j(t) { + while (true) { + const e = t.o; + if (e.p === 0) return; + const s = e.o; + if (e === s.i) { + const i = s.h; + if (i && i.p === 1) { + i.p = e.p = 0; + if (s === this.v) return; + s.p = 1; + t = s; + continue; + } else if (t === e.h) { + t.p = 0; + if (t.i) { + t.i.o = e; + } + if (t.h) { + t.h.o = s; + } + e.h = t.i; + s.i = t.h; + t.i = e; + t.h = s; + if (s === this.v) { + this.v = t; + this.C.o = t; + } else { + const e = s.o; + if (e.i === s) { + e.i = t; + } else e.h = t; + } + t.o = s.o; + e.o = t; + s.o = t; + s.p = 1; + } else { + e.p = 0; + if (s === this.v) { + this.v = s.g(); + } else s.g(); + s.p = 1; + return; + } + } else { + const i = s.i; + if (i && i.p === 1) { + i.p = e.p = 0; + if (s === this.v) return; + s.p = 1; + t = s; + continue; + } else if (t === e.i) { + t.p = 0; + if (t.i) { + t.i.o = s; + } + if (t.h) { + t.h.o = e; + } + s.h = t.i; + e.i = t.h; + t.i = s; + t.h = e; + if (s === this.v) { + this.v = t; + this.C.o = t; + } else { + const e = s.o; + if (e.i === s) { + e.i = t; + } else e.h = t; + } + t.o = s.o; + e.o = t; + s.o = t; + s.p = 1; + } else { + e.p = 0; + if (s === this.v) { + this.v = s._(); + } else s._(); + s.p = 1; + return; + } + } + if (this.enableIndex) { + e.O(); + s.O(); + t.O(); + } + return; + } + } + q(t, e, s) { + if (this.v === undefined) { + this.m += 1; + this.v = new this.N(t, e, 0); + this.v.o = this.C; + this.C.o = this.C.i = this.C.h = this.v; + return this.m; + } + let i; + const r = this.C.i; + const n = this.A(r.u, t); + if (n === 0) { + r.l = e; + return this.m; + } else if (n > 0) { + r.i = new this.N(t, e); + r.i.o = r; + i = r.i; + this.C.i = i; + } else { + const r = this.C.h; + const n = this.A(r.u, t); + if (n === 0) { + r.l = e; + return this.m; + } else if (n < 0) { + r.h = new this.N(t, e); + r.h.o = r; + i = r.h; + this.C.h = i; + } else { + if (s !== undefined) { + const r = s.T; + if (r !== this.C) { + const s = this.A(r.u, t); + if (s === 0) { + r.l = e; + return this.m; + } else if (s > 0) { + const s = r.I(); + const n = this.A(s.u, t); + if (n === 0) { + s.l = e; + return this.m; + } else if (n < 0) { + i = new this.N(t, e); + if (s.h === undefined) { + s.h = i; + i.o = s; + } else { + r.i = i; + i.o = r; + } + } + } + } + } + if (i === undefined) { + i = this.v; + while (true) { + const s = this.A(i.u, t); + if (s > 0) { + if (i.i === undefined) { + i.i = new this.N(t, e); + i.i.o = i; + i = i.i; + break; + } + i = i.i; + } else if (s < 0) { + if (i.h === undefined) { + i.h = new this.N(t, e); + i.h.o = i; + i = i.h; + break; + } + i = i.h; + } else { + i.l = e; + return this.m; + } + } + } + } + } + if (this.enableIndex) { + let t = i.o; + while (t !== this.C) { + t.M += 1; + t = t.o; + } + } + this.j(i); + this.m += 1; + return this.m; + } + H(t, e) { + while (t) { + const s = this.A(t.u, e); + if (s < 0) { + t = t.h; + } else if (s > 0) { + t = t.i; + } else return t; + } + return t || this.C; + } + clear() { + this.m = 0; + this.v = undefined; + this.C.o = undefined; + this.C.i = this.C.h = undefined; + } + updateKeyByIterator(t, e) { + const s = t.T; + if (s === this.C) { + throwIteratorAccessError(); + } + if (this.m === 1) { + s.u = e; + return true; + } + const i = s.B().u; + if (s === this.C.i) { + if (this.A(i, e) > 0) { + s.u = e; + return true; + } + return false; + } + const r = s.I().u; + if (s === this.C.h) { + if (this.A(r, e) < 0) { + s.u = e; + return true; + } + return false; + } + if (this.A(r, e) >= 0 || this.A(i, e) <= 0) return false; + s.u = e; + return true; + } + eraseElementByPos(t) { + if (t < 0 || t > this.m - 1) { + throw new RangeError; + } + const e = this.U(t); + this.S(e); + return this.m; + } + eraseElementByKey(t) { + if (this.m === 0) return false; + const e = this.H(this.v, t); + if (e === this.C) return false; + this.S(e); + return true; + } + eraseElementByIterator(t) { + const e = t.T; + if (e === this.C) { + throwIteratorAccessError(); + } + const s = e.h === undefined; + const i = t.iteratorType === 0; + if (i) { + if (s) t.next(); + } else { + if (!s || e.i === undefined) t.next(); + } + this.S(e); + return t; + } + getHeight() { + if (this.m === 0) return 0; + function traversal(t) { + if (!t) return 0; + return Math.max(traversal(t.i), traversal(t.h)) + 1; + } + return traversal(this.v); + } +} + +class TreeIterator extends ContainerIterator { + constructor(t, e, s) { + super(s); + this.T = t; + this.C = e; + if (this.iteratorType === 0) { + this.pre = function() { + if (this.T === this.C.i) { + throwIteratorAccessError(); + } + this.T = this.T.I(); + return this; + }; + this.next = function() { + if (this.T === this.C) { + throwIteratorAccessError(); + } + this.T = this.T.B(); + return this; + }; + } else { + this.pre = function() { + if (this.T === this.C.h) { + throwIteratorAccessError(); + } + this.T = this.T.B(); + return this; + }; + this.next = function() { + if (this.T === this.C) { + throwIteratorAccessError(); + } + this.T = this.T.I(); + return this; + }; + } + } + get index() { + let t = this.T; + const e = this.C.o; + if (t === this.C) { + if (e) { + return e.M - 1; + } + return 0; + } + let s = 0; + if (t.i) { + s += t.i.M; + } + while (t !== e) { + const e = t.o; + if (t === e.h) { + s += 1; + if (e.i) { + s += e.i.M; + } + } + t = e; + } + return s; + } + isAccessible() { + return this.T !== this.C; + } +} + +class OrderedMapIterator extends TreeIterator { + constructor(t, e, s, i) { + super(t, e, i); + this.container = s; + } + get pointer() { + if (this.T === this.C) { + throwIteratorAccessError(); + } + const t = this; + return new Proxy([], { + get(e, s) { + if (s === "0") return t.T.u; else if (s === "1") return t.T.l; + e[0] = t.T.u; + e[1] = t.T.l; + return e[s]; + }, + set(e, s, i) { + if (s !== "1") { + throw new TypeError("prop must be 1"); + } + t.T.l = i; + return true; + } + }); + } + copy() { + return new OrderedMapIterator(this.T, this.C, this.container, this.iteratorType); + } +} + +class OrderedMap extends TreeContainer { + constructor(t = [], e, s) { + super(e, s); + const i = this; + t.forEach((function(t) { + i.setElement(t[0], t[1]); + })); + } + begin() { + return new OrderedMapIterator(this.C.i || this.C, this.C, this); + } + end() { + return new OrderedMapIterator(this.C, this.C, this); + } + rBegin() { + return new OrderedMapIterator(this.C.h || this.C, this.C, this, 1); + } + rEnd() { + return new OrderedMapIterator(this.C, this.C, this, 1); + } + front() { + if (this.m === 0) return; + const t = this.C.i; + return [ t.u, t.l ]; + } + back() { + if (this.m === 0) return; + const t = this.C.h; + return [ t.u, t.l ]; + } + lowerBound(t) { + const e = this.R(this.v, t); + return new OrderedMapIterator(e, this.C, this); + } + upperBound(t) { + const e = this.K(this.v, t); + return new OrderedMapIterator(e, this.C, this); + } + reverseLowerBound(t) { + const e = this.L(this.v, t); + return new OrderedMapIterator(e, this.C, this); + } + reverseUpperBound(t) { + const e = this.k(this.v, t); + return new OrderedMapIterator(e, this.C, this); + } + forEach(t) { + this.U((function(e, s, i) { + t([ e.u, e.l ], s, i); + })); + } + setElement(t, e, s) { + return this.q(t, e, s); + } + getElementByPos(t) { + if (t < 0 || t > this.m - 1) { + throw new RangeError; + } + const e = this.U(t); + return [ e.u, e.l ]; + } + find(t) { + const e = this.H(this.v, t); + return new OrderedMapIterator(e, this.C, this); + } + getElementByKey(t) { + const e = this.H(this.v, t); + return e.l; + } + union(t) { + const e = this; + t.forEach((function(t) { + e.setElement(t[0], t[1]); + })); + return this.m; + } + * [Symbol.iterator]() { + const t = this.m; + const e = this.U(); + for (let s = 0; s < t; ++s) { + const t = e[s]; + yield [ t.u, t.l ]; + } + } +} + +exports.OrderedMap = OrderedMap; +//# sourceMappingURL=index.js.map diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js new file mode 100644 index 00000000..49e11378 --- /dev/null +++ b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js @@ -0,0 +1,900 @@ +import pkceChallenge from 'pkce-challenge'; +import { LATEST_PROTOCOL_VERSION } from '../types.js'; +import { OAuthErrorResponseSchema, OpenIdProviderDiscoveryMetadataSchema } from '../shared/auth.js'; +import { OAuthClientInformationFullSchema, OAuthMetadataSchema, OAuthProtectedResourceMetadataSchema, OAuthTokensSchema } from '../shared/auth.js'; +import { checkResourceAllowed, resourceUrlFromServerUrl } from '../shared/auth-utils.js'; +import { InvalidClientError, InvalidClientMetadataError, InvalidGrantError, OAUTH_ERRORS, OAuthError, ServerError, UnauthorizedClientError } from '../server/auth/errors.js'; +export class UnauthorizedError extends Error { + constructor(message) { + super(message ?? 'Unauthorized'); + } +} +function isClientAuthMethod(method) { + return ['client_secret_basic', 'client_secret_post', 'none'].includes(method); +} +const AUTHORIZATION_CODE_RESPONSE_TYPE = 'code'; +const AUTHORIZATION_CODE_CHALLENGE_METHOD = 'S256'; +/** + * Determines the best client authentication method to use based on server support and client configuration. + * + * Priority order (highest to lowest): + * 1. client_secret_basic (if client secret is available) + * 2. client_secret_post (if client secret is available) + * 3. none (for public clients) + * + * @param clientInformation - OAuth client information containing credentials + * @param supportedMethods - Authentication methods supported by the authorization server + * @returns The selected authentication method + */ +export function selectClientAuthMethod(clientInformation, supportedMethods) { + const hasClientSecret = clientInformation.client_secret !== undefined; + // If server doesn't specify supported methods, use RFC 6749 defaults + if (supportedMethods.length === 0) { + return hasClientSecret ? 'client_secret_post' : 'none'; + } + // Prefer the method returned by the server during client registration if valid and supported + if ('token_endpoint_auth_method' in clientInformation && + clientInformation.token_endpoint_auth_method && + isClientAuthMethod(clientInformation.token_endpoint_auth_method) && + supportedMethods.includes(clientInformation.token_endpoint_auth_method)) { + return clientInformation.token_endpoint_auth_method; + } + // Try methods in priority order (most secure first) + if (hasClientSecret && supportedMethods.includes('client_secret_basic')) { + return 'client_secret_basic'; + } + if (hasClientSecret && supportedMethods.includes('client_secret_post')) { + return 'client_secret_post'; + } + if (supportedMethods.includes('none')) { + return 'none'; + } + // Fallback: use what we have + return hasClientSecret ? 'client_secret_post' : 'none'; +} +/** + * Applies client authentication to the request based on the specified method. + * + * Implements OAuth 2.1 client authentication methods: + * - client_secret_basic: HTTP Basic authentication (RFC 6749 Section 2.3.1) + * - client_secret_post: Credentials in request body (RFC 6749 Section 2.3.1) + * - none: Public client authentication (RFC 6749 Section 2.1) + * + * @param method - The authentication method to use + * @param clientInformation - OAuth client information containing credentials + * @param headers - HTTP headers object to modify + * @param params - URL search parameters to modify + * @throws {Error} When required credentials are missing + */ +function applyClientAuthentication(method, clientInformation, headers, params) { + const { client_id, client_secret } = clientInformation; + switch (method) { + case 'client_secret_basic': + applyBasicAuth(client_id, client_secret, headers); + return; + case 'client_secret_post': + applyPostAuth(client_id, client_secret, params); + return; + case 'none': + applyPublicAuth(client_id, params); + return; + default: + throw new Error(`Unsupported client authentication method: ${method}`); + } +} +/** + * Applies HTTP Basic authentication (RFC 6749 Section 2.3.1) + */ +function applyBasicAuth(clientId, clientSecret, headers) { + if (!clientSecret) { + throw new Error('client_secret_basic authentication requires a client_secret'); + } + const credentials = btoa(`${clientId}:${clientSecret}`); + headers.set('Authorization', `Basic ${credentials}`); +} +/** + * Applies POST body authentication (RFC 6749 Section 2.3.1) + */ +function applyPostAuth(clientId, clientSecret, params) { + params.set('client_id', clientId); + if (clientSecret) { + params.set('client_secret', clientSecret); + } +} +/** + * Applies public client authentication (RFC 6749 Section 2.1) + */ +function applyPublicAuth(clientId, params) { + params.set('client_id', clientId); +} +/** + * Parses an OAuth error response from a string or Response object. + * + * If the input is a standard OAuth2.0 error response, it will be parsed according to the spec + * and an instance of the appropriate OAuthError subclass will be returned. + * If parsing fails, it falls back to a generic ServerError that includes + * the response status (if available) and original content. + * + * @param input - A Response object or string containing the error response + * @returns A Promise that resolves to an OAuthError instance + */ +export async function parseErrorResponse(input) { + const statusCode = input instanceof Response ? input.status : undefined; + const body = input instanceof Response ? await input.text() : input; + try { + const result = OAuthErrorResponseSchema.parse(JSON.parse(body)); + const { error, error_description, error_uri } = result; + const errorClass = OAUTH_ERRORS[error] || ServerError; + return new errorClass(error_description || '', error_uri); + } + catch (error) { + // Not a valid OAuth error response, but try to inform the user of the raw data anyway + const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ''}Invalid OAuth error response: ${error}. Raw body: ${body}`; + return new ServerError(errorMessage); + } +} +/** + * Orchestrates the full auth flow with a server. + * + * This can be used as a single entry point for all authorization functionality, + * instead of linking together the other lower-level functions in this module. + */ +export async function auth(provider, options) { + try { + return await authInternal(provider, options); + } + catch (error) { + // Handle recoverable error types by invalidating credentials and retrying + if (error instanceof InvalidClientError || error instanceof UnauthorizedClientError) { + await provider.invalidateCredentials?.('all'); + return await authInternal(provider, options); + } + else if (error instanceof InvalidGrantError) { + await provider.invalidateCredentials?.('tokens'); + return await authInternal(provider, options); + } + // Throw otherwise + throw error; + } +} +async function authInternal(provider, { serverUrl, authorizationCode, scope, resourceMetadataUrl, fetchFn }) { + // Check if the provider has cached discovery state to skip discovery + const cachedState = await provider.discoveryState?.(); + let resourceMetadata; + let authorizationServerUrl; + let metadata; + // If resourceMetadataUrl is not provided, try to load it from cached state + // This handles browser redirects where the URL was saved before navigation + let effectiveResourceMetadataUrl = resourceMetadataUrl; + if (!effectiveResourceMetadataUrl && cachedState?.resourceMetadataUrl) { + effectiveResourceMetadataUrl = new URL(cachedState.resourceMetadataUrl); + } + if (cachedState?.authorizationServerUrl) { + // Restore discovery state from cache + authorizationServerUrl = cachedState.authorizationServerUrl; + resourceMetadata = cachedState.resourceMetadata; + metadata = + cachedState.authorizationServerMetadata ?? (await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn })); + // If resource metadata wasn't cached, try to fetch it for selectResourceURL + if (!resourceMetadata) { + try { + resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl }, fetchFn); + } + catch { + // RFC 9728 not available — selectResourceURL will handle undefined + } + } + // Re-save if we enriched the cached state with missing metadata + if (metadata !== cachedState.authorizationServerMetadata || resourceMetadata !== cachedState.resourceMetadata) { + await provider.saveDiscoveryState?.({ + authorizationServerUrl: String(authorizationServerUrl), + resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(), + resourceMetadata, + authorizationServerMetadata: metadata + }); + } + } + else { + // Full discovery via RFC 9728 + const serverInfo = await discoverOAuthServerInfo(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl, fetchFn }); + authorizationServerUrl = serverInfo.authorizationServerUrl; + metadata = serverInfo.authorizationServerMetadata; + resourceMetadata = serverInfo.resourceMetadata; + // Persist discovery state for future use + // TODO: resourceMetadataUrl is only populated when explicitly provided via options + // or loaded from cached state. The URL derived internally by + // discoverOAuthProtectedResourceMetadata() is not captured back here. + await provider.saveDiscoveryState?.({ + authorizationServerUrl: String(authorizationServerUrl), + resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(), + resourceMetadata, + authorizationServerMetadata: metadata + }); + } + const resource = await selectResourceURL(serverUrl, provider, resourceMetadata); + // Handle client registration if needed + let clientInformation = await Promise.resolve(provider.clientInformation()); + if (!clientInformation) { + if (authorizationCode !== undefined) { + throw new Error('Existing OAuth client information is required when exchanging an authorization code'); + } + const supportsUrlBasedClientId = metadata?.client_id_metadata_document_supported === true; + const clientMetadataUrl = provider.clientMetadataUrl; + if (clientMetadataUrl && !isHttpsUrl(clientMetadataUrl)) { + throw new InvalidClientMetadataError(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`); + } + const shouldUseUrlBasedClientId = supportsUrlBasedClientId && clientMetadataUrl; + if (shouldUseUrlBasedClientId) { + // SEP-991: URL-based Client IDs + clientInformation = { + client_id: clientMetadataUrl + }; + await provider.saveClientInformation?.(clientInformation); + } + else { + // Fallback to dynamic registration + if (!provider.saveClientInformation) { + throw new Error('OAuth client information must be saveable for dynamic registration'); + } + const fullInformation = await registerClient(authorizationServerUrl, { + metadata, + clientMetadata: provider.clientMetadata, + fetchFn + }); + await provider.saveClientInformation(fullInformation); + clientInformation = fullInformation; + } + } + // Non-interactive flows (e.g., client_credentials, jwt-bearer) don't need a redirect URL + const nonInteractiveFlow = !provider.redirectUrl; + // Exchange authorization code for tokens, or fetch tokens directly for non-interactive flows + if (authorizationCode !== undefined || nonInteractiveFlow) { + const tokens = await fetchToken(provider, authorizationServerUrl, { + metadata, + resource, + authorizationCode, + fetchFn + }); + await provider.saveTokens(tokens); + return 'AUTHORIZED'; + } + const tokens = await provider.tokens(); + // Handle token refresh or new authorization + if (tokens?.refresh_token) { + try { + // Attempt to refresh the token + const newTokens = await refreshAuthorization(authorizationServerUrl, { + metadata, + clientInformation, + refreshToken: tokens.refresh_token, + resource, + addClientAuthentication: provider.addClientAuthentication, + fetchFn + }); + await provider.saveTokens(newTokens); + return 'AUTHORIZED'; + } + catch (error) { + // If this is a ServerError, or an unknown type, log it out and try to continue. Otherwise, escalate so we can fix things and retry. + if (!(error instanceof OAuthError) || error instanceof ServerError) { + // Could not refresh OAuth tokens + } + else { + // Refresh failed for another reason, re-throw + throw error; + } + } + } + const state = provider.state ? await provider.state() : undefined; + // Start new authorization flow + const { authorizationUrl, codeVerifier } = await startAuthorization(authorizationServerUrl, { + metadata, + clientInformation, + state, + redirectUrl: provider.redirectUrl, + scope: scope || resourceMetadata?.scopes_supported?.join(' ') || provider.clientMetadata.scope, + resource + }); + await provider.saveCodeVerifier(codeVerifier); + await provider.redirectToAuthorization(authorizationUrl); + return 'REDIRECT'; +} +/** + * SEP-991: URL-based Client IDs + * Validate that the client_id is a valid URL with https scheme + */ +export function isHttpsUrl(value) { + if (!value) + return false; + try { + const url = new URL(value); + return url.protocol === 'https:' && url.pathname !== '/'; + } + catch { + return false; + } +} +export async function selectResourceURL(serverUrl, provider, resourceMetadata) { + const defaultResource = resourceUrlFromServerUrl(serverUrl); + // If provider has custom validation, delegate to it + if (provider.validateResourceURL) { + return await provider.validateResourceURL(defaultResource, resourceMetadata?.resource); + } + // Only include resource parameter when Protected Resource Metadata is present + if (!resourceMetadata) { + return undefined; + } + // Validate that the metadata's resource is compatible with our request + if (!checkResourceAllowed({ requestedResource: defaultResource, configuredResource: resourceMetadata.resource })) { + throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`); + } + // Prefer the resource from metadata since it's what the server is telling us to request + return new URL(resourceMetadata.resource); +} +/** + * Extract resource_metadata, scope, and error from WWW-Authenticate header. + */ +export function extractWWWAuthenticateParams(res) { + const authenticateHeader = res.headers.get('WWW-Authenticate'); + if (!authenticateHeader) { + return {}; + } + const [type, scheme] = authenticateHeader.split(' '); + if (type.toLowerCase() !== 'bearer' || !scheme) { + return {}; + } + const resourceMetadataMatch = extractFieldFromWwwAuth(res, 'resource_metadata') || undefined; + let resourceMetadataUrl; + if (resourceMetadataMatch) { + try { + resourceMetadataUrl = new URL(resourceMetadataMatch); + } + catch { + // Ignore invalid URL + } + } + const scope = extractFieldFromWwwAuth(res, 'scope') || undefined; + const error = extractFieldFromWwwAuth(res, 'error') || undefined; + return { + resourceMetadataUrl, + scope, + error + }; +} +/** + * Extracts a specific field's value from the WWW-Authenticate header string. + * + * @param response The HTTP response object containing the headers. + * @param fieldName The name of the field to extract (e.g., "realm", "nonce"). + * @returns The field value + */ +function extractFieldFromWwwAuth(response, fieldName) { + const wwwAuthHeader = response.headers.get('WWW-Authenticate'); + if (!wwwAuthHeader) { + return null; + } + const pattern = new RegExp(`${fieldName}=(?:"([^"]+)"|([^\\s,]+))`); + const match = wwwAuthHeader.match(pattern); + if (match) { + // Pattern matches: field_name="value" or field_name=value (unquoted) + return match[1] || match[2]; + } + return null; +} +/** + * Extract resource_metadata from response header. + * @deprecated Use `extractWWWAuthenticateParams` instead. + */ +export function extractResourceMetadataUrl(res) { + const authenticateHeader = res.headers.get('WWW-Authenticate'); + if (!authenticateHeader) { + return undefined; + } + const [type, scheme] = authenticateHeader.split(' '); + if (type.toLowerCase() !== 'bearer' || !scheme) { + return undefined; + } + const regex = /resource_metadata="([^"]*)"/; + const match = regex.exec(authenticateHeader); + if (!match) { + return undefined; + } + try { + return new URL(match[1]); + } + catch { + return undefined; + } +} +/** + * Looks up RFC 9728 OAuth 2.0 Protected Resource Metadata. + * + * If the server returns a 404 for the well-known endpoint, this function will + * return `undefined`. Any other errors will be thrown as exceptions. + */ +export async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) { + const response = await discoverMetadataWithFallback(serverUrl, 'oauth-protected-resource', fetchFn, { + protocolVersion: opts?.protocolVersion, + metadataUrl: opts?.resourceMetadataUrl + }); + if (!response || response.status === 404) { + await response?.body?.cancel(); + throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`); + } + if (!response.ok) { + await response.body?.cancel(); + throw new Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`); + } + return OAuthProtectedResourceMetadataSchema.parse(await response.json()); +} +/** + * Helper function to handle fetch with CORS retry logic + */ +async function fetchWithCorsRetry(url, headers, fetchFn = fetch) { + try { + return await fetchFn(url, { headers }); + } + catch (error) { + if (error instanceof TypeError) { + if (headers) { + // CORS errors come back as TypeError, retry without headers + return fetchWithCorsRetry(url, undefined, fetchFn); + } + else { + // We're getting CORS errors on retry too, return undefined + return undefined; + } + } + throw error; + } +} +/** + * Constructs the well-known path for auth-related metadata discovery + */ +function buildWellKnownPath(wellKnownPrefix, pathname = '', options = {}) { + // Strip trailing slash from pathname to avoid double slashes + if (pathname.endsWith('/')) { + pathname = pathname.slice(0, -1); + } + return options.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`; +} +/** + * Tries to discover OAuth metadata at a specific URL + */ +async function tryMetadataDiscovery(url, protocolVersion, fetchFn = fetch) { + const headers = { + 'MCP-Protocol-Version': protocolVersion + }; + return await fetchWithCorsRetry(url, headers, fetchFn); +} +/** + * Determines if fallback to root discovery should be attempted + */ +function shouldAttemptFallback(response, pathname) { + return !response || (response.status >= 400 && response.status < 500 && pathname !== '/'); +} +/** + * Generic function for discovering OAuth metadata with fallback support + */ +async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) { + const issuer = new URL(serverUrl); + const protocolVersion = opts?.protocolVersion ?? LATEST_PROTOCOL_VERSION; + let url; + if (opts?.metadataUrl) { + url = new URL(opts.metadataUrl); + } + else { + // Try path-aware discovery first + const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname); + url = new URL(wellKnownPath, opts?.metadataServerUrl ?? issuer); + url.search = issuer.search; + } + let response = await tryMetadataDiscovery(url, protocolVersion, fetchFn); + // If path-aware discovery fails with 404 and we're not already at root, try fallback to root discovery + if (!opts?.metadataUrl && shouldAttemptFallback(response, issuer.pathname)) { + const rootUrl = new URL(`/.well-known/${wellKnownType}`, issuer); + response = await tryMetadataDiscovery(rootUrl, protocolVersion, fetchFn); + } + return response; +} +/** + * Looks up RFC 8414 OAuth 2.0 Authorization Server Metadata. + * + * If the server returns a 404 for the well-known endpoint, this function will + * return `undefined`. Any other errors will be thrown as exceptions. + * + * @deprecated This function is deprecated in favor of `discoverAuthorizationServerMetadata`. + */ +export async function discoverOAuthMetadata(issuer, { authorizationServerUrl, protocolVersion } = {}, fetchFn = fetch) { + if (typeof issuer === 'string') { + issuer = new URL(issuer); + } + if (!authorizationServerUrl) { + authorizationServerUrl = issuer; + } + if (typeof authorizationServerUrl === 'string') { + authorizationServerUrl = new URL(authorizationServerUrl); + } + protocolVersion ?? (protocolVersion = LATEST_PROTOCOL_VERSION); + const response = await discoverMetadataWithFallback(authorizationServerUrl, 'oauth-authorization-server', fetchFn, { + protocolVersion, + metadataServerUrl: authorizationServerUrl + }); + if (!response || response.status === 404) { + await response?.body?.cancel(); + return undefined; + } + if (!response.ok) { + await response.body?.cancel(); + throw new Error(`HTTP ${response.status} trying to load well-known OAuth metadata`); + } + return OAuthMetadataSchema.parse(await response.json()); +} +/** + * Builds a list of discovery URLs to try for authorization server metadata. + * URLs are returned in priority order: + * 1. OAuth metadata at the given URL + * 2. OIDC metadata endpoints at the given URL + */ +export function buildDiscoveryUrls(authorizationServerUrl) { + const url = typeof authorizationServerUrl === 'string' ? new URL(authorizationServerUrl) : authorizationServerUrl; + const hasPath = url.pathname !== '/'; + const urlsToTry = []; + if (!hasPath) { + // Root path: https://example.com/.well-known/oauth-authorization-server + urlsToTry.push({ + url: new URL('/.well-known/oauth-authorization-server', url.origin), + type: 'oauth' + }); + // OIDC: https://example.com/.well-known/openid-configuration + urlsToTry.push({ + url: new URL(`/.well-known/openid-configuration`, url.origin), + type: 'oidc' + }); + return urlsToTry; + } + // Strip trailing slash from pathname to avoid double slashes + let pathname = url.pathname; + if (pathname.endsWith('/')) { + pathname = pathname.slice(0, -1); + } + // 1. OAuth metadata at the given URL + // Insert well-known before the path: https://example.com/.well-known/oauth-authorization-server/tenant1 + urlsToTry.push({ + url: new URL(`/.well-known/oauth-authorization-server${pathname}`, url.origin), + type: 'oauth' + }); + // 2. OIDC metadata endpoints + // RFC 8414 style: Insert /.well-known/openid-configuration before the path + urlsToTry.push({ + url: new URL(`/.well-known/openid-configuration${pathname}`, url.origin), + type: 'oidc' + }); + // OIDC Discovery 1.0 style: Append /.well-known/openid-configuration after the path + urlsToTry.push({ + url: new URL(`${pathname}/.well-known/openid-configuration`, url.origin), + type: 'oidc' + }); + return urlsToTry; +} +/** + * Discovers authorization server metadata with support for RFC 8414 OAuth 2.0 Authorization Server Metadata + * and OpenID Connect Discovery 1.0 specifications. + * + * This function implements a fallback strategy for authorization server discovery: + * 1. Attempts RFC 8414 OAuth metadata discovery first + * 2. If OAuth discovery fails, falls back to OpenID Connect Discovery + * + * @param authorizationServerUrl - The authorization server URL obtained from the MCP Server's + * protected resource metadata, or the MCP server's URL if the + * metadata was not found. + * @param options - Configuration options + * @param options.fetchFn - Optional fetch function for making HTTP requests, defaults to global fetch + * @param options.protocolVersion - MCP protocol version to use, defaults to LATEST_PROTOCOL_VERSION + * @returns Promise resolving to authorization server metadata, or undefined if discovery fails + */ +export async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn = fetch, protocolVersion = LATEST_PROTOCOL_VERSION } = {}) { + const headers = { + 'MCP-Protocol-Version': protocolVersion, + Accept: 'application/json' + }; + // Get the list of URLs to try + const urlsToTry = buildDiscoveryUrls(authorizationServerUrl); + // Try each URL in order + for (const { url: endpointUrl, type } of urlsToTry) { + const response = await fetchWithCorsRetry(endpointUrl, headers, fetchFn); + if (!response) { + /** + * CORS error occurred - don't throw as the endpoint may not allow CORS, + * continue trying other possible endpoints + */ + continue; + } + if (!response.ok) { + await response.body?.cancel(); + // Continue looking for any 4xx response code. + if (response.status >= 400 && response.status < 500) { + continue; // Try next URL + } + throw new Error(`HTTP ${response.status} trying to load ${type === 'oauth' ? 'OAuth' : 'OpenID provider'} metadata from ${endpointUrl}`); + } + // Parse and validate based on type + if (type === 'oauth') { + return OAuthMetadataSchema.parse(await response.json()); + } + else { + return OpenIdProviderDiscoveryMetadataSchema.parse(await response.json()); + } + } + return undefined; +} +/** + * Discovers the authorization server for an MCP server following + * {@link https://datatracker.ietf.org/doc/html/rfc9728 | RFC 9728} (OAuth 2.0 Protected + * Resource Metadata), with fallback to treating the server URL as the + * authorization server. + * + * This function combines two discovery steps into one call: + * 1. Probes `/.well-known/oauth-protected-resource` on the MCP server to find the + * authorization server URL (RFC 9728). + * 2. Fetches authorization server metadata from that URL (RFC 8414 / OpenID Connect Discovery). + * + * Use this when you need the authorization server metadata for operations outside the + * {@linkcode auth} orchestrator, such as token refresh or token revocation. + * + * @param serverUrl - The MCP resource server URL + * @param opts - Optional configuration + * @param opts.resourceMetadataUrl - Override URL for the protected resource metadata endpoint + * @param opts.fetchFn - Custom fetch function for HTTP requests + * @returns Authorization server URL, metadata, and resource metadata (if available) + */ +export async function discoverOAuthServerInfo(serverUrl, opts) { + let resourceMetadata; + let authorizationServerUrl; + try { + resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: opts?.resourceMetadataUrl }, opts?.fetchFn); + if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) { + authorizationServerUrl = resourceMetadata.authorization_servers[0]; + } + } + catch { + // RFC 9728 not supported -- fall back to treating the server URL as the authorization server + } + // If we don't get a valid authorization server from protected resource metadata, + // fall back to the legacy MCP spec behavior: MCP server base URL acts as the authorization server + if (!authorizationServerUrl) { + authorizationServerUrl = String(new URL('/', serverUrl)); + } + const authorizationServerMetadata = await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn: opts?.fetchFn }); + return { + authorizationServerUrl, + authorizationServerMetadata, + resourceMetadata + }; +} +/** + * Begins the authorization flow with the given server, by generating a PKCE challenge and constructing the authorization URL. + */ +export async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state, resource }) { + let authorizationUrl; + if (metadata) { + authorizationUrl = new URL(metadata.authorization_endpoint); + if (!metadata.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE)) { + throw new Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`); + } + if (metadata.code_challenge_methods_supported && + !metadata.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD)) { + throw new Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`); + } + } + else { + authorizationUrl = new URL('/authorize', authorizationServerUrl); + } + // Generate PKCE challenge + const challenge = await pkceChallenge(); + const codeVerifier = challenge.code_verifier; + const codeChallenge = challenge.code_challenge; + authorizationUrl.searchParams.set('response_type', AUTHORIZATION_CODE_RESPONSE_TYPE); + authorizationUrl.searchParams.set('client_id', clientInformation.client_id); + authorizationUrl.searchParams.set('code_challenge', codeChallenge); + authorizationUrl.searchParams.set('code_challenge_method', AUTHORIZATION_CODE_CHALLENGE_METHOD); + authorizationUrl.searchParams.set('redirect_uri', String(redirectUrl)); + if (state) { + authorizationUrl.searchParams.set('state', state); + } + if (scope) { + authorizationUrl.searchParams.set('scope', scope); + } + if (scope?.includes('offline_access')) { + // if the request includes the OIDC-only "offline_access" scope, + // we need to set the prompt to "consent" to ensure the user is prompted to grant offline access + // https://openid.net/specs/openid-connect-core-1_0.html#OfflineAccess + authorizationUrl.searchParams.append('prompt', 'consent'); + } + if (resource) { + authorizationUrl.searchParams.set('resource', resource.href); + } + return { authorizationUrl, codeVerifier }; +} +/** + * Prepares token request parameters for an authorization code exchange. + * + * This is the default implementation used by fetchToken when the provider + * doesn't implement prepareTokenRequest. + * + * @param authorizationCode - The authorization code received from the authorization endpoint + * @param codeVerifier - The PKCE code verifier + * @param redirectUri - The redirect URI used in the authorization request + * @returns URLSearchParams for the authorization_code grant + */ +export function prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri) { + return new URLSearchParams({ + grant_type: 'authorization_code', + code: authorizationCode, + code_verifier: codeVerifier, + redirect_uri: String(redirectUri) + }); +} +/** + * Internal helper to execute a token request with the given parameters. + * Used by exchangeAuthorization, refreshAuthorization, and fetchToken. + */ +async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequestParams, clientInformation, addClientAuthentication, resource, fetchFn }) { + const tokenUrl = metadata?.token_endpoint ? new URL(metadata.token_endpoint) : new URL('/token', authorizationServerUrl); + const headers = new Headers({ + 'Content-Type': 'application/x-www-form-urlencoded', + Accept: 'application/json' + }); + if (resource) { + tokenRequestParams.set('resource', resource.href); + } + if (addClientAuthentication) { + await addClientAuthentication(headers, tokenRequestParams, tokenUrl, metadata); + } + else if (clientInformation) { + const supportedMethods = metadata?.token_endpoint_auth_methods_supported ?? []; + const authMethod = selectClientAuthMethod(clientInformation, supportedMethods); + applyClientAuthentication(authMethod, clientInformation, headers, tokenRequestParams); + } + const response = await (fetchFn ?? fetch)(tokenUrl, { + method: 'POST', + headers, + body: tokenRequestParams + }); + if (!response.ok) { + throw await parseErrorResponse(response); + } + return OAuthTokensSchema.parse(await response.json()); +} +/** + * Exchanges an authorization code for an access token with the given server. + * + * Supports multiple client authentication methods as specified in OAuth 2.1: + * - Automatically selects the best authentication method based on server support + * - Falls back to appropriate defaults when server metadata is unavailable + * + * @param authorizationServerUrl - The authorization server's base URL + * @param options - Configuration object containing client info, auth code, etc. + * @returns Promise resolving to OAuth tokens + * @throws {Error} When token exchange fails or authentication is invalid + */ +export async function exchangeAuthorization(authorizationServerUrl, { metadata, clientInformation, authorizationCode, codeVerifier, redirectUri, resource, addClientAuthentication, fetchFn }) { + const tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri); + return executeTokenRequest(authorizationServerUrl, { + metadata, + tokenRequestParams, + clientInformation, + addClientAuthentication, + resource, + fetchFn + }); +} +/** + * Exchange a refresh token for an updated access token. + * + * Supports multiple client authentication methods as specified in OAuth 2.1: + * - Automatically selects the best authentication method based on server support + * - Preserves the original refresh token if a new one is not returned + * + * @param authorizationServerUrl - The authorization server's base URL + * @param options - Configuration object containing client info, refresh token, etc. + * @returns Promise resolving to OAuth tokens (preserves original refresh_token if not replaced) + * @throws {Error} When token refresh fails or authentication is invalid + */ +export async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) { + const tokenRequestParams = new URLSearchParams({ + grant_type: 'refresh_token', + refresh_token: refreshToken + }); + const tokens = await executeTokenRequest(authorizationServerUrl, { + metadata, + tokenRequestParams, + clientInformation, + addClientAuthentication, + resource, + fetchFn + }); + // Preserve original refresh token if server didn't return a new one + return { refresh_token: refreshToken, ...tokens }; +} +/** + * Unified token fetching that works with any grant type via provider.prepareTokenRequest(). + * + * This function provides a single entry point for obtaining tokens regardless of the + * OAuth grant type. The provider's prepareTokenRequest() method determines which grant + * to use and supplies the grant-specific parameters. + * + * @param provider - OAuth client provider that implements prepareTokenRequest() + * @param authorizationServerUrl - The authorization server's base URL + * @param options - Configuration for the token request + * @returns Promise resolving to OAuth tokens + * @throws {Error} When provider doesn't implement prepareTokenRequest or token fetch fails + * + * @example + * // Provider for client_credentials: + * class MyProvider implements OAuthClientProvider { + * prepareTokenRequest(scope) { + * const params = new URLSearchParams({ grant_type: 'client_credentials' }); + * if (scope) params.set('scope', scope); + * return params; + * } + * // ... other methods + * } + * + * const tokens = await fetchToken(provider, authServerUrl, { metadata }); + */ +export async function fetchToken(provider, authorizationServerUrl, { metadata, resource, authorizationCode, fetchFn } = {}) { + const scope = provider.clientMetadata.scope; + // Use provider's prepareTokenRequest if available, otherwise fall back to authorization_code + let tokenRequestParams; + if (provider.prepareTokenRequest) { + tokenRequestParams = await provider.prepareTokenRequest(scope); + } + // Default to authorization_code grant if no custom prepareTokenRequest + if (!tokenRequestParams) { + if (!authorizationCode) { + throw new Error('Either provider.prepareTokenRequest() or authorizationCode is required'); + } + if (!provider.redirectUrl) { + throw new Error('redirectUrl is required for authorization_code flow'); + } + const codeVerifier = await provider.codeVerifier(); + tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, provider.redirectUrl); + } + const clientInformation = await provider.clientInformation(); + return executeTokenRequest(authorizationServerUrl, { + metadata, + tokenRequestParams, + clientInformation: clientInformation ?? undefined, + addClientAuthentication: provider.addClientAuthentication, + resource, + fetchFn + }); +} +/** + * Performs OAuth 2.0 Dynamic Client Registration according to RFC 7591. + */ +export async function registerClient(authorizationServerUrl, { metadata, clientMetadata, fetchFn }) { + let registrationUrl; + if (metadata) { + if (!metadata.registration_endpoint) { + throw new Error('Incompatible auth server: does not support dynamic client registration'); + } + registrationUrl = new URL(metadata.registration_endpoint); + } + else { + registrationUrl = new URL('/register', authorizationServerUrl); + } + const response = await (fetchFn ?? fetch)(registrationUrl, { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify(clientMetadata) + }); + if (!response.ok) { + throw await parseErrorResponse(response); + } + return OAuthClientInformationFullSchema.parse(await response.json()); +} +//# sourceMappingURL=auth.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js new file mode 100644 index 00000000..49b12c6c --- /dev/null +++ b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js @@ -0,0 +1,624 @@ +import { mergeCapabilities, Protocol } from '../shared/protocol.js'; +import { CallToolResultSchema, CompleteResultSchema, EmptyResultSchema, ErrorCode, GetPromptResultSchema, InitializeResultSchema, LATEST_PROTOCOL_VERSION, ListPromptsResultSchema, ListResourcesResultSchema, ListResourceTemplatesResultSchema, ListToolsResultSchema, McpError, ReadResourceResultSchema, SUPPORTED_PROTOCOL_VERSIONS, ElicitResultSchema, ElicitRequestSchema, CreateTaskResultSchema, CreateMessageRequestSchema, CreateMessageResultSchema, CreateMessageResultWithToolsSchema, ToolListChangedNotificationSchema, PromptListChangedNotificationSchema, ResourceListChangedNotificationSchema, ListChangedOptionsBaseSchema } from '../types.js'; +import { AjvJsonSchemaValidator } from '../validation/ajv-provider.js'; +import { getObjectShape, isZ4Schema, safeParse } from '../server/zod-compat.js'; +import { ExperimentalClientTasks } from '../experimental/tasks/client.js'; +import { assertToolsCallTaskCapability, assertClientRequestTaskCapability } from '../experimental/tasks/helpers.js'; +/** + * Elicitation default application helper. Applies defaults to the data based on the schema. + * + * @param schema - The schema to apply defaults to. + * @param data - The data to apply defaults to. + */ +function applyElicitationDefaults(schema, data) { + if (!schema || data === null || typeof data !== 'object') + return; + // Handle object properties + if (schema.type === 'object' && schema.properties && typeof schema.properties === 'object') { + const obj = data; + const props = schema.properties; + for (const key of Object.keys(props)) { + const propSchema = props[key]; + // If missing or explicitly undefined, apply default if present + if (obj[key] === undefined && Object.prototype.hasOwnProperty.call(propSchema, 'default')) { + obj[key] = propSchema.default; + } + // Recurse into existing nested objects/arrays + if (obj[key] !== undefined) { + applyElicitationDefaults(propSchema, obj[key]); + } + } + } + if (Array.isArray(schema.anyOf)) { + for (const sub of schema.anyOf) { + // Skip boolean schemas (true/false are valid JSON Schemas but have no defaults) + if (typeof sub !== 'boolean') { + applyElicitationDefaults(sub, data); + } + } + } + // Combine schemas + if (Array.isArray(schema.oneOf)) { + for (const sub of schema.oneOf) { + // Skip boolean schemas (true/false are valid JSON Schemas but have no defaults) + if (typeof sub !== 'boolean') { + applyElicitationDefaults(sub, data); + } + } + } +} +/** + * Determines which elicitation modes are supported based on declared client capabilities. + * + * According to the spec: + * - An empty elicitation capability object defaults to form mode support (backwards compatibility) + * - URL mode is only supported if explicitly declared + * + * @param capabilities - The client's elicitation capabilities + * @returns An object indicating which modes are supported + */ +export function getSupportedElicitationModes(capabilities) { + if (!capabilities) { + return { supportsFormMode: false, supportsUrlMode: false }; + } + const hasFormCapability = capabilities.form !== undefined; + const hasUrlCapability = capabilities.url !== undefined; + // If neither form nor url are explicitly declared, form mode is supported (backwards compatibility) + const supportsFormMode = hasFormCapability || (!hasFormCapability && !hasUrlCapability); + const supportsUrlMode = hasUrlCapability; + return { supportsFormMode, supportsUrlMode }; +} +/** + * An MCP client on top of a pluggable transport. + * + * The client will automatically begin the initialization flow with the server when connect() is called. + * + * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters: + * + * ```typescript + * // Custom schemas + * const CustomRequestSchema = RequestSchema.extend({...}) + * const CustomNotificationSchema = NotificationSchema.extend({...}) + * const CustomResultSchema = ResultSchema.extend({...}) + * + * // Type aliases + * type CustomRequest = z.infer + * type CustomNotification = z.infer + * type CustomResult = z.infer + * + * // Create typed client + * const client = new Client({ + * name: "CustomClient", + * version: "1.0.0" + * }) + * ``` + */ +export class Client extends Protocol { + /** + * Initializes this client with the given name and version information. + */ + constructor(_clientInfo, options) { + super(options); + this._clientInfo = _clientInfo; + this._cachedToolOutputValidators = new Map(); + this._cachedKnownTaskTools = new Set(); + this._cachedRequiredTaskTools = new Set(); + this._listChangedDebounceTimers = new Map(); + this._capabilities = options?.capabilities ?? {}; + this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator(); + // Store list changed config for setup after connection (when we know server capabilities) + if (options?.listChanged) { + this._pendingListChangedConfig = options.listChanged; + } + } + /** + * Set up handlers for list changed notifications based on config and server capabilities. + * This should only be called after initialization when server capabilities are known. + * Handlers are silently skipped if the server doesn't advertise the corresponding listChanged capability. + * @internal + */ + _setupListChangedHandlers(config) { + if (config.tools && this._serverCapabilities?.tools?.listChanged) { + this._setupListChangedHandler('tools', ToolListChangedNotificationSchema, config.tools, async () => { + const result = await this.listTools(); + return result.tools; + }); + } + if (config.prompts && this._serverCapabilities?.prompts?.listChanged) { + this._setupListChangedHandler('prompts', PromptListChangedNotificationSchema, config.prompts, async () => { + const result = await this.listPrompts(); + return result.prompts; + }); + } + if (config.resources && this._serverCapabilities?.resources?.listChanged) { + this._setupListChangedHandler('resources', ResourceListChangedNotificationSchema, config.resources, async () => { + const result = await this.listResources(); + return result.resources; + }); + } + } + /** + * Access experimental features. + * + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ + get experimental() { + if (!this._experimental) { + this._experimental = { + tasks: new ExperimentalClientTasks(this) + }; + } + return this._experimental; + } + /** + * Registers new capabilities. This can only be called before connecting to a transport. + * + * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). + */ + registerCapabilities(capabilities) { + if (this.transport) { + throw new Error('Cannot register capabilities after connecting to transport'); + } + this._capabilities = mergeCapabilities(this._capabilities, capabilities); + } + /** + * Override request handler registration to enforce client-side validation for elicitation. + */ + setRequestHandler(requestSchema, handler) { + const shape = getObjectShape(requestSchema); + const methodSchema = shape?.method; + if (!methodSchema) { + throw new Error('Schema is missing a method literal'); + } + // Extract literal value using type-safe property access + let methodValue; + if (isZ4Schema(methodSchema)) { + const v4Schema = methodSchema; + const v4Def = v4Schema._zod?.def; + methodValue = v4Def?.value ?? v4Schema.value; + } + else { + const v3Schema = methodSchema; + const legacyDef = v3Schema._def; + methodValue = legacyDef?.value ?? v3Schema.value; + } + if (typeof methodValue !== 'string') { + throw new Error('Schema method literal must be a string'); + } + const method = methodValue; + if (method === 'elicitation/create') { + const wrappedHandler = async (request, extra) => { + const validatedRequest = safeParse(ElicitRequestSchema, request); + if (!validatedRequest.success) { + // Type guard: if success is false, error is guaranteed to exist + const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation request: ${errorMessage}`); + } + const { params } = validatedRequest.data; + params.mode = params.mode ?? 'form'; + const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation); + if (params.mode === 'form' && !supportsFormMode) { + throw new McpError(ErrorCode.InvalidParams, 'Client does not support form-mode elicitation requests'); + } + if (params.mode === 'url' && !supportsUrlMode) { + throw new McpError(ErrorCode.InvalidParams, 'Client does not support URL-mode elicitation requests'); + } + const result = await Promise.resolve(handler(request, extra)); + // When task creation is requested, validate and return CreateTaskResult + if (params.task) { + const taskValidationResult = safeParse(CreateTaskResultSchema, result); + if (!taskValidationResult.success) { + const errorMessage = taskValidationResult.error instanceof Error + ? taskValidationResult.error.message + : String(taskValidationResult.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`); + } + return taskValidationResult.data; + } + // For non-task requests, validate against ElicitResultSchema + const validationResult = safeParse(ElicitResultSchema, result); + if (!validationResult.success) { + // Type guard: if success is false, error is guaranteed to exist + const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation result: ${errorMessage}`); + } + const validatedResult = validationResult.data; + const requestedSchema = params.mode === 'form' ? params.requestedSchema : undefined; + if (params.mode === 'form' && validatedResult.action === 'accept' && validatedResult.content && requestedSchema) { + if (this._capabilities.elicitation?.form?.applyDefaults) { + try { + applyElicitationDefaults(requestedSchema, validatedResult.content); + } + catch { + // gracefully ignore errors in default application + } + } + } + return validatedResult; + }; + // Install the wrapped handler + return super.setRequestHandler(requestSchema, wrappedHandler); + } + if (method === 'sampling/createMessage') { + const wrappedHandler = async (request, extra) => { + const validatedRequest = safeParse(CreateMessageRequestSchema, request); + if (!validatedRequest.success) { + const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid sampling request: ${errorMessage}`); + } + const { params } = validatedRequest.data; + const result = await Promise.resolve(handler(request, extra)); + // When task creation is requested, validate and return CreateTaskResult + if (params.task) { + const taskValidationResult = safeParse(CreateTaskResultSchema, result); + if (!taskValidationResult.success) { + const errorMessage = taskValidationResult.error instanceof Error + ? taskValidationResult.error.message + : String(taskValidationResult.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`); + } + return taskValidationResult.data; + } + // For non-task requests, validate against appropriate schema based on tools presence + const hasTools = params.tools || params.toolChoice; + const resultSchema = hasTools ? CreateMessageResultWithToolsSchema : CreateMessageResultSchema; + const validationResult = safeParse(resultSchema, result); + if (!validationResult.success) { + const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid sampling result: ${errorMessage}`); + } + return validationResult.data; + }; + // Install the wrapped handler + return super.setRequestHandler(requestSchema, wrappedHandler); + } + // Other handlers use default behavior + return super.setRequestHandler(requestSchema, handler); + } + assertCapability(capability, method) { + if (!this._serverCapabilities?.[capability]) { + throw new Error(`Server does not support ${capability} (required for ${method})`); + } + } + async connect(transport, options) { + await super.connect(transport); + // When transport sessionId is already set this means we are trying to reconnect. + // In this case we don't need to initialize again. + if (transport.sessionId !== undefined) { + return; + } + try { + const result = await this.request({ + method: 'initialize', + params: { + protocolVersion: LATEST_PROTOCOL_VERSION, + capabilities: this._capabilities, + clientInfo: this._clientInfo + } + }, InitializeResultSchema, options); + if (result === undefined) { + throw new Error(`Server sent invalid initialize result: ${result}`); + } + if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) { + throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`); + } + this._serverCapabilities = result.capabilities; + this._serverVersion = result.serverInfo; + // HTTP transports must set the protocol version in each header after initialization. + if (transport.setProtocolVersion) { + transport.setProtocolVersion(result.protocolVersion); + } + this._instructions = result.instructions; + await this.notification({ + method: 'notifications/initialized' + }); + // Set up list changed handlers now that we know server capabilities + if (this._pendingListChangedConfig) { + this._setupListChangedHandlers(this._pendingListChangedConfig); + this._pendingListChangedConfig = undefined; + } + } + catch (error) { + // Disconnect if initialization fails. + void this.close(); + throw error; + } + } + /** + * After initialization has completed, this will be populated with the server's reported capabilities. + */ + getServerCapabilities() { + return this._serverCapabilities; + } + /** + * After initialization has completed, this will be populated with information about the server's name and version. + */ + getServerVersion() { + return this._serverVersion; + } + /** + * After initialization has completed, this may be populated with information about the server's instructions. + */ + getInstructions() { + return this._instructions; + } + assertCapabilityForMethod(method) { + switch (method) { + case 'logging/setLevel': + if (!this._serverCapabilities?.logging) { + throw new Error(`Server does not support logging (required for ${method})`); + } + break; + case 'prompts/get': + case 'prompts/list': + if (!this._serverCapabilities?.prompts) { + throw new Error(`Server does not support prompts (required for ${method})`); + } + break; + case 'resources/list': + case 'resources/templates/list': + case 'resources/read': + case 'resources/subscribe': + case 'resources/unsubscribe': + if (!this._serverCapabilities?.resources) { + throw new Error(`Server does not support resources (required for ${method})`); + } + if (method === 'resources/subscribe' && !this._serverCapabilities.resources.subscribe) { + throw new Error(`Server does not support resource subscriptions (required for ${method})`); + } + break; + case 'tools/call': + case 'tools/list': + if (!this._serverCapabilities?.tools) { + throw new Error(`Server does not support tools (required for ${method})`); + } + break; + case 'completion/complete': + if (!this._serverCapabilities?.completions) { + throw new Error(`Server does not support completions (required for ${method})`); + } + break; + case 'initialize': + // No specific capability required for initialize + break; + case 'ping': + // No specific capability required for ping + break; + } + } + assertNotificationCapability(method) { + switch (method) { + case 'notifications/roots/list_changed': + if (!this._capabilities.roots?.listChanged) { + throw new Error(`Client does not support roots list changed notifications (required for ${method})`); + } + break; + case 'notifications/initialized': + // No specific capability required for initialized + break; + case 'notifications/cancelled': + // Cancellation notifications are always allowed + break; + case 'notifications/progress': + // Progress notifications are always allowed + break; + } + } + assertRequestHandlerCapability(method) { + // Task handlers are registered in Protocol constructor before _capabilities is initialized + // Skip capability check for task methods during initialization + if (!this._capabilities) { + return; + } + switch (method) { + case 'sampling/createMessage': + if (!this._capabilities.sampling) { + throw new Error(`Client does not support sampling capability (required for ${method})`); + } + break; + case 'elicitation/create': + if (!this._capabilities.elicitation) { + throw new Error(`Client does not support elicitation capability (required for ${method})`); + } + break; + case 'roots/list': + if (!this._capabilities.roots) { + throw new Error(`Client does not support roots capability (required for ${method})`); + } + break; + case 'tasks/get': + case 'tasks/list': + case 'tasks/result': + case 'tasks/cancel': + if (!this._capabilities.tasks) { + throw new Error(`Client does not support tasks capability (required for ${method})`); + } + break; + case 'ping': + // No specific capability required for ping + break; + } + } + assertTaskCapability(method) { + assertToolsCallTaskCapability(this._serverCapabilities?.tasks?.requests, method, 'Server'); + } + assertTaskHandlerCapability(method) { + // Task handlers are registered in Protocol constructor before _capabilities is initialized + // Skip capability check for task methods during initialization + if (!this._capabilities) { + return; + } + assertClientRequestTaskCapability(this._capabilities.tasks?.requests, method, 'Client'); + } + async ping(options) { + return this.request({ method: 'ping' }, EmptyResultSchema, options); + } + async complete(params, options) { + return this.request({ method: 'completion/complete', params }, CompleteResultSchema, options); + } + async setLoggingLevel(level, options) { + return this.request({ method: 'logging/setLevel', params: { level } }, EmptyResultSchema, options); + } + async getPrompt(params, options) { + return this.request({ method: 'prompts/get', params }, GetPromptResultSchema, options); + } + async listPrompts(params, options) { + return this.request({ method: 'prompts/list', params }, ListPromptsResultSchema, options); + } + async listResources(params, options) { + return this.request({ method: 'resources/list', params }, ListResourcesResultSchema, options); + } + async listResourceTemplates(params, options) { + return this.request({ method: 'resources/templates/list', params }, ListResourceTemplatesResultSchema, options); + } + async readResource(params, options) { + return this.request({ method: 'resources/read', params }, ReadResourceResultSchema, options); + } + async subscribeResource(params, options) { + return this.request({ method: 'resources/subscribe', params }, EmptyResultSchema, options); + } + async unsubscribeResource(params, options) { + return this.request({ method: 'resources/unsubscribe', params }, EmptyResultSchema, options); + } + /** + * Calls a tool and waits for the result. Automatically validates structured output if the tool has an outputSchema. + * + * For task-based execution with streaming behavior, use client.experimental.tasks.callToolStream() instead. + */ + async callTool(params, resultSchema = CallToolResultSchema, options) { + // Guard: required-task tools need experimental API + if (this.isToolTaskRequired(params.name)) { + throw new McpError(ErrorCode.InvalidRequest, `Tool "${params.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`); + } + const result = await this.request({ method: 'tools/call', params }, resultSchema, options); + // Check if the tool has an outputSchema + const validator = this.getToolOutputValidator(params.name); + if (validator) { + // If tool has outputSchema, it MUST return structuredContent (unless it's an error) + if (!result.structuredContent && !result.isError) { + throw new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`); + } + // Only validate structured content if present (not when there's an error) + if (result.structuredContent) { + try { + // Validate the structured content against the schema + const validationResult = validator(result.structuredContent); + if (!validationResult.valid) { + throw new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`); + } + } + catch (error) { + if (error instanceof McpError) { + throw error; + } + throw new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`); + } + } + } + return result; + } + isToolTask(toolName) { + if (!this._serverCapabilities?.tasks?.requests?.tools?.call) { + return false; + } + return this._cachedKnownTaskTools.has(toolName); + } + /** + * Check if a tool requires task-based execution. + * Unlike isToolTask which includes 'optional' tools, this only checks for 'required'. + */ + isToolTaskRequired(toolName) { + return this._cachedRequiredTaskTools.has(toolName); + } + /** + * Cache validators for tool output schemas. + * Called after listTools() to pre-compile validators for better performance. + */ + cacheToolMetadata(tools) { + this._cachedToolOutputValidators.clear(); + this._cachedKnownTaskTools.clear(); + this._cachedRequiredTaskTools.clear(); + for (const tool of tools) { + // If the tool has an outputSchema, create and cache the validator + if (tool.outputSchema) { + const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema); + this._cachedToolOutputValidators.set(tool.name, toolValidator); + } + // If the tool supports task-based execution, cache that information + const taskSupport = tool.execution?.taskSupport; + if (taskSupport === 'required' || taskSupport === 'optional') { + this._cachedKnownTaskTools.add(tool.name); + } + if (taskSupport === 'required') { + this._cachedRequiredTaskTools.add(tool.name); + } + } + } + /** + * Get cached validator for a tool + */ + getToolOutputValidator(toolName) { + return this._cachedToolOutputValidators.get(toolName); + } + async listTools(params, options) { + const result = await this.request({ method: 'tools/list', params }, ListToolsResultSchema, options); + // Cache the tools and their output schemas for future validation + this.cacheToolMetadata(result.tools); + return result; + } + /** + * Set up a single list changed handler. + * @internal + */ + _setupListChangedHandler(listType, notificationSchema, options, fetcher) { + // Validate options using Zod schema (validates autoRefresh and debounceMs) + const parseResult = ListChangedOptionsBaseSchema.safeParse(options); + if (!parseResult.success) { + throw new Error(`Invalid ${listType} listChanged options: ${parseResult.error.message}`); + } + // Validate callback + if (typeof options.onChanged !== 'function') { + throw new Error(`Invalid ${listType} listChanged options: onChanged must be a function`); + } + const { autoRefresh, debounceMs } = parseResult.data; + const { onChanged } = options; + const refresh = async () => { + if (!autoRefresh) { + onChanged(null, null); + return; + } + try { + const items = await fetcher(); + onChanged(null, items); + } + catch (e) { + const error = e instanceof Error ? e : new Error(String(e)); + onChanged(error, null); + } + }; + const handler = () => { + if (debounceMs) { + // Clear any pending debounce timer for this list type + const existingTimer = this._listChangedDebounceTimers.get(listType); + if (existingTimer) { + clearTimeout(existingTimer); + } + // Set up debounced refresh + const timer = setTimeout(refresh, debounceMs); + this._listChangedDebounceTimers.set(listType, timer); + } + else { + // No debounce, refresh immediately + refresh(); + } + }; + // Register notification handler + this.setNotificationHandler(notificationSchema, handler); + } + async sendRootsListChanged() { + return this.notification({ method: 'notifications/roots/list_changed' }); + } +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js new file mode 100644 index 00000000..58c47415 --- /dev/null +++ b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js @@ -0,0 +1,206 @@ +import { EventSource } from 'eventsource'; +import { createFetchWithInit, normalizeHeaders } from '../shared/transport.js'; +import { JSONRPCMessageSchema } from '../types.js'; +import { auth, extractWWWAuthenticateParams, UnauthorizedError } from './auth.js'; +export class SseError extends Error { + constructor(code, message, event) { + super(`SSE error: ${message}`); + this.code = code; + this.event = event; + } +} +/** + * Client transport for SSE: this will connect to a server using Server-Sent Events for receiving + * messages and make separate POST requests for sending messages. + * @deprecated SSEClientTransport is deprecated. Prefer to use StreamableHTTPClientTransport where possible instead. Note that because some servers are still using SSE, clients may need to support both transports during the migration period. + */ +export class SSEClientTransport { + constructor(url, opts) { + this._url = url; + this._resourceMetadataUrl = undefined; + this._scope = undefined; + this._eventSourceInit = opts?.eventSourceInit; + this._requestInit = opts?.requestInit; + this._authProvider = opts?.authProvider; + this._fetch = opts?.fetch; + this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit); + } + async _authThenStart() { + if (!this._authProvider) { + throw new UnauthorizedError('No auth provider'); + } + let result; + try { + result = await auth(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + } + catch (error) { + this.onerror?.(error); + throw error; + } + if (result !== 'AUTHORIZED') { + throw new UnauthorizedError(); + } + return await this._startOrAuth(); + } + async _commonHeaders() { + const headers = {}; + if (this._authProvider) { + const tokens = await this._authProvider.tokens(); + if (tokens) { + headers['Authorization'] = `Bearer ${tokens.access_token}`; + } + } + if (this._protocolVersion) { + headers['mcp-protocol-version'] = this._protocolVersion; + } + const extraHeaders = normalizeHeaders(this._requestInit?.headers); + return new Headers({ + ...headers, + ...extraHeaders + }); + } + _startOrAuth() { + const fetchImpl = (this?._eventSourceInit?.fetch ?? this._fetch ?? fetch); + return new Promise((resolve, reject) => { + this._eventSource = new EventSource(this._url.href, { + ...this._eventSourceInit, + fetch: async (url, init) => { + const headers = await this._commonHeaders(); + headers.set('Accept', 'text/event-stream'); + const response = await fetchImpl(url, { + ...init, + headers + }); + if (response.status === 401 && response.headers.has('www-authenticate')) { + const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response); + this._resourceMetadataUrl = resourceMetadataUrl; + this._scope = scope; + } + return response; + } + }); + this._abortController = new AbortController(); + this._eventSource.onerror = event => { + if (event.code === 401 && this._authProvider) { + this._authThenStart().then(resolve, reject); + return; + } + const error = new SseError(event.code, event.message, event); + reject(error); + this.onerror?.(error); + }; + this._eventSource.onopen = () => { + // The connection is open, but we need to wait for the endpoint to be received. + }; + this._eventSource.addEventListener('endpoint', (event) => { + const messageEvent = event; + try { + this._endpoint = new URL(messageEvent.data, this._url); + if (this._endpoint.origin !== this._url.origin) { + throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`); + } + } + catch (error) { + reject(error); + this.onerror?.(error); + void this.close(); + return; + } + resolve(); + }); + this._eventSource.onmessage = (event) => { + const messageEvent = event; + let message; + try { + message = JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data)); + } + catch (error) { + this.onerror?.(error); + return; + } + this.onmessage?.(message); + }; + }); + } + async start() { + if (this._eventSource) { + throw new Error('SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.'); + } + return await this._startOrAuth(); + } + /** + * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth. + */ + async finishAuth(authorizationCode) { + if (!this._authProvider) { + throw new UnauthorizedError('No auth provider'); + } + const result = await auth(this._authProvider, { + serverUrl: this._url, + authorizationCode, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + if (result !== 'AUTHORIZED') { + throw new UnauthorizedError('Failed to authorize'); + } + } + async close() { + this._abortController?.abort(); + this._eventSource?.close(); + this.onclose?.(); + } + async send(message) { + if (!this._endpoint) { + throw new Error('Not connected'); + } + try { + const headers = await this._commonHeaders(); + headers.set('content-type', 'application/json'); + const init = { + ...this._requestInit, + method: 'POST', + headers, + body: JSON.stringify(message), + signal: this._abortController?.signal + }; + const response = await (this._fetch ?? fetch)(this._endpoint, init); + if (!response.ok) { + const text = await response.text().catch(() => null); + if (response.status === 401 && this._authProvider) { + const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response); + this._resourceMetadataUrl = resourceMetadataUrl; + this._scope = scope; + const result = await auth(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + if (result !== 'AUTHORIZED') { + throw new UnauthorizedError(); + } + // Purposely _not_ awaited, so we don't call onerror twice + return this.send(message); + } + throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`); + } + // Release connection - POST responses don't have content we need + await response.body?.cancel(); + } + catch (error) { + this.onerror?.(error); + throw error; + } + } + setProtocolVersion(version) { + this._protocolVersion = version; + } +} +//# sourceMappingURL=sse.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js new file mode 100644 index 00000000..e1e4b9c6 --- /dev/null +++ b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js @@ -0,0 +1,191 @@ +import spawn from 'cross-spawn'; +import process from 'node:process'; +import { PassThrough } from 'node:stream'; +import { ReadBuffer, serializeMessage } from '../shared/stdio.js'; +/** + * Environment variables to inherit by default, if an environment is not explicitly given. + */ +export const DEFAULT_INHERITED_ENV_VARS = process.platform === 'win32' + ? [ + 'APPDATA', + 'HOMEDRIVE', + 'HOMEPATH', + 'LOCALAPPDATA', + 'PATH', + 'PROCESSOR_ARCHITECTURE', + 'SYSTEMDRIVE', + 'SYSTEMROOT', + 'TEMP', + 'USERNAME', + 'USERPROFILE', + 'PROGRAMFILES' + ] + : /* list inspired by the default env inheritance of sudo */ + ['HOME', 'LOGNAME', 'PATH', 'SHELL', 'TERM', 'USER']; +/** + * Returns a default environment object including only environment variables deemed safe to inherit. + */ +export function getDefaultEnvironment() { + const env = {}; + for (const key of DEFAULT_INHERITED_ENV_VARS) { + const value = process.env[key]; + if (value === undefined) { + continue; + } + if (value.startsWith('()')) { + // Skip functions, which are a security risk. + continue; + } + env[key] = value; + } + return env; +} +/** + * Client transport for stdio: this will connect to a server by spawning a process and communicating with it over stdin/stdout. + * + * This transport is only available in Node.js environments. + */ +export class StdioClientTransport { + constructor(server) { + this._readBuffer = new ReadBuffer(); + this._stderrStream = null; + this._serverParams = server; + if (server.stderr === 'pipe' || server.stderr === 'overlapped') { + this._stderrStream = new PassThrough(); + } + } + /** + * Starts the server process and prepares to communicate with it. + */ + async start() { + if (this._process) { + throw new Error('StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.'); + } + return new Promise((resolve, reject) => { + this._process = spawn(this._serverParams.command, this._serverParams.args ?? [], { + // merge default env with server env because mcp server needs some env vars + env: { + ...getDefaultEnvironment(), + ...this._serverParams.env + }, + stdio: ['pipe', 'pipe', this._serverParams.stderr ?? 'inherit'], + shell: false, + windowsHide: process.platform === 'win32' && isElectron(), + cwd: this._serverParams.cwd + }); + this._process.on('error', error => { + reject(error); + this.onerror?.(error); + }); + this._process.on('spawn', () => { + resolve(); + }); + this._process.on('close', _code => { + this._process = undefined; + this.onclose?.(); + }); + this._process.stdin?.on('error', error => { + this.onerror?.(error); + }); + this._process.stdout?.on('data', chunk => { + this._readBuffer.append(chunk); + this.processReadBuffer(); + }); + this._process.stdout?.on('error', error => { + this.onerror?.(error); + }); + if (this._stderrStream && this._process.stderr) { + this._process.stderr.pipe(this._stderrStream); + } + }); + } + /** + * The stderr stream of the child process, if `StdioServerParameters.stderr` was set to "pipe" or "overlapped". + * + * If stderr piping was requested, a PassThrough stream is returned _immediately_, allowing callers to + * attach listeners before the start method is invoked. This prevents loss of any early + * error output emitted by the child process. + */ + get stderr() { + if (this._stderrStream) { + return this._stderrStream; + } + return this._process?.stderr ?? null; + } + /** + * The child process pid spawned by this transport. + * + * This is only available after the transport has been started. + */ + get pid() { + return this._process?.pid ?? null; + } + processReadBuffer() { + while (true) { + try { + const message = this._readBuffer.readMessage(); + if (message === null) { + break; + } + this.onmessage?.(message); + } + catch (error) { + this.onerror?.(error); + } + } + } + async close() { + if (this._process) { + const processToClose = this._process; + this._process = undefined; + const closePromise = new Promise(resolve => { + processToClose.once('close', () => { + resolve(); + }); + }); + try { + processToClose.stdin?.end(); + } + catch { + // ignore + } + await Promise.race([closePromise, new Promise(resolve => setTimeout(resolve, 2000).unref())]); + if (processToClose.exitCode === null) { + try { + processToClose.kill('SIGTERM'); + } + catch { + // ignore + } + await Promise.race([closePromise, new Promise(resolve => setTimeout(resolve, 2000).unref())]); + } + if (processToClose.exitCode === null) { + try { + processToClose.kill('SIGKILL'); + } + catch { + // ignore + } + } + } + this._readBuffer.clear(); + } + send(message) { + return new Promise(resolve => { + if (!this._process?.stdin) { + throw new Error('Not connected'); + } + const json = serializeMessage(message); + if (this._process.stdin.write(json)) { + resolve(); + } + else { + this._process.stdin.once('drain', resolve); + } + }); + } +} +function isElectron() { + return 'type' in process; +} +//# sourceMappingURL=stdio.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js new file mode 100644 index 00000000..624172aa --- /dev/null +++ b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js @@ -0,0 +1,477 @@ +import { createFetchWithInit, normalizeHeaders } from '../shared/transport.js'; +import { isInitializedNotification, isJSONRPCRequest, isJSONRPCResultResponse, JSONRPCMessageSchema } from '../types.js'; +import { auth, extractWWWAuthenticateParams, UnauthorizedError } from './auth.js'; +import { EventSourceParserStream } from 'eventsource-parser/stream'; +// Default reconnection options for StreamableHTTP connections +const DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = { + initialReconnectionDelay: 1000, + maxReconnectionDelay: 30000, + reconnectionDelayGrowFactor: 1.5, + maxRetries: 2 +}; +export class StreamableHTTPError extends Error { + constructor(code, message) { + super(`Streamable HTTP error: ${message}`); + this.code = code; + } +} +/** + * Client transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification. + * It will connect to a server using HTTP POST for sending messages and HTTP GET with Server-Sent Events + * for receiving messages. + */ +export class StreamableHTTPClientTransport { + constructor(url, opts) { + this._hasCompletedAuthFlow = false; // Circuit breaker: detect auth success followed by immediate 401 + this._url = url; + this._resourceMetadataUrl = undefined; + this._scope = undefined; + this._requestInit = opts?.requestInit; + this._authProvider = opts?.authProvider; + this._fetch = opts?.fetch; + this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit); + this._sessionId = opts?.sessionId; + this._reconnectionOptions = opts?.reconnectionOptions ?? DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS; + } + async _authThenStart() { + if (!this._authProvider) { + throw new UnauthorizedError('No auth provider'); + } + let result; + try { + result = await auth(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + } + catch (error) { + this.onerror?.(error); + throw error; + } + if (result !== 'AUTHORIZED') { + throw new UnauthorizedError(); + } + return await this._startOrAuthSse({ resumptionToken: undefined }); + } + async _commonHeaders() { + const headers = {}; + if (this._authProvider) { + const tokens = await this._authProvider.tokens(); + if (tokens) { + headers['Authorization'] = `Bearer ${tokens.access_token}`; + } + } + if (this._sessionId) { + headers['mcp-session-id'] = this._sessionId; + } + if (this._protocolVersion) { + headers['mcp-protocol-version'] = this._protocolVersion; + } + const extraHeaders = normalizeHeaders(this._requestInit?.headers); + return new Headers({ + ...headers, + ...extraHeaders + }); + } + async _startOrAuthSse(options) { + const { resumptionToken } = options; + try { + // Try to open an initial SSE stream with GET to listen for server messages + // This is optional according to the spec - server may not support it + const headers = await this._commonHeaders(); + headers.set('Accept', 'text/event-stream'); + // Include Last-Event-ID header for resumable streams if provided + if (resumptionToken) { + headers.set('last-event-id', resumptionToken); + } + const response = await (this._fetch ?? fetch)(this._url, { + method: 'GET', + headers, + signal: this._abortController?.signal + }); + if (!response.ok) { + await response.body?.cancel(); + if (response.status === 401 && this._authProvider) { + // Need to authenticate + return await this._authThenStart(); + } + // 405 indicates that the server does not offer an SSE stream at GET endpoint + // This is an expected case that should not trigger an error + if (response.status === 405) { + return; + } + throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${response.statusText}`); + } + this._handleSseStream(response.body, options, true); + } + catch (error) { + this.onerror?.(error); + throw error; + } + } + /** + * Calculates the next reconnection delay using backoff algorithm + * + * @param attempt Current reconnection attempt count for the specific stream + * @returns Time to wait in milliseconds before next reconnection attempt + */ + _getNextReconnectionDelay(attempt) { + // Use server-provided retry value if available + if (this._serverRetryMs !== undefined) { + return this._serverRetryMs; + } + // Fall back to exponential backoff + const initialDelay = this._reconnectionOptions.initialReconnectionDelay; + const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor; + const maxDelay = this._reconnectionOptions.maxReconnectionDelay; + // Cap at maximum delay + return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay); + } + /** + * Schedule a reconnection attempt using server-provided retry interval or backoff + * + * @param lastEventId The ID of the last received event for resumability + * @param attemptCount Current reconnection attempt count for this specific stream + */ + _scheduleReconnection(options, attemptCount = 0) { + // Use provided options or default options + const maxRetries = this._reconnectionOptions.maxRetries; + // Check if we've exceeded maximum retry attempts + if (attemptCount >= maxRetries) { + this.onerror?.(new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`)); + return; + } + // Calculate next delay based on current attempt count + const delay = this._getNextReconnectionDelay(attemptCount); + // Schedule the reconnection + this._reconnectionTimeout = setTimeout(() => { + // Use the last event ID to resume where we left off + this._startOrAuthSse(options).catch(error => { + this.onerror?.(new Error(`Failed to reconnect SSE stream: ${error instanceof Error ? error.message : String(error)}`)); + // Schedule another attempt if this one failed, incrementing the attempt counter + this._scheduleReconnection(options, attemptCount + 1); + }); + }, delay); + } + _handleSseStream(stream, options, isReconnectable) { + if (!stream) { + return; + } + const { onresumptiontoken, replayMessageId } = options; + let lastEventId; + // Track whether we've received a priming event (event with ID) + // Per spec, server SHOULD send a priming event with ID before closing + let hasPrimingEvent = false; + // Track whether we've received a response - if so, no need to reconnect + // Reconnection is for when server disconnects BEFORE sending response + let receivedResponse = false; + const processStream = async () => { + // this is the closest we can get to trying to catch network errors + // if something happens reader will throw + try { + // Create a pipeline: binary stream -> text decoder -> SSE parser + const reader = stream + .pipeThrough(new TextDecoderStream()) + .pipeThrough(new EventSourceParserStream({ + onRetry: (retryMs) => { + // Capture server-provided retry value for reconnection timing + this._serverRetryMs = retryMs; + } + })) + .getReader(); + while (true) { + const { value: event, done } = await reader.read(); + if (done) { + break; + } + // Update last event ID if provided + if (event.id) { + lastEventId = event.id; + // Mark that we've received a priming event - stream is now resumable + hasPrimingEvent = true; + onresumptiontoken?.(event.id); + } + // Skip events with no data (priming events, keep-alives) + if (!event.data) { + continue; + } + if (!event.event || event.event === 'message') { + try { + const message = JSONRPCMessageSchema.parse(JSON.parse(event.data)); + if (isJSONRPCResultResponse(message)) { + // Mark that we received a response - no need to reconnect for this request + receivedResponse = true; + if (replayMessageId !== undefined) { + message.id = replayMessageId; + } + } + this.onmessage?.(message); + } + catch (error) { + this.onerror?.(error); + } + } + } + // Handle graceful server-side disconnect + // Server may close connection after sending event ID and retry field + // Reconnect if: already reconnectable (GET stream) OR received a priming event (POST stream with event ID) + // BUT don't reconnect if we already received a response - the request is complete + const canResume = isReconnectable || hasPrimingEvent; + const needsReconnect = canResume && !receivedResponse; + if (needsReconnect && this._abortController && !this._abortController.signal.aborted) { + this._scheduleReconnection({ + resumptionToken: lastEventId, + onresumptiontoken, + replayMessageId + }, 0); + } + } + catch (error) { + // Handle stream errors - likely a network disconnect + this.onerror?.(new Error(`SSE stream disconnected: ${error}`)); + // Attempt to reconnect if the stream disconnects unexpectedly and we aren't closing + // Reconnect if: already reconnectable (GET stream) OR received a priming event (POST stream with event ID) + // BUT don't reconnect if we already received a response - the request is complete + const canResume = isReconnectable || hasPrimingEvent; + const needsReconnect = canResume && !receivedResponse; + if (needsReconnect && this._abortController && !this._abortController.signal.aborted) { + // Use the exponential backoff reconnection strategy + try { + this._scheduleReconnection({ + resumptionToken: lastEventId, + onresumptiontoken, + replayMessageId + }, 0); + } + catch (error) { + this.onerror?.(new Error(`Failed to reconnect: ${error instanceof Error ? error.message : String(error)}`)); + } + } + } + }; + processStream(); + } + async start() { + if (this._abortController) { + throw new Error('StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.'); + } + this._abortController = new AbortController(); + } + /** + * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth. + */ + async finishAuth(authorizationCode) { + if (!this._authProvider) { + throw new UnauthorizedError('No auth provider'); + } + const result = await auth(this._authProvider, { + serverUrl: this._url, + authorizationCode, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + if (result !== 'AUTHORIZED') { + throw new UnauthorizedError('Failed to authorize'); + } + } + async close() { + if (this._reconnectionTimeout) { + clearTimeout(this._reconnectionTimeout); + this._reconnectionTimeout = undefined; + } + this._abortController?.abort(); + this.onclose?.(); + } + async send(message, options) { + try { + const { resumptionToken, onresumptiontoken } = options || {}; + if (resumptionToken) { + // If we have at last event ID, we need to reconnect the SSE stream + this._startOrAuthSse({ resumptionToken, replayMessageId: isJSONRPCRequest(message) ? message.id : undefined }).catch(err => this.onerror?.(err)); + return; + } + const headers = await this._commonHeaders(); + headers.set('content-type', 'application/json'); + headers.set('accept', 'application/json, text/event-stream'); + const init = { + ...this._requestInit, + method: 'POST', + headers, + body: JSON.stringify(message), + signal: this._abortController?.signal + }; + const response = await (this._fetch ?? fetch)(this._url, init); + // Handle session ID received during initialization + const sessionId = response.headers.get('mcp-session-id'); + if (sessionId) { + this._sessionId = sessionId; + } + if (!response.ok) { + const text = await response.text().catch(() => null); + if (response.status === 401 && this._authProvider) { + // Prevent infinite recursion when server returns 401 after successful auth + if (this._hasCompletedAuthFlow) { + throw new StreamableHTTPError(401, 'Server returned 401 after successful authentication'); + } + const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response); + this._resourceMetadataUrl = resourceMetadataUrl; + this._scope = scope; + const result = await auth(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + if (result !== 'AUTHORIZED') { + throw new UnauthorizedError(); + } + // Mark that we completed auth flow + this._hasCompletedAuthFlow = true; + // Purposely _not_ awaited, so we don't call onerror twice + return this.send(message); + } + if (response.status === 403 && this._authProvider) { + const { resourceMetadataUrl, scope, error } = extractWWWAuthenticateParams(response); + if (error === 'insufficient_scope') { + const wwwAuthHeader = response.headers.get('WWW-Authenticate'); + // Check if we've already tried upscoping with this header to prevent infinite loops. + if (this._lastUpscopingHeader === wwwAuthHeader) { + throw new StreamableHTTPError(403, 'Server returned 403 after trying upscoping'); + } + if (scope) { + this._scope = scope; + } + if (resourceMetadataUrl) { + this._resourceMetadataUrl = resourceMetadataUrl; + } + // Mark that upscoping was tried. + this._lastUpscopingHeader = wwwAuthHeader ?? undefined; + const result = await auth(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetch + }); + if (result !== 'AUTHORIZED') { + throw new UnauthorizedError(); + } + return this.send(message); + } + } + throw new StreamableHTTPError(response.status, `Error POSTing to endpoint: ${text}`); + } + // Reset auth loop flag on successful response + this._hasCompletedAuthFlow = false; + this._lastUpscopingHeader = undefined; + // If the response is 202 Accepted, there's no body to process + if (response.status === 202) { + await response.body?.cancel(); + // if the accepted notification is initialized, we start the SSE stream + // if it's supported by the server + if (isInitializedNotification(message)) { + // Start without a lastEventId since this is a fresh connection + this._startOrAuthSse({ resumptionToken: undefined }).catch(err => this.onerror?.(err)); + } + return; + } + // Get original message(s) for detecting request IDs + const messages = Array.isArray(message) ? message : [message]; + const hasRequests = messages.filter(msg => 'method' in msg && 'id' in msg && msg.id !== undefined).length > 0; + // Check the response type + const contentType = response.headers.get('content-type'); + if (hasRequests) { + if (contentType?.includes('text/event-stream')) { + // Handle SSE stream responses for requests + // We use the same handler as standalone streams, which now supports + // reconnection with the last event ID + this._handleSseStream(response.body, { onresumptiontoken }, false); + } + else if (contentType?.includes('application/json')) { + // For non-streaming servers, we might get direct JSON responses + const data = await response.json(); + const responseMessages = Array.isArray(data) + ? data.map(msg => JSONRPCMessageSchema.parse(msg)) + : [JSONRPCMessageSchema.parse(data)]; + for (const msg of responseMessages) { + this.onmessage?.(msg); + } + } + else { + await response.body?.cancel(); + throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType}`); + } + } + else { + // No requests in message but got 200 OK - still need to release connection + await response.body?.cancel(); + } + } + catch (error) { + this.onerror?.(error); + throw error; + } + } + get sessionId() { + return this._sessionId; + } + /** + * Terminates the current session by sending a DELETE request to the server. + * + * Clients that no longer need a particular session + * (e.g., because the user is leaving the client application) SHOULD send an + * HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly + * terminate the session. + * + * The server MAY respond with HTTP 405 Method Not Allowed, indicating that + * the server does not allow clients to terminate sessions. + */ + async terminateSession() { + if (!this._sessionId) { + return; // No session to terminate + } + try { + const headers = await this._commonHeaders(); + const init = { + ...this._requestInit, + method: 'DELETE', + headers, + signal: this._abortController?.signal + }; + const response = await (this._fetch ?? fetch)(this._url, init); + await response.body?.cancel(); + // We specifically handle 405 as a valid response according to the spec, + // meaning the server does not support explicit session termination + if (!response.ok && response.status !== 405) { + throw new StreamableHTTPError(response.status, `Failed to terminate session: ${response.statusText}`); + } + this._sessionId = undefined; + } + catch (error) { + this.onerror?.(error); + throw error; + } + } + setProtocolVersion(version) { + this._protocolVersion = version; + } + get protocolVersion() { + return this._protocolVersion; + } + /** + * Resume an SSE stream from a previous event ID. + * Opens a GET SSE connection with Last-Event-ID header to replay missed events. + * + * @param lastEventId The event ID to resume from + * @param options Optional callback to receive new resumption tokens + */ + async resumeStream(lastEventId, options) { + await this._startOrAuthSse({ + resumptionToken: lastEventId, + onresumptiontoken: options?.onresumptiontoken + }); + } +} +//# sourceMappingURL=streamableHttp.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js new file mode 100644 index 00000000..0c1d8af7 --- /dev/null +++ b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js @@ -0,0 +1,184 @@ +/** + * Experimental client task features for MCP SDK. + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ +import { CallToolResultSchema, McpError, ErrorCode } from '../../types.js'; +/** + * Experimental task features for MCP clients. + * + * Access via `client.experimental.tasks`: + * ```typescript + * const stream = client.experimental.tasks.callToolStream({ name: 'tool', arguments: {} }); + * const task = await client.experimental.tasks.getTask(taskId); + * ``` + * + * @experimental + */ +export class ExperimentalClientTasks { + constructor(_client) { + this._client = _client; + } + /** + * Calls a tool and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * This method provides streaming access to tool execution, allowing you to + * observe intermediate task status updates for long-running tool calls. + * Automatically validates structured output if the tool has an outputSchema. + * + * @example + * ```typescript + * const stream = client.experimental.tasks.callToolStream({ name: 'myTool', arguments: {} }); + * for await (const message of stream) { + * switch (message.type) { + * case 'taskCreated': + * console.log('Tool execution started:', message.task.taskId); + * break; + * case 'taskStatus': + * console.log('Tool status:', message.task.status); + * break; + * case 'result': + * console.log('Tool result:', message.result); + * break; + * case 'error': + * console.error('Tool error:', message.error); + * break; + * } + * } + * ``` + * + * @param params - Tool call parameters (name and arguments) + * @param resultSchema - Zod schema for validating the result (defaults to CallToolResultSchema) + * @param options - Optional request options (timeout, signal, task creation params, etc.) + * @returns AsyncGenerator that yields ResponseMessage objects + * + * @experimental + */ + async *callToolStream(params, resultSchema = CallToolResultSchema, options) { + // Access Client's internal methods + const clientInternal = this._client; + // Add task creation parameters if server supports it and not explicitly provided + const optionsWithTask = { + ...options, + // We check if the tool is known to be a task during auto-configuration, but assume + // the caller knows what they're doing if they pass this explicitly + task: options?.task ?? (clientInternal.isToolTask(params.name) ? {} : undefined) + }; + const stream = clientInternal.requestStream({ method: 'tools/call', params }, resultSchema, optionsWithTask); + // Get the validator for this tool (if it has an output schema) + const validator = clientInternal.getToolOutputValidator(params.name); + // Iterate through the stream and validate the final result if needed + for await (const message of stream) { + // If this is a result message and the tool has an output schema, validate it + if (message.type === 'result' && validator) { + const result = message.result; + // If tool has outputSchema, it MUST return structuredContent (unless it's an error) + if (!result.structuredContent && !result.isError) { + yield { + type: 'error', + error: new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`) + }; + return; + } + // Only validate structured content if present (not when there's an error) + if (result.structuredContent) { + try { + // Validate the structured content against the schema + const validationResult = validator(result.structuredContent); + if (!validationResult.valid) { + yield { + type: 'error', + error: new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`) + }; + return; + } + } + catch (error) { + if (error instanceof McpError) { + yield { type: 'error', error }; + return; + } + yield { + type: 'error', + error: new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`) + }; + return; + } + } + } + // Yield the message (either validated result or any other message type) + yield message; + } + } + /** + * Gets the current status of a task. + * + * @param taskId - The task identifier + * @param options - Optional request options + * @returns The task status + * + * @experimental + */ + async getTask(taskId, options) { + return this._client.getTask({ taskId }, options); + } + /** + * Retrieves the result of a completed task. + * + * @param taskId - The task identifier + * @param resultSchema - Zod schema for validating the result + * @param options - Optional request options + * @returns The task result + * + * @experimental + */ + async getTaskResult(taskId, resultSchema, options) { + // Delegate to the client's underlying Protocol method + return this._client.getTaskResult({ taskId }, resultSchema, options); + } + /** + * Lists tasks with optional pagination. + * + * @param cursor - Optional pagination cursor + * @param options - Optional request options + * @returns List of tasks with optional next cursor + * + * @experimental + */ + async listTasks(cursor, options) { + // Delegate to the client's underlying Protocol method + return this._client.listTasks(cursor ? { cursor } : undefined, options); + } + /** + * Cancels a running task. + * + * @param taskId - The task identifier + * @param options - Optional request options + * + * @experimental + */ + async cancelTask(taskId, options) { + // Delegate to the client's underlying Protocol method + return this._client.cancelTask({ taskId }, options); + } + /** + * Sends a request and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * This method provides streaming access to request processing, allowing you to + * observe intermediate task status updates for task-augmented requests. + * + * @param request - The request to send + * @param resultSchema - Zod schema for validating the result + * @param options - Optional request options (timeout, signal, task creation params, etc.) + * @returns AsyncGenerator that yields ResponseMessage objects + * + * @experimental + */ + requestStream(request, resultSchema, options) { + return this._client.requestStream(request, resultSchema, options); + } +} +//# sourceMappingURL=client.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js new file mode 100644 index 00000000..38800311 --- /dev/null +++ b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js @@ -0,0 +1,64 @@ +/** + * Experimental task capability assertion helpers. + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ +/** + * Asserts that task creation is supported for tools/call. + * Used by Client.assertTaskCapability and Server.assertTaskHandlerCapability. + * + * @param requests - The task requests capability object + * @param method - The method being checked + * @param entityName - 'Server' or 'Client' for error messages + * @throws Error if the capability is not supported + * + * @experimental + */ +export function assertToolsCallTaskCapability(requests, method, entityName) { + if (!requests) { + throw new Error(`${entityName} does not support task creation (required for ${method})`); + } + switch (method) { + case 'tools/call': + if (!requests.tools?.call) { + throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`); + } + break; + default: + // Method doesn't support tasks, which is fine - no error + break; + } +} +/** + * Asserts that task creation is supported for sampling/createMessage or elicitation/create. + * Used by Server.assertTaskCapability and Client.assertTaskHandlerCapability. + * + * @param requests - The task requests capability object + * @param method - The method being checked + * @param entityName - 'Server' or 'Client' for error messages + * @throws Error if the capability is not supported + * + * @experimental + */ +export function assertClientRequestTaskCapability(requests, method, entityName) { + if (!requests) { + throw new Error(`${entityName} does not support task creation (required for ${method})`); + } + switch (method) { + case 'sampling/createMessage': + if (!requests.sampling?.createMessage) { + throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`); + } + break; + case 'elicitation/create': + if (!requests.elicitation?.create) { + throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`); + } + break; + default: + // Method doesn't support tasks, which is fine - no error + break; + } +} +//# sourceMappingURL=helpers.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js new file mode 100644 index 00000000..d4949de6 --- /dev/null +++ b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js @@ -0,0 +1,16 @@ +/** + * Experimental task interfaces for MCP SDK. + * WARNING: These APIs are experimental and may change without notice. + */ +/** + * Checks if a task status represents a terminal state. + * Terminal states are those where the task has finished and will not change. + * + * @param status - The task status to check + * @returns True if the status is terminal (completed, failed, or cancelled) + * @experimental + */ +export function isTerminal(status) { + return status === 'completed' || status === 'failed' || status === 'cancelled'; +} +//# sourceMappingURL=interfaces.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js new file mode 100644 index 00000000..059ab7b1 --- /dev/null +++ b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js @@ -0,0 +1,246 @@ +/** + * Experimental server task features for MCP SDK. + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ +import { CreateMessageResultSchema, ElicitResultSchema } from '../../types.js'; +/** + * Experimental task features for low-level MCP servers. + * + * Access via `server.experimental.tasks`: + * ```typescript + * const stream = server.experimental.tasks.requestStream(request, schema, options); + * ``` + * + * For high-level server usage with task-based tools, use `McpServer.experimental.tasks` instead. + * + * @experimental + */ +export class ExperimentalServerTasks { + constructor(_server) { + this._server = _server; + } + /** + * Sends a request and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * This method provides streaming access to request processing, allowing you to + * observe intermediate task status updates for task-augmented requests. + * + * @param request - The request to send + * @param resultSchema - Zod schema for validating the result + * @param options - Optional request options (timeout, signal, task creation params, etc.) + * @returns AsyncGenerator that yields ResponseMessage objects + * + * @experimental + */ + requestStream(request, resultSchema, options) { + return this._server.requestStream(request, resultSchema, options); + } + /** + * Sends a sampling request and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * For task-augmented requests, yields 'taskCreated' and 'taskStatus' messages + * before the final result. + * + * @example + * ```typescript + * const stream = server.experimental.tasks.createMessageStream({ + * messages: [{ role: 'user', content: { type: 'text', text: 'Hello' } }], + * maxTokens: 100 + * }, { + * onprogress: (progress) => { + * // Handle streaming tokens via progress notifications + * console.log('Progress:', progress.message); + * } + * }); + * + * for await (const message of stream) { + * switch (message.type) { + * case 'taskCreated': + * console.log('Task created:', message.task.taskId); + * break; + * case 'taskStatus': + * console.log('Task status:', message.task.status); + * break; + * case 'result': + * console.log('Final result:', message.result); + * break; + * case 'error': + * console.error('Error:', message.error); + * break; + * } + * } + * ``` + * + * @param params - The sampling request parameters + * @param options - Optional request options (timeout, signal, task creation params, onprogress, etc.) + * @returns AsyncGenerator that yields ResponseMessage objects + * + * @experimental + */ + createMessageStream(params, options) { + // Access client capabilities via the server + const clientCapabilities = this._server.getClientCapabilities(); + // Capability check - only required when tools/toolChoice are provided + if ((params.tools || params.toolChoice) && !clientCapabilities?.sampling?.tools) { + throw new Error('Client does not support sampling tools capability.'); + } + // Message structure validation - always validate tool_use/tool_result pairs. + // These may appear even without tools/toolChoice in the current request when + // a previous sampling request returned tool_use and this is a follow-up with results. + if (params.messages.length > 0) { + const lastMessage = params.messages[params.messages.length - 1]; + const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content]; + const hasToolResults = lastContent.some(c => c.type === 'tool_result'); + const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : undefined; + const previousContent = previousMessage + ? Array.isArray(previousMessage.content) + ? previousMessage.content + : [previousMessage.content] + : []; + const hasPreviousToolUse = previousContent.some(c => c.type === 'tool_use'); + if (hasToolResults) { + if (lastContent.some(c => c.type !== 'tool_result')) { + throw new Error('The last message must contain only tool_result content if any is present'); + } + if (!hasPreviousToolUse) { + throw new Error('tool_result blocks are not matching any tool_use from the previous message'); + } + } + if (hasPreviousToolUse) { + // Extract tool_use IDs from previous message and tool_result IDs from current message + const toolUseIds = new Set(previousContent.filter(c => c.type === 'tool_use').map(c => c.id)); + const toolResultIds = new Set(lastContent.filter(c => c.type === 'tool_result').map(c => c.toolUseId)); + if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every(id => toolResultIds.has(id))) { + throw new Error('ids of tool_result blocks and tool_use blocks from previous message do not match'); + } + } + } + return this.requestStream({ + method: 'sampling/createMessage', + params + }, CreateMessageResultSchema, options); + } + /** + * Sends an elicitation request and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * For task-augmented requests (especially URL-based elicitation), yields 'taskCreated' + * and 'taskStatus' messages before the final result. + * + * @example + * ```typescript + * const stream = server.experimental.tasks.elicitInputStream({ + * mode: 'url', + * message: 'Please authenticate', + * elicitationId: 'auth-123', + * url: 'https://example.com/auth' + * }, { + * task: { ttl: 300000 } // Task-augmented for long-running auth flow + * }); + * + * for await (const message of stream) { + * switch (message.type) { + * case 'taskCreated': + * console.log('Task created:', message.task.taskId); + * break; + * case 'taskStatus': + * console.log('Task status:', message.task.status); + * break; + * case 'result': + * console.log('User action:', message.result.action); + * break; + * case 'error': + * console.error('Error:', message.error); + * break; + * } + * } + * ``` + * + * @param params - The elicitation request parameters + * @param options - Optional request options (timeout, signal, task creation params, etc.) + * @returns AsyncGenerator that yields ResponseMessage objects + * + * @experimental + */ + elicitInputStream(params, options) { + // Access client capabilities via the server + const clientCapabilities = this._server.getClientCapabilities(); + const mode = params.mode ?? 'form'; + // Capability check based on mode + switch (mode) { + case 'url': { + if (!clientCapabilities?.elicitation?.url) { + throw new Error('Client does not support url elicitation.'); + } + break; + } + case 'form': { + if (!clientCapabilities?.elicitation?.form) { + throw new Error('Client does not support form elicitation.'); + } + break; + } + } + // Normalize params to ensure mode is set for form mode (defaults to 'form' per spec) + const normalizedParams = mode === 'form' && params.mode === undefined ? { ...params, mode: 'form' } : params; + // Cast to ServerRequest needed because TypeScript can't narrow the union type + // based on the discriminated 'method' field when constructing the object literal + return this.requestStream({ + method: 'elicitation/create', + params: normalizedParams + }, ElicitResultSchema, options); + } + /** + * Gets the current status of a task. + * + * @param taskId - The task identifier + * @param options - Optional request options + * @returns The task status + * + * @experimental + */ + async getTask(taskId, options) { + return this._server.getTask({ taskId }, options); + } + /** + * Retrieves the result of a completed task. + * + * @param taskId - The task identifier + * @param resultSchema - Zod schema for validating the result + * @param options - Optional request options + * @returns The task result + * + * @experimental + */ + async getTaskResult(taskId, resultSchema, options) { + return this._server.getTaskResult({ taskId }, resultSchema, options); + } + /** + * Lists tasks with optional pagination. + * + * @param cursor - Optional pagination cursor + * @param options - Optional request options + * @returns List of tasks with optional next cursor + * + * @experimental + */ + async listTasks(cursor, options) { + return this._server.listTasks(cursor ? { cursor } : undefined, options); + } + /** + * Cancels a running task. + * + * @param taskId - The task identifier + * @param options - Optional request options + * + * @experimental + */ + async cancelTask(taskId, options) { + return this._server.cancelTask({ taskId }, options); + } +} +//# sourceMappingURL=server.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js new file mode 100644 index 00000000..7106ab98 --- /dev/null +++ b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js @@ -0,0 +1,180 @@ +/** + * Base class for all OAuth errors + */ +export class OAuthError extends Error { + constructor(message, errorUri) { + super(message); + this.errorUri = errorUri; + this.name = this.constructor.name; + } + /** + * Converts the error to a standard OAuth error response object + */ + toResponseObject() { + const response = { + error: this.errorCode, + error_description: this.message + }; + if (this.errorUri) { + response.error_uri = this.errorUri; + } + return response; + } + get errorCode() { + return this.constructor.errorCode; + } +} +/** + * Invalid request error - The request is missing a required parameter, + * includes an invalid parameter value, includes a parameter more than once, + * or is otherwise malformed. + */ +export class InvalidRequestError extends OAuthError { +} +InvalidRequestError.errorCode = 'invalid_request'; +/** + * Invalid client error - Client authentication failed (e.g., unknown client, no client + * authentication included, or unsupported authentication method). + */ +export class InvalidClientError extends OAuthError { +} +InvalidClientError.errorCode = 'invalid_client'; +/** + * Invalid grant error - The provided authorization grant or refresh token is + * invalid, expired, revoked, does not match the redirection URI used in the + * authorization request, or was issued to another client. + */ +export class InvalidGrantError extends OAuthError { +} +InvalidGrantError.errorCode = 'invalid_grant'; +/** + * Unauthorized client error - The authenticated client is not authorized to use + * this authorization grant type. + */ +export class UnauthorizedClientError extends OAuthError { +} +UnauthorizedClientError.errorCode = 'unauthorized_client'; +/** + * Unsupported grant type error - The authorization grant type is not supported + * by the authorization server. + */ +export class UnsupportedGrantTypeError extends OAuthError { +} +UnsupportedGrantTypeError.errorCode = 'unsupported_grant_type'; +/** + * Invalid scope error - The requested scope is invalid, unknown, malformed, or + * exceeds the scope granted by the resource owner. + */ +export class InvalidScopeError extends OAuthError { +} +InvalidScopeError.errorCode = 'invalid_scope'; +/** + * Access denied error - The resource owner or authorization server denied the request. + */ +export class AccessDeniedError extends OAuthError { +} +AccessDeniedError.errorCode = 'access_denied'; +/** + * Server error - The authorization server encountered an unexpected condition + * that prevented it from fulfilling the request. + */ +export class ServerError extends OAuthError { +} +ServerError.errorCode = 'server_error'; +/** + * Temporarily unavailable error - The authorization server is currently unable to + * handle the request due to a temporary overloading or maintenance of the server. + */ +export class TemporarilyUnavailableError extends OAuthError { +} +TemporarilyUnavailableError.errorCode = 'temporarily_unavailable'; +/** + * Unsupported response type error - The authorization server does not support + * obtaining an authorization code using this method. + */ +export class UnsupportedResponseTypeError extends OAuthError { +} +UnsupportedResponseTypeError.errorCode = 'unsupported_response_type'; +/** + * Unsupported token type error - The authorization server does not support + * the requested token type. + */ +export class UnsupportedTokenTypeError extends OAuthError { +} +UnsupportedTokenTypeError.errorCode = 'unsupported_token_type'; +/** + * Invalid token error - The access token provided is expired, revoked, malformed, + * or invalid for other reasons. + */ +export class InvalidTokenError extends OAuthError { +} +InvalidTokenError.errorCode = 'invalid_token'; +/** + * Method not allowed error - The HTTP method used is not allowed for this endpoint. + * (Custom, non-standard error) + */ +export class MethodNotAllowedError extends OAuthError { +} +MethodNotAllowedError.errorCode = 'method_not_allowed'; +/** + * Too many requests error - Rate limit exceeded. + * (Custom, non-standard error based on RFC 6585) + */ +export class TooManyRequestsError extends OAuthError { +} +TooManyRequestsError.errorCode = 'too_many_requests'; +/** + * Invalid client metadata error - The client metadata is invalid. + * (Custom error for dynamic client registration - RFC 7591) + */ +export class InvalidClientMetadataError extends OAuthError { +} +InvalidClientMetadataError.errorCode = 'invalid_client_metadata'; +/** + * Insufficient scope error - The request requires higher privileges than provided by the access token. + */ +export class InsufficientScopeError extends OAuthError { +} +InsufficientScopeError.errorCode = 'insufficient_scope'; +/** + * Invalid target error - The requested resource is invalid, missing, unknown, or malformed. + * (Custom error for resource indicators - RFC 8707) + */ +export class InvalidTargetError extends OAuthError { +} +InvalidTargetError.errorCode = 'invalid_target'; +/** + * A utility class for defining one-off error codes + */ +export class CustomOAuthError extends OAuthError { + constructor(customErrorCode, message, errorUri) { + super(message, errorUri); + this.customErrorCode = customErrorCode; + } + get errorCode() { + return this.customErrorCode; + } +} +/** + * A full list of all OAuthErrors, enabling parsing from error responses + */ +export const OAUTH_ERRORS = { + [InvalidRequestError.errorCode]: InvalidRequestError, + [InvalidClientError.errorCode]: InvalidClientError, + [InvalidGrantError.errorCode]: InvalidGrantError, + [UnauthorizedClientError.errorCode]: UnauthorizedClientError, + [UnsupportedGrantTypeError.errorCode]: UnsupportedGrantTypeError, + [InvalidScopeError.errorCode]: InvalidScopeError, + [AccessDeniedError.errorCode]: AccessDeniedError, + [ServerError.errorCode]: ServerError, + [TemporarilyUnavailableError.errorCode]: TemporarilyUnavailableError, + [UnsupportedResponseTypeError.errorCode]: UnsupportedResponseTypeError, + [UnsupportedTokenTypeError.errorCode]: UnsupportedTokenTypeError, + [InvalidTokenError.errorCode]: InvalidTokenError, + [MethodNotAllowedError.errorCode]: MethodNotAllowedError, + [TooManyRequestsError.errorCode]: TooManyRequestsError, + [InvalidClientMetadataError.errorCode]: InvalidClientMetadataError, + [InsufficientScopeError.errorCode]: InsufficientScopeError, + [InvalidTargetError.errorCode]: InvalidTargetError +}; +//# sourceMappingURL=errors.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js new file mode 100644 index 00000000..51d060e5 --- /dev/null +++ b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js @@ -0,0 +1,440 @@ +import { mergeCapabilities, Protocol } from '../shared/protocol.js'; +import { CreateMessageResultSchema, CreateMessageResultWithToolsSchema, ElicitResultSchema, EmptyResultSchema, ErrorCode, InitializedNotificationSchema, InitializeRequestSchema, LATEST_PROTOCOL_VERSION, ListRootsResultSchema, LoggingLevelSchema, McpError, SetLevelRequestSchema, SUPPORTED_PROTOCOL_VERSIONS, CallToolRequestSchema, CallToolResultSchema, CreateTaskResultSchema } from '../types.js'; +import { AjvJsonSchemaValidator } from '../validation/ajv-provider.js'; +import { getObjectShape, isZ4Schema, safeParse } from './zod-compat.js'; +import { ExperimentalServerTasks } from '../experimental/tasks/server.js'; +import { assertToolsCallTaskCapability, assertClientRequestTaskCapability } from '../experimental/tasks/helpers.js'; +/** + * An MCP server on top of a pluggable transport. + * + * This server will automatically respond to the initialization flow as initiated from the client. + * + * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters: + * + * ```typescript + * // Custom schemas + * const CustomRequestSchema = RequestSchema.extend({...}) + * const CustomNotificationSchema = NotificationSchema.extend({...}) + * const CustomResultSchema = ResultSchema.extend({...}) + * + * // Type aliases + * type CustomRequest = z.infer + * type CustomNotification = z.infer + * type CustomResult = z.infer + * + * // Create typed server + * const server = new Server({ + * name: "CustomServer", + * version: "1.0.0" + * }) + * ``` + * @deprecated Use `McpServer` instead for the high-level API. Only use `Server` for advanced use cases. + */ +export class Server extends Protocol { + /** + * Initializes this server with the given name and version information. + */ + constructor(_serverInfo, options) { + super(options); + this._serverInfo = _serverInfo; + // Map log levels by session id + this._loggingLevels = new Map(); + // Map LogLevelSchema to severity index + this.LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index])); + // Is a message with the given level ignored in the log level set for the given session id? + this.isMessageIgnored = (level, sessionId) => { + const currentLevel = this._loggingLevels.get(sessionId); + return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false; + }; + this._capabilities = options?.capabilities ?? {}; + this._instructions = options?.instructions; + this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator(); + this.setRequestHandler(InitializeRequestSchema, request => this._oninitialize(request)); + this.setNotificationHandler(InitializedNotificationSchema, () => this.oninitialized?.()); + if (this._capabilities.logging) { + this.setRequestHandler(SetLevelRequestSchema, async (request, extra) => { + const transportSessionId = extra.sessionId || extra.requestInfo?.headers['mcp-session-id'] || undefined; + const { level } = request.params; + const parseResult = LoggingLevelSchema.safeParse(level); + if (parseResult.success) { + this._loggingLevels.set(transportSessionId, parseResult.data); + } + return {}; + }); + } + } + /** + * Access experimental features. + * + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ + get experimental() { + if (!this._experimental) { + this._experimental = { + tasks: new ExperimentalServerTasks(this) + }; + } + return this._experimental; + } + /** + * Registers new capabilities. This can only be called before connecting to a transport. + * + * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). + */ + registerCapabilities(capabilities) { + if (this.transport) { + throw new Error('Cannot register capabilities after connecting to transport'); + } + this._capabilities = mergeCapabilities(this._capabilities, capabilities); + } + /** + * Override request handler registration to enforce server-side validation for tools/call. + */ + setRequestHandler(requestSchema, handler) { + const shape = getObjectShape(requestSchema); + const methodSchema = shape?.method; + if (!methodSchema) { + throw new Error('Schema is missing a method literal'); + } + // Extract literal value using type-safe property access + let methodValue; + if (isZ4Schema(methodSchema)) { + const v4Schema = methodSchema; + const v4Def = v4Schema._zod?.def; + methodValue = v4Def?.value ?? v4Schema.value; + } + else { + const v3Schema = methodSchema; + const legacyDef = v3Schema._def; + methodValue = legacyDef?.value ?? v3Schema.value; + } + if (typeof methodValue !== 'string') { + throw new Error('Schema method literal must be a string'); + } + const method = methodValue; + if (method === 'tools/call') { + const wrappedHandler = async (request, extra) => { + const validatedRequest = safeParse(CallToolRequestSchema, request); + if (!validatedRequest.success) { + const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call request: ${errorMessage}`); + } + const { params } = validatedRequest.data; + const result = await Promise.resolve(handler(request, extra)); + // When task creation is requested, validate and return CreateTaskResult + if (params.task) { + const taskValidationResult = safeParse(CreateTaskResultSchema, result); + if (!taskValidationResult.success) { + const errorMessage = taskValidationResult.error instanceof Error + ? taskValidationResult.error.message + : String(taskValidationResult.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`); + } + return taskValidationResult.data; + } + // For non-task requests, validate against CallToolResultSchema + const validationResult = safeParse(CallToolResultSchema, result); + if (!validationResult.success) { + const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call result: ${errorMessage}`); + } + return validationResult.data; + }; + // Install the wrapped handler + return super.setRequestHandler(requestSchema, wrappedHandler); + } + // Other handlers use default behavior + return super.setRequestHandler(requestSchema, handler); + } + assertCapabilityForMethod(method) { + switch (method) { + case 'sampling/createMessage': + if (!this._clientCapabilities?.sampling) { + throw new Error(`Client does not support sampling (required for ${method})`); + } + break; + case 'elicitation/create': + if (!this._clientCapabilities?.elicitation) { + throw new Error(`Client does not support elicitation (required for ${method})`); + } + break; + case 'roots/list': + if (!this._clientCapabilities?.roots) { + throw new Error(`Client does not support listing roots (required for ${method})`); + } + break; + case 'ping': + // No specific capability required for ping + break; + } + } + assertNotificationCapability(method) { + switch (method) { + case 'notifications/message': + if (!this._capabilities.logging) { + throw new Error(`Server does not support logging (required for ${method})`); + } + break; + case 'notifications/resources/updated': + case 'notifications/resources/list_changed': + if (!this._capabilities.resources) { + throw new Error(`Server does not support notifying about resources (required for ${method})`); + } + break; + case 'notifications/tools/list_changed': + if (!this._capabilities.tools) { + throw new Error(`Server does not support notifying of tool list changes (required for ${method})`); + } + break; + case 'notifications/prompts/list_changed': + if (!this._capabilities.prompts) { + throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`); + } + break; + case 'notifications/elicitation/complete': + if (!this._clientCapabilities?.elicitation?.url) { + throw new Error(`Client does not support URL elicitation (required for ${method})`); + } + break; + case 'notifications/cancelled': + // Cancellation notifications are always allowed + break; + case 'notifications/progress': + // Progress notifications are always allowed + break; + } + } + assertRequestHandlerCapability(method) { + // Task handlers are registered in Protocol constructor before _capabilities is initialized + // Skip capability check for task methods during initialization + if (!this._capabilities) { + return; + } + switch (method) { + case 'completion/complete': + if (!this._capabilities.completions) { + throw new Error(`Server does not support completions (required for ${method})`); + } + break; + case 'logging/setLevel': + if (!this._capabilities.logging) { + throw new Error(`Server does not support logging (required for ${method})`); + } + break; + case 'prompts/get': + case 'prompts/list': + if (!this._capabilities.prompts) { + throw new Error(`Server does not support prompts (required for ${method})`); + } + break; + case 'resources/list': + case 'resources/templates/list': + case 'resources/read': + if (!this._capabilities.resources) { + throw new Error(`Server does not support resources (required for ${method})`); + } + break; + case 'tools/call': + case 'tools/list': + if (!this._capabilities.tools) { + throw new Error(`Server does not support tools (required for ${method})`); + } + break; + case 'tasks/get': + case 'tasks/list': + case 'tasks/result': + case 'tasks/cancel': + if (!this._capabilities.tasks) { + throw new Error(`Server does not support tasks capability (required for ${method})`); + } + break; + case 'ping': + case 'initialize': + // No specific capability required for these methods + break; + } + } + assertTaskCapability(method) { + assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests, method, 'Client'); + } + assertTaskHandlerCapability(method) { + // Task handlers are registered in Protocol constructor before _capabilities is initialized + // Skip capability check for task methods during initialization + if (!this._capabilities) { + return; + } + assertToolsCallTaskCapability(this._capabilities.tasks?.requests, method, 'Server'); + } + async _oninitialize(request) { + const requestedVersion = request.params.protocolVersion; + this._clientCapabilities = request.params.capabilities; + this._clientVersion = request.params.clientInfo; + const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION; + return { + protocolVersion, + capabilities: this.getCapabilities(), + serverInfo: this._serverInfo, + ...(this._instructions && { instructions: this._instructions }) + }; + } + /** + * After initialization has completed, this will be populated with the client's reported capabilities. + */ + getClientCapabilities() { + return this._clientCapabilities; + } + /** + * After initialization has completed, this will be populated with information about the client's name and version. + */ + getClientVersion() { + return this._clientVersion; + } + getCapabilities() { + return this._capabilities; + } + async ping() { + return this.request({ method: 'ping' }, EmptyResultSchema); + } + // Implementation + async createMessage(params, options) { + // Capability check - only required when tools/toolChoice are provided + if (params.tools || params.toolChoice) { + if (!this._clientCapabilities?.sampling?.tools) { + throw new Error('Client does not support sampling tools capability.'); + } + } + // Message structure validation - always validate tool_use/tool_result pairs. + // These may appear even without tools/toolChoice in the current request when + // a previous sampling request returned tool_use and this is a follow-up with results. + if (params.messages.length > 0) { + const lastMessage = params.messages[params.messages.length - 1]; + const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content]; + const hasToolResults = lastContent.some(c => c.type === 'tool_result'); + const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : undefined; + const previousContent = previousMessage + ? Array.isArray(previousMessage.content) + ? previousMessage.content + : [previousMessage.content] + : []; + const hasPreviousToolUse = previousContent.some(c => c.type === 'tool_use'); + if (hasToolResults) { + if (lastContent.some(c => c.type !== 'tool_result')) { + throw new Error('The last message must contain only tool_result content if any is present'); + } + if (!hasPreviousToolUse) { + throw new Error('tool_result blocks are not matching any tool_use from the previous message'); + } + } + if (hasPreviousToolUse) { + const toolUseIds = new Set(previousContent.filter(c => c.type === 'tool_use').map(c => c.id)); + const toolResultIds = new Set(lastContent.filter(c => c.type === 'tool_result').map(c => c.toolUseId)); + if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every(id => toolResultIds.has(id))) { + throw new Error('ids of tool_result blocks and tool_use blocks from previous message do not match'); + } + } + } + // Use different schemas based on whether tools are provided + if (params.tools) { + return this.request({ method: 'sampling/createMessage', params }, CreateMessageResultWithToolsSchema, options); + } + return this.request({ method: 'sampling/createMessage', params }, CreateMessageResultSchema, options); + } + /** + * Creates an elicitation request for the given parameters. + * For backwards compatibility, `mode` may be omitted for form requests and will default to `'form'`. + * @param params The parameters for the elicitation request. + * @param options Optional request options. + * @returns The result of the elicitation request. + */ + async elicitInput(params, options) { + const mode = (params.mode ?? 'form'); + switch (mode) { + case 'url': { + if (!this._clientCapabilities?.elicitation?.url) { + throw new Error('Client does not support url elicitation.'); + } + const urlParams = params; + return this.request({ method: 'elicitation/create', params: urlParams }, ElicitResultSchema, options); + } + case 'form': { + if (!this._clientCapabilities?.elicitation?.form) { + throw new Error('Client does not support form elicitation.'); + } + const formParams = params.mode === 'form' ? params : { ...params, mode: 'form' }; + const result = await this.request({ method: 'elicitation/create', params: formParams }, ElicitResultSchema, options); + if (result.action === 'accept' && result.content && formParams.requestedSchema) { + try { + const validator = this._jsonSchemaValidator.getValidator(formParams.requestedSchema); + const validationResult = validator(result.content); + if (!validationResult.valid) { + throw new McpError(ErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`); + } + } + catch (error) { + if (error instanceof McpError) { + throw error; + } + throw new McpError(ErrorCode.InternalError, `Error validating elicitation response: ${error instanceof Error ? error.message : String(error)}`); + } + } + return result; + } + } + } + /** + * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete` + * notification for the specified elicitation ID. + * + * @param elicitationId The ID of the elicitation to mark as complete. + * @param options Optional notification options. Useful when the completion notification should be related to a prior request. + * @returns A function that emits the completion notification when awaited. + */ + createElicitationCompletionNotifier(elicitationId, options) { + if (!this._clientCapabilities?.elicitation?.url) { + throw new Error('Client does not support URL elicitation (required for notifications/elicitation/complete)'); + } + return () => this.notification({ + method: 'notifications/elicitation/complete', + params: { + elicitationId + } + }, options); + } + async listRoots(params, options) { + return this.request({ method: 'roots/list', params }, ListRootsResultSchema, options); + } + /** + * Sends a logging message to the client, if connected. + * Note: You only need to send the parameters object, not the entire JSON RPC message + * @see LoggingMessageNotification + * @param params + * @param sessionId optional for stateless and backward compatibility + */ + async sendLoggingMessage(params, sessionId) { + if (this._capabilities.logging) { + if (!this.isMessageIgnored(params.level, sessionId)) { + return this.notification({ method: 'notifications/message', params }); + } + } + } + async sendResourceUpdated(params) { + return this.notification({ + method: 'notifications/resources/updated', + params + }); + } + async sendResourceListChanged() { + return this.notification({ + method: 'notifications/resources/list_changed' + }); + } + async sendToolListChanged() { + return this.notification({ method: 'notifications/tools/list_changed' }); + } + async sendPromptListChanged() { + return this.notification({ method: 'notifications/prompts/list_changed' }); + } +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js new file mode 100644 index 00000000..727fe70a --- /dev/null +++ b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js @@ -0,0 +1,75 @@ +import process from 'node:process'; +import { ReadBuffer, serializeMessage } from '../shared/stdio.js'; +/** + * Server transport for stdio: this communicates with an MCP client by reading from the current process' stdin and writing to stdout. + * + * This transport is only available in Node.js environments. + */ +export class StdioServerTransport { + constructor(_stdin = process.stdin, _stdout = process.stdout) { + this._stdin = _stdin; + this._stdout = _stdout; + this._readBuffer = new ReadBuffer(); + this._started = false; + // Arrow functions to bind `this` properly, while maintaining function identity. + this._ondata = (chunk) => { + this._readBuffer.append(chunk); + this.processReadBuffer(); + }; + this._onerror = (error) => { + this.onerror?.(error); + }; + } + /** + * Starts listening for messages on stdin. + */ + async start() { + if (this._started) { + throw new Error('StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.'); + } + this._started = true; + this._stdin.on('data', this._ondata); + this._stdin.on('error', this._onerror); + } + processReadBuffer() { + while (true) { + try { + const message = this._readBuffer.readMessage(); + if (message === null) { + break; + } + this.onmessage?.(message); + } + catch (error) { + this.onerror?.(error); + } + } + } + async close() { + // Remove our event listeners first + this._stdin.off('data', this._ondata); + this._stdin.off('error', this._onerror); + // Check if we were the only data listener + const remainingDataListeners = this._stdin.listenerCount('data'); + if (remainingDataListeners === 0) { + // Only pause stdin if we were the only listener + // This prevents interfering with other parts of the application that might be using stdin + this._stdin.pause(); + } + // Clear the buffer and notify closure + this._readBuffer.clear(); + this.onclose?.(); + } + send(message) { + return new Promise(resolve => { + const json = serializeMessage(message); + if (this._stdout.write(json)) { + resolve(); + } + else { + this._stdout.once('drain', resolve); + } + }); + } +} +//# sourceMappingURL=stdio.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js new file mode 100644 index 00000000..be30a223 --- /dev/null +++ b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js @@ -0,0 +1,209 @@ +// zod-compat.ts +// ---------------------------------------------------- +// Unified types + helpers to accept Zod v3 and v4 (Mini) +// ---------------------------------------------------- +import * as z3rt from 'zod/v3'; +import * as z4mini from 'zod/v4-mini'; +// --- Runtime detection --- +export function isZ4Schema(s) { + // Present on Zod 4 (Classic & Mini) schemas; absent on Zod 3 + const schema = s; + return !!schema._zod; +} +// --- Schema construction --- +export function objectFromShape(shape) { + const values = Object.values(shape); + if (values.length === 0) + return z4mini.object({}); // default to v4 Mini + const allV4 = values.every(isZ4Schema); + const allV3 = values.every(s => !isZ4Schema(s)); + if (allV4) + return z4mini.object(shape); + if (allV3) + return z3rt.object(shape); + throw new Error('Mixed Zod versions detected in object shape.'); +} +// --- Unified parsing --- +export function safeParse(schema, data) { + if (isZ4Schema(schema)) { + // Mini exposes top-level safeParse + const result = z4mini.safeParse(schema, data); + return result; + } + const v3Schema = schema; + const result = v3Schema.safeParse(data); + return result; +} +export async function safeParseAsync(schema, data) { + if (isZ4Schema(schema)) { + // Mini exposes top-level safeParseAsync + const result = await z4mini.safeParseAsync(schema, data); + return result; + } + const v3Schema = schema; + const result = await v3Schema.safeParseAsync(data); + return result; +} +// --- Shape extraction --- +export function getObjectShape(schema) { + if (!schema) + return undefined; + // Zod v3 exposes `.shape`; Zod v4 keeps the shape on `_zod.def.shape` + let rawShape; + if (isZ4Schema(schema)) { + const v4Schema = schema; + rawShape = v4Schema._zod?.def?.shape; + } + else { + const v3Schema = schema; + rawShape = v3Schema.shape; + } + if (!rawShape) + return undefined; + if (typeof rawShape === 'function') { + try { + return rawShape(); + } + catch { + return undefined; + } + } + return rawShape; +} +// --- Schema normalization --- +/** + * Normalizes a schema to an object schema. Handles both: + * - Already-constructed object schemas (v3 or v4) + * - Raw shapes that need to be wrapped into object schemas + */ +export function normalizeObjectSchema(schema) { + if (!schema) + return undefined; + // First check if it's a raw shape (Record) + // Raw shapes don't have _def or _zod properties and aren't schemas themselves + if (typeof schema === 'object') { + // Check if it's actually a ZodRawShapeCompat (not a schema instance) + // by checking if it lacks schema-like internal properties + const asV3 = schema; + const asV4 = schema; + // If it's not a schema instance (no _def or _zod), it might be a raw shape + if (!asV3._def && !asV4._zod) { + // Check if all values are schemas (heuristic to confirm it's a raw shape) + const values = Object.values(schema); + if (values.length > 0 && + values.every(v => typeof v === 'object' && + v !== null && + (v._def !== undefined || + v._zod !== undefined || + typeof v.parse === 'function'))) { + return objectFromShape(schema); + } + } + } + // If we get here, it should be an AnySchema (not a raw shape) + // Check if it's already an object schema + if (isZ4Schema(schema)) { + // Check if it's a v4 object + const v4Schema = schema; + const def = v4Schema._zod?.def; + if (def && (def.type === 'object' || def.shape !== undefined)) { + return schema; + } + } + else { + // Check if it's a v3 object + const v3Schema = schema; + if (v3Schema.shape !== undefined) { + return schema; + } + } + return undefined; +} +// --- Error message extraction --- +/** + * Safely extracts an error message from a parse result error. + * Zod errors can have different structures, so we handle various cases. + */ +export function getParseErrorMessage(error) { + if (error && typeof error === 'object') { + // Try common error structures + if ('message' in error && typeof error.message === 'string') { + return error.message; + } + if ('issues' in error && Array.isArray(error.issues) && error.issues.length > 0) { + const firstIssue = error.issues[0]; + if (firstIssue && typeof firstIssue === 'object' && 'message' in firstIssue) { + return String(firstIssue.message); + } + } + // Fallback: try to stringify the error + try { + return JSON.stringify(error); + } + catch { + return String(error); + } + } + return String(error); +} +// --- Schema metadata access --- +/** + * Gets the description from a schema, if available. + * Works with both Zod v3 and v4. + * + * Both versions expose a `.description` getter that returns the description + * from their respective internal storage (v3: _def, v4: globalRegistry). + */ +export function getSchemaDescription(schema) { + return schema.description; +} +/** + * Checks if a schema is optional. + * Works with both Zod v3 and v4. + */ +export function isSchemaOptional(schema) { + if (isZ4Schema(schema)) { + const v4Schema = schema; + return v4Schema._zod?.def?.type === 'optional'; + } + const v3Schema = schema; + // v3 has isOptional() method + if (typeof schema.isOptional === 'function') { + return schema.isOptional(); + } + return v3Schema._def?.typeName === 'ZodOptional'; +} +/** + * Gets the literal value from a schema, if it's a literal schema. + * Works with both Zod v3 and v4. + * Returns undefined if the schema is not a literal or the value cannot be determined. + */ +export function getLiteralValue(schema) { + if (isZ4Schema(schema)) { + const v4Schema = schema; + const def = v4Schema._zod?.def; + if (def) { + // Try various ways to get the literal value + if (def.value !== undefined) + return def.value; + if (Array.isArray(def.values) && def.values.length > 0) { + return def.values[0]; + } + } + } + const v3Schema = schema; + const def = v3Schema._def; + if (def) { + if (def.value !== undefined) + return def.value; + if (Array.isArray(def.values) && def.values.length > 0) { + return def.values[0]; + } + } + // Fallback: check for direct value property (some Zod versions) + const directValue = schema.value; + if (directValue !== undefined) + return directValue; + return undefined; +} +//# sourceMappingURL=zod-compat.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js new file mode 100644 index 00000000..62f7fd0e --- /dev/null +++ b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js @@ -0,0 +1,51 @@ +// zod-json-schema-compat.ts +// ---------------------------------------------------- +// JSON Schema conversion for both Zod v3 and Zod v4 (Mini) +// v3 uses your vendored converter; v4 uses Mini's toJSONSchema +// ---------------------------------------------------- +import * as z4mini from 'zod/v4-mini'; +import { getObjectShape, safeParse, isZ4Schema, getLiteralValue } from './zod-compat.js'; +import { zodToJsonSchema } from 'zod-to-json-schema'; +function mapMiniTarget(t) { + if (!t) + return 'draft-7'; + if (t === 'jsonSchema7' || t === 'draft-7') + return 'draft-7'; + if (t === 'jsonSchema2019-09' || t === 'draft-2020-12') + return 'draft-2020-12'; + return 'draft-7'; // fallback +} +export function toJsonSchemaCompat(schema, opts) { + if (isZ4Schema(schema)) { + // v4 branch — use Mini's built-in toJSONSchema + return z4mini.toJSONSchema(schema, { + target: mapMiniTarget(opts?.target), + io: opts?.pipeStrategy ?? 'input' + }); + } + // v3 branch — use vendored converter + return zodToJsonSchema(schema, { + strictUnions: opts?.strictUnions ?? true, + pipeStrategy: opts?.pipeStrategy ?? 'input' + }); +} +export function getMethodLiteral(schema) { + const shape = getObjectShape(schema); + const methodSchema = shape?.method; + if (!methodSchema) { + throw new Error('Schema is missing a method literal'); + } + const value = getLiteralValue(methodSchema); + if (typeof value !== 'string') { + throw new Error('Schema method literal must be a string'); + } + return value; +} +export function parseWithCompat(schema, data) { + const result = safeParse(schema, data); + if (!result.success) { + throw result.error; + } + return result.data; +} +//# sourceMappingURL=zod-json-schema-compat.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js new file mode 100644 index 00000000..1883885e --- /dev/null +++ b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js @@ -0,0 +1,44 @@ +/** + * Utilities for handling OAuth resource URIs. + */ +/** + * Converts a server URL to a resource URL by removing the fragment. + * RFC 8707 section 2 states that resource URIs "MUST NOT include a fragment component". + * Keeps everything else unchanged (scheme, domain, port, path, query). + */ +export function resourceUrlFromServerUrl(url) { + const resourceURL = typeof url === 'string' ? new URL(url) : new URL(url.href); + resourceURL.hash = ''; // Remove fragment + return resourceURL; +} +/** + * Checks if a requested resource URL matches a configured resource URL. + * A requested resource matches if it has the same scheme, domain, port, + * and its path starts with the configured resource's path. + * + * @param requestedResource The resource URL being requested + * @param configuredResource The resource URL that has been configured + * @returns true if the requested resource matches the configured resource, false otherwise + */ +export function checkResourceAllowed({ requestedResource, configuredResource }) { + const requested = typeof requestedResource === 'string' ? new URL(requestedResource) : new URL(requestedResource.href); + const configured = typeof configuredResource === 'string' ? new URL(configuredResource) : new URL(configuredResource.href); + // Compare the origin (scheme, domain, and port) + if (requested.origin !== configured.origin) { + return false; + } + // Handle cases like requested=/foo and configured=/foo/ + if (requested.pathname.length < configured.pathname.length) { + return false; + } + // Check if the requested path starts with the configured path + // Ensure both paths end with / for proper comparison + // This ensures that if we have paths like "/api" and "/api/users", + // we properly detect that "/api/users" is a subpath of "/api" + // By adding a trailing slash if missing, we avoid false positives + // where paths like "/api123" would incorrectly match "/api" + const requestedPath = requested.pathname.endsWith('/') ? requested.pathname : requested.pathname + '/'; + const configuredPath = configured.pathname.endsWith('/') ? configured.pathname : configured.pathname + '/'; + return requestedPath.startsWith(configuredPath); +} +//# sourceMappingURL=auth-utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js new file mode 100644 index 00000000..04f38eb8 --- /dev/null +++ b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js @@ -0,0 +1,198 @@ +import * as z from 'zod/v4'; +/** + * Reusable URL validation that disallows javascript: scheme + */ +export const SafeUrlSchema = z + .url() + .superRefine((val, ctx) => { + if (!URL.canParse(val)) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: 'URL must be parseable', + fatal: true + }); + return z.NEVER; + } +}) + .refine(url => { + const u = new URL(url); + return u.protocol !== 'javascript:' && u.protocol !== 'data:' && u.protocol !== 'vbscript:'; +}, { message: 'URL cannot use javascript:, data:, or vbscript: scheme' }); +/** + * RFC 9728 OAuth Protected Resource Metadata + */ +export const OAuthProtectedResourceMetadataSchema = z.looseObject({ + resource: z.string().url(), + authorization_servers: z.array(SafeUrlSchema).optional(), + jwks_uri: z.string().url().optional(), + scopes_supported: z.array(z.string()).optional(), + bearer_methods_supported: z.array(z.string()).optional(), + resource_signing_alg_values_supported: z.array(z.string()).optional(), + resource_name: z.string().optional(), + resource_documentation: z.string().optional(), + resource_policy_uri: z.string().url().optional(), + resource_tos_uri: z.string().url().optional(), + tls_client_certificate_bound_access_tokens: z.boolean().optional(), + authorization_details_types_supported: z.array(z.string()).optional(), + dpop_signing_alg_values_supported: z.array(z.string()).optional(), + dpop_bound_access_tokens_required: z.boolean().optional() +}); +/** + * RFC 8414 OAuth 2.0 Authorization Server Metadata + */ +export const OAuthMetadataSchema = z.looseObject({ + issuer: z.string(), + authorization_endpoint: SafeUrlSchema, + token_endpoint: SafeUrlSchema, + registration_endpoint: SafeUrlSchema.optional(), + scopes_supported: z.array(z.string()).optional(), + response_types_supported: z.array(z.string()), + response_modes_supported: z.array(z.string()).optional(), + grant_types_supported: z.array(z.string()).optional(), + token_endpoint_auth_methods_supported: z.array(z.string()).optional(), + token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), + service_documentation: SafeUrlSchema.optional(), + revocation_endpoint: SafeUrlSchema.optional(), + revocation_endpoint_auth_methods_supported: z.array(z.string()).optional(), + revocation_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), + introspection_endpoint: z.string().optional(), + introspection_endpoint_auth_methods_supported: z.array(z.string()).optional(), + introspection_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), + code_challenge_methods_supported: z.array(z.string()).optional(), + client_id_metadata_document_supported: z.boolean().optional() +}); +/** + * OpenID Connect Discovery 1.0 Provider Metadata + * see: https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata + */ +export const OpenIdProviderMetadataSchema = z.looseObject({ + issuer: z.string(), + authorization_endpoint: SafeUrlSchema, + token_endpoint: SafeUrlSchema, + userinfo_endpoint: SafeUrlSchema.optional(), + jwks_uri: SafeUrlSchema, + registration_endpoint: SafeUrlSchema.optional(), + scopes_supported: z.array(z.string()).optional(), + response_types_supported: z.array(z.string()), + response_modes_supported: z.array(z.string()).optional(), + grant_types_supported: z.array(z.string()).optional(), + acr_values_supported: z.array(z.string()).optional(), + subject_types_supported: z.array(z.string()), + id_token_signing_alg_values_supported: z.array(z.string()), + id_token_encryption_alg_values_supported: z.array(z.string()).optional(), + id_token_encryption_enc_values_supported: z.array(z.string()).optional(), + userinfo_signing_alg_values_supported: z.array(z.string()).optional(), + userinfo_encryption_alg_values_supported: z.array(z.string()).optional(), + userinfo_encryption_enc_values_supported: z.array(z.string()).optional(), + request_object_signing_alg_values_supported: z.array(z.string()).optional(), + request_object_encryption_alg_values_supported: z.array(z.string()).optional(), + request_object_encryption_enc_values_supported: z.array(z.string()).optional(), + token_endpoint_auth_methods_supported: z.array(z.string()).optional(), + token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), + display_values_supported: z.array(z.string()).optional(), + claim_types_supported: z.array(z.string()).optional(), + claims_supported: z.array(z.string()).optional(), + service_documentation: z.string().optional(), + claims_locales_supported: z.array(z.string()).optional(), + ui_locales_supported: z.array(z.string()).optional(), + claims_parameter_supported: z.boolean().optional(), + request_parameter_supported: z.boolean().optional(), + request_uri_parameter_supported: z.boolean().optional(), + require_request_uri_registration: z.boolean().optional(), + op_policy_uri: SafeUrlSchema.optional(), + op_tos_uri: SafeUrlSchema.optional(), + client_id_metadata_document_supported: z.boolean().optional() +}); +/** + * OpenID Connect Discovery metadata that may include OAuth 2.0 fields + * This schema represents the real-world scenario where OIDC providers + * return a mix of OpenID Connect and OAuth 2.0 metadata fields + */ +export const OpenIdProviderDiscoveryMetadataSchema = z.object({ + ...OpenIdProviderMetadataSchema.shape, + ...OAuthMetadataSchema.pick({ + code_challenge_methods_supported: true + }).shape +}); +/** + * OAuth 2.1 token response + */ +export const OAuthTokensSchema = z + .object({ + access_token: z.string(), + id_token: z.string().optional(), // Optional for OAuth 2.1, but necessary in OpenID Connect + token_type: z.string(), + expires_in: z.coerce.number().optional(), + scope: z.string().optional(), + refresh_token: z.string().optional() +}) + .strip(); +/** + * OAuth 2.1 error response + */ +export const OAuthErrorResponseSchema = z.object({ + error: z.string(), + error_description: z.string().optional(), + error_uri: z.string().optional() +}); +/** + * Optional version of SafeUrlSchema that allows empty string for retrocompatibility on tos_uri and logo_uri + */ +export const OptionalSafeUrlSchema = SafeUrlSchema.optional().or(z.literal('').transform(() => undefined)); +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration metadata + */ +export const OAuthClientMetadataSchema = z + .object({ + redirect_uris: z.array(SafeUrlSchema), + token_endpoint_auth_method: z.string().optional(), + grant_types: z.array(z.string()).optional(), + response_types: z.array(z.string()).optional(), + client_name: z.string().optional(), + client_uri: SafeUrlSchema.optional(), + logo_uri: OptionalSafeUrlSchema, + scope: z.string().optional(), + contacts: z.array(z.string()).optional(), + tos_uri: OptionalSafeUrlSchema, + policy_uri: z.string().optional(), + jwks_uri: SafeUrlSchema.optional(), + jwks: z.any().optional(), + software_id: z.string().optional(), + software_version: z.string().optional(), + software_statement: z.string().optional() +}) + .strip(); +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration client information + */ +export const OAuthClientInformationSchema = z + .object({ + client_id: z.string(), + client_secret: z.string().optional(), + client_id_issued_at: z.number().optional(), + client_secret_expires_at: z.number().optional() +}) + .strip(); +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata) + */ +export const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema); +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration error response + */ +export const OAuthClientRegistrationErrorSchema = z + .object({ + error: z.string(), + error_description: z.string().optional() +}) + .strip(); +/** + * RFC 7009 OAuth 2.0 Token Revocation request + */ +export const OAuthTokenRevocationRequestSchema = z + .object({ + token: z.string(), + token_type_hint: z.string().optional() +}) + .strip(); +//# sourceMappingURL=auth.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js new file mode 100644 index 00000000..5740ba10 --- /dev/null +++ b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js @@ -0,0 +1,1099 @@ +import { safeParse } from '../server/zod-compat.js'; +import { CancelledNotificationSchema, CreateTaskResultSchema, ErrorCode, GetTaskRequestSchema, GetTaskResultSchema, GetTaskPayloadRequestSchema, ListTasksRequestSchema, ListTasksResultSchema, CancelTaskRequestSchema, CancelTaskResultSchema, isJSONRPCErrorResponse, isJSONRPCRequest, isJSONRPCResultResponse, isJSONRPCNotification, McpError, PingRequestSchema, ProgressNotificationSchema, RELATED_TASK_META_KEY, TaskStatusNotificationSchema, isTaskAugmentedRequestParams } from '../types.js'; +import { isTerminal } from '../experimental/tasks/interfaces.js'; +import { getMethodLiteral, parseWithCompat } from '../server/zod-json-schema-compat.js'; +/** + * The default request timeout, in miliseconds. + */ +export const DEFAULT_REQUEST_TIMEOUT_MSEC = 60000; +/** + * Implements MCP protocol framing on top of a pluggable transport, including + * features like request/response linking, notifications, and progress. + */ +export class Protocol { + constructor(_options) { + this._options = _options; + this._requestMessageId = 0; + this._requestHandlers = new Map(); + this._requestHandlerAbortControllers = new Map(); + this._notificationHandlers = new Map(); + this._responseHandlers = new Map(); + this._progressHandlers = new Map(); + this._timeoutInfo = new Map(); + this._pendingDebouncedNotifications = new Set(); + // Maps task IDs to progress tokens to keep handlers alive after CreateTaskResult + this._taskProgressTokens = new Map(); + this._requestResolvers = new Map(); + this.setNotificationHandler(CancelledNotificationSchema, notification => { + this._oncancel(notification); + }); + this.setNotificationHandler(ProgressNotificationSchema, notification => { + this._onprogress(notification); + }); + this.setRequestHandler(PingRequestSchema, + // Automatic pong by default. + _request => ({})); + // Install task handlers if TaskStore is provided + this._taskStore = _options?.taskStore; + this._taskMessageQueue = _options?.taskMessageQueue; + if (this._taskStore) { + this.setRequestHandler(GetTaskRequestSchema, async (request, extra) => { + const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId); + if (!task) { + throw new McpError(ErrorCode.InvalidParams, 'Failed to retrieve task: Task not found'); + } + // Per spec: tasks/get responses SHALL NOT include related-task metadata + // as the taskId parameter is the source of truth + // @ts-expect-error SendResultT cannot contain GetTaskResult, but we include it in our derived types everywhere else + return { + ...task + }; + }); + this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => { + const handleTaskResult = async () => { + const taskId = request.params.taskId; + // Deliver queued messages + if (this._taskMessageQueue) { + let queuedMessage; + while ((queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId))) { + // Handle response and error messages by routing them to the appropriate resolver + if (queuedMessage.type === 'response' || queuedMessage.type === 'error') { + const message = queuedMessage.message; + const requestId = message.id; + // Lookup resolver in _requestResolvers map + const resolver = this._requestResolvers.get(requestId); + if (resolver) { + // Remove resolver from map after invocation + this._requestResolvers.delete(requestId); + // Invoke resolver with response or error + if (queuedMessage.type === 'response') { + resolver(message); + } + else { + // Convert JSONRPCError to McpError + const errorMessage = message; + const error = new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data); + resolver(error); + } + } + else { + // Handle missing resolver gracefully with error logging + const messageType = queuedMessage.type === 'response' ? 'Response' : 'Error'; + this._onerror(new Error(`${messageType} handler missing for request ${requestId}`)); + } + // Continue to next message + continue; + } + // Send the message on the response stream by passing the relatedRequestId + // This tells the transport to write the message to the tasks/result response stream + await this._transport?.send(queuedMessage.message, { relatedRequestId: extra.requestId }); + } + } + // Now check task status + const task = await this._taskStore.getTask(taskId, extra.sessionId); + if (!task) { + throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`); + } + // Block if task is not terminal (we've already delivered all queued messages above) + if (!isTerminal(task.status)) { + // Wait for status change or new messages + await this._waitForTaskUpdate(taskId, extra.signal); + // After waking up, recursively call to deliver any new messages or result + return await handleTaskResult(); + } + // If task is terminal, return the result + if (isTerminal(task.status)) { + const result = await this._taskStore.getTaskResult(taskId, extra.sessionId); + this._clearTaskQueue(taskId); + return { + ...result, + _meta: { + ...result._meta, + [RELATED_TASK_META_KEY]: { + taskId: taskId + } + } + }; + } + return await handleTaskResult(); + }; + return await handleTaskResult(); + }); + this.setRequestHandler(ListTasksRequestSchema, async (request, extra) => { + try { + const { tasks, nextCursor } = await this._taskStore.listTasks(request.params?.cursor, extra.sessionId); + // @ts-expect-error SendResultT cannot contain ListTasksResult, but we include it in our derived types everywhere else + return { + tasks, + nextCursor, + _meta: {} + }; + } + catch (error) { + throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error instanceof Error ? error.message : String(error)}`); + } + }); + this.setRequestHandler(CancelTaskRequestSchema, async (request, extra) => { + try { + // Get the current task to check if it's in a terminal state, in case the implementation is not atomic + const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId); + if (!task) { + throw new McpError(ErrorCode.InvalidParams, `Task not found: ${request.params.taskId}`); + } + // Reject cancellation of terminal tasks + if (isTerminal(task.status)) { + throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`); + } + await this._taskStore.updateTaskStatus(request.params.taskId, 'cancelled', 'Client cancelled task execution.', extra.sessionId); + this._clearTaskQueue(request.params.taskId); + const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId); + if (!cancelledTask) { + // Task was deleted during cancellation (e.g., cleanup happened) + throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`); + } + return { + _meta: {}, + ...cancelledTask + }; + } + catch (error) { + // Re-throw McpError as-is + if (error instanceof McpError) { + throw error; + } + throw new McpError(ErrorCode.InvalidRequest, `Failed to cancel task: ${error instanceof Error ? error.message : String(error)}`); + } + }); + } + } + async _oncancel(notification) { + if (!notification.params.requestId) { + return; + } + // Handle request cancellation + const controller = this._requestHandlerAbortControllers.get(notification.params.requestId); + controller?.abort(notification.params.reason); + } + _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) { + this._timeoutInfo.set(messageId, { + timeoutId: setTimeout(onTimeout, timeout), + startTime: Date.now(), + timeout, + maxTotalTimeout, + resetTimeoutOnProgress, + onTimeout + }); + } + _resetTimeout(messageId) { + const info = this._timeoutInfo.get(messageId); + if (!info) + return false; + const totalElapsed = Date.now() - info.startTime; + if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) { + this._timeoutInfo.delete(messageId); + throw McpError.fromError(ErrorCode.RequestTimeout, 'Maximum total timeout exceeded', { + maxTotalTimeout: info.maxTotalTimeout, + totalElapsed + }); + } + clearTimeout(info.timeoutId); + info.timeoutId = setTimeout(info.onTimeout, info.timeout); + return true; + } + _cleanupTimeout(messageId) { + const info = this._timeoutInfo.get(messageId); + if (info) { + clearTimeout(info.timeoutId); + this._timeoutInfo.delete(messageId); + } + } + /** + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. + */ + async connect(transport) { + if (this._transport) { + throw new Error('Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.'); + } + this._transport = transport; + const _onclose = this.transport?.onclose; + this._transport.onclose = () => { + _onclose?.(); + this._onclose(); + }; + const _onerror = this.transport?.onerror; + this._transport.onerror = (error) => { + _onerror?.(error); + this._onerror(error); + }; + const _onmessage = this._transport?.onmessage; + this._transport.onmessage = (message, extra) => { + _onmessage?.(message, extra); + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { + this._onresponse(message); + } + else if (isJSONRPCRequest(message)) { + this._onrequest(message, extra); + } + else if (isJSONRPCNotification(message)) { + this._onnotification(message); + } + else { + this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`)); + } + }; + await this._transport.start(); + } + _onclose() { + const responseHandlers = this._responseHandlers; + this._responseHandlers = new Map(); + this._progressHandlers.clear(); + this._taskProgressTokens.clear(); + this._pendingDebouncedNotifications.clear(); + // Abort all in-flight request handlers so they stop sending messages + for (const controller of this._requestHandlerAbortControllers.values()) { + controller.abort(); + } + this._requestHandlerAbortControllers.clear(); + const error = McpError.fromError(ErrorCode.ConnectionClosed, 'Connection closed'); + this._transport = undefined; + this.onclose?.(); + for (const handler of responseHandlers.values()) { + handler(error); + } + } + _onerror(error) { + this.onerror?.(error); + } + _onnotification(notification) { + const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler; + // Ignore notifications not being subscribed to. + if (handler === undefined) { + return; + } + // Starting with Promise.resolve() puts any synchronous errors into the monad as well. + Promise.resolve() + .then(() => handler(notification)) + .catch(error => this._onerror(new Error(`Uncaught error in notification handler: ${error}`))); + } + _onrequest(request, extra) { + const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler; + // Capture the current transport at request time to ensure responses go to the correct client + const capturedTransport = this._transport; + // Extract taskId from request metadata if present (needed early for method not found case) + const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId; + if (handler === undefined) { + const errorResponse = { + jsonrpc: '2.0', + id: request.id, + error: { + code: ErrorCode.MethodNotFound, + message: 'Method not found' + } + }; + // Queue or send the error response based on whether this is a task-related request + if (relatedTaskId && this._taskMessageQueue) { + this._enqueueTaskMessage(relatedTaskId, { + type: 'error', + message: errorResponse, + timestamp: Date.now() + }, capturedTransport?.sessionId).catch(error => this._onerror(new Error(`Failed to enqueue error response: ${error}`))); + } + else { + capturedTransport + ?.send(errorResponse) + .catch(error => this._onerror(new Error(`Failed to send an error response: ${error}`))); + } + return; + } + const abortController = new AbortController(); + this._requestHandlerAbortControllers.set(request.id, abortController); + const taskCreationParams = isTaskAugmentedRequestParams(request.params) ? request.params.task : undefined; + const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport?.sessionId) : undefined; + const fullExtra = { + signal: abortController.signal, + sessionId: capturedTransport?.sessionId, + _meta: request.params?._meta, + sendNotification: async (notification) => { + if (abortController.signal.aborted) + return; + // Include related-task metadata if this request is part of a task + const notificationOptions = { relatedRequestId: request.id }; + if (relatedTaskId) { + notificationOptions.relatedTask = { taskId: relatedTaskId }; + } + await this.notification(notification, notificationOptions); + }, + sendRequest: async (r, resultSchema, options) => { + if (abortController.signal.aborted) { + throw new McpError(ErrorCode.ConnectionClosed, 'Request was cancelled'); + } + // Include related-task metadata if this request is part of a task + const requestOptions = { ...options, relatedRequestId: request.id }; + if (relatedTaskId && !requestOptions.relatedTask) { + requestOptions.relatedTask = { taskId: relatedTaskId }; + } + // Set task status to input_required when sending a request within a task context + // Use the taskId from options (explicit) or fall back to relatedTaskId (inherited) + const effectiveTaskId = requestOptions.relatedTask?.taskId ?? relatedTaskId; + if (effectiveTaskId && taskStore) { + await taskStore.updateTaskStatus(effectiveTaskId, 'input_required'); + } + return await this.request(r, resultSchema, requestOptions); + }, + authInfo: extra?.authInfo, + requestId: request.id, + requestInfo: extra?.requestInfo, + taskId: relatedTaskId, + taskStore: taskStore, + taskRequestedTtl: taskCreationParams?.ttl, + closeSSEStream: extra?.closeSSEStream, + closeStandaloneSSEStream: extra?.closeStandaloneSSEStream + }; + // Starting with Promise.resolve() puts any synchronous errors into the monad as well. + Promise.resolve() + .then(() => { + // If this request asked for task creation, check capability first + if (taskCreationParams) { + // Check if the request method supports task creation + this.assertTaskHandlerCapability(request.method); + } + }) + .then(() => handler(request, fullExtra)) + .then(async (result) => { + if (abortController.signal.aborted) { + // Request was cancelled + return; + } + const response = { + result, + jsonrpc: '2.0', + id: request.id + }; + // Queue or send the response based on whether this is a task-related request + if (relatedTaskId && this._taskMessageQueue) { + await this._enqueueTaskMessage(relatedTaskId, { + type: 'response', + message: response, + timestamp: Date.now() + }, capturedTransport?.sessionId); + } + else { + await capturedTransport?.send(response); + } + }, async (error) => { + if (abortController.signal.aborted) { + // Request was cancelled + return; + } + const errorResponse = { + jsonrpc: '2.0', + id: request.id, + error: { + code: Number.isSafeInteger(error['code']) ? error['code'] : ErrorCode.InternalError, + message: error.message ?? 'Internal error', + ...(error['data'] !== undefined && { data: error['data'] }) + } + }; + // Queue or send the error response based on whether this is a task-related request + if (relatedTaskId && this._taskMessageQueue) { + await this._enqueueTaskMessage(relatedTaskId, { + type: 'error', + message: errorResponse, + timestamp: Date.now() + }, capturedTransport?.sessionId); + } + else { + await capturedTransport?.send(errorResponse); + } + }) + .catch(error => this._onerror(new Error(`Failed to send response: ${error}`))) + .finally(() => { + this._requestHandlerAbortControllers.delete(request.id); + }); + } + _onprogress(notification) { + const { progressToken, ...params } = notification.params; + const messageId = Number(progressToken); + const handler = this._progressHandlers.get(messageId); + if (!handler) { + this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`)); + return; + } + const responseHandler = this._responseHandlers.get(messageId); + const timeoutInfo = this._timeoutInfo.get(messageId); + if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) { + try { + this._resetTimeout(messageId); + } + catch (error) { + // Clean up if maxTotalTimeout was exceeded + this._responseHandlers.delete(messageId); + this._progressHandlers.delete(messageId); + this._cleanupTimeout(messageId); + responseHandler(error); + return; + } + } + handler(params); + } + _onresponse(response) { + const messageId = Number(response.id); + // Check if this is a response to a queued request + const resolver = this._requestResolvers.get(messageId); + if (resolver) { + this._requestResolvers.delete(messageId); + if (isJSONRPCResultResponse(response)) { + resolver(response); + } + else { + const error = new McpError(response.error.code, response.error.message, response.error.data); + resolver(error); + } + return; + } + const handler = this._responseHandlers.get(messageId); + if (handler === undefined) { + this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`)); + return; + } + this._responseHandlers.delete(messageId); + this._cleanupTimeout(messageId); + // Keep progress handler alive for CreateTaskResult responses + let isTaskResponse = false; + if (isJSONRPCResultResponse(response) && response.result && typeof response.result === 'object') { + const result = response.result; + if (result.task && typeof result.task === 'object') { + const task = result.task; + if (typeof task.taskId === 'string') { + isTaskResponse = true; + this._taskProgressTokens.set(task.taskId, messageId); + } + } + } + if (!isTaskResponse) { + this._progressHandlers.delete(messageId); + } + if (isJSONRPCResultResponse(response)) { + handler(response); + } + else { + const error = McpError.fromError(response.error.code, response.error.message, response.error.data); + handler(error); + } + } + get transport() { + return this._transport; + } + /** + * Closes the connection. + */ + async close() { + await this._transport?.close(); + } + /** + * Sends a request and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * @example + * ```typescript + * const stream = protocol.requestStream(request, resultSchema, options); + * for await (const message of stream) { + * switch (message.type) { + * case 'taskCreated': + * console.log('Task created:', message.task.taskId); + * break; + * case 'taskStatus': + * console.log('Task status:', message.task.status); + * break; + * case 'result': + * console.log('Final result:', message.result); + * break; + * case 'error': + * console.error('Error:', message.error); + * break; + * } + * } + * ``` + * + * @experimental Use `client.experimental.tasks.requestStream()` to access this method. + */ + async *requestStream(request, resultSchema, options) { + const { task } = options ?? {}; + // For non-task requests, just yield the result + if (!task) { + try { + const result = await this.request(request, resultSchema, options); + yield { type: 'result', result }; + } + catch (error) { + yield { + type: 'error', + error: error instanceof McpError ? error : new McpError(ErrorCode.InternalError, String(error)) + }; + } + return; + } + // For task-augmented requests, we need to poll for status + // First, make the request to create the task + let taskId; + try { + // Send the request and get the CreateTaskResult + const createResult = await this.request(request, CreateTaskResultSchema, options); + // Extract taskId from the result + if (createResult.task) { + taskId = createResult.task.taskId; + yield { type: 'taskCreated', task: createResult.task }; + } + else { + throw new McpError(ErrorCode.InternalError, 'Task creation did not return a task'); + } + // Poll for task completion + while (true) { + // Get current task status + const task = await this.getTask({ taskId }, options); + yield { type: 'taskStatus', task }; + // Check if task is terminal + if (isTerminal(task.status)) { + if (task.status === 'completed') { + // Get the final result + const result = await this.getTaskResult({ taskId }, resultSchema, options); + yield { type: 'result', result }; + } + else if (task.status === 'failed') { + yield { + type: 'error', + error: new McpError(ErrorCode.InternalError, `Task ${taskId} failed`) + }; + } + else if (task.status === 'cancelled') { + yield { + type: 'error', + error: new McpError(ErrorCode.InternalError, `Task ${taskId} was cancelled`) + }; + } + return; + } + // When input_required, call tasks/result to deliver queued messages + // (elicitation, sampling) via SSE and block until terminal + if (task.status === 'input_required') { + const result = await this.getTaskResult({ taskId }, resultSchema, options); + yield { type: 'result', result }; + return; + } + // Wait before polling again + const pollInterval = task.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1000; + await new Promise(resolve => setTimeout(resolve, pollInterval)); + // Check if cancelled + options?.signal?.throwIfAborted(); + } + } + catch (error) { + yield { + type: 'error', + error: error instanceof McpError ? error : new McpError(ErrorCode.InternalError, String(error)) + }; + } + } + /** + * Sends a request and waits for a response. + * + * Do not use this method to emit notifications! Use notification() instead. + */ + request(request, resultSchema, options) { + const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {}; + // Send the request + return new Promise((resolve, reject) => { + const earlyReject = (error) => { + reject(error); + }; + if (!this._transport) { + earlyReject(new Error('Not connected')); + return; + } + if (this._options?.enforceStrictCapabilities === true) { + try { + this.assertCapabilityForMethod(request.method); + // If task creation is requested, also check task capabilities + if (task) { + this.assertTaskCapability(request.method); + } + } + catch (e) { + earlyReject(e); + return; + } + } + options?.signal?.throwIfAborted(); + const messageId = this._requestMessageId++; + const jsonrpcRequest = { + ...request, + jsonrpc: '2.0', + id: messageId + }; + if (options?.onprogress) { + this._progressHandlers.set(messageId, options.onprogress); + jsonrpcRequest.params = { + ...request.params, + _meta: { + ...(request.params?._meta || {}), + progressToken: messageId + } + }; + } + // Augment with task creation parameters if provided + if (task) { + jsonrpcRequest.params = { + ...jsonrpcRequest.params, + task: task + }; + } + // Augment with related task metadata if relatedTask is provided + if (relatedTask) { + jsonrpcRequest.params = { + ...jsonrpcRequest.params, + _meta: { + ...(jsonrpcRequest.params?._meta || {}), + [RELATED_TASK_META_KEY]: relatedTask + } + }; + } + const cancel = (reason) => { + this._responseHandlers.delete(messageId); + this._progressHandlers.delete(messageId); + this._cleanupTimeout(messageId); + this._transport + ?.send({ + jsonrpc: '2.0', + method: 'notifications/cancelled', + params: { + requestId: messageId, + reason: String(reason) + } + }, { relatedRequestId, resumptionToken, onresumptiontoken }) + .catch(error => this._onerror(new Error(`Failed to send cancellation: ${error}`))); + // Wrap the reason in an McpError if it isn't already + const error = reason instanceof McpError ? reason : new McpError(ErrorCode.RequestTimeout, String(reason)); + reject(error); + }; + this._responseHandlers.set(messageId, response => { + if (options?.signal?.aborted) { + return; + } + if (response instanceof Error) { + return reject(response); + } + try { + const parseResult = safeParse(resultSchema, response.result); + if (!parseResult.success) { + // Type guard: if success is false, error is guaranteed to exist + reject(parseResult.error); + } + else { + resolve(parseResult.data); + } + } + catch (error) { + reject(error); + } + }); + options?.signal?.addEventListener('abort', () => { + cancel(options?.signal?.reason); + }); + const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC; + const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, 'Request timed out', { timeout })); + this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false); + // Queue request if related to a task + const relatedTaskId = relatedTask?.taskId; + if (relatedTaskId) { + // Store the response resolver for this request so responses can be routed back + const responseResolver = (response) => { + const handler = this._responseHandlers.get(messageId); + if (handler) { + handler(response); + } + else { + // Log error when resolver is missing, but don't fail + this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`)); + } + }; + this._requestResolvers.set(messageId, responseResolver); + this._enqueueTaskMessage(relatedTaskId, { + type: 'request', + message: jsonrpcRequest, + timestamp: Date.now() + }).catch(error => { + this._cleanupTimeout(messageId); + reject(error); + }); + // Don't send through transport - queued messages are delivered via tasks/result only + // This prevents duplicate delivery for bidirectional transports + } + else { + // No related task - send through transport normally + this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch(error => { + this._cleanupTimeout(messageId); + reject(error); + }); + } + }); + } + /** + * Gets the current status of a task. + * + * @experimental Use `client.experimental.tasks.getTask()` to access this method. + */ + async getTask(params, options) { + // @ts-expect-error SendRequestT cannot directly contain GetTaskRequest, but we ensure all type instantiations contain it anyways + return this.request({ method: 'tasks/get', params }, GetTaskResultSchema, options); + } + /** + * Retrieves the result of a completed task. + * + * @experimental Use `client.experimental.tasks.getTaskResult()` to access this method. + */ + async getTaskResult(params, resultSchema, options) { + // @ts-expect-error SendRequestT cannot directly contain GetTaskPayloadRequest, but we ensure all type instantiations contain it anyways + return this.request({ method: 'tasks/result', params }, resultSchema, options); + } + /** + * Lists tasks, optionally starting from a pagination cursor. + * + * @experimental Use `client.experimental.tasks.listTasks()` to access this method. + */ + async listTasks(params, options) { + // @ts-expect-error SendRequestT cannot directly contain ListTasksRequest, but we ensure all type instantiations contain it anyways + return this.request({ method: 'tasks/list', params }, ListTasksResultSchema, options); + } + /** + * Cancels a specific task. + * + * @experimental Use `client.experimental.tasks.cancelTask()` to access this method. + */ + async cancelTask(params, options) { + // @ts-expect-error SendRequestT cannot directly contain CancelTaskRequest, but we ensure all type instantiations contain it anyways + return this.request({ method: 'tasks/cancel', params }, CancelTaskResultSchema, options); + } + /** + * Emits a notification, which is a one-way message that does not expect a response. + */ + async notification(notification, options) { + if (!this._transport) { + throw new Error('Not connected'); + } + this.assertNotificationCapability(notification.method); + // Queue notification if related to a task + const relatedTaskId = options?.relatedTask?.taskId; + if (relatedTaskId) { + // Build the JSONRPC notification with metadata + const jsonrpcNotification = { + ...notification, + jsonrpc: '2.0', + params: { + ...notification.params, + _meta: { + ...(notification.params?._meta || {}), + [RELATED_TASK_META_KEY]: options.relatedTask + } + } + }; + await this._enqueueTaskMessage(relatedTaskId, { + type: 'notification', + message: jsonrpcNotification, + timestamp: Date.now() + }); + // Don't send through transport - queued messages are delivered via tasks/result only + // This prevents duplicate delivery for bidirectional transports + return; + } + const debouncedMethods = this._options?.debouncedNotificationMethods ?? []; + // A notification can only be debounced if it's in the list AND it's "simple" + // (i.e., has no parameters and no related request ID or related task that could be lost). + const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !options?.relatedRequestId && !options?.relatedTask; + if (canDebounce) { + // If a notification of this type is already scheduled, do nothing. + if (this._pendingDebouncedNotifications.has(notification.method)) { + return; + } + // Mark this notification type as pending. + this._pendingDebouncedNotifications.add(notification.method); + // Schedule the actual send to happen in the next microtask. + // This allows all synchronous calls in the current event loop tick to be coalesced. + Promise.resolve().then(() => { + // Un-mark the notification so the next one can be scheduled. + this._pendingDebouncedNotifications.delete(notification.method); + // SAFETY CHECK: If the connection was closed while this was pending, abort. + if (!this._transport) { + return; + } + let jsonrpcNotification = { + ...notification, + jsonrpc: '2.0' + }; + // Augment with related task metadata if relatedTask is provided + if (options?.relatedTask) { + jsonrpcNotification = { + ...jsonrpcNotification, + params: { + ...jsonrpcNotification.params, + _meta: { + ...(jsonrpcNotification.params?._meta || {}), + [RELATED_TASK_META_KEY]: options.relatedTask + } + } + }; + } + // Send the notification, but don't await it here to avoid blocking. + // Handle potential errors with a .catch(). + this._transport?.send(jsonrpcNotification, options).catch(error => this._onerror(error)); + }); + // Return immediately. + return; + } + let jsonrpcNotification = { + ...notification, + jsonrpc: '2.0' + }; + // Augment with related task metadata if relatedTask is provided + if (options?.relatedTask) { + jsonrpcNotification = { + ...jsonrpcNotification, + params: { + ...jsonrpcNotification.params, + _meta: { + ...(jsonrpcNotification.params?._meta || {}), + [RELATED_TASK_META_KEY]: options.relatedTask + } + } + }; + } + await this._transport.send(jsonrpcNotification, options); + } + /** + * Registers a handler to invoke when this protocol object receives a request with the given method. + * + * Note that this will replace any previous request handler for the same method. + */ + setRequestHandler(requestSchema, handler) { + const method = getMethodLiteral(requestSchema); + this.assertRequestHandlerCapability(method); + this._requestHandlers.set(method, (request, extra) => { + const parsed = parseWithCompat(requestSchema, request); + return Promise.resolve(handler(parsed, extra)); + }); + } + /** + * Removes the request handler for the given method. + */ + removeRequestHandler(method) { + this._requestHandlers.delete(method); + } + /** + * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. + */ + assertCanSetRequestHandler(method) { + if (this._requestHandlers.has(method)) { + throw new Error(`A request handler for ${method} already exists, which would be overridden`); + } + } + /** + * Registers a handler to invoke when this protocol object receives a notification with the given method. + * + * Note that this will replace any previous notification handler for the same method. + */ + setNotificationHandler(notificationSchema, handler) { + const method = getMethodLiteral(notificationSchema); + this._notificationHandlers.set(method, notification => { + const parsed = parseWithCompat(notificationSchema, notification); + return Promise.resolve(handler(parsed)); + }); + } + /** + * Removes the notification handler for the given method. + */ + removeNotificationHandler(method) { + this._notificationHandlers.delete(method); + } + /** + * Cleans up the progress handler associated with a task. + * This should be called when a task reaches a terminal status. + */ + _cleanupTaskProgressHandler(taskId) { + const progressToken = this._taskProgressTokens.get(taskId); + if (progressToken !== undefined) { + this._progressHandlers.delete(progressToken); + this._taskProgressTokens.delete(taskId); + } + } + /** + * Enqueues a task-related message for side-channel delivery via tasks/result. + * @param taskId The task ID to associate the message with + * @param message The message to enqueue + * @param sessionId Optional session ID for binding the operation to a specific session + * @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow) + * + * Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle + * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer + * simply propagates the error. + */ + async _enqueueTaskMessage(taskId, message, sessionId) { + // Task message queues are only used when taskStore is configured + if (!this._taskStore || !this._taskMessageQueue) { + throw new Error('Cannot enqueue task message: taskStore and taskMessageQueue are not configured'); + } + const maxQueueSize = this._options?.maxTaskQueueSize; + await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize); + } + /** + * Clears the message queue for a task and rejects any pending request resolvers. + * @param taskId The task ID whose queue should be cleared + * @param sessionId Optional session ID for binding the operation to a specific session + */ + async _clearTaskQueue(taskId, sessionId) { + if (this._taskMessageQueue) { + // Reject any pending request resolvers + const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId); + for (const message of messages) { + if (message.type === 'request' && isJSONRPCRequest(message.message)) { + // Extract request ID from the message + const requestId = message.message.id; + const resolver = this._requestResolvers.get(requestId); + if (resolver) { + resolver(new McpError(ErrorCode.InternalError, 'Task cancelled or completed')); + this._requestResolvers.delete(requestId); + } + else { + // Log error when resolver is missing during cleanup for better observability + this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`)); + } + } + } + } + } + /** + * Waits for a task update (new messages or status change) with abort signal support. + * Uses polling to check for updates at the task's configured poll interval. + * @param taskId The task ID to wait for + * @param signal Abort signal to cancel the wait + * @returns Promise that resolves when an update occurs or rejects if aborted + */ + async _waitForTaskUpdate(taskId, signal) { + // Get the task's poll interval, falling back to default + let interval = this._options?.defaultTaskPollInterval ?? 1000; + try { + const task = await this._taskStore?.getTask(taskId); + if (task?.pollInterval) { + interval = task.pollInterval; + } + } + catch { + // Use default interval if task lookup fails + } + return new Promise((resolve, reject) => { + if (signal.aborted) { + reject(new McpError(ErrorCode.InvalidRequest, 'Request cancelled')); + return; + } + // Wait for the poll interval, then resolve so caller can check for updates + const timeoutId = setTimeout(resolve, interval); + // Clean up timeout and reject if aborted + signal.addEventListener('abort', () => { + clearTimeout(timeoutId); + reject(new McpError(ErrorCode.InvalidRequest, 'Request cancelled')); + }, { once: true }); + }); + } + requestTaskStore(request, sessionId) { + const taskStore = this._taskStore; + if (!taskStore) { + throw new Error('No task store configured'); + } + return { + createTask: async (taskParams) => { + if (!request) { + throw new Error('No request provided'); + } + return await taskStore.createTask(taskParams, request.id, { + method: request.method, + params: request.params + }, sessionId); + }, + getTask: async (taskId) => { + const task = await taskStore.getTask(taskId, sessionId); + if (!task) { + throw new McpError(ErrorCode.InvalidParams, 'Failed to retrieve task: Task not found'); + } + return task; + }, + storeTaskResult: async (taskId, status, result) => { + await taskStore.storeTaskResult(taskId, status, result, sessionId); + // Get updated task state and send notification + const task = await taskStore.getTask(taskId, sessionId); + if (task) { + const notification = TaskStatusNotificationSchema.parse({ + method: 'notifications/tasks/status', + params: task + }); + await this.notification(notification); + if (isTerminal(task.status)) { + this._cleanupTaskProgressHandler(taskId); + // Don't clear queue here - it will be cleared after delivery via tasks/result + } + } + }, + getTaskResult: taskId => { + return taskStore.getTaskResult(taskId, sessionId); + }, + updateTaskStatus: async (taskId, status, statusMessage) => { + // Check if task exists + const task = await taskStore.getTask(taskId, sessionId); + if (!task) { + throw new McpError(ErrorCode.InvalidParams, `Task "${taskId}" not found - it may have been cleaned up`); + } + // Don't allow transitions from terminal states + if (isTerminal(task.status)) { + throw new McpError(ErrorCode.InvalidParams, `Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`); + } + await taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId); + // Get updated task state and send notification + const updatedTask = await taskStore.getTask(taskId, sessionId); + if (updatedTask) { + const notification = TaskStatusNotificationSchema.parse({ + method: 'notifications/tasks/status', + params: updatedTask + }); + await this.notification(notification); + if (isTerminal(updatedTask.status)) { + this._cleanupTaskProgressHandler(taskId); + // Don't clear queue here - it will be cleared after delivery via tasks/result + } + } + }, + listTasks: cursor => { + return taskStore.listTasks(cursor, sessionId); + } + }; + } +} +function isPlainObject(value) { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} +export function mergeCapabilities(base, additional) { + const result = { ...base }; + for (const key in additional) { + const k = key; + const addValue = additional[k]; + if (addValue === undefined) + continue; + const baseValue = result[k]; + if (isPlainObject(baseValue) && isPlainObject(addValue)) { + result[k] = { ...baseValue, ...addValue }; + } + else { + result[k] = addValue; + } + } + return result; +} +//# sourceMappingURL=protocol.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js new file mode 100644 index 00000000..30f299f5 --- /dev/null +++ b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js @@ -0,0 +1,31 @@ +import { JSONRPCMessageSchema } from '../types.js'; +/** + * Buffers a continuous stdio stream into discrete JSON-RPC messages. + */ +export class ReadBuffer { + append(chunk) { + this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk; + } + readMessage() { + if (!this._buffer) { + return null; + } + const index = this._buffer.indexOf('\n'); + if (index === -1) { + return null; + } + const line = this._buffer.toString('utf8', 0, index).replace(/\r$/, ''); + this._buffer = this._buffer.subarray(index + 1); + return deserializeMessage(line); + } + clear() { + this._buffer = undefined; + } +} +export function deserializeMessage(line) { + return JSONRPCMessageSchema.parse(JSON.parse(line)); +} +export function serializeMessage(message) { + return JSON.stringify(message) + '\n'; +} +//# sourceMappingURL=stdio.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js new file mode 100644 index 00000000..ce25e23c --- /dev/null +++ b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js @@ -0,0 +1,39 @@ +/** + * Normalizes HeadersInit to a plain Record for manipulation. + * Handles Headers objects, arrays of tuples, and plain objects. + */ +export function normalizeHeaders(headers) { + if (!headers) + return {}; + if (headers instanceof Headers) { + return Object.fromEntries(headers.entries()); + } + if (Array.isArray(headers)) { + return Object.fromEntries(headers); + } + return { ...headers }; +} +/** + * Creates a fetch function that includes base RequestInit options. + * This ensures requests inherit settings like credentials, mode, headers, etc. from the base init. + * + * @param baseFetch - The base fetch function to wrap (defaults to global fetch) + * @param baseInit - The base RequestInit to merge with each request + * @returns A wrapped fetch function that merges base options with call-specific options + */ +export function createFetchWithInit(baseFetch = fetch, baseInit) { + if (!baseInit) { + return baseFetch; + } + // Return a wrapped fetch that merges base RequestInit with call-specific init + return async (url, init) => { + const mergedInit = { + ...baseInit, + ...init, + // Headers need special handling - merge instead of replace + headers: init?.headers ? { ...normalizeHeaders(baseInit.headers), ...normalizeHeaders(init.headers) } : baseInit.headers + }; + return baseFetch(url, mergedInit); + }; +} +//# sourceMappingURL=transport.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js new file mode 100644 index 00000000..8edb88ec --- /dev/null +++ b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js @@ -0,0 +1,2052 @@ +import * as z from 'zod/v4'; +export const LATEST_PROTOCOL_VERSION = '2025-11-25'; +export const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = '2025-03-26'; +export const SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, '2025-06-18', '2025-03-26', '2024-11-05', '2024-10-07']; +export const RELATED_TASK_META_KEY = 'io.modelcontextprotocol/related-task'; +/* JSON-RPC types */ +export const JSONRPC_VERSION = '2.0'; +/** + * Assert 'object' type schema. + * + * @internal + */ +const AssertObjectSchema = z.custom((v) => v !== null && (typeof v === 'object' || typeof v === 'function')); +/** + * A progress token, used to associate progress notifications with the original request. + */ +export const ProgressTokenSchema = z.union([z.string(), z.number().int()]); +/** + * An opaque token used to represent a cursor for pagination. + */ +export const CursorSchema = z.string(); +/** + * Task creation parameters, used to ask that the server create a task to represent a request. + */ +export const TaskCreationParamsSchema = z.looseObject({ + /** + * Time in milliseconds to keep task results available after completion. + * If null, the task has unlimited lifetime until manually cleaned up. + */ + ttl: z.union([z.number(), z.null()]).optional(), + /** + * Time in milliseconds to wait between task status requests. + */ + pollInterval: z.number().optional() +}); +export const TaskMetadataSchema = z.object({ + ttl: z.number().optional() +}); +/** + * Metadata for associating messages with a task. + * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. + */ +export const RelatedTaskMetadataSchema = z.object({ + taskId: z.string() +}); +const RequestMetaSchema = z.looseObject({ + /** + * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. + */ + progressToken: ProgressTokenSchema.optional(), + /** + * If specified, this request is related to the provided task. + */ + [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() +}); +/** + * Common params for any request. + */ +const BaseRequestParamsSchema = z.object({ + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta: RequestMetaSchema.optional() +}); +/** + * Common params for any task-augmented request. + */ +export const TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * If specified, the caller is requesting task-augmented execution for this request. + * The request will return a CreateTaskResult immediately, and the actual result can be + * retrieved later via tasks/result. + * + * Task augmentation is subject to capability negotiation - receivers MUST declare support + * for task augmentation of specific request types in their capabilities. + */ + task: TaskMetadataSchema.optional() +}); +/** + * Checks if a value is a valid TaskAugmentedRequestParams. + * @param value - The value to check. + * + * @returns True if the value is a valid TaskAugmentedRequestParams, false otherwise. + */ +export const isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success; +export const RequestSchema = z.object({ + method: z.string(), + params: BaseRequestParamsSchema.loose().optional() +}); +const NotificationsParamsSchema = z.object({ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: RequestMetaSchema.optional() +}); +export const NotificationSchema = z.object({ + method: z.string(), + params: NotificationsParamsSchema.loose().optional() +}); +export const ResultSchema = z.looseObject({ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: RequestMetaSchema.optional() +}); +/** + * A uniquely identifying ID for a request in JSON-RPC. + */ +export const RequestIdSchema = z.union([z.string(), z.number().int()]); +/** + * A request that expects a response. + */ +export const JSONRPCRequestSchema = z + .object({ + jsonrpc: z.literal(JSONRPC_VERSION), + id: RequestIdSchema, + ...RequestSchema.shape +}) + .strict(); +export const isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success; +/** + * A notification which does not expect a response. + */ +export const JSONRPCNotificationSchema = z + .object({ + jsonrpc: z.literal(JSONRPC_VERSION), + ...NotificationSchema.shape +}) + .strict(); +export const isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success; +/** + * A successful (non-error) response to a request. + */ +export const JSONRPCResultResponseSchema = z + .object({ + jsonrpc: z.literal(JSONRPC_VERSION), + id: RequestIdSchema, + result: ResultSchema +}) + .strict(); +/** + * Checks if a value is a valid JSONRPCResultResponse. + * @param value - The value to check. + * + * @returns True if the value is a valid JSONRPCResultResponse, false otherwise. + */ +export const isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success; +/** + * @deprecated Use {@link isJSONRPCResultResponse} instead. + * + * Please note that {@link JSONRPCResponse} is a union of {@link JSONRPCResultResponse} and {@link JSONRPCErrorResponse} as per the updated JSON-RPC specification. (was previously just {@link JSONRPCResultResponse}) + */ +export const isJSONRPCResponse = isJSONRPCResultResponse; +/** + * Error codes defined by the JSON-RPC specification. + */ +export var ErrorCode; +(function (ErrorCode) { + // SDK error codes + ErrorCode[ErrorCode["ConnectionClosed"] = -32000] = "ConnectionClosed"; + ErrorCode[ErrorCode["RequestTimeout"] = -32001] = "RequestTimeout"; + // Standard JSON-RPC error codes + ErrorCode[ErrorCode["ParseError"] = -32700] = "ParseError"; + ErrorCode[ErrorCode["InvalidRequest"] = -32600] = "InvalidRequest"; + ErrorCode[ErrorCode["MethodNotFound"] = -32601] = "MethodNotFound"; + ErrorCode[ErrorCode["InvalidParams"] = -32602] = "InvalidParams"; + ErrorCode[ErrorCode["InternalError"] = -32603] = "InternalError"; + // MCP-specific error codes + ErrorCode[ErrorCode["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; +})(ErrorCode || (ErrorCode = {})); +/** + * A response to a request that indicates an error occurred. + */ +export const JSONRPCErrorResponseSchema = z + .object({ + jsonrpc: z.literal(JSONRPC_VERSION), + id: RequestIdSchema.optional(), + error: z.object({ + /** + * The error type that occurred. + */ + code: z.number().int(), + /** + * A short description of the error. The message SHOULD be limited to a concise single sentence. + */ + message: z.string(), + /** + * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). + */ + data: z.unknown().optional() + }) +}) + .strict(); +/** + * @deprecated Use {@link JSONRPCErrorResponseSchema} instead. + */ +export const JSONRPCErrorSchema = JSONRPCErrorResponseSchema; +/** + * Checks if a value is a valid JSONRPCErrorResponse. + * @param value - The value to check. + * + * @returns True if the value is a valid JSONRPCErrorResponse, false otherwise. + */ +export const isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success; +/** + * @deprecated Use {@link isJSONRPCErrorResponse} instead. + */ +export const isJSONRPCError = isJSONRPCErrorResponse; +export const JSONRPCMessageSchema = z.union([ + JSONRPCRequestSchema, + JSONRPCNotificationSchema, + JSONRPCResultResponseSchema, + JSONRPCErrorResponseSchema +]); +export const JSONRPCResponseSchema = z.union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]); +/* Empty result */ +/** + * A response that indicates success but carries no data. + */ +export const EmptyResultSchema = ResultSchema.strict(); +export const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The ID of the request to cancel. + * + * This MUST correspond to the ID of a request previously issued in the same direction. + */ + requestId: RequestIdSchema.optional(), + /** + * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. + */ + reason: z.string().optional() +}); +/* Cancellation */ +/** + * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. + * + * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. + * + * This notification indicates that the result will be unused, so any associated processing SHOULD cease. + * + * A client MUST NOT attempt to cancel its `initialize` request. + */ +export const CancelledNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/cancelled'), + params: CancelledNotificationParamsSchema +}); +/* Base Metadata */ +/** + * Icon schema for use in tools, prompts, resources, and implementations. + */ +export const IconSchema = z.object({ + /** + * URL or data URI for the icon. + */ + src: z.string(), + /** + * Optional MIME type for the icon. + */ + mimeType: z.string().optional(), + /** + * Optional array of strings that specify sizes at which the icon can be used. + * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. + * + * If not provided, the client should assume that the icon can be used at any size. + */ + sizes: z.array(z.string()).optional(), + /** + * Optional specifier for the theme this icon is designed for. `light` indicates + * the icon is designed to be used with a light background, and `dark` indicates + * the icon is designed to be used with a dark background. + * + * If not provided, the client should assume the icon can be used with any theme. + */ + theme: z.enum(['light', 'dark']).optional() +}); +/** + * Base schema to add `icons` property. + * + */ +export const IconsSchema = z.object({ + /** + * Optional set of sized icons that the client can display in a user interface. + * + * Clients that support rendering icons MUST support at least the following MIME types: + * - `image/png` - PNG images (safe, universal compatibility) + * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility) + * + * Clients that support rendering icons SHOULD also support: + * - `image/svg+xml` - SVG images (scalable but requires security precautions) + * - `image/webp` - WebP images (modern, efficient format) + */ + icons: z.array(IconSchema).optional() +}); +/** + * Base metadata interface for common properties across resources, tools, prompts, and implementations. + */ +export const BaseMetadataSchema = z.object({ + /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */ + name: z.string(), + /** + * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, + * even by those unfamiliar with domain-specific terminology. + * + * If not provided, the name should be used for display (except for Tool, + * where `annotations.title` should be given precedence over using `name`, + * if present). + */ + title: z.string().optional() +}); +/* Initialization */ +/** + * Describes the name and version of an MCP implementation. + */ +export const ImplementationSchema = BaseMetadataSchema.extend({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + version: z.string(), + /** + * An optional URL of the website for this implementation. + */ + websiteUrl: z.string().optional(), + /** + * An optional human-readable description of what this implementation does. + * + * This can be used by clients or servers to provide context about their purpose + * and capabilities. For example, a server might describe the types of resources + * or tools it provides, while a client might describe its intended use case. + */ + description: z.string().optional() +}); +const FormElicitationCapabilitySchema = z.intersection(z.object({ + applyDefaults: z.boolean().optional() +}), z.record(z.string(), z.unknown())); +const ElicitationCapabilitySchema = z.preprocess(value => { + if (value && typeof value === 'object' && !Array.isArray(value)) { + if (Object.keys(value).length === 0) { + return { form: {} }; + } + } + return value; +}, z.intersection(z.object({ + form: FormElicitationCapabilitySchema.optional(), + url: AssertObjectSchema.optional() +}), z.record(z.string(), z.unknown()).optional())); +/** + * Task capabilities for clients, indicating which request types support task creation. + */ +export const ClientTasksCapabilitySchema = z.looseObject({ + /** + * Present if the client supports listing tasks. + */ + list: AssertObjectSchema.optional(), + /** + * Present if the client supports cancelling tasks. + */ + cancel: AssertObjectSchema.optional(), + /** + * Capabilities for task creation on specific request types. + */ + requests: z + .looseObject({ + /** + * Task support for sampling requests. + */ + sampling: z + .looseObject({ + createMessage: AssertObjectSchema.optional() + }) + .optional(), + /** + * Task support for elicitation requests. + */ + elicitation: z + .looseObject({ + create: AssertObjectSchema.optional() + }) + .optional() + }) + .optional() +}); +/** + * Task capabilities for servers, indicating which request types support task creation. + */ +export const ServerTasksCapabilitySchema = z.looseObject({ + /** + * Present if the server supports listing tasks. + */ + list: AssertObjectSchema.optional(), + /** + * Present if the server supports cancelling tasks. + */ + cancel: AssertObjectSchema.optional(), + /** + * Capabilities for task creation on specific request types. + */ + requests: z + .looseObject({ + /** + * Task support for tool requests. + */ + tools: z + .looseObject({ + call: AssertObjectSchema.optional() + }) + .optional() + }) + .optional() +}); +/** + * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. + */ +export const ClientCapabilitiesSchema = z.object({ + /** + * Experimental, non-standard capabilities that the client supports. + */ + experimental: z.record(z.string(), AssertObjectSchema).optional(), + /** + * Present if the client supports sampling from an LLM. + */ + sampling: z + .object({ + /** + * Present if the client supports context inclusion via includeContext parameter. + * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it). + */ + context: AssertObjectSchema.optional(), + /** + * Present if the client supports tool use via tools and toolChoice parameters. + */ + tools: AssertObjectSchema.optional() + }) + .optional(), + /** + * Present if the client supports eliciting user input. + */ + elicitation: ElicitationCapabilitySchema.optional(), + /** + * Present if the client supports listing roots. + */ + roots: z + .object({ + /** + * Whether the client supports issuing notifications for changes to the roots list. + */ + listChanged: z.boolean().optional() + }) + .optional(), + /** + * Present if the client supports task creation. + */ + tasks: ClientTasksCapabilitySchema.optional() +}); +export const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. + */ + protocolVersion: z.string(), + capabilities: ClientCapabilitiesSchema, + clientInfo: ImplementationSchema +}); +/** + * This request is sent from the client to the server when it first connects, asking it to begin initialization. + */ +export const InitializeRequestSchema = RequestSchema.extend({ + method: z.literal('initialize'), + params: InitializeRequestParamsSchema +}); +export const isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success; +/** + * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. + */ +export const ServerCapabilitiesSchema = z.object({ + /** + * Experimental, non-standard capabilities that the server supports. + */ + experimental: z.record(z.string(), AssertObjectSchema).optional(), + /** + * Present if the server supports sending log messages to the client. + */ + logging: AssertObjectSchema.optional(), + /** + * Present if the server supports sending completions to the client. + */ + completions: AssertObjectSchema.optional(), + /** + * Present if the server offers any prompt templates. + */ + prompts: z + .object({ + /** + * Whether this server supports issuing notifications for changes to the prompt list. + */ + listChanged: z.boolean().optional() + }) + .optional(), + /** + * Present if the server offers any resources to read. + */ + resources: z + .object({ + /** + * Whether this server supports clients subscribing to resource updates. + */ + subscribe: z.boolean().optional(), + /** + * Whether this server supports issuing notifications for changes to the resource list. + */ + listChanged: z.boolean().optional() + }) + .optional(), + /** + * Present if the server offers any tools to call. + */ + tools: z + .object({ + /** + * Whether this server supports issuing notifications for changes to the tool list. + */ + listChanged: z.boolean().optional() + }) + .optional(), + /** + * Present if the server supports task creation. + */ + tasks: ServerTasksCapabilitySchema.optional() +}); +/** + * After receiving an initialize request from the client, the server sends this response. + */ +export const InitializeResultSchema = ResultSchema.extend({ + /** + * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. + */ + protocolVersion: z.string(), + capabilities: ServerCapabilitiesSchema, + serverInfo: ImplementationSchema, + /** + * Instructions describing how to use the server and its features. + * + * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. + */ + instructions: z.string().optional() +}); +/** + * This notification is sent from the client to the server after initialization has finished. + */ +export const InitializedNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/initialized'), + params: NotificationsParamsSchema.optional() +}); +export const isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success; +/* Ping */ +/** + * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. + */ +export const PingRequestSchema = RequestSchema.extend({ + method: z.literal('ping'), + params: BaseRequestParamsSchema.optional() +}); +/* Progress notifications */ +export const ProgressSchema = z.object({ + /** + * The progress thus far. This should increase every time progress is made, even if the total is unknown. + */ + progress: z.number(), + /** + * Total number of items to process (or total progress required), if known. + */ + total: z.optional(z.number()), + /** + * An optional message describing the current progress. + */ + message: z.optional(z.string()) +}); +export const ProgressNotificationParamsSchema = z.object({ + ...NotificationsParamsSchema.shape, + ...ProgressSchema.shape, + /** + * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. + */ + progressToken: ProgressTokenSchema +}); +/** + * An out-of-band notification used to inform the receiver of a progress update for a long-running request. + * + * @category notifications/progress + */ +export const ProgressNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/progress'), + params: ProgressNotificationParamsSchema +}); +export const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * An opaque token representing the current pagination position. + * If provided, the server should return results starting after this cursor. + */ + cursor: CursorSchema.optional() +}); +/* Pagination */ +export const PaginatedRequestSchema = RequestSchema.extend({ + params: PaginatedRequestParamsSchema.optional() +}); +export const PaginatedResultSchema = ResultSchema.extend({ + /** + * An opaque token representing the pagination position after the last returned result. + * If present, there may be more results available. + */ + nextCursor: CursorSchema.optional() +}); +/** + * The status of a task. + * */ +export const TaskStatusSchema = z.enum(['working', 'input_required', 'completed', 'failed', 'cancelled']); +/* Tasks */ +/** + * A pollable state object associated with a request. + */ +export const TaskSchema = z.object({ + taskId: z.string(), + status: TaskStatusSchema, + /** + * Time in milliseconds to keep task results available after completion. + * If null, the task has unlimited lifetime until manually cleaned up. + */ + ttl: z.union([z.number(), z.null()]), + /** + * ISO 8601 timestamp when the task was created. + */ + createdAt: z.string(), + /** + * ISO 8601 timestamp when the task was last updated. + */ + lastUpdatedAt: z.string(), + pollInterval: z.optional(z.number()), + /** + * Optional diagnostic message for failed tasks or other status information. + */ + statusMessage: z.optional(z.string()) +}); +/** + * Result returned when a task is created, containing the task data wrapped in a task field. + */ +export const CreateTaskResultSchema = ResultSchema.extend({ + task: TaskSchema +}); +/** + * Parameters for task status notification. + */ +export const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema); +/** + * A notification sent when a task's status changes. + */ +export const TaskStatusNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/tasks/status'), + params: TaskStatusNotificationParamsSchema +}); +/** + * A request to get the state of a specific task. + */ +export const GetTaskRequestSchema = RequestSchema.extend({ + method: z.literal('tasks/get'), + params: BaseRequestParamsSchema.extend({ + taskId: z.string() + }) +}); +/** + * The response to a tasks/get request. + */ +export const GetTaskResultSchema = ResultSchema.merge(TaskSchema); +/** + * A request to get the result of a specific task. + */ +export const GetTaskPayloadRequestSchema = RequestSchema.extend({ + method: z.literal('tasks/result'), + params: BaseRequestParamsSchema.extend({ + taskId: z.string() + }) +}); +/** + * The response to a tasks/result request. + * The structure matches the result type of the original request. + * For example, a tools/call task would return the CallToolResult structure. + * + */ +export const GetTaskPayloadResultSchema = ResultSchema.loose(); +/** + * A request to list tasks. + */ +export const ListTasksRequestSchema = PaginatedRequestSchema.extend({ + method: z.literal('tasks/list') +}); +/** + * The response to a tasks/list request. + */ +export const ListTasksResultSchema = PaginatedResultSchema.extend({ + tasks: z.array(TaskSchema) +}); +/** + * A request to cancel a specific task. + */ +export const CancelTaskRequestSchema = RequestSchema.extend({ + method: z.literal('tasks/cancel'), + params: BaseRequestParamsSchema.extend({ + taskId: z.string() + }) +}); +/** + * The response to a tasks/cancel request. + */ +export const CancelTaskResultSchema = ResultSchema.merge(TaskSchema); +/* Resources */ +/** + * The contents of a specific resource or sub-resource. + */ +export const ResourceContentsSchema = z.object({ + /** + * The URI of this resource. + */ + uri: z.string(), + /** + * The MIME type of this resource, if known. + */ + mimeType: z.optional(z.string()), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +export const TextResourceContentsSchema = ResourceContentsSchema.extend({ + /** + * The text of the item. This must only be set if the item can actually be represented as text (not binary data). + */ + text: z.string() +}); +/** + * A Zod schema for validating Base64 strings that is more performant and + * robust for very large inputs than the default regex-based check. It avoids + * stack overflows by using the native `atob` function for validation. + */ +const Base64Schema = z.string().refine(val => { + try { + // atob throws a DOMException if the string contains characters + // that are not part of the Base64 character set. + atob(val); + return true; + } + catch { + return false; + } +}, { message: 'Invalid Base64 string' }); +export const BlobResourceContentsSchema = ResourceContentsSchema.extend({ + /** + * A base64-encoded string representing the binary data of the item. + */ + blob: Base64Schema +}); +/** + * The sender or recipient of messages and data in a conversation. + */ +export const RoleSchema = z.enum(['user', 'assistant']); +/** + * Optional annotations providing clients additional context about a resource. + */ +export const AnnotationsSchema = z.object({ + /** + * Intended audience(s) for the resource. + */ + audience: z.array(RoleSchema).optional(), + /** + * Importance hint for the resource, from 0 (least) to 1 (most). + */ + priority: z.number().min(0).max(1).optional(), + /** + * ISO 8601 timestamp for the most recent modification. + */ + lastModified: z.iso.datetime({ offset: true }).optional() +}); +/** + * A known resource that the server is capable of reading. + */ +export const ResourceSchema = z.object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * The URI of this resource. + */ + uri: z.string(), + /** + * A description of what this resource represents. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description: z.optional(z.string()), + /** + * The MIME type of this resource, if known. + */ + mimeType: z.optional(z.string()), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.looseObject({})) +}); +/** + * A template description for resources available on the server. + */ +export const ResourceTemplateSchema = z.object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * A URI template (according to RFC 6570) that can be used to construct resource URIs. + */ + uriTemplate: z.string(), + /** + * A description of what this template is for. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description: z.optional(z.string()), + /** + * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. + */ + mimeType: z.optional(z.string()), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.looseObject({})) +}); +/** + * Sent from the client to request a list of resources the server has. + */ +export const ListResourcesRequestSchema = PaginatedRequestSchema.extend({ + method: z.literal('resources/list') +}); +/** + * The server's response to a resources/list request from the client. + */ +export const ListResourcesResultSchema = PaginatedResultSchema.extend({ + resources: z.array(ResourceSchema) +}); +/** + * Sent from the client to request a list of resource templates the server has. + */ +export const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ + method: z.literal('resources/templates/list') +}); +/** + * The server's response to a resources/templates/list request from the client. + */ +export const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ + resourceTemplates: z.array(ResourceTemplateSchema) +}); +export const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it. + * + * @format uri + */ + uri: z.string() +}); +/** + * Parameters for a `resources/read` request. + */ +export const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; +/** + * Sent from the client to the server, to read a specific resource URI. + */ +export const ReadResourceRequestSchema = RequestSchema.extend({ + method: z.literal('resources/read'), + params: ReadResourceRequestParamsSchema +}); +/** + * The server's response to a resources/read request from the client. + */ +export const ReadResourceResultSchema = ResultSchema.extend({ + contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema])) +}); +/** + * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. + */ +export const ResourceListChangedNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/resources/list_changed'), + params: NotificationsParamsSchema.optional() +}); +export const SubscribeRequestParamsSchema = ResourceRequestParamsSchema; +/** + * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. + */ +export const SubscribeRequestSchema = RequestSchema.extend({ + method: z.literal('resources/subscribe'), + params: SubscribeRequestParamsSchema +}); +export const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; +/** + * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. + */ +export const UnsubscribeRequestSchema = RequestSchema.extend({ + method: z.literal('resources/unsubscribe'), + params: UnsubscribeRequestParamsSchema +}); +/** + * Parameters for a `notifications/resources/updated` notification. + */ +export const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. + */ + uri: z.string() +}); +/** + * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request. + */ +export const ResourceUpdatedNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/resources/updated'), + params: ResourceUpdatedNotificationParamsSchema +}); +/* Prompts */ +/** + * Describes an argument that a prompt can accept. + */ +export const PromptArgumentSchema = z.object({ + /** + * The name of the argument. + */ + name: z.string(), + /** + * A human-readable description of the argument. + */ + description: z.optional(z.string()), + /** + * Whether this argument must be provided. + */ + required: z.optional(z.boolean()) +}); +/** + * A prompt or prompt template that the server offers. + */ +export const PromptSchema = z.object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * An optional description of what this prompt provides + */ + description: z.optional(z.string()), + /** + * A list of arguments to use for templating the prompt. + */ + arguments: z.optional(z.array(PromptArgumentSchema)), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.looseObject({})) +}); +/** + * Sent from the client to request a list of prompts and prompt templates the server has. + */ +export const ListPromptsRequestSchema = PaginatedRequestSchema.extend({ + method: z.literal('prompts/list') +}); +/** + * The server's response to a prompts/list request from the client. + */ +export const ListPromptsResultSchema = PaginatedResultSchema.extend({ + prompts: z.array(PromptSchema) +}); +/** + * Parameters for a `prompts/get` request. + */ +export const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The name of the prompt or prompt template. + */ + name: z.string(), + /** + * Arguments to use for templating the prompt. + */ + arguments: z.record(z.string(), z.string()).optional() +}); +/** + * Used by the client to get a prompt provided by the server. + */ +export const GetPromptRequestSchema = RequestSchema.extend({ + method: z.literal('prompts/get'), + params: GetPromptRequestParamsSchema +}); +/** + * Text provided to or from an LLM. + */ +export const TextContentSchema = z.object({ + type: z.literal('text'), + /** + * The text content of the message. + */ + text: z.string(), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * An image provided to or from an LLM. + */ +export const ImageContentSchema = z.object({ + type: z.literal('image'), + /** + * The base64-encoded image data. + */ + data: Base64Schema, + /** + * The MIME type of the image. Different providers may support different image types. + */ + mimeType: z.string(), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * An Audio provided to or from an LLM. + */ +export const AudioContentSchema = z.object({ + type: z.literal('audio'), + /** + * The base64-encoded audio data. + */ + data: Base64Schema, + /** + * The MIME type of the audio. Different providers may support different audio types. + */ + mimeType: z.string(), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * A tool call request from an assistant (LLM). + * Represents the assistant's request to use a tool. + */ +export const ToolUseContentSchema = z.object({ + type: z.literal('tool_use'), + /** + * The name of the tool to invoke. + * Must match a tool name from the request's tools array. + */ + name: z.string(), + /** + * Unique identifier for this tool call. + * Used to correlate with ToolResultContent in subsequent messages. + */ + id: z.string(), + /** + * Arguments to pass to the tool. + * Must conform to the tool's inputSchema. + */ + input: z.record(z.string(), z.unknown()), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * The contents of a resource, embedded into a prompt or tool call result. + */ +export const EmbeddedResourceSchema = z.object({ + type: z.literal('resource'), + resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * A resource that the server is capable of reading, included in a prompt or tool call result. + * + * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests. + */ +export const ResourceLinkSchema = ResourceSchema.extend({ + type: z.literal('resource_link') +}); +/** + * A content block that can be used in prompts and tool results. + */ +export const ContentBlockSchema = z.union([ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ResourceLinkSchema, + EmbeddedResourceSchema +]); +/** + * Describes a message returned as part of a prompt. + */ +export const PromptMessageSchema = z.object({ + role: RoleSchema, + content: ContentBlockSchema +}); +/** + * The server's response to a prompts/get request from the client. + */ +export const GetPromptResultSchema = ResultSchema.extend({ + /** + * An optional description for the prompt. + */ + description: z.string().optional(), + messages: z.array(PromptMessageSchema) +}); +/** + * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. + */ +export const PromptListChangedNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/prompts/list_changed'), + params: NotificationsParamsSchema.optional() +}); +/* Tools */ +/** + * Additional properties describing a Tool to clients. + * + * NOTE: all properties in ToolAnnotations are **hints**. + * They are not guaranteed to provide a faithful description of + * tool behavior (including descriptive properties like `title`). + * + * Clients should never make tool use decisions based on ToolAnnotations + * received from untrusted servers. + */ +export const ToolAnnotationsSchema = z.object({ + /** + * A human-readable title for the tool. + */ + title: z.string().optional(), + /** + * If true, the tool does not modify its environment. + * + * Default: false + */ + readOnlyHint: z.boolean().optional(), + /** + * If true, the tool may perform destructive updates to its environment. + * If false, the tool performs only additive updates. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: true + */ + destructiveHint: z.boolean().optional(), + /** + * If true, calling the tool repeatedly with the same arguments + * will have no additional effect on the its environment. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: false + */ + idempotentHint: z.boolean().optional(), + /** + * If true, this tool may interact with an "open world" of external + * entities. If false, the tool's domain of interaction is closed. + * For example, the world of a web search tool is open, whereas that + * of a memory tool is not. + * + * Default: true + */ + openWorldHint: z.boolean().optional() +}); +/** + * Execution-related properties for a tool. + */ +export const ToolExecutionSchema = z.object({ + /** + * Indicates the tool's preference for task-augmented execution. + * - "required": Clients MUST invoke the tool as a task + * - "optional": Clients MAY invoke the tool as a task or normal request + * - "forbidden": Clients MUST NOT attempt to invoke the tool as a task + * + * If not present, defaults to "forbidden". + */ + taskSupport: z.enum(['required', 'optional', 'forbidden']).optional() +}); +/** + * Definition for a tool the client can call. + */ +export const ToolSchema = z.object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * A human-readable description of the tool. + */ + description: z.string().optional(), + /** + * A JSON Schema 2020-12 object defining the expected parameters for the tool. + * Must have type: 'object' at the root level per MCP spec. + */ + inputSchema: z + .object({ + type: z.literal('object'), + properties: z.record(z.string(), AssertObjectSchema).optional(), + required: z.array(z.string()).optional() + }) + .catchall(z.unknown()), + /** + * An optional JSON Schema 2020-12 object defining the structure of the tool's output + * returned in the structuredContent field of a CallToolResult. + * Must have type: 'object' at the root level per MCP spec. + */ + outputSchema: z + .object({ + type: z.literal('object'), + properties: z.record(z.string(), AssertObjectSchema).optional(), + required: z.array(z.string()).optional() + }) + .catchall(z.unknown()) + .optional(), + /** + * Optional additional tool information. + */ + annotations: ToolAnnotationsSchema.optional(), + /** + * Execution-related properties for this tool. + */ + execution: ToolExecutionSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * Sent from the client to request a list of tools the server has. + */ +export const ListToolsRequestSchema = PaginatedRequestSchema.extend({ + method: z.literal('tools/list') +}); +/** + * The server's response to a tools/list request from the client. + */ +export const ListToolsResultSchema = PaginatedResultSchema.extend({ + tools: z.array(ToolSchema) +}); +/** + * The server's response to a tool call. + */ +export const CallToolResultSchema = ResultSchema.extend({ + /** + * A list of content objects that represent the result of the tool call. + * + * If the Tool does not define an outputSchema, this field MUST be present in the result. + * For backwards compatibility, this field is always present, but it may be empty. + */ + content: z.array(ContentBlockSchema).default([]), + /** + * An object containing structured tool output. + * + * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema. + */ + structuredContent: z.record(z.string(), z.unknown()).optional(), + /** + * Whether the tool call ended in an error. + * + * If not set, this is assumed to be false (the call was successful). + * + * Any errors that originate from the tool SHOULD be reported inside the result + * object, with `isError` set to true, _not_ as an MCP protocol-level error + * response. Otherwise, the LLM would not be able to see that an error occurred + * and self-correct. + * + * However, any errors in _finding_ the tool, an error indicating that the + * server does not support tool calls, or any other exceptional conditions, + * should be reported as an MCP error response. + */ + isError: z.boolean().optional() +}); +/** + * CallToolResultSchema extended with backwards compatibility to protocol version 2024-10-07. + */ +export const CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({ + toolResult: z.unknown() +})); +/** + * Parameters for a `tools/call` request. + */ +export const CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + /** + * The name of the tool to call. + */ + name: z.string(), + /** + * Arguments to pass to the tool. + */ + arguments: z.record(z.string(), z.unknown()).optional() +}); +/** + * Used by the client to invoke a tool provided by the server. + */ +export const CallToolRequestSchema = RequestSchema.extend({ + method: z.literal('tools/call'), + params: CallToolRequestParamsSchema +}); +/** + * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. + */ +export const ToolListChangedNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/tools/list_changed'), + params: NotificationsParamsSchema.optional() +}); +/** + * Base schema for list changed subscription options (without callback). + * Used internally for Zod validation of autoRefresh and debounceMs. + */ +export const ListChangedOptionsBaseSchema = z.object({ + /** + * If true, the list will be refreshed automatically when a list changed notification is received. + * The callback will be called with the updated list. + * + * If false, the callback will be called with null items, allowing manual refresh. + * + * @default true + */ + autoRefresh: z.boolean().default(true), + /** + * Debounce time in milliseconds for list changed notification processing. + * + * Multiple notifications received within this timeframe will only trigger one refresh. + * Set to 0 to disable debouncing. + * + * @default 300 + */ + debounceMs: z.number().int().nonnegative().default(300) +}); +/* Logging */ +/** + * The severity of a log message. + */ +export const LoggingLevelSchema = z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']); +/** + * Parameters for a `logging/setLevel` request. + */ +export const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message. + */ + level: LoggingLevelSchema +}); +/** + * A request from the client to the server, to enable or adjust logging. + */ +export const SetLevelRequestSchema = RequestSchema.extend({ + method: z.literal('logging/setLevel'), + params: SetLevelRequestParamsSchema +}); +/** + * Parameters for a `notifications/message` notification. + */ +export const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The severity of this log message. + */ + level: LoggingLevelSchema, + /** + * An optional name of the logger issuing this message. + */ + logger: z.string().optional(), + /** + * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. + */ + data: z.unknown() +}); +/** + * Notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically. + */ +export const LoggingMessageNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/message'), + params: LoggingMessageNotificationParamsSchema +}); +/* Sampling */ +/** + * Hints to use for model selection. + */ +export const ModelHintSchema = z.object({ + /** + * A hint for a model name. + */ + name: z.string().optional() +}); +/** + * The server's preferences for model selection, requested of the client during sampling. + */ +export const ModelPreferencesSchema = z.object({ + /** + * Optional hints to use for model selection. + */ + hints: z.array(ModelHintSchema).optional(), + /** + * How much to prioritize cost when selecting a model. + */ + costPriority: z.number().min(0).max(1).optional(), + /** + * How much to prioritize sampling speed (latency) when selecting a model. + */ + speedPriority: z.number().min(0).max(1).optional(), + /** + * How much to prioritize intelligence and capabilities when selecting a model. + */ + intelligencePriority: z.number().min(0).max(1).optional() +}); +/** + * Controls tool usage behavior in sampling requests. + */ +export const ToolChoiceSchema = z.object({ + /** + * Controls when tools are used: + * - "auto": Model decides whether to use tools (default) + * - "required": Model MUST use at least one tool before completing + * - "none": Model MUST NOT use any tools + */ + mode: z.enum(['auto', 'required', 'none']).optional() +}); +/** + * The result of a tool execution, provided by the user (server). + * Represents the outcome of invoking a tool requested via ToolUseContent. + */ +export const ToolResultContentSchema = z.object({ + type: z.literal('tool_result'), + toolUseId: z.string().describe('The unique identifier for the corresponding tool call.'), + content: z.array(ContentBlockSchema).default([]), + structuredContent: z.object({}).loose().optional(), + isError: z.boolean().optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * Basic content types for sampling responses (without tool use). + * Used for backwards-compatible CreateMessageResult when tools are not used. + */ +export const SamplingContentSchema = z.discriminatedUnion('type', [TextContentSchema, ImageContentSchema, AudioContentSchema]); +/** + * Content block types allowed in sampling messages. + * This includes text, image, audio, tool use requests, and tool results. + */ +export const SamplingMessageContentBlockSchema = z.discriminatedUnion('type', [ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ToolUseContentSchema, + ToolResultContentSchema +]); +/** + * Describes a message issued to or received from an LLM API. + */ +export const SamplingMessageSchema = z.object({ + role: RoleSchema, + content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * Parameters for a `sampling/createMessage` request. + */ +export const CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + messages: z.array(SamplingMessageSchema), + /** + * The server's preferences for which model to select. The client MAY modify or omit this request. + */ + modelPreferences: ModelPreferencesSchema.optional(), + /** + * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. + */ + systemPrompt: z.string().optional(), + /** + * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. + * The client MAY ignore this request. + * + * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client + * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases. + */ + includeContext: z.enum(['none', 'thisServer', 'allServers']).optional(), + temperature: z.number().optional(), + /** + * The requested maximum number of tokens to sample (to prevent runaway completions). + * + * The client MAY choose to sample fewer tokens than the requested maximum. + */ + maxTokens: z.number().int(), + stopSequences: z.array(z.string()).optional(), + /** + * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. + */ + metadata: AssertObjectSchema.optional(), + /** + * Tools that the model may use during generation. + * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + */ + tools: z.array(ToolSchema).optional(), + /** + * Controls how the model uses tools. + * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + * Default is `{ mode: "auto" }`. + */ + toolChoice: ToolChoiceSchema.optional() +}); +/** + * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. + */ +export const CreateMessageRequestSchema = RequestSchema.extend({ + method: z.literal('sampling/createMessage'), + params: CreateMessageRequestParamsSchema +}); +/** + * The client's response to a sampling/create_message request from the server. + * This is the backwards-compatible version that returns single content (no arrays). + * Used when the request does not include tools. + */ +export const CreateMessageResultSchema = ResultSchema.extend({ + /** + * The name of the model that generated the message. + */ + model: z.string(), + /** + * The reason why sampling stopped, if known. + * + * Standard values: + * - "endTurn": Natural end of the assistant's turn + * - "stopSequence": A stop sequence was encountered + * - "maxTokens": Maximum token limit was reached + * + * This field is an open string to allow for provider-specific stop reasons. + */ + stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens']).or(z.string())), + role: RoleSchema, + /** + * Response content. Single content block (text, image, or audio). + */ + content: SamplingContentSchema +}); +/** + * The client's response to a sampling/create_message request when tools were provided. + * This version supports array content for tool use flows. + */ +export const CreateMessageResultWithToolsSchema = ResultSchema.extend({ + /** + * The name of the model that generated the message. + */ + model: z.string(), + /** + * The reason why sampling stopped, if known. + * + * Standard values: + * - "endTurn": Natural end of the assistant's turn + * - "stopSequence": A stop sequence was encountered + * - "maxTokens": Maximum token limit was reached + * - "toolUse": The model wants to use one or more tools + * + * This field is an open string to allow for provider-specific stop reasons. + */ + stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens', 'toolUse']).or(z.string())), + role: RoleSchema, + /** + * Response content. May be a single block or array. May include ToolUseContent if stopReason is "toolUse". + */ + content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]) +}); +/* Elicitation */ +/** + * Primitive schema definition for boolean fields. + */ +export const BooleanSchemaSchema = z.object({ + type: z.literal('boolean'), + title: z.string().optional(), + description: z.string().optional(), + default: z.boolean().optional() +}); +/** + * Primitive schema definition for string fields. + */ +export const StringSchemaSchema = z.object({ + type: z.literal('string'), + title: z.string().optional(), + description: z.string().optional(), + minLength: z.number().optional(), + maxLength: z.number().optional(), + format: z.enum(['email', 'uri', 'date', 'date-time']).optional(), + default: z.string().optional() +}); +/** + * Primitive schema definition for number fields. + */ +export const NumberSchemaSchema = z.object({ + type: z.enum(['number', 'integer']), + title: z.string().optional(), + description: z.string().optional(), + minimum: z.number().optional(), + maximum: z.number().optional(), + default: z.number().optional() +}); +/** + * Schema for single-selection enumeration without display titles for options. + */ +export const UntitledSingleSelectEnumSchemaSchema = z.object({ + type: z.literal('string'), + title: z.string().optional(), + description: z.string().optional(), + enum: z.array(z.string()), + default: z.string().optional() +}); +/** + * Schema for single-selection enumeration with display titles for each option. + */ +export const TitledSingleSelectEnumSchemaSchema = z.object({ + type: z.literal('string'), + title: z.string().optional(), + description: z.string().optional(), + oneOf: z.array(z.object({ + const: z.string(), + title: z.string() + })), + default: z.string().optional() +}); +/** + * Use TitledSingleSelectEnumSchema instead. + * This interface will be removed in a future version. + */ +export const LegacyTitledEnumSchemaSchema = z.object({ + type: z.literal('string'), + title: z.string().optional(), + description: z.string().optional(), + enum: z.array(z.string()), + enumNames: z.array(z.string()).optional(), + default: z.string().optional() +}); +// Combined single selection enumeration +export const SingleSelectEnumSchemaSchema = z.union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); +/** + * Schema for multiple-selection enumeration without display titles for options. + */ +export const UntitledMultiSelectEnumSchemaSchema = z.object({ + type: z.literal('array'), + title: z.string().optional(), + description: z.string().optional(), + minItems: z.number().optional(), + maxItems: z.number().optional(), + items: z.object({ + type: z.literal('string'), + enum: z.array(z.string()) + }), + default: z.array(z.string()).optional() +}); +/** + * Schema for multiple-selection enumeration with display titles for each option. + */ +export const TitledMultiSelectEnumSchemaSchema = z.object({ + type: z.literal('array'), + title: z.string().optional(), + description: z.string().optional(), + minItems: z.number().optional(), + maxItems: z.number().optional(), + items: z.object({ + anyOf: z.array(z.object({ + const: z.string(), + title: z.string() + })) + }), + default: z.array(z.string()).optional() +}); +/** + * Combined schema for multiple-selection enumeration + */ +export const MultiSelectEnumSchemaSchema = z.union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); +/** + * Primitive schema definition for enum fields. + */ +export const EnumSchemaSchema = z.union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]); +/** + * Union of all primitive schema definitions. + */ +export const PrimitiveSchemaDefinitionSchema = z.union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]); +/** + * Parameters for an `elicitation/create` request for form-based elicitation. + */ +export const ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + /** + * The elicitation mode. + * + * Optional for backward compatibility. Clients MUST treat missing mode as "form". + */ + mode: z.literal('form').optional(), + /** + * The message to present to the user describing what information is being requested. + */ + message: z.string(), + /** + * A restricted subset of JSON Schema. + * Only top-level properties are allowed, without nesting. + */ + requestedSchema: z.object({ + type: z.literal('object'), + properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema), + required: z.array(z.string()).optional() + }) +}); +/** + * Parameters for an `elicitation/create` request for URL-based elicitation. + */ +export const ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + /** + * The elicitation mode. + */ + mode: z.literal('url'), + /** + * The message to present to the user explaining why the interaction is needed. + */ + message: z.string(), + /** + * The ID of the elicitation, which must be unique within the context of the server. + * The client MUST treat this ID as an opaque value. + */ + elicitationId: z.string(), + /** + * The URL that the user should navigate to. + */ + url: z.string().url() +}); +/** + * The parameters for a request to elicit additional information from the user via the client. + */ +export const ElicitRequestParamsSchema = z.union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); +/** + * A request from the server to elicit user input via the client. + * The client should present the message and form fields to the user (form mode) + * or navigate to a URL (URL mode). + */ +export const ElicitRequestSchema = RequestSchema.extend({ + method: z.literal('elicitation/create'), + params: ElicitRequestParamsSchema +}); +/** + * Parameters for a `notifications/elicitation/complete` notification. + * + * @category notifications/elicitation/complete + */ +export const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The ID of the elicitation that completed. + */ + elicitationId: z.string() +}); +/** + * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. + * + * @category notifications/elicitation/complete + */ +export const ElicitationCompleteNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/elicitation/complete'), + params: ElicitationCompleteNotificationParamsSchema +}); +/** + * The client's response to an elicitation/create request from the server. + */ +export const ElicitResultSchema = ResultSchema.extend({ + /** + * The user action in response to the elicitation. + * - "accept": User submitted the form/confirmed the action + * - "decline": User explicitly decline the action + * - "cancel": User dismissed without making an explicit choice + */ + action: z.enum(['accept', 'decline', 'cancel']), + /** + * The submitted form data, only present when action is "accept". + * Contains values matching the requested schema. + * Per MCP spec, content is "typically omitted" for decline/cancel actions. + * We normalize null to undefined for leniency while maintaining type compatibility. + */ + content: z.preprocess(val => (val === null ? undefined : val), z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])).optional()) +}); +/* Autocomplete */ +/** + * A reference to a resource or resource template definition. + */ +export const ResourceTemplateReferenceSchema = z.object({ + type: z.literal('ref/resource'), + /** + * The URI or URI template of the resource. + */ + uri: z.string() +}); +/** + * @deprecated Use ResourceTemplateReferenceSchema instead + */ +export const ResourceReferenceSchema = ResourceTemplateReferenceSchema; +/** + * Identifies a prompt. + */ +export const PromptReferenceSchema = z.object({ + type: z.literal('ref/prompt'), + /** + * The name of the prompt or prompt template + */ + name: z.string() +}); +/** + * Parameters for a `completion/complete` request. + */ +export const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ + ref: z.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), + /** + * The argument's information + */ + argument: z.object({ + /** + * The name of the argument + */ + name: z.string(), + /** + * The value of the argument to use for completion matching. + */ + value: z.string() + }), + context: z + .object({ + /** + * Previously-resolved variables in a URI template or prompt. + */ + arguments: z.record(z.string(), z.string()).optional() + }) + .optional() +}); +/** + * A request from the client to the server, to ask for completion options. + */ +export const CompleteRequestSchema = RequestSchema.extend({ + method: z.literal('completion/complete'), + params: CompleteRequestParamsSchema +}); +export function assertCompleteRequestPrompt(request) { + if (request.params.ref.type !== 'ref/prompt') { + throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`); + } + void request; +} +export function assertCompleteRequestResourceTemplate(request) { + if (request.params.ref.type !== 'ref/resource') { + throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`); + } + void request; +} +/** + * The server's response to a completion/complete request + */ +export const CompleteResultSchema = ResultSchema.extend({ + completion: z.looseObject({ + /** + * An array of completion values. Must not exceed 100 items. + */ + values: z.array(z.string()).max(100), + /** + * The total number of completion options available. This can exceed the number of values actually sent in the response. + */ + total: z.optional(z.number().int()), + /** + * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. + */ + hasMore: z.optional(z.boolean()) + }) +}); +/* Roots */ +/** + * Represents a root directory or file that the server can operate on. + */ +export const RootSchema = z.object({ + /** + * The URI identifying the root. This *must* start with file:// for now. + */ + uri: z.string().startsWith('file://'), + /** + * An optional name for the root. + */ + name: z.string().optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * Sent from the server to request a list of root URIs from the client. + */ +export const ListRootsRequestSchema = RequestSchema.extend({ + method: z.literal('roots/list'), + params: BaseRequestParamsSchema.optional() +}); +/** + * The client's response to a roots/list request from the server. + */ +export const ListRootsResultSchema = ResultSchema.extend({ + roots: z.array(RootSchema) +}); +/** + * A notification from the client to the server, informing it that the list of roots has changed. + */ +export const RootsListChangedNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/roots/list_changed'), + params: NotificationsParamsSchema.optional() +}); +/* Client messages */ +export const ClientRequestSchema = z.union([ + PingRequestSchema, + InitializeRequestSchema, + CompleteRequestSchema, + SetLevelRequestSchema, + GetPromptRequestSchema, + ListPromptsRequestSchema, + ListResourcesRequestSchema, + ListResourceTemplatesRequestSchema, + ReadResourceRequestSchema, + SubscribeRequestSchema, + UnsubscribeRequestSchema, + CallToolRequestSchema, + ListToolsRequestSchema, + GetTaskRequestSchema, + GetTaskPayloadRequestSchema, + ListTasksRequestSchema, + CancelTaskRequestSchema +]); +export const ClientNotificationSchema = z.union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + InitializedNotificationSchema, + RootsListChangedNotificationSchema, + TaskStatusNotificationSchema +]); +export const ClientResultSchema = z.union([ + EmptyResultSchema, + CreateMessageResultSchema, + CreateMessageResultWithToolsSchema, + ElicitResultSchema, + ListRootsResultSchema, + GetTaskResultSchema, + ListTasksResultSchema, + CreateTaskResultSchema +]); +/* Server messages */ +export const ServerRequestSchema = z.union([ + PingRequestSchema, + CreateMessageRequestSchema, + ElicitRequestSchema, + ListRootsRequestSchema, + GetTaskRequestSchema, + GetTaskPayloadRequestSchema, + ListTasksRequestSchema, + CancelTaskRequestSchema +]); +export const ServerNotificationSchema = z.union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + LoggingMessageNotificationSchema, + ResourceUpdatedNotificationSchema, + ResourceListChangedNotificationSchema, + ToolListChangedNotificationSchema, + PromptListChangedNotificationSchema, + TaskStatusNotificationSchema, + ElicitationCompleteNotificationSchema +]); +export const ServerResultSchema = z.union([ + EmptyResultSchema, + InitializeResultSchema, + CompleteResultSchema, + GetPromptResultSchema, + ListPromptsResultSchema, + ListResourcesResultSchema, + ListResourceTemplatesResultSchema, + ReadResourceResultSchema, + CallToolResultSchema, + ListToolsResultSchema, + GetTaskResultSchema, + ListTasksResultSchema, + CreateTaskResultSchema +]); +export class McpError extends Error { + constructor(code, message, data) { + super(`MCP error ${code}: ${message}`); + this.code = code; + this.data = data; + this.name = 'McpError'; + } + /** + * Factory method to create the appropriate error type based on the error code and data + */ + static fromError(code, message, data) { + // Check for specific error types + if (code === ErrorCode.UrlElicitationRequired && data) { + const errorData = data; + if (errorData.elicitations) { + return new UrlElicitationRequiredError(errorData.elicitations, message); + } + } + // Default to generic McpError + return new McpError(code, message, data); + } +} +/** + * Specialized error type when a tool requires a URL mode elicitation. + * This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against. + */ +export class UrlElicitationRequiredError extends McpError { + constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? 's' : ''} required`) { + super(ErrorCode.UrlElicitationRequired, message, { + elicitations: elicitations + }); + } + get elicitations() { + return this.data?.elicitations ?? []; + } +} +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js new file mode 100644 index 00000000..a0ab0674 --- /dev/null +++ b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js @@ -0,0 +1,87 @@ +/** + * AJV-based JSON Schema validator provider + */ +import Ajv from 'ajv'; +import _addFormats from 'ajv-formats'; +function createDefaultAjvInstance() { + const ajv = new Ajv({ + strict: false, + validateFormats: true, + validateSchema: false, + allErrors: true + }); + const addFormats = _addFormats; + addFormats(ajv); + return ajv; +} +/** + * @example + * ```typescript + * // Use with default AJV instance (recommended) + * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; + * const validator = new AjvJsonSchemaValidator(); + * + * // Use with custom AJV instance + * import { Ajv } from 'ajv'; + * const ajv = new Ajv({ strict: true, allErrors: true }); + * const validator = new AjvJsonSchemaValidator(ajv); + * ``` + */ +export class AjvJsonSchemaValidator { + /** + * Create an AJV validator + * + * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created. + * + * @example + * ```typescript + * // Use default configuration (recommended for most cases) + * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; + * const validator = new AjvJsonSchemaValidator(); + * + * // Or provide custom AJV instance for advanced configuration + * import { Ajv } from 'ajv'; + * import addFormats from 'ajv-formats'; + * + * const ajv = new Ajv({ validateFormats: true }); + * addFormats(ajv); + * const validator = new AjvJsonSchemaValidator(ajv); + * ``` + */ + constructor(ajv) { + this._ajv = ajv ?? createDefaultAjvInstance(); + } + /** + * Create a validator for the given JSON Schema + * + * The validator is compiled once and can be reused multiple times. + * If the schema has an $id, it will be cached by AJV automatically. + * + * @param schema - Standard JSON Schema object + * @returns A validator function that validates input data + */ + getValidator(schema) { + // Check if schema has $id and is already compiled/cached + const ajvValidator = '$id' in schema && typeof schema.$id === 'string' + ? (this._ajv.getSchema(schema.$id) ?? this._ajv.compile(schema)) + : this._ajv.compile(schema); + return (input) => { + const valid = ajvValidator(input); + if (valid) { + return { + valid: true, + data: input, + errorMessage: undefined + }; + } + else { + return { + valid: false, + data: undefined, + errorMessage: this._ajv.errorsText(ajvValidator.errors) + }; + } + }; + } +} +//# sourceMappingURL=ajv-provider.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/NoopLogger.js b/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/NoopLogger.js new file mode 100644 index 00000000..7e1b2188 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/NoopLogger.js @@ -0,0 +1,24 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NOOP_LOGGER = exports.NoopLogger = void 0; +class NoopLogger { + emit(_logRecord) { } +} +exports.NoopLogger = NoopLogger; +exports.NOOP_LOGGER = new NoopLogger(); +//# sourceMappingURL=NoopLogger.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/NoopLoggerProvider.js b/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/NoopLoggerProvider.js new file mode 100644 index 00000000..1601f1a1 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/NoopLoggerProvider.js @@ -0,0 +1,27 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NOOP_LOGGER_PROVIDER = exports.NoopLoggerProvider = void 0; +const NoopLogger_1 = require("./NoopLogger"); +class NoopLoggerProvider { + getLogger(_name, _version, _options) { + return new NoopLogger_1.NoopLogger(); + } +} +exports.NoopLoggerProvider = NoopLoggerProvider; +exports.NOOP_LOGGER_PROVIDER = new NoopLoggerProvider(); +//# sourceMappingURL=NoopLoggerProvider.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/ProxyLogger.js b/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/ProxyLogger.js new file mode 100644 index 00000000..a37a9e6f --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/ProxyLogger.js @@ -0,0 +1,52 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ProxyLogger = void 0; +const NoopLogger_1 = require("./NoopLogger"); +class ProxyLogger { + constructor(_provider, name, version, options) { + this._provider = _provider; + this.name = name; + this.version = version; + this.options = options; + } + /** + * Emit a log record. This method should only be used by log appenders. + * + * @param logRecord + */ + emit(logRecord) { + this._getLogger().emit(logRecord); + } + /** + * Try to get a logger from the proxy logger provider. + * If the proxy logger provider has no delegate, return a noop logger. + */ + _getLogger() { + if (this._delegate) { + return this._delegate; + } + const logger = this._provider._getDelegateLogger(this.name, this.version, this.options); + if (!logger) { + return NoopLogger_1.NOOP_LOGGER; + } + this._delegate = logger; + return this._delegate; + } +} +exports.ProxyLogger = ProxyLogger; +//# sourceMappingURL=ProxyLogger.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/ProxyLoggerProvider.js b/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/ProxyLoggerProvider.js new file mode 100644 index 00000000..dd0b2909 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/ProxyLoggerProvider.js @@ -0,0 +1,51 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ProxyLoggerProvider = void 0; +const NoopLoggerProvider_1 = require("./NoopLoggerProvider"); +const ProxyLogger_1 = require("./ProxyLogger"); +class ProxyLoggerProvider { + getLogger(name, version, options) { + var _a; + return ((_a = this._getDelegateLogger(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyLogger_1.ProxyLogger(this, name, version, options)); + } + /** + * Get the delegate logger provider. + * Used by tests only. + * @internal + */ + _getDelegate() { + var _a; + return (_a = this._delegate) !== null && _a !== void 0 ? _a : NoopLoggerProvider_1.NOOP_LOGGER_PROVIDER; + } + /** + * Set the delegate logger provider + * @internal + */ + _setDelegate(delegate) { + this._delegate = delegate; + } + /** + * @internal + */ + _getDelegateLogger(name, version, options) { + var _a; + return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getLogger(name, version, options); + } +} +exports.ProxyLoggerProvider = ProxyLoggerProvider; +//# sourceMappingURL=ProxyLoggerProvider.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/api/logs.js b/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/api/logs.js new file mode 100644 index 00000000..8fd7e224 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/api/logs.js @@ -0,0 +1,64 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LogsAPI = void 0; +const global_utils_1 = require("../internal/global-utils"); +const NoopLoggerProvider_1 = require("../NoopLoggerProvider"); +const ProxyLoggerProvider_1 = require("../ProxyLoggerProvider"); +class LogsAPI { + constructor() { + this._proxyLoggerProvider = new ProxyLoggerProvider_1.ProxyLoggerProvider(); + } + static getInstance() { + if (!this._instance) { + this._instance = new LogsAPI(); + } + return this._instance; + } + setGlobalLoggerProvider(provider) { + if (global_utils_1._global[global_utils_1.GLOBAL_LOGS_API_KEY]) { + return this.getLoggerProvider(); + } + global_utils_1._global[global_utils_1.GLOBAL_LOGS_API_KEY] = (0, global_utils_1.makeGetter)(global_utils_1.API_BACKWARDS_COMPATIBILITY_VERSION, provider, NoopLoggerProvider_1.NOOP_LOGGER_PROVIDER); + this._proxyLoggerProvider._setDelegate(provider); + return provider; + } + /** + * Returns the global logger provider. + * + * @returns LoggerProvider + */ + getLoggerProvider() { + var _a, _b; + return ((_b = (_a = global_utils_1._global[global_utils_1.GLOBAL_LOGS_API_KEY]) === null || _a === void 0 ? void 0 : _a.call(global_utils_1._global, global_utils_1.API_BACKWARDS_COMPATIBILITY_VERSION)) !== null && _b !== void 0 ? _b : this._proxyLoggerProvider); + } + /** + * Returns a logger from the global logger provider. + * + * @returns Logger + */ + getLogger(name, version, options) { + return this.getLoggerProvider().getLogger(name, version, options); + } + /** Remove the global logger provider */ + disable() { + delete global_utils_1._global[global_utils_1.GLOBAL_LOGS_API_KEY]; + this._proxyLoggerProvider = new ProxyLoggerProvider_1.ProxyLoggerProvider(); + } +} +exports.LogsAPI = LogsAPI; +//# sourceMappingURL=logs.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/index.js new file mode 100644 index 00000000..9c147a97 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/index.js @@ -0,0 +1,28 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.logs = exports.ProxyLoggerProvider = exports.NoopLogger = exports.NOOP_LOGGER = exports.SeverityNumber = void 0; +var LogRecord_1 = require("./types/LogRecord"); +Object.defineProperty(exports, "SeverityNumber", { enumerable: true, get: function () { return LogRecord_1.SeverityNumber; } }); +var NoopLogger_1 = require("./NoopLogger"); +Object.defineProperty(exports, "NOOP_LOGGER", { enumerable: true, get: function () { return NoopLogger_1.NOOP_LOGGER; } }); +Object.defineProperty(exports, "NoopLogger", { enumerable: true, get: function () { return NoopLogger_1.NoopLogger; } }); +var ProxyLoggerProvider_1 = require("./ProxyLoggerProvider"); +Object.defineProperty(exports, "ProxyLoggerProvider", { enumerable: true, get: function () { return ProxyLoggerProvider_1.ProxyLoggerProvider; } }); +const logs_1 = require("./api/logs"); +exports.logs = logs_1.LogsAPI.getInstance(); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/internal/global-utils.js b/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/internal/global-utils.js new file mode 100644 index 00000000..b1b2fbe7 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/internal/global-utils.js @@ -0,0 +1,42 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.API_BACKWARDS_COMPATIBILITY_VERSION = exports.makeGetter = exports._global = exports.GLOBAL_LOGS_API_KEY = void 0; +const platform_1 = require("../platform"); +exports.GLOBAL_LOGS_API_KEY = Symbol.for('io.opentelemetry.js.api.logs'); +exports._global = platform_1._globalThis; +/** + * Make a function which accepts a version integer and returns the instance of an API if the version + * is compatible, or a fallback version (usually NOOP) if it is not. + * + * @param requiredVersion Backwards compatibility version which is required to return the instance + * @param instance Instance which should be returned if the required version is compatible + * @param fallback Fallback instance, usually NOOP, which will be returned if the required version is not compatible + */ +function makeGetter(requiredVersion, instance, fallback) { + return (version) => version === requiredVersion ? instance : fallback; +} +exports.makeGetter = makeGetter; +/** + * A number which should be incremented each time a backwards incompatible + * change is made to the API. This number is used when an API package + * attempts to access the global API to ensure it is getting a compatible + * version. If the global API is not compatible with the API package + * attempting to get it, a NOOP API implementation will be returned. + */ +exports.API_BACKWARDS_COMPATIBILITY_VERSION = 1; +//# sourceMappingURL=global-utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/platform/index.js b/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/platform/index.js new file mode 100644 index 00000000..a7cc3283 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/platform/index.js @@ -0,0 +1,21 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports._globalThis = void 0; +var node_1 = require("./node"); +Object.defineProperty(exports, "_globalThis", { enumerable: true, get: function () { return node_1._globalThis; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/platform/node/globalThis.js b/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/platform/node/globalThis.js new file mode 100644 index 00000000..9ae59140 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/platform/node/globalThis.js @@ -0,0 +1,22 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports._globalThis = void 0; +/** only globals that common to node and browsers are allowed */ +// eslint-disable-next-line n/no-unsupported-features/es-builtins +exports._globalThis = typeof globalThis === 'object' ? globalThis : global; +//# sourceMappingURL=globalThis.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/platform/node/index.js b/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/platform/node/index.js new file mode 100644 index 00000000..ffe6d10d --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/platform/node/index.js @@ -0,0 +1,21 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports._globalThis = void 0; +var globalThis_1 = require("./globalThis"); +Object.defineProperty(exports, "_globalThis", { enumerable: true, get: function () { return globalThis_1._globalThis; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/types/LogRecord.js b/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/types/LogRecord.js new file mode 100644 index 00000000..3e9e301a --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/types/LogRecord.js @@ -0,0 +1,47 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SeverityNumber = void 0; +var SeverityNumber; +(function (SeverityNumber) { + SeverityNumber[SeverityNumber["UNSPECIFIED"] = 0] = "UNSPECIFIED"; + SeverityNumber[SeverityNumber["TRACE"] = 1] = "TRACE"; + SeverityNumber[SeverityNumber["TRACE2"] = 2] = "TRACE2"; + SeverityNumber[SeverityNumber["TRACE3"] = 3] = "TRACE3"; + SeverityNumber[SeverityNumber["TRACE4"] = 4] = "TRACE4"; + SeverityNumber[SeverityNumber["DEBUG"] = 5] = "DEBUG"; + SeverityNumber[SeverityNumber["DEBUG2"] = 6] = "DEBUG2"; + SeverityNumber[SeverityNumber["DEBUG3"] = 7] = "DEBUG3"; + SeverityNumber[SeverityNumber["DEBUG4"] = 8] = "DEBUG4"; + SeverityNumber[SeverityNumber["INFO"] = 9] = "INFO"; + SeverityNumber[SeverityNumber["INFO2"] = 10] = "INFO2"; + SeverityNumber[SeverityNumber["INFO3"] = 11] = "INFO3"; + SeverityNumber[SeverityNumber["INFO4"] = 12] = "INFO4"; + SeverityNumber[SeverityNumber["WARN"] = 13] = "WARN"; + SeverityNumber[SeverityNumber["WARN2"] = 14] = "WARN2"; + SeverityNumber[SeverityNumber["WARN3"] = 15] = "WARN3"; + SeverityNumber[SeverityNumber["WARN4"] = 16] = "WARN4"; + SeverityNumber[SeverityNumber["ERROR"] = 17] = "ERROR"; + SeverityNumber[SeverityNumber["ERROR2"] = 18] = "ERROR2"; + SeverityNumber[SeverityNumber["ERROR3"] = 19] = "ERROR3"; + SeverityNumber[SeverityNumber["ERROR4"] = 20] = "ERROR4"; + SeverityNumber[SeverityNumber["FATAL"] = 21] = "FATAL"; + SeverityNumber[SeverityNumber["FATAL2"] = 22] = "FATAL2"; + SeverityNumber[SeverityNumber["FATAL3"] = 23] = "FATAL3"; + SeverityNumber[SeverityNumber["FATAL4"] = 24] = "FATAL4"; +})(SeverityNumber = exports.SeverityNumber || (exports.SeverityNumber = {})); +//# sourceMappingURL=LogRecord.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/api/context.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/api/context.js new file mode 100644 index 00000000..8af551f8 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/api/context.js @@ -0,0 +1,81 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ContextAPI = void 0; +const NoopContextManager_1 = require("../context/NoopContextManager"); +const global_utils_1 = require("../internal/global-utils"); +const diag_1 = require("./diag"); +const API_NAME = 'context'; +const NOOP_CONTEXT_MANAGER = new NoopContextManager_1.NoopContextManager(); +/** + * Singleton object which represents the entry point to the OpenTelemetry Context API + */ +class ContextAPI { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { } + /** Get the singleton instance of the Context API */ + static getInstance() { + if (!this._instance) { + this._instance = new ContextAPI(); + } + return this._instance; + } + /** + * Set the current context manager. + * + * @returns true if the context manager was successfully registered, else false + */ + setGlobalContextManager(contextManager) { + return (0, global_utils_1.registerGlobal)(API_NAME, contextManager, diag_1.DiagAPI.instance()); + } + /** + * Get the currently active context + */ + active() { + return this._getContextManager().active(); + } + /** + * Execute a function with an active context + * + * @param context context to be active during function execution + * @param fn function to execute in a context + * @param thisArg optional receiver to be used for calling fn + * @param args optional arguments forwarded to fn + */ + with(context, fn, thisArg, ...args) { + return this._getContextManager().with(context, fn, thisArg, ...args); + } + /** + * Bind a context to a target function or event emitter + * + * @param context context to bind to the event emitter or function. Defaults to the currently active context + * @param target function or event emitter to bind + */ + bind(context, target) { + return this._getContextManager().bind(context, target); + } + _getContextManager() { + return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_CONTEXT_MANAGER; + } + /** Disable and remove the global context manager */ + disable() { + this._getContextManager().disable(); + (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); + } +} +exports.ContextAPI = ContextAPI; +//# sourceMappingURL=context.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/api/diag.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/api/diag.js new file mode 100644 index 00000000..94569232 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/api/diag.js @@ -0,0 +1,93 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DiagAPI = void 0; +const ComponentLogger_1 = require("../diag/ComponentLogger"); +const logLevelLogger_1 = require("../diag/internal/logLevelLogger"); +const types_1 = require("../diag/types"); +const global_utils_1 = require("../internal/global-utils"); +const API_NAME = 'diag'; +/** + * Singleton object which represents the entry point to the OpenTelemetry internal + * diagnostic API + */ +class DiagAPI { + /** + * Private internal constructor + * @private + */ + constructor() { + function _logProxy(funcName) { + return function (...args) { + const logger = (0, global_utils_1.getGlobal)('diag'); + // shortcut if logger not set + if (!logger) + return; + return logger[funcName](...args); + }; + } + // Using self local variable for minification purposes as 'this' cannot be minified + const self = this; + // DiagAPI specific functions + const setLogger = (logger, optionsOrLogLevel = { logLevel: types_1.DiagLogLevel.INFO }) => { + var _a, _b, _c; + if (logger === self) { + // There isn't much we can do here. + // Logging to the console might break the user application. + // Try to log to self. If a logger was previously registered it will receive the log. + const err = new Error('Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'); + self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message); + return false; + } + if (typeof optionsOrLogLevel === 'number') { + optionsOrLogLevel = { + logLevel: optionsOrLogLevel, + }; + } + const oldLogger = (0, global_utils_1.getGlobal)('diag'); + const newLogger = (0, logLevelLogger_1.createLogLevelDiagLogger)((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : types_1.DiagLogLevel.INFO, logger); + // There already is an logger registered. We'll let it know before overwriting it. + if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { + const stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : ''; + oldLogger.warn(`Current logger will be overwritten from ${stack}`); + newLogger.warn(`Current logger will overwrite one already registered from ${stack}`); + } + return (0, global_utils_1.registerGlobal)('diag', newLogger, self, true); + }; + self.setLogger = setLogger; + self.disable = () => { + (0, global_utils_1.unregisterGlobal)(API_NAME, self); + }; + self.createComponentLogger = (options) => { + return new ComponentLogger_1.DiagComponentLogger(options); + }; + self.verbose = _logProxy('verbose'); + self.debug = _logProxy('debug'); + self.info = _logProxy('info'); + self.warn = _logProxy('warn'); + self.error = _logProxy('error'); + } + /** Get the singleton instance of the DiagAPI API */ + static instance() { + if (!this._instance) { + this._instance = new DiagAPI(); + } + return this._instance; + } +} +exports.DiagAPI = DiagAPI; +//# sourceMappingURL=diag.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/api/metrics.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/api/metrics.js new file mode 100644 index 00000000..4bbc4331 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/api/metrics.js @@ -0,0 +1,61 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MetricsAPI = void 0; +const NoopMeterProvider_1 = require("../metrics/NoopMeterProvider"); +const global_utils_1 = require("../internal/global-utils"); +const diag_1 = require("./diag"); +const API_NAME = 'metrics'; +/** + * Singleton object which represents the entry point to the OpenTelemetry Metrics API + */ +class MetricsAPI { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { } + /** Get the singleton instance of the Metrics API */ + static getInstance() { + if (!this._instance) { + this._instance = new MetricsAPI(); + } + return this._instance; + } + /** + * Set the current global meter provider. + * Returns true if the meter provider was successfully registered, else false. + */ + setGlobalMeterProvider(provider) { + return (0, global_utils_1.registerGlobal)(API_NAME, provider, diag_1.DiagAPI.instance()); + } + /** + * Returns the global meter provider. + */ + getMeterProvider() { + return (0, global_utils_1.getGlobal)(API_NAME) || NoopMeterProvider_1.NOOP_METER_PROVIDER; + } + /** + * Returns a meter from the global meter provider. + */ + getMeter(name, version, options) { + return this.getMeterProvider().getMeter(name, version, options); + } + /** Remove the global meter provider */ + disable() { + (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); + } +} +exports.MetricsAPI = MetricsAPI; +//# sourceMappingURL=metrics.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/api/propagation.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/api/propagation.js new file mode 100644 index 00000000..7f03df81 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/api/propagation.js @@ -0,0 +1,89 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PropagationAPI = void 0; +const global_utils_1 = require("../internal/global-utils"); +const NoopTextMapPropagator_1 = require("../propagation/NoopTextMapPropagator"); +const TextMapPropagator_1 = require("../propagation/TextMapPropagator"); +const context_helpers_1 = require("../baggage/context-helpers"); +const utils_1 = require("../baggage/utils"); +const diag_1 = require("./diag"); +const API_NAME = 'propagation'; +const NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator_1.NoopTextMapPropagator(); +/** + * Singleton object which represents the entry point to the OpenTelemetry Propagation API + */ +class PropagationAPI { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { + this.createBaggage = utils_1.createBaggage; + this.getBaggage = context_helpers_1.getBaggage; + this.getActiveBaggage = context_helpers_1.getActiveBaggage; + this.setBaggage = context_helpers_1.setBaggage; + this.deleteBaggage = context_helpers_1.deleteBaggage; + } + /** Get the singleton instance of the Propagator API */ + static getInstance() { + if (!this._instance) { + this._instance = new PropagationAPI(); + } + return this._instance; + } + /** + * Set the current propagator. + * + * @returns true if the propagator was successfully registered, else false + */ + setGlobalPropagator(propagator) { + return (0, global_utils_1.registerGlobal)(API_NAME, propagator, diag_1.DiagAPI.instance()); + } + /** + * Inject context into a carrier to be propagated inter-process + * + * @param context Context carrying tracing data to inject + * @param carrier carrier to inject context into + * @param setter Function used to set values on the carrier + */ + inject(context, carrier, setter = TextMapPropagator_1.defaultTextMapSetter) { + return this._getGlobalPropagator().inject(context, carrier, setter); + } + /** + * Extract context from a carrier + * + * @param context Context which the newly created context will inherit from + * @param carrier Carrier to extract context from + * @param getter Function used to extract keys from a carrier + */ + extract(context, carrier, getter = TextMapPropagator_1.defaultTextMapGetter) { + return this._getGlobalPropagator().extract(context, carrier, getter); + } + /** + * Return a list of all fields which may be used by the propagator. + */ + fields() { + return this._getGlobalPropagator().fields(); + } + /** Remove the global propagator */ + disable() { + (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); + } + _getGlobalPropagator() { + return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR; + } +} +exports.PropagationAPI = PropagationAPI; +//# sourceMappingURL=propagation.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/api/trace.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/api/trace.js new file mode 100644 index 00000000..aa7a9da5 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/api/trace.js @@ -0,0 +1,79 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TraceAPI = void 0; +const global_utils_1 = require("../internal/global-utils"); +const ProxyTracerProvider_1 = require("../trace/ProxyTracerProvider"); +const spancontext_utils_1 = require("../trace/spancontext-utils"); +const context_utils_1 = require("../trace/context-utils"); +const diag_1 = require("./diag"); +const API_NAME = 'trace'; +/** + * Singleton object which represents the entry point to the OpenTelemetry Tracing API + */ +class TraceAPI { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { + this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider(); + this.wrapSpanContext = spancontext_utils_1.wrapSpanContext; + this.isSpanContextValid = spancontext_utils_1.isSpanContextValid; + this.deleteSpan = context_utils_1.deleteSpan; + this.getSpan = context_utils_1.getSpan; + this.getActiveSpan = context_utils_1.getActiveSpan; + this.getSpanContext = context_utils_1.getSpanContext; + this.setSpan = context_utils_1.setSpan; + this.setSpanContext = context_utils_1.setSpanContext; + } + /** Get the singleton instance of the Trace API */ + static getInstance() { + if (!this._instance) { + this._instance = new TraceAPI(); + } + return this._instance; + } + /** + * Set the current global tracer. + * + * @returns true if the tracer provider was successfully registered, else false + */ + setGlobalTracerProvider(provider) { + const success = (0, global_utils_1.registerGlobal)(API_NAME, this._proxyTracerProvider, diag_1.DiagAPI.instance()); + if (success) { + this._proxyTracerProvider.setDelegate(provider); + } + return success; + } + /** + * Returns the global tracer provider. + */ + getTracerProvider() { + return (0, global_utils_1.getGlobal)(API_NAME) || this._proxyTracerProvider; + } + /** + * Returns a tracer from the global tracer provider. + */ + getTracer(name, version) { + return this.getTracerProvider().getTracer(name, version); + } + /** Remove the global tracer provider */ + disable() { + (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); + this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider(); + } +} +exports.TraceAPI = TraceAPI; +//# sourceMappingURL=trace.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/baggage/context-helpers.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/baggage/context-helpers.js new file mode 100644 index 00000000..cc0f00bf --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/baggage/context-helpers.js @@ -0,0 +1,63 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.deleteBaggage = exports.setBaggage = exports.getActiveBaggage = exports.getBaggage = void 0; +const context_1 = require("../api/context"); +const context_2 = require("../context/context"); +/** + * Baggage key + */ +const BAGGAGE_KEY = (0, context_2.createContextKey)('OpenTelemetry Baggage Key'); +/** + * Retrieve the current baggage from the given context + * + * @param {Context} Context that manage all context values + * @returns {Baggage} Extracted baggage from the context + */ +function getBaggage(context) { + return context.getValue(BAGGAGE_KEY) || undefined; +} +exports.getBaggage = getBaggage; +/** + * Retrieve the current baggage from the active/current context + * + * @returns {Baggage} Extracted baggage from the context + */ +function getActiveBaggage() { + return getBaggage(context_1.ContextAPI.getInstance().active()); +} +exports.getActiveBaggage = getActiveBaggage; +/** + * Store a baggage in the given context + * + * @param {Context} Context that manage all context values + * @param {Baggage} baggage that will be set in the actual context + */ +function setBaggage(context, baggage) { + return context.setValue(BAGGAGE_KEY, baggage); +} +exports.setBaggage = setBaggage; +/** + * Delete the baggage stored in the given context + * + * @param {Context} Context that manage all context values + */ +function deleteBaggage(context) { + return context.deleteValue(BAGGAGE_KEY); +} +exports.deleteBaggage = deleteBaggage; +//# sourceMappingURL=context-helpers.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/baggage/internal/baggage-impl.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/baggage/internal/baggage-impl.js new file mode 100644 index 00000000..6f04d4a6 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/baggage/internal/baggage-impl.js @@ -0,0 +1,55 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BaggageImpl = void 0; +class BaggageImpl { + constructor(entries) { + this._entries = entries ? new Map(entries) : new Map(); + } + getEntry(key) { + const entry = this._entries.get(key); + if (!entry) { + return undefined; + } + return Object.assign({}, entry); + } + getAllEntries() { + return Array.from(this._entries.entries()).map(([k, v]) => [k, v]); + } + setEntry(key, entry) { + const newBaggage = new BaggageImpl(this._entries); + newBaggage._entries.set(key, entry); + return newBaggage; + } + removeEntry(key) { + const newBaggage = new BaggageImpl(this._entries); + newBaggage._entries.delete(key); + return newBaggage; + } + removeEntries(...keys) { + const newBaggage = new BaggageImpl(this._entries); + for (const key of keys) { + newBaggage._entries.delete(key); + } + return newBaggage; + } + clear() { + return new BaggageImpl(); + } +} +exports.BaggageImpl = BaggageImpl; +//# sourceMappingURL=baggage-impl.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/baggage/internal/symbol.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/baggage/internal/symbol.js new file mode 100644 index 00000000..324c216d --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/baggage/internal/symbol.js @@ -0,0 +1,23 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.baggageEntryMetadataSymbol = void 0; +/** + * Symbol used to make BaggageEntryMetadata an opaque type + */ +exports.baggageEntryMetadataSymbol = Symbol('BaggageEntryMetadata'); +//# sourceMappingURL=symbol.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/baggage/utils.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/baggage/utils.js new file mode 100644 index 00000000..a0bfbf6c --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/baggage/utils.js @@ -0,0 +1,51 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.baggageEntryMetadataFromString = exports.createBaggage = void 0; +const diag_1 = require("../api/diag"); +const baggage_impl_1 = require("./internal/baggage-impl"); +const symbol_1 = require("./internal/symbol"); +const diag = diag_1.DiagAPI.instance(); +/** + * Create a new Baggage with optional entries + * + * @param entries An array of baggage entries the new baggage should contain + */ +function createBaggage(entries = {}) { + return new baggage_impl_1.BaggageImpl(new Map(Object.entries(entries))); +} +exports.createBaggage = createBaggage; +/** + * Create a serializable BaggageEntryMetadata object from a string. + * + * @param str string metadata. Format is currently not defined by the spec and has no special meaning. + * + */ +function baggageEntryMetadataFromString(str) { + if (typeof str !== 'string') { + diag.error(`Cannot create baggage metadata from unknown type: ${typeof str}`); + str = ''; + } + return { + __TYPE__: symbol_1.baggageEntryMetadataSymbol, + toString() { + return str; + }, + }; +} +exports.baggageEntryMetadataFromString = baggageEntryMetadataFromString; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/context-api.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/context-api.js new file mode 100644 index 00000000..b9aeea93 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/context-api.js @@ -0,0 +1,24 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.context = void 0; +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +const context_1 = require("./api/context"); +/** Entrypoint for context API */ +exports.context = context_1.ContextAPI.getInstance(); +//# sourceMappingURL=context-api.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/context/NoopContextManager.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/context/NoopContextManager.js new file mode 100644 index 00000000..10c6ae1b --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/context/NoopContextManager.js @@ -0,0 +1,38 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NoopContextManager = void 0; +const context_1 = require("./context"); +class NoopContextManager { + active() { + return context_1.ROOT_CONTEXT; + } + with(_context, fn, thisArg, ...args) { + return fn.call(thisArg, ...args); + } + bind(_context, target) { + return target; + } + enable() { + return this; + } + disable() { + return this; + } +} +exports.NoopContextManager = NoopContextManager; +//# sourceMappingURL=NoopContextManager.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/context/context.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/context/context.js new file mode 100644 index 00000000..eecc1593 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/context/context.js @@ -0,0 +1,55 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ROOT_CONTEXT = exports.createContextKey = void 0; +/** Get a key to uniquely identify a context value */ +function createContextKey(description) { + // The specification states that for the same input, multiple calls should + // return different keys. Due to the nature of the JS dependency management + // system, this creates problems where multiple versions of some package + // could hold different keys for the same property. + // + // Therefore, we use Symbol.for which returns the same key for the same input. + return Symbol.for(description); +} +exports.createContextKey = createContextKey; +class BaseContext { + /** + * Construct a new context which inherits values from an optional parent context. + * + * @param parentContext a context from which to inherit values + */ + constructor(parentContext) { + // for minification + const self = this; + self._currentContext = parentContext ? new Map(parentContext) : new Map(); + self.getValue = (key) => self._currentContext.get(key); + self.setValue = (key, value) => { + const context = new BaseContext(self._currentContext); + context._currentContext.set(key, value); + return context; + }; + self.deleteValue = (key) => { + const context = new BaseContext(self._currentContext); + context._currentContext.delete(key); + return context; + }; + } +} +/** The root context is used as the default parent context when there is no active context */ +exports.ROOT_CONTEXT = new BaseContext(); +//# sourceMappingURL=context.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/diag-api.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/diag-api.js new file mode 100644 index 00000000..cbf28db3 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/diag-api.js @@ -0,0 +1,29 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.diag = void 0; +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +const diag_1 = require("./api/diag"); +/** + * Entrypoint for Diag API. + * Defines Diagnostic handler used for internal diagnostic logging operations. + * The default provides a Noop DiagLogger implementation which may be changed via the + * diag.setLogger(logger: DiagLogger) function. + */ +exports.diag = diag_1.DiagAPI.instance(); +//# sourceMappingURL=diag-api.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/diag/ComponentLogger.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/diag/ComponentLogger.js new file mode 100644 index 00000000..579b7e68 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/diag/ComponentLogger.js @@ -0,0 +1,59 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DiagComponentLogger = void 0; +const global_utils_1 = require("../internal/global-utils"); +/** + * Component Logger which is meant to be used as part of any component which + * will add automatically additional namespace in front of the log message. + * It will then forward all message to global diag logger + * @example + * const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' }); + * cLogger.debug('test'); + * // @opentelemetry/instrumentation-http test + */ +class DiagComponentLogger { + constructor(props) { + this._namespace = props.namespace || 'DiagComponentLogger'; + } + debug(...args) { + return logProxy('debug', this._namespace, args); + } + error(...args) { + return logProxy('error', this._namespace, args); + } + info(...args) { + return logProxy('info', this._namespace, args); + } + warn(...args) { + return logProxy('warn', this._namespace, args); + } + verbose(...args) { + return logProxy('verbose', this._namespace, args); + } +} +exports.DiagComponentLogger = DiagComponentLogger; +function logProxy(funcName, namespace, args) { + const logger = (0, global_utils_1.getGlobal)('diag'); + // shortcut if logger not set + if (!logger) { + return; + } + args.unshift(namespace); + return logger[funcName](...args); +} +//# sourceMappingURL=ComponentLogger.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/diag/consoleLogger.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/diag/consoleLogger.js new file mode 100644 index 00000000..1962275f --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/diag/consoleLogger.js @@ -0,0 +1,57 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DiagConsoleLogger = void 0; +const consoleMap = [ + { n: 'error', c: 'error' }, + { n: 'warn', c: 'warn' }, + { n: 'info', c: 'info' }, + { n: 'debug', c: 'debug' }, + { n: 'verbose', c: 'trace' }, +]; +/** + * A simple Immutable Console based diagnostic logger which will output any messages to the Console. + * If you want to limit the amount of logging to a specific level or lower use the + * {@link createLogLevelDiagLogger} + */ +class DiagConsoleLogger { + constructor() { + function _consoleFunc(funcName) { + return function (...args) { + if (console) { + // Some environments only expose the console when the F12 developer console is open + // eslint-disable-next-line no-console + let theFunc = console[funcName]; + if (typeof theFunc !== 'function') { + // Not all environments support all functions + // eslint-disable-next-line no-console + theFunc = console.log; + } + // One last final check + if (typeof theFunc === 'function') { + return theFunc.apply(console, args); + } + } + }; + } + for (let i = 0; i < consoleMap.length; i++) { + this[consoleMap[i].n] = _consoleFunc(consoleMap[i].c); + } + } +} +exports.DiagConsoleLogger = DiagConsoleLogger; +//# sourceMappingURL=consoleLogger.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/diag/internal/logLevelLogger.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/diag/internal/logLevelLogger.js new file mode 100644 index 00000000..ee1702e5 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/diag/internal/logLevelLogger.js @@ -0,0 +1,45 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createLogLevelDiagLogger = void 0; +const types_1 = require("../types"); +function createLogLevelDiagLogger(maxLevel, logger) { + if (maxLevel < types_1.DiagLogLevel.NONE) { + maxLevel = types_1.DiagLogLevel.NONE; + } + else if (maxLevel > types_1.DiagLogLevel.ALL) { + maxLevel = types_1.DiagLogLevel.ALL; + } + // In case the logger is null or undefined + logger = logger || {}; + function _filterFunc(funcName, theLevel) { + const theFunc = logger[funcName]; + if (typeof theFunc === 'function' && maxLevel >= theLevel) { + return theFunc.bind(logger); + } + return function () { }; + } + return { + error: _filterFunc('error', types_1.DiagLogLevel.ERROR), + warn: _filterFunc('warn', types_1.DiagLogLevel.WARN), + info: _filterFunc('info', types_1.DiagLogLevel.INFO), + debug: _filterFunc('debug', types_1.DiagLogLevel.DEBUG), + verbose: _filterFunc('verbose', types_1.DiagLogLevel.VERBOSE), + }; +} +exports.createLogLevelDiagLogger = createLogLevelDiagLogger; +//# sourceMappingURL=logLevelLogger.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/diag/types.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/diag/types.js new file mode 100644 index 00000000..c195e45e --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/diag/types.js @@ -0,0 +1,44 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DiagLogLevel = void 0; +/** + * Defines the available internal logging levels for the diagnostic logger, the numeric values + * of the levels are defined to match the original values from the initial LogLevel to avoid + * compatibility/migration issues for any implementation that assume the numeric ordering. + */ +var DiagLogLevel; +(function (DiagLogLevel) { + /** Diagnostic Logging level setting to disable all logging (except and forced logs) */ + DiagLogLevel[DiagLogLevel["NONE"] = 0] = "NONE"; + /** Identifies an error scenario */ + DiagLogLevel[DiagLogLevel["ERROR"] = 30] = "ERROR"; + /** Identifies a warning scenario */ + DiagLogLevel[DiagLogLevel["WARN"] = 50] = "WARN"; + /** General informational log message */ + DiagLogLevel[DiagLogLevel["INFO"] = 60] = "INFO"; + /** General debug log message */ + DiagLogLevel[DiagLogLevel["DEBUG"] = 70] = "DEBUG"; + /** + * Detailed trace level logging should only be used for development, should only be set + * in a development environment. + */ + DiagLogLevel[DiagLogLevel["VERBOSE"] = 80] = "VERBOSE"; + /** Used to set the logging level to include all logging */ + DiagLogLevel[DiagLogLevel["ALL"] = 9999] = "ALL"; +})(DiagLogLevel = exports.DiagLogLevel || (exports.DiagLogLevel = {})); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/index.js new file mode 100644 index 00000000..cb0a8723 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/index.js @@ -0,0 +1,81 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.trace = exports.propagation = exports.metrics = exports.diag = exports.context = exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = exports.isValidSpanId = exports.isValidTraceId = exports.isSpanContextValid = exports.createTraceState = exports.TraceFlags = exports.SpanStatusCode = exports.SpanKind = exports.SamplingDecision = exports.ProxyTracerProvider = exports.ProxyTracer = exports.defaultTextMapSetter = exports.defaultTextMapGetter = exports.ValueType = exports.createNoopMeter = exports.DiagLogLevel = exports.DiagConsoleLogger = exports.ROOT_CONTEXT = exports.createContextKey = exports.baggageEntryMetadataFromString = void 0; +var utils_1 = require("./baggage/utils"); +Object.defineProperty(exports, "baggageEntryMetadataFromString", { enumerable: true, get: function () { return utils_1.baggageEntryMetadataFromString; } }); +// Context APIs +var context_1 = require("./context/context"); +Object.defineProperty(exports, "createContextKey", { enumerable: true, get: function () { return context_1.createContextKey; } }); +Object.defineProperty(exports, "ROOT_CONTEXT", { enumerable: true, get: function () { return context_1.ROOT_CONTEXT; } }); +// Diag APIs +var consoleLogger_1 = require("./diag/consoleLogger"); +Object.defineProperty(exports, "DiagConsoleLogger", { enumerable: true, get: function () { return consoleLogger_1.DiagConsoleLogger; } }); +var types_1 = require("./diag/types"); +Object.defineProperty(exports, "DiagLogLevel", { enumerable: true, get: function () { return types_1.DiagLogLevel; } }); +// Metrics APIs +var NoopMeter_1 = require("./metrics/NoopMeter"); +Object.defineProperty(exports, "createNoopMeter", { enumerable: true, get: function () { return NoopMeter_1.createNoopMeter; } }); +var Metric_1 = require("./metrics/Metric"); +Object.defineProperty(exports, "ValueType", { enumerable: true, get: function () { return Metric_1.ValueType; } }); +// Propagation APIs +var TextMapPropagator_1 = require("./propagation/TextMapPropagator"); +Object.defineProperty(exports, "defaultTextMapGetter", { enumerable: true, get: function () { return TextMapPropagator_1.defaultTextMapGetter; } }); +Object.defineProperty(exports, "defaultTextMapSetter", { enumerable: true, get: function () { return TextMapPropagator_1.defaultTextMapSetter; } }); +var ProxyTracer_1 = require("./trace/ProxyTracer"); +Object.defineProperty(exports, "ProxyTracer", { enumerable: true, get: function () { return ProxyTracer_1.ProxyTracer; } }); +var ProxyTracerProvider_1 = require("./trace/ProxyTracerProvider"); +Object.defineProperty(exports, "ProxyTracerProvider", { enumerable: true, get: function () { return ProxyTracerProvider_1.ProxyTracerProvider; } }); +var SamplingResult_1 = require("./trace/SamplingResult"); +Object.defineProperty(exports, "SamplingDecision", { enumerable: true, get: function () { return SamplingResult_1.SamplingDecision; } }); +var span_kind_1 = require("./trace/span_kind"); +Object.defineProperty(exports, "SpanKind", { enumerable: true, get: function () { return span_kind_1.SpanKind; } }); +var status_1 = require("./trace/status"); +Object.defineProperty(exports, "SpanStatusCode", { enumerable: true, get: function () { return status_1.SpanStatusCode; } }); +var trace_flags_1 = require("./trace/trace_flags"); +Object.defineProperty(exports, "TraceFlags", { enumerable: true, get: function () { return trace_flags_1.TraceFlags; } }); +var utils_2 = require("./trace/internal/utils"); +Object.defineProperty(exports, "createTraceState", { enumerable: true, get: function () { return utils_2.createTraceState; } }); +var spancontext_utils_1 = require("./trace/spancontext-utils"); +Object.defineProperty(exports, "isSpanContextValid", { enumerable: true, get: function () { return spancontext_utils_1.isSpanContextValid; } }); +Object.defineProperty(exports, "isValidTraceId", { enumerable: true, get: function () { return spancontext_utils_1.isValidTraceId; } }); +Object.defineProperty(exports, "isValidSpanId", { enumerable: true, get: function () { return spancontext_utils_1.isValidSpanId; } }); +var invalid_span_constants_1 = require("./trace/invalid-span-constants"); +Object.defineProperty(exports, "INVALID_SPANID", { enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPANID; } }); +Object.defineProperty(exports, "INVALID_TRACEID", { enumerable: true, get: function () { return invalid_span_constants_1.INVALID_TRACEID; } }); +Object.defineProperty(exports, "INVALID_SPAN_CONTEXT", { enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPAN_CONTEXT; } }); +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +const context_api_1 = require("./context-api"); +Object.defineProperty(exports, "context", { enumerable: true, get: function () { return context_api_1.context; } }); +const diag_api_1 = require("./diag-api"); +Object.defineProperty(exports, "diag", { enumerable: true, get: function () { return diag_api_1.diag; } }); +const metrics_api_1 = require("./metrics-api"); +Object.defineProperty(exports, "metrics", { enumerable: true, get: function () { return metrics_api_1.metrics; } }); +const propagation_api_1 = require("./propagation-api"); +Object.defineProperty(exports, "propagation", { enumerable: true, get: function () { return propagation_api_1.propagation; } }); +const trace_api_1 = require("./trace-api"); +Object.defineProperty(exports, "trace", { enumerable: true, get: function () { return trace_api_1.trace; } }); +// Default export. +exports.default = { + context: context_api_1.context, + diag: diag_api_1.diag, + metrics: metrics_api_1.metrics, + propagation: propagation_api_1.propagation, + trace: trace_api_1.trace, +}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/internal/global-utils.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/internal/global-utils.js new file mode 100644 index 00000000..11a1a441 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/internal/global-utils.js @@ -0,0 +1,64 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.unregisterGlobal = exports.getGlobal = exports.registerGlobal = void 0; +const platform_1 = require("../platform"); +const version_1 = require("../version"); +const semver_1 = require("./semver"); +const major = version_1.VERSION.split('.')[0]; +const GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(`opentelemetry.js.api.${major}`); +const _global = platform_1._globalThis; +function registerGlobal(type, instance, diag, allowOverride = false) { + var _a; + const api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : { + version: version_1.VERSION, + }); + if (!allowOverride && api[type]) { + // already registered an API of this type + const err = new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`); + diag.error(err.stack || err.message); + return false; + } + if (api.version !== version_1.VERSION) { + // All registered APIs must be of the same version exactly + const err = new Error(`@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${version_1.VERSION}`); + diag.error(err.stack || err.message); + return false; + } + api[type] = instance; + diag.debug(`@opentelemetry/api: Registered a global for ${type} v${version_1.VERSION}.`); + return true; +} +exports.registerGlobal = registerGlobal; +function getGlobal(type) { + var _a, _b; + const globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version; + if (!globalVersion || !(0, semver_1.isCompatible)(globalVersion)) { + return; + } + return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type]; +} +exports.getGlobal = getGlobal; +function unregisterGlobal(type, diag) { + diag.debug(`@opentelemetry/api: Unregistering a global for ${type} v${version_1.VERSION}.`); + const api = _global[GLOBAL_OPENTELEMETRY_API_KEY]; + if (api) { + delete api[type]; + } +} +exports.unregisterGlobal = unregisterGlobal; +//# sourceMappingURL=global-utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/internal/semver.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/internal/semver.js new file mode 100644 index 00000000..7a073b22 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/internal/semver.js @@ -0,0 +1,122 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isCompatible = exports._makeCompatibilityCheck = void 0; +const version_1 = require("../version"); +const re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; +/** + * Create a function to test an API version to see if it is compatible with the provided ownVersion. + * + * The returned function has the following semantics: + * - Exact match is always compatible + * - Major versions must match exactly + * - 1.x package cannot use global 2.x package + * - 2.x package cannot use global 1.x package + * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API + * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects + * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3 + * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor + * - Patch and build tag differences are not considered at this time + * + * @param ownVersion version which should be checked against + */ +function _makeCompatibilityCheck(ownVersion) { + const acceptedVersions = new Set([ownVersion]); + const rejectedVersions = new Set(); + const myVersionMatch = ownVersion.match(re); + if (!myVersionMatch) { + // we cannot guarantee compatibility so we always return noop + return () => false; + } + const ownVersionParsed = { + major: +myVersionMatch[1], + minor: +myVersionMatch[2], + patch: +myVersionMatch[3], + prerelease: myVersionMatch[4], + }; + // if ownVersion has a prerelease tag, versions must match exactly + if (ownVersionParsed.prerelease != null) { + return function isExactmatch(globalVersion) { + return globalVersion === ownVersion; + }; + } + function _reject(v) { + rejectedVersions.add(v); + return false; + } + function _accept(v) { + acceptedVersions.add(v); + return true; + } + return function isCompatible(globalVersion) { + if (acceptedVersions.has(globalVersion)) { + return true; + } + if (rejectedVersions.has(globalVersion)) { + return false; + } + const globalVersionMatch = globalVersion.match(re); + if (!globalVersionMatch) { + // cannot parse other version + // we cannot guarantee compatibility so we always noop + return _reject(globalVersion); + } + const globalVersionParsed = { + major: +globalVersionMatch[1], + minor: +globalVersionMatch[2], + patch: +globalVersionMatch[3], + prerelease: globalVersionMatch[4], + }; + // if globalVersion has a prerelease tag, versions must match exactly + if (globalVersionParsed.prerelease != null) { + return _reject(globalVersion); + } + // major versions must match + if (ownVersionParsed.major !== globalVersionParsed.major) { + return _reject(globalVersion); + } + if (ownVersionParsed.major === 0) { + if (ownVersionParsed.minor === globalVersionParsed.minor && + ownVersionParsed.patch <= globalVersionParsed.patch) { + return _accept(globalVersion); + } + return _reject(globalVersion); + } + if (ownVersionParsed.minor <= globalVersionParsed.minor) { + return _accept(globalVersion); + } + return _reject(globalVersion); + }; +} +exports._makeCompatibilityCheck = _makeCompatibilityCheck; +/** + * Test an API version to see if it is compatible with this API. + * + * - Exact match is always compatible + * - Major versions must match exactly + * - 1.x package cannot use global 2.x package + * - 2.x package cannot use global 1.x package + * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API + * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects + * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3 + * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor + * - Patch and build tag differences are not considered at this time + * + * @param version version of the API requesting an instance of the global API + */ +exports.isCompatible = _makeCompatibilityCheck(version_1.VERSION); +//# sourceMappingURL=semver.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/metrics-api.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/metrics-api.js new file mode 100644 index 00000000..987f7c25 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/metrics-api.js @@ -0,0 +1,24 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.metrics = void 0; +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +const metrics_1 = require("./api/metrics"); +/** Entrypoint for metrics API */ +exports.metrics = metrics_1.MetricsAPI.getInstance(); +//# sourceMappingURL=metrics-api.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/metrics/Metric.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/metrics/Metric.js new file mode 100644 index 00000000..4966c3d5 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/metrics/Metric.js @@ -0,0 +1,25 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ValueType = void 0; +/** The Type of value. It describes how the data is reported. */ +var ValueType; +(function (ValueType) { + ValueType[ValueType["INT"] = 0] = "INT"; + ValueType[ValueType["DOUBLE"] = 1] = "DOUBLE"; +})(ValueType = exports.ValueType || (exports.ValueType = {})); +//# sourceMappingURL=Metric.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/metrics/NoopMeter.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/metrics/NoopMeter.js new file mode 100644 index 00000000..d40ef036 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/metrics/NoopMeter.js @@ -0,0 +1,127 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createNoopMeter = exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = exports.NOOP_OBSERVABLE_GAUGE_METRIC = exports.NOOP_OBSERVABLE_COUNTER_METRIC = exports.NOOP_UP_DOWN_COUNTER_METRIC = exports.NOOP_HISTOGRAM_METRIC = exports.NOOP_GAUGE_METRIC = exports.NOOP_COUNTER_METRIC = exports.NOOP_METER = exports.NoopObservableUpDownCounterMetric = exports.NoopObservableGaugeMetric = exports.NoopObservableCounterMetric = exports.NoopObservableMetric = exports.NoopHistogramMetric = exports.NoopGaugeMetric = exports.NoopUpDownCounterMetric = exports.NoopCounterMetric = exports.NoopMetric = exports.NoopMeter = void 0; +/** + * NoopMeter is a noop implementation of the {@link Meter} interface. It reuses + * constant NoopMetrics for all of its methods. + */ +class NoopMeter { + constructor() { } + /** + * @see {@link Meter.createGauge} + */ + createGauge(_name, _options) { + return exports.NOOP_GAUGE_METRIC; + } + /** + * @see {@link Meter.createHistogram} + */ + createHistogram(_name, _options) { + return exports.NOOP_HISTOGRAM_METRIC; + } + /** + * @see {@link Meter.createCounter} + */ + createCounter(_name, _options) { + return exports.NOOP_COUNTER_METRIC; + } + /** + * @see {@link Meter.createUpDownCounter} + */ + createUpDownCounter(_name, _options) { + return exports.NOOP_UP_DOWN_COUNTER_METRIC; + } + /** + * @see {@link Meter.createObservableGauge} + */ + createObservableGauge(_name, _options) { + return exports.NOOP_OBSERVABLE_GAUGE_METRIC; + } + /** + * @see {@link Meter.createObservableCounter} + */ + createObservableCounter(_name, _options) { + return exports.NOOP_OBSERVABLE_COUNTER_METRIC; + } + /** + * @see {@link Meter.createObservableUpDownCounter} + */ + createObservableUpDownCounter(_name, _options) { + return exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC; + } + /** + * @see {@link Meter.addBatchObservableCallback} + */ + addBatchObservableCallback(_callback, _observables) { } + /** + * @see {@link Meter.removeBatchObservableCallback} + */ + removeBatchObservableCallback(_callback) { } +} +exports.NoopMeter = NoopMeter; +class NoopMetric { +} +exports.NoopMetric = NoopMetric; +class NoopCounterMetric extends NoopMetric { + add(_value, _attributes) { } +} +exports.NoopCounterMetric = NoopCounterMetric; +class NoopUpDownCounterMetric extends NoopMetric { + add(_value, _attributes) { } +} +exports.NoopUpDownCounterMetric = NoopUpDownCounterMetric; +class NoopGaugeMetric extends NoopMetric { + record(_value, _attributes) { } +} +exports.NoopGaugeMetric = NoopGaugeMetric; +class NoopHistogramMetric extends NoopMetric { + record(_value, _attributes) { } +} +exports.NoopHistogramMetric = NoopHistogramMetric; +class NoopObservableMetric { + addCallback(_callback) { } + removeCallback(_callback) { } +} +exports.NoopObservableMetric = NoopObservableMetric; +class NoopObservableCounterMetric extends NoopObservableMetric { +} +exports.NoopObservableCounterMetric = NoopObservableCounterMetric; +class NoopObservableGaugeMetric extends NoopObservableMetric { +} +exports.NoopObservableGaugeMetric = NoopObservableGaugeMetric; +class NoopObservableUpDownCounterMetric extends NoopObservableMetric { +} +exports.NoopObservableUpDownCounterMetric = NoopObservableUpDownCounterMetric; +exports.NOOP_METER = new NoopMeter(); +// Synchronous instruments +exports.NOOP_COUNTER_METRIC = new NoopCounterMetric(); +exports.NOOP_GAUGE_METRIC = new NoopGaugeMetric(); +exports.NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric(); +exports.NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric(); +// Asynchronous instruments +exports.NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric(); +exports.NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric(); +exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = new NoopObservableUpDownCounterMetric(); +/** + * Create a no-op Meter + */ +function createNoopMeter() { + return exports.NOOP_METER; +} +exports.createNoopMeter = createNoopMeter; +//# sourceMappingURL=NoopMeter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/metrics/NoopMeterProvider.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/metrics/NoopMeterProvider.js new file mode 100644 index 00000000..b1c1cc06 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/metrics/NoopMeterProvider.js @@ -0,0 +1,31 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NOOP_METER_PROVIDER = exports.NoopMeterProvider = void 0; +const NoopMeter_1 = require("./NoopMeter"); +/** + * An implementation of the {@link MeterProvider} which returns an impotent Meter + * for all calls to `getMeter` + */ +class NoopMeterProvider { + getMeter(_name, _version, _options) { + return NoopMeter_1.NOOP_METER; + } +} +exports.NoopMeterProvider = NoopMeterProvider; +exports.NOOP_METER_PROVIDER = new NoopMeterProvider(); +//# sourceMappingURL=NoopMeterProvider.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/platform/index.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/platform/index.js new file mode 100644 index 00000000..33b834db --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/platform/index.js @@ -0,0 +1,29 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./node"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/platform/node/globalThis.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/platform/node/globalThis.js new file mode 100644 index 00000000..82c4e394 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/platform/node/globalThis.js @@ -0,0 +1,22 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports._globalThis = void 0; +/** only globals that common to node and browsers are allowed */ +// eslint-disable-next-line node/no-unsupported-features/es-builtins +exports._globalThis = typeof globalThis === 'object' ? globalThis : global; +//# sourceMappingURL=globalThis.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/platform/node/index.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/platform/node/index.js new file mode 100644 index 00000000..99fd57c8 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/platform/node/index.js @@ -0,0 +1,29 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./globalThis"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/propagation-api.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/propagation-api.js new file mode 100644 index 00000000..f014fb4a --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/propagation-api.js @@ -0,0 +1,24 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.propagation = void 0; +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +const propagation_1 = require("./api/propagation"); +/** Entrypoint for propagation API */ +exports.propagation = propagation_1.PropagationAPI.getInstance(); +//# sourceMappingURL=propagation-api.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/propagation/NoopTextMapPropagator.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/propagation/NoopTextMapPropagator.js new file mode 100644 index 00000000..3f395829 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/propagation/NoopTextMapPropagator.js @@ -0,0 +1,34 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NoopTextMapPropagator = void 0; +/** + * No-op implementations of {@link TextMapPropagator}. + */ +class NoopTextMapPropagator { + /** Noop inject function does nothing */ + inject(_context, _carrier) { } + /** Noop extract function does nothing and returns the input context */ + extract(context, _carrier) { + return context; + } + fields() { + return []; + } +} +exports.NoopTextMapPropagator = NoopTextMapPropagator; +//# sourceMappingURL=NoopTextMapPropagator.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/propagation/TextMapPropagator.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/propagation/TextMapPropagator.js new file mode 100644 index 00000000..513f33c6 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/propagation/TextMapPropagator.js @@ -0,0 +1,41 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defaultTextMapSetter = exports.defaultTextMapGetter = void 0; +exports.defaultTextMapGetter = { + get(carrier, key) { + if (carrier == null) { + return undefined; + } + return carrier[key]; + }, + keys(carrier) { + if (carrier == null) { + return []; + } + return Object.keys(carrier); + }, +}; +exports.defaultTextMapSetter = { + set(carrier, key, value) { + if (carrier == null) { + return; + } + carrier[key] = value; + }, +}; +//# sourceMappingURL=TextMapPropagator.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace-api.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace-api.js new file mode 100644 index 00000000..c8bbe93a --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace-api.js @@ -0,0 +1,24 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.trace = void 0; +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +const trace_1 = require("./api/trace"); +/** Entrypoint for trace API */ +exports.trace = trace_1.TraceAPI.getInstance(); +//# sourceMappingURL=trace-api.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/NonRecordingSpan.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/NonRecordingSpan.js new file mode 100644 index 00000000..6d3e6eea --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/NonRecordingSpan.js @@ -0,0 +1,69 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NonRecordingSpan = void 0; +const invalid_span_constants_1 = require("./invalid-span-constants"); +/** + * The NonRecordingSpan is the default {@link Span} that is used when no Span + * implementation is available. All operations are no-op including context + * propagation. + */ +class NonRecordingSpan { + constructor(_spanContext = invalid_span_constants_1.INVALID_SPAN_CONTEXT) { + this._spanContext = _spanContext; + } + // Returns a SpanContext. + spanContext() { + return this._spanContext; + } + // By default does nothing + setAttribute(_key, _value) { + return this; + } + // By default does nothing + setAttributes(_attributes) { + return this; + } + // By default does nothing + addEvent(_name, _attributes) { + return this; + } + addLink(_link) { + return this; + } + addLinks(_links) { + return this; + } + // By default does nothing + setStatus(_status) { + return this; + } + // By default does nothing + updateName(_name) { + return this; + } + // By default does nothing + end(_endTime) { } + // isRecording always returns false for NonRecordingSpan. + isRecording() { + return false; + } + // By default does nothing + recordException(_exception, _time) { } +} +exports.NonRecordingSpan = NonRecordingSpan; +//# sourceMappingURL=NonRecordingSpan.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/NoopTracer.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/NoopTracer.js new file mode 100644 index 00000000..0a823aa5 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/NoopTracer.js @@ -0,0 +1,75 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NoopTracer = void 0; +const context_1 = require("../api/context"); +const context_utils_1 = require("../trace/context-utils"); +const NonRecordingSpan_1 = require("./NonRecordingSpan"); +const spancontext_utils_1 = require("./spancontext-utils"); +const contextApi = context_1.ContextAPI.getInstance(); +/** + * No-op implementations of {@link Tracer}. + */ +class NoopTracer { + // startSpan starts a noop span. + startSpan(name, options, context = contextApi.active()) { + const root = Boolean(options === null || options === void 0 ? void 0 : options.root); + if (root) { + return new NonRecordingSpan_1.NonRecordingSpan(); + } + const parentFromContext = context && (0, context_utils_1.getSpanContext)(context); + if (isSpanContext(parentFromContext) && + (0, spancontext_utils_1.isSpanContextValid)(parentFromContext)) { + return new NonRecordingSpan_1.NonRecordingSpan(parentFromContext); + } + else { + return new NonRecordingSpan_1.NonRecordingSpan(); + } + } + startActiveSpan(name, arg2, arg3, arg4) { + let opts; + let ctx; + let fn; + if (arguments.length < 2) { + return; + } + else if (arguments.length === 2) { + fn = arg2; + } + else if (arguments.length === 3) { + opts = arg2; + fn = arg3; + } + else { + opts = arg2; + ctx = arg3; + fn = arg4; + } + const parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active(); + const span = this.startSpan(name, opts, parentContext); + const contextWithSpanSet = (0, context_utils_1.setSpan)(parentContext, span); + return contextApi.with(contextWithSpanSet, fn, undefined, span); + } +} +exports.NoopTracer = NoopTracer; +function isSpanContext(spanContext) { + return (typeof spanContext === 'object' && + typeof spanContext['spanId'] === 'string' && + typeof spanContext['traceId'] === 'string' && + typeof spanContext['traceFlags'] === 'number'); +} +//# sourceMappingURL=NoopTracer.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/NoopTracerProvider.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/NoopTracerProvider.js new file mode 100644 index 00000000..c9e08d63 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/NoopTracerProvider.js @@ -0,0 +1,32 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NoopTracerProvider = void 0; +const NoopTracer_1 = require("./NoopTracer"); +/** + * An implementation of the {@link TracerProvider} which returns an impotent + * Tracer for all calls to `getTracer`. + * + * All operations are no-op. + */ +class NoopTracerProvider { + getTracer(_name, _version, _options) { + return new NoopTracer_1.NoopTracer(); + } +} +exports.NoopTracerProvider = NoopTracerProvider; +//# sourceMappingURL=NoopTracerProvider.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/ProxyTracer.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/ProxyTracer.js new file mode 100644 index 00000000..66776801 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/ProxyTracer.js @@ -0,0 +1,55 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ProxyTracer = void 0; +const NoopTracer_1 = require("./NoopTracer"); +const NOOP_TRACER = new NoopTracer_1.NoopTracer(); +/** + * Proxy tracer provided by the proxy tracer provider + */ +class ProxyTracer { + constructor(_provider, name, version, options) { + this._provider = _provider; + this.name = name; + this.version = version; + this.options = options; + } + startSpan(name, options, context) { + return this._getTracer().startSpan(name, options, context); + } + startActiveSpan(_name, _options, _context, _fn) { + const tracer = this._getTracer(); + return Reflect.apply(tracer.startActiveSpan, tracer, arguments); + } + /** + * Try to get a tracer from the proxy tracer provider. + * If the proxy tracer provider has no delegate, return a noop tracer. + */ + _getTracer() { + if (this._delegate) { + return this._delegate; + } + const tracer = this._provider.getDelegateTracer(this.name, this.version, this.options); + if (!tracer) { + return NOOP_TRACER; + } + this._delegate = tracer; + return this._delegate; + } +} +exports.ProxyTracer = ProxyTracer; +//# sourceMappingURL=ProxyTracer.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/ProxyTracerProvider.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/ProxyTracerProvider.js new file mode 100644 index 00000000..75ec910d --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/ProxyTracerProvider.js @@ -0,0 +1,54 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ProxyTracerProvider = void 0; +const ProxyTracer_1 = require("./ProxyTracer"); +const NoopTracerProvider_1 = require("./NoopTracerProvider"); +const NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider(); +/** + * Tracer provider which provides {@link ProxyTracer}s. + * + * Before a delegate is set, tracers provided are NoOp. + * When a delegate is set, traces are provided from the delegate. + * When a delegate is set after tracers have already been provided, + * all tracers already provided will use the provided delegate implementation. + */ +class ProxyTracerProvider { + /** + * Get a {@link ProxyTracer} + */ + getTracer(name, version, options) { + var _a; + return ((_a = this.getDelegateTracer(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyTracer_1.ProxyTracer(this, name, version, options)); + } + getDelegate() { + var _a; + return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER; + } + /** + * Set the delegate tracer provider + */ + setDelegate(delegate) { + this._delegate = delegate; + } + getDelegateTracer(name, version, options) { + var _a; + return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version, options); + } +} +exports.ProxyTracerProvider = ProxyTracerProvider; +//# sourceMappingURL=ProxyTracerProvider.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/SamplingResult.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/SamplingResult.js new file mode 100644 index 00000000..6df6b3bf --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/SamplingResult.js @@ -0,0 +1,42 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SamplingDecision = void 0; +/** + * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead. + * A sampling decision that determines how a {@link Span} will be recorded + * and collected. + */ +var SamplingDecision; +(function (SamplingDecision) { + /** + * `Span.isRecording() === false`, span will not be recorded and all events + * and attributes will be dropped. + */ + SamplingDecision[SamplingDecision["NOT_RECORD"] = 0] = "NOT_RECORD"; + /** + * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags} + * MUST NOT be set. + */ + SamplingDecision[SamplingDecision["RECORD"] = 1] = "RECORD"; + /** + * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags} + * MUST be set. + */ + SamplingDecision[SamplingDecision["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED"; +})(SamplingDecision = exports.SamplingDecision || (exports.SamplingDecision = {})); +//# sourceMappingURL=SamplingResult.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/context-utils.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/context-utils.js new file mode 100644 index 00000000..d7e9c3a3 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/context-utils.js @@ -0,0 +1,82 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getSpanContext = exports.setSpanContext = exports.deleteSpan = exports.setSpan = exports.getActiveSpan = exports.getSpan = void 0; +const context_1 = require("../context/context"); +const NonRecordingSpan_1 = require("./NonRecordingSpan"); +const context_2 = require("../api/context"); +/** + * span key + */ +const SPAN_KEY = (0, context_1.createContextKey)('OpenTelemetry Context Key SPAN'); +/** + * Return the span if one exists + * + * @param context context to get span from + */ +function getSpan(context) { + return context.getValue(SPAN_KEY) || undefined; +} +exports.getSpan = getSpan; +/** + * Gets the span from the current context, if one exists. + */ +function getActiveSpan() { + return getSpan(context_2.ContextAPI.getInstance().active()); +} +exports.getActiveSpan = getActiveSpan; +/** + * Set the span on a context + * + * @param context context to use as parent + * @param span span to set active + */ +function setSpan(context, span) { + return context.setValue(SPAN_KEY, span); +} +exports.setSpan = setSpan; +/** + * Remove current span stored in the context + * + * @param context context to delete span from + */ +function deleteSpan(context) { + return context.deleteValue(SPAN_KEY); +} +exports.deleteSpan = deleteSpan; +/** + * Wrap span context in a NoopSpan and set as span in a new + * context + * + * @param context context to set active span on + * @param spanContext span context to be wrapped + */ +function setSpanContext(context, spanContext) { + return setSpan(context, new NonRecordingSpan_1.NonRecordingSpan(spanContext)); +} +exports.setSpanContext = setSpanContext; +/** + * Get the span context of the span if it exists. + * + * @param context context to get values from + */ +function getSpanContext(context) { + var _a; + return (_a = getSpan(context)) === null || _a === void 0 ? void 0 : _a.spanContext(); +} +exports.getSpanContext = getSpanContext; +//# sourceMappingURL=context-utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-impl.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-impl.js new file mode 100644 index 00000000..93c0289c --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-impl.js @@ -0,0 +1,103 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TraceStateImpl = void 0; +const tracestate_validators_1 = require("./tracestate-validators"); +const MAX_TRACE_STATE_ITEMS = 32; +const MAX_TRACE_STATE_LEN = 512; +const LIST_MEMBERS_SEPARATOR = ','; +const LIST_MEMBER_KEY_VALUE_SPLITTER = '='; +/** + * TraceState must be a class and not a simple object type because of the spec + * requirement (https://www.w3.org/TR/trace-context/#tracestate-field). + * + * Here is the list of allowed mutations: + * - New key-value pair should be added into the beginning of the list + * - The value of any key can be updated. Modified keys MUST be moved to the + * beginning of the list. + */ +class TraceStateImpl { + constructor(rawTraceState) { + this._internalState = new Map(); + if (rawTraceState) + this._parse(rawTraceState); + } + set(key, value) { + // TODO: Benchmark the different approaches(map vs list) and + // use the faster one. + const traceState = this._clone(); + if (traceState._internalState.has(key)) { + traceState._internalState.delete(key); + } + traceState._internalState.set(key, value); + return traceState; + } + unset(key) { + const traceState = this._clone(); + traceState._internalState.delete(key); + return traceState; + } + get(key) { + return this._internalState.get(key); + } + serialize() { + return this._keys() + .reduce((agg, key) => { + agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key)); + return agg; + }, []) + .join(LIST_MEMBERS_SEPARATOR); + } + _parse(rawTraceState) { + if (rawTraceState.length > MAX_TRACE_STATE_LEN) + return; + this._internalState = rawTraceState + .split(LIST_MEMBERS_SEPARATOR) + .reverse() // Store in reverse so new keys (.set(...)) will be placed at the beginning + .reduce((agg, part) => { + const listMember = part.trim(); // Optional Whitespace (OWS) handling + const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER); + if (i !== -1) { + const key = listMember.slice(0, i); + const value = listMember.slice(i + 1, part.length); + if ((0, tracestate_validators_1.validateKey)(key) && (0, tracestate_validators_1.validateValue)(value)) { + agg.set(key, value); + } + else { + // TODO: Consider to add warning log + } + } + return agg; + }, new Map()); + // Because of the reverse() requirement, trunc must be done after map is created + if (this._internalState.size > MAX_TRACE_STATE_ITEMS) { + this._internalState = new Map(Array.from(this._internalState.entries()) + .reverse() // Use reverse same as original tracestate parse chain + .slice(0, MAX_TRACE_STATE_ITEMS)); + } + } + _keys() { + return Array.from(this._internalState.keys()).reverse(); + } + _clone() { + const traceState = new TraceStateImpl(); + traceState._internalState = new Map(this._internalState); + return traceState; + } +} +exports.TraceStateImpl = TraceStateImpl; +//# sourceMappingURL=tracestate-impl.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-validators.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-validators.js new file mode 100644 index 00000000..3e370449 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-validators.js @@ -0,0 +1,46 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateValue = exports.validateKey = void 0; +const VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]'; +const VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`; +const VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`; +const VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`); +const VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/; +const INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/; +/** + * Key is opaque string up to 256 characters printable. It MUST begin with a + * lowercase letter, and can only contain lowercase letters a-z, digits 0-9, + * underscores _, dashes -, asterisks *, and forward slashes /. + * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the + * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key. + * see https://www.w3.org/TR/trace-context/#key + */ +function validateKey(key) { + return VALID_KEY_REGEX.test(key); +} +exports.validateKey = validateKey; +/** + * Value is opaque string up to 256 characters printable ASCII RFC0020 + * characters (i.e., the range 0x20 to 0x7E) except comma , and =. + */ +function validateValue(value) { + return (VALID_VALUE_BASE_REGEX.test(value) && + !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value)); +} +exports.validateValue = validateValue; +//# sourceMappingURL=tracestate-validators.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/internal/utils.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/internal/utils.js new file mode 100644 index 00000000..3d954190 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/internal/utils.js @@ -0,0 +1,24 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createTraceState = void 0; +const tracestate_impl_1 = require("./tracestate-impl"); +function createTraceState(rawTraceState) { + return new tracestate_impl_1.TraceStateImpl(rawTraceState); +} +exports.createTraceState = createTraceState; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/invalid-span-constants.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/invalid-span-constants.js new file mode 100644 index 00000000..77fb79e9 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/invalid-span-constants.js @@ -0,0 +1,27 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = void 0; +const trace_flags_1 = require("./trace_flags"); +exports.INVALID_SPANID = '0000000000000000'; +exports.INVALID_TRACEID = '00000000000000000000000000000000'; +exports.INVALID_SPAN_CONTEXT = { + traceId: exports.INVALID_TRACEID, + spanId: exports.INVALID_SPANID, + traceFlags: trace_flags_1.TraceFlags.NONE, +}; +//# sourceMappingURL=invalid-span-constants.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/span_kind.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/span_kind.js new file mode 100644 index 00000000..9c06e2c2 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/span_kind.js @@ -0,0 +1,46 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SpanKind = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var SpanKind; +(function (SpanKind) { + /** Default value. Indicates that the span is used internally. */ + SpanKind[SpanKind["INTERNAL"] = 0] = "INTERNAL"; + /** + * Indicates that the span covers server-side handling of an RPC or other + * remote request. + */ + SpanKind[SpanKind["SERVER"] = 1] = "SERVER"; + /** + * Indicates that the span covers the client-side wrapper around an RPC or + * other remote request. + */ + SpanKind[SpanKind["CLIENT"] = 2] = "CLIENT"; + /** + * Indicates that the span describes producer sending a message to a + * broker. Unlike client and server, there is no direct critical path latency + * relationship between producer and consumer spans. + */ + SpanKind[SpanKind["PRODUCER"] = 3] = "PRODUCER"; + /** + * Indicates that the span describes consumer receiving a message from a + * broker. Unlike client and server, there is no direct critical path latency + * relationship between producer and consumer spans. + */ + SpanKind[SpanKind["CONSUMER"] = 4] = "CONSUMER"; +})(SpanKind = exports.SpanKind || (exports.SpanKind = {})); +//# sourceMappingURL=span_kind.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/spancontext-utils.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/spancontext-utils.js new file mode 100644 index 00000000..dc88f5e6 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/spancontext-utils.js @@ -0,0 +1,49 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wrapSpanContext = exports.isSpanContextValid = exports.isValidSpanId = exports.isValidTraceId = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const invalid_span_constants_1 = require("./invalid-span-constants"); +const NonRecordingSpan_1 = require("./NonRecordingSpan"); +const VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i; +const VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i; +function isValidTraceId(traceId) { + return VALID_TRACEID_REGEX.test(traceId) && traceId !== invalid_span_constants_1.INVALID_TRACEID; +} +exports.isValidTraceId = isValidTraceId; +function isValidSpanId(spanId) { + return VALID_SPANID_REGEX.test(spanId) && spanId !== invalid_span_constants_1.INVALID_SPANID; +} +exports.isValidSpanId = isValidSpanId; +/** + * Returns true if this {@link SpanContext} is valid. + * @return true if this {@link SpanContext} is valid. + */ +function isSpanContextValid(spanContext) { + return (isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId)); +} +exports.isSpanContextValid = isSpanContextValid; +/** + * Wrap the given {@link SpanContext} in a new non-recording {@link Span} + * + * @param spanContext span context to be wrapped + * @returns a new non-recording {@link Span} with the provided context + */ +function wrapSpanContext(spanContext) { + return new NonRecordingSpan_1.NonRecordingSpan(spanContext); +} +exports.wrapSpanContext = wrapSpanContext; +//# sourceMappingURL=spancontext-utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/status.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/status.js new file mode 100644 index 00000000..50cbdef8 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/status.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SpanStatusCode = void 0; +/** + * An enumeration of status codes. + */ +var SpanStatusCode; +(function (SpanStatusCode) { + /** + * The default status. + */ + SpanStatusCode[SpanStatusCode["UNSET"] = 0] = "UNSET"; + /** + * The operation has been validated by an Application developer or + * Operator to have completed successfully. + */ + SpanStatusCode[SpanStatusCode["OK"] = 1] = "OK"; + /** + * The operation contains an error. + */ + SpanStatusCode[SpanStatusCode["ERROR"] = 2] = "ERROR"; +})(SpanStatusCode = exports.SpanStatusCode || (exports.SpanStatusCode = {})); +//# sourceMappingURL=status.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/trace_flags.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/trace_flags.js new file mode 100644 index 00000000..f8d4dd8a --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/trace_flags.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TraceFlags = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var TraceFlags; +(function (TraceFlags) { + /** Represents no flag set. */ + TraceFlags[TraceFlags["NONE"] = 0] = "NONE"; + /** Bit to represent whether trace is sampled in trace flags. */ + TraceFlags[TraceFlags["SAMPLED"] = 1] = "SAMPLED"; +})(TraceFlags = exports.TraceFlags || (exports.TraceFlags = {})); +//# sourceMappingURL=trace_flags.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/version.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/version.js new file mode 100644 index 00000000..3c717941 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/api/build/src/version.js @@ -0,0 +1,21 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.VERSION = void 0; +// this is autogenerated file, see scripts/version-update.js +exports.VERSION = '1.9.0'; +//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/ExportResult.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/ExportResult.js new file mode 100644 index 00000000..724d006d --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/core/build/src/ExportResult.js @@ -0,0 +1,24 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ExportResultCode = void 0; +var ExportResultCode; +(function (ExportResultCode) { + ExportResultCode[ExportResultCode["SUCCESS"] = 0] = "SUCCESS"; + ExportResultCode[ExportResultCode["FAILED"] = 1] = "FAILED"; +})(ExportResultCode = exports.ExportResultCode || (exports.ExportResultCode = {})); +//# sourceMappingURL=ExportResult.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/baggage/constants.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/baggage/constants.js new file mode 100644 index 00000000..88dcfcef --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/core/build/src/baggage/constants.js @@ -0,0 +1,30 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BAGGAGE_MAX_TOTAL_LENGTH = exports.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS = exports.BAGGAGE_MAX_NAME_VALUE_PAIRS = exports.BAGGAGE_HEADER = exports.BAGGAGE_ITEMS_SEPARATOR = exports.BAGGAGE_PROPERTIES_SEPARATOR = exports.BAGGAGE_KEY_PAIR_SEPARATOR = void 0; +exports.BAGGAGE_KEY_PAIR_SEPARATOR = '='; +exports.BAGGAGE_PROPERTIES_SEPARATOR = ';'; +exports.BAGGAGE_ITEMS_SEPARATOR = ','; +// Name of the http header used to propagate the baggage +exports.BAGGAGE_HEADER = 'baggage'; +// Maximum number of name-value pairs allowed by w3c spec +exports.BAGGAGE_MAX_NAME_VALUE_PAIRS = 180; +// Maximum number of bytes per a single name-value pair allowed by w3c spec +exports.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS = 4096; +// Maximum total length of all name-value pairs allowed by w3c spec +exports.BAGGAGE_MAX_TOTAL_LENGTH = 8192; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/baggage/propagation/W3CBaggagePropagator.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/baggage/propagation/W3CBaggagePropagator.js new file mode 100644 index 00000000..d2959501 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/core/build/src/baggage/propagation/W3CBaggagePropagator.js @@ -0,0 +1,76 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.W3CBaggagePropagator = void 0; +const api_1 = require("@opentelemetry/api"); +const suppress_tracing_1 = require("../../trace/suppress-tracing"); +const constants_1 = require("../constants"); +const utils_1 = require("../utils"); +/** + * Propagates {@link Baggage} through Context format propagation. + * + * Based on the Baggage specification: + * https://w3c.github.io/baggage/ + */ +class W3CBaggagePropagator { + inject(context, carrier, setter) { + const baggage = api_1.propagation.getBaggage(context); + if (!baggage || (0, suppress_tracing_1.isTracingSuppressed)(context)) + return; + const keyPairs = (0, utils_1.getKeyPairs)(baggage) + .filter((pair) => { + return pair.length <= constants_1.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS; + }) + .slice(0, constants_1.BAGGAGE_MAX_NAME_VALUE_PAIRS); + const headerValue = (0, utils_1.serializeKeyPairs)(keyPairs); + if (headerValue.length > 0) { + setter.set(carrier, constants_1.BAGGAGE_HEADER, headerValue); + } + } + extract(context, carrier, getter) { + const headerValue = getter.get(carrier, constants_1.BAGGAGE_HEADER); + const baggageString = Array.isArray(headerValue) + ? headerValue.join(constants_1.BAGGAGE_ITEMS_SEPARATOR) + : headerValue; + if (!baggageString) + return context; + const baggage = {}; + if (baggageString.length === 0) { + return context; + } + const pairs = baggageString.split(constants_1.BAGGAGE_ITEMS_SEPARATOR); + pairs.forEach(entry => { + const keyPair = (0, utils_1.parsePairKeyValue)(entry); + if (keyPair) { + const baggageEntry = { value: keyPair.value }; + if (keyPair.metadata) { + baggageEntry.metadata = keyPair.metadata; + } + baggage[keyPair.key] = baggageEntry; + } + }); + if (Object.entries(baggage).length === 0) { + return context; + } + return api_1.propagation.setBaggage(context, api_1.propagation.createBaggage(baggage)); + } + fields() { + return [constants_1.BAGGAGE_HEADER]; + } +} +exports.W3CBaggagePropagator = W3CBaggagePropagator; +//# sourceMappingURL=W3CBaggagePropagator.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/baggage/utils.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/baggage/utils.js new file mode 100644 index 00000000..3cb9015f --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/core/build/src/baggage/utils.js @@ -0,0 +1,76 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseKeyPairsIntoRecord = exports.parsePairKeyValue = exports.getKeyPairs = exports.serializeKeyPairs = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const api_1 = require("@opentelemetry/api"); +const constants_1 = require("./constants"); +function serializeKeyPairs(keyPairs) { + return keyPairs.reduce((hValue, current) => { + const value = `${hValue}${hValue !== '' ? constants_1.BAGGAGE_ITEMS_SEPARATOR : ''}${current}`; + return value.length > constants_1.BAGGAGE_MAX_TOTAL_LENGTH ? hValue : value; + }, ''); +} +exports.serializeKeyPairs = serializeKeyPairs; +function getKeyPairs(baggage) { + return baggage.getAllEntries().map(([key, value]) => { + let entry = `${encodeURIComponent(key)}=${encodeURIComponent(value.value)}`; + // include opaque metadata if provided + // NOTE: we intentionally don't URI-encode the metadata - that responsibility falls on the metadata implementation + if (value.metadata !== undefined) { + entry += constants_1.BAGGAGE_PROPERTIES_SEPARATOR + value.metadata.toString(); + } + return entry; + }); +} +exports.getKeyPairs = getKeyPairs; +function parsePairKeyValue(entry) { + const valueProps = entry.split(constants_1.BAGGAGE_PROPERTIES_SEPARATOR); + if (valueProps.length <= 0) + return; + const keyPairPart = valueProps.shift(); + if (!keyPairPart) + return; + const separatorIndex = keyPairPart.indexOf(constants_1.BAGGAGE_KEY_PAIR_SEPARATOR); + if (separatorIndex <= 0) + return; + const key = decodeURIComponent(keyPairPart.substring(0, separatorIndex).trim()); + const value = decodeURIComponent(keyPairPart.substring(separatorIndex + 1).trim()); + let metadata; + if (valueProps.length > 0) { + metadata = (0, api_1.baggageEntryMetadataFromString)(valueProps.join(constants_1.BAGGAGE_PROPERTIES_SEPARATOR)); + } + return { key, value, metadata }; +} +exports.parsePairKeyValue = parsePairKeyValue; +/** + * Parse a string serialized in the baggage HTTP Format (without metadata): + * https://github.com/w3c/baggage/blob/master/baggage/HTTP_HEADER_FORMAT.md + */ +function parseKeyPairsIntoRecord(value) { + const result = {}; + if (typeof value === 'string' && value.length > 0) { + value.split(constants_1.BAGGAGE_ITEMS_SEPARATOR).forEach(entry => { + const keyPair = parsePairKeyValue(entry); + if (keyPair !== undefined && keyPair.value.length > 0) { + result[keyPair.key] = keyPair.value; + } + }); + } + return result; +} +exports.parseKeyPairsIntoRecord = parseKeyPairsIntoRecord; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/common/anchored-clock.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/common/anchored-clock.js new file mode 100644 index 00000000..e4ae16cd --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/core/build/src/common/anchored-clock.js @@ -0,0 +1,61 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AnchoredClock = void 0; +/** + * A utility for returning wall times anchored to a given point in time. Wall time measurements will + * not be taken from the system, but instead are computed by adding a monotonic clock time + * to the anchor point. + * + * This is needed because the system time can change and result in unexpected situations like + * spans ending before they are started. Creating an anchored clock for each local root span + * ensures that span timings and durations are accurate while preventing span times from drifting + * too far from the system clock. + * + * Only creating an anchored clock once per local trace ensures span times are correct relative + * to each other. For example, a child span will never have a start time before its parent even + * if the system clock is corrected during the local trace. + * + * Heavily inspired by the OTel Java anchored clock + * https://github.com/open-telemetry/opentelemetry-java/blob/main/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/AnchoredClock.java + */ +class AnchoredClock { + _monotonicClock; + _epochMillis; + _performanceMillis; + /** + * Create a new AnchoredClock anchored to the current time returned by systemClock. + * + * @param systemClock should be a clock that returns the number of milliseconds since January 1 1970 such as Date + * @param monotonicClock should be a clock that counts milliseconds monotonically such as window.performance or perf_hooks.performance + */ + constructor(systemClock, monotonicClock) { + this._monotonicClock = monotonicClock; + this._epochMillis = systemClock.now(); + this._performanceMillis = monotonicClock.now(); + } + /** + * Returns the current time by adding the number of milliseconds since the + * AnchoredClock was created to the creation epoch time + */ + now() { + const delta = this._monotonicClock.now() - this._performanceMillis; + return this._epochMillis + delta; + } +} +exports.AnchoredClock = AnchoredClock; +//# sourceMappingURL=anchored-clock.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/common/attributes.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/common/attributes.js new file mode 100644 index 00000000..8f7bbfff --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/core/build/src/common/attributes.js @@ -0,0 +1,93 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isAttributeValue = exports.isAttributeKey = exports.sanitizeAttributes = void 0; +const api_1 = require("@opentelemetry/api"); +function sanitizeAttributes(attributes) { + const out = {}; + if (typeof attributes !== 'object' || attributes == null) { + return out; + } + for (const key in attributes) { + if (!Object.prototype.hasOwnProperty.call(attributes, key)) { + continue; + } + if (!isAttributeKey(key)) { + api_1.diag.warn(`Invalid attribute key: ${key}`); + continue; + } + const val = attributes[key]; + if (!isAttributeValue(val)) { + api_1.diag.warn(`Invalid attribute value set for key: ${key}`); + continue; + } + if (Array.isArray(val)) { + out[key] = val.slice(); + } + else { + out[key] = val; + } + } + return out; +} +exports.sanitizeAttributes = sanitizeAttributes; +function isAttributeKey(key) { + return typeof key === 'string' && key !== ''; +} +exports.isAttributeKey = isAttributeKey; +function isAttributeValue(val) { + if (val == null) { + return true; + } + if (Array.isArray(val)) { + return isHomogeneousAttributeValueArray(val); + } + return isValidPrimitiveAttributeValueType(typeof val); +} +exports.isAttributeValue = isAttributeValue; +function isHomogeneousAttributeValueArray(arr) { + let type; + for (const element of arr) { + // null/undefined elements are allowed + if (element == null) + continue; + const elementType = typeof element; + if (elementType === type) { + continue; + } + if (!type) { + if (isValidPrimitiveAttributeValueType(elementType)) { + type = elementType; + continue; + } + // encountered an invalid primitive + return false; + } + return false; + } + return true; +} +function isValidPrimitiveAttributeValueType(valType) { + switch (valType) { + case 'number': + case 'boolean': + case 'string': + return true; + } + return false; +} +//# sourceMappingURL=attributes.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/common/global-error-handler.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/common/global-error-handler.js new file mode 100644 index 00000000..a5d9b765 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/core/build/src/common/global-error-handler.js @@ -0,0 +1,41 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.globalErrorHandler = exports.setGlobalErrorHandler = void 0; +const logging_error_handler_1 = require("./logging-error-handler"); +/** The global error handler delegate */ +let delegateHandler = (0, logging_error_handler_1.loggingErrorHandler)(); +/** + * Set the global error handler + * @param {ErrorHandler} handler + */ +function setGlobalErrorHandler(handler) { + delegateHandler = handler; +} +exports.setGlobalErrorHandler = setGlobalErrorHandler; +/** + * Return the global error handler + * @param {Exception} ex + */ +function globalErrorHandler(ex) { + try { + delegateHandler(ex); + } + catch { } // eslint-disable-line no-empty +} +exports.globalErrorHandler = globalErrorHandler; +//# sourceMappingURL=global-error-handler.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/common/logging-error-handler.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/common/logging-error-handler.js new file mode 100644 index 00000000..e1ea6e02 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/core/build/src/common/logging-error-handler.js @@ -0,0 +1,63 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.loggingErrorHandler = void 0; +const api_1 = require("@opentelemetry/api"); +/** + * Returns a function that logs an error using the provided logger, or a + * console logger if one was not provided. + */ +function loggingErrorHandler() { + return (ex) => { + api_1.diag.error(stringifyException(ex)); + }; +} +exports.loggingErrorHandler = loggingErrorHandler; +/** + * Converts an exception into a string representation + * @param {Exception} ex + */ +function stringifyException(ex) { + if (typeof ex === 'string') { + return ex; + } + else { + return JSON.stringify(flattenException(ex)); + } +} +/** + * Flattens an exception into key-value pairs by traversing the prototype chain + * and coercing values to strings. Duplicate properties will not be overwritten; + * the first insert wins. + */ +function flattenException(ex) { + const result = {}; + let current = ex; + while (current !== null) { + Object.getOwnPropertyNames(current).forEach(propertyName => { + if (result[propertyName]) + return; + const value = current[propertyName]; + if (value) { + result[propertyName] = String(value); + } + }); + current = Object.getPrototypeOf(current); + } + return result; +} +//# sourceMappingURL=logging-error-handler.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/common/time.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/common/time.js new file mode 100644 index 00000000..0dfd7502 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/core/build/src/common/time.js @@ -0,0 +1,171 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.addHrTimes = exports.isTimeInput = exports.isTimeInputHrTime = exports.hrTimeToMicroseconds = exports.hrTimeToMilliseconds = exports.hrTimeToNanoseconds = exports.hrTimeToTimeStamp = exports.hrTimeDuration = exports.timeInputToHrTime = exports.hrTime = exports.getTimeOrigin = exports.millisToHrTime = void 0; +const platform_1 = require("../platform"); +const NANOSECOND_DIGITS = 9; +const NANOSECOND_DIGITS_IN_MILLIS = 6; +const MILLISECONDS_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS_IN_MILLIS); +const SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS); +/** + * Converts a number of milliseconds from epoch to HrTime([seconds, remainder in nanoseconds]). + * @param epochMillis + */ +function millisToHrTime(epochMillis) { + const epochSeconds = epochMillis / 1000; + // Decimals only. + const seconds = Math.trunc(epochSeconds); + // Round sub-nanosecond accuracy to nanosecond. + const nanos = Math.round((epochMillis % 1000) * MILLISECONDS_TO_NANOSECONDS); + return [seconds, nanos]; +} +exports.millisToHrTime = millisToHrTime; +function getTimeOrigin() { + let timeOrigin = platform_1.otperformance.timeOrigin; + if (typeof timeOrigin !== 'number') { + const perf = platform_1.otperformance; + timeOrigin = perf.timing && perf.timing.fetchStart; + } + return timeOrigin; +} +exports.getTimeOrigin = getTimeOrigin; +/** + * Returns an hrtime calculated via performance component. + * @param performanceNow + */ +function hrTime(performanceNow) { + const timeOrigin = millisToHrTime(getTimeOrigin()); + const now = millisToHrTime(typeof performanceNow === 'number' ? performanceNow : platform_1.otperformance.now()); + return addHrTimes(timeOrigin, now); +} +exports.hrTime = hrTime; +/** + * + * Converts a TimeInput to an HrTime, defaults to _hrtime(). + * @param time + */ +function timeInputToHrTime(time) { + // process.hrtime + if (isTimeInputHrTime(time)) { + return time; + } + else if (typeof time === 'number') { + // Must be a performance.now() if it's smaller than process start time. + if (time < getTimeOrigin()) { + return hrTime(time); + } + else { + // epoch milliseconds or performance.timeOrigin + return millisToHrTime(time); + } + } + else if (time instanceof Date) { + return millisToHrTime(time.getTime()); + } + else { + throw TypeError('Invalid input type'); + } +} +exports.timeInputToHrTime = timeInputToHrTime; +/** + * Returns a duration of two hrTime. + * @param startTime + * @param endTime + */ +function hrTimeDuration(startTime, endTime) { + let seconds = endTime[0] - startTime[0]; + let nanos = endTime[1] - startTime[1]; + // overflow + if (nanos < 0) { + seconds -= 1; + // negate + nanos += SECOND_TO_NANOSECONDS; + } + return [seconds, nanos]; +} +exports.hrTimeDuration = hrTimeDuration; +/** + * Convert hrTime to timestamp, for example "2019-05-14T17:00:00.000123456Z" + * @param time + */ +function hrTimeToTimeStamp(time) { + const precision = NANOSECOND_DIGITS; + const tmp = `${'0'.repeat(precision)}${time[1]}Z`; + const nanoString = tmp.substring(tmp.length - precision - 1); + const date = new Date(time[0] * 1000).toISOString(); + return date.replace('000Z', nanoString); +} +exports.hrTimeToTimeStamp = hrTimeToTimeStamp; +/** + * Convert hrTime to nanoseconds. + * @param time + */ +function hrTimeToNanoseconds(time) { + return time[0] * SECOND_TO_NANOSECONDS + time[1]; +} +exports.hrTimeToNanoseconds = hrTimeToNanoseconds; +/** + * Convert hrTime to milliseconds. + * @param time + */ +function hrTimeToMilliseconds(time) { + return time[0] * 1e3 + time[1] / 1e6; +} +exports.hrTimeToMilliseconds = hrTimeToMilliseconds; +/** + * Convert hrTime to microseconds. + * @param time + */ +function hrTimeToMicroseconds(time) { + return time[0] * 1e6 + time[1] / 1e3; +} +exports.hrTimeToMicroseconds = hrTimeToMicroseconds; +/** + * check if time is HrTime + * @param value + */ +function isTimeInputHrTime(value) { + return (Array.isArray(value) && + value.length === 2 && + typeof value[0] === 'number' && + typeof value[1] === 'number'); +} +exports.isTimeInputHrTime = isTimeInputHrTime; +/** + * check if input value is a correct types.TimeInput + * @param value + */ +function isTimeInput(value) { + return (isTimeInputHrTime(value) || + typeof value === 'number' || + value instanceof Date); +} +exports.isTimeInput = isTimeInput; +/** + * Given 2 HrTime formatted times, return their sum as an HrTime. + */ +function addHrTimes(time1, time2) { + const out = [time1[0] + time2[0], time1[1] + time2[1]]; + // Nanoseconds + if (out[1] >= SECOND_TO_NANOSECONDS) { + out[1] -= SECOND_TO_NANOSECONDS; + out[0] += 1; + } + return out; +} +exports.addHrTimes = addHrTimes; +//# sourceMappingURL=time.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/common/timer-util.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/common/timer-util.js new file mode 100644 index 00000000..76043b63 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/core/build/src/common/timer-util.js @@ -0,0 +1,29 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.unrefTimer = void 0; +/** + * @deprecated please copy this code to your implementation instead, this function will be removed in the next major version of this package. + * @param timer + */ +function unrefTimer(timer) { + if (typeof timer !== 'number') { + timer.unref(); + } +} +exports.unrefTimer = unrefTimer; +//# sourceMappingURL=timer-util.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/index.js new file mode 100644 index 00000000..acba8c7a --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/core/build/src/index.js @@ -0,0 +1,92 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.internal = exports.diagLogLevelFromString = exports.BindOnceFuture = exports.urlMatches = exports.isUrlIgnored = exports.callWithTimeout = exports.TimeoutError = exports.merge = exports.TraceState = exports.unsuppressTracing = exports.suppressTracing = exports.isTracingSuppressed = exports.setRPCMetadata = exports.getRPCMetadata = exports.deleteRPCMetadata = exports.RPCType = exports.parseTraceParent = exports.W3CTraceContextPropagator = exports.TRACE_STATE_HEADER = exports.TRACE_PARENT_HEADER = exports.CompositePropagator = exports.otperformance = exports.getStringListFromEnv = exports.getNumberFromEnv = exports.getBooleanFromEnv = exports.getStringFromEnv = exports._globalThis = exports.SDK_INFO = exports.parseKeyPairsIntoRecord = exports.ExportResultCode = exports.unrefTimer = exports.timeInputToHrTime = exports.millisToHrTime = exports.isTimeInputHrTime = exports.isTimeInput = exports.hrTimeToTimeStamp = exports.hrTimeToNanoseconds = exports.hrTimeToMilliseconds = exports.hrTimeToMicroseconds = exports.hrTimeDuration = exports.hrTime = exports.getTimeOrigin = exports.addHrTimes = exports.loggingErrorHandler = exports.setGlobalErrorHandler = exports.globalErrorHandler = exports.sanitizeAttributes = exports.isAttributeValue = exports.AnchoredClock = exports.W3CBaggagePropagator = void 0; +var W3CBaggagePropagator_1 = require("./baggage/propagation/W3CBaggagePropagator"); +Object.defineProperty(exports, "W3CBaggagePropagator", { enumerable: true, get: function () { return W3CBaggagePropagator_1.W3CBaggagePropagator; } }); +var anchored_clock_1 = require("./common/anchored-clock"); +Object.defineProperty(exports, "AnchoredClock", { enumerable: true, get: function () { return anchored_clock_1.AnchoredClock; } }); +var attributes_1 = require("./common/attributes"); +Object.defineProperty(exports, "isAttributeValue", { enumerable: true, get: function () { return attributes_1.isAttributeValue; } }); +Object.defineProperty(exports, "sanitizeAttributes", { enumerable: true, get: function () { return attributes_1.sanitizeAttributes; } }); +var global_error_handler_1 = require("./common/global-error-handler"); +Object.defineProperty(exports, "globalErrorHandler", { enumerable: true, get: function () { return global_error_handler_1.globalErrorHandler; } }); +Object.defineProperty(exports, "setGlobalErrorHandler", { enumerable: true, get: function () { return global_error_handler_1.setGlobalErrorHandler; } }); +var logging_error_handler_1 = require("./common/logging-error-handler"); +Object.defineProperty(exports, "loggingErrorHandler", { enumerable: true, get: function () { return logging_error_handler_1.loggingErrorHandler; } }); +var time_1 = require("./common/time"); +Object.defineProperty(exports, "addHrTimes", { enumerable: true, get: function () { return time_1.addHrTimes; } }); +Object.defineProperty(exports, "getTimeOrigin", { enumerable: true, get: function () { return time_1.getTimeOrigin; } }); +Object.defineProperty(exports, "hrTime", { enumerable: true, get: function () { return time_1.hrTime; } }); +Object.defineProperty(exports, "hrTimeDuration", { enumerable: true, get: function () { return time_1.hrTimeDuration; } }); +Object.defineProperty(exports, "hrTimeToMicroseconds", { enumerable: true, get: function () { return time_1.hrTimeToMicroseconds; } }); +Object.defineProperty(exports, "hrTimeToMilliseconds", { enumerable: true, get: function () { return time_1.hrTimeToMilliseconds; } }); +Object.defineProperty(exports, "hrTimeToNanoseconds", { enumerable: true, get: function () { return time_1.hrTimeToNanoseconds; } }); +Object.defineProperty(exports, "hrTimeToTimeStamp", { enumerable: true, get: function () { return time_1.hrTimeToTimeStamp; } }); +Object.defineProperty(exports, "isTimeInput", { enumerable: true, get: function () { return time_1.isTimeInput; } }); +Object.defineProperty(exports, "isTimeInputHrTime", { enumerable: true, get: function () { return time_1.isTimeInputHrTime; } }); +Object.defineProperty(exports, "millisToHrTime", { enumerable: true, get: function () { return time_1.millisToHrTime; } }); +Object.defineProperty(exports, "timeInputToHrTime", { enumerable: true, get: function () { return time_1.timeInputToHrTime; } }); +var timer_util_1 = require("./common/timer-util"); +Object.defineProperty(exports, "unrefTimer", { enumerable: true, get: function () { return timer_util_1.unrefTimer; } }); +var ExportResult_1 = require("./ExportResult"); +Object.defineProperty(exports, "ExportResultCode", { enumerable: true, get: function () { return ExportResult_1.ExportResultCode; } }); +var utils_1 = require("./baggage/utils"); +Object.defineProperty(exports, "parseKeyPairsIntoRecord", { enumerable: true, get: function () { return utils_1.parseKeyPairsIntoRecord; } }); +var platform_1 = require("./platform"); +Object.defineProperty(exports, "SDK_INFO", { enumerable: true, get: function () { return platform_1.SDK_INFO; } }); +Object.defineProperty(exports, "_globalThis", { enumerable: true, get: function () { return platform_1._globalThis; } }); +Object.defineProperty(exports, "getStringFromEnv", { enumerable: true, get: function () { return platform_1.getStringFromEnv; } }); +Object.defineProperty(exports, "getBooleanFromEnv", { enumerable: true, get: function () { return platform_1.getBooleanFromEnv; } }); +Object.defineProperty(exports, "getNumberFromEnv", { enumerable: true, get: function () { return platform_1.getNumberFromEnv; } }); +Object.defineProperty(exports, "getStringListFromEnv", { enumerable: true, get: function () { return platform_1.getStringListFromEnv; } }); +Object.defineProperty(exports, "otperformance", { enumerable: true, get: function () { return platform_1.otperformance; } }); +var composite_1 = require("./propagation/composite"); +Object.defineProperty(exports, "CompositePropagator", { enumerable: true, get: function () { return composite_1.CompositePropagator; } }); +var W3CTraceContextPropagator_1 = require("./trace/W3CTraceContextPropagator"); +Object.defineProperty(exports, "TRACE_PARENT_HEADER", { enumerable: true, get: function () { return W3CTraceContextPropagator_1.TRACE_PARENT_HEADER; } }); +Object.defineProperty(exports, "TRACE_STATE_HEADER", { enumerable: true, get: function () { return W3CTraceContextPropagator_1.TRACE_STATE_HEADER; } }); +Object.defineProperty(exports, "W3CTraceContextPropagator", { enumerable: true, get: function () { return W3CTraceContextPropagator_1.W3CTraceContextPropagator; } }); +Object.defineProperty(exports, "parseTraceParent", { enumerable: true, get: function () { return W3CTraceContextPropagator_1.parseTraceParent; } }); +var rpc_metadata_1 = require("./trace/rpc-metadata"); +Object.defineProperty(exports, "RPCType", { enumerable: true, get: function () { return rpc_metadata_1.RPCType; } }); +Object.defineProperty(exports, "deleteRPCMetadata", { enumerable: true, get: function () { return rpc_metadata_1.deleteRPCMetadata; } }); +Object.defineProperty(exports, "getRPCMetadata", { enumerable: true, get: function () { return rpc_metadata_1.getRPCMetadata; } }); +Object.defineProperty(exports, "setRPCMetadata", { enumerable: true, get: function () { return rpc_metadata_1.setRPCMetadata; } }); +var suppress_tracing_1 = require("./trace/suppress-tracing"); +Object.defineProperty(exports, "isTracingSuppressed", { enumerable: true, get: function () { return suppress_tracing_1.isTracingSuppressed; } }); +Object.defineProperty(exports, "suppressTracing", { enumerable: true, get: function () { return suppress_tracing_1.suppressTracing; } }); +Object.defineProperty(exports, "unsuppressTracing", { enumerable: true, get: function () { return suppress_tracing_1.unsuppressTracing; } }); +var TraceState_1 = require("./trace/TraceState"); +Object.defineProperty(exports, "TraceState", { enumerable: true, get: function () { return TraceState_1.TraceState; } }); +var merge_1 = require("./utils/merge"); +Object.defineProperty(exports, "merge", { enumerable: true, get: function () { return merge_1.merge; } }); +var timeout_1 = require("./utils/timeout"); +Object.defineProperty(exports, "TimeoutError", { enumerable: true, get: function () { return timeout_1.TimeoutError; } }); +Object.defineProperty(exports, "callWithTimeout", { enumerable: true, get: function () { return timeout_1.callWithTimeout; } }); +var url_1 = require("./utils/url"); +Object.defineProperty(exports, "isUrlIgnored", { enumerable: true, get: function () { return url_1.isUrlIgnored; } }); +Object.defineProperty(exports, "urlMatches", { enumerable: true, get: function () { return url_1.urlMatches; } }); +var callback_1 = require("./utils/callback"); +Object.defineProperty(exports, "BindOnceFuture", { enumerable: true, get: function () { return callback_1.BindOnceFuture; } }); +var configuration_1 = require("./utils/configuration"); +Object.defineProperty(exports, "diagLogLevelFromString", { enumerable: true, get: function () { return configuration_1.diagLogLevelFromString; } }); +const exporter_1 = require("./internal/exporter"); +exports.internal = { + _export: exporter_1._export, +}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/internal/exporter.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/internal/exporter.js new file mode 100644 index 00000000..c5c35110 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/core/build/src/internal/exporter.js @@ -0,0 +1,36 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports._export = void 0; +const api_1 = require("@opentelemetry/api"); +const suppress_tracing_1 = require("../trace/suppress-tracing"); +/** + * @internal + * Shared functionality used by Exporters while exporting data, including suppression of Traces. + */ +function _export(exporter, arg) { + return new Promise(resolve => { + // prevent downstream exporter calls from generating spans + api_1.context.with((0, suppress_tracing_1.suppressTracing)(api_1.context.active()), () => { + exporter.export(arg, (result) => { + resolve(result); + }); + }); + }); +} +exports._export = _export; +//# sourceMappingURL=exporter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/internal/validators.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/internal/validators.js new file mode 100644 index 00000000..820522ca --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/core/build/src/internal/validators.js @@ -0,0 +1,46 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateValue = exports.validateKey = void 0; +const VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]'; +const VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`; +const VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`; +const VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`); +const VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/; +const INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/; +/** + * Key is opaque string up to 256 characters printable. It MUST begin with a + * lowercase letter, and can only contain lowercase letters a-z, digits 0-9, + * underscores _, dashes -, asterisks *, and forward slashes /. + * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the + * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key. + * see https://www.w3.org/TR/trace-context/#key + */ +function validateKey(key) { + return VALID_KEY_REGEX.test(key); +} +exports.validateKey = validateKey; +/** + * Value is opaque string up to 256 characters printable ASCII RFC0020 + * characters (i.e., the range 0x20 to 0x7E) except comma , and =. + */ +function validateValue(value) { + return (VALID_VALUE_BASE_REGEX.test(value) && + !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value)); +} +exports.validateValue = validateValue; +//# sourceMappingURL=validators.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/index.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/index.js new file mode 100644 index 00000000..5e83a058 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/index.js @@ -0,0 +1,27 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getStringListFromEnv = exports.getNumberFromEnv = exports.getStringFromEnv = exports.getBooleanFromEnv = exports.otperformance = exports._globalThis = exports.SDK_INFO = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var node_1 = require("./node"); +Object.defineProperty(exports, "SDK_INFO", { enumerable: true, get: function () { return node_1.SDK_INFO; } }); +Object.defineProperty(exports, "_globalThis", { enumerable: true, get: function () { return node_1._globalThis; } }); +Object.defineProperty(exports, "otperformance", { enumerable: true, get: function () { return node_1.otperformance; } }); +Object.defineProperty(exports, "getBooleanFromEnv", { enumerable: true, get: function () { return node_1.getBooleanFromEnv; } }); +Object.defineProperty(exports, "getStringFromEnv", { enumerable: true, get: function () { return node_1.getStringFromEnv; } }); +Object.defineProperty(exports, "getNumberFromEnv", { enumerable: true, get: function () { return node_1.getNumberFromEnv; } }); +Object.defineProperty(exports, "getStringListFromEnv", { enumerable: true, get: function () { return node_1.getStringListFromEnv; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/environment.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/environment.js new file mode 100644 index 00000000..d0268b37 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/environment.js @@ -0,0 +1,104 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getStringListFromEnv = exports.getBooleanFromEnv = exports.getStringFromEnv = exports.getNumberFromEnv = void 0; +const api_1 = require("@opentelemetry/api"); +const util_1 = require("util"); +/** + * Retrieves a number from an environment variable. + * - Returns `undefined` if the environment variable is empty, unset, contains only whitespace, or is not a number. + * - Returns a number in all other cases. + * + * @param {string} key - The name of the environment variable to retrieve. + * @returns {number | undefined} - The number value or `undefined`. + */ +function getNumberFromEnv(key) { + const raw = process.env[key]; + if (raw == null || raw.trim() === '') { + return undefined; + } + const value = Number(raw); + if (isNaN(value)) { + api_1.diag.warn(`Unknown value ${(0, util_1.inspect)(raw)} for ${key}, expected a number, using defaults`); + return undefined; + } + return value; +} +exports.getNumberFromEnv = getNumberFromEnv; +/** + * Retrieves a string from an environment variable. + * - Returns `undefined` if the environment variable is empty, unset, or contains only whitespace. + * + * @param {string} key - The name of the environment variable to retrieve. + * @returns {string | undefined} - The string value or `undefined`. + */ +function getStringFromEnv(key) { + const raw = process.env[key]; + if (raw == null || raw.trim() === '') { + return undefined; + } + return raw; +} +exports.getStringFromEnv = getStringFromEnv; +/** + * Retrieves a boolean value from an environment variable. + * - Trims leading and trailing whitespace and ignores casing. + * - Returns `false` if the environment variable is empty, unset, or contains only whitespace. + * - Returns `false` for strings that cannot be mapped to a boolean. + * + * @param {string} key - The name of the environment variable to retrieve. + * @returns {boolean} - The boolean value or `false` if the environment variable is unset empty, unset, or contains only whitespace. + */ +function getBooleanFromEnv(key) { + const raw = process.env[key]?.trim().toLowerCase(); + if (raw == null || raw === '') { + // NOTE: falling back to `false` instead of `undefined` as required by the specification. + // If you have a use-case that requires `undefined`, consider using `getStringFromEnv()` and applying the necessary + // normalizations in the consuming code. + return false; + } + if (raw === 'true') { + return true; + } + else if (raw === 'false') { + return false; + } + else { + api_1.diag.warn(`Unknown value ${(0, util_1.inspect)(raw)} for ${key}, expected 'true' or 'false', falling back to 'false' (default)`); + return false; + } +} +exports.getBooleanFromEnv = getBooleanFromEnv; +/** + * Retrieves a list of strings from an environment variable. + * - Uses ',' as the delimiter. + * - Trims leading and trailing whitespace from each entry. + * - Excludes empty entries. + * - Returns `undefined` if the environment variable is empty or contains only whitespace. + * - Returns an empty array if all entries are empty or whitespace. + * + * @param {string} key - The name of the environment variable to retrieve. + * @returns {string[] | undefined} - The list of strings or `undefined`. + */ +function getStringListFromEnv(key) { + return getStringFromEnv(key) + ?.split(',') + .map(v => v.trim()) + .filter(s => s !== ''); +} +exports.getStringListFromEnv = getStringListFromEnv; +//# sourceMappingURL=environment.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/globalThis.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/globalThis.js new file mode 100644 index 00000000..9ae59140 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/globalThis.js @@ -0,0 +1,22 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports._globalThis = void 0; +/** only globals that common to node and browsers are allowed */ +// eslint-disable-next-line n/no-unsupported-features/es-builtins +exports._globalThis = typeof globalThis === 'object' ? globalThis : global; +//# sourceMappingURL=globalThis.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/index.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/index.js new file mode 100644 index 00000000..6934fac6 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/index.js @@ -0,0 +1,30 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SDK_INFO = exports.otperformance = exports._globalThis = exports.getStringListFromEnv = exports.getNumberFromEnv = exports.getBooleanFromEnv = exports.getStringFromEnv = void 0; +var environment_1 = require("./environment"); +Object.defineProperty(exports, "getStringFromEnv", { enumerable: true, get: function () { return environment_1.getStringFromEnv; } }); +Object.defineProperty(exports, "getBooleanFromEnv", { enumerable: true, get: function () { return environment_1.getBooleanFromEnv; } }); +Object.defineProperty(exports, "getNumberFromEnv", { enumerable: true, get: function () { return environment_1.getNumberFromEnv; } }); +Object.defineProperty(exports, "getStringListFromEnv", { enumerable: true, get: function () { return environment_1.getStringListFromEnv; } }); +var globalThis_1 = require("./globalThis"); +Object.defineProperty(exports, "_globalThis", { enumerable: true, get: function () { return globalThis_1._globalThis; } }); +var performance_1 = require("./performance"); +Object.defineProperty(exports, "otperformance", { enumerable: true, get: function () { return performance_1.otperformance; } }); +var sdk_info_1 = require("./sdk-info"); +Object.defineProperty(exports, "SDK_INFO", { enumerable: true, get: function () { return sdk_info_1.SDK_INFO; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/performance.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/performance.js new file mode 100644 index 00000000..ade758b8 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/performance.js @@ -0,0 +1,21 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.otperformance = void 0; +const perf_hooks_1 = require("perf_hooks"); +exports.otperformance = perf_hooks_1.performance; +//# sourceMappingURL=performance.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/sdk-info.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/sdk-info.js new file mode 100644 index 00000000..357c2663 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/sdk-info.js @@ -0,0 +1,29 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SDK_INFO = void 0; +const version_1 = require("../../version"); +const semantic_conventions_1 = require("@opentelemetry/semantic-conventions"); +const semconv_1 = require("../../semconv"); +/** Constants describing the SDK in use */ +exports.SDK_INFO = { + [semantic_conventions_1.ATTR_TELEMETRY_SDK_NAME]: 'opentelemetry', + [semconv_1.ATTR_PROCESS_RUNTIME_NAME]: 'node', + [semantic_conventions_1.ATTR_TELEMETRY_SDK_LANGUAGE]: semantic_conventions_1.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS, + [semantic_conventions_1.ATTR_TELEMETRY_SDK_VERSION]: version_1.VERSION, +}; +//# sourceMappingURL=sdk-info.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/propagation/composite.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/propagation/composite.js new file mode 100644 index 00000000..c45d7775 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/core/build/src/propagation/composite.js @@ -0,0 +1,81 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CompositePropagator = void 0; +const api_1 = require("@opentelemetry/api"); +/** Combines multiple propagators into a single propagator. */ +class CompositePropagator { + _propagators; + _fields; + /** + * Construct a composite propagator from a list of propagators. + * + * @param [config] Configuration object for composite propagator + */ + constructor(config = {}) { + this._propagators = config.propagators ?? []; + this._fields = Array.from(new Set(this._propagators + // older propagators may not have fields function, null check to be sure + .map(p => (typeof p.fields === 'function' ? p.fields() : [])) + .reduce((x, y) => x.concat(y), []))); + } + /** + * Run each of the configured propagators with the given context and carrier. + * Propagators are run in the order they are configured, so if multiple + * propagators write the same carrier key, the propagator later in the list + * will "win". + * + * @param context Context to inject + * @param carrier Carrier into which context will be injected + */ + inject(context, carrier, setter) { + for (const propagator of this._propagators) { + try { + propagator.inject(context, carrier, setter); + } + catch (err) { + api_1.diag.warn(`Failed to inject with ${propagator.constructor.name}. Err: ${err.message}`); + } + } + } + /** + * Run each of the configured propagators with the given context and carrier. + * Propagators are run in the order they are configured, so if multiple + * propagators write the same context key, the propagator later in the list + * will "win". + * + * @param context Context to add values to + * @param carrier Carrier from which to extract context + */ + extract(context, carrier, getter) { + return this._propagators.reduce((ctx, propagator) => { + try { + return propagator.extract(ctx, carrier, getter); + } + catch (err) { + api_1.diag.warn(`Failed to extract with ${propagator.constructor.name}. Err: ${err.message}`); + } + return ctx; + }, context); + } + fields() { + // return a new array so our fields cannot be modified + return this._fields.slice(); + } +} +exports.CompositePropagator = CompositePropagator; +//# sourceMappingURL=composite.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/semconv.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/semconv.js new file mode 100644 index 00000000..2cd8ceaf --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/core/build/src/semconv.js @@ -0,0 +1,32 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ATTR_PROCESS_RUNTIME_NAME = void 0; +/* + * This file contains a copy of unstable semantic convention definitions + * used by this package. + * @see https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions#unstable-semconv + */ +/** + * The name of the runtime of this process. + * + * @example OpenJDK Runtime Environment + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_PROCESS_RUNTIME_NAME = 'process.runtime.name'; +//# sourceMappingURL=semconv.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/trace/TraceState.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/trace/TraceState.js new file mode 100644 index 00000000..6fdfa5e8 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/core/build/src/trace/TraceState.js @@ -0,0 +1,103 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TraceState = void 0; +const validators_1 = require("../internal/validators"); +const MAX_TRACE_STATE_ITEMS = 32; +const MAX_TRACE_STATE_LEN = 512; +const LIST_MEMBERS_SEPARATOR = ','; +const LIST_MEMBER_KEY_VALUE_SPLITTER = '='; +/** + * TraceState must be a class and not a simple object type because of the spec + * requirement (https://www.w3.org/TR/trace-context/#tracestate-field). + * + * Here is the list of allowed mutations: + * - New key-value pair should be added into the beginning of the list + * - The value of any key can be updated. Modified keys MUST be moved to the + * beginning of the list. + */ +class TraceState { + _internalState = new Map(); + constructor(rawTraceState) { + if (rawTraceState) + this._parse(rawTraceState); + } + set(key, value) { + // TODO: Benchmark the different approaches(map vs list) and + // use the faster one. + const traceState = this._clone(); + if (traceState._internalState.has(key)) { + traceState._internalState.delete(key); + } + traceState._internalState.set(key, value); + return traceState; + } + unset(key) { + const traceState = this._clone(); + traceState._internalState.delete(key); + return traceState; + } + get(key) { + return this._internalState.get(key); + } + serialize() { + return this._keys() + .reduce((agg, key) => { + agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key)); + return agg; + }, []) + .join(LIST_MEMBERS_SEPARATOR); + } + _parse(rawTraceState) { + if (rawTraceState.length > MAX_TRACE_STATE_LEN) + return; + this._internalState = rawTraceState + .split(LIST_MEMBERS_SEPARATOR) + .reverse() // Store in reverse so new keys (.set(...)) will be placed at the beginning + .reduce((agg, part) => { + const listMember = part.trim(); // Optional Whitespace (OWS) handling + const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER); + if (i !== -1) { + const key = listMember.slice(0, i); + const value = listMember.slice(i + 1, part.length); + if ((0, validators_1.validateKey)(key) && (0, validators_1.validateValue)(value)) { + agg.set(key, value); + } + else { + // TODO: Consider to add warning log + } + } + return agg; + }, new Map()); + // Because of the reverse() requirement, trunc must be done after map is created + if (this._internalState.size > MAX_TRACE_STATE_ITEMS) { + this._internalState = new Map(Array.from(this._internalState.entries()) + .reverse() // Use reverse same as original tracestate parse chain + .slice(0, MAX_TRACE_STATE_ITEMS)); + } + } + _keys() { + return Array.from(this._internalState.keys()).reverse(); + } + _clone() { + const traceState = new TraceState(); + traceState._internalState = new Map(this._internalState); + return traceState; + } +} +exports.TraceState = TraceState; +//# sourceMappingURL=TraceState.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/trace/W3CTraceContextPropagator.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/trace/W3CTraceContextPropagator.js new file mode 100644 index 00000000..86832129 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/core/build/src/trace/W3CTraceContextPropagator.js @@ -0,0 +1,104 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.W3CTraceContextPropagator = exports.parseTraceParent = exports.TRACE_STATE_HEADER = exports.TRACE_PARENT_HEADER = void 0; +const api_1 = require("@opentelemetry/api"); +const suppress_tracing_1 = require("./suppress-tracing"); +const TraceState_1 = require("./TraceState"); +exports.TRACE_PARENT_HEADER = 'traceparent'; +exports.TRACE_STATE_HEADER = 'tracestate'; +const VERSION = '00'; +const VERSION_PART = '(?!ff)[\\da-f]{2}'; +const TRACE_ID_PART = '(?![0]{32})[\\da-f]{32}'; +const PARENT_ID_PART = '(?![0]{16})[\\da-f]{16}'; +const FLAGS_PART = '[\\da-f]{2}'; +const TRACE_PARENT_REGEX = new RegExp(`^\\s?(${VERSION_PART})-(${TRACE_ID_PART})-(${PARENT_ID_PART})-(${FLAGS_PART})(-.*)?\\s?$`); +/** + * Parses information from the [traceparent] span tag and converts it into {@link SpanContext} + * @param traceParent - A meta property that comes from server. + * It should be dynamically generated server side to have the server's request trace Id, + * a parent span Id that was set on the server's request span, + * and the trace flags to indicate the server's sampling decision + * (01 = sampled, 00 = not sampled). + * for example: '{version}-{traceId}-{spanId}-{sampleDecision}' + * For more information see {@link https://www.w3.org/TR/trace-context/} + */ +function parseTraceParent(traceParent) { + const match = TRACE_PARENT_REGEX.exec(traceParent); + if (!match) + return null; + // According to the specification the implementation should be compatible + // with future versions. If there are more parts, we only reject it if it's using version 00 + // See https://www.w3.org/TR/trace-context/#versioning-of-traceparent + if (match[1] === '00' && match[5]) + return null; + return { + traceId: match[2], + spanId: match[3], + traceFlags: parseInt(match[4], 16), + }; +} +exports.parseTraceParent = parseTraceParent; +/** + * Propagates {@link SpanContext} through Trace Context format propagation. + * + * Based on the Trace Context specification: + * https://www.w3.org/TR/trace-context/ + */ +class W3CTraceContextPropagator { + inject(context, carrier, setter) { + const spanContext = api_1.trace.getSpanContext(context); + if (!spanContext || + (0, suppress_tracing_1.isTracingSuppressed)(context) || + !(0, api_1.isSpanContextValid)(spanContext)) + return; + const traceParent = `${VERSION}-${spanContext.traceId}-${spanContext.spanId}-0${Number(spanContext.traceFlags || api_1.TraceFlags.NONE).toString(16)}`; + setter.set(carrier, exports.TRACE_PARENT_HEADER, traceParent); + if (spanContext.traceState) { + setter.set(carrier, exports.TRACE_STATE_HEADER, spanContext.traceState.serialize()); + } + } + extract(context, carrier, getter) { + const traceParentHeader = getter.get(carrier, exports.TRACE_PARENT_HEADER); + if (!traceParentHeader) + return context; + const traceParent = Array.isArray(traceParentHeader) + ? traceParentHeader[0] + : traceParentHeader; + if (typeof traceParent !== 'string') + return context; + const spanContext = parseTraceParent(traceParent); + if (!spanContext) + return context; + spanContext.isRemote = true; + const traceStateHeader = getter.get(carrier, exports.TRACE_STATE_HEADER); + if (traceStateHeader) { + // If more than one `tracestate` header is found, we merge them into a + // single header. + const state = Array.isArray(traceStateHeader) + ? traceStateHeader.join(',') + : traceStateHeader; + spanContext.traceState = new TraceState_1.TraceState(typeof state === 'string' ? state : undefined); + } + return api_1.trace.setSpanContext(context, spanContext); + } + fields() { + return [exports.TRACE_PARENT_HEADER, exports.TRACE_STATE_HEADER]; + } +} +exports.W3CTraceContextPropagator = W3CTraceContextPropagator; +//# sourceMappingURL=W3CTraceContextPropagator.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/trace/rpc-metadata.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/trace/rpc-metadata.js new file mode 100644 index 00000000..48de80cf --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/core/build/src/trace/rpc-metadata.js @@ -0,0 +1,37 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getRPCMetadata = exports.deleteRPCMetadata = exports.setRPCMetadata = exports.RPCType = void 0; +const api_1 = require("@opentelemetry/api"); +const RPC_METADATA_KEY = (0, api_1.createContextKey)('OpenTelemetry SDK Context Key RPC_METADATA'); +var RPCType; +(function (RPCType) { + RPCType["HTTP"] = "http"; +})(RPCType = exports.RPCType || (exports.RPCType = {})); +function setRPCMetadata(context, meta) { + return context.setValue(RPC_METADATA_KEY, meta); +} +exports.setRPCMetadata = setRPCMetadata; +function deleteRPCMetadata(context) { + return context.deleteValue(RPC_METADATA_KEY); +} +exports.deleteRPCMetadata = deleteRPCMetadata; +function getRPCMetadata(context) { + return context.getValue(RPC_METADATA_KEY); +} +exports.getRPCMetadata = getRPCMetadata; +//# sourceMappingURL=rpc-metadata.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/trace/suppress-tracing.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/trace/suppress-tracing.js new file mode 100644 index 00000000..be8931d3 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/core/build/src/trace/suppress-tracing.js @@ -0,0 +1,33 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isTracingSuppressed = exports.unsuppressTracing = exports.suppressTracing = void 0; +const api_1 = require("@opentelemetry/api"); +const SUPPRESS_TRACING_KEY = (0, api_1.createContextKey)('OpenTelemetry SDK Context Key SUPPRESS_TRACING'); +function suppressTracing(context) { + return context.setValue(SUPPRESS_TRACING_KEY, true); +} +exports.suppressTracing = suppressTracing; +function unsuppressTracing(context) { + return context.deleteValue(SUPPRESS_TRACING_KEY); +} +exports.unsuppressTracing = unsuppressTracing; +function isTracingSuppressed(context) { + return context.getValue(SUPPRESS_TRACING_KEY) === true; +} +exports.isTracingSuppressed = isTracingSuppressed; +//# sourceMappingURL=suppress-tracing.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/callback.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/callback.js new file mode 100644 index 00000000..82520d9c --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/callback.js @@ -0,0 +1,52 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BindOnceFuture = void 0; +const promise_1 = require("./promise"); +/** + * Bind the callback and only invoke the callback once regardless how many times `BindOnceFuture.call` is invoked. + */ +class BindOnceFuture { + _callback; + _that; + _isCalled = false; + _deferred = new promise_1.Deferred(); + constructor(_callback, _that) { + this._callback = _callback; + this._that = _that; + } + get isCalled() { + return this._isCalled; + } + get promise() { + return this._deferred.promise; + } + call(...args) { + if (!this._isCalled) { + this._isCalled = true; + try { + Promise.resolve(this._callback.call(this._that, ...args)).then(val => this._deferred.resolve(val), err => this._deferred.reject(err)); + } + catch (err) { + this._deferred.reject(err); + } + } + return this._deferred.promise; + } +} +exports.BindOnceFuture = BindOnceFuture; +//# sourceMappingURL=callback.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/configuration.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/configuration.js new file mode 100644 index 00000000..64ea67e3 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/configuration.js @@ -0,0 +1,46 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.diagLogLevelFromString = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const api_1 = require("@opentelemetry/api"); +const logLevelMap = { + ALL: api_1.DiagLogLevel.ALL, + VERBOSE: api_1.DiagLogLevel.VERBOSE, + DEBUG: api_1.DiagLogLevel.DEBUG, + INFO: api_1.DiagLogLevel.INFO, + WARN: api_1.DiagLogLevel.WARN, + ERROR: api_1.DiagLogLevel.ERROR, + NONE: api_1.DiagLogLevel.NONE, +}; +/** + * Convert a string to a {@link DiagLogLevel}, defaults to {@link DiagLogLevel} if the log level does not exist or undefined if the input is undefined. + * @param value + */ +function diagLogLevelFromString(value) { + if (value == null) { + // don't fall back to default - no value set has different semantics for ús than an incorrect value (do not set vs. fall back to default) + return undefined; + } + const resolvedLogLevel = logLevelMap[value.toUpperCase()]; + if (resolvedLogLevel == null) { + api_1.diag.warn(`Unknown log level "${value}", expected one of ${Object.keys(logLevelMap)}, using default`); + return api_1.DiagLogLevel.INFO; + } + return resolvedLogLevel; +} +exports.diagLogLevelFromString = diagLogLevelFromString; +//# sourceMappingURL=configuration.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/lodash.merge.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/lodash.merge.js new file mode 100644 index 00000000..9e531958 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/lodash.merge.js @@ -0,0 +1,157 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isPlainObject = void 0; +/* eslint-disable @typescript-eslint/no-explicit-any */ +/** + * based on lodash in order to support esm builds without esModuleInterop. + * lodash is using MIT License. + **/ +const objectTag = '[object Object]'; +const nullTag = '[object Null]'; +const undefinedTag = '[object Undefined]'; +const funcProto = Function.prototype; +const funcToString = funcProto.toString; +const objectCtorString = funcToString.call(Object); +const getPrototypeOf = Object.getPrototypeOf; +const objectProto = Object.prototype; +const hasOwnProperty = objectProto.hasOwnProperty; +const symToStringTag = Symbol ? Symbol.toStringTag : undefined; +const nativeObjectToString = objectProto.toString; +/** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ +function isPlainObject(value) { + if (!isObjectLike(value) || baseGetTag(value) !== objectTag) { + return false; + } + const proto = getPrototypeOf(value); + if (proto === null) { + return true; + } + const Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; + return (typeof Ctor == 'function' && + Ctor instanceof Ctor && + funcToString.call(Ctor) === objectCtorString); +} +exports.isPlainObject = isPlainObject; +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return value != null && typeof value == 'object'; +} +/** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ +function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return symToStringTag && symToStringTag in Object(value) + ? getRawTag(value) + : objectToString(value); +} +/** + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ +function getRawTag(value) { + const isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; + let unmasked = false; + try { + value[symToStringTag] = undefined; + unmasked = true; + } + catch { + // silence + } + const result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } + else { + delete value[symToStringTag]; + } + } + return result; +} +/** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ +function objectToString(value) { + return nativeObjectToString.call(value); +} +//# sourceMappingURL=lodash.merge.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/merge.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/merge.js new file mode 100644 index 00000000..d821c714 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/merge.js @@ -0,0 +1,162 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.merge = void 0; +/* eslint-disable @typescript-eslint/no-explicit-any */ +const lodash_merge_1 = require("./lodash.merge"); +const MAX_LEVEL = 20; +/** + * Merges objects together + * @param args - objects / values to be merged + */ +function merge(...args) { + let result = args.shift(); + const objects = new WeakMap(); + while (args.length > 0) { + result = mergeTwoObjects(result, args.shift(), 0, objects); + } + return result; +} +exports.merge = merge; +function takeValue(value) { + if (isArray(value)) { + return value.slice(); + } + return value; +} +/** + * Merges two objects + * @param one - first object + * @param two - second object + * @param level - current deep level + * @param objects - objects holder that has been already referenced - to prevent + * cyclic dependency + */ +function mergeTwoObjects(one, two, level = 0, objects) { + let result; + if (level > MAX_LEVEL) { + return undefined; + } + level++; + if (isPrimitive(one) || isPrimitive(two) || isFunction(two)) { + result = takeValue(two); + } + else if (isArray(one)) { + result = one.slice(); + if (isArray(two)) { + for (let i = 0, j = two.length; i < j; i++) { + result.push(takeValue(two[i])); + } + } + else if (isObject(two)) { + const keys = Object.keys(two); + for (let i = 0, j = keys.length; i < j; i++) { + const key = keys[i]; + result[key] = takeValue(two[key]); + } + } + } + else if (isObject(one)) { + if (isObject(two)) { + if (!shouldMerge(one, two)) { + return two; + } + result = Object.assign({}, one); + const keys = Object.keys(two); + for (let i = 0, j = keys.length; i < j; i++) { + const key = keys[i]; + const twoValue = two[key]; + if (isPrimitive(twoValue)) { + if (typeof twoValue === 'undefined') { + delete result[key]; + } + else { + // result[key] = takeValue(twoValue); + result[key] = twoValue; + } + } + else { + const obj1 = result[key]; + const obj2 = twoValue; + if (wasObjectReferenced(one, key, objects) || + wasObjectReferenced(two, key, objects)) { + delete result[key]; + } + else { + if (isObject(obj1) && isObject(obj2)) { + const arr1 = objects.get(obj1) || []; + const arr2 = objects.get(obj2) || []; + arr1.push({ obj: one, key }); + arr2.push({ obj: two, key }); + objects.set(obj1, arr1); + objects.set(obj2, arr2); + } + result[key] = mergeTwoObjects(result[key], twoValue, level, objects); + } + } + } + } + else { + result = two; + } + } + return result; +} +/** + * Function to check if object has been already reference + * @param obj + * @param key + * @param objects + */ +function wasObjectReferenced(obj, key, objects) { + const arr = objects.get(obj[key]) || []; + for (let i = 0, j = arr.length; i < j; i++) { + const info = arr[i]; + if (info.key === key && info.obj === obj) { + return true; + } + } + return false; +} +function isArray(value) { + return Array.isArray(value); +} +function isFunction(value) { + return typeof value === 'function'; +} +function isObject(value) { + return (!isPrimitive(value) && + !isArray(value) && + !isFunction(value) && + typeof value === 'object'); +} +function isPrimitive(value) { + return (typeof value === 'string' || + typeof value === 'number' || + typeof value === 'boolean' || + typeof value === 'undefined' || + value instanceof Date || + value instanceof RegExp || + value === null); +} +function shouldMerge(one, two) { + if (!(0, lodash_merge_1.isPlainObject)(one) || !(0, lodash_merge_1.isPlainObject)(two)) { + return false; + } + return true; +} +//# sourceMappingURL=merge.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/promise.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/promise.js new file mode 100644 index 00000000..e564737a --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/promise.js @@ -0,0 +1,40 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Deferred = void 0; +class Deferred { + _promise; + _resolve; + _reject; + constructor() { + this._promise = new Promise((resolve, reject) => { + this._resolve = resolve; + this._reject = reject; + }); + } + get promise() { + return this._promise; + } + resolve(val) { + this._resolve(val); + } + reject(err) { + this._reject(err); + } +} +exports.Deferred = Deferred; +//# sourceMappingURL=promise.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/timeout.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/timeout.js new file mode 100644 index 00000000..fd45a561 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/timeout.js @@ -0,0 +1,56 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.callWithTimeout = exports.TimeoutError = void 0; +/** + * Error that is thrown on timeouts. + */ +class TimeoutError extends Error { + constructor(message) { + super(message); + // manually adjust prototype to retain `instanceof` functionality when targeting ES5, see: + // https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work + Object.setPrototypeOf(this, TimeoutError.prototype); + } +} +exports.TimeoutError = TimeoutError; +/** + * Adds a timeout to a promise and rejects if the specified timeout has elapsed. Also rejects if the specified promise + * rejects, and resolves if the specified promise resolves. + * + *

NOTE: this operation will continue even after it throws a {@link TimeoutError}. + * + * @param promise promise to use with timeout. + * @param timeout the timeout in milliseconds until the returned promise is rejected. + */ +function callWithTimeout(promise, timeout) { + let timeoutHandle; + const timeoutPromise = new Promise(function timeoutFunction(_resolve, reject) { + timeoutHandle = setTimeout(function timeoutHandler() { + reject(new TimeoutError('Operation timed out.')); + }, timeout); + }); + return Promise.race([promise, timeoutPromise]).then(result => { + clearTimeout(timeoutHandle); + return result; + }, reason => { + clearTimeout(timeoutHandle); + throw reason; + }); +} +exports.callWithTimeout = callWithTimeout; +//# sourceMappingURL=timeout.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/url.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/url.js new file mode 100644 index 00000000..7bce5b50 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/url.js @@ -0,0 +1,45 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isUrlIgnored = exports.urlMatches = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function urlMatches(url, urlToMatch) { + if (typeof urlToMatch === 'string') { + return url === urlToMatch; + } + else { + return !!url.match(urlToMatch); + } +} +exports.urlMatches = urlMatches; +/** + * Check if {@param url} should be ignored when comparing against {@param ignoredUrls} + * @param url + * @param ignoredUrls + */ +function isUrlIgnored(url, ignoredUrls) { + if (!ignoredUrls) { + return false; + } + for (const ignoreUrl of ignoredUrls) { + if (urlMatches(url, ignoreUrl)) { + return true; + } + } + return false; +} +exports.isUrlIgnored = isUrlIgnored; +//# sourceMappingURL=url.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/version.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/version.js new file mode 100644 index 00000000..deecc74a --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/core/build/src/version.js @@ -0,0 +1,21 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.VERSION = void 0; +// this is autogenerated file, see scripts/version-update.js +exports.VERSION = '2.2.0'; +//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-grpc/build/src/OTLPLogExporter.js b/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-grpc/build/src/OTLPLogExporter.js new file mode 100644 index 00000000..ee67c2dd --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-grpc/build/src/OTLPLogExporter.js @@ -0,0 +1,31 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OTLPLogExporter = void 0; +const otlp_grpc_exporter_base_1 = require("@opentelemetry/otlp-grpc-exporter-base"); +const otlp_transformer_1 = require("@opentelemetry/otlp-transformer"); +const otlp_exporter_base_1 = require("@opentelemetry/otlp-exporter-base"); +/** + * OTLP Logs Exporter for Node + */ +class OTLPLogExporter extends otlp_exporter_base_1.OTLPExporterBase { + constructor(config = {}) { + super((0, otlp_grpc_exporter_base_1.createOtlpGrpcExportDelegate)((0, otlp_grpc_exporter_base_1.convertLegacyOtlpGrpcOptions)(config, 'LOGS'), otlp_transformer_1.ProtobufLogsSerializer, 'LogsExportService', '/opentelemetry.proto.collector.logs.v1.LogsService/Export')); + } +} +exports.OTLPLogExporter = OTLPLogExporter; +//# sourceMappingURL=OTLPLogExporter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-grpc/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-grpc/build/src/index.js new file mode 100644 index 00000000..52d5e649 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-grpc/build/src/index.js @@ -0,0 +1,21 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OTLPLogExporter = void 0; +var OTLPLogExporter_1 = require("./OTLPLogExporter"); +Object.defineProperty(exports, "OTLPLogExporter", { enumerable: true, get: function () { return OTLPLogExporter_1.OTLPLogExporter; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/index.js new file mode 100644 index 00000000..d074d1d3 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/index.js @@ -0,0 +1,21 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OTLPLogExporter = void 0; +var platform_1 = require("./platform"); +Object.defineProperty(exports, "OTLPLogExporter", { enumerable: true, get: function () { return platform_1.OTLPLogExporter; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/index.js new file mode 100644 index 00000000..0c66169c --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/index.js @@ -0,0 +1,21 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OTLPLogExporter = void 0; +var node_1 = require("./node"); +Object.defineProperty(exports, "OTLPLogExporter", { enumerable: true, get: function () { return node_1.OTLPLogExporter; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/node/OTLPLogExporter.js b/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/node/OTLPLogExporter.js new file mode 100644 index 00000000..0d5ba863 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/node/OTLPLogExporter.js @@ -0,0 +1,33 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OTLPLogExporter = void 0; +const otlp_exporter_base_1 = require("@opentelemetry/otlp-exporter-base"); +const otlp_transformer_1 = require("@opentelemetry/otlp-transformer"); +const node_http_1 = require("@opentelemetry/otlp-exporter-base/node-http"); +/** + * Collector Logs Exporter for Node + */ +class OTLPLogExporter extends otlp_exporter_base_1.OTLPExporterBase { + constructor(config = {}) { + super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config, 'LOGS', 'v1/logs', { + 'Content-Type': 'application/json', + }), otlp_transformer_1.JsonLogsSerializer)); + } +} +exports.OTLPLogExporter = OTLPLogExporter; +//# sourceMappingURL=OTLPLogExporter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/node/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/node/index.js new file mode 100644 index 00000000..52d5e649 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/node/index.js @@ -0,0 +1,21 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OTLPLogExporter = void 0; +var OTLPLogExporter_1 = require("./OTLPLogExporter"); +Object.defineProperty(exports, "OTLPLogExporter", { enumerable: true, get: function () { return OTLPLogExporter_1.OTLPLogExporter; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/index.js new file mode 100644 index 00000000..f0e2d801 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/index.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OTLPLogExporter = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var platform_1 = require("./platform"); +Object.defineProperty(exports, "OTLPLogExporter", { enumerable: true, get: function () { return platform_1.OTLPLogExporter; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/index.js new file mode 100644 index 00000000..9a00e764 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/index.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OTLPLogExporter = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var node_1 = require("./node"); +Object.defineProperty(exports, "OTLPLogExporter", { enumerable: true, get: function () { return node_1.OTLPLogExporter; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/node/OTLPLogExporter.js b/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/node/OTLPLogExporter.js new file mode 100644 index 00000000..8f6facfa --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/node/OTLPLogExporter.js @@ -0,0 +1,33 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OTLPLogExporter = void 0; +const otlp_exporter_base_1 = require("@opentelemetry/otlp-exporter-base"); +const otlp_transformer_1 = require("@opentelemetry/otlp-transformer"); +const node_http_1 = require("@opentelemetry/otlp-exporter-base/node-http"); +/** + * OTLP Log Protobuf Exporter for Node.js + */ +class OTLPLogExporter extends otlp_exporter_base_1.OTLPExporterBase { + constructor(config = {}) { + super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config, 'LOGS', 'v1/logs', { + 'Content-Type': 'application/x-protobuf', + }), otlp_transformer_1.ProtobufLogsSerializer)); + } +} +exports.OTLPLogExporter = OTLPLogExporter; +//# sourceMappingURL=OTLPLogExporter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/node/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/node/index.js new file mode 100644 index 00000000..52d5e649 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/node/index.js @@ -0,0 +1,21 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OTLPLogExporter = void 0; +var OTLPLogExporter_1 = require("./OTLPLogExporter"); +Object.defineProperty(exports, "OTLPLogExporter", { enumerable: true, get: function () { return OTLPLogExporter_1.OTLPLogExporter; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-grpc/build/src/OTLPMetricExporter.js b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-grpc/build/src/OTLPMetricExporter.js new file mode 100644 index 00000000..7c1862d9 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-grpc/build/src/OTLPMetricExporter.js @@ -0,0 +1,31 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OTLPMetricExporter = void 0; +const exporter_metrics_otlp_http_1 = require("@opentelemetry/exporter-metrics-otlp-http"); +const otlp_grpc_exporter_base_1 = require("@opentelemetry/otlp-grpc-exporter-base"); +const otlp_transformer_1 = require("@opentelemetry/otlp-transformer"); +/** + * OTLP-gRPC metric exporter + */ +class OTLPMetricExporter extends exporter_metrics_otlp_http_1.OTLPMetricExporterBase { + constructor(config) { + super((0, otlp_grpc_exporter_base_1.createOtlpGrpcExportDelegate)((0, otlp_grpc_exporter_base_1.convertLegacyOtlpGrpcOptions)(config ?? {}, 'METRICS'), otlp_transformer_1.ProtobufMetricsSerializer, 'MetricsExportService', '/opentelemetry.proto.collector.metrics.v1.MetricsService/Export'), config); + } +} +exports.OTLPMetricExporter = OTLPMetricExporter; +//# sourceMappingURL=OTLPMetricExporter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-grpc/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-grpc/build/src/index.js new file mode 100644 index 00000000..89bafa1f --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-grpc/build/src/index.js @@ -0,0 +1,21 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OTLPMetricExporter = void 0; +var OTLPMetricExporter_1 = require("./OTLPMetricExporter"); +Object.defineProperty(exports, "OTLPMetricExporter", { enumerable: true, get: function () { return OTLPMetricExporter_1.OTLPMetricExporter; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/OTLPMetricExporterBase.js b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/OTLPMetricExporterBase.js new file mode 100644 index 00000000..dfd0168e --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/OTLPMetricExporterBase.js @@ -0,0 +1,104 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OTLPMetricExporterBase = exports.LowMemoryTemporalitySelector = exports.DeltaTemporalitySelector = exports.CumulativeTemporalitySelector = void 0; +const core_1 = require("@opentelemetry/core"); +const sdk_metrics_1 = require("@opentelemetry/sdk-metrics"); +const OTLPMetricExporterOptions_1 = require("./OTLPMetricExporterOptions"); +const otlp_exporter_base_1 = require("@opentelemetry/otlp-exporter-base"); +const api_1 = require("@opentelemetry/api"); +const CumulativeTemporalitySelector = () => sdk_metrics_1.AggregationTemporality.CUMULATIVE; +exports.CumulativeTemporalitySelector = CumulativeTemporalitySelector; +const DeltaTemporalitySelector = (instrumentType) => { + switch (instrumentType) { + case sdk_metrics_1.InstrumentType.COUNTER: + case sdk_metrics_1.InstrumentType.OBSERVABLE_COUNTER: + case sdk_metrics_1.InstrumentType.GAUGE: + case sdk_metrics_1.InstrumentType.HISTOGRAM: + case sdk_metrics_1.InstrumentType.OBSERVABLE_GAUGE: + return sdk_metrics_1.AggregationTemporality.DELTA; + case sdk_metrics_1.InstrumentType.UP_DOWN_COUNTER: + case sdk_metrics_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER: + return sdk_metrics_1.AggregationTemporality.CUMULATIVE; + } +}; +exports.DeltaTemporalitySelector = DeltaTemporalitySelector; +const LowMemoryTemporalitySelector = (instrumentType) => { + switch (instrumentType) { + case sdk_metrics_1.InstrumentType.COUNTER: + case sdk_metrics_1.InstrumentType.HISTOGRAM: + return sdk_metrics_1.AggregationTemporality.DELTA; + case sdk_metrics_1.InstrumentType.GAUGE: + case sdk_metrics_1.InstrumentType.UP_DOWN_COUNTER: + case sdk_metrics_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER: + case sdk_metrics_1.InstrumentType.OBSERVABLE_COUNTER: + case sdk_metrics_1.InstrumentType.OBSERVABLE_GAUGE: + return sdk_metrics_1.AggregationTemporality.CUMULATIVE; + } +}; +exports.LowMemoryTemporalitySelector = LowMemoryTemporalitySelector; +function chooseTemporalitySelectorFromEnvironment() { + const configuredTemporality = ((0, core_1.getStringFromEnv)('OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE') ?? + 'cumulative').toLowerCase(); + if (configuredTemporality === 'cumulative') { + return exports.CumulativeTemporalitySelector; + } + if (configuredTemporality === 'delta') { + return exports.DeltaTemporalitySelector; + } + if (configuredTemporality === 'lowmemory') { + return exports.LowMemoryTemporalitySelector; + } + api_1.diag.warn(`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '${configuredTemporality}', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead.`); + return exports.CumulativeTemporalitySelector; +} +function chooseTemporalitySelector(temporalityPreference) { + // Directly passed preference has priority. + if (temporalityPreference != null) { + if (temporalityPreference === OTLPMetricExporterOptions_1.AggregationTemporalityPreference.DELTA) { + return exports.DeltaTemporalitySelector; + } + else if (temporalityPreference === OTLPMetricExporterOptions_1.AggregationTemporalityPreference.LOWMEMORY) { + return exports.LowMemoryTemporalitySelector; + } + return exports.CumulativeTemporalitySelector; + } + return chooseTemporalitySelectorFromEnvironment(); +} +const DEFAULT_AGGREGATION = Object.freeze({ + type: sdk_metrics_1.AggregationType.DEFAULT, +}); +function chooseAggregationSelector(config) { + return config?.aggregationPreference ?? (() => DEFAULT_AGGREGATION); +} +class OTLPMetricExporterBase extends otlp_exporter_base_1.OTLPExporterBase { + _aggregationTemporalitySelector; + _aggregationSelector; + constructor(delegate, config) { + super(delegate); + this._aggregationSelector = chooseAggregationSelector(config); + this._aggregationTemporalitySelector = chooseTemporalitySelector(config?.temporalityPreference); + } + selectAggregation(instrumentType) { + return this._aggregationSelector(instrumentType); + } + selectAggregationTemporality(instrumentType) { + return this._aggregationTemporalitySelector(instrumentType); + } +} +exports.OTLPMetricExporterBase = OTLPMetricExporterBase; +//# sourceMappingURL=OTLPMetricExporterBase.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/OTLPMetricExporterOptions.js b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/OTLPMetricExporterOptions.js new file mode 100644 index 00000000..239bb04e --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/OTLPMetricExporterOptions.js @@ -0,0 +1,25 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AggregationTemporalityPreference = void 0; +var AggregationTemporalityPreference; +(function (AggregationTemporalityPreference) { + AggregationTemporalityPreference[AggregationTemporalityPreference["DELTA"] = 0] = "DELTA"; + AggregationTemporalityPreference[AggregationTemporalityPreference["CUMULATIVE"] = 1] = "CUMULATIVE"; + AggregationTemporalityPreference[AggregationTemporalityPreference["LOWMEMORY"] = 2] = "LOWMEMORY"; +})(AggregationTemporalityPreference = exports.AggregationTemporalityPreference || (exports.AggregationTemporalityPreference = {})); +//# sourceMappingURL=OTLPMetricExporterOptions.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/index.js new file mode 100644 index 00000000..82165886 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/index.js @@ -0,0 +1,28 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OTLPMetricExporterBase = exports.LowMemoryTemporalitySelector = exports.DeltaTemporalitySelector = exports.CumulativeTemporalitySelector = exports.AggregationTemporalityPreference = exports.OTLPMetricExporter = void 0; +var platform_1 = require("./platform"); +Object.defineProperty(exports, "OTLPMetricExporter", { enumerable: true, get: function () { return platform_1.OTLPMetricExporter; } }); +var OTLPMetricExporterOptions_1 = require("./OTLPMetricExporterOptions"); +Object.defineProperty(exports, "AggregationTemporalityPreference", { enumerable: true, get: function () { return OTLPMetricExporterOptions_1.AggregationTemporalityPreference; } }); +var OTLPMetricExporterBase_1 = require("./OTLPMetricExporterBase"); +Object.defineProperty(exports, "CumulativeTemporalitySelector", { enumerable: true, get: function () { return OTLPMetricExporterBase_1.CumulativeTemporalitySelector; } }); +Object.defineProperty(exports, "DeltaTemporalitySelector", { enumerable: true, get: function () { return OTLPMetricExporterBase_1.DeltaTemporalitySelector; } }); +Object.defineProperty(exports, "LowMemoryTemporalitySelector", { enumerable: true, get: function () { return OTLPMetricExporterBase_1.LowMemoryTemporalitySelector; } }); +Object.defineProperty(exports, "OTLPMetricExporterBase", { enumerable: true, get: function () { return OTLPMetricExporterBase_1.OTLPMetricExporterBase; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/index.js new file mode 100644 index 00000000..5d3b9887 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/index.js @@ -0,0 +1,21 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OTLPMetricExporter = void 0; +var node_1 = require("./node"); +Object.defineProperty(exports, "OTLPMetricExporter", { enumerable: true, get: function () { return node_1.OTLPMetricExporter; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/node/OTLPMetricExporter.js b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/node/OTLPMetricExporter.js new file mode 100644 index 00000000..13ea3433 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/node/OTLPMetricExporter.js @@ -0,0 +1,33 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OTLPMetricExporter = void 0; +const OTLPMetricExporterBase_1 = require("../../OTLPMetricExporterBase"); +const otlp_transformer_1 = require("@opentelemetry/otlp-transformer"); +const node_http_1 = require("@opentelemetry/otlp-exporter-base/node-http"); +/** + * OTLP Metric Exporter for Node.js + */ +class OTLPMetricExporter extends OTLPMetricExporterBase_1.OTLPMetricExporterBase { + constructor(config) { + super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config ?? {}, 'METRICS', 'v1/metrics', { + 'Content-Type': 'application/json', + }), otlp_transformer_1.JsonMetricsSerializer), config); + } +} +exports.OTLPMetricExporter = OTLPMetricExporter; +//# sourceMappingURL=OTLPMetricExporter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/node/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/node/index.js new file mode 100644 index 00000000..89bafa1f --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/node/index.js @@ -0,0 +1,21 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OTLPMetricExporter = void 0; +var OTLPMetricExporter_1 = require("./OTLPMetricExporter"); +Object.defineProperty(exports, "OTLPMetricExporter", { enumerable: true, get: function () { return OTLPMetricExporter_1.OTLPMetricExporter; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/index.js new file mode 100644 index 00000000..e1a1b768 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/index.js @@ -0,0 +1,21 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OTLPMetricExporter = void 0; +var platform_1 = require("./platform"); +Object.defineProperty(exports, "OTLPMetricExporter", { enumerable: true, get: function () { return platform_1.OTLPMetricExporter; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/index.js new file mode 100644 index 00000000..5d3b9887 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/index.js @@ -0,0 +1,21 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OTLPMetricExporter = void 0; +var node_1 = require("./node"); +Object.defineProperty(exports, "OTLPMetricExporter", { enumerable: true, get: function () { return node_1.OTLPMetricExporter; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/node/OTLPMetricExporter.js b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/node/OTLPMetricExporter.js new file mode 100644 index 00000000..15d7b2c0 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/node/OTLPMetricExporter.js @@ -0,0 +1,30 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OTLPMetricExporter = void 0; +const exporter_metrics_otlp_http_1 = require("@opentelemetry/exporter-metrics-otlp-http"); +const otlp_transformer_1 = require("@opentelemetry/otlp-transformer"); +const node_http_1 = require("@opentelemetry/otlp-exporter-base/node-http"); +class OTLPMetricExporter extends exporter_metrics_otlp_http_1.OTLPMetricExporterBase { + constructor(config) { + super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config ?? {}, 'METRICS', 'v1/metrics', { + 'Content-Type': 'application/x-protobuf', + }), otlp_transformer_1.ProtobufMetricsSerializer), config); + } +} +exports.OTLPMetricExporter = OTLPMetricExporter; +//# sourceMappingURL=OTLPMetricExporter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/node/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/node/index.js new file mode 100644 index 00000000..89bafa1f --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/node/index.js @@ -0,0 +1,21 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OTLPMetricExporter = void 0; +var OTLPMetricExporter_1 = require("./OTLPMetricExporter"); +Object.defineProperty(exports, "OTLPMetricExporter", { enumerable: true, get: function () { return OTLPMetricExporter_1.OTLPMetricExporter; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-prometheus/build/src/PrometheusExporter.js b/claude-code-source/node_modules/@opentelemetry/exporter-prometheus/build/src/PrometheusExporter.js new file mode 100644 index 00000000..2edf78ac --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-prometheus/build/src/PrometheusExporter.js @@ -0,0 +1,195 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PrometheusExporter = void 0; +const api_1 = require("@opentelemetry/api"); +const core_1 = require("@opentelemetry/core"); +const sdk_metrics_1 = require("@opentelemetry/sdk-metrics"); +const http_1 = require("http"); +const PrometheusSerializer_1 = require("./PrometheusSerializer"); +/** Node.js v8.x compat */ +const url_1 = require("url"); +class PrometheusExporter extends sdk_metrics_1.MetricReader { + static DEFAULT_OPTIONS = { + host: undefined, + port: 9464, + endpoint: '/metrics', + prefix: '', + appendTimestamp: false, + withResourceConstantLabels: undefined, + withoutTargetInfo: false, + }; + _host; + _port; + _baseUrl; + _endpoint; + _server; + _prefix; + _appendTimestamp; + _serializer; + _startServerPromise; + // This will be required when histogram is implemented. Leaving here so it is not forgotten + // Histogram cannot have a attribute named 'le' + // private static readonly RESERVED_HISTOGRAM_LABEL = 'le'; + /** + * Constructor + * @param config Exporter configuration + * @param callback Callback to be called after a server was started + */ + constructor(config = {}, callback = () => { }) { + super({ + aggregationSelector: _instrumentType => { + return { + type: sdk_metrics_1.AggregationType.DEFAULT, + }; + }, + aggregationTemporalitySelector: _instrumentType => sdk_metrics_1.AggregationTemporality.CUMULATIVE, + metricProducers: config.metricProducers, + }); + this._host = + config.host || + process.env.OTEL_EXPORTER_PROMETHEUS_HOST || + PrometheusExporter.DEFAULT_OPTIONS.host; + this._port = + config.port || + Number(process.env.OTEL_EXPORTER_PROMETHEUS_PORT) || + PrometheusExporter.DEFAULT_OPTIONS.port; + this._prefix = config.prefix || PrometheusExporter.DEFAULT_OPTIONS.prefix; + this._appendTimestamp = + typeof config.appendTimestamp === 'boolean' + ? config.appendTimestamp + : PrometheusExporter.DEFAULT_OPTIONS.appendTimestamp; + const _withResourceConstantLabels = config.withResourceConstantLabels || + PrometheusExporter.DEFAULT_OPTIONS.withResourceConstantLabels; + const _withoutTargetInfo = config.withoutTargetInfo || + PrometheusExporter.DEFAULT_OPTIONS.withoutTargetInfo; + // unref to prevent prometheus exporter from holding the process open on exit + this._server = (0, http_1.createServer)(this._requestHandler).unref(); + this._serializer = new PrometheusSerializer_1.PrometheusSerializer(this._prefix, this._appendTimestamp, _withResourceConstantLabels, _withoutTargetInfo); + this._baseUrl = `http://${this._host}:${this._port}/`; + this._endpoint = (config.endpoint || PrometheusExporter.DEFAULT_OPTIONS.endpoint).replace(/^([^/])/, '/$1'); + if (config.preventServerStart !== true) { + this.startServer().then(callback, err => { + api_1.diag.error(err); + callback(err); + }); + } + else if (callback) { + // Do not invoke callback immediately to avoid zalgo problem. + queueMicrotask(callback); + } + } + async onForceFlush() { + /** do nothing */ + } + /** + * Shuts down the export server and clears the registry + */ + onShutdown() { + return this.stopServer(); + } + /** + * Stops the Prometheus export server + */ + stopServer() { + if (!this._server) { + api_1.diag.debug('Prometheus stopServer() was called but server was never started.'); + return Promise.resolve(); + } + else { + return new Promise(resolve => { + this._server.close(err => { + if (!err) { + api_1.diag.debug('Prometheus exporter was stopped'); + } + else { + if (err.code !== + 'ERR_SERVER_NOT_RUNNING') { + (0, core_1.globalErrorHandler)(err); + } + } + resolve(); + }); + }); + } + } + /** + * Starts the Prometheus export server + */ + startServer() { + this._startServerPromise ??= new Promise((resolve, reject) => { + this._server.once('error', reject); + this._server.listen({ + port: this._port, + host: this._host, + }, () => { + api_1.diag.debug(`Prometheus exporter server started: ${this._host}:${this._port}/${this._endpoint}`); + resolve(); + }); + }); + return this._startServerPromise; + } + /** + * Request handler that responds with the current state of metrics + * @param _request Incoming HTTP request of server instance + * @param response HTTP response object used to response to request + */ + getMetricsRequestHandler(_request, response) { + this._exportMetrics(response); + } + /** + * Request handler used by http library to respond to incoming requests + * for the current state of metrics by the Prometheus backend. + * + * @param request Incoming HTTP request to export server + * @param response HTTP response object used to respond to request + */ + _requestHandler = (request, response) => { + if (request.url != null && + new url_1.URL(request.url, this._baseUrl).pathname === this._endpoint) { + this._exportMetrics(response); + } + else { + this._notFound(response); + } + }; + /** + * Responds to incoming message with current state of all metrics. + */ + _exportMetrics = (response) => { + response.statusCode = 200; + response.setHeader('content-type', 'text/plain'); + this.collect().then(collectionResult => { + const { resourceMetrics, errors } = collectionResult; + if (errors.length) { + api_1.diag.error('PrometheusExporter: metrics collection errors', ...errors); + } + response.end(this._serializer.serialize(resourceMetrics)); + }, err => { + response.end(`# failed to export metrics: ${err}`); + }); + }; + /** + * Responds with 404 status code to all requests that do not match the configured endpoint. + */ + _notFound = (response) => { + response.statusCode = 404; + response.end(); + }; +} +exports.PrometheusExporter = PrometheusExporter; +//# sourceMappingURL=PrometheusExporter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-prometheus/build/src/PrometheusSerializer.js b/claude-code-source/node_modules/@opentelemetry/exporter-prometheus/build/src/PrometheusSerializer.js new file mode 100644 index 00000000..5cc25164 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-prometheus/build/src/PrometheusSerializer.js @@ -0,0 +1,264 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PrometheusSerializer = void 0; +const api_1 = require("@opentelemetry/api"); +const sdk_metrics_1 = require("@opentelemetry/sdk-metrics"); +const core_1 = require("@opentelemetry/core"); +function escapeString(str) { + return str.replace(/\\/g, '\\\\').replace(/\n/g, '\\n'); +} +/** + * String Attribute values are converted directly to Prometheus attribute values. + * Non-string values are represented as JSON-encoded strings. + * + * `undefined` is converted to an empty string. + */ +function escapeAttributeValue(str = '') { + if (typeof str !== 'string') { + str = JSON.stringify(str); + } + return escapeString(str).replace(/"/g, '\\"'); +} +const invalidCharacterRegex = /[^a-z0-9_]/gi; +const multipleUnderscoreRegex = /_{2,}/g; +/** + * Ensures metric names are valid Prometheus metric names by removing + * characters allowed by OpenTelemetry but disallowed by Prometheus. + * + * https://prometheus.io/docs/concepts/data_model/#metric-names-and-attributes + * + * 1. Names must match `[a-zA-Z_:][a-zA-Z0-9_:]*` + * + * 2. Colons are reserved for user defined recording rules. + * They should not be used by exporters or direct instrumentation. + * + * OpenTelemetry metric names are already validated in the Meter when they are created, + * and they match the format `[a-zA-Z][a-zA-Z0-9_.\-]*` which is very close to a valid + * prometheus metric name, so we only need to strip characters valid in OpenTelemetry + * but not valid in prometheus and replace them with '_'. + * + * @param name name to be sanitized + */ +function sanitizePrometheusMetricName(name) { + // replace all invalid characters with '_' + return name + .replace(invalidCharacterRegex, '_') + .replace(multipleUnderscoreRegex, '_'); +} +/** + * @private + * + * Helper method which assists in enforcing the naming conventions for metric + * names in Prometheus + * @param name the name of the metric + * @param type the kind of metric + * @returns string + */ +function enforcePrometheusNamingConvention(name, data) { + // Prometheus requires that metrics of the Counter kind have "_total" suffix + if (!name.endsWith('_total') && + data.dataPointType === sdk_metrics_1.DataPointType.SUM && + data.isMonotonic) { + name = name + '_total'; + } + return name; +} +function valueString(value) { + if (value === Infinity) { + return '+Inf'; + } + else if (value === -Infinity) { + return '-Inf'; + } + else { + // Handle finite numbers and NaN. + return `${value}`; + } +} +function toPrometheusType(metricData) { + switch (metricData.dataPointType) { + case sdk_metrics_1.DataPointType.SUM: + if (metricData.isMonotonic) { + return 'counter'; + } + return 'gauge'; + case sdk_metrics_1.DataPointType.GAUGE: + return 'gauge'; + case sdk_metrics_1.DataPointType.HISTOGRAM: + return 'histogram'; + default: + return 'untyped'; + } +} +function stringify(metricName, attributes, value, timestamp, additionalAttributes) { + let hasAttribute = false; + let attributesStr = ''; + for (const [key, val] of Object.entries(attributes)) { + const sanitizedAttributeName = sanitizePrometheusMetricName(key); + hasAttribute = true; + attributesStr += `${attributesStr.length > 0 ? ',' : ''}${sanitizedAttributeName}="${escapeAttributeValue(val)}"`; + } + if (additionalAttributes) { + for (const [key, val] of Object.entries(additionalAttributes)) { + const sanitizedAttributeName = sanitizePrometheusMetricName(key); + hasAttribute = true; + attributesStr += `${attributesStr.length > 0 ? ',' : ''}${sanitizedAttributeName}="${escapeAttributeValue(val)}"`; + } + } + if (hasAttribute) { + metricName += `{${attributesStr}}`; + } + return `${metricName} ${valueString(value)}${timestamp !== undefined ? ' ' + String(timestamp) : ''}\n`; +} +const NO_REGISTERED_METRICS = '# no registered metrics'; +class PrometheusSerializer { + _prefix; + _appendTimestamp; + _additionalAttributes; + _withResourceConstantLabels; + _withoutTargetInfo; + constructor(prefix, appendTimestamp = false, withResourceConstantLabels, withoutTargetInfo) { + if (prefix) { + this._prefix = prefix + '_'; + } + this._appendTimestamp = appendTimestamp; + this._withResourceConstantLabels = withResourceConstantLabels; + this._withoutTargetInfo = !!withoutTargetInfo; + } + serialize(resourceMetrics) { + let str = ''; + this._additionalAttributes = this._filterResourceConstantLabels(resourceMetrics.resource.attributes, this._withResourceConstantLabels); + for (const scopeMetrics of resourceMetrics.scopeMetrics) { + str += this._serializeScopeMetrics(scopeMetrics); + } + if (str === '') { + str += NO_REGISTERED_METRICS; + } + return this._serializeResource(resourceMetrics.resource) + str; + } + _filterResourceConstantLabels(attributes, pattern) { + if (pattern) { + const filteredAttributes = {}; + for (const [key, value] of Object.entries(attributes)) { + if (key.match(pattern)) { + filteredAttributes[key] = value; + } + } + return filteredAttributes; + } + return; + } + _serializeScopeMetrics(scopeMetrics) { + let str = ''; + for (const metric of scopeMetrics.metrics) { + str += this._serializeMetricData(metric) + '\n'; + } + return str; + } + _serializeMetricData(metricData) { + let name = sanitizePrometheusMetricName(escapeString(metricData.descriptor.name)); + if (this._prefix) { + name = `${this._prefix}${name}`; + } + const dataPointType = metricData.dataPointType; + name = enforcePrometheusNamingConvention(name, metricData); + const help = `# HELP ${name} ${escapeString(metricData.descriptor.description || 'description missing')}`; + const unit = metricData.descriptor.unit + ? `\n# UNIT ${name} ${escapeString(metricData.descriptor.unit)}` + : ''; + const type = `# TYPE ${name} ${toPrometheusType(metricData)}`; + let results = ''; + switch (dataPointType) { + case sdk_metrics_1.DataPointType.SUM: + case sdk_metrics_1.DataPointType.GAUGE: { + results = metricData.dataPoints + .map(it => this._serializeSingularDataPoint(name, metricData, it)) + .join(''); + break; + } + case sdk_metrics_1.DataPointType.HISTOGRAM: { + results = metricData.dataPoints + .map(it => this._serializeHistogramDataPoint(name, metricData, it)) + .join(''); + break; + } + default: { + api_1.diag.error(`Unrecognizable DataPointType: ${dataPointType} for metric "${name}"`); + } + } + return `${help}${unit}\n${type}\n${results}`.trim(); + } + _serializeSingularDataPoint(name, data, dataPoint) { + let results = ''; + name = enforcePrometheusNamingConvention(name, data); + const { value, attributes } = dataPoint; + const timestamp = (0, core_1.hrTimeToMilliseconds)(dataPoint.endTime); + results += stringify(name, attributes, value, this._appendTimestamp ? timestamp : undefined, this._additionalAttributes); + return results; + } + _serializeHistogramDataPoint(name, data, dataPoint) { + let results = ''; + name = enforcePrometheusNamingConvention(name, data); + const attributes = dataPoint.attributes; + const histogram = dataPoint.value; + const timestamp = (0, core_1.hrTimeToMilliseconds)(dataPoint.endTime); + /** Histogram["bucket"] is not typed with `number` */ + for (const key of ['count', 'sum']) { + const value = histogram[key]; + if (value != null) + results += stringify(name + '_' + key, attributes, value, this._appendTimestamp ? timestamp : undefined, this._additionalAttributes); + } + let cumulativeSum = 0; + const countEntries = histogram.buckets.counts.entries(); + let infiniteBoundaryDefined = false; + for (const [idx, val] of countEntries) { + cumulativeSum += val; + const upperBound = histogram.buckets.boundaries[idx]; + /** HistogramAggregator is producing different boundary output - + * in one case not including infinity values, in other - + * full, e.g. [0, 100] and [0, 100, Infinity] + * we should consider that in export, if Infinity is defined, use it + * as boundary + */ + if (upperBound === undefined && infiniteBoundaryDefined) { + break; + } + if (upperBound === Infinity) { + infiniteBoundaryDefined = true; + } + results += stringify(name + '_bucket', attributes, cumulativeSum, this._appendTimestamp ? timestamp : undefined, Object.assign({}, this._additionalAttributes ?? {}, { + le: upperBound === undefined || upperBound === Infinity + ? '+Inf' + : String(upperBound), + })); + } + return results; + } + _serializeResource(resource) { + if (this._withoutTargetInfo === true) { + return ''; + } + const name = 'target_info'; + const help = `# HELP ${name} Target metadata`; + const type = `# TYPE ${name} gauge`; + const results = stringify(name, resource.attributes, 1).trim(); + return `${help}\n${type}\n${results}\n`; + } +} +exports.PrometheusSerializer = PrometheusSerializer; +//# sourceMappingURL=PrometheusSerializer.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-prometheus/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-prometheus/build/src/index.js new file mode 100644 index 00000000..0427e351 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-prometheus/build/src/index.js @@ -0,0 +1,23 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PrometheusSerializer = exports.PrometheusExporter = void 0; +var PrometheusExporter_1 = require("./PrometheusExporter"); +Object.defineProperty(exports, "PrometheusExporter", { enumerable: true, get: function () { return PrometheusExporter_1.PrometheusExporter; } }); +var PrometheusSerializer_1 = require("./PrometheusSerializer"); +Object.defineProperty(exports, "PrometheusSerializer", { enumerable: true, get: function () { return PrometheusSerializer_1.PrometheusSerializer; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-grpc/build/src/OTLPTraceExporter.js b/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-grpc/build/src/OTLPTraceExporter.js new file mode 100644 index 00000000..d65398ca --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-grpc/build/src/OTLPTraceExporter.js @@ -0,0 +1,31 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OTLPTraceExporter = void 0; +const otlp_grpc_exporter_base_1 = require("@opentelemetry/otlp-grpc-exporter-base"); +const otlp_transformer_1 = require("@opentelemetry/otlp-transformer"); +const otlp_exporter_base_1 = require("@opentelemetry/otlp-exporter-base"); +/** + * OTLP Trace Exporter for Node + */ +class OTLPTraceExporter extends otlp_exporter_base_1.OTLPExporterBase { + constructor(config = {}) { + super((0, otlp_grpc_exporter_base_1.createOtlpGrpcExportDelegate)((0, otlp_grpc_exporter_base_1.convertLegacyOtlpGrpcOptions)(config, 'TRACES'), otlp_transformer_1.ProtobufTraceSerializer, 'TraceExportService', '/opentelemetry.proto.collector.trace.v1.TraceService/Export')); + } +} +exports.OTLPTraceExporter = OTLPTraceExporter; +//# sourceMappingURL=OTLPTraceExporter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-grpc/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-grpc/build/src/index.js new file mode 100644 index 00000000..532d74f2 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-grpc/build/src/index.js @@ -0,0 +1,21 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OTLPTraceExporter = void 0; +var OTLPTraceExporter_1 = require("./OTLPTraceExporter"); +Object.defineProperty(exports, "OTLPTraceExporter", { enumerable: true, get: function () { return OTLPTraceExporter_1.OTLPTraceExporter; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/index.js new file mode 100644 index 00000000..7fcd8476 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/index.js @@ -0,0 +1,21 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OTLPTraceExporter = void 0; +var platform_1 = require("./platform"); +Object.defineProperty(exports, "OTLPTraceExporter", { enumerable: true, get: function () { return platform_1.OTLPTraceExporter; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/index.js new file mode 100644 index 00000000..e9701c10 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/index.js @@ -0,0 +1,21 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OTLPTraceExporter = void 0; +var node_1 = require("./node"); +Object.defineProperty(exports, "OTLPTraceExporter", { enumerable: true, get: function () { return node_1.OTLPTraceExporter; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/node/OTLPTraceExporter.js b/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/node/OTLPTraceExporter.js new file mode 100644 index 00000000..2acd49b9 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/node/OTLPTraceExporter.js @@ -0,0 +1,33 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OTLPTraceExporter = void 0; +const otlp_exporter_base_1 = require("@opentelemetry/otlp-exporter-base"); +const otlp_transformer_1 = require("@opentelemetry/otlp-transformer"); +const node_http_1 = require("@opentelemetry/otlp-exporter-base/node-http"); +/** + * Collector Trace Exporter for Node + */ +class OTLPTraceExporter extends otlp_exporter_base_1.OTLPExporterBase { + constructor(config = {}) { + super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config, 'TRACES', 'v1/traces', { + 'Content-Type': 'application/json', + }), otlp_transformer_1.JsonTraceSerializer)); + } +} +exports.OTLPTraceExporter = OTLPTraceExporter; +//# sourceMappingURL=OTLPTraceExporter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/node/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/node/index.js new file mode 100644 index 00000000..532d74f2 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/node/index.js @@ -0,0 +1,21 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OTLPTraceExporter = void 0; +var OTLPTraceExporter_1 = require("./OTLPTraceExporter"); +Object.defineProperty(exports, "OTLPTraceExporter", { enumerable: true, get: function () { return OTLPTraceExporter_1.OTLPTraceExporter; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/index.js new file mode 100644 index 00000000..c72a409a --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/index.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OTLPTraceExporter = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var platform_1 = require("./platform"); +Object.defineProperty(exports, "OTLPTraceExporter", { enumerable: true, get: function () { return platform_1.OTLPTraceExporter; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/index.js new file mode 100644 index 00000000..7d7c7e67 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/index.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OTLPTraceExporter = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var node_1 = require("./node"); +Object.defineProperty(exports, "OTLPTraceExporter", { enumerable: true, get: function () { return node_1.OTLPTraceExporter; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/node/OTLPTraceExporter.js b/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/node/OTLPTraceExporter.js new file mode 100644 index 00000000..b17e7f90 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/node/OTLPTraceExporter.js @@ -0,0 +1,33 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OTLPTraceExporter = void 0; +const otlp_exporter_base_1 = require("@opentelemetry/otlp-exporter-base"); +const otlp_transformer_1 = require("@opentelemetry/otlp-transformer"); +const node_http_1 = require("@opentelemetry/otlp-exporter-base/node-http"); +/** + * Collector Trace Exporter for Node with protobuf + */ +class OTLPTraceExporter extends otlp_exporter_base_1.OTLPExporterBase { + constructor(config = {}) { + super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config, 'TRACES', 'v1/traces', { + 'Content-Type': 'application/x-protobuf', + }), otlp_transformer_1.ProtobufTraceSerializer)); + } +} +exports.OTLPTraceExporter = OTLPTraceExporter; +//# sourceMappingURL=OTLPTraceExporter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/node/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/node/index.js new file mode 100644 index 00000000..532d74f2 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/node/index.js @@ -0,0 +1,21 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OTLPTraceExporter = void 0; +var OTLPTraceExporter_1 = require("./OTLPTraceExporter"); +Object.defineProperty(exports, "OTLPTraceExporter", { enumerable: true, get: function () { return OTLPTraceExporter_1.OTLPTraceExporter; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/OTLPExporterBase.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/OTLPExporterBase.js new file mode 100644 index 00000000..a370aa54 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/OTLPExporterBase.js @@ -0,0 +1,40 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OTLPExporterBase = void 0; +class OTLPExporterBase { + _delegate; + constructor(_delegate) { + this._delegate = _delegate; + } + /** + * Export items. + * @param items + * @param resultCallback + */ + export(items, resultCallback) { + this._delegate.export(items, resultCallback); + } + forceFlush() { + return this._delegate.forceFlush(); + } + shutdown() { + return this._delegate.shutdown(); + } +} +exports.OTLPExporterBase = OTLPExporterBase; +//# sourceMappingURL=OTLPExporterBase.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/bounded-queue-export-promise-handler.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/bounded-queue-export-promise-handler.js new file mode 100644 index 00000000..e234e32b --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/bounded-queue-export-promise-handler.js @@ -0,0 +1,54 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createBoundedQueueExportPromiseHandler = void 0; +class BoundedQueueExportPromiseHandler { + _concurrencyLimit; + _sendingPromises = []; + /** + * @param concurrencyLimit maximum promises allowed in a queue at the same time. + */ + constructor(concurrencyLimit) { + this._concurrencyLimit = concurrencyLimit; + } + pushPromise(promise) { + if (this.hasReachedLimit()) { + throw new Error('Concurrency Limit reached'); + } + this._sendingPromises.push(promise); + const popPromise = () => { + const index = this._sendingPromises.indexOf(promise); + void this._sendingPromises.splice(index, 1); + }; + promise.then(popPromise, popPromise); + } + hasReachedLimit() { + return this._sendingPromises.length >= this._concurrencyLimit; + } + async awaitAll() { + await Promise.all(this._sendingPromises); + } +} +/** + * Promise queue for keeping track of export promises. Finished promises will be auto-dequeued. + * Allows for awaiting all promises in the queue. + */ +function createBoundedQueueExportPromiseHandler(options) { + return new BoundedQueueExportPromiseHandler(options.concurrencyLimit); +} +exports.createBoundedQueueExportPromiseHandler = createBoundedQueueExportPromiseHandler; +//# sourceMappingURL=bounded-queue-export-promise-handler.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/convert-legacy-http-options.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/convert-legacy-http-options.js new file mode 100644 index 00000000..758fcfb0 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/convert-legacy-http-options.js @@ -0,0 +1,27 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.convertLegacyHeaders = void 0; +const shared_configuration_1 = require("./shared-configuration"); +function convertLegacyHeaders(config) { + if (typeof config.headers === 'function') { + return config.headers; + } + return (0, shared_configuration_1.wrapStaticHeadersInFunction)(config.headers); +} +exports.convertLegacyHeaders = convertLegacyHeaders; +//# sourceMappingURL=convert-legacy-http-options.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/convert-legacy-node-http-options.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/convert-legacy-node-http-options.js new file mode 100644 index 00000000..7b50474f --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/convert-legacy-node-http-options.js @@ -0,0 +1,47 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.convertLegacyHttpOptions = void 0; +const api_1 = require("@opentelemetry/api"); +const otlp_node_http_configuration_1 = require("./otlp-node-http-configuration"); +const index_node_http_1 = require("../index-node-http"); +const otlp_node_http_env_configuration_1 = require("./otlp-node-http-env-configuration"); +const convert_legacy_http_options_1 = require("./convert-legacy-http-options"); +function convertLegacyAgentOptions(config) { + if (typeof config.httpAgentOptions === 'function') { + return config.httpAgentOptions; + } + let legacy = config.httpAgentOptions; + if (config.keepAlive != null) { + legacy = { keepAlive: config.keepAlive, ...legacy }; + } + if (legacy != null) { + return (0, index_node_http_1.httpAgentFactoryFromOptions)(legacy); + } + else { + return undefined; + } +} +/** + * @deprecated this will be removed in 2.0 + * @param config + * @param signalIdentifier + * @param signalResourcePath + * @param requiredHeaders + */ +function convertLegacyHttpOptions(config, signalIdentifier, signalResourcePath, requiredHeaders) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (config.metadata) { + api_1.diag.warn('Metadata cannot be set when using http'); + } + return (0, otlp_node_http_configuration_1.mergeOtlpNodeHttpConfigurationWithDefaults)({ + url: config.url, + headers: (0, convert_legacy_http_options_1.convertLegacyHeaders)(config), + concurrencyLimit: config.concurrencyLimit, + timeoutMillis: config.timeoutMillis, + compression: config.compression, + agentFactory: convertLegacyAgentOptions(config), + userAgent: config.userAgent, + }, (0, otlp_node_http_env_configuration_1.getNodeHttpConfigurationFromEnvironment)(signalIdentifier, signalResourcePath), (0, otlp_node_http_configuration_1.getNodeHttpConfigurationDefaults)(requiredHeaders, signalResourcePath)); +} +exports.convertLegacyHttpOptions = convertLegacyHttpOptions; +//# sourceMappingURL=convert-legacy-node-http-options.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/legacy-node-configuration.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/legacy-node-configuration.js new file mode 100644 index 00000000..863c8cdc --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/legacy-node-configuration.js @@ -0,0 +1,24 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CompressionAlgorithm = void 0; +var CompressionAlgorithm; +(function (CompressionAlgorithm) { + CompressionAlgorithm["NONE"] = "none"; + CompressionAlgorithm["GZIP"] = "gzip"; +})(CompressionAlgorithm = exports.CompressionAlgorithm || (exports.CompressionAlgorithm = {})); +//# sourceMappingURL=legacy-node-configuration.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/otlp-http-configuration.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/otlp-http-configuration.js new file mode 100644 index 00000000..28a89dac --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/otlp-http-configuration.js @@ -0,0 +1,75 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getHttpConfigurationDefaults = exports.mergeOtlpHttpConfigurationWithDefaults = void 0; +const shared_configuration_1 = require("./shared-configuration"); +const util_1 = require("../util"); +function mergeHeaders(userProvidedHeaders, fallbackHeaders, defaultHeaders) { + return async () => { + const requiredHeaders = { + ...(await defaultHeaders()), + }; + const headers = {}; + // add fallback ones first + if (fallbackHeaders != null) { + Object.assign(headers, await fallbackHeaders()); + } + // override with user-provided ones + if (userProvidedHeaders != null) { + Object.assign(headers, (0, util_1.validateAndNormalizeHeaders)(await userProvidedHeaders())); + } + // override required ones. + return Object.assign(headers, requiredHeaders); + }; +} +function validateUserProvidedUrl(url) { + if (url == null) { + return undefined; + } + try { + // NOTE: In non-browser environments, `globalThis.location` will be `undefined`. + const base = globalThis.location?.href; + return new URL(url, base).href; + } + catch { + throw new Error(`Configuration: Could not parse user-provided export URL: '${url}'`); + } +} +/** + * @param userProvidedConfiguration Configuration options provided by the user in code. + * @param fallbackConfiguration Fallback to use when the {@link userProvidedConfiguration} does not specify an option. + * @param defaultConfiguration The defaults as defined by the exporter specification + */ +function mergeOtlpHttpConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration) { + return { + ...(0, shared_configuration_1.mergeOtlpSharedConfigurationWithDefaults)(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration), + headers: mergeHeaders(userProvidedConfiguration.headers, fallbackConfiguration.headers, defaultConfiguration.headers), + url: validateUserProvidedUrl(userProvidedConfiguration.url) ?? + fallbackConfiguration.url ?? + defaultConfiguration.url, + }; +} +exports.mergeOtlpHttpConfigurationWithDefaults = mergeOtlpHttpConfigurationWithDefaults; +function getHttpConfigurationDefaults(requiredHeaders, signalResourcePath) { + return { + ...(0, shared_configuration_1.getSharedConfigurationDefaults)(), + headers: async () => requiredHeaders, + url: 'http://localhost:4318/' + signalResourcePath, + }; +} +exports.getHttpConfigurationDefaults = getHttpConfigurationDefaults; +//# sourceMappingURL=otlp-http-configuration.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/otlp-node-http-configuration.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/otlp-node-http-configuration.js new file mode 100644 index 00000000..2fe2d26f --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/otlp-node-http-configuration.js @@ -0,0 +1,56 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getNodeHttpConfigurationDefaults = exports.mergeOtlpNodeHttpConfigurationWithDefaults = exports.httpAgentFactoryFromOptions = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const otlp_http_configuration_1 = require("./otlp-http-configuration"); +function httpAgentFactoryFromOptions(options) { + return async (protocol) => { + const isInsecure = protocol === 'http:'; + const module = isInsecure ? import('http') : import('https'); + const { Agent } = await module; + if (isInsecure) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars -- these props should not be used in agent options + const { ca, cert, key, ...insecureOptions } = options; + return new Agent(insecureOptions); + } + return new Agent(options); + }; +} +exports.httpAgentFactoryFromOptions = httpAgentFactoryFromOptions; +/** + * @param userProvidedConfiguration Configuration options provided by the user in code. + * @param fallbackConfiguration Fallback to use when the {@link userProvidedConfiguration} does not specify an option. + * @param defaultConfiguration The defaults as defined by the exporter specification + */ +function mergeOtlpNodeHttpConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration) { + return { + ...(0, otlp_http_configuration_1.mergeOtlpHttpConfigurationWithDefaults)(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration), + agentFactory: userProvidedConfiguration.agentFactory ?? + fallbackConfiguration.agentFactory ?? + defaultConfiguration.agentFactory, + userAgent: userProvidedConfiguration.userAgent, + }; +} +exports.mergeOtlpNodeHttpConfigurationWithDefaults = mergeOtlpNodeHttpConfigurationWithDefaults; +function getNodeHttpConfigurationDefaults(requiredHeaders, signalResourcePath) { + return { + ...(0, otlp_http_configuration_1.getHttpConfigurationDefaults)(requiredHeaders, signalResourcePath), + agentFactory: httpAgentFactoryFromOptions({ keepAlive: true }), + }; +} +exports.getNodeHttpConfigurationDefaults = getNodeHttpConfigurationDefaults; +//# sourceMappingURL=otlp-node-http-configuration.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/otlp-node-http-env-configuration.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/otlp-node-http-env-configuration.js new file mode 100644 index 00000000..1465531c --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/otlp-node-http-env-configuration.js @@ -0,0 +1,134 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getNodeHttpConfigurationFromEnvironment = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const fs = require("fs"); +const path = require("path"); +const core_1 = require("@opentelemetry/core"); +const api_1 = require("@opentelemetry/api"); +const shared_env_configuration_1 = require("./shared-env-configuration"); +const shared_configuration_1 = require("./shared-configuration"); +const otlp_node_http_configuration_1 = require("./otlp-node-http-configuration"); +function getStaticHeadersFromEnv(signalIdentifier) { + const signalSpecificRawHeaders = (0, core_1.getStringFromEnv)(`OTEL_EXPORTER_OTLP_${signalIdentifier}_HEADERS`); + const nonSignalSpecificRawHeaders = (0, core_1.getStringFromEnv)('OTEL_EXPORTER_OTLP_HEADERS'); + const signalSpecificHeaders = (0, core_1.parseKeyPairsIntoRecord)(signalSpecificRawHeaders); + const nonSignalSpecificHeaders = (0, core_1.parseKeyPairsIntoRecord)(nonSignalSpecificRawHeaders); + if (Object.keys(signalSpecificHeaders).length === 0 && + Object.keys(nonSignalSpecificHeaders).length === 0) { + return undefined; + } + // headers are combined instead of overwritten, with the specific headers taking precedence over + // the non-specific ones. + return Object.assign({}, (0, core_1.parseKeyPairsIntoRecord)(nonSignalSpecificRawHeaders), (0, core_1.parseKeyPairsIntoRecord)(signalSpecificRawHeaders)); +} +function appendRootPathToUrlIfNeeded(url) { + try { + const parsedUrl = new URL(url); + // This will automatically append '/' if there's no root path. + return parsedUrl.toString(); + } + catch { + api_1.diag.warn(`Configuration: Could not parse environment-provided export URL: '${url}', falling back to undefined`); + return undefined; + } +} +function appendResourcePathToUrl(url, path) { + try { + // just try to parse, if it fails we catch and warn. + new URL(url); + } + catch { + api_1.diag.warn(`Configuration: Could not parse environment-provided export URL: '${url}', falling back to undefined`); + return undefined; + } + if (!url.endsWith('/')) { + url = url + '/'; + } + url += path; + try { + // just try to parse, if it fails we catch and warn. + new URL(url); + } + catch { + api_1.diag.warn(`Configuration: Provided URL appended with '${path}' is not a valid URL, using 'undefined' instead of '${url}'`); + return undefined; + } + return url; +} +function getNonSpecificUrlFromEnv(signalResourcePath) { + const envUrl = (0, core_1.getStringFromEnv)('OTEL_EXPORTER_OTLP_ENDPOINT'); + if (envUrl === undefined) { + return undefined; + } + return appendResourcePathToUrl(envUrl, signalResourcePath); +} +function getSpecificUrlFromEnv(signalIdentifier) { + const envUrl = (0, core_1.getStringFromEnv)(`OTEL_EXPORTER_OTLP_${signalIdentifier}_ENDPOINT`); + if (envUrl === undefined) { + return undefined; + } + return appendRootPathToUrlIfNeeded(envUrl); +} +function readFileFromEnv(signalSpecificEnvVar, nonSignalSpecificEnvVar, warningMessage) { + const signalSpecificPath = (0, core_1.getStringFromEnv)(signalSpecificEnvVar); + const nonSignalSpecificPath = (0, core_1.getStringFromEnv)(nonSignalSpecificEnvVar); + const filePath = signalSpecificPath ?? nonSignalSpecificPath; + if (filePath != null) { + try { + return fs.readFileSync(path.resolve(process.cwd(), filePath)); + } + catch { + api_1.diag.warn(warningMessage); + return undefined; + } + } + else { + return undefined; + } +} +function getClientCertificateFromEnv(signalIdentifier) { + return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_CERTIFICATE`, 'OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE', 'Failed to read client certificate chain file'); +} +function getClientKeyFromEnv(signalIdentifier) { + return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_KEY`, 'OTEL_EXPORTER_OTLP_CLIENT_KEY', 'Failed to read client certificate private key file'); +} +function getRootCertificateFromEnv(signalIdentifier) { + return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CERTIFICATE`, 'OTEL_EXPORTER_OTLP_CERTIFICATE', 'Failed to read root certificate file'); +} +/** + * Reads and returns configuration from the environment + * + * @param signalIdentifier all caps part in environment variables that identifies the signal (e.g.: METRICS, TRACES, LOGS) + * @param signalResourcePath signal resource path to append if necessary (e.g.: v1/metrics, v1/traces, v1/logs) + */ +function getNodeHttpConfigurationFromEnvironment(signalIdentifier, signalResourcePath) { + return { + ...(0, shared_env_configuration_1.getSharedConfigurationFromEnvironment)(signalIdentifier), + url: getSpecificUrlFromEnv(signalIdentifier) ?? + getNonSpecificUrlFromEnv(signalResourcePath), + headers: (0, shared_configuration_1.wrapStaticHeadersInFunction)(getStaticHeadersFromEnv(signalIdentifier)), + agentFactory: (0, otlp_node_http_configuration_1.httpAgentFactoryFromOptions)({ + keepAlive: true, + ca: getRootCertificateFromEnv(signalIdentifier), + cert: getClientCertificateFromEnv(signalIdentifier), + key: getClientKeyFromEnv(signalIdentifier), + }), + }; +} +exports.getNodeHttpConfigurationFromEnvironment = getNodeHttpConfigurationFromEnvironment; +//# sourceMappingURL=otlp-node-http-env-configuration.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/shared-configuration.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/shared-configuration.js new file mode 100644 index 00000000..02dc8bbd --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/shared-configuration.js @@ -0,0 +1,60 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getSharedConfigurationDefaults = exports.mergeOtlpSharedConfigurationWithDefaults = exports.wrapStaticHeadersInFunction = exports.validateTimeoutMillis = void 0; +function validateTimeoutMillis(timeoutMillis) { + if (Number.isFinite(timeoutMillis) && timeoutMillis > 0) { + return timeoutMillis; + } + throw new Error(`Configuration: timeoutMillis is invalid, expected number greater than 0 (actual: '${timeoutMillis}')`); +} +exports.validateTimeoutMillis = validateTimeoutMillis; +function wrapStaticHeadersInFunction(headers) { + if (headers == null) { + return undefined; + } + return async () => headers; +} +exports.wrapStaticHeadersInFunction = wrapStaticHeadersInFunction; +/** + * @param userProvidedConfiguration Configuration options provided by the user in code. + * @param fallbackConfiguration Fallback to use when the {@link userProvidedConfiguration} does not specify an option. + * @param defaultConfiguration The defaults as defined by the exporter specification + */ +function mergeOtlpSharedConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration) { + return { + timeoutMillis: validateTimeoutMillis(userProvidedConfiguration.timeoutMillis ?? + fallbackConfiguration.timeoutMillis ?? + defaultConfiguration.timeoutMillis), + concurrencyLimit: userProvidedConfiguration.concurrencyLimit ?? + fallbackConfiguration.concurrencyLimit ?? + defaultConfiguration.concurrencyLimit, + compression: userProvidedConfiguration.compression ?? + fallbackConfiguration.compression ?? + defaultConfiguration.compression, + }; +} +exports.mergeOtlpSharedConfigurationWithDefaults = mergeOtlpSharedConfigurationWithDefaults; +function getSharedConfigurationDefaults() { + return { + timeoutMillis: 10000, + concurrencyLimit: 30, + compression: 'none', + }; +} +exports.getSharedConfigurationDefaults = getSharedConfigurationDefaults; +//# sourceMappingURL=shared-configuration.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/shared-env-configuration.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/shared-env-configuration.js new file mode 100644 index 00000000..9a222a18 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/shared-env-configuration.js @@ -0,0 +1,56 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getSharedConfigurationFromEnvironment = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const core_1 = require("@opentelemetry/core"); +const api_1 = require("@opentelemetry/api"); +function parseAndValidateTimeoutFromEnv(timeoutEnvVar) { + const envTimeout = (0, core_1.getNumberFromEnv)(timeoutEnvVar); + if (envTimeout != null) { + if (Number.isFinite(envTimeout) && envTimeout > 0) { + return envTimeout; + } + api_1.diag.warn(`Configuration: ${timeoutEnvVar} is invalid, expected number greater than 0 (actual: ${envTimeout})`); + } + return undefined; +} +function getTimeoutFromEnv(signalIdentifier) { + const specificTimeout = parseAndValidateTimeoutFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_TIMEOUT`); + const nonSpecificTimeout = parseAndValidateTimeoutFromEnv('OTEL_EXPORTER_OTLP_TIMEOUT'); + return specificTimeout ?? nonSpecificTimeout; +} +function parseAndValidateCompressionFromEnv(compressionEnvVar) { + const compression = (0, core_1.getStringFromEnv)(compressionEnvVar)?.trim(); + if (compression == null || compression === 'none' || compression === 'gzip') { + return compression; + } + api_1.diag.warn(`Configuration: ${compressionEnvVar} is invalid, expected 'none' or 'gzip' (actual: '${compression}')`); + return undefined; +} +function getCompressionFromEnv(signalIdentifier) { + const specificCompression = parseAndValidateCompressionFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_COMPRESSION`); + const nonSpecificCompression = parseAndValidateCompressionFromEnv('OTEL_EXPORTER_OTLP_COMPRESSION'); + return specificCompression ?? nonSpecificCompression; +} +function getSharedConfigurationFromEnvironment(signalIdentifier) { + return { + timeoutMillis: getTimeoutFromEnv(signalIdentifier), + compression: getCompressionFromEnv(signalIdentifier), + }; +} +exports.getSharedConfigurationFromEnvironment = getSharedConfigurationFromEnvironment; +//# sourceMappingURL=shared-env-configuration.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/index-node-http.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/index-node-http.js new file mode 100644 index 00000000..9aaadc5a --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/index-node-http.js @@ -0,0 +1,27 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.convertLegacyHttpOptions = exports.getSharedConfigurationFromEnvironment = exports.createOtlpHttpExportDelegate = exports.httpAgentFactoryFromOptions = void 0; +var otlp_node_http_configuration_1 = require("./configuration/otlp-node-http-configuration"); +Object.defineProperty(exports, "httpAgentFactoryFromOptions", { enumerable: true, get: function () { return otlp_node_http_configuration_1.httpAgentFactoryFromOptions; } }); +var otlp_http_export_delegate_1 = require("./otlp-http-export-delegate"); +Object.defineProperty(exports, "createOtlpHttpExportDelegate", { enumerable: true, get: function () { return otlp_http_export_delegate_1.createOtlpHttpExportDelegate; } }); +var shared_env_configuration_1 = require("./configuration/shared-env-configuration"); +Object.defineProperty(exports, "getSharedConfigurationFromEnvironment", { enumerable: true, get: function () { return shared_env_configuration_1.getSharedConfigurationFromEnvironment; } }); +var convert_legacy_node_http_options_1 = require("./configuration/convert-legacy-node-http-options"); +Object.defineProperty(exports, "convertLegacyHttpOptions", { enumerable: true, get: function () { return convert_legacy_node_http_options_1.convertLegacyHttpOptions; } }); +//# sourceMappingURL=index-node-http.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/index.js new file mode 100644 index 00000000..8d288f58 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/index.js @@ -0,0 +1,30 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createOtlpNetworkExportDelegate = exports.CompressionAlgorithm = exports.getSharedConfigurationDefaults = exports.mergeOtlpSharedConfigurationWithDefaults = exports.OTLPExporterError = exports.OTLPExporterBase = void 0; +var OTLPExporterBase_1 = require("./OTLPExporterBase"); +Object.defineProperty(exports, "OTLPExporterBase", { enumerable: true, get: function () { return OTLPExporterBase_1.OTLPExporterBase; } }); +var types_1 = require("./types"); +Object.defineProperty(exports, "OTLPExporterError", { enumerable: true, get: function () { return types_1.OTLPExporterError; } }); +var shared_configuration_1 = require("./configuration/shared-configuration"); +Object.defineProperty(exports, "mergeOtlpSharedConfigurationWithDefaults", { enumerable: true, get: function () { return shared_configuration_1.mergeOtlpSharedConfigurationWithDefaults; } }); +Object.defineProperty(exports, "getSharedConfigurationDefaults", { enumerable: true, get: function () { return shared_configuration_1.getSharedConfigurationDefaults; } }); +var legacy_node_configuration_1 = require("./configuration/legacy-node-configuration"); +Object.defineProperty(exports, "CompressionAlgorithm", { enumerable: true, get: function () { return legacy_node_configuration_1.CompressionAlgorithm; } }); +var otlp_network_export_delegate_1 = require("./otlp-network-export-delegate"); +Object.defineProperty(exports, "createOtlpNetworkExportDelegate", { enumerable: true, get: function () { return otlp_network_export_delegate_1.createOtlpNetworkExportDelegate; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/is-export-retryable.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/is-export-retryable.js new file mode 100644 index 00000000..8aa8d626 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/is-export-retryable.js @@ -0,0 +1,40 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseRetryAfterToMills = exports.isExportRetryable = void 0; +function isExportRetryable(statusCode) { + const retryCodes = [429, 502, 503, 504]; + return retryCodes.includes(statusCode); +} +exports.isExportRetryable = isExportRetryable; +function parseRetryAfterToMills(retryAfter) { + if (retryAfter == null) { + return undefined; + } + const seconds = Number.parseInt(retryAfter, 10); + if (Number.isInteger(seconds)) { + return seconds > 0 ? seconds * 1000 : -1; + } + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After#directives + const delay = new Date(retryAfter).getTime() - Date.now(); + if (delay >= 0) { + return delay; + } + return 0; +} +exports.parseRetryAfterToMills = parseRetryAfterToMills; +//# sourceMappingURL=is-export-retryable.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/logging-response-handler.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/logging-response-handler.js new file mode 100644 index 00000000..28dd66e4 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/logging-response-handler.js @@ -0,0 +1,42 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createLoggingPartialSuccessResponseHandler = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const api_1 = require("@opentelemetry/api"); +function isPartialSuccessResponse(response) { + return Object.prototype.hasOwnProperty.call(response, 'partialSuccess'); +} +/** + * Default response handler that logs a partial success to the console. + */ +function createLoggingPartialSuccessResponseHandler() { + return { + handleResponse(response) { + // Partial success MUST never be an empty object according the specification + // see https://opentelemetry.io/docs/specs/otlp/#partial-success + if (response == null || + !isPartialSuccessResponse(response) || + response.partialSuccess == null || + Object.keys(response.partialSuccess).length === 0) { + return; + } + api_1.diag.warn('Received Partial Success response:', JSON.stringify(response.partialSuccess)); + }, + }; +} +exports.createLoggingPartialSuccessResponseHandler = createLoggingPartialSuccessResponseHandler; +//# sourceMappingURL=logging-response-handler.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/otlp-export-delegate.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/otlp-export-delegate.js new file mode 100644 index 00000000..924bc3cf --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/otlp-export-delegate.js @@ -0,0 +1,115 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createOtlpExportDelegate = void 0; +const core_1 = require("@opentelemetry/core"); +const types_1 = require("./types"); +const logging_response_handler_1 = require("./logging-response-handler"); +const api_1 = require("@opentelemetry/api"); +class OTLPExportDelegate { + _transport; + _serializer; + _responseHandler; + _promiseQueue; + _timeout; + _diagLogger; + constructor(_transport, _serializer, _responseHandler, _promiseQueue, _timeout) { + this._transport = _transport; + this._serializer = _serializer; + this._responseHandler = _responseHandler; + this._promiseQueue = _promiseQueue; + this._timeout = _timeout; + this._diagLogger = api_1.diag.createComponentLogger({ + namespace: 'OTLPExportDelegate', + }); + } + export(internalRepresentation, resultCallback) { + this._diagLogger.debug('items to be sent', internalRepresentation); + // don't do any work if too many exports are in progress. + if (this._promiseQueue.hasReachedLimit()) { + resultCallback({ + code: core_1.ExportResultCode.FAILED, + error: new Error('Concurrent export limit reached'), + }); + return; + } + const serializedRequest = this._serializer.serializeRequest(internalRepresentation); + if (serializedRequest == null) { + resultCallback({ + code: core_1.ExportResultCode.FAILED, + error: new Error('Nothing to send'), + }); + return; + } + this._promiseQueue.pushPromise(this._transport.send(serializedRequest, this._timeout).then(response => { + if (response.status === 'success') { + if (response.data != null) { + try { + this._responseHandler.handleResponse(this._serializer.deserializeResponse(response.data)); + } + catch (e) { + this._diagLogger.warn('Export succeeded but could not deserialize response - is the response specification compliant?', e, response.data); + } + } + // No matter the response, we can consider the export still successful. + resultCallback({ + code: core_1.ExportResultCode.SUCCESS, + }); + return; + } + else if (response.status === 'failure' && response.error) { + resultCallback({ + code: core_1.ExportResultCode.FAILED, + error: response.error, + }); + return; + } + else if (response.status === 'retryable') { + resultCallback({ + code: core_1.ExportResultCode.FAILED, + error: new types_1.OTLPExporterError('Export failed with retryable status'), + }); + } + else { + resultCallback({ + code: core_1.ExportResultCode.FAILED, + error: new types_1.OTLPExporterError('Export failed with unknown error'), + }); + } + }, reason => resultCallback({ + code: core_1.ExportResultCode.FAILED, + error: reason, + }))); + } + forceFlush() { + return this._promiseQueue.awaitAll(); + } + async shutdown() { + this._diagLogger.debug('shutdown started'); + await this.forceFlush(); + this._transport.shutdown(); + } +} +/** + * Creates a generic delegate for OTLP exports which only contains parts of the OTLP export that are shared across all + * signals. + */ +function createOtlpExportDelegate(components, settings) { + return new OTLPExportDelegate(components.transport, components.serializer, (0, logging_response_handler_1.createLoggingPartialSuccessResponseHandler)(), components.promiseHandler, settings.timeout); +} +exports.createOtlpExportDelegate = createOtlpExportDelegate; +//# sourceMappingURL=otlp-export-delegate.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/otlp-http-export-delegate.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/otlp-http-export-delegate.js new file mode 100644 index 00000000..796577ad --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/otlp-http-export-delegate.js @@ -0,0 +1,33 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createOtlpHttpExportDelegate = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const otlp_export_delegate_1 = require("./otlp-export-delegate"); +const http_exporter_transport_1 = require("./transport/http-exporter-transport"); +const bounded_queue_export_promise_handler_1 = require("./bounded-queue-export-promise-handler"); +const retrying_transport_1 = require("./retrying-transport"); +function createOtlpHttpExportDelegate(options, serializer) { + return (0, otlp_export_delegate_1.createOtlpExportDelegate)({ + transport: (0, retrying_transport_1.createRetryingTransport)({ + transport: (0, http_exporter_transport_1.createHttpExporterTransport)(options), + }), + serializer: serializer, + promiseHandler: (0, bounded_queue_export_promise_handler_1.createBoundedQueueExportPromiseHandler)(options), + }, { timeout: options.timeoutMillis }); +} +exports.createOtlpHttpExportDelegate = createOtlpHttpExportDelegate; +//# sourceMappingURL=otlp-http-export-delegate.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/otlp-network-export-delegate.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/otlp-network-export-delegate.js new file mode 100644 index 00000000..064c7b73 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/otlp-network-export-delegate.js @@ -0,0 +1,29 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createOtlpNetworkExportDelegate = void 0; +const bounded_queue_export_promise_handler_1 = require("./bounded-queue-export-promise-handler"); +const otlp_export_delegate_1 = require("./otlp-export-delegate"); +function createOtlpNetworkExportDelegate(options, serializer, transport) { + return (0, otlp_export_delegate_1.createOtlpExportDelegate)({ + transport: transport, + serializer, + promiseHandler: (0, bounded_queue_export_promise_handler_1.createBoundedQueueExportPromiseHandler)(options), + }, { timeout: options.timeoutMillis }); +} +exports.createOtlpNetworkExportDelegate = createOtlpNetworkExportDelegate; +//# sourceMappingURL=otlp-network-export-delegate.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/retrying-transport.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/retrying-transport.js new file mode 100644 index 00000000..083013e3 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/retrying-transport.js @@ -0,0 +1,73 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createRetryingTransport = void 0; +const MAX_ATTEMPTS = 5; +const INITIAL_BACKOFF = 1000; +const MAX_BACKOFF = 5000; +const BACKOFF_MULTIPLIER = 1.5; +const JITTER = 0.2; +/** + * Get a pseudo-random jitter that falls in the range of [-JITTER, +JITTER] + */ +function getJitter() { + return Math.random() * (2 * JITTER) - JITTER; +} +class RetryingTransport { + _transport; + constructor(_transport) { + this._transport = _transport; + } + retry(data, timeoutMillis, inMillis) { + return new Promise((resolve, reject) => { + setTimeout(() => { + this._transport.send(data, timeoutMillis).then(resolve, reject); + }, inMillis); + }); + } + async send(data, timeoutMillis) { + const deadline = Date.now() + timeoutMillis; + let result = await this._transport.send(data, timeoutMillis); + let attempts = MAX_ATTEMPTS; + let nextBackoff = INITIAL_BACKOFF; + while (result.status === 'retryable' && attempts > 0) { + attempts--; + // use maximum of computed backoff and 0 to avoid negative timeouts + const backoff = Math.max(Math.min(nextBackoff, MAX_BACKOFF) + getJitter(), 0); + nextBackoff = nextBackoff * BACKOFF_MULTIPLIER; + const retryInMillis = result.retryInMillis ?? backoff; + // return when expected retry time is after the export deadline. + const remainingTimeoutMillis = deadline - Date.now(); + if (retryInMillis > remainingTimeoutMillis) { + return result; + } + result = await this.retry(data, remainingTimeoutMillis, retryInMillis); + } + return result; + } + shutdown() { + return this._transport.shutdown(); + } +} +/** + * Creates an Exporter Transport that retries on 'retryable' response. + */ +function createRetryingTransport(options) { + return new RetryingTransport(options.transport); +} +exports.createRetryingTransport = createRetryingTransport; +//# sourceMappingURL=retrying-transport.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/transport/http-exporter-transport.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/transport/http-exporter-transport.js new file mode 100644 index 00000000..b22cd8c5 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/transport/http-exporter-transport.js @@ -0,0 +1,60 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createHttpExporterTransport = void 0; +const http_transport_utils_1 = require("./http-transport-utils"); +class HttpExporterTransport { + _parameters; + _utils = null; + constructor(_parameters) { + this._parameters = _parameters; + } + async send(data, timeoutMillis) { + const { agent, request } = await this._loadUtils(); + const headers = await this._parameters.headers(); + return new Promise(resolve => { + (0, http_transport_utils_1.sendWithHttp)(request, this._parameters.url, headers, this._parameters.compression, this._parameters.userAgent, agent, data, result => { + resolve(result); + }, timeoutMillis); + }); + } + shutdown() { + // intentionally left empty, nothing to do. + } + async _loadUtils() { + let utils = this._utils; + if (utils === null) { + const protocol = new URL(this._parameters.url).protocol; + const [agent, request] = await Promise.all([ + this._parameters.agentFactory(protocol), + requestFunctionFactory(protocol), + ]); + utils = this._utils = { agent, request }; + } + return utils; + } +} +async function requestFunctionFactory(protocol) { + const module = protocol === 'http:' ? import('http') : import('https'); + const { request } = await module; + return request; +} +function createHttpExporterTransport(parameters) { + return new HttpExporterTransport(parameters); +} +exports.createHttpExporterTransport = createHttpExporterTransport; +//# sourceMappingURL=http-exporter-transport.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/transport/http-transport-utils.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/transport/http-transport-utils.js new file mode 100644 index 00000000..35ee0703 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/transport/http-transport-utils.js @@ -0,0 +1,99 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.compressAndSend = exports.sendWithHttp = void 0; +const zlib = require("zlib"); +const stream_1 = require("stream"); +const is_export_retryable_1 = require("../is-export-retryable"); +const types_1 = require("../types"); +const version_1 = require("../version"); +const DEFAULT_USER_AGENT = `OTel-OTLP-Exporter-JavaScript/${version_1.VERSION}`; +/** + * Sends data using http + * @param request + * @param params + * @param agent + * @param data + * @param onDone + * @param timeoutMillis + */ +function sendWithHttp(request, url, headers, compression, userAgent, agent, data, onDone, timeoutMillis) { + const parsedUrl = new URL(url); + if (userAgent) { + headers['User-Agent'] = `${userAgent} ${DEFAULT_USER_AGENT}`; + } + else { + headers['User-Agent'] = DEFAULT_USER_AGENT; + } + const options = { + hostname: parsedUrl.hostname, + port: parsedUrl.port, + path: parsedUrl.pathname, + method: 'POST', + headers, + agent, + }; + const req = request(options, (res) => { + const responseData = []; + res.on('data', chunk => responseData.push(chunk)); + res.on('end', () => { + if (res.statusCode && res.statusCode < 299) { + onDone({ + status: 'success', + data: Buffer.concat(responseData), + }); + } + else if (res.statusCode && (0, is_export_retryable_1.isExportRetryable)(res.statusCode)) { + onDone({ + status: 'retryable', + retryInMillis: (0, is_export_retryable_1.parseRetryAfterToMills)(res.headers['retry-after']), + }); + } + else { + const error = new types_1.OTLPExporterError(res.statusMessage, res.statusCode, Buffer.concat(responseData).toString()); + onDone({ + status: 'failure', + error, + }); + } + }); + }); + req.setTimeout(timeoutMillis, () => { + req.destroy(); + onDone({ + status: 'failure', + error: new Error('Request Timeout'), + }); + }); + req.on('error', (error) => { + onDone({ + status: 'failure', + error, + }); + }); + compressAndSend(req, compression, data, (error) => { + onDone({ + status: 'failure', + error, + }); + }); +} +exports.sendWithHttp = sendWithHttp; +function compressAndSend(req, compression, data, onError) { + let dataStream = readableFromUint8Array(data); + if (compression === 'gzip') { + req.setHeader('Content-Encoding', 'gzip'); + dataStream = dataStream + .on('error', onError) + .pipe(zlib.createGzip()) + .on('error', onError); + } + dataStream.pipe(req).on('error', onError); +} +exports.compressAndSend = compressAndSend; +function readableFromUint8Array(buff) { + const readable = new stream_1.Readable(); + readable.push(buff); + readable.push(null); + return readable; +} +//# sourceMappingURL=http-transport-utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/types.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/types.js new file mode 100644 index 00000000..3505fcf6 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/types.js @@ -0,0 +1,33 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OTLPExporterError = void 0; +/** + * Interface for handling error + */ +class OTLPExporterError extends Error { + code; + name = 'OTLPExporterError'; + data; + constructor(message, code, data) { + super(message); + this.data = data; + this.code = code; + } +} +exports.OTLPExporterError = OTLPExporterError; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/util.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/util.js new file mode 100644 index 00000000..e8a5edab --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/util.js @@ -0,0 +1,37 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateAndNormalizeHeaders = void 0; +const api_1 = require("@opentelemetry/api"); +/** + * Parses headers from config leaving only those that have defined values + * @param partialHeaders + */ +function validateAndNormalizeHeaders(partialHeaders) { + const headers = {}; + Object.entries(partialHeaders ?? {}).forEach(([key, value]) => { + if (typeof value !== 'undefined') { + headers[key] = String(value); + } + else { + api_1.diag.warn(`Header "${key}" has invalid value (${value}) and will be ignored`); + } + }); + return headers; +} +exports.validateAndNormalizeHeaders = validateAndNormalizeHeaders; +//# sourceMappingURL=util.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/version.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/version.js new file mode 100644 index 00000000..19056c5e --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/version.js @@ -0,0 +1,21 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.VERSION = void 0; +// this is autogenerated file, see scripts/version-update.js +exports.VERSION = '0.208.0'; +//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/convert-legacy-otlp-grpc-options.js b/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/convert-legacy-otlp-grpc-options.js new file mode 100644 index 00000000..382be6aa --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/convert-legacy-otlp-grpc-options.js @@ -0,0 +1,35 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.convertLegacyOtlpGrpcOptions = void 0; +const api_1 = require("@opentelemetry/api"); +const otlp_grpc_configuration_1 = require("./otlp-grpc-configuration"); +const grpc_exporter_transport_1 = require("../grpc-exporter-transport"); +const otlp_grpc_env_configuration_1 = require("./otlp-grpc-env-configuration"); +/** + * @deprecated + * @param config + * @param signalIdentifier + */ +function convertLegacyOtlpGrpcOptions(config, signalIdentifier) { + if (config.headers) { + api_1.diag.warn('Headers cannot be set when using grpc'); + } + // keep credentials locally in case user updates the reference on the config object + const userProvidedCredentials = config.credentials; + return (0, otlp_grpc_configuration_1.mergeOtlpGrpcConfigurationWithDefaults)({ + url: config.url, + metadata: () => { + // metadata resolution strategy is merge, so we can return empty here, and it will not override the rest of the settings. + return config.metadata ?? (0, grpc_exporter_transport_1.createEmptyMetadata)(); + }, + compression: config.compression, + timeoutMillis: config.timeoutMillis, + concurrencyLimit: config.concurrencyLimit, + credentials: userProvidedCredentials != null + ? () => userProvidedCredentials + : undefined, + userAgent: config.userAgent, + }, (0, otlp_grpc_env_configuration_1.getOtlpGrpcConfigurationFromEnv)(signalIdentifier), (0, otlp_grpc_configuration_1.getOtlpGrpcDefaultConfiguration)()); +} +exports.convertLegacyOtlpGrpcOptions = convertLegacyOtlpGrpcOptions; +//# sourceMappingURL=convert-legacy-otlp-grpc-options.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/otlp-grpc-configuration.js b/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/otlp-grpc-configuration.js new file mode 100644 index 00000000..545090cd --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/otlp-grpc-configuration.js @@ -0,0 +1,89 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getOtlpGrpcDefaultConfiguration = exports.mergeOtlpGrpcConfigurationWithDefaults = exports.validateAndNormalizeUrl = void 0; +const otlp_exporter_base_1 = require("@opentelemetry/otlp-exporter-base"); +const grpc_exporter_transport_1 = require("../grpc-exporter-transport"); +const url_1 = require("url"); +const api_1 = require("@opentelemetry/api"); +function validateAndNormalizeUrl(url) { + url = url.trim(); + const hasProtocol = url.match(/^([\w]{1,8}):\/\//); + if (!hasProtocol) { + url = `https://${url}`; + } + const target = new url_1.URL(url); + if (target.protocol === 'unix:') { + return url; + } + if (target.pathname && target.pathname !== '/') { + api_1.diag.warn('URL path should not be set when using grpc, the path part of the URL will be ignored.'); + } + if (target.protocol !== '' && !target.protocol?.match(/^(http)s?:$/)) { + api_1.diag.warn('URL protocol should be http(s)://. Using http://.'); + } + return target.host; +} +exports.validateAndNormalizeUrl = validateAndNormalizeUrl; +function overrideMetadataEntriesIfNotPresent(metadata, additionalMetadata) { + for (const [key, value] of Object.entries(additionalMetadata.getMap())) { + // only override with env var data if the key has no values. + // not using Metadata.merge() as it will keep both values. + if (metadata.get(key).length < 1) { + metadata.set(key, value); + } + } +} +function mergeOtlpGrpcConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration) { + const rawUrl = userProvidedConfiguration.url ?? + fallbackConfiguration.url ?? + defaultConfiguration.url; + return { + ...(0, otlp_exporter_base_1.mergeOtlpSharedConfigurationWithDefaults)(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration), + metadata: () => { + const metadata = defaultConfiguration.metadata(); + overrideMetadataEntriesIfNotPresent(metadata, + // clone to ensure we don't modify what the user gave us in case they hold on to the returned reference + userProvidedConfiguration.metadata?.().clone() ?? (0, grpc_exporter_transport_1.createEmptyMetadata)()); + overrideMetadataEntriesIfNotPresent(metadata, fallbackConfiguration.metadata?.() ?? (0, grpc_exporter_transport_1.createEmptyMetadata)()); + return metadata; + }, + url: validateAndNormalizeUrl(rawUrl), + credentials: userProvidedConfiguration.credentials ?? + fallbackConfiguration.credentials?.(rawUrl) ?? + defaultConfiguration.credentials(rawUrl), + userAgent: userProvidedConfiguration.userAgent, + }; +} +exports.mergeOtlpGrpcConfigurationWithDefaults = mergeOtlpGrpcConfigurationWithDefaults; +function getOtlpGrpcDefaultConfiguration() { + return { + ...(0, otlp_exporter_base_1.getSharedConfigurationDefaults)(), + metadata: () => (0, grpc_exporter_transport_1.createEmptyMetadata)(), + url: 'http://localhost:4317', + credentials: (url) => { + if (url.startsWith('http://')) { + return () => (0, grpc_exporter_transport_1.createInsecureCredentials)(); + } + else { + return () => (0, grpc_exporter_transport_1.createSslCredentials)(); + } + }, + }; +} +exports.getOtlpGrpcDefaultConfiguration = getOtlpGrpcDefaultConfiguration; +//# sourceMappingURL=otlp-grpc-configuration.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/otlp-grpc-env-configuration.js b/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/otlp-grpc-env-configuration.js new file mode 100644 index 00000000..292df421 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/otlp-grpc-env-configuration.js @@ -0,0 +1,159 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getOtlpGrpcConfigurationFromEnv = void 0; +const core_1 = require("@opentelemetry/core"); +const grpc_exporter_transport_1 = require("../grpc-exporter-transport"); +const node_http_1 = require("@opentelemetry/otlp-exporter-base/node-http"); +const fs = require("fs"); +const path = require("path"); +const api_1 = require("@opentelemetry/api"); +function fallbackIfNullishOrBlank(signalSpecific, nonSignalSpecific) { + if (signalSpecific != null && signalSpecific !== '') { + return signalSpecific; + } + if (nonSignalSpecific != null && nonSignalSpecific !== '') { + return nonSignalSpecific; + } + return undefined; +} +function getMetadataFromEnv(signalIdentifier) { + const signalSpecificRawHeaders = process.env[`OTEL_EXPORTER_OTLP_${signalIdentifier}_HEADERS`]?.trim(); + const nonSignalSpecificRawHeaders = process.env['OTEL_EXPORTER_OTLP_HEADERS']?.trim(); + const signalSpecificHeaders = (0, core_1.parseKeyPairsIntoRecord)(signalSpecificRawHeaders); + const nonSignalSpecificHeaders = (0, core_1.parseKeyPairsIntoRecord)(nonSignalSpecificRawHeaders); + if (Object.keys(signalSpecificHeaders).length === 0 && + Object.keys(nonSignalSpecificHeaders).length === 0) { + return undefined; + } + const mergeHeaders = Object.assign({}, nonSignalSpecificHeaders, signalSpecificHeaders); + const metadata = (0, grpc_exporter_transport_1.createEmptyMetadata)(); + // for this to work, metadata MUST be empty - otherwise `Metadata#set()` will merge items. + for (const [key, value] of Object.entries(mergeHeaders)) { + metadata.set(key, value); + } + return metadata; +} +function getMetadataProviderFromEnv(signalIdentifier) { + const metadata = getMetadataFromEnv(signalIdentifier); + if (metadata == null) { + return undefined; + } + return () => metadata; +} +function getUrlFromEnv(signalIdentifier) { + // This does not change the string beyond trimming on purpose. + // Normally a user would just use a host and port for gRPC, but the OTLP Exporter specification requires us to + // use the raw provided endpoint to derive credential settings. Therefore, we only normalize right when + // we merge user-provided, env-provided and defaults together, and we have determined which credentials to use. + // + // Examples: + // - example.test:4317 -> use secure credentials from environment (or provided via code) + // - http://example.test:4317 -> use insecure credentials if nothing else is provided + // - https://example.test:4317 -> use secure credentials from environment (or provided via code) + const specificEndpoint = process.env[`OTEL_EXPORTER_OTLP_${signalIdentifier}_ENDPOINT`]?.trim(); + const nonSpecificEndpoint = process.env[`OTEL_EXPORTER_OTLP_ENDPOINT`]?.trim(); + return fallbackIfNullishOrBlank(specificEndpoint, nonSpecificEndpoint); +} +/** + * Determines whether the env var for insecure credentials is set to {@code true}. + * + * It will allow the following values as {@code true} + * - 'true' + * - 'true ' + * - ' true' + * - 'TrUE' + * - 'TRUE' + * + * It will not allow: + * - 'true false' + * - 'false true' + * - 'true!' + * - 'true,true' + * - '1' + * - ' ' + * + * @param signalIdentifier + */ +function getInsecureSettingFromEnv(signalIdentifier) { + const signalSpecificInsecureValue = process.env[`OTEL_EXPORTER_OTLP_${signalIdentifier}_INSECURE`] + ?.toLowerCase() + .trim(); + const nonSignalSpecificInsecureValue = process.env[`OTEL_EXPORTER_OTLP_INSECURE`] + ?.toLowerCase() + .trim(); + return (fallbackIfNullishOrBlank(signalSpecificInsecureValue, nonSignalSpecificInsecureValue) === 'true'); +} +function readFileFromEnv(signalSpecificEnvVar, nonSignalSpecificEnvVar, warningMessage) { + const signalSpecificPath = process.env[signalSpecificEnvVar]?.trim(); + const nonSignalSpecificPath = process.env[nonSignalSpecificEnvVar]?.trim(); + const filePath = fallbackIfNullishOrBlank(signalSpecificPath, nonSignalSpecificPath); + if (filePath != null) { + try { + return fs.readFileSync(path.resolve(process.cwd(), filePath)); + } + catch { + api_1.diag.warn(warningMessage); + return undefined; + } + } + else { + return undefined; + } +} +function getClientCertificateFromEnv(signalIdentifier) { + return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_CERTIFICATE`, 'OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE', 'Failed to read client certificate chain file'); +} +function getClientKeyFromEnv(signalIdentifier) { + return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_KEY`, 'OTEL_EXPORTER_OTLP_CLIENT_KEY', 'Failed to read client certificate private key file'); +} +function getRootCertificateFromEnv(signalIdentifier) { + return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CERTIFICATE`, 'OTEL_EXPORTER_OTLP_CERTIFICATE', 'Failed to read root certificate file'); +} +function getCredentialsFromEnvIgnoreInsecure(signalIdentifier) { + const clientKey = getClientKeyFromEnv(signalIdentifier); + const clientCertificate = getClientCertificateFromEnv(signalIdentifier); + const rootCertificate = getRootCertificateFromEnv(signalIdentifier); + // if the chain is not intact, @grpc/grpc-js will throw. This is fine when a user provides it in code, but env var + // config is not allowed to throw, so we add this safeguard and try to make the best of it here. + const clientChainIntact = clientKey != null && clientCertificate != null; + if (rootCertificate != null && !clientChainIntact) { + api_1.diag.warn('Client key and certificate must both be provided, but one was missing - attempting to create credentials from just the root certificate'); + return (0, grpc_exporter_transport_1.createSslCredentials)(getRootCertificateFromEnv(signalIdentifier)); + } + return (0, grpc_exporter_transport_1.createSslCredentials)(rootCertificate, clientKey, clientCertificate); +} +function getCredentialsFromEnv(signalIdentifier) { + if (getInsecureSettingFromEnv(signalIdentifier)) { + return (0, grpc_exporter_transport_1.createInsecureCredentials)(); + } + return getCredentialsFromEnvIgnoreInsecure(signalIdentifier); +} +function getOtlpGrpcConfigurationFromEnv(signalIdentifier) { + return { + ...(0, node_http_1.getSharedConfigurationFromEnvironment)(signalIdentifier), + metadata: getMetadataProviderFromEnv(signalIdentifier), + url: getUrlFromEnv(signalIdentifier), + credentials: (finalResolvedUrl) => { + // Always assume insecure on http:// and secure on https://, the protocol always takes precedence over the insecure setting. + // note: the spec does not make any exception for + // - "localhost:4317". If the protocol is omitted, credentials are required unless insecure is set + // - "unix://", as it's neither http:// nor https:// and therefore credentials are required unless insecure is set + if (finalResolvedUrl.startsWith('http://')) { + return () => { + return (0, grpc_exporter_transport_1.createInsecureCredentials)(); + }; + } + else if (finalResolvedUrl.startsWith('https://')) { + return () => { + return getCredentialsFromEnvIgnoreInsecure(signalIdentifier); + }; + } + // defer to env settings in this case + return () => { + return getCredentialsFromEnv(signalIdentifier); + }; + }, + }; +} +exports.getOtlpGrpcConfigurationFromEnv = getOtlpGrpcConfigurationFromEnv; +//# sourceMappingURL=otlp-grpc-env-configuration.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/create-service-client-constructor.js b/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/create-service-client-constructor.js new file mode 100644 index 00000000..2327fd88 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/create-service-client-constructor.js @@ -0,0 +1,50 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createServiceClientConstructor = void 0; +const grpc = require("@grpc/grpc-js"); +/** + * Creates a unary service client constructor that, when instantiated, does not serialize/deserialize anything. + * Allows for passing in {@link Buffer} directly, serialization can be handled via protobufjs or custom implementations. + * + * @param path service path + * @param name service name + */ +function createServiceClientConstructor(path, name) { + const serviceDefinition = { + export: { + path: path, + requestStream: false, + responseStream: false, + requestSerialize: (arg) => { + return arg; + }, + requestDeserialize: (arg) => { + return arg; + }, + responseSerialize: (arg) => { + return arg; + }, + responseDeserialize: (arg) => { + return arg; + }, + }, + }; + return grpc.makeGenericClientConstructor(serviceDefinition, name); +} +exports.createServiceClientConstructor = createServiceClientConstructor; +//# sourceMappingURL=create-service-client-constructor.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/grpc-exporter-transport.js b/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/grpc-exporter-transport.js new file mode 100644 index 00000000..4bbc8353 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/grpc-exporter-transport.js @@ -0,0 +1,131 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createOtlpGrpcExporterTransport = exports.GrpcExporterTransport = exports.createEmptyMetadata = exports.createSslCredentials = exports.createInsecureCredentials = void 0; +const version_1 = require("./version"); +const DEFAULT_USER_AGENT = `OTel-OTLP-Exporter-JavaScript/${version_1.VERSION}`; +function createUserAgent(userAgent) { + if (userAgent) { + return `${userAgent} ${DEFAULT_USER_AGENT}`; + } + return DEFAULT_USER_AGENT; +} +// values taken from '@grpc/grpc-js` so that we don't need to require/import it. +const GRPC_COMPRESSION_NONE = 0; +const GRPC_COMPRESSION_GZIP = 2; +function toGrpcCompression(compression) { + return compression === 'gzip' ? GRPC_COMPRESSION_GZIP : GRPC_COMPRESSION_NONE; +} +function createInsecureCredentials() { + // Lazy-load so that we don't need to require/import '@grpc/grpc-js' before it can be wrapped by instrumentation. + const { credentials, + // eslint-disable-next-line @typescript-eslint/no-require-imports + } = require('@grpc/grpc-js'); + return credentials.createInsecure(); +} +exports.createInsecureCredentials = createInsecureCredentials; +function createSslCredentials(rootCert, privateKey, certChain) { + // Lazy-load so that we don't need to require/import '@grpc/grpc-js' before it can be wrapped by instrumentation. + const { credentials, + // eslint-disable-next-line @typescript-eslint/no-require-imports + } = require('@grpc/grpc-js'); + return credentials.createSsl(rootCert, privateKey, certChain); +} +exports.createSslCredentials = createSslCredentials; +function createEmptyMetadata() { + // Lazy-load so that we don't need to require/import '@grpc/grpc-js' before it can be wrapped by instrumentation. + const { Metadata, + // eslint-disable-next-line @typescript-eslint/no-require-imports + } = require('@grpc/grpc-js'); + return new Metadata(); +} +exports.createEmptyMetadata = createEmptyMetadata; +class GrpcExporterTransport { + _parameters; + _client; + _metadata; + constructor(_parameters) { + this._parameters = _parameters; + } + shutdown() { + this._client?.close(); + } + send(data, timeoutMillis) { + // We need to make a for gRPC + const buffer = Buffer.from(data); + if (this._client == null) { + // Lazy require to ensure that grpc is not loaded before instrumentations can wrap it + const { createServiceClientConstructor, + // eslint-disable-next-line @typescript-eslint/no-require-imports + } = require('./create-service-client-constructor'); + try { + this._metadata = this._parameters.metadata(); + } + catch (error) { + return Promise.resolve({ + status: 'failure', + error: error, + }); + } + const clientConstructor = createServiceClientConstructor(this._parameters.grpcPath, this._parameters.grpcName); + try { + this._client = new clientConstructor(this._parameters.address, this._parameters.credentials(), { + 'grpc.default_compression_algorithm': toGrpcCompression(this._parameters.compression), + 'grpc.primary_user_agent': createUserAgent(this._parameters.userAgent), + }); + } + catch (error) { + return Promise.resolve({ + status: 'failure', + error: error, + }); + } + } + return new Promise(resolve => { + const deadline = Date.now() + timeoutMillis; + // this should never happen + if (this._metadata == null) { + return resolve({ + error: new Error('metadata was null'), + status: 'failure', + }); + } + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore The gRPC client constructor is created on runtime, so we don't have any types for the resulting client. + this._client.export(buffer, this._metadata, { deadline: deadline }, (err, response) => { + if (err) { + resolve({ + status: 'failure', + error: err, + }); + } + else { + resolve({ + data: response, + status: 'success', + }); + } + }); + }); + } +} +exports.GrpcExporterTransport = GrpcExporterTransport; +function createOtlpGrpcExporterTransport(options) { + return new GrpcExporterTransport(options); +} +exports.createOtlpGrpcExporterTransport = createOtlpGrpcExporterTransport; +//# sourceMappingURL=grpc-exporter-transport.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/index.js new file mode 100644 index 00000000..f82eb1e7 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/index.js @@ -0,0 +1,23 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createOtlpGrpcExportDelegate = exports.convertLegacyOtlpGrpcOptions = void 0; +var convert_legacy_otlp_grpc_options_1 = require("./configuration/convert-legacy-otlp-grpc-options"); +Object.defineProperty(exports, "convertLegacyOtlpGrpcOptions", { enumerable: true, get: function () { return convert_legacy_otlp_grpc_options_1.convertLegacyOtlpGrpcOptions; } }); +var otlp_grpc_export_delegate_1 = require("./otlp-grpc-export-delegate"); +Object.defineProperty(exports, "createOtlpGrpcExportDelegate", { enumerable: true, get: function () { return otlp_grpc_export_delegate_1.createOtlpGrpcExportDelegate; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/otlp-grpc-export-delegate.js b/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/otlp-grpc-export-delegate.js new file mode 100644 index 00000000..6738005a --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/otlp-grpc-export-delegate.js @@ -0,0 +1,33 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createOtlpGrpcExportDelegate = void 0; +const otlp_exporter_base_1 = require("@opentelemetry/otlp-exporter-base"); +const grpc_exporter_transport_1 = require("./grpc-exporter-transport"); +function createOtlpGrpcExportDelegate(options, serializer, grpcName, grpcPath) { + return (0, otlp_exporter_base_1.createOtlpNetworkExportDelegate)(options, serializer, (0, grpc_exporter_transport_1.createOtlpGrpcExporterTransport)({ + address: options.url, + compression: options.compression, + credentials: options.credentials, + metadata: options.metadata, + userAgent: options.userAgent, + grpcName, + grpcPath, + })); +} +exports.createOtlpGrpcExportDelegate = createOtlpGrpcExportDelegate; +//# sourceMappingURL=otlp-grpc-export-delegate.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/version.js b/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/version.js new file mode 100644 index 00000000..19056c5e --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/version.js @@ -0,0 +1,21 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.VERSION = void 0; +// this is autogenerated file, see scripts/version-update.js +exports.VERSION = '0.208.0'; +//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/common/hex-to-binary.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/common/hex-to-binary.js new file mode 100644 index 00000000..48c7cb4e --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/common/hex-to-binary.js @@ -0,0 +1,42 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hexToBinary = void 0; +function intValue(charCode) { + // 0-9 + if (charCode >= 48 && charCode <= 57) { + return charCode - 48; + } + // a-f + if (charCode >= 97 && charCode <= 102) { + return charCode - 87; + } + // A-F + return charCode - 55; +} +function hexToBinary(hexStr) { + const buf = new Uint8Array(hexStr.length / 2); + let offset = 0; + for (let i = 0; i < hexStr.length; i += 2) { + const hi = intValue(hexStr.charCodeAt(i)); + const lo = intValue(hexStr.charCodeAt(i + 1)); + buf[offset++] = (hi << 4) | lo; + } + return buf; +} +exports.hexToBinary = hexToBinary; +//# sourceMappingURL=hex-to-binary.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/common/internal.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/common/internal.js new file mode 100644 index 00000000..0cdb555b --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/common/internal.js @@ -0,0 +1,57 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.toAnyValue = exports.toKeyValue = exports.toAttributes = exports.createInstrumentationScope = exports.createResource = void 0; +function createResource(resource) { + const result = { + attributes: toAttributes(resource.attributes), + droppedAttributesCount: 0, + }; + const schemaUrl = resource.schemaUrl; + if (schemaUrl && schemaUrl !== '') + result.schemaUrl = schemaUrl; + return result; +} +exports.createResource = createResource; +function createInstrumentationScope(scope) { + return { + name: scope.name, + version: scope.version, + }; +} +exports.createInstrumentationScope = createInstrumentationScope; +function toAttributes(attributes) { + return Object.keys(attributes).map(key => toKeyValue(key, attributes[key])); +} +exports.toAttributes = toAttributes; +function toKeyValue(key, value) { + return { + key: key, + value: toAnyValue(value), + }; +} +exports.toKeyValue = toKeyValue; +function toAnyValue(value) { + const t = typeof value; + if (t === 'string') + return { stringValue: value }; + if (t === 'number') { + if (!Number.isInteger(value)) + return { doubleValue: value }; + return { intValue: value }; + } + if (t === 'boolean') + return { boolValue: value }; + if (value instanceof Uint8Array) + return { bytesValue: value }; + if (Array.isArray(value)) + return { arrayValue: { values: value.map(toAnyValue) } }; + if (t === 'object' && value != null) + return { + kvlistValue: { + values: Object.entries(value).map(([k, v]) => toKeyValue(k, v)), + }, + }; + return {}; +} +exports.toAnyValue = toAnyValue; +//# sourceMappingURL=internal.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/common/utils.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/common/utils.js new file mode 100644 index 00000000..b612ddba --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/common/utils.js @@ -0,0 +1,69 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getOtlpEncoder = exports.encodeAsString = exports.encodeAsLongBits = exports.toLongBits = exports.hrTimeToNanos = void 0; +const core_1 = require("@opentelemetry/core"); +const hex_to_binary_1 = require("./hex-to-binary"); +function hrTimeToNanos(hrTime) { + const NANOSECONDS = BigInt(1000000000); + return (BigInt(Math.trunc(hrTime[0])) * NANOSECONDS + BigInt(Math.trunc(hrTime[1]))); +} +exports.hrTimeToNanos = hrTimeToNanos; +function toLongBits(value) { + const low = Number(BigInt.asUintN(32, value)); + const high = Number(BigInt.asUintN(32, value >> BigInt(32))); + return { low, high }; +} +exports.toLongBits = toLongBits; +function encodeAsLongBits(hrTime) { + const nanos = hrTimeToNanos(hrTime); + return toLongBits(nanos); +} +exports.encodeAsLongBits = encodeAsLongBits; +function encodeAsString(hrTime) { + const nanos = hrTimeToNanos(hrTime); + return nanos.toString(); +} +exports.encodeAsString = encodeAsString; +const encodeTimestamp = typeof BigInt !== 'undefined' ? encodeAsString : core_1.hrTimeToNanoseconds; +function identity(value) { + return value; +} +function optionalHexToBinary(str) { + if (str === undefined) + return undefined; + return (0, hex_to_binary_1.hexToBinary)(str); +} +const DEFAULT_ENCODER = { + encodeHrTime: encodeAsLongBits, + encodeSpanContext: hex_to_binary_1.hexToBinary, + encodeOptionalSpanContext: optionalHexToBinary, +}; +function getOtlpEncoder(options) { + if (options === undefined) { + return DEFAULT_ENCODER; + } + const useLongBits = options.useLongBits ?? true; + const useHex = options.useHex ?? false; + return { + encodeHrTime: useLongBits ? encodeAsLongBits : encodeTimestamp, + encodeSpanContext: useHex ? identity : hex_to_binary_1.hexToBinary, + encodeOptionalSpanContext: useHex ? identity : optionalHexToBinary, + }; +} +exports.getOtlpEncoder = getOtlpEncoder; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/generated/root.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/generated/root.js new file mode 100644 index 00000000..659530f3 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/generated/root.js @@ -0,0 +1,13299 @@ +/*eslint-disable block-scoped-var, id-length, no-control-regex, no-magic-numbers, no-prototype-builtins, no-redeclare, no-shadow, no-var, sort-vars*/ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var $protobuf = require("protobufjs/minimal"); +// Common aliases +var $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util; +// Exported root namespace +var $root = $protobuf.roots["default"] || ($protobuf.roots["default"] = {}); +$root.opentelemetry = (function () { + /** + * Namespace opentelemetry. + * @exports opentelemetry + * @namespace + */ + var opentelemetry = {}; + opentelemetry.proto = (function () { + /** + * Namespace proto. + * @memberof opentelemetry + * @namespace + */ + var proto = {}; + proto.common = (function () { + /** + * Namespace common. + * @memberof opentelemetry.proto + * @namespace + */ + var common = {}; + common.v1 = (function () { + /** + * Namespace v1. + * @memberof opentelemetry.proto.common + * @namespace + */ + var v1 = {}; + v1.AnyValue = (function () { + /** + * Properties of an AnyValue. + * @memberof opentelemetry.proto.common.v1 + * @interface IAnyValue + * @property {string|null} [stringValue] AnyValue stringValue + * @property {boolean|null} [boolValue] AnyValue boolValue + * @property {number|Long|null} [intValue] AnyValue intValue + * @property {number|null} [doubleValue] AnyValue doubleValue + * @property {opentelemetry.proto.common.v1.IArrayValue|null} [arrayValue] AnyValue arrayValue + * @property {opentelemetry.proto.common.v1.IKeyValueList|null} [kvlistValue] AnyValue kvlistValue + * @property {Uint8Array|null} [bytesValue] AnyValue bytesValue + */ + /** + * Constructs a new AnyValue. + * @memberof opentelemetry.proto.common.v1 + * @classdesc Represents an AnyValue. + * @implements IAnyValue + * @constructor + * @param {opentelemetry.proto.common.v1.IAnyValue=} [properties] Properties to set + */ + function AnyValue(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * AnyValue stringValue. + * @member {string|null|undefined} stringValue + * @memberof opentelemetry.proto.common.v1.AnyValue + * @instance + */ + AnyValue.prototype.stringValue = null; + /** + * AnyValue boolValue. + * @member {boolean|null|undefined} boolValue + * @memberof opentelemetry.proto.common.v1.AnyValue + * @instance + */ + AnyValue.prototype.boolValue = null; + /** + * AnyValue intValue. + * @member {number|Long|null|undefined} intValue + * @memberof opentelemetry.proto.common.v1.AnyValue + * @instance + */ + AnyValue.prototype.intValue = null; + /** + * AnyValue doubleValue. + * @member {number|null|undefined} doubleValue + * @memberof opentelemetry.proto.common.v1.AnyValue + * @instance + */ + AnyValue.prototype.doubleValue = null; + /** + * AnyValue arrayValue. + * @member {opentelemetry.proto.common.v1.IArrayValue|null|undefined} arrayValue + * @memberof opentelemetry.proto.common.v1.AnyValue + * @instance + */ + AnyValue.prototype.arrayValue = null; + /** + * AnyValue kvlistValue. + * @member {opentelemetry.proto.common.v1.IKeyValueList|null|undefined} kvlistValue + * @memberof opentelemetry.proto.common.v1.AnyValue + * @instance + */ + AnyValue.prototype.kvlistValue = null; + /** + * AnyValue bytesValue. + * @member {Uint8Array|null|undefined} bytesValue + * @memberof opentelemetry.proto.common.v1.AnyValue + * @instance + */ + AnyValue.prototype.bytesValue = null; + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + /** + * AnyValue value. + * @member {"stringValue"|"boolValue"|"intValue"|"doubleValue"|"arrayValue"|"kvlistValue"|"bytesValue"|undefined} value + * @memberof opentelemetry.proto.common.v1.AnyValue + * @instance + */ + Object.defineProperty(AnyValue.prototype, "value", { + get: $util.oneOfGetter($oneOfFields = ["stringValue", "boolValue", "intValue", "doubleValue", "arrayValue", "kvlistValue", "bytesValue"]), + set: $util.oneOfSetter($oneOfFields) + }); + /** + * Creates a new AnyValue instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.common.v1.AnyValue + * @static + * @param {opentelemetry.proto.common.v1.IAnyValue=} [properties] Properties to set + * @returns {opentelemetry.proto.common.v1.AnyValue} AnyValue instance + */ + AnyValue.create = function create(properties) { + return new AnyValue(properties); + }; + /** + * Encodes the specified AnyValue message. Does not implicitly {@link opentelemetry.proto.common.v1.AnyValue.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.common.v1.AnyValue + * @static + * @param {opentelemetry.proto.common.v1.IAnyValue} message AnyValue message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AnyValue.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.stringValue != null && Object.hasOwnProperty.call(message, "stringValue")) + writer.uint32(/* id 1, wireType 2 =*/ 10).string(message.stringValue); + if (message.boolValue != null && Object.hasOwnProperty.call(message, "boolValue")) + writer.uint32(/* id 2, wireType 0 =*/ 16).bool(message.boolValue); + if (message.intValue != null && Object.hasOwnProperty.call(message, "intValue")) + writer.uint32(/* id 3, wireType 0 =*/ 24).int64(message.intValue); + if (message.doubleValue != null && Object.hasOwnProperty.call(message, "doubleValue")) + writer.uint32(/* id 4, wireType 1 =*/ 33).double(message.doubleValue); + if (message.arrayValue != null && Object.hasOwnProperty.call(message, "arrayValue")) + $root.opentelemetry.proto.common.v1.ArrayValue.encode(message.arrayValue, writer.uint32(/* id 5, wireType 2 =*/ 42).fork()).ldelim(); + if (message.kvlistValue != null && Object.hasOwnProperty.call(message, "kvlistValue")) + $root.opentelemetry.proto.common.v1.KeyValueList.encode(message.kvlistValue, writer.uint32(/* id 6, wireType 2 =*/ 50).fork()).ldelim(); + if (message.bytesValue != null && Object.hasOwnProperty.call(message, "bytesValue")) + writer.uint32(/* id 7, wireType 2 =*/ 58).bytes(message.bytesValue); + return writer; + }; + /** + * Encodes the specified AnyValue message, length delimited. Does not implicitly {@link opentelemetry.proto.common.v1.AnyValue.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.common.v1.AnyValue + * @static + * @param {opentelemetry.proto.common.v1.IAnyValue} message AnyValue message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AnyValue.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes an AnyValue message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.common.v1.AnyValue + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.common.v1.AnyValue} AnyValue + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AnyValue.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.common.v1.AnyValue(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.stringValue = reader.string(); + break; + } + case 2: { + message.boolValue = reader.bool(); + break; + } + case 3: { + message.intValue = reader.int64(); + break; + } + case 4: { + message.doubleValue = reader.double(); + break; + } + case 5: { + message.arrayValue = $root.opentelemetry.proto.common.v1.ArrayValue.decode(reader, reader.uint32()); + break; + } + case 6: { + message.kvlistValue = $root.opentelemetry.proto.common.v1.KeyValueList.decode(reader, reader.uint32()); + break; + } + case 7: { + message.bytesValue = reader.bytes(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes an AnyValue message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.common.v1.AnyValue + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.common.v1.AnyValue} AnyValue + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AnyValue.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies an AnyValue message. + * @function verify + * @memberof opentelemetry.proto.common.v1.AnyValue + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + AnyValue.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.stringValue != null && message.hasOwnProperty("stringValue")) { + properties.value = 1; + if (!$util.isString(message.stringValue)) + return "stringValue: string expected"; + } + if (message.boolValue != null && message.hasOwnProperty("boolValue")) { + if (properties.value === 1) + return "value: multiple values"; + properties.value = 1; + if (typeof message.boolValue !== "boolean") + return "boolValue: boolean expected"; + } + if (message.intValue != null && message.hasOwnProperty("intValue")) { + if (properties.value === 1) + return "value: multiple values"; + properties.value = 1; + if (!$util.isInteger(message.intValue) && !(message.intValue && $util.isInteger(message.intValue.low) && $util.isInteger(message.intValue.high))) + return "intValue: integer|Long expected"; + } + if (message.doubleValue != null && message.hasOwnProperty("doubleValue")) { + if (properties.value === 1) + return "value: multiple values"; + properties.value = 1; + if (typeof message.doubleValue !== "number") + return "doubleValue: number expected"; + } + if (message.arrayValue != null && message.hasOwnProperty("arrayValue")) { + if (properties.value === 1) + return "value: multiple values"; + properties.value = 1; + { + var error = $root.opentelemetry.proto.common.v1.ArrayValue.verify(message.arrayValue); + if (error) + return "arrayValue." + error; + } + } + if (message.kvlistValue != null && message.hasOwnProperty("kvlistValue")) { + if (properties.value === 1) + return "value: multiple values"; + properties.value = 1; + { + var error = $root.opentelemetry.proto.common.v1.KeyValueList.verify(message.kvlistValue); + if (error) + return "kvlistValue." + error; + } + } + if (message.bytesValue != null && message.hasOwnProperty("bytesValue")) { + if (properties.value === 1) + return "value: multiple values"; + properties.value = 1; + if (!(message.bytesValue && typeof message.bytesValue.length === "number" || $util.isString(message.bytesValue))) + return "bytesValue: buffer expected"; + } + return null; + }; + /** + * Creates an AnyValue message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.common.v1.AnyValue + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.common.v1.AnyValue} AnyValue + */ + AnyValue.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.common.v1.AnyValue) + return object; + var message = new $root.opentelemetry.proto.common.v1.AnyValue(); + if (object.stringValue != null) + message.stringValue = String(object.stringValue); + if (object.boolValue != null) + message.boolValue = Boolean(object.boolValue); + if (object.intValue != null) + if ($util.Long) + (message.intValue = $util.Long.fromValue(object.intValue)).unsigned = false; + else if (typeof object.intValue === "string") + message.intValue = parseInt(object.intValue, 10); + else if (typeof object.intValue === "number") + message.intValue = object.intValue; + else if (typeof object.intValue === "object") + message.intValue = new $util.LongBits(object.intValue.low >>> 0, object.intValue.high >>> 0).toNumber(); + if (object.doubleValue != null) + message.doubleValue = Number(object.doubleValue); + if (object.arrayValue != null) { + if (typeof object.arrayValue !== "object") + throw TypeError(".opentelemetry.proto.common.v1.AnyValue.arrayValue: object expected"); + message.arrayValue = $root.opentelemetry.proto.common.v1.ArrayValue.fromObject(object.arrayValue); + } + if (object.kvlistValue != null) { + if (typeof object.kvlistValue !== "object") + throw TypeError(".opentelemetry.proto.common.v1.AnyValue.kvlistValue: object expected"); + message.kvlistValue = $root.opentelemetry.proto.common.v1.KeyValueList.fromObject(object.kvlistValue); + } + if (object.bytesValue != null) + if (typeof object.bytesValue === "string") + $util.base64.decode(object.bytesValue, message.bytesValue = $util.newBuffer($util.base64.length(object.bytesValue)), 0); + else if (object.bytesValue.length >= 0) + message.bytesValue = object.bytesValue; + return message; + }; + /** + * Creates a plain object from an AnyValue message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.common.v1.AnyValue + * @static + * @param {opentelemetry.proto.common.v1.AnyValue} message AnyValue + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + AnyValue.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.stringValue != null && message.hasOwnProperty("stringValue")) { + object.stringValue = message.stringValue; + if (options.oneofs) + object.value = "stringValue"; + } + if (message.boolValue != null && message.hasOwnProperty("boolValue")) { + object.boolValue = message.boolValue; + if (options.oneofs) + object.value = "boolValue"; + } + if (message.intValue != null && message.hasOwnProperty("intValue")) { + if (typeof message.intValue === "number") + object.intValue = options.longs === String ? String(message.intValue) : message.intValue; + else + object.intValue = options.longs === String ? $util.Long.prototype.toString.call(message.intValue) : options.longs === Number ? new $util.LongBits(message.intValue.low >>> 0, message.intValue.high >>> 0).toNumber() : message.intValue; + if (options.oneofs) + object.value = "intValue"; + } + if (message.doubleValue != null && message.hasOwnProperty("doubleValue")) { + object.doubleValue = options.json && !isFinite(message.doubleValue) ? String(message.doubleValue) : message.doubleValue; + if (options.oneofs) + object.value = "doubleValue"; + } + if (message.arrayValue != null && message.hasOwnProperty("arrayValue")) { + object.arrayValue = $root.opentelemetry.proto.common.v1.ArrayValue.toObject(message.arrayValue, options); + if (options.oneofs) + object.value = "arrayValue"; + } + if (message.kvlistValue != null && message.hasOwnProperty("kvlistValue")) { + object.kvlistValue = $root.opentelemetry.proto.common.v1.KeyValueList.toObject(message.kvlistValue, options); + if (options.oneofs) + object.value = "kvlistValue"; + } + if (message.bytesValue != null && message.hasOwnProperty("bytesValue")) { + object.bytesValue = options.bytes === String ? $util.base64.encode(message.bytesValue, 0, message.bytesValue.length) : options.bytes === Array ? Array.prototype.slice.call(message.bytesValue) : message.bytesValue; + if (options.oneofs) + object.value = "bytesValue"; + } + return object; + }; + /** + * Converts this AnyValue to JSON. + * @function toJSON + * @memberof opentelemetry.proto.common.v1.AnyValue + * @instance + * @returns {Object.} JSON object + */ + AnyValue.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for AnyValue + * @function getTypeUrl + * @memberof opentelemetry.proto.common.v1.AnyValue + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + AnyValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.common.v1.AnyValue"; + }; + return AnyValue; + })(); + v1.ArrayValue = (function () { + /** + * Properties of an ArrayValue. + * @memberof opentelemetry.proto.common.v1 + * @interface IArrayValue + * @property {Array.|null} [values] ArrayValue values + */ + /** + * Constructs a new ArrayValue. + * @memberof opentelemetry.proto.common.v1 + * @classdesc Represents an ArrayValue. + * @implements IArrayValue + * @constructor + * @param {opentelemetry.proto.common.v1.IArrayValue=} [properties] Properties to set + */ + function ArrayValue(properties) { + this.values = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * ArrayValue values. + * @member {Array.} values + * @memberof opentelemetry.proto.common.v1.ArrayValue + * @instance + */ + ArrayValue.prototype.values = $util.emptyArray; + /** + * Creates a new ArrayValue instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.common.v1.ArrayValue + * @static + * @param {opentelemetry.proto.common.v1.IArrayValue=} [properties] Properties to set + * @returns {opentelemetry.proto.common.v1.ArrayValue} ArrayValue instance + */ + ArrayValue.create = function create(properties) { + return new ArrayValue(properties); + }; + /** + * Encodes the specified ArrayValue message. Does not implicitly {@link opentelemetry.proto.common.v1.ArrayValue.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.common.v1.ArrayValue + * @static + * @param {opentelemetry.proto.common.v1.IArrayValue} message ArrayValue message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ArrayValue.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.values != null && message.values.length) + for (var i = 0; i < message.values.length; ++i) + $root.opentelemetry.proto.common.v1.AnyValue.encode(message.values[i], writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); + return writer; + }; + /** + * Encodes the specified ArrayValue message, length delimited. Does not implicitly {@link opentelemetry.proto.common.v1.ArrayValue.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.common.v1.ArrayValue + * @static + * @param {opentelemetry.proto.common.v1.IArrayValue} message ArrayValue message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ArrayValue.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes an ArrayValue message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.common.v1.ArrayValue + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.common.v1.ArrayValue} ArrayValue + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ArrayValue.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.common.v1.ArrayValue(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.values && message.values.length)) + message.values = []; + message.values.push($root.opentelemetry.proto.common.v1.AnyValue.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes an ArrayValue message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.common.v1.ArrayValue + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.common.v1.ArrayValue} ArrayValue + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ArrayValue.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies an ArrayValue message. + * @function verify + * @memberof opentelemetry.proto.common.v1.ArrayValue + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ArrayValue.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.values != null && message.hasOwnProperty("values")) { + if (!Array.isArray(message.values)) + return "values: array expected"; + for (var i = 0; i < message.values.length; ++i) { + var error = $root.opentelemetry.proto.common.v1.AnyValue.verify(message.values[i]); + if (error) + return "values." + error; + } + } + return null; + }; + /** + * Creates an ArrayValue message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.common.v1.ArrayValue + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.common.v1.ArrayValue} ArrayValue + */ + ArrayValue.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.common.v1.ArrayValue) + return object; + var message = new $root.opentelemetry.proto.common.v1.ArrayValue(); + if (object.values) { + if (!Array.isArray(object.values)) + throw TypeError(".opentelemetry.proto.common.v1.ArrayValue.values: array expected"); + message.values = []; + for (var i = 0; i < object.values.length; ++i) { + if (typeof object.values[i] !== "object") + throw TypeError(".opentelemetry.proto.common.v1.ArrayValue.values: object expected"); + message.values[i] = $root.opentelemetry.proto.common.v1.AnyValue.fromObject(object.values[i]); + } + } + return message; + }; + /** + * Creates a plain object from an ArrayValue message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.common.v1.ArrayValue + * @static + * @param {opentelemetry.proto.common.v1.ArrayValue} message ArrayValue + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ArrayValue.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.values = []; + if (message.values && message.values.length) { + object.values = []; + for (var j = 0; j < message.values.length; ++j) + object.values[j] = $root.opentelemetry.proto.common.v1.AnyValue.toObject(message.values[j], options); + } + return object; + }; + /** + * Converts this ArrayValue to JSON. + * @function toJSON + * @memberof opentelemetry.proto.common.v1.ArrayValue + * @instance + * @returns {Object.} JSON object + */ + ArrayValue.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for ArrayValue + * @function getTypeUrl + * @memberof opentelemetry.proto.common.v1.ArrayValue + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ArrayValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.common.v1.ArrayValue"; + }; + return ArrayValue; + })(); + v1.KeyValueList = (function () { + /** + * Properties of a KeyValueList. + * @memberof opentelemetry.proto.common.v1 + * @interface IKeyValueList + * @property {Array.|null} [values] KeyValueList values + */ + /** + * Constructs a new KeyValueList. + * @memberof opentelemetry.proto.common.v1 + * @classdesc Represents a KeyValueList. + * @implements IKeyValueList + * @constructor + * @param {opentelemetry.proto.common.v1.IKeyValueList=} [properties] Properties to set + */ + function KeyValueList(properties) { + this.values = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * KeyValueList values. + * @member {Array.} values + * @memberof opentelemetry.proto.common.v1.KeyValueList + * @instance + */ + KeyValueList.prototype.values = $util.emptyArray; + /** + * Creates a new KeyValueList instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.common.v1.KeyValueList + * @static + * @param {opentelemetry.proto.common.v1.IKeyValueList=} [properties] Properties to set + * @returns {opentelemetry.proto.common.v1.KeyValueList} KeyValueList instance + */ + KeyValueList.create = function create(properties) { + return new KeyValueList(properties); + }; + /** + * Encodes the specified KeyValueList message. Does not implicitly {@link opentelemetry.proto.common.v1.KeyValueList.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.common.v1.KeyValueList + * @static + * @param {opentelemetry.proto.common.v1.IKeyValueList} message KeyValueList message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + KeyValueList.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.values != null && message.values.length) + for (var i = 0; i < message.values.length; ++i) + $root.opentelemetry.proto.common.v1.KeyValue.encode(message.values[i], writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); + return writer; + }; + /** + * Encodes the specified KeyValueList message, length delimited. Does not implicitly {@link opentelemetry.proto.common.v1.KeyValueList.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.common.v1.KeyValueList + * @static + * @param {opentelemetry.proto.common.v1.IKeyValueList} message KeyValueList message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + KeyValueList.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes a KeyValueList message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.common.v1.KeyValueList + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.common.v1.KeyValueList} KeyValueList + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + KeyValueList.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.common.v1.KeyValueList(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.values && message.values.length)) + message.values = []; + message.values.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes a KeyValueList message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.common.v1.KeyValueList + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.common.v1.KeyValueList} KeyValueList + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + KeyValueList.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies a KeyValueList message. + * @function verify + * @memberof opentelemetry.proto.common.v1.KeyValueList + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + KeyValueList.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.values != null && message.hasOwnProperty("values")) { + if (!Array.isArray(message.values)) + return "values: array expected"; + for (var i = 0; i < message.values.length; ++i) { + var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.values[i]); + if (error) + return "values." + error; + } + } + return null; + }; + /** + * Creates a KeyValueList message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.common.v1.KeyValueList + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.common.v1.KeyValueList} KeyValueList + */ + KeyValueList.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.common.v1.KeyValueList) + return object; + var message = new $root.opentelemetry.proto.common.v1.KeyValueList(); + if (object.values) { + if (!Array.isArray(object.values)) + throw TypeError(".opentelemetry.proto.common.v1.KeyValueList.values: array expected"); + message.values = []; + for (var i = 0; i < object.values.length; ++i) { + if (typeof object.values[i] !== "object") + throw TypeError(".opentelemetry.proto.common.v1.KeyValueList.values: object expected"); + message.values[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.values[i]); + } + } + return message; + }; + /** + * Creates a plain object from a KeyValueList message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.common.v1.KeyValueList + * @static + * @param {opentelemetry.proto.common.v1.KeyValueList} message KeyValueList + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + KeyValueList.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.values = []; + if (message.values && message.values.length) { + object.values = []; + for (var j = 0; j < message.values.length; ++j) + object.values[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.values[j], options); + } + return object; + }; + /** + * Converts this KeyValueList to JSON. + * @function toJSON + * @memberof opentelemetry.proto.common.v1.KeyValueList + * @instance + * @returns {Object.} JSON object + */ + KeyValueList.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for KeyValueList + * @function getTypeUrl + * @memberof opentelemetry.proto.common.v1.KeyValueList + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + KeyValueList.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.common.v1.KeyValueList"; + }; + return KeyValueList; + })(); + v1.KeyValue = (function () { + /** + * Properties of a KeyValue. + * @memberof opentelemetry.proto.common.v1 + * @interface IKeyValue + * @property {string|null} [key] KeyValue key + * @property {opentelemetry.proto.common.v1.IAnyValue|null} [value] KeyValue value + */ + /** + * Constructs a new KeyValue. + * @memberof opentelemetry.proto.common.v1 + * @classdesc Represents a KeyValue. + * @implements IKeyValue + * @constructor + * @param {opentelemetry.proto.common.v1.IKeyValue=} [properties] Properties to set + */ + function KeyValue(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * KeyValue key. + * @member {string|null|undefined} key + * @memberof opentelemetry.proto.common.v1.KeyValue + * @instance + */ + KeyValue.prototype.key = null; + /** + * KeyValue value. + * @member {opentelemetry.proto.common.v1.IAnyValue|null|undefined} value + * @memberof opentelemetry.proto.common.v1.KeyValue + * @instance + */ + KeyValue.prototype.value = null; + /** + * Creates a new KeyValue instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.common.v1.KeyValue + * @static + * @param {opentelemetry.proto.common.v1.IKeyValue=} [properties] Properties to set + * @returns {opentelemetry.proto.common.v1.KeyValue} KeyValue instance + */ + KeyValue.create = function create(properties) { + return new KeyValue(properties); + }; + /** + * Encodes the specified KeyValue message. Does not implicitly {@link opentelemetry.proto.common.v1.KeyValue.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.common.v1.KeyValue + * @static + * @param {opentelemetry.proto.common.v1.IKeyValue} message KeyValue message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + KeyValue.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.key != null && Object.hasOwnProperty.call(message, "key")) + writer.uint32(/* id 1, wireType 2 =*/ 10).string(message.key); + if (message.value != null && Object.hasOwnProperty.call(message, "value")) + $root.opentelemetry.proto.common.v1.AnyValue.encode(message.value, writer.uint32(/* id 2, wireType 2 =*/ 18).fork()).ldelim(); + return writer; + }; + /** + * Encodes the specified KeyValue message, length delimited. Does not implicitly {@link opentelemetry.proto.common.v1.KeyValue.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.common.v1.KeyValue + * @static + * @param {opentelemetry.proto.common.v1.IKeyValue} message KeyValue message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + KeyValue.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes a KeyValue message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.common.v1.KeyValue + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.common.v1.KeyValue} KeyValue + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + KeyValue.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.common.v1.KeyValue(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.key = reader.string(); + break; + } + case 2: { + message.value = $root.opentelemetry.proto.common.v1.AnyValue.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes a KeyValue message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.common.v1.KeyValue + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.common.v1.KeyValue} KeyValue + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + KeyValue.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies a KeyValue message. + * @function verify + * @memberof opentelemetry.proto.common.v1.KeyValue + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + KeyValue.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.key != null && message.hasOwnProperty("key")) + if (!$util.isString(message.key)) + return "key: string expected"; + if (message.value != null && message.hasOwnProperty("value")) { + var error = $root.opentelemetry.proto.common.v1.AnyValue.verify(message.value); + if (error) + return "value." + error; + } + return null; + }; + /** + * Creates a KeyValue message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.common.v1.KeyValue + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.common.v1.KeyValue} KeyValue + */ + KeyValue.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.common.v1.KeyValue) + return object; + var message = new $root.opentelemetry.proto.common.v1.KeyValue(); + if (object.key != null) + message.key = String(object.key); + if (object.value != null) { + if (typeof object.value !== "object") + throw TypeError(".opentelemetry.proto.common.v1.KeyValue.value: object expected"); + message.value = $root.opentelemetry.proto.common.v1.AnyValue.fromObject(object.value); + } + return message; + }; + /** + * Creates a plain object from a KeyValue message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.common.v1.KeyValue + * @static + * @param {opentelemetry.proto.common.v1.KeyValue} message KeyValue + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + KeyValue.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.key = ""; + object.value = null; + } + if (message.key != null && message.hasOwnProperty("key")) + object.key = message.key; + if (message.value != null && message.hasOwnProperty("value")) + object.value = $root.opentelemetry.proto.common.v1.AnyValue.toObject(message.value, options); + return object; + }; + /** + * Converts this KeyValue to JSON. + * @function toJSON + * @memberof opentelemetry.proto.common.v1.KeyValue + * @instance + * @returns {Object.} JSON object + */ + KeyValue.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for KeyValue + * @function getTypeUrl + * @memberof opentelemetry.proto.common.v1.KeyValue + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + KeyValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.common.v1.KeyValue"; + }; + return KeyValue; + })(); + v1.InstrumentationScope = (function () { + /** + * Properties of an InstrumentationScope. + * @memberof opentelemetry.proto.common.v1 + * @interface IInstrumentationScope + * @property {string|null} [name] InstrumentationScope name + * @property {string|null} [version] InstrumentationScope version + * @property {Array.|null} [attributes] InstrumentationScope attributes + * @property {number|null} [droppedAttributesCount] InstrumentationScope droppedAttributesCount + */ + /** + * Constructs a new InstrumentationScope. + * @memberof opentelemetry.proto.common.v1 + * @classdesc Represents an InstrumentationScope. + * @implements IInstrumentationScope + * @constructor + * @param {opentelemetry.proto.common.v1.IInstrumentationScope=} [properties] Properties to set + */ + function InstrumentationScope(properties) { + this.attributes = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * InstrumentationScope name. + * @member {string|null|undefined} name + * @memberof opentelemetry.proto.common.v1.InstrumentationScope + * @instance + */ + InstrumentationScope.prototype.name = null; + /** + * InstrumentationScope version. + * @member {string|null|undefined} version + * @memberof opentelemetry.proto.common.v1.InstrumentationScope + * @instance + */ + InstrumentationScope.prototype.version = null; + /** + * InstrumentationScope attributes. + * @member {Array.} attributes + * @memberof opentelemetry.proto.common.v1.InstrumentationScope + * @instance + */ + InstrumentationScope.prototype.attributes = $util.emptyArray; + /** + * InstrumentationScope droppedAttributesCount. + * @member {number|null|undefined} droppedAttributesCount + * @memberof opentelemetry.proto.common.v1.InstrumentationScope + * @instance + */ + InstrumentationScope.prototype.droppedAttributesCount = null; + /** + * Creates a new InstrumentationScope instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.common.v1.InstrumentationScope + * @static + * @param {opentelemetry.proto.common.v1.IInstrumentationScope=} [properties] Properties to set + * @returns {opentelemetry.proto.common.v1.InstrumentationScope} InstrumentationScope instance + */ + InstrumentationScope.create = function create(properties) { + return new InstrumentationScope(properties); + }; + /** + * Encodes the specified InstrumentationScope message. Does not implicitly {@link opentelemetry.proto.common.v1.InstrumentationScope.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.common.v1.InstrumentationScope + * @static + * @param {opentelemetry.proto.common.v1.IInstrumentationScope} message InstrumentationScope message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + InstrumentationScope.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/ 10).string(message.name); + if (message.version != null && Object.hasOwnProperty.call(message, "version")) + writer.uint32(/* id 2, wireType 2 =*/ 18).string(message.version); + if (message.attributes != null && message.attributes.length) + for (var i = 0; i < message.attributes.length; ++i) + $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(/* id 3, wireType 2 =*/ 26).fork()).ldelim(); + if (message.droppedAttributesCount != null && Object.hasOwnProperty.call(message, "droppedAttributesCount")) + writer.uint32(/* id 4, wireType 0 =*/ 32).uint32(message.droppedAttributesCount); + return writer; + }; + /** + * Encodes the specified InstrumentationScope message, length delimited. Does not implicitly {@link opentelemetry.proto.common.v1.InstrumentationScope.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.common.v1.InstrumentationScope + * @static + * @param {opentelemetry.proto.common.v1.IInstrumentationScope} message InstrumentationScope message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + InstrumentationScope.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes an InstrumentationScope message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.common.v1.InstrumentationScope + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.common.v1.InstrumentationScope} InstrumentationScope + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + InstrumentationScope.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.common.v1.InstrumentationScope(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + case 2: { + message.version = reader.string(); + break; + } + case 3: { + if (!(message.attributes && message.attributes.length)) + message.attributes = []; + message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32())); + break; + } + case 4: { + message.droppedAttributesCount = reader.uint32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes an InstrumentationScope message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.common.v1.InstrumentationScope + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.common.v1.InstrumentationScope} InstrumentationScope + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + InstrumentationScope.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies an InstrumentationScope message. + * @function verify + * @memberof opentelemetry.proto.common.v1.InstrumentationScope + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + InstrumentationScope.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.version != null && message.hasOwnProperty("version")) + if (!$util.isString(message.version)) + return "version: string expected"; + if (message.attributes != null && message.hasOwnProperty("attributes")) { + if (!Array.isArray(message.attributes)) + return "attributes: array expected"; + for (var i = 0; i < message.attributes.length; ++i) { + var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]); + if (error) + return "attributes." + error; + } + } + if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) + if (!$util.isInteger(message.droppedAttributesCount)) + return "droppedAttributesCount: integer expected"; + return null; + }; + /** + * Creates an InstrumentationScope message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.common.v1.InstrumentationScope + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.common.v1.InstrumentationScope} InstrumentationScope + */ + InstrumentationScope.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.common.v1.InstrumentationScope) + return object; + var message = new $root.opentelemetry.proto.common.v1.InstrumentationScope(); + if (object.name != null) + message.name = String(object.name); + if (object.version != null) + message.version = String(object.version); + if (object.attributes) { + if (!Array.isArray(object.attributes)) + throw TypeError(".opentelemetry.proto.common.v1.InstrumentationScope.attributes: array expected"); + message.attributes = []; + for (var i = 0; i < object.attributes.length; ++i) { + if (typeof object.attributes[i] !== "object") + throw TypeError(".opentelemetry.proto.common.v1.InstrumentationScope.attributes: object expected"); + message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]); + } + } + if (object.droppedAttributesCount != null) + message.droppedAttributesCount = object.droppedAttributesCount >>> 0; + return message; + }; + /** + * Creates a plain object from an InstrumentationScope message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.common.v1.InstrumentationScope + * @static + * @param {opentelemetry.proto.common.v1.InstrumentationScope} message InstrumentationScope + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + InstrumentationScope.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.attributes = []; + if (options.defaults) { + object.name = ""; + object.version = ""; + object.droppedAttributesCount = 0; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.version != null && message.hasOwnProperty("version")) + object.version = message.version; + if (message.attributes && message.attributes.length) { + object.attributes = []; + for (var j = 0; j < message.attributes.length; ++j) + object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options); + } + if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) + object.droppedAttributesCount = message.droppedAttributesCount; + return object; + }; + /** + * Converts this InstrumentationScope to JSON. + * @function toJSON + * @memberof opentelemetry.proto.common.v1.InstrumentationScope + * @instance + * @returns {Object.} JSON object + */ + InstrumentationScope.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for InstrumentationScope + * @function getTypeUrl + * @memberof opentelemetry.proto.common.v1.InstrumentationScope + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + InstrumentationScope.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.common.v1.InstrumentationScope"; + }; + return InstrumentationScope; + })(); + v1.EntityRef = (function () { + /** + * Properties of an EntityRef. + * @memberof opentelemetry.proto.common.v1 + * @interface IEntityRef + * @property {string|null} [schemaUrl] EntityRef schemaUrl + * @property {string|null} [type] EntityRef type + * @property {Array.|null} [idKeys] EntityRef idKeys + * @property {Array.|null} [descriptionKeys] EntityRef descriptionKeys + */ + /** + * Constructs a new EntityRef. + * @memberof opentelemetry.proto.common.v1 + * @classdesc Represents an EntityRef. + * @implements IEntityRef + * @constructor + * @param {opentelemetry.proto.common.v1.IEntityRef=} [properties] Properties to set + */ + function EntityRef(properties) { + this.idKeys = []; + this.descriptionKeys = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * EntityRef schemaUrl. + * @member {string|null|undefined} schemaUrl + * @memberof opentelemetry.proto.common.v1.EntityRef + * @instance + */ + EntityRef.prototype.schemaUrl = null; + /** + * EntityRef type. + * @member {string|null|undefined} type + * @memberof opentelemetry.proto.common.v1.EntityRef + * @instance + */ + EntityRef.prototype.type = null; + /** + * EntityRef idKeys. + * @member {Array.} idKeys + * @memberof opentelemetry.proto.common.v1.EntityRef + * @instance + */ + EntityRef.prototype.idKeys = $util.emptyArray; + /** + * EntityRef descriptionKeys. + * @member {Array.} descriptionKeys + * @memberof opentelemetry.proto.common.v1.EntityRef + * @instance + */ + EntityRef.prototype.descriptionKeys = $util.emptyArray; + /** + * Creates a new EntityRef instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.common.v1.EntityRef + * @static + * @param {opentelemetry.proto.common.v1.IEntityRef=} [properties] Properties to set + * @returns {opentelemetry.proto.common.v1.EntityRef} EntityRef instance + */ + EntityRef.create = function create(properties) { + return new EntityRef(properties); + }; + /** + * Encodes the specified EntityRef message. Does not implicitly {@link opentelemetry.proto.common.v1.EntityRef.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.common.v1.EntityRef + * @static + * @param {opentelemetry.proto.common.v1.IEntityRef} message EntityRef message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + EntityRef.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.schemaUrl != null && Object.hasOwnProperty.call(message, "schemaUrl")) + writer.uint32(/* id 1, wireType 2 =*/ 10).string(message.schemaUrl); + if (message.type != null && Object.hasOwnProperty.call(message, "type")) + writer.uint32(/* id 2, wireType 2 =*/ 18).string(message.type); + if (message.idKeys != null && message.idKeys.length) + for (var i = 0; i < message.idKeys.length; ++i) + writer.uint32(/* id 3, wireType 2 =*/ 26).string(message.idKeys[i]); + if (message.descriptionKeys != null && message.descriptionKeys.length) + for (var i = 0; i < message.descriptionKeys.length; ++i) + writer.uint32(/* id 4, wireType 2 =*/ 34).string(message.descriptionKeys[i]); + return writer; + }; + /** + * Encodes the specified EntityRef message, length delimited. Does not implicitly {@link opentelemetry.proto.common.v1.EntityRef.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.common.v1.EntityRef + * @static + * @param {opentelemetry.proto.common.v1.IEntityRef} message EntityRef message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + EntityRef.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes an EntityRef message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.common.v1.EntityRef + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.common.v1.EntityRef} EntityRef + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + EntityRef.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.common.v1.EntityRef(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.schemaUrl = reader.string(); + break; + } + case 2: { + message.type = reader.string(); + break; + } + case 3: { + if (!(message.idKeys && message.idKeys.length)) + message.idKeys = []; + message.idKeys.push(reader.string()); + break; + } + case 4: { + if (!(message.descriptionKeys && message.descriptionKeys.length)) + message.descriptionKeys = []; + message.descriptionKeys.push(reader.string()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes an EntityRef message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.common.v1.EntityRef + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.common.v1.EntityRef} EntityRef + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + EntityRef.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies an EntityRef message. + * @function verify + * @memberof opentelemetry.proto.common.v1.EntityRef + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + EntityRef.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) + if (!$util.isString(message.schemaUrl)) + return "schemaUrl: string expected"; + if (message.type != null && message.hasOwnProperty("type")) + if (!$util.isString(message.type)) + return "type: string expected"; + if (message.idKeys != null && message.hasOwnProperty("idKeys")) { + if (!Array.isArray(message.idKeys)) + return "idKeys: array expected"; + for (var i = 0; i < message.idKeys.length; ++i) + if (!$util.isString(message.idKeys[i])) + return "idKeys: string[] expected"; + } + if (message.descriptionKeys != null && message.hasOwnProperty("descriptionKeys")) { + if (!Array.isArray(message.descriptionKeys)) + return "descriptionKeys: array expected"; + for (var i = 0; i < message.descriptionKeys.length; ++i) + if (!$util.isString(message.descriptionKeys[i])) + return "descriptionKeys: string[] expected"; + } + return null; + }; + /** + * Creates an EntityRef message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.common.v1.EntityRef + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.common.v1.EntityRef} EntityRef + */ + EntityRef.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.common.v1.EntityRef) + return object; + var message = new $root.opentelemetry.proto.common.v1.EntityRef(); + if (object.schemaUrl != null) + message.schemaUrl = String(object.schemaUrl); + if (object.type != null) + message.type = String(object.type); + if (object.idKeys) { + if (!Array.isArray(object.idKeys)) + throw TypeError(".opentelemetry.proto.common.v1.EntityRef.idKeys: array expected"); + message.idKeys = []; + for (var i = 0; i < object.idKeys.length; ++i) + message.idKeys[i] = String(object.idKeys[i]); + } + if (object.descriptionKeys) { + if (!Array.isArray(object.descriptionKeys)) + throw TypeError(".opentelemetry.proto.common.v1.EntityRef.descriptionKeys: array expected"); + message.descriptionKeys = []; + for (var i = 0; i < object.descriptionKeys.length; ++i) + message.descriptionKeys[i] = String(object.descriptionKeys[i]); + } + return message; + }; + /** + * Creates a plain object from an EntityRef message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.common.v1.EntityRef + * @static + * @param {opentelemetry.proto.common.v1.EntityRef} message EntityRef + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EntityRef.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.idKeys = []; + object.descriptionKeys = []; + } + if (options.defaults) { + object.schemaUrl = ""; + object.type = ""; + } + if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) + object.schemaUrl = message.schemaUrl; + if (message.type != null && message.hasOwnProperty("type")) + object.type = message.type; + if (message.idKeys && message.idKeys.length) { + object.idKeys = []; + for (var j = 0; j < message.idKeys.length; ++j) + object.idKeys[j] = message.idKeys[j]; + } + if (message.descriptionKeys && message.descriptionKeys.length) { + object.descriptionKeys = []; + for (var j = 0; j < message.descriptionKeys.length; ++j) + object.descriptionKeys[j] = message.descriptionKeys[j]; + } + return object; + }; + /** + * Converts this EntityRef to JSON. + * @function toJSON + * @memberof opentelemetry.proto.common.v1.EntityRef + * @instance + * @returns {Object.} JSON object + */ + EntityRef.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for EntityRef + * @function getTypeUrl + * @memberof opentelemetry.proto.common.v1.EntityRef + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EntityRef.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.common.v1.EntityRef"; + }; + return EntityRef; + })(); + return v1; + })(); + return common; + })(); + proto.resource = (function () { + /** + * Namespace resource. + * @memberof opentelemetry.proto + * @namespace + */ + var resource = {}; + resource.v1 = (function () { + /** + * Namespace v1. + * @memberof opentelemetry.proto.resource + * @namespace + */ + var v1 = {}; + v1.Resource = (function () { + /** + * Properties of a Resource. + * @memberof opentelemetry.proto.resource.v1 + * @interface IResource + * @property {Array.|null} [attributes] Resource attributes + * @property {number|null} [droppedAttributesCount] Resource droppedAttributesCount + * @property {Array.|null} [entityRefs] Resource entityRefs + */ + /** + * Constructs a new Resource. + * @memberof opentelemetry.proto.resource.v1 + * @classdesc Represents a Resource. + * @implements IResource + * @constructor + * @param {opentelemetry.proto.resource.v1.IResource=} [properties] Properties to set + */ + function Resource(properties) { + this.attributes = []; + this.entityRefs = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * Resource attributes. + * @member {Array.} attributes + * @memberof opentelemetry.proto.resource.v1.Resource + * @instance + */ + Resource.prototype.attributes = $util.emptyArray; + /** + * Resource droppedAttributesCount. + * @member {number|null|undefined} droppedAttributesCount + * @memberof opentelemetry.proto.resource.v1.Resource + * @instance + */ + Resource.prototype.droppedAttributesCount = null; + /** + * Resource entityRefs. + * @member {Array.} entityRefs + * @memberof opentelemetry.proto.resource.v1.Resource + * @instance + */ + Resource.prototype.entityRefs = $util.emptyArray; + /** + * Creates a new Resource instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.resource.v1.Resource + * @static + * @param {opentelemetry.proto.resource.v1.IResource=} [properties] Properties to set + * @returns {opentelemetry.proto.resource.v1.Resource} Resource instance + */ + Resource.create = function create(properties) { + return new Resource(properties); + }; + /** + * Encodes the specified Resource message. Does not implicitly {@link opentelemetry.proto.resource.v1.Resource.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.resource.v1.Resource + * @static + * @param {opentelemetry.proto.resource.v1.IResource} message Resource message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Resource.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.attributes != null && message.attributes.length) + for (var i = 0; i < message.attributes.length; ++i) + $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); + if (message.droppedAttributesCount != null && Object.hasOwnProperty.call(message, "droppedAttributesCount")) + writer.uint32(/* id 2, wireType 0 =*/ 16).uint32(message.droppedAttributesCount); + if (message.entityRefs != null && message.entityRefs.length) + for (var i = 0; i < message.entityRefs.length; ++i) + $root.opentelemetry.proto.common.v1.EntityRef.encode(message.entityRefs[i], writer.uint32(/* id 3, wireType 2 =*/ 26).fork()).ldelim(); + return writer; + }; + /** + * Encodes the specified Resource message, length delimited. Does not implicitly {@link opentelemetry.proto.resource.v1.Resource.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.resource.v1.Resource + * @static + * @param {opentelemetry.proto.resource.v1.IResource} message Resource message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Resource.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes a Resource message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.resource.v1.Resource + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.resource.v1.Resource} Resource + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Resource.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.resource.v1.Resource(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.attributes && message.attributes.length)) + message.attributes = []; + message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32())); + break; + } + case 2: { + message.droppedAttributesCount = reader.uint32(); + break; + } + case 3: { + if (!(message.entityRefs && message.entityRefs.length)) + message.entityRefs = []; + message.entityRefs.push($root.opentelemetry.proto.common.v1.EntityRef.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes a Resource message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.resource.v1.Resource + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.resource.v1.Resource} Resource + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Resource.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies a Resource message. + * @function verify + * @memberof opentelemetry.proto.resource.v1.Resource + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Resource.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.attributes != null && message.hasOwnProperty("attributes")) { + if (!Array.isArray(message.attributes)) + return "attributes: array expected"; + for (var i = 0; i < message.attributes.length; ++i) { + var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]); + if (error) + return "attributes." + error; + } + } + if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) + if (!$util.isInteger(message.droppedAttributesCount)) + return "droppedAttributesCount: integer expected"; + if (message.entityRefs != null && message.hasOwnProperty("entityRefs")) { + if (!Array.isArray(message.entityRefs)) + return "entityRefs: array expected"; + for (var i = 0; i < message.entityRefs.length; ++i) { + var error = $root.opentelemetry.proto.common.v1.EntityRef.verify(message.entityRefs[i]); + if (error) + return "entityRefs." + error; + } + } + return null; + }; + /** + * Creates a Resource message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.resource.v1.Resource + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.resource.v1.Resource} Resource + */ + Resource.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.resource.v1.Resource) + return object; + var message = new $root.opentelemetry.proto.resource.v1.Resource(); + if (object.attributes) { + if (!Array.isArray(object.attributes)) + throw TypeError(".opentelemetry.proto.resource.v1.Resource.attributes: array expected"); + message.attributes = []; + for (var i = 0; i < object.attributes.length; ++i) { + if (typeof object.attributes[i] !== "object") + throw TypeError(".opentelemetry.proto.resource.v1.Resource.attributes: object expected"); + message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]); + } + } + if (object.droppedAttributesCount != null) + message.droppedAttributesCount = object.droppedAttributesCount >>> 0; + if (object.entityRefs) { + if (!Array.isArray(object.entityRefs)) + throw TypeError(".opentelemetry.proto.resource.v1.Resource.entityRefs: array expected"); + message.entityRefs = []; + for (var i = 0; i < object.entityRefs.length; ++i) { + if (typeof object.entityRefs[i] !== "object") + throw TypeError(".opentelemetry.proto.resource.v1.Resource.entityRefs: object expected"); + message.entityRefs[i] = $root.opentelemetry.proto.common.v1.EntityRef.fromObject(object.entityRefs[i]); + } + } + return message; + }; + /** + * Creates a plain object from a Resource message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.resource.v1.Resource + * @static + * @param {opentelemetry.proto.resource.v1.Resource} message Resource + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Resource.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.attributes = []; + object.entityRefs = []; + } + if (options.defaults) + object.droppedAttributesCount = 0; + if (message.attributes && message.attributes.length) { + object.attributes = []; + for (var j = 0; j < message.attributes.length; ++j) + object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options); + } + if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) + object.droppedAttributesCount = message.droppedAttributesCount; + if (message.entityRefs && message.entityRefs.length) { + object.entityRefs = []; + for (var j = 0; j < message.entityRefs.length; ++j) + object.entityRefs[j] = $root.opentelemetry.proto.common.v1.EntityRef.toObject(message.entityRefs[j], options); + } + return object; + }; + /** + * Converts this Resource to JSON. + * @function toJSON + * @memberof opentelemetry.proto.resource.v1.Resource + * @instance + * @returns {Object.} JSON object + */ + Resource.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for Resource + * @function getTypeUrl + * @memberof opentelemetry.proto.resource.v1.Resource + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Resource.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.resource.v1.Resource"; + }; + return Resource; + })(); + return v1; + })(); + return resource; + })(); + proto.trace = (function () { + /** + * Namespace trace. + * @memberof opentelemetry.proto + * @namespace + */ + var trace = {}; + trace.v1 = (function () { + /** + * Namespace v1. + * @memberof opentelemetry.proto.trace + * @namespace + */ + var v1 = {}; + v1.TracesData = (function () { + /** + * Properties of a TracesData. + * @memberof opentelemetry.proto.trace.v1 + * @interface ITracesData + * @property {Array.|null} [resourceSpans] TracesData resourceSpans + */ + /** + * Constructs a new TracesData. + * @memberof opentelemetry.proto.trace.v1 + * @classdesc Represents a TracesData. + * @implements ITracesData + * @constructor + * @param {opentelemetry.proto.trace.v1.ITracesData=} [properties] Properties to set + */ + function TracesData(properties) { + this.resourceSpans = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * TracesData resourceSpans. + * @member {Array.} resourceSpans + * @memberof opentelemetry.proto.trace.v1.TracesData + * @instance + */ + TracesData.prototype.resourceSpans = $util.emptyArray; + /** + * Creates a new TracesData instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.trace.v1.TracesData + * @static + * @param {opentelemetry.proto.trace.v1.ITracesData=} [properties] Properties to set + * @returns {opentelemetry.proto.trace.v1.TracesData} TracesData instance + */ + TracesData.create = function create(properties) { + return new TracesData(properties); + }; + /** + * Encodes the specified TracesData message. Does not implicitly {@link opentelemetry.proto.trace.v1.TracesData.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.trace.v1.TracesData + * @static + * @param {opentelemetry.proto.trace.v1.ITracesData} message TracesData message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + TracesData.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.resourceSpans != null && message.resourceSpans.length) + for (var i = 0; i < message.resourceSpans.length; ++i) + $root.opentelemetry.proto.trace.v1.ResourceSpans.encode(message.resourceSpans[i], writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); + return writer; + }; + /** + * Encodes the specified TracesData message, length delimited. Does not implicitly {@link opentelemetry.proto.trace.v1.TracesData.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.trace.v1.TracesData + * @static + * @param {opentelemetry.proto.trace.v1.ITracesData} message TracesData message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + TracesData.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes a TracesData message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.trace.v1.TracesData + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.trace.v1.TracesData} TracesData + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + TracesData.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.trace.v1.TracesData(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.resourceSpans && message.resourceSpans.length)) + message.resourceSpans = []; + message.resourceSpans.push($root.opentelemetry.proto.trace.v1.ResourceSpans.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes a TracesData message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.trace.v1.TracesData + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.trace.v1.TracesData} TracesData + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + TracesData.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies a TracesData message. + * @function verify + * @memberof opentelemetry.proto.trace.v1.TracesData + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + TracesData.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.resourceSpans != null && message.hasOwnProperty("resourceSpans")) { + if (!Array.isArray(message.resourceSpans)) + return "resourceSpans: array expected"; + for (var i = 0; i < message.resourceSpans.length; ++i) { + var error = $root.opentelemetry.proto.trace.v1.ResourceSpans.verify(message.resourceSpans[i]); + if (error) + return "resourceSpans." + error; + } + } + return null; + }; + /** + * Creates a TracesData message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.trace.v1.TracesData + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.trace.v1.TracesData} TracesData + */ + TracesData.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.trace.v1.TracesData) + return object; + var message = new $root.opentelemetry.proto.trace.v1.TracesData(); + if (object.resourceSpans) { + if (!Array.isArray(object.resourceSpans)) + throw TypeError(".opentelemetry.proto.trace.v1.TracesData.resourceSpans: array expected"); + message.resourceSpans = []; + for (var i = 0; i < object.resourceSpans.length; ++i) { + if (typeof object.resourceSpans[i] !== "object") + throw TypeError(".opentelemetry.proto.trace.v1.TracesData.resourceSpans: object expected"); + message.resourceSpans[i] = $root.opentelemetry.proto.trace.v1.ResourceSpans.fromObject(object.resourceSpans[i]); + } + } + return message; + }; + /** + * Creates a plain object from a TracesData message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.trace.v1.TracesData + * @static + * @param {opentelemetry.proto.trace.v1.TracesData} message TracesData + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + TracesData.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.resourceSpans = []; + if (message.resourceSpans && message.resourceSpans.length) { + object.resourceSpans = []; + for (var j = 0; j < message.resourceSpans.length; ++j) + object.resourceSpans[j] = $root.opentelemetry.proto.trace.v1.ResourceSpans.toObject(message.resourceSpans[j], options); + } + return object; + }; + /** + * Converts this TracesData to JSON. + * @function toJSON + * @memberof opentelemetry.proto.trace.v1.TracesData + * @instance + * @returns {Object.} JSON object + */ + TracesData.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for TracesData + * @function getTypeUrl + * @memberof opentelemetry.proto.trace.v1.TracesData + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + TracesData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.trace.v1.TracesData"; + }; + return TracesData; + })(); + v1.ResourceSpans = (function () { + /** + * Properties of a ResourceSpans. + * @memberof opentelemetry.proto.trace.v1 + * @interface IResourceSpans + * @property {opentelemetry.proto.resource.v1.IResource|null} [resource] ResourceSpans resource + * @property {Array.|null} [scopeSpans] ResourceSpans scopeSpans + * @property {string|null} [schemaUrl] ResourceSpans schemaUrl + */ + /** + * Constructs a new ResourceSpans. + * @memberof opentelemetry.proto.trace.v1 + * @classdesc Represents a ResourceSpans. + * @implements IResourceSpans + * @constructor + * @param {opentelemetry.proto.trace.v1.IResourceSpans=} [properties] Properties to set + */ + function ResourceSpans(properties) { + this.scopeSpans = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * ResourceSpans resource. + * @member {opentelemetry.proto.resource.v1.IResource|null|undefined} resource + * @memberof opentelemetry.proto.trace.v1.ResourceSpans + * @instance + */ + ResourceSpans.prototype.resource = null; + /** + * ResourceSpans scopeSpans. + * @member {Array.} scopeSpans + * @memberof opentelemetry.proto.trace.v1.ResourceSpans + * @instance + */ + ResourceSpans.prototype.scopeSpans = $util.emptyArray; + /** + * ResourceSpans schemaUrl. + * @member {string|null|undefined} schemaUrl + * @memberof opentelemetry.proto.trace.v1.ResourceSpans + * @instance + */ + ResourceSpans.prototype.schemaUrl = null; + /** + * Creates a new ResourceSpans instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.trace.v1.ResourceSpans + * @static + * @param {opentelemetry.proto.trace.v1.IResourceSpans=} [properties] Properties to set + * @returns {opentelemetry.proto.trace.v1.ResourceSpans} ResourceSpans instance + */ + ResourceSpans.create = function create(properties) { + return new ResourceSpans(properties); + }; + /** + * Encodes the specified ResourceSpans message. Does not implicitly {@link opentelemetry.proto.trace.v1.ResourceSpans.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.trace.v1.ResourceSpans + * @static + * @param {opentelemetry.proto.trace.v1.IResourceSpans} message ResourceSpans message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ResourceSpans.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.resource != null && Object.hasOwnProperty.call(message, "resource")) + $root.opentelemetry.proto.resource.v1.Resource.encode(message.resource, writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); + if (message.scopeSpans != null && message.scopeSpans.length) + for (var i = 0; i < message.scopeSpans.length; ++i) + $root.opentelemetry.proto.trace.v1.ScopeSpans.encode(message.scopeSpans[i], writer.uint32(/* id 2, wireType 2 =*/ 18).fork()).ldelim(); + if (message.schemaUrl != null && Object.hasOwnProperty.call(message, "schemaUrl")) + writer.uint32(/* id 3, wireType 2 =*/ 26).string(message.schemaUrl); + return writer; + }; + /** + * Encodes the specified ResourceSpans message, length delimited. Does not implicitly {@link opentelemetry.proto.trace.v1.ResourceSpans.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.trace.v1.ResourceSpans + * @static + * @param {opentelemetry.proto.trace.v1.IResourceSpans} message ResourceSpans message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ResourceSpans.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes a ResourceSpans message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.trace.v1.ResourceSpans + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.trace.v1.ResourceSpans} ResourceSpans + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ResourceSpans.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.trace.v1.ResourceSpans(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.resource = $root.opentelemetry.proto.resource.v1.Resource.decode(reader, reader.uint32()); + break; + } + case 2: { + if (!(message.scopeSpans && message.scopeSpans.length)) + message.scopeSpans = []; + message.scopeSpans.push($root.opentelemetry.proto.trace.v1.ScopeSpans.decode(reader, reader.uint32())); + break; + } + case 3: { + message.schemaUrl = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes a ResourceSpans message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.trace.v1.ResourceSpans + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.trace.v1.ResourceSpans} ResourceSpans + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ResourceSpans.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies a ResourceSpans message. + * @function verify + * @memberof opentelemetry.proto.trace.v1.ResourceSpans + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ResourceSpans.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.resource != null && message.hasOwnProperty("resource")) { + var error = $root.opentelemetry.proto.resource.v1.Resource.verify(message.resource); + if (error) + return "resource." + error; + } + if (message.scopeSpans != null && message.hasOwnProperty("scopeSpans")) { + if (!Array.isArray(message.scopeSpans)) + return "scopeSpans: array expected"; + for (var i = 0; i < message.scopeSpans.length; ++i) { + var error = $root.opentelemetry.proto.trace.v1.ScopeSpans.verify(message.scopeSpans[i]); + if (error) + return "scopeSpans." + error; + } + } + if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) + if (!$util.isString(message.schemaUrl)) + return "schemaUrl: string expected"; + return null; + }; + /** + * Creates a ResourceSpans message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.trace.v1.ResourceSpans + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.trace.v1.ResourceSpans} ResourceSpans + */ + ResourceSpans.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.trace.v1.ResourceSpans) + return object; + var message = new $root.opentelemetry.proto.trace.v1.ResourceSpans(); + if (object.resource != null) { + if (typeof object.resource !== "object") + throw TypeError(".opentelemetry.proto.trace.v1.ResourceSpans.resource: object expected"); + message.resource = $root.opentelemetry.proto.resource.v1.Resource.fromObject(object.resource); + } + if (object.scopeSpans) { + if (!Array.isArray(object.scopeSpans)) + throw TypeError(".opentelemetry.proto.trace.v1.ResourceSpans.scopeSpans: array expected"); + message.scopeSpans = []; + for (var i = 0; i < object.scopeSpans.length; ++i) { + if (typeof object.scopeSpans[i] !== "object") + throw TypeError(".opentelemetry.proto.trace.v1.ResourceSpans.scopeSpans: object expected"); + message.scopeSpans[i] = $root.opentelemetry.proto.trace.v1.ScopeSpans.fromObject(object.scopeSpans[i]); + } + } + if (object.schemaUrl != null) + message.schemaUrl = String(object.schemaUrl); + return message; + }; + /** + * Creates a plain object from a ResourceSpans message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.trace.v1.ResourceSpans + * @static + * @param {opentelemetry.proto.trace.v1.ResourceSpans} message ResourceSpans + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ResourceSpans.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.scopeSpans = []; + if (options.defaults) { + object.resource = null; + object.schemaUrl = ""; + } + if (message.resource != null && message.hasOwnProperty("resource")) + object.resource = $root.opentelemetry.proto.resource.v1.Resource.toObject(message.resource, options); + if (message.scopeSpans && message.scopeSpans.length) { + object.scopeSpans = []; + for (var j = 0; j < message.scopeSpans.length; ++j) + object.scopeSpans[j] = $root.opentelemetry.proto.trace.v1.ScopeSpans.toObject(message.scopeSpans[j], options); + } + if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) + object.schemaUrl = message.schemaUrl; + return object; + }; + /** + * Converts this ResourceSpans to JSON. + * @function toJSON + * @memberof opentelemetry.proto.trace.v1.ResourceSpans + * @instance + * @returns {Object.} JSON object + */ + ResourceSpans.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for ResourceSpans + * @function getTypeUrl + * @memberof opentelemetry.proto.trace.v1.ResourceSpans + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ResourceSpans.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.trace.v1.ResourceSpans"; + }; + return ResourceSpans; + })(); + v1.ScopeSpans = (function () { + /** + * Properties of a ScopeSpans. + * @memberof opentelemetry.proto.trace.v1 + * @interface IScopeSpans + * @property {opentelemetry.proto.common.v1.IInstrumentationScope|null} [scope] ScopeSpans scope + * @property {Array.|null} [spans] ScopeSpans spans + * @property {string|null} [schemaUrl] ScopeSpans schemaUrl + */ + /** + * Constructs a new ScopeSpans. + * @memberof opentelemetry.proto.trace.v1 + * @classdesc Represents a ScopeSpans. + * @implements IScopeSpans + * @constructor + * @param {opentelemetry.proto.trace.v1.IScopeSpans=} [properties] Properties to set + */ + function ScopeSpans(properties) { + this.spans = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * ScopeSpans scope. + * @member {opentelemetry.proto.common.v1.IInstrumentationScope|null|undefined} scope + * @memberof opentelemetry.proto.trace.v1.ScopeSpans + * @instance + */ + ScopeSpans.prototype.scope = null; + /** + * ScopeSpans spans. + * @member {Array.} spans + * @memberof opentelemetry.proto.trace.v1.ScopeSpans + * @instance + */ + ScopeSpans.prototype.spans = $util.emptyArray; + /** + * ScopeSpans schemaUrl. + * @member {string|null|undefined} schemaUrl + * @memberof opentelemetry.proto.trace.v1.ScopeSpans + * @instance + */ + ScopeSpans.prototype.schemaUrl = null; + /** + * Creates a new ScopeSpans instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.trace.v1.ScopeSpans + * @static + * @param {opentelemetry.proto.trace.v1.IScopeSpans=} [properties] Properties to set + * @returns {opentelemetry.proto.trace.v1.ScopeSpans} ScopeSpans instance + */ + ScopeSpans.create = function create(properties) { + return new ScopeSpans(properties); + }; + /** + * Encodes the specified ScopeSpans message. Does not implicitly {@link opentelemetry.proto.trace.v1.ScopeSpans.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.trace.v1.ScopeSpans + * @static + * @param {opentelemetry.proto.trace.v1.IScopeSpans} message ScopeSpans message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ScopeSpans.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.scope != null && Object.hasOwnProperty.call(message, "scope")) + $root.opentelemetry.proto.common.v1.InstrumentationScope.encode(message.scope, writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); + if (message.spans != null && message.spans.length) + for (var i = 0; i < message.spans.length; ++i) + $root.opentelemetry.proto.trace.v1.Span.encode(message.spans[i], writer.uint32(/* id 2, wireType 2 =*/ 18).fork()).ldelim(); + if (message.schemaUrl != null && Object.hasOwnProperty.call(message, "schemaUrl")) + writer.uint32(/* id 3, wireType 2 =*/ 26).string(message.schemaUrl); + return writer; + }; + /** + * Encodes the specified ScopeSpans message, length delimited. Does not implicitly {@link opentelemetry.proto.trace.v1.ScopeSpans.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.trace.v1.ScopeSpans + * @static + * @param {opentelemetry.proto.trace.v1.IScopeSpans} message ScopeSpans message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ScopeSpans.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes a ScopeSpans message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.trace.v1.ScopeSpans + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.trace.v1.ScopeSpans} ScopeSpans + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ScopeSpans.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.trace.v1.ScopeSpans(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.decode(reader, reader.uint32()); + break; + } + case 2: { + if (!(message.spans && message.spans.length)) + message.spans = []; + message.spans.push($root.opentelemetry.proto.trace.v1.Span.decode(reader, reader.uint32())); + break; + } + case 3: { + message.schemaUrl = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes a ScopeSpans message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.trace.v1.ScopeSpans + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.trace.v1.ScopeSpans} ScopeSpans + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ScopeSpans.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies a ScopeSpans message. + * @function verify + * @memberof opentelemetry.proto.trace.v1.ScopeSpans + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ScopeSpans.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.scope != null && message.hasOwnProperty("scope")) { + var error = $root.opentelemetry.proto.common.v1.InstrumentationScope.verify(message.scope); + if (error) + return "scope." + error; + } + if (message.spans != null && message.hasOwnProperty("spans")) { + if (!Array.isArray(message.spans)) + return "spans: array expected"; + for (var i = 0; i < message.spans.length; ++i) { + var error = $root.opentelemetry.proto.trace.v1.Span.verify(message.spans[i]); + if (error) + return "spans." + error; + } + } + if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) + if (!$util.isString(message.schemaUrl)) + return "schemaUrl: string expected"; + return null; + }; + /** + * Creates a ScopeSpans message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.trace.v1.ScopeSpans + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.trace.v1.ScopeSpans} ScopeSpans + */ + ScopeSpans.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.trace.v1.ScopeSpans) + return object; + var message = new $root.opentelemetry.proto.trace.v1.ScopeSpans(); + if (object.scope != null) { + if (typeof object.scope !== "object") + throw TypeError(".opentelemetry.proto.trace.v1.ScopeSpans.scope: object expected"); + message.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.fromObject(object.scope); + } + if (object.spans) { + if (!Array.isArray(object.spans)) + throw TypeError(".opentelemetry.proto.trace.v1.ScopeSpans.spans: array expected"); + message.spans = []; + for (var i = 0; i < object.spans.length; ++i) { + if (typeof object.spans[i] !== "object") + throw TypeError(".opentelemetry.proto.trace.v1.ScopeSpans.spans: object expected"); + message.spans[i] = $root.opentelemetry.proto.trace.v1.Span.fromObject(object.spans[i]); + } + } + if (object.schemaUrl != null) + message.schemaUrl = String(object.schemaUrl); + return message; + }; + /** + * Creates a plain object from a ScopeSpans message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.trace.v1.ScopeSpans + * @static + * @param {opentelemetry.proto.trace.v1.ScopeSpans} message ScopeSpans + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ScopeSpans.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.spans = []; + if (options.defaults) { + object.scope = null; + object.schemaUrl = ""; + } + if (message.scope != null && message.hasOwnProperty("scope")) + object.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.toObject(message.scope, options); + if (message.spans && message.spans.length) { + object.spans = []; + for (var j = 0; j < message.spans.length; ++j) + object.spans[j] = $root.opentelemetry.proto.trace.v1.Span.toObject(message.spans[j], options); + } + if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) + object.schemaUrl = message.schemaUrl; + return object; + }; + /** + * Converts this ScopeSpans to JSON. + * @function toJSON + * @memberof opentelemetry.proto.trace.v1.ScopeSpans + * @instance + * @returns {Object.} JSON object + */ + ScopeSpans.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for ScopeSpans + * @function getTypeUrl + * @memberof opentelemetry.proto.trace.v1.ScopeSpans + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ScopeSpans.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.trace.v1.ScopeSpans"; + }; + return ScopeSpans; + })(); + v1.Span = (function () { + /** + * Properties of a Span. + * @memberof opentelemetry.proto.trace.v1 + * @interface ISpan + * @property {Uint8Array|null} [traceId] Span traceId + * @property {Uint8Array|null} [spanId] Span spanId + * @property {string|null} [traceState] Span traceState + * @property {Uint8Array|null} [parentSpanId] Span parentSpanId + * @property {number|null} [flags] Span flags + * @property {string|null} [name] Span name + * @property {opentelemetry.proto.trace.v1.Span.SpanKind|null} [kind] Span kind + * @property {number|Long|null} [startTimeUnixNano] Span startTimeUnixNano + * @property {number|Long|null} [endTimeUnixNano] Span endTimeUnixNano + * @property {Array.|null} [attributes] Span attributes + * @property {number|null} [droppedAttributesCount] Span droppedAttributesCount + * @property {Array.|null} [events] Span events + * @property {number|null} [droppedEventsCount] Span droppedEventsCount + * @property {Array.|null} [links] Span links + * @property {number|null} [droppedLinksCount] Span droppedLinksCount + * @property {opentelemetry.proto.trace.v1.IStatus|null} [status] Span status + */ + /** + * Constructs a new Span. + * @memberof opentelemetry.proto.trace.v1 + * @classdesc Represents a Span. + * @implements ISpan + * @constructor + * @param {opentelemetry.proto.trace.v1.ISpan=} [properties] Properties to set + */ + function Span(properties) { + this.attributes = []; + this.events = []; + this.links = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * Span traceId. + * @member {Uint8Array|null|undefined} traceId + * @memberof opentelemetry.proto.trace.v1.Span + * @instance + */ + Span.prototype.traceId = null; + /** + * Span spanId. + * @member {Uint8Array|null|undefined} spanId + * @memberof opentelemetry.proto.trace.v1.Span + * @instance + */ + Span.prototype.spanId = null; + /** + * Span traceState. + * @member {string|null|undefined} traceState + * @memberof opentelemetry.proto.trace.v1.Span + * @instance + */ + Span.prototype.traceState = null; + /** + * Span parentSpanId. + * @member {Uint8Array|null|undefined} parentSpanId + * @memberof opentelemetry.proto.trace.v1.Span + * @instance + */ + Span.prototype.parentSpanId = null; + /** + * Span flags. + * @member {number|null|undefined} flags + * @memberof opentelemetry.proto.trace.v1.Span + * @instance + */ + Span.prototype.flags = null; + /** + * Span name. + * @member {string|null|undefined} name + * @memberof opentelemetry.proto.trace.v1.Span + * @instance + */ + Span.prototype.name = null; + /** + * Span kind. + * @member {opentelemetry.proto.trace.v1.Span.SpanKind|null|undefined} kind + * @memberof opentelemetry.proto.trace.v1.Span + * @instance + */ + Span.prototype.kind = null; + /** + * Span startTimeUnixNano. + * @member {number|Long|null|undefined} startTimeUnixNano + * @memberof opentelemetry.proto.trace.v1.Span + * @instance + */ + Span.prototype.startTimeUnixNano = null; + /** + * Span endTimeUnixNano. + * @member {number|Long|null|undefined} endTimeUnixNano + * @memberof opentelemetry.proto.trace.v1.Span + * @instance + */ + Span.prototype.endTimeUnixNano = null; + /** + * Span attributes. + * @member {Array.} attributes + * @memberof opentelemetry.proto.trace.v1.Span + * @instance + */ + Span.prototype.attributes = $util.emptyArray; + /** + * Span droppedAttributesCount. + * @member {number|null|undefined} droppedAttributesCount + * @memberof opentelemetry.proto.trace.v1.Span + * @instance + */ + Span.prototype.droppedAttributesCount = null; + /** + * Span events. + * @member {Array.} events + * @memberof opentelemetry.proto.trace.v1.Span + * @instance + */ + Span.prototype.events = $util.emptyArray; + /** + * Span droppedEventsCount. + * @member {number|null|undefined} droppedEventsCount + * @memberof opentelemetry.proto.trace.v1.Span + * @instance + */ + Span.prototype.droppedEventsCount = null; + /** + * Span links. + * @member {Array.} links + * @memberof opentelemetry.proto.trace.v1.Span + * @instance + */ + Span.prototype.links = $util.emptyArray; + /** + * Span droppedLinksCount. + * @member {number|null|undefined} droppedLinksCount + * @memberof opentelemetry.proto.trace.v1.Span + * @instance + */ + Span.prototype.droppedLinksCount = null; + /** + * Span status. + * @member {opentelemetry.proto.trace.v1.IStatus|null|undefined} status + * @memberof opentelemetry.proto.trace.v1.Span + * @instance + */ + Span.prototype.status = null; + /** + * Creates a new Span instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.trace.v1.Span + * @static + * @param {opentelemetry.proto.trace.v1.ISpan=} [properties] Properties to set + * @returns {opentelemetry.proto.trace.v1.Span} Span instance + */ + Span.create = function create(properties) { + return new Span(properties); + }; + /** + * Encodes the specified Span message. Does not implicitly {@link opentelemetry.proto.trace.v1.Span.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.trace.v1.Span + * @static + * @param {opentelemetry.proto.trace.v1.ISpan} message Span message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Span.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.traceId != null && Object.hasOwnProperty.call(message, "traceId")) + writer.uint32(/* id 1, wireType 2 =*/ 10).bytes(message.traceId); + if (message.spanId != null && Object.hasOwnProperty.call(message, "spanId")) + writer.uint32(/* id 2, wireType 2 =*/ 18).bytes(message.spanId); + if (message.traceState != null && Object.hasOwnProperty.call(message, "traceState")) + writer.uint32(/* id 3, wireType 2 =*/ 26).string(message.traceState); + if (message.parentSpanId != null && Object.hasOwnProperty.call(message, "parentSpanId")) + writer.uint32(/* id 4, wireType 2 =*/ 34).bytes(message.parentSpanId); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 5, wireType 2 =*/ 42).string(message.name); + if (message.kind != null && Object.hasOwnProperty.call(message, "kind")) + writer.uint32(/* id 6, wireType 0 =*/ 48).int32(message.kind); + if (message.startTimeUnixNano != null && Object.hasOwnProperty.call(message, "startTimeUnixNano")) + writer.uint32(/* id 7, wireType 1 =*/ 57).fixed64(message.startTimeUnixNano); + if (message.endTimeUnixNano != null && Object.hasOwnProperty.call(message, "endTimeUnixNano")) + writer.uint32(/* id 8, wireType 1 =*/ 65).fixed64(message.endTimeUnixNano); + if (message.attributes != null && message.attributes.length) + for (var i = 0; i < message.attributes.length; ++i) + $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(/* id 9, wireType 2 =*/ 74).fork()).ldelim(); + if (message.droppedAttributesCount != null && Object.hasOwnProperty.call(message, "droppedAttributesCount")) + writer.uint32(/* id 10, wireType 0 =*/ 80).uint32(message.droppedAttributesCount); + if (message.events != null && message.events.length) + for (var i = 0; i < message.events.length; ++i) + $root.opentelemetry.proto.trace.v1.Span.Event.encode(message.events[i], writer.uint32(/* id 11, wireType 2 =*/ 90).fork()).ldelim(); + if (message.droppedEventsCount != null && Object.hasOwnProperty.call(message, "droppedEventsCount")) + writer.uint32(/* id 12, wireType 0 =*/ 96).uint32(message.droppedEventsCount); + if (message.links != null && message.links.length) + for (var i = 0; i < message.links.length; ++i) + $root.opentelemetry.proto.trace.v1.Span.Link.encode(message.links[i], writer.uint32(/* id 13, wireType 2 =*/ 106).fork()).ldelim(); + if (message.droppedLinksCount != null && Object.hasOwnProperty.call(message, "droppedLinksCount")) + writer.uint32(/* id 14, wireType 0 =*/ 112).uint32(message.droppedLinksCount); + if (message.status != null && Object.hasOwnProperty.call(message, "status")) + $root.opentelemetry.proto.trace.v1.Status.encode(message.status, writer.uint32(/* id 15, wireType 2 =*/ 122).fork()).ldelim(); + if (message.flags != null && Object.hasOwnProperty.call(message, "flags")) + writer.uint32(/* id 16, wireType 5 =*/ 133).fixed32(message.flags); + return writer; + }; + /** + * Encodes the specified Span message, length delimited. Does not implicitly {@link opentelemetry.proto.trace.v1.Span.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.trace.v1.Span + * @static + * @param {opentelemetry.proto.trace.v1.ISpan} message Span message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Span.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes a Span message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.trace.v1.Span + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.trace.v1.Span} Span + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Span.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.trace.v1.Span(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.traceId = reader.bytes(); + break; + } + case 2: { + message.spanId = reader.bytes(); + break; + } + case 3: { + message.traceState = reader.string(); + break; + } + case 4: { + message.parentSpanId = reader.bytes(); + break; + } + case 16: { + message.flags = reader.fixed32(); + break; + } + case 5: { + message.name = reader.string(); + break; + } + case 6: { + message.kind = reader.int32(); + break; + } + case 7: { + message.startTimeUnixNano = reader.fixed64(); + break; + } + case 8: { + message.endTimeUnixNano = reader.fixed64(); + break; + } + case 9: { + if (!(message.attributes && message.attributes.length)) + message.attributes = []; + message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32())); + break; + } + case 10: { + message.droppedAttributesCount = reader.uint32(); + break; + } + case 11: { + if (!(message.events && message.events.length)) + message.events = []; + message.events.push($root.opentelemetry.proto.trace.v1.Span.Event.decode(reader, reader.uint32())); + break; + } + case 12: { + message.droppedEventsCount = reader.uint32(); + break; + } + case 13: { + if (!(message.links && message.links.length)) + message.links = []; + message.links.push($root.opentelemetry.proto.trace.v1.Span.Link.decode(reader, reader.uint32())); + break; + } + case 14: { + message.droppedLinksCount = reader.uint32(); + break; + } + case 15: { + message.status = $root.opentelemetry.proto.trace.v1.Status.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes a Span message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.trace.v1.Span + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.trace.v1.Span} Span + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Span.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies a Span message. + * @function verify + * @memberof opentelemetry.proto.trace.v1.Span + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Span.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.traceId != null && message.hasOwnProperty("traceId")) + if (!(message.traceId && typeof message.traceId.length === "number" || $util.isString(message.traceId))) + return "traceId: buffer expected"; + if (message.spanId != null && message.hasOwnProperty("spanId")) + if (!(message.spanId && typeof message.spanId.length === "number" || $util.isString(message.spanId))) + return "spanId: buffer expected"; + if (message.traceState != null && message.hasOwnProperty("traceState")) + if (!$util.isString(message.traceState)) + return "traceState: string expected"; + if (message.parentSpanId != null && message.hasOwnProperty("parentSpanId")) + if (!(message.parentSpanId && typeof message.parentSpanId.length === "number" || $util.isString(message.parentSpanId))) + return "parentSpanId: buffer expected"; + if (message.flags != null && message.hasOwnProperty("flags")) + if (!$util.isInteger(message.flags)) + return "flags: integer expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.kind != null && message.hasOwnProperty("kind")) + switch (message.kind) { + default: + return "kind: enum value expected"; + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + break; + } + if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano")) + if (!$util.isInteger(message.startTimeUnixNano) && !(message.startTimeUnixNano && $util.isInteger(message.startTimeUnixNano.low) && $util.isInteger(message.startTimeUnixNano.high))) + return "startTimeUnixNano: integer|Long expected"; + if (message.endTimeUnixNano != null && message.hasOwnProperty("endTimeUnixNano")) + if (!$util.isInteger(message.endTimeUnixNano) && !(message.endTimeUnixNano && $util.isInteger(message.endTimeUnixNano.low) && $util.isInteger(message.endTimeUnixNano.high))) + return "endTimeUnixNano: integer|Long expected"; + if (message.attributes != null && message.hasOwnProperty("attributes")) { + if (!Array.isArray(message.attributes)) + return "attributes: array expected"; + for (var i = 0; i < message.attributes.length; ++i) { + var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]); + if (error) + return "attributes." + error; + } + } + if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) + if (!$util.isInteger(message.droppedAttributesCount)) + return "droppedAttributesCount: integer expected"; + if (message.events != null && message.hasOwnProperty("events")) { + if (!Array.isArray(message.events)) + return "events: array expected"; + for (var i = 0; i < message.events.length; ++i) { + var error = $root.opentelemetry.proto.trace.v1.Span.Event.verify(message.events[i]); + if (error) + return "events." + error; + } + } + if (message.droppedEventsCount != null && message.hasOwnProperty("droppedEventsCount")) + if (!$util.isInteger(message.droppedEventsCount)) + return "droppedEventsCount: integer expected"; + if (message.links != null && message.hasOwnProperty("links")) { + if (!Array.isArray(message.links)) + return "links: array expected"; + for (var i = 0; i < message.links.length; ++i) { + var error = $root.opentelemetry.proto.trace.v1.Span.Link.verify(message.links[i]); + if (error) + return "links." + error; + } + } + if (message.droppedLinksCount != null && message.hasOwnProperty("droppedLinksCount")) + if (!$util.isInteger(message.droppedLinksCount)) + return "droppedLinksCount: integer expected"; + if (message.status != null && message.hasOwnProperty("status")) { + var error = $root.opentelemetry.proto.trace.v1.Status.verify(message.status); + if (error) + return "status." + error; + } + return null; + }; + /** + * Creates a Span message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.trace.v1.Span + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.trace.v1.Span} Span + */ + Span.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.trace.v1.Span) + return object; + var message = new $root.opentelemetry.proto.trace.v1.Span(); + if (object.traceId != null) + if (typeof object.traceId === "string") + $util.base64.decode(object.traceId, message.traceId = $util.newBuffer($util.base64.length(object.traceId)), 0); + else if (object.traceId.length >= 0) + message.traceId = object.traceId; + if (object.spanId != null) + if (typeof object.spanId === "string") + $util.base64.decode(object.spanId, message.spanId = $util.newBuffer($util.base64.length(object.spanId)), 0); + else if (object.spanId.length >= 0) + message.spanId = object.spanId; + if (object.traceState != null) + message.traceState = String(object.traceState); + if (object.parentSpanId != null) + if (typeof object.parentSpanId === "string") + $util.base64.decode(object.parentSpanId, message.parentSpanId = $util.newBuffer($util.base64.length(object.parentSpanId)), 0); + else if (object.parentSpanId.length >= 0) + message.parentSpanId = object.parentSpanId; + if (object.flags != null) + message.flags = object.flags >>> 0; + if (object.name != null) + message.name = String(object.name); + switch (object.kind) { + default: + if (typeof object.kind === "number") { + message.kind = object.kind; + break; + } + break; + case "SPAN_KIND_UNSPECIFIED": + case 0: + message.kind = 0; + break; + case "SPAN_KIND_INTERNAL": + case 1: + message.kind = 1; + break; + case "SPAN_KIND_SERVER": + case 2: + message.kind = 2; + break; + case "SPAN_KIND_CLIENT": + case 3: + message.kind = 3; + break; + case "SPAN_KIND_PRODUCER": + case 4: + message.kind = 4; + break; + case "SPAN_KIND_CONSUMER": + case 5: + message.kind = 5; + break; + } + if (object.startTimeUnixNano != null) + if ($util.Long) + (message.startTimeUnixNano = $util.Long.fromValue(object.startTimeUnixNano)).unsigned = false; + else if (typeof object.startTimeUnixNano === "string") + message.startTimeUnixNano = parseInt(object.startTimeUnixNano, 10); + else if (typeof object.startTimeUnixNano === "number") + message.startTimeUnixNano = object.startTimeUnixNano; + else if (typeof object.startTimeUnixNano === "object") + message.startTimeUnixNano = new $util.LongBits(object.startTimeUnixNano.low >>> 0, object.startTimeUnixNano.high >>> 0).toNumber(); + if (object.endTimeUnixNano != null) + if ($util.Long) + (message.endTimeUnixNano = $util.Long.fromValue(object.endTimeUnixNano)).unsigned = false; + else if (typeof object.endTimeUnixNano === "string") + message.endTimeUnixNano = parseInt(object.endTimeUnixNano, 10); + else if (typeof object.endTimeUnixNano === "number") + message.endTimeUnixNano = object.endTimeUnixNano; + else if (typeof object.endTimeUnixNano === "object") + message.endTimeUnixNano = new $util.LongBits(object.endTimeUnixNano.low >>> 0, object.endTimeUnixNano.high >>> 0).toNumber(); + if (object.attributes) { + if (!Array.isArray(object.attributes)) + throw TypeError(".opentelemetry.proto.trace.v1.Span.attributes: array expected"); + message.attributes = []; + for (var i = 0; i < object.attributes.length; ++i) { + if (typeof object.attributes[i] !== "object") + throw TypeError(".opentelemetry.proto.trace.v1.Span.attributes: object expected"); + message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]); + } + } + if (object.droppedAttributesCount != null) + message.droppedAttributesCount = object.droppedAttributesCount >>> 0; + if (object.events) { + if (!Array.isArray(object.events)) + throw TypeError(".opentelemetry.proto.trace.v1.Span.events: array expected"); + message.events = []; + for (var i = 0; i < object.events.length; ++i) { + if (typeof object.events[i] !== "object") + throw TypeError(".opentelemetry.proto.trace.v1.Span.events: object expected"); + message.events[i] = $root.opentelemetry.proto.trace.v1.Span.Event.fromObject(object.events[i]); + } + } + if (object.droppedEventsCount != null) + message.droppedEventsCount = object.droppedEventsCount >>> 0; + if (object.links) { + if (!Array.isArray(object.links)) + throw TypeError(".opentelemetry.proto.trace.v1.Span.links: array expected"); + message.links = []; + for (var i = 0; i < object.links.length; ++i) { + if (typeof object.links[i] !== "object") + throw TypeError(".opentelemetry.proto.trace.v1.Span.links: object expected"); + message.links[i] = $root.opentelemetry.proto.trace.v1.Span.Link.fromObject(object.links[i]); + } + } + if (object.droppedLinksCount != null) + message.droppedLinksCount = object.droppedLinksCount >>> 0; + if (object.status != null) { + if (typeof object.status !== "object") + throw TypeError(".opentelemetry.proto.trace.v1.Span.status: object expected"); + message.status = $root.opentelemetry.proto.trace.v1.Status.fromObject(object.status); + } + return message; + }; + /** + * Creates a plain object from a Span message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.trace.v1.Span + * @static + * @param {opentelemetry.proto.trace.v1.Span} message Span + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Span.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.attributes = []; + object.events = []; + object.links = []; + } + if (options.defaults) { + if (options.bytes === String) + object.traceId = ""; + else { + object.traceId = []; + if (options.bytes !== Array) + object.traceId = $util.newBuffer(object.traceId); + } + if (options.bytes === String) + object.spanId = ""; + else { + object.spanId = []; + if (options.bytes !== Array) + object.spanId = $util.newBuffer(object.spanId); + } + object.traceState = ""; + if (options.bytes === String) + object.parentSpanId = ""; + else { + object.parentSpanId = []; + if (options.bytes !== Array) + object.parentSpanId = $util.newBuffer(object.parentSpanId); + } + object.name = ""; + object.kind = options.enums === String ? "SPAN_KIND_UNSPECIFIED" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.startTimeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } + else + object.startTimeUnixNano = options.longs === String ? "0" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.endTimeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } + else + object.endTimeUnixNano = options.longs === String ? "0" : 0; + object.droppedAttributesCount = 0; + object.droppedEventsCount = 0; + object.droppedLinksCount = 0; + object.status = null; + object.flags = 0; + } + if (message.traceId != null && message.hasOwnProperty("traceId")) + object.traceId = options.bytes === String ? $util.base64.encode(message.traceId, 0, message.traceId.length) : options.bytes === Array ? Array.prototype.slice.call(message.traceId) : message.traceId; + if (message.spanId != null && message.hasOwnProperty("spanId")) + object.spanId = options.bytes === String ? $util.base64.encode(message.spanId, 0, message.spanId.length) : options.bytes === Array ? Array.prototype.slice.call(message.spanId) : message.spanId; + if (message.traceState != null && message.hasOwnProperty("traceState")) + object.traceState = message.traceState; + if (message.parentSpanId != null && message.hasOwnProperty("parentSpanId")) + object.parentSpanId = options.bytes === String ? $util.base64.encode(message.parentSpanId, 0, message.parentSpanId.length) : options.bytes === Array ? Array.prototype.slice.call(message.parentSpanId) : message.parentSpanId; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.kind != null && message.hasOwnProperty("kind")) + object.kind = options.enums === String ? $root.opentelemetry.proto.trace.v1.Span.SpanKind[message.kind] === undefined ? message.kind : $root.opentelemetry.proto.trace.v1.Span.SpanKind[message.kind] : message.kind; + if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano")) + if (typeof message.startTimeUnixNano === "number") + object.startTimeUnixNano = options.longs === String ? String(message.startTimeUnixNano) : message.startTimeUnixNano; + else + object.startTimeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.startTimeUnixNano) : options.longs === Number ? new $util.LongBits(message.startTimeUnixNano.low >>> 0, message.startTimeUnixNano.high >>> 0).toNumber() : message.startTimeUnixNano; + if (message.endTimeUnixNano != null && message.hasOwnProperty("endTimeUnixNano")) + if (typeof message.endTimeUnixNano === "number") + object.endTimeUnixNano = options.longs === String ? String(message.endTimeUnixNano) : message.endTimeUnixNano; + else + object.endTimeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.endTimeUnixNano) : options.longs === Number ? new $util.LongBits(message.endTimeUnixNano.low >>> 0, message.endTimeUnixNano.high >>> 0).toNumber() : message.endTimeUnixNano; + if (message.attributes && message.attributes.length) { + object.attributes = []; + for (var j = 0; j < message.attributes.length; ++j) + object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options); + } + if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) + object.droppedAttributesCount = message.droppedAttributesCount; + if (message.events && message.events.length) { + object.events = []; + for (var j = 0; j < message.events.length; ++j) + object.events[j] = $root.opentelemetry.proto.trace.v1.Span.Event.toObject(message.events[j], options); + } + if (message.droppedEventsCount != null && message.hasOwnProperty("droppedEventsCount")) + object.droppedEventsCount = message.droppedEventsCount; + if (message.links && message.links.length) { + object.links = []; + for (var j = 0; j < message.links.length; ++j) + object.links[j] = $root.opentelemetry.proto.trace.v1.Span.Link.toObject(message.links[j], options); + } + if (message.droppedLinksCount != null && message.hasOwnProperty("droppedLinksCount")) + object.droppedLinksCount = message.droppedLinksCount; + if (message.status != null && message.hasOwnProperty("status")) + object.status = $root.opentelemetry.proto.trace.v1.Status.toObject(message.status, options); + if (message.flags != null && message.hasOwnProperty("flags")) + object.flags = message.flags; + return object; + }; + /** + * Converts this Span to JSON. + * @function toJSON + * @memberof opentelemetry.proto.trace.v1.Span + * @instance + * @returns {Object.} JSON object + */ + Span.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for Span + * @function getTypeUrl + * @memberof opentelemetry.proto.trace.v1.Span + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Span.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.trace.v1.Span"; + }; + /** + * SpanKind enum. + * @name opentelemetry.proto.trace.v1.Span.SpanKind + * @enum {number} + * @property {number} SPAN_KIND_UNSPECIFIED=0 SPAN_KIND_UNSPECIFIED value + * @property {number} SPAN_KIND_INTERNAL=1 SPAN_KIND_INTERNAL value + * @property {number} SPAN_KIND_SERVER=2 SPAN_KIND_SERVER value + * @property {number} SPAN_KIND_CLIENT=3 SPAN_KIND_CLIENT value + * @property {number} SPAN_KIND_PRODUCER=4 SPAN_KIND_PRODUCER value + * @property {number} SPAN_KIND_CONSUMER=5 SPAN_KIND_CONSUMER value + */ + Span.SpanKind = (function () { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "SPAN_KIND_UNSPECIFIED"] = 0; + values[valuesById[1] = "SPAN_KIND_INTERNAL"] = 1; + values[valuesById[2] = "SPAN_KIND_SERVER"] = 2; + values[valuesById[3] = "SPAN_KIND_CLIENT"] = 3; + values[valuesById[4] = "SPAN_KIND_PRODUCER"] = 4; + values[valuesById[5] = "SPAN_KIND_CONSUMER"] = 5; + return values; + })(); + Span.Event = (function () { + /** + * Properties of an Event. + * @memberof opentelemetry.proto.trace.v1.Span + * @interface IEvent + * @property {number|Long|null} [timeUnixNano] Event timeUnixNano + * @property {string|null} [name] Event name + * @property {Array.|null} [attributes] Event attributes + * @property {number|null} [droppedAttributesCount] Event droppedAttributesCount + */ + /** + * Constructs a new Event. + * @memberof opentelemetry.proto.trace.v1.Span + * @classdesc Represents an Event. + * @implements IEvent + * @constructor + * @param {opentelemetry.proto.trace.v1.Span.IEvent=} [properties] Properties to set + */ + function Event(properties) { + this.attributes = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * Event timeUnixNano. + * @member {number|Long|null|undefined} timeUnixNano + * @memberof opentelemetry.proto.trace.v1.Span.Event + * @instance + */ + Event.prototype.timeUnixNano = null; + /** + * Event name. + * @member {string|null|undefined} name + * @memberof opentelemetry.proto.trace.v1.Span.Event + * @instance + */ + Event.prototype.name = null; + /** + * Event attributes. + * @member {Array.} attributes + * @memberof opentelemetry.proto.trace.v1.Span.Event + * @instance + */ + Event.prototype.attributes = $util.emptyArray; + /** + * Event droppedAttributesCount. + * @member {number|null|undefined} droppedAttributesCount + * @memberof opentelemetry.proto.trace.v1.Span.Event + * @instance + */ + Event.prototype.droppedAttributesCount = null; + /** + * Creates a new Event instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.trace.v1.Span.Event + * @static + * @param {opentelemetry.proto.trace.v1.Span.IEvent=} [properties] Properties to set + * @returns {opentelemetry.proto.trace.v1.Span.Event} Event instance + */ + Event.create = function create(properties) { + return new Event(properties); + }; + /** + * Encodes the specified Event message. Does not implicitly {@link opentelemetry.proto.trace.v1.Span.Event.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.trace.v1.Span.Event + * @static + * @param {opentelemetry.proto.trace.v1.Span.IEvent} message Event message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Event.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.timeUnixNano != null && Object.hasOwnProperty.call(message, "timeUnixNano")) + writer.uint32(/* id 1, wireType 1 =*/ 9).fixed64(message.timeUnixNano); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 2, wireType 2 =*/ 18).string(message.name); + if (message.attributes != null && message.attributes.length) + for (var i = 0; i < message.attributes.length; ++i) + $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(/* id 3, wireType 2 =*/ 26).fork()).ldelim(); + if (message.droppedAttributesCount != null && Object.hasOwnProperty.call(message, "droppedAttributesCount")) + writer.uint32(/* id 4, wireType 0 =*/ 32).uint32(message.droppedAttributesCount); + return writer; + }; + /** + * Encodes the specified Event message, length delimited. Does not implicitly {@link opentelemetry.proto.trace.v1.Span.Event.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.trace.v1.Span.Event + * @static + * @param {opentelemetry.proto.trace.v1.Span.IEvent} message Event message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Event.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes an Event message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.trace.v1.Span.Event + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.trace.v1.Span.Event} Event + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Event.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.trace.v1.Span.Event(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.timeUnixNano = reader.fixed64(); + break; + } + case 2: { + message.name = reader.string(); + break; + } + case 3: { + if (!(message.attributes && message.attributes.length)) + message.attributes = []; + message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32())); + break; + } + case 4: { + message.droppedAttributesCount = reader.uint32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes an Event message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.trace.v1.Span.Event + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.trace.v1.Span.Event} Event + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Event.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies an Event message. + * @function verify + * @memberof opentelemetry.proto.trace.v1.Span.Event + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Event.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) + if (!$util.isInteger(message.timeUnixNano) && !(message.timeUnixNano && $util.isInteger(message.timeUnixNano.low) && $util.isInteger(message.timeUnixNano.high))) + return "timeUnixNano: integer|Long expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.attributes != null && message.hasOwnProperty("attributes")) { + if (!Array.isArray(message.attributes)) + return "attributes: array expected"; + for (var i = 0; i < message.attributes.length; ++i) { + var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]); + if (error) + return "attributes." + error; + } + } + if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) + if (!$util.isInteger(message.droppedAttributesCount)) + return "droppedAttributesCount: integer expected"; + return null; + }; + /** + * Creates an Event message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.trace.v1.Span.Event + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.trace.v1.Span.Event} Event + */ + Event.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.trace.v1.Span.Event) + return object; + var message = new $root.opentelemetry.proto.trace.v1.Span.Event(); + if (object.timeUnixNano != null) + if ($util.Long) + (message.timeUnixNano = $util.Long.fromValue(object.timeUnixNano)).unsigned = false; + else if (typeof object.timeUnixNano === "string") + message.timeUnixNano = parseInt(object.timeUnixNano, 10); + else if (typeof object.timeUnixNano === "number") + message.timeUnixNano = object.timeUnixNano; + else if (typeof object.timeUnixNano === "object") + message.timeUnixNano = new $util.LongBits(object.timeUnixNano.low >>> 0, object.timeUnixNano.high >>> 0).toNumber(); + if (object.name != null) + message.name = String(object.name); + if (object.attributes) { + if (!Array.isArray(object.attributes)) + throw TypeError(".opentelemetry.proto.trace.v1.Span.Event.attributes: array expected"); + message.attributes = []; + for (var i = 0; i < object.attributes.length; ++i) { + if (typeof object.attributes[i] !== "object") + throw TypeError(".opentelemetry.proto.trace.v1.Span.Event.attributes: object expected"); + message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]); + } + } + if (object.droppedAttributesCount != null) + message.droppedAttributesCount = object.droppedAttributesCount >>> 0; + return message; + }; + /** + * Creates a plain object from an Event message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.trace.v1.Span.Event + * @static + * @param {opentelemetry.proto.trace.v1.Span.Event} message Event + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Event.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.attributes = []; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.timeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } + else + object.timeUnixNano = options.longs === String ? "0" : 0; + object.name = ""; + object.droppedAttributesCount = 0; + } + if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) + if (typeof message.timeUnixNano === "number") + object.timeUnixNano = options.longs === String ? String(message.timeUnixNano) : message.timeUnixNano; + else + object.timeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.timeUnixNano) : options.longs === Number ? new $util.LongBits(message.timeUnixNano.low >>> 0, message.timeUnixNano.high >>> 0).toNumber() : message.timeUnixNano; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.attributes && message.attributes.length) { + object.attributes = []; + for (var j = 0; j < message.attributes.length; ++j) + object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options); + } + if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) + object.droppedAttributesCount = message.droppedAttributesCount; + return object; + }; + /** + * Converts this Event to JSON. + * @function toJSON + * @memberof opentelemetry.proto.trace.v1.Span.Event + * @instance + * @returns {Object.} JSON object + */ + Event.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for Event + * @function getTypeUrl + * @memberof opentelemetry.proto.trace.v1.Span.Event + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Event.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.trace.v1.Span.Event"; + }; + return Event; + })(); + Span.Link = (function () { + /** + * Properties of a Link. + * @memberof opentelemetry.proto.trace.v1.Span + * @interface ILink + * @property {Uint8Array|null} [traceId] Link traceId + * @property {Uint8Array|null} [spanId] Link spanId + * @property {string|null} [traceState] Link traceState + * @property {Array.|null} [attributes] Link attributes + * @property {number|null} [droppedAttributesCount] Link droppedAttributesCount + * @property {number|null} [flags] Link flags + */ + /** + * Constructs a new Link. + * @memberof opentelemetry.proto.trace.v1.Span + * @classdesc Represents a Link. + * @implements ILink + * @constructor + * @param {opentelemetry.proto.trace.v1.Span.ILink=} [properties] Properties to set + */ + function Link(properties) { + this.attributes = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * Link traceId. + * @member {Uint8Array|null|undefined} traceId + * @memberof opentelemetry.proto.trace.v1.Span.Link + * @instance + */ + Link.prototype.traceId = null; + /** + * Link spanId. + * @member {Uint8Array|null|undefined} spanId + * @memberof opentelemetry.proto.trace.v1.Span.Link + * @instance + */ + Link.prototype.spanId = null; + /** + * Link traceState. + * @member {string|null|undefined} traceState + * @memberof opentelemetry.proto.trace.v1.Span.Link + * @instance + */ + Link.prototype.traceState = null; + /** + * Link attributes. + * @member {Array.} attributes + * @memberof opentelemetry.proto.trace.v1.Span.Link + * @instance + */ + Link.prototype.attributes = $util.emptyArray; + /** + * Link droppedAttributesCount. + * @member {number|null|undefined} droppedAttributesCount + * @memberof opentelemetry.proto.trace.v1.Span.Link + * @instance + */ + Link.prototype.droppedAttributesCount = null; + /** + * Link flags. + * @member {number|null|undefined} flags + * @memberof opentelemetry.proto.trace.v1.Span.Link + * @instance + */ + Link.prototype.flags = null; + /** + * Creates a new Link instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.trace.v1.Span.Link + * @static + * @param {opentelemetry.proto.trace.v1.Span.ILink=} [properties] Properties to set + * @returns {opentelemetry.proto.trace.v1.Span.Link} Link instance + */ + Link.create = function create(properties) { + return new Link(properties); + }; + /** + * Encodes the specified Link message. Does not implicitly {@link opentelemetry.proto.trace.v1.Span.Link.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.trace.v1.Span.Link + * @static + * @param {opentelemetry.proto.trace.v1.Span.ILink} message Link message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Link.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.traceId != null && Object.hasOwnProperty.call(message, "traceId")) + writer.uint32(/* id 1, wireType 2 =*/ 10).bytes(message.traceId); + if (message.spanId != null && Object.hasOwnProperty.call(message, "spanId")) + writer.uint32(/* id 2, wireType 2 =*/ 18).bytes(message.spanId); + if (message.traceState != null && Object.hasOwnProperty.call(message, "traceState")) + writer.uint32(/* id 3, wireType 2 =*/ 26).string(message.traceState); + if (message.attributes != null && message.attributes.length) + for (var i = 0; i < message.attributes.length; ++i) + $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(/* id 4, wireType 2 =*/ 34).fork()).ldelim(); + if (message.droppedAttributesCount != null && Object.hasOwnProperty.call(message, "droppedAttributesCount")) + writer.uint32(/* id 5, wireType 0 =*/ 40).uint32(message.droppedAttributesCount); + if (message.flags != null && Object.hasOwnProperty.call(message, "flags")) + writer.uint32(/* id 6, wireType 5 =*/ 53).fixed32(message.flags); + return writer; + }; + /** + * Encodes the specified Link message, length delimited. Does not implicitly {@link opentelemetry.proto.trace.v1.Span.Link.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.trace.v1.Span.Link + * @static + * @param {opentelemetry.proto.trace.v1.Span.ILink} message Link message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Link.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes a Link message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.trace.v1.Span.Link + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.trace.v1.Span.Link} Link + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Link.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.trace.v1.Span.Link(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.traceId = reader.bytes(); + break; + } + case 2: { + message.spanId = reader.bytes(); + break; + } + case 3: { + message.traceState = reader.string(); + break; + } + case 4: { + if (!(message.attributes && message.attributes.length)) + message.attributes = []; + message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32())); + break; + } + case 5: { + message.droppedAttributesCount = reader.uint32(); + break; + } + case 6: { + message.flags = reader.fixed32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes a Link message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.trace.v1.Span.Link + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.trace.v1.Span.Link} Link + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Link.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies a Link message. + * @function verify + * @memberof opentelemetry.proto.trace.v1.Span.Link + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Link.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.traceId != null && message.hasOwnProperty("traceId")) + if (!(message.traceId && typeof message.traceId.length === "number" || $util.isString(message.traceId))) + return "traceId: buffer expected"; + if (message.spanId != null && message.hasOwnProperty("spanId")) + if (!(message.spanId && typeof message.spanId.length === "number" || $util.isString(message.spanId))) + return "spanId: buffer expected"; + if (message.traceState != null && message.hasOwnProperty("traceState")) + if (!$util.isString(message.traceState)) + return "traceState: string expected"; + if (message.attributes != null && message.hasOwnProperty("attributes")) { + if (!Array.isArray(message.attributes)) + return "attributes: array expected"; + for (var i = 0; i < message.attributes.length; ++i) { + var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]); + if (error) + return "attributes." + error; + } + } + if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) + if (!$util.isInteger(message.droppedAttributesCount)) + return "droppedAttributesCount: integer expected"; + if (message.flags != null && message.hasOwnProperty("flags")) + if (!$util.isInteger(message.flags)) + return "flags: integer expected"; + return null; + }; + /** + * Creates a Link message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.trace.v1.Span.Link + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.trace.v1.Span.Link} Link + */ + Link.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.trace.v1.Span.Link) + return object; + var message = new $root.opentelemetry.proto.trace.v1.Span.Link(); + if (object.traceId != null) + if (typeof object.traceId === "string") + $util.base64.decode(object.traceId, message.traceId = $util.newBuffer($util.base64.length(object.traceId)), 0); + else if (object.traceId.length >= 0) + message.traceId = object.traceId; + if (object.spanId != null) + if (typeof object.spanId === "string") + $util.base64.decode(object.spanId, message.spanId = $util.newBuffer($util.base64.length(object.spanId)), 0); + else if (object.spanId.length >= 0) + message.spanId = object.spanId; + if (object.traceState != null) + message.traceState = String(object.traceState); + if (object.attributes) { + if (!Array.isArray(object.attributes)) + throw TypeError(".opentelemetry.proto.trace.v1.Span.Link.attributes: array expected"); + message.attributes = []; + for (var i = 0; i < object.attributes.length; ++i) { + if (typeof object.attributes[i] !== "object") + throw TypeError(".opentelemetry.proto.trace.v1.Span.Link.attributes: object expected"); + message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]); + } + } + if (object.droppedAttributesCount != null) + message.droppedAttributesCount = object.droppedAttributesCount >>> 0; + if (object.flags != null) + message.flags = object.flags >>> 0; + return message; + }; + /** + * Creates a plain object from a Link message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.trace.v1.Span.Link + * @static + * @param {opentelemetry.proto.trace.v1.Span.Link} message Link + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Link.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.attributes = []; + if (options.defaults) { + if (options.bytes === String) + object.traceId = ""; + else { + object.traceId = []; + if (options.bytes !== Array) + object.traceId = $util.newBuffer(object.traceId); + } + if (options.bytes === String) + object.spanId = ""; + else { + object.spanId = []; + if (options.bytes !== Array) + object.spanId = $util.newBuffer(object.spanId); + } + object.traceState = ""; + object.droppedAttributesCount = 0; + object.flags = 0; + } + if (message.traceId != null && message.hasOwnProperty("traceId")) + object.traceId = options.bytes === String ? $util.base64.encode(message.traceId, 0, message.traceId.length) : options.bytes === Array ? Array.prototype.slice.call(message.traceId) : message.traceId; + if (message.spanId != null && message.hasOwnProperty("spanId")) + object.spanId = options.bytes === String ? $util.base64.encode(message.spanId, 0, message.spanId.length) : options.bytes === Array ? Array.prototype.slice.call(message.spanId) : message.spanId; + if (message.traceState != null && message.hasOwnProperty("traceState")) + object.traceState = message.traceState; + if (message.attributes && message.attributes.length) { + object.attributes = []; + for (var j = 0; j < message.attributes.length; ++j) + object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options); + } + if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) + object.droppedAttributesCount = message.droppedAttributesCount; + if (message.flags != null && message.hasOwnProperty("flags")) + object.flags = message.flags; + return object; + }; + /** + * Converts this Link to JSON. + * @function toJSON + * @memberof opentelemetry.proto.trace.v1.Span.Link + * @instance + * @returns {Object.} JSON object + */ + Link.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for Link + * @function getTypeUrl + * @memberof opentelemetry.proto.trace.v1.Span.Link + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Link.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.trace.v1.Span.Link"; + }; + return Link; + })(); + return Span; + })(); + v1.Status = (function () { + /** + * Properties of a Status. + * @memberof opentelemetry.proto.trace.v1 + * @interface IStatus + * @property {string|null} [message] Status message + * @property {opentelemetry.proto.trace.v1.Status.StatusCode|null} [code] Status code + */ + /** + * Constructs a new Status. + * @memberof opentelemetry.proto.trace.v1 + * @classdesc Represents a Status. + * @implements IStatus + * @constructor + * @param {opentelemetry.proto.trace.v1.IStatus=} [properties] Properties to set + */ + function Status(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * Status message. + * @member {string|null|undefined} message + * @memberof opentelemetry.proto.trace.v1.Status + * @instance + */ + Status.prototype.message = null; + /** + * Status code. + * @member {opentelemetry.proto.trace.v1.Status.StatusCode|null|undefined} code + * @memberof opentelemetry.proto.trace.v1.Status + * @instance + */ + Status.prototype.code = null; + /** + * Creates a new Status instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.trace.v1.Status + * @static + * @param {opentelemetry.proto.trace.v1.IStatus=} [properties] Properties to set + * @returns {opentelemetry.proto.trace.v1.Status} Status instance + */ + Status.create = function create(properties) { + return new Status(properties); + }; + /** + * Encodes the specified Status message. Does not implicitly {@link opentelemetry.proto.trace.v1.Status.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.trace.v1.Status + * @static + * @param {opentelemetry.proto.trace.v1.IStatus} message Status message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Status.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.message != null && Object.hasOwnProperty.call(message, "message")) + writer.uint32(/* id 2, wireType 2 =*/ 18).string(message.message); + if (message.code != null && Object.hasOwnProperty.call(message, "code")) + writer.uint32(/* id 3, wireType 0 =*/ 24).int32(message.code); + return writer; + }; + /** + * Encodes the specified Status message, length delimited. Does not implicitly {@link opentelemetry.proto.trace.v1.Status.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.trace.v1.Status + * @static + * @param {opentelemetry.proto.trace.v1.IStatus} message Status message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Status.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes a Status message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.trace.v1.Status + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.trace.v1.Status} Status + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Status.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.trace.v1.Status(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 2: { + message.message = reader.string(); + break; + } + case 3: { + message.code = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes a Status message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.trace.v1.Status + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.trace.v1.Status} Status + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Status.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies a Status message. + * @function verify + * @memberof opentelemetry.proto.trace.v1.Status + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Status.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.message != null && message.hasOwnProperty("message")) + if (!$util.isString(message.message)) + return "message: string expected"; + if (message.code != null && message.hasOwnProperty("code")) + switch (message.code) { + default: + return "code: enum value expected"; + case 0: + case 1: + case 2: + break; + } + return null; + }; + /** + * Creates a Status message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.trace.v1.Status + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.trace.v1.Status} Status + */ + Status.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.trace.v1.Status) + return object; + var message = new $root.opentelemetry.proto.trace.v1.Status(); + if (object.message != null) + message.message = String(object.message); + switch (object.code) { + default: + if (typeof object.code === "number") { + message.code = object.code; + break; + } + break; + case "STATUS_CODE_UNSET": + case 0: + message.code = 0; + break; + case "STATUS_CODE_OK": + case 1: + message.code = 1; + break; + case "STATUS_CODE_ERROR": + case 2: + message.code = 2; + break; + } + return message; + }; + /** + * Creates a plain object from a Status message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.trace.v1.Status + * @static + * @param {opentelemetry.proto.trace.v1.Status} message Status + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Status.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.message = ""; + object.code = options.enums === String ? "STATUS_CODE_UNSET" : 0; + } + if (message.message != null && message.hasOwnProperty("message")) + object.message = message.message; + if (message.code != null && message.hasOwnProperty("code")) + object.code = options.enums === String ? $root.opentelemetry.proto.trace.v1.Status.StatusCode[message.code] === undefined ? message.code : $root.opentelemetry.proto.trace.v1.Status.StatusCode[message.code] : message.code; + return object; + }; + /** + * Converts this Status to JSON. + * @function toJSON + * @memberof opentelemetry.proto.trace.v1.Status + * @instance + * @returns {Object.} JSON object + */ + Status.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for Status + * @function getTypeUrl + * @memberof opentelemetry.proto.trace.v1.Status + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Status.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.trace.v1.Status"; + }; + /** + * StatusCode enum. + * @name opentelemetry.proto.trace.v1.Status.StatusCode + * @enum {number} + * @property {number} STATUS_CODE_UNSET=0 STATUS_CODE_UNSET value + * @property {number} STATUS_CODE_OK=1 STATUS_CODE_OK value + * @property {number} STATUS_CODE_ERROR=2 STATUS_CODE_ERROR value + */ + Status.StatusCode = (function () { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "STATUS_CODE_UNSET"] = 0; + values[valuesById[1] = "STATUS_CODE_OK"] = 1; + values[valuesById[2] = "STATUS_CODE_ERROR"] = 2; + return values; + })(); + return Status; + })(); + /** + * SpanFlags enum. + * @name opentelemetry.proto.trace.v1.SpanFlags + * @enum {number} + * @property {number} SPAN_FLAGS_DO_NOT_USE=0 SPAN_FLAGS_DO_NOT_USE value + * @property {number} SPAN_FLAGS_TRACE_FLAGS_MASK=255 SPAN_FLAGS_TRACE_FLAGS_MASK value + * @property {number} SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK=256 SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK value + * @property {number} SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK=512 SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK value + */ + v1.SpanFlags = (function () { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "SPAN_FLAGS_DO_NOT_USE"] = 0; + values[valuesById[255] = "SPAN_FLAGS_TRACE_FLAGS_MASK"] = 255; + values[valuesById[256] = "SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK"] = 256; + values[valuesById[512] = "SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK"] = 512; + return values; + })(); + return v1; + })(); + return trace; + })(); + proto.collector = (function () { + /** + * Namespace collector. + * @memberof opentelemetry.proto + * @namespace + */ + var collector = {}; + collector.trace = (function () { + /** + * Namespace trace. + * @memberof opentelemetry.proto.collector + * @namespace + */ + var trace = {}; + trace.v1 = (function () { + /** + * Namespace v1. + * @memberof opentelemetry.proto.collector.trace + * @namespace + */ + var v1 = {}; + v1.TraceService = (function () { + /** + * Constructs a new TraceService service. + * @memberof opentelemetry.proto.collector.trace.v1 + * @classdesc Represents a TraceService + * @extends $protobuf.rpc.Service + * @constructor + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ + function TraceService(rpcImpl, requestDelimited, responseDelimited) { + $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); + } + (TraceService.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = TraceService; + /** + * Creates new TraceService service using the specified rpc implementation. + * @function create + * @memberof opentelemetry.proto.collector.trace.v1.TraceService + * @static + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + * @returns {TraceService} RPC service. Useful where requests and/or responses are streamed. + */ + TraceService.create = function create(rpcImpl, requestDelimited, responseDelimited) { + return new this(rpcImpl, requestDelimited, responseDelimited); + }; + /** + * Callback as used by {@link opentelemetry.proto.collector.trace.v1.TraceService#export_}. + * @memberof opentelemetry.proto.collector.trace.v1.TraceService + * @typedef ExportCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse} [response] ExportTraceServiceResponse + */ + /** + * Calls Export. + * @function export + * @memberof opentelemetry.proto.collector.trace.v1.TraceService + * @instance + * @param {opentelemetry.proto.collector.trace.v1.IExportTraceServiceRequest} request ExportTraceServiceRequest message or plain object + * @param {opentelemetry.proto.collector.trace.v1.TraceService.ExportCallback} callback Node-style callback called with the error, if any, and ExportTraceServiceResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(TraceService.prototype["export"] = function export_(request, callback) { + return this.rpcCall(export_, $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest, $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse, request, callback); + }, "name", { value: "Export" }); + /** + * Calls Export. + * @function export + * @memberof opentelemetry.proto.collector.trace.v1.TraceService + * @instance + * @param {opentelemetry.proto.collector.trace.v1.IExportTraceServiceRequest} request ExportTraceServiceRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + return TraceService; + })(); + v1.ExportTraceServiceRequest = (function () { + /** + * Properties of an ExportTraceServiceRequest. + * @memberof opentelemetry.proto.collector.trace.v1 + * @interface IExportTraceServiceRequest + * @property {Array.|null} [resourceSpans] ExportTraceServiceRequest resourceSpans + */ + /** + * Constructs a new ExportTraceServiceRequest. + * @memberof opentelemetry.proto.collector.trace.v1 + * @classdesc Represents an ExportTraceServiceRequest. + * @implements IExportTraceServiceRequest + * @constructor + * @param {opentelemetry.proto.collector.trace.v1.IExportTraceServiceRequest=} [properties] Properties to set + */ + function ExportTraceServiceRequest(properties) { + this.resourceSpans = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * ExportTraceServiceRequest resourceSpans. + * @member {Array.} resourceSpans + * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest + * @instance + */ + ExportTraceServiceRequest.prototype.resourceSpans = $util.emptyArray; + /** + * Creates a new ExportTraceServiceRequest instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest + * @static + * @param {opentelemetry.proto.collector.trace.v1.IExportTraceServiceRequest=} [properties] Properties to set + * @returns {opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest} ExportTraceServiceRequest instance + */ + ExportTraceServiceRequest.create = function create(properties) { + return new ExportTraceServiceRequest(properties); + }; + /** + * Encodes the specified ExportTraceServiceRequest message. Does not implicitly {@link opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest + * @static + * @param {opentelemetry.proto.collector.trace.v1.IExportTraceServiceRequest} message ExportTraceServiceRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExportTraceServiceRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.resourceSpans != null && message.resourceSpans.length) + for (var i = 0; i < message.resourceSpans.length; ++i) + $root.opentelemetry.proto.trace.v1.ResourceSpans.encode(message.resourceSpans[i], writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); + return writer; + }; + /** + * Encodes the specified ExportTraceServiceRequest message, length delimited. Does not implicitly {@link opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest + * @static + * @param {opentelemetry.proto.collector.trace.v1.IExportTraceServiceRequest} message ExportTraceServiceRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExportTraceServiceRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes an ExportTraceServiceRequest message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest} ExportTraceServiceRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExportTraceServiceRequest.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.resourceSpans && message.resourceSpans.length)) + message.resourceSpans = []; + message.resourceSpans.push($root.opentelemetry.proto.trace.v1.ResourceSpans.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes an ExportTraceServiceRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest} ExportTraceServiceRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExportTraceServiceRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies an ExportTraceServiceRequest message. + * @function verify + * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ExportTraceServiceRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.resourceSpans != null && message.hasOwnProperty("resourceSpans")) { + if (!Array.isArray(message.resourceSpans)) + return "resourceSpans: array expected"; + for (var i = 0; i < message.resourceSpans.length; ++i) { + var error = $root.opentelemetry.proto.trace.v1.ResourceSpans.verify(message.resourceSpans[i]); + if (error) + return "resourceSpans." + error; + } + } + return null; + }; + /** + * Creates an ExportTraceServiceRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest} ExportTraceServiceRequest + */ + ExportTraceServiceRequest.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest) + return object; + var message = new $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest(); + if (object.resourceSpans) { + if (!Array.isArray(object.resourceSpans)) + throw TypeError(".opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest.resourceSpans: array expected"); + message.resourceSpans = []; + for (var i = 0; i < object.resourceSpans.length; ++i) { + if (typeof object.resourceSpans[i] !== "object") + throw TypeError(".opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest.resourceSpans: object expected"); + message.resourceSpans[i] = $root.opentelemetry.proto.trace.v1.ResourceSpans.fromObject(object.resourceSpans[i]); + } + } + return message; + }; + /** + * Creates a plain object from an ExportTraceServiceRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest + * @static + * @param {opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest} message ExportTraceServiceRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExportTraceServiceRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.resourceSpans = []; + if (message.resourceSpans && message.resourceSpans.length) { + object.resourceSpans = []; + for (var j = 0; j < message.resourceSpans.length; ++j) + object.resourceSpans[j] = $root.opentelemetry.proto.trace.v1.ResourceSpans.toObject(message.resourceSpans[j], options); + } + return object; + }; + /** + * Converts this ExportTraceServiceRequest to JSON. + * @function toJSON + * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest + * @instance + * @returns {Object.} JSON object + */ + ExportTraceServiceRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for ExportTraceServiceRequest + * @function getTypeUrl + * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExportTraceServiceRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest"; + }; + return ExportTraceServiceRequest; + })(); + v1.ExportTraceServiceResponse = (function () { + /** + * Properties of an ExportTraceServiceResponse. + * @memberof opentelemetry.proto.collector.trace.v1 + * @interface IExportTraceServiceResponse + * @property {opentelemetry.proto.collector.trace.v1.IExportTracePartialSuccess|null} [partialSuccess] ExportTraceServiceResponse partialSuccess + */ + /** + * Constructs a new ExportTraceServiceResponse. + * @memberof opentelemetry.proto.collector.trace.v1 + * @classdesc Represents an ExportTraceServiceResponse. + * @implements IExportTraceServiceResponse + * @constructor + * @param {opentelemetry.proto.collector.trace.v1.IExportTraceServiceResponse=} [properties] Properties to set + */ + function ExportTraceServiceResponse(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * ExportTraceServiceResponse partialSuccess. + * @member {opentelemetry.proto.collector.trace.v1.IExportTracePartialSuccess|null|undefined} partialSuccess + * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse + * @instance + */ + ExportTraceServiceResponse.prototype.partialSuccess = null; + /** + * Creates a new ExportTraceServiceResponse instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse + * @static + * @param {opentelemetry.proto.collector.trace.v1.IExportTraceServiceResponse=} [properties] Properties to set + * @returns {opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse} ExportTraceServiceResponse instance + */ + ExportTraceServiceResponse.create = function create(properties) { + return new ExportTraceServiceResponse(properties); + }; + /** + * Encodes the specified ExportTraceServiceResponse message. Does not implicitly {@link opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse + * @static + * @param {opentelemetry.proto.collector.trace.v1.IExportTraceServiceResponse} message ExportTraceServiceResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExportTraceServiceResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.partialSuccess != null && Object.hasOwnProperty.call(message, "partialSuccess")) + $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.encode(message.partialSuccess, writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); + return writer; + }; + /** + * Encodes the specified ExportTraceServiceResponse message, length delimited. Does not implicitly {@link opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse + * @static + * @param {opentelemetry.proto.collector.trace.v1.IExportTraceServiceResponse} message ExportTraceServiceResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExportTraceServiceResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes an ExportTraceServiceResponse message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse} ExportTraceServiceResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExportTraceServiceResponse.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.partialSuccess = $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes an ExportTraceServiceResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse} ExportTraceServiceResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExportTraceServiceResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies an ExportTraceServiceResponse message. + * @function verify + * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ExportTraceServiceResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.partialSuccess != null && message.hasOwnProperty("partialSuccess")) { + var error = $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.verify(message.partialSuccess); + if (error) + return "partialSuccess." + error; + } + return null; + }; + /** + * Creates an ExportTraceServiceResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse} ExportTraceServiceResponse + */ + ExportTraceServiceResponse.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse) + return object; + var message = new $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse(); + if (object.partialSuccess != null) { + if (typeof object.partialSuccess !== "object") + throw TypeError(".opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse.partialSuccess: object expected"); + message.partialSuccess = $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.fromObject(object.partialSuccess); + } + return message; + }; + /** + * Creates a plain object from an ExportTraceServiceResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse + * @static + * @param {opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse} message ExportTraceServiceResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExportTraceServiceResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.partialSuccess = null; + if (message.partialSuccess != null && message.hasOwnProperty("partialSuccess")) + object.partialSuccess = $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.toObject(message.partialSuccess, options); + return object; + }; + /** + * Converts this ExportTraceServiceResponse to JSON. + * @function toJSON + * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse + * @instance + * @returns {Object.} JSON object + */ + ExportTraceServiceResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for ExportTraceServiceResponse + * @function getTypeUrl + * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExportTraceServiceResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse"; + }; + return ExportTraceServiceResponse; + })(); + v1.ExportTracePartialSuccess = (function () { + /** + * Properties of an ExportTracePartialSuccess. + * @memberof opentelemetry.proto.collector.trace.v1 + * @interface IExportTracePartialSuccess + * @property {number|Long|null} [rejectedSpans] ExportTracePartialSuccess rejectedSpans + * @property {string|null} [errorMessage] ExportTracePartialSuccess errorMessage + */ + /** + * Constructs a new ExportTracePartialSuccess. + * @memberof opentelemetry.proto.collector.trace.v1 + * @classdesc Represents an ExportTracePartialSuccess. + * @implements IExportTracePartialSuccess + * @constructor + * @param {opentelemetry.proto.collector.trace.v1.IExportTracePartialSuccess=} [properties] Properties to set + */ + function ExportTracePartialSuccess(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * ExportTracePartialSuccess rejectedSpans. + * @member {number|Long|null|undefined} rejectedSpans + * @memberof opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess + * @instance + */ + ExportTracePartialSuccess.prototype.rejectedSpans = null; + /** + * ExportTracePartialSuccess errorMessage. + * @member {string|null|undefined} errorMessage + * @memberof opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess + * @instance + */ + ExportTracePartialSuccess.prototype.errorMessage = null; + /** + * Creates a new ExportTracePartialSuccess instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess + * @static + * @param {opentelemetry.proto.collector.trace.v1.IExportTracePartialSuccess=} [properties] Properties to set + * @returns {opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess} ExportTracePartialSuccess instance + */ + ExportTracePartialSuccess.create = function create(properties) { + return new ExportTracePartialSuccess(properties); + }; + /** + * Encodes the specified ExportTracePartialSuccess message. Does not implicitly {@link opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess + * @static + * @param {opentelemetry.proto.collector.trace.v1.IExportTracePartialSuccess} message ExportTracePartialSuccess message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExportTracePartialSuccess.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.rejectedSpans != null && Object.hasOwnProperty.call(message, "rejectedSpans")) + writer.uint32(/* id 1, wireType 0 =*/ 8).int64(message.rejectedSpans); + if (message.errorMessage != null && Object.hasOwnProperty.call(message, "errorMessage")) + writer.uint32(/* id 2, wireType 2 =*/ 18).string(message.errorMessage); + return writer; + }; + /** + * Encodes the specified ExportTracePartialSuccess message, length delimited. Does not implicitly {@link opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess + * @static + * @param {opentelemetry.proto.collector.trace.v1.IExportTracePartialSuccess} message ExportTracePartialSuccess message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExportTracePartialSuccess.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes an ExportTracePartialSuccess message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess} ExportTracePartialSuccess + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExportTracePartialSuccess.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.rejectedSpans = reader.int64(); + break; + } + case 2: { + message.errorMessage = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes an ExportTracePartialSuccess message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess} ExportTracePartialSuccess + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExportTracePartialSuccess.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies an ExportTracePartialSuccess message. + * @function verify + * @memberof opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ExportTracePartialSuccess.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.rejectedSpans != null && message.hasOwnProperty("rejectedSpans")) + if (!$util.isInteger(message.rejectedSpans) && !(message.rejectedSpans && $util.isInteger(message.rejectedSpans.low) && $util.isInteger(message.rejectedSpans.high))) + return "rejectedSpans: integer|Long expected"; + if (message.errorMessage != null && message.hasOwnProperty("errorMessage")) + if (!$util.isString(message.errorMessage)) + return "errorMessage: string expected"; + return null; + }; + /** + * Creates an ExportTracePartialSuccess message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess} ExportTracePartialSuccess + */ + ExportTracePartialSuccess.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess) + return object; + var message = new $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess(); + if (object.rejectedSpans != null) + if ($util.Long) + (message.rejectedSpans = $util.Long.fromValue(object.rejectedSpans)).unsigned = false; + else if (typeof object.rejectedSpans === "string") + message.rejectedSpans = parseInt(object.rejectedSpans, 10); + else if (typeof object.rejectedSpans === "number") + message.rejectedSpans = object.rejectedSpans; + else if (typeof object.rejectedSpans === "object") + message.rejectedSpans = new $util.LongBits(object.rejectedSpans.low >>> 0, object.rejectedSpans.high >>> 0).toNumber(); + if (object.errorMessage != null) + message.errorMessage = String(object.errorMessage); + return message; + }; + /** + * Creates a plain object from an ExportTracePartialSuccess message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess + * @static + * @param {opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess} message ExportTracePartialSuccess + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExportTracePartialSuccess.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.rejectedSpans = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } + else + object.rejectedSpans = options.longs === String ? "0" : 0; + object.errorMessage = ""; + } + if (message.rejectedSpans != null && message.hasOwnProperty("rejectedSpans")) + if (typeof message.rejectedSpans === "number") + object.rejectedSpans = options.longs === String ? String(message.rejectedSpans) : message.rejectedSpans; + else + object.rejectedSpans = options.longs === String ? $util.Long.prototype.toString.call(message.rejectedSpans) : options.longs === Number ? new $util.LongBits(message.rejectedSpans.low >>> 0, message.rejectedSpans.high >>> 0).toNumber() : message.rejectedSpans; + if (message.errorMessage != null && message.hasOwnProperty("errorMessage")) + object.errorMessage = message.errorMessage; + return object; + }; + /** + * Converts this ExportTracePartialSuccess to JSON. + * @function toJSON + * @memberof opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess + * @instance + * @returns {Object.} JSON object + */ + ExportTracePartialSuccess.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for ExportTracePartialSuccess + * @function getTypeUrl + * @memberof opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExportTracePartialSuccess.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess"; + }; + return ExportTracePartialSuccess; + })(); + return v1; + })(); + return trace; + })(); + collector.metrics = (function () { + /** + * Namespace metrics. + * @memberof opentelemetry.proto.collector + * @namespace + */ + var metrics = {}; + metrics.v1 = (function () { + /** + * Namespace v1. + * @memberof opentelemetry.proto.collector.metrics + * @namespace + */ + var v1 = {}; + v1.MetricsService = (function () { + /** + * Constructs a new MetricsService service. + * @memberof opentelemetry.proto.collector.metrics.v1 + * @classdesc Represents a MetricsService + * @extends $protobuf.rpc.Service + * @constructor + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ + function MetricsService(rpcImpl, requestDelimited, responseDelimited) { + $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); + } + (MetricsService.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = MetricsService; + /** + * Creates new MetricsService service using the specified rpc implementation. + * @function create + * @memberof opentelemetry.proto.collector.metrics.v1.MetricsService + * @static + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + * @returns {MetricsService} RPC service. Useful where requests and/or responses are streamed. + */ + MetricsService.create = function create(rpcImpl, requestDelimited, responseDelimited) { + return new this(rpcImpl, requestDelimited, responseDelimited); + }; + /** + * Callback as used by {@link opentelemetry.proto.collector.metrics.v1.MetricsService#export_}. + * @memberof opentelemetry.proto.collector.metrics.v1.MetricsService + * @typedef ExportCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse} [response] ExportMetricsServiceResponse + */ + /** + * Calls Export. + * @function export + * @memberof opentelemetry.proto.collector.metrics.v1.MetricsService + * @instance + * @param {opentelemetry.proto.collector.metrics.v1.IExportMetricsServiceRequest} request ExportMetricsServiceRequest message or plain object + * @param {opentelemetry.proto.collector.metrics.v1.MetricsService.ExportCallback} callback Node-style callback called with the error, if any, and ExportMetricsServiceResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(MetricsService.prototype["export"] = function export_(request, callback) { + return this.rpcCall(export_, $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest, $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse, request, callback); + }, "name", { value: "Export" }); + /** + * Calls Export. + * @function export + * @memberof opentelemetry.proto.collector.metrics.v1.MetricsService + * @instance + * @param {opentelemetry.proto.collector.metrics.v1.IExportMetricsServiceRequest} request ExportMetricsServiceRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + return MetricsService; + })(); + v1.ExportMetricsServiceRequest = (function () { + /** + * Properties of an ExportMetricsServiceRequest. + * @memberof opentelemetry.proto.collector.metrics.v1 + * @interface IExportMetricsServiceRequest + * @property {Array.|null} [resourceMetrics] ExportMetricsServiceRequest resourceMetrics + */ + /** + * Constructs a new ExportMetricsServiceRequest. + * @memberof opentelemetry.proto.collector.metrics.v1 + * @classdesc Represents an ExportMetricsServiceRequest. + * @implements IExportMetricsServiceRequest + * @constructor + * @param {opentelemetry.proto.collector.metrics.v1.IExportMetricsServiceRequest=} [properties] Properties to set + */ + function ExportMetricsServiceRequest(properties) { + this.resourceMetrics = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * ExportMetricsServiceRequest resourceMetrics. + * @member {Array.} resourceMetrics + * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest + * @instance + */ + ExportMetricsServiceRequest.prototype.resourceMetrics = $util.emptyArray; + /** + * Creates a new ExportMetricsServiceRequest instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest + * @static + * @param {opentelemetry.proto.collector.metrics.v1.IExportMetricsServiceRequest=} [properties] Properties to set + * @returns {opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest} ExportMetricsServiceRequest instance + */ + ExportMetricsServiceRequest.create = function create(properties) { + return new ExportMetricsServiceRequest(properties); + }; + /** + * Encodes the specified ExportMetricsServiceRequest message. Does not implicitly {@link opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest + * @static + * @param {opentelemetry.proto.collector.metrics.v1.IExportMetricsServiceRequest} message ExportMetricsServiceRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExportMetricsServiceRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.resourceMetrics != null && message.resourceMetrics.length) + for (var i = 0; i < message.resourceMetrics.length; ++i) + $root.opentelemetry.proto.metrics.v1.ResourceMetrics.encode(message.resourceMetrics[i], writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); + return writer; + }; + /** + * Encodes the specified ExportMetricsServiceRequest message, length delimited. Does not implicitly {@link opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest + * @static + * @param {opentelemetry.proto.collector.metrics.v1.IExportMetricsServiceRequest} message ExportMetricsServiceRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExportMetricsServiceRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes an ExportMetricsServiceRequest message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest} ExportMetricsServiceRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExportMetricsServiceRequest.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.resourceMetrics && message.resourceMetrics.length)) + message.resourceMetrics = []; + message.resourceMetrics.push($root.opentelemetry.proto.metrics.v1.ResourceMetrics.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes an ExportMetricsServiceRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest} ExportMetricsServiceRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExportMetricsServiceRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies an ExportMetricsServiceRequest message. + * @function verify + * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ExportMetricsServiceRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.resourceMetrics != null && message.hasOwnProperty("resourceMetrics")) { + if (!Array.isArray(message.resourceMetrics)) + return "resourceMetrics: array expected"; + for (var i = 0; i < message.resourceMetrics.length; ++i) { + var error = $root.opentelemetry.proto.metrics.v1.ResourceMetrics.verify(message.resourceMetrics[i]); + if (error) + return "resourceMetrics." + error; + } + } + return null; + }; + /** + * Creates an ExportMetricsServiceRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest} ExportMetricsServiceRequest + */ + ExportMetricsServiceRequest.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest) + return object; + var message = new $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest(); + if (object.resourceMetrics) { + if (!Array.isArray(object.resourceMetrics)) + throw TypeError(".opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest.resourceMetrics: array expected"); + message.resourceMetrics = []; + for (var i = 0; i < object.resourceMetrics.length; ++i) { + if (typeof object.resourceMetrics[i] !== "object") + throw TypeError(".opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest.resourceMetrics: object expected"); + message.resourceMetrics[i] = $root.opentelemetry.proto.metrics.v1.ResourceMetrics.fromObject(object.resourceMetrics[i]); + } + } + return message; + }; + /** + * Creates a plain object from an ExportMetricsServiceRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest + * @static + * @param {opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest} message ExportMetricsServiceRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExportMetricsServiceRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.resourceMetrics = []; + if (message.resourceMetrics && message.resourceMetrics.length) { + object.resourceMetrics = []; + for (var j = 0; j < message.resourceMetrics.length; ++j) + object.resourceMetrics[j] = $root.opentelemetry.proto.metrics.v1.ResourceMetrics.toObject(message.resourceMetrics[j], options); + } + return object; + }; + /** + * Converts this ExportMetricsServiceRequest to JSON. + * @function toJSON + * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest + * @instance + * @returns {Object.} JSON object + */ + ExportMetricsServiceRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for ExportMetricsServiceRequest + * @function getTypeUrl + * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExportMetricsServiceRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest"; + }; + return ExportMetricsServiceRequest; + })(); + v1.ExportMetricsServiceResponse = (function () { + /** + * Properties of an ExportMetricsServiceResponse. + * @memberof opentelemetry.proto.collector.metrics.v1 + * @interface IExportMetricsServiceResponse + * @property {opentelemetry.proto.collector.metrics.v1.IExportMetricsPartialSuccess|null} [partialSuccess] ExportMetricsServiceResponse partialSuccess + */ + /** + * Constructs a new ExportMetricsServiceResponse. + * @memberof opentelemetry.proto.collector.metrics.v1 + * @classdesc Represents an ExportMetricsServiceResponse. + * @implements IExportMetricsServiceResponse + * @constructor + * @param {opentelemetry.proto.collector.metrics.v1.IExportMetricsServiceResponse=} [properties] Properties to set + */ + function ExportMetricsServiceResponse(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * ExportMetricsServiceResponse partialSuccess. + * @member {opentelemetry.proto.collector.metrics.v1.IExportMetricsPartialSuccess|null|undefined} partialSuccess + * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse + * @instance + */ + ExportMetricsServiceResponse.prototype.partialSuccess = null; + /** + * Creates a new ExportMetricsServiceResponse instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse + * @static + * @param {opentelemetry.proto.collector.metrics.v1.IExportMetricsServiceResponse=} [properties] Properties to set + * @returns {opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse} ExportMetricsServiceResponse instance + */ + ExportMetricsServiceResponse.create = function create(properties) { + return new ExportMetricsServiceResponse(properties); + }; + /** + * Encodes the specified ExportMetricsServiceResponse message. Does not implicitly {@link opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse + * @static + * @param {opentelemetry.proto.collector.metrics.v1.IExportMetricsServiceResponse} message ExportMetricsServiceResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExportMetricsServiceResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.partialSuccess != null && Object.hasOwnProperty.call(message, "partialSuccess")) + $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.encode(message.partialSuccess, writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); + return writer; + }; + /** + * Encodes the specified ExportMetricsServiceResponse message, length delimited. Does not implicitly {@link opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse + * @static + * @param {opentelemetry.proto.collector.metrics.v1.IExportMetricsServiceResponse} message ExportMetricsServiceResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExportMetricsServiceResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes an ExportMetricsServiceResponse message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse} ExportMetricsServiceResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExportMetricsServiceResponse.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.partialSuccess = $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes an ExportMetricsServiceResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse} ExportMetricsServiceResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExportMetricsServiceResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies an ExportMetricsServiceResponse message. + * @function verify + * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ExportMetricsServiceResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.partialSuccess != null && message.hasOwnProperty("partialSuccess")) { + var error = $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.verify(message.partialSuccess); + if (error) + return "partialSuccess." + error; + } + return null; + }; + /** + * Creates an ExportMetricsServiceResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse} ExportMetricsServiceResponse + */ + ExportMetricsServiceResponse.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse) + return object; + var message = new $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse(); + if (object.partialSuccess != null) { + if (typeof object.partialSuccess !== "object") + throw TypeError(".opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse.partialSuccess: object expected"); + message.partialSuccess = $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.fromObject(object.partialSuccess); + } + return message; + }; + /** + * Creates a plain object from an ExportMetricsServiceResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse + * @static + * @param {opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse} message ExportMetricsServiceResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExportMetricsServiceResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.partialSuccess = null; + if (message.partialSuccess != null && message.hasOwnProperty("partialSuccess")) + object.partialSuccess = $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.toObject(message.partialSuccess, options); + return object; + }; + /** + * Converts this ExportMetricsServiceResponse to JSON. + * @function toJSON + * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse + * @instance + * @returns {Object.} JSON object + */ + ExportMetricsServiceResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for ExportMetricsServiceResponse + * @function getTypeUrl + * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExportMetricsServiceResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse"; + }; + return ExportMetricsServiceResponse; + })(); + v1.ExportMetricsPartialSuccess = (function () { + /** + * Properties of an ExportMetricsPartialSuccess. + * @memberof opentelemetry.proto.collector.metrics.v1 + * @interface IExportMetricsPartialSuccess + * @property {number|Long|null} [rejectedDataPoints] ExportMetricsPartialSuccess rejectedDataPoints + * @property {string|null} [errorMessage] ExportMetricsPartialSuccess errorMessage + */ + /** + * Constructs a new ExportMetricsPartialSuccess. + * @memberof opentelemetry.proto.collector.metrics.v1 + * @classdesc Represents an ExportMetricsPartialSuccess. + * @implements IExportMetricsPartialSuccess + * @constructor + * @param {opentelemetry.proto.collector.metrics.v1.IExportMetricsPartialSuccess=} [properties] Properties to set + */ + function ExportMetricsPartialSuccess(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * ExportMetricsPartialSuccess rejectedDataPoints. + * @member {number|Long|null|undefined} rejectedDataPoints + * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess + * @instance + */ + ExportMetricsPartialSuccess.prototype.rejectedDataPoints = null; + /** + * ExportMetricsPartialSuccess errorMessage. + * @member {string|null|undefined} errorMessage + * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess + * @instance + */ + ExportMetricsPartialSuccess.prototype.errorMessage = null; + /** + * Creates a new ExportMetricsPartialSuccess instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess + * @static + * @param {opentelemetry.proto.collector.metrics.v1.IExportMetricsPartialSuccess=} [properties] Properties to set + * @returns {opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess} ExportMetricsPartialSuccess instance + */ + ExportMetricsPartialSuccess.create = function create(properties) { + return new ExportMetricsPartialSuccess(properties); + }; + /** + * Encodes the specified ExportMetricsPartialSuccess message. Does not implicitly {@link opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess + * @static + * @param {opentelemetry.proto.collector.metrics.v1.IExportMetricsPartialSuccess} message ExportMetricsPartialSuccess message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExportMetricsPartialSuccess.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.rejectedDataPoints != null && Object.hasOwnProperty.call(message, "rejectedDataPoints")) + writer.uint32(/* id 1, wireType 0 =*/ 8).int64(message.rejectedDataPoints); + if (message.errorMessage != null && Object.hasOwnProperty.call(message, "errorMessage")) + writer.uint32(/* id 2, wireType 2 =*/ 18).string(message.errorMessage); + return writer; + }; + /** + * Encodes the specified ExportMetricsPartialSuccess message, length delimited. Does not implicitly {@link opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess + * @static + * @param {opentelemetry.proto.collector.metrics.v1.IExportMetricsPartialSuccess} message ExportMetricsPartialSuccess message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExportMetricsPartialSuccess.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes an ExportMetricsPartialSuccess message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess} ExportMetricsPartialSuccess + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExportMetricsPartialSuccess.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.rejectedDataPoints = reader.int64(); + break; + } + case 2: { + message.errorMessage = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes an ExportMetricsPartialSuccess message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess} ExportMetricsPartialSuccess + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExportMetricsPartialSuccess.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies an ExportMetricsPartialSuccess message. + * @function verify + * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ExportMetricsPartialSuccess.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.rejectedDataPoints != null && message.hasOwnProperty("rejectedDataPoints")) + if (!$util.isInteger(message.rejectedDataPoints) && !(message.rejectedDataPoints && $util.isInteger(message.rejectedDataPoints.low) && $util.isInteger(message.rejectedDataPoints.high))) + return "rejectedDataPoints: integer|Long expected"; + if (message.errorMessage != null && message.hasOwnProperty("errorMessage")) + if (!$util.isString(message.errorMessage)) + return "errorMessage: string expected"; + return null; + }; + /** + * Creates an ExportMetricsPartialSuccess message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess} ExportMetricsPartialSuccess + */ + ExportMetricsPartialSuccess.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess) + return object; + var message = new $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess(); + if (object.rejectedDataPoints != null) + if ($util.Long) + (message.rejectedDataPoints = $util.Long.fromValue(object.rejectedDataPoints)).unsigned = false; + else if (typeof object.rejectedDataPoints === "string") + message.rejectedDataPoints = parseInt(object.rejectedDataPoints, 10); + else if (typeof object.rejectedDataPoints === "number") + message.rejectedDataPoints = object.rejectedDataPoints; + else if (typeof object.rejectedDataPoints === "object") + message.rejectedDataPoints = new $util.LongBits(object.rejectedDataPoints.low >>> 0, object.rejectedDataPoints.high >>> 0).toNumber(); + if (object.errorMessage != null) + message.errorMessage = String(object.errorMessage); + return message; + }; + /** + * Creates a plain object from an ExportMetricsPartialSuccess message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess + * @static + * @param {opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess} message ExportMetricsPartialSuccess + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExportMetricsPartialSuccess.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.rejectedDataPoints = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } + else + object.rejectedDataPoints = options.longs === String ? "0" : 0; + object.errorMessage = ""; + } + if (message.rejectedDataPoints != null && message.hasOwnProperty("rejectedDataPoints")) + if (typeof message.rejectedDataPoints === "number") + object.rejectedDataPoints = options.longs === String ? String(message.rejectedDataPoints) : message.rejectedDataPoints; + else + object.rejectedDataPoints = options.longs === String ? $util.Long.prototype.toString.call(message.rejectedDataPoints) : options.longs === Number ? new $util.LongBits(message.rejectedDataPoints.low >>> 0, message.rejectedDataPoints.high >>> 0).toNumber() : message.rejectedDataPoints; + if (message.errorMessage != null && message.hasOwnProperty("errorMessage")) + object.errorMessage = message.errorMessage; + return object; + }; + /** + * Converts this ExportMetricsPartialSuccess to JSON. + * @function toJSON + * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess + * @instance + * @returns {Object.} JSON object + */ + ExportMetricsPartialSuccess.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for ExportMetricsPartialSuccess + * @function getTypeUrl + * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExportMetricsPartialSuccess.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess"; + }; + return ExportMetricsPartialSuccess; + })(); + return v1; + })(); + return metrics; + })(); + collector.logs = (function () { + /** + * Namespace logs. + * @memberof opentelemetry.proto.collector + * @namespace + */ + var logs = {}; + logs.v1 = (function () { + /** + * Namespace v1. + * @memberof opentelemetry.proto.collector.logs + * @namespace + */ + var v1 = {}; + v1.LogsService = (function () { + /** + * Constructs a new LogsService service. + * @memberof opentelemetry.proto.collector.logs.v1 + * @classdesc Represents a LogsService + * @extends $protobuf.rpc.Service + * @constructor + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ + function LogsService(rpcImpl, requestDelimited, responseDelimited) { + $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); + } + (LogsService.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = LogsService; + /** + * Creates new LogsService service using the specified rpc implementation. + * @function create + * @memberof opentelemetry.proto.collector.logs.v1.LogsService + * @static + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + * @returns {LogsService} RPC service. Useful where requests and/or responses are streamed. + */ + LogsService.create = function create(rpcImpl, requestDelimited, responseDelimited) { + return new this(rpcImpl, requestDelimited, responseDelimited); + }; + /** + * Callback as used by {@link opentelemetry.proto.collector.logs.v1.LogsService#export_}. + * @memberof opentelemetry.proto.collector.logs.v1.LogsService + * @typedef ExportCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse} [response] ExportLogsServiceResponse + */ + /** + * Calls Export. + * @function export + * @memberof opentelemetry.proto.collector.logs.v1.LogsService + * @instance + * @param {opentelemetry.proto.collector.logs.v1.IExportLogsServiceRequest} request ExportLogsServiceRequest message or plain object + * @param {opentelemetry.proto.collector.logs.v1.LogsService.ExportCallback} callback Node-style callback called with the error, if any, and ExportLogsServiceResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(LogsService.prototype["export"] = function export_(request, callback) { + return this.rpcCall(export_, $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest, $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse, request, callback); + }, "name", { value: "Export" }); + /** + * Calls Export. + * @function export + * @memberof opentelemetry.proto.collector.logs.v1.LogsService + * @instance + * @param {opentelemetry.proto.collector.logs.v1.IExportLogsServiceRequest} request ExportLogsServiceRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + return LogsService; + })(); + v1.ExportLogsServiceRequest = (function () { + /** + * Properties of an ExportLogsServiceRequest. + * @memberof opentelemetry.proto.collector.logs.v1 + * @interface IExportLogsServiceRequest + * @property {Array.|null} [resourceLogs] ExportLogsServiceRequest resourceLogs + */ + /** + * Constructs a new ExportLogsServiceRequest. + * @memberof opentelemetry.proto.collector.logs.v1 + * @classdesc Represents an ExportLogsServiceRequest. + * @implements IExportLogsServiceRequest + * @constructor + * @param {opentelemetry.proto.collector.logs.v1.IExportLogsServiceRequest=} [properties] Properties to set + */ + function ExportLogsServiceRequest(properties) { + this.resourceLogs = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * ExportLogsServiceRequest resourceLogs. + * @member {Array.} resourceLogs + * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest + * @instance + */ + ExportLogsServiceRequest.prototype.resourceLogs = $util.emptyArray; + /** + * Creates a new ExportLogsServiceRequest instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest + * @static + * @param {opentelemetry.proto.collector.logs.v1.IExportLogsServiceRequest=} [properties] Properties to set + * @returns {opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest} ExportLogsServiceRequest instance + */ + ExportLogsServiceRequest.create = function create(properties) { + return new ExportLogsServiceRequest(properties); + }; + /** + * Encodes the specified ExportLogsServiceRequest message. Does not implicitly {@link opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest + * @static + * @param {opentelemetry.proto.collector.logs.v1.IExportLogsServiceRequest} message ExportLogsServiceRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExportLogsServiceRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.resourceLogs != null && message.resourceLogs.length) + for (var i = 0; i < message.resourceLogs.length; ++i) + $root.opentelemetry.proto.logs.v1.ResourceLogs.encode(message.resourceLogs[i], writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); + return writer; + }; + /** + * Encodes the specified ExportLogsServiceRequest message, length delimited. Does not implicitly {@link opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest + * @static + * @param {opentelemetry.proto.collector.logs.v1.IExportLogsServiceRequest} message ExportLogsServiceRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExportLogsServiceRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes an ExportLogsServiceRequest message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest} ExportLogsServiceRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExportLogsServiceRequest.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.resourceLogs && message.resourceLogs.length)) + message.resourceLogs = []; + message.resourceLogs.push($root.opentelemetry.proto.logs.v1.ResourceLogs.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes an ExportLogsServiceRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest} ExportLogsServiceRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExportLogsServiceRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies an ExportLogsServiceRequest message. + * @function verify + * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ExportLogsServiceRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.resourceLogs != null && message.hasOwnProperty("resourceLogs")) { + if (!Array.isArray(message.resourceLogs)) + return "resourceLogs: array expected"; + for (var i = 0; i < message.resourceLogs.length; ++i) { + var error = $root.opentelemetry.proto.logs.v1.ResourceLogs.verify(message.resourceLogs[i]); + if (error) + return "resourceLogs." + error; + } + } + return null; + }; + /** + * Creates an ExportLogsServiceRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest} ExportLogsServiceRequest + */ + ExportLogsServiceRequest.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest) + return object; + var message = new $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest(); + if (object.resourceLogs) { + if (!Array.isArray(object.resourceLogs)) + throw TypeError(".opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest.resourceLogs: array expected"); + message.resourceLogs = []; + for (var i = 0; i < object.resourceLogs.length; ++i) { + if (typeof object.resourceLogs[i] !== "object") + throw TypeError(".opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest.resourceLogs: object expected"); + message.resourceLogs[i] = $root.opentelemetry.proto.logs.v1.ResourceLogs.fromObject(object.resourceLogs[i]); + } + } + return message; + }; + /** + * Creates a plain object from an ExportLogsServiceRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest + * @static + * @param {opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest} message ExportLogsServiceRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExportLogsServiceRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.resourceLogs = []; + if (message.resourceLogs && message.resourceLogs.length) { + object.resourceLogs = []; + for (var j = 0; j < message.resourceLogs.length; ++j) + object.resourceLogs[j] = $root.opentelemetry.proto.logs.v1.ResourceLogs.toObject(message.resourceLogs[j], options); + } + return object; + }; + /** + * Converts this ExportLogsServiceRequest to JSON. + * @function toJSON + * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest + * @instance + * @returns {Object.} JSON object + */ + ExportLogsServiceRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for ExportLogsServiceRequest + * @function getTypeUrl + * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExportLogsServiceRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest"; + }; + return ExportLogsServiceRequest; + })(); + v1.ExportLogsServiceResponse = (function () { + /** + * Properties of an ExportLogsServiceResponse. + * @memberof opentelemetry.proto.collector.logs.v1 + * @interface IExportLogsServiceResponse + * @property {opentelemetry.proto.collector.logs.v1.IExportLogsPartialSuccess|null} [partialSuccess] ExportLogsServiceResponse partialSuccess + */ + /** + * Constructs a new ExportLogsServiceResponse. + * @memberof opentelemetry.proto.collector.logs.v1 + * @classdesc Represents an ExportLogsServiceResponse. + * @implements IExportLogsServiceResponse + * @constructor + * @param {opentelemetry.proto.collector.logs.v1.IExportLogsServiceResponse=} [properties] Properties to set + */ + function ExportLogsServiceResponse(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * ExportLogsServiceResponse partialSuccess. + * @member {opentelemetry.proto.collector.logs.v1.IExportLogsPartialSuccess|null|undefined} partialSuccess + * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse + * @instance + */ + ExportLogsServiceResponse.prototype.partialSuccess = null; + /** + * Creates a new ExportLogsServiceResponse instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse + * @static + * @param {opentelemetry.proto.collector.logs.v1.IExportLogsServiceResponse=} [properties] Properties to set + * @returns {opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse} ExportLogsServiceResponse instance + */ + ExportLogsServiceResponse.create = function create(properties) { + return new ExportLogsServiceResponse(properties); + }; + /** + * Encodes the specified ExportLogsServiceResponse message. Does not implicitly {@link opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse + * @static + * @param {opentelemetry.proto.collector.logs.v1.IExportLogsServiceResponse} message ExportLogsServiceResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExportLogsServiceResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.partialSuccess != null && Object.hasOwnProperty.call(message, "partialSuccess")) + $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.encode(message.partialSuccess, writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); + return writer; + }; + /** + * Encodes the specified ExportLogsServiceResponse message, length delimited. Does not implicitly {@link opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse + * @static + * @param {opentelemetry.proto.collector.logs.v1.IExportLogsServiceResponse} message ExportLogsServiceResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExportLogsServiceResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes an ExportLogsServiceResponse message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse} ExportLogsServiceResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExportLogsServiceResponse.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.partialSuccess = $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes an ExportLogsServiceResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse} ExportLogsServiceResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExportLogsServiceResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies an ExportLogsServiceResponse message. + * @function verify + * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ExportLogsServiceResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.partialSuccess != null && message.hasOwnProperty("partialSuccess")) { + var error = $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.verify(message.partialSuccess); + if (error) + return "partialSuccess." + error; + } + return null; + }; + /** + * Creates an ExportLogsServiceResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse} ExportLogsServiceResponse + */ + ExportLogsServiceResponse.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse) + return object; + var message = new $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse(); + if (object.partialSuccess != null) { + if (typeof object.partialSuccess !== "object") + throw TypeError(".opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse.partialSuccess: object expected"); + message.partialSuccess = $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.fromObject(object.partialSuccess); + } + return message; + }; + /** + * Creates a plain object from an ExportLogsServiceResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse + * @static + * @param {opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse} message ExportLogsServiceResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExportLogsServiceResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.partialSuccess = null; + if (message.partialSuccess != null && message.hasOwnProperty("partialSuccess")) + object.partialSuccess = $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.toObject(message.partialSuccess, options); + return object; + }; + /** + * Converts this ExportLogsServiceResponse to JSON. + * @function toJSON + * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse + * @instance + * @returns {Object.} JSON object + */ + ExportLogsServiceResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for ExportLogsServiceResponse + * @function getTypeUrl + * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExportLogsServiceResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse"; + }; + return ExportLogsServiceResponse; + })(); + v1.ExportLogsPartialSuccess = (function () { + /** + * Properties of an ExportLogsPartialSuccess. + * @memberof opentelemetry.proto.collector.logs.v1 + * @interface IExportLogsPartialSuccess + * @property {number|Long|null} [rejectedLogRecords] ExportLogsPartialSuccess rejectedLogRecords + * @property {string|null} [errorMessage] ExportLogsPartialSuccess errorMessage + */ + /** + * Constructs a new ExportLogsPartialSuccess. + * @memberof opentelemetry.proto.collector.logs.v1 + * @classdesc Represents an ExportLogsPartialSuccess. + * @implements IExportLogsPartialSuccess + * @constructor + * @param {opentelemetry.proto.collector.logs.v1.IExportLogsPartialSuccess=} [properties] Properties to set + */ + function ExportLogsPartialSuccess(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * ExportLogsPartialSuccess rejectedLogRecords. + * @member {number|Long|null|undefined} rejectedLogRecords + * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess + * @instance + */ + ExportLogsPartialSuccess.prototype.rejectedLogRecords = null; + /** + * ExportLogsPartialSuccess errorMessage. + * @member {string|null|undefined} errorMessage + * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess + * @instance + */ + ExportLogsPartialSuccess.prototype.errorMessage = null; + /** + * Creates a new ExportLogsPartialSuccess instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess + * @static + * @param {opentelemetry.proto.collector.logs.v1.IExportLogsPartialSuccess=} [properties] Properties to set + * @returns {opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess} ExportLogsPartialSuccess instance + */ + ExportLogsPartialSuccess.create = function create(properties) { + return new ExportLogsPartialSuccess(properties); + }; + /** + * Encodes the specified ExportLogsPartialSuccess message. Does not implicitly {@link opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess + * @static + * @param {opentelemetry.proto.collector.logs.v1.IExportLogsPartialSuccess} message ExportLogsPartialSuccess message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExportLogsPartialSuccess.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.rejectedLogRecords != null && Object.hasOwnProperty.call(message, "rejectedLogRecords")) + writer.uint32(/* id 1, wireType 0 =*/ 8).int64(message.rejectedLogRecords); + if (message.errorMessage != null && Object.hasOwnProperty.call(message, "errorMessage")) + writer.uint32(/* id 2, wireType 2 =*/ 18).string(message.errorMessage); + return writer; + }; + /** + * Encodes the specified ExportLogsPartialSuccess message, length delimited. Does not implicitly {@link opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess + * @static + * @param {opentelemetry.proto.collector.logs.v1.IExportLogsPartialSuccess} message ExportLogsPartialSuccess message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExportLogsPartialSuccess.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes an ExportLogsPartialSuccess message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess} ExportLogsPartialSuccess + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExportLogsPartialSuccess.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.rejectedLogRecords = reader.int64(); + break; + } + case 2: { + message.errorMessage = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes an ExportLogsPartialSuccess message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess} ExportLogsPartialSuccess + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExportLogsPartialSuccess.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies an ExportLogsPartialSuccess message. + * @function verify + * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ExportLogsPartialSuccess.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.rejectedLogRecords != null && message.hasOwnProperty("rejectedLogRecords")) + if (!$util.isInteger(message.rejectedLogRecords) && !(message.rejectedLogRecords && $util.isInteger(message.rejectedLogRecords.low) && $util.isInteger(message.rejectedLogRecords.high))) + return "rejectedLogRecords: integer|Long expected"; + if (message.errorMessage != null && message.hasOwnProperty("errorMessage")) + if (!$util.isString(message.errorMessage)) + return "errorMessage: string expected"; + return null; + }; + /** + * Creates an ExportLogsPartialSuccess message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess} ExportLogsPartialSuccess + */ + ExportLogsPartialSuccess.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess) + return object; + var message = new $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess(); + if (object.rejectedLogRecords != null) + if ($util.Long) + (message.rejectedLogRecords = $util.Long.fromValue(object.rejectedLogRecords)).unsigned = false; + else if (typeof object.rejectedLogRecords === "string") + message.rejectedLogRecords = parseInt(object.rejectedLogRecords, 10); + else if (typeof object.rejectedLogRecords === "number") + message.rejectedLogRecords = object.rejectedLogRecords; + else if (typeof object.rejectedLogRecords === "object") + message.rejectedLogRecords = new $util.LongBits(object.rejectedLogRecords.low >>> 0, object.rejectedLogRecords.high >>> 0).toNumber(); + if (object.errorMessage != null) + message.errorMessage = String(object.errorMessage); + return message; + }; + /** + * Creates a plain object from an ExportLogsPartialSuccess message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess + * @static + * @param {opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess} message ExportLogsPartialSuccess + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExportLogsPartialSuccess.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.rejectedLogRecords = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } + else + object.rejectedLogRecords = options.longs === String ? "0" : 0; + object.errorMessage = ""; + } + if (message.rejectedLogRecords != null && message.hasOwnProperty("rejectedLogRecords")) + if (typeof message.rejectedLogRecords === "number") + object.rejectedLogRecords = options.longs === String ? String(message.rejectedLogRecords) : message.rejectedLogRecords; + else + object.rejectedLogRecords = options.longs === String ? $util.Long.prototype.toString.call(message.rejectedLogRecords) : options.longs === Number ? new $util.LongBits(message.rejectedLogRecords.low >>> 0, message.rejectedLogRecords.high >>> 0).toNumber() : message.rejectedLogRecords; + if (message.errorMessage != null && message.hasOwnProperty("errorMessage")) + object.errorMessage = message.errorMessage; + return object; + }; + /** + * Converts this ExportLogsPartialSuccess to JSON. + * @function toJSON + * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess + * @instance + * @returns {Object.} JSON object + */ + ExportLogsPartialSuccess.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for ExportLogsPartialSuccess + * @function getTypeUrl + * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExportLogsPartialSuccess.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess"; + }; + return ExportLogsPartialSuccess; + })(); + return v1; + })(); + return logs; + })(); + return collector; + })(); + proto.metrics = (function () { + /** + * Namespace metrics. + * @memberof opentelemetry.proto + * @namespace + */ + var metrics = {}; + metrics.v1 = (function () { + /** + * Namespace v1. + * @memberof opentelemetry.proto.metrics + * @namespace + */ + var v1 = {}; + v1.MetricsData = (function () { + /** + * Properties of a MetricsData. + * @memberof opentelemetry.proto.metrics.v1 + * @interface IMetricsData + * @property {Array.|null} [resourceMetrics] MetricsData resourceMetrics + */ + /** + * Constructs a new MetricsData. + * @memberof opentelemetry.proto.metrics.v1 + * @classdesc Represents a MetricsData. + * @implements IMetricsData + * @constructor + * @param {opentelemetry.proto.metrics.v1.IMetricsData=} [properties] Properties to set + */ + function MetricsData(properties) { + this.resourceMetrics = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * MetricsData resourceMetrics. + * @member {Array.} resourceMetrics + * @memberof opentelemetry.proto.metrics.v1.MetricsData + * @instance + */ + MetricsData.prototype.resourceMetrics = $util.emptyArray; + /** + * Creates a new MetricsData instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.metrics.v1.MetricsData + * @static + * @param {opentelemetry.proto.metrics.v1.IMetricsData=} [properties] Properties to set + * @returns {opentelemetry.proto.metrics.v1.MetricsData} MetricsData instance + */ + MetricsData.create = function create(properties) { + return new MetricsData(properties); + }; + /** + * Encodes the specified MetricsData message. Does not implicitly {@link opentelemetry.proto.metrics.v1.MetricsData.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.metrics.v1.MetricsData + * @static + * @param {opentelemetry.proto.metrics.v1.IMetricsData} message MetricsData message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + MetricsData.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.resourceMetrics != null && message.resourceMetrics.length) + for (var i = 0; i < message.resourceMetrics.length; ++i) + $root.opentelemetry.proto.metrics.v1.ResourceMetrics.encode(message.resourceMetrics[i], writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); + return writer; + }; + /** + * Encodes the specified MetricsData message, length delimited. Does not implicitly {@link opentelemetry.proto.metrics.v1.MetricsData.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.metrics.v1.MetricsData + * @static + * @param {opentelemetry.proto.metrics.v1.IMetricsData} message MetricsData message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + MetricsData.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes a MetricsData message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.metrics.v1.MetricsData + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.metrics.v1.MetricsData} MetricsData + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + MetricsData.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.MetricsData(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.resourceMetrics && message.resourceMetrics.length)) + message.resourceMetrics = []; + message.resourceMetrics.push($root.opentelemetry.proto.metrics.v1.ResourceMetrics.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes a MetricsData message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.metrics.v1.MetricsData + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.metrics.v1.MetricsData} MetricsData + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + MetricsData.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies a MetricsData message. + * @function verify + * @memberof opentelemetry.proto.metrics.v1.MetricsData + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + MetricsData.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.resourceMetrics != null && message.hasOwnProperty("resourceMetrics")) { + if (!Array.isArray(message.resourceMetrics)) + return "resourceMetrics: array expected"; + for (var i = 0; i < message.resourceMetrics.length; ++i) { + var error = $root.opentelemetry.proto.metrics.v1.ResourceMetrics.verify(message.resourceMetrics[i]); + if (error) + return "resourceMetrics." + error; + } + } + return null; + }; + /** + * Creates a MetricsData message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.metrics.v1.MetricsData + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.metrics.v1.MetricsData} MetricsData + */ + MetricsData.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.metrics.v1.MetricsData) + return object; + var message = new $root.opentelemetry.proto.metrics.v1.MetricsData(); + if (object.resourceMetrics) { + if (!Array.isArray(object.resourceMetrics)) + throw TypeError(".opentelemetry.proto.metrics.v1.MetricsData.resourceMetrics: array expected"); + message.resourceMetrics = []; + for (var i = 0; i < object.resourceMetrics.length; ++i) { + if (typeof object.resourceMetrics[i] !== "object") + throw TypeError(".opentelemetry.proto.metrics.v1.MetricsData.resourceMetrics: object expected"); + message.resourceMetrics[i] = $root.opentelemetry.proto.metrics.v1.ResourceMetrics.fromObject(object.resourceMetrics[i]); + } + } + return message; + }; + /** + * Creates a plain object from a MetricsData message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.metrics.v1.MetricsData + * @static + * @param {opentelemetry.proto.metrics.v1.MetricsData} message MetricsData + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MetricsData.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.resourceMetrics = []; + if (message.resourceMetrics && message.resourceMetrics.length) { + object.resourceMetrics = []; + for (var j = 0; j < message.resourceMetrics.length; ++j) + object.resourceMetrics[j] = $root.opentelemetry.proto.metrics.v1.ResourceMetrics.toObject(message.resourceMetrics[j], options); + } + return object; + }; + /** + * Converts this MetricsData to JSON. + * @function toJSON + * @memberof opentelemetry.proto.metrics.v1.MetricsData + * @instance + * @returns {Object.} JSON object + */ + MetricsData.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for MetricsData + * @function getTypeUrl + * @memberof opentelemetry.proto.metrics.v1.MetricsData + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MetricsData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.MetricsData"; + }; + return MetricsData; + })(); + v1.ResourceMetrics = (function () { + /** + * Properties of a ResourceMetrics. + * @memberof opentelemetry.proto.metrics.v1 + * @interface IResourceMetrics + * @property {opentelemetry.proto.resource.v1.IResource|null} [resource] ResourceMetrics resource + * @property {Array.|null} [scopeMetrics] ResourceMetrics scopeMetrics + * @property {string|null} [schemaUrl] ResourceMetrics schemaUrl + */ + /** + * Constructs a new ResourceMetrics. + * @memberof opentelemetry.proto.metrics.v1 + * @classdesc Represents a ResourceMetrics. + * @implements IResourceMetrics + * @constructor + * @param {opentelemetry.proto.metrics.v1.IResourceMetrics=} [properties] Properties to set + */ + function ResourceMetrics(properties) { + this.scopeMetrics = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * ResourceMetrics resource. + * @member {opentelemetry.proto.resource.v1.IResource|null|undefined} resource + * @memberof opentelemetry.proto.metrics.v1.ResourceMetrics + * @instance + */ + ResourceMetrics.prototype.resource = null; + /** + * ResourceMetrics scopeMetrics. + * @member {Array.} scopeMetrics + * @memberof opentelemetry.proto.metrics.v1.ResourceMetrics + * @instance + */ + ResourceMetrics.prototype.scopeMetrics = $util.emptyArray; + /** + * ResourceMetrics schemaUrl. + * @member {string|null|undefined} schemaUrl + * @memberof opentelemetry.proto.metrics.v1.ResourceMetrics + * @instance + */ + ResourceMetrics.prototype.schemaUrl = null; + /** + * Creates a new ResourceMetrics instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.metrics.v1.ResourceMetrics + * @static + * @param {opentelemetry.proto.metrics.v1.IResourceMetrics=} [properties] Properties to set + * @returns {opentelemetry.proto.metrics.v1.ResourceMetrics} ResourceMetrics instance + */ + ResourceMetrics.create = function create(properties) { + return new ResourceMetrics(properties); + }; + /** + * Encodes the specified ResourceMetrics message. Does not implicitly {@link opentelemetry.proto.metrics.v1.ResourceMetrics.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.metrics.v1.ResourceMetrics + * @static + * @param {opentelemetry.proto.metrics.v1.IResourceMetrics} message ResourceMetrics message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ResourceMetrics.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.resource != null && Object.hasOwnProperty.call(message, "resource")) + $root.opentelemetry.proto.resource.v1.Resource.encode(message.resource, writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); + if (message.scopeMetrics != null && message.scopeMetrics.length) + for (var i = 0; i < message.scopeMetrics.length; ++i) + $root.opentelemetry.proto.metrics.v1.ScopeMetrics.encode(message.scopeMetrics[i], writer.uint32(/* id 2, wireType 2 =*/ 18).fork()).ldelim(); + if (message.schemaUrl != null && Object.hasOwnProperty.call(message, "schemaUrl")) + writer.uint32(/* id 3, wireType 2 =*/ 26).string(message.schemaUrl); + return writer; + }; + /** + * Encodes the specified ResourceMetrics message, length delimited. Does not implicitly {@link opentelemetry.proto.metrics.v1.ResourceMetrics.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.metrics.v1.ResourceMetrics + * @static + * @param {opentelemetry.proto.metrics.v1.IResourceMetrics} message ResourceMetrics message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ResourceMetrics.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes a ResourceMetrics message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.metrics.v1.ResourceMetrics + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.metrics.v1.ResourceMetrics} ResourceMetrics + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ResourceMetrics.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.ResourceMetrics(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.resource = $root.opentelemetry.proto.resource.v1.Resource.decode(reader, reader.uint32()); + break; + } + case 2: { + if (!(message.scopeMetrics && message.scopeMetrics.length)) + message.scopeMetrics = []; + message.scopeMetrics.push($root.opentelemetry.proto.metrics.v1.ScopeMetrics.decode(reader, reader.uint32())); + break; + } + case 3: { + message.schemaUrl = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes a ResourceMetrics message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.metrics.v1.ResourceMetrics + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.metrics.v1.ResourceMetrics} ResourceMetrics + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ResourceMetrics.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies a ResourceMetrics message. + * @function verify + * @memberof opentelemetry.proto.metrics.v1.ResourceMetrics + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ResourceMetrics.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.resource != null && message.hasOwnProperty("resource")) { + var error = $root.opentelemetry.proto.resource.v1.Resource.verify(message.resource); + if (error) + return "resource." + error; + } + if (message.scopeMetrics != null && message.hasOwnProperty("scopeMetrics")) { + if (!Array.isArray(message.scopeMetrics)) + return "scopeMetrics: array expected"; + for (var i = 0; i < message.scopeMetrics.length; ++i) { + var error = $root.opentelemetry.proto.metrics.v1.ScopeMetrics.verify(message.scopeMetrics[i]); + if (error) + return "scopeMetrics." + error; + } + } + if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) + if (!$util.isString(message.schemaUrl)) + return "schemaUrl: string expected"; + return null; + }; + /** + * Creates a ResourceMetrics message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.metrics.v1.ResourceMetrics + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.metrics.v1.ResourceMetrics} ResourceMetrics + */ + ResourceMetrics.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.metrics.v1.ResourceMetrics) + return object; + var message = new $root.opentelemetry.proto.metrics.v1.ResourceMetrics(); + if (object.resource != null) { + if (typeof object.resource !== "object") + throw TypeError(".opentelemetry.proto.metrics.v1.ResourceMetrics.resource: object expected"); + message.resource = $root.opentelemetry.proto.resource.v1.Resource.fromObject(object.resource); + } + if (object.scopeMetrics) { + if (!Array.isArray(object.scopeMetrics)) + throw TypeError(".opentelemetry.proto.metrics.v1.ResourceMetrics.scopeMetrics: array expected"); + message.scopeMetrics = []; + for (var i = 0; i < object.scopeMetrics.length; ++i) { + if (typeof object.scopeMetrics[i] !== "object") + throw TypeError(".opentelemetry.proto.metrics.v1.ResourceMetrics.scopeMetrics: object expected"); + message.scopeMetrics[i] = $root.opentelemetry.proto.metrics.v1.ScopeMetrics.fromObject(object.scopeMetrics[i]); + } + } + if (object.schemaUrl != null) + message.schemaUrl = String(object.schemaUrl); + return message; + }; + /** + * Creates a plain object from a ResourceMetrics message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.metrics.v1.ResourceMetrics + * @static + * @param {opentelemetry.proto.metrics.v1.ResourceMetrics} message ResourceMetrics + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ResourceMetrics.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.scopeMetrics = []; + if (options.defaults) { + object.resource = null; + object.schemaUrl = ""; + } + if (message.resource != null && message.hasOwnProperty("resource")) + object.resource = $root.opentelemetry.proto.resource.v1.Resource.toObject(message.resource, options); + if (message.scopeMetrics && message.scopeMetrics.length) { + object.scopeMetrics = []; + for (var j = 0; j < message.scopeMetrics.length; ++j) + object.scopeMetrics[j] = $root.opentelemetry.proto.metrics.v1.ScopeMetrics.toObject(message.scopeMetrics[j], options); + } + if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) + object.schemaUrl = message.schemaUrl; + return object; + }; + /** + * Converts this ResourceMetrics to JSON. + * @function toJSON + * @memberof opentelemetry.proto.metrics.v1.ResourceMetrics + * @instance + * @returns {Object.} JSON object + */ + ResourceMetrics.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for ResourceMetrics + * @function getTypeUrl + * @memberof opentelemetry.proto.metrics.v1.ResourceMetrics + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ResourceMetrics.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.ResourceMetrics"; + }; + return ResourceMetrics; + })(); + v1.ScopeMetrics = (function () { + /** + * Properties of a ScopeMetrics. + * @memberof opentelemetry.proto.metrics.v1 + * @interface IScopeMetrics + * @property {opentelemetry.proto.common.v1.IInstrumentationScope|null} [scope] ScopeMetrics scope + * @property {Array.|null} [metrics] ScopeMetrics metrics + * @property {string|null} [schemaUrl] ScopeMetrics schemaUrl + */ + /** + * Constructs a new ScopeMetrics. + * @memberof opentelemetry.proto.metrics.v1 + * @classdesc Represents a ScopeMetrics. + * @implements IScopeMetrics + * @constructor + * @param {opentelemetry.proto.metrics.v1.IScopeMetrics=} [properties] Properties to set + */ + function ScopeMetrics(properties) { + this.metrics = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * ScopeMetrics scope. + * @member {opentelemetry.proto.common.v1.IInstrumentationScope|null|undefined} scope + * @memberof opentelemetry.proto.metrics.v1.ScopeMetrics + * @instance + */ + ScopeMetrics.prototype.scope = null; + /** + * ScopeMetrics metrics. + * @member {Array.} metrics + * @memberof opentelemetry.proto.metrics.v1.ScopeMetrics + * @instance + */ + ScopeMetrics.prototype.metrics = $util.emptyArray; + /** + * ScopeMetrics schemaUrl. + * @member {string|null|undefined} schemaUrl + * @memberof opentelemetry.proto.metrics.v1.ScopeMetrics + * @instance + */ + ScopeMetrics.prototype.schemaUrl = null; + /** + * Creates a new ScopeMetrics instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.metrics.v1.ScopeMetrics + * @static + * @param {opentelemetry.proto.metrics.v1.IScopeMetrics=} [properties] Properties to set + * @returns {opentelemetry.proto.metrics.v1.ScopeMetrics} ScopeMetrics instance + */ + ScopeMetrics.create = function create(properties) { + return new ScopeMetrics(properties); + }; + /** + * Encodes the specified ScopeMetrics message. Does not implicitly {@link opentelemetry.proto.metrics.v1.ScopeMetrics.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.metrics.v1.ScopeMetrics + * @static + * @param {opentelemetry.proto.metrics.v1.IScopeMetrics} message ScopeMetrics message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ScopeMetrics.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.scope != null && Object.hasOwnProperty.call(message, "scope")) + $root.opentelemetry.proto.common.v1.InstrumentationScope.encode(message.scope, writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); + if (message.metrics != null && message.metrics.length) + for (var i = 0; i < message.metrics.length; ++i) + $root.opentelemetry.proto.metrics.v1.Metric.encode(message.metrics[i], writer.uint32(/* id 2, wireType 2 =*/ 18).fork()).ldelim(); + if (message.schemaUrl != null && Object.hasOwnProperty.call(message, "schemaUrl")) + writer.uint32(/* id 3, wireType 2 =*/ 26).string(message.schemaUrl); + return writer; + }; + /** + * Encodes the specified ScopeMetrics message, length delimited. Does not implicitly {@link opentelemetry.proto.metrics.v1.ScopeMetrics.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.metrics.v1.ScopeMetrics + * @static + * @param {opentelemetry.proto.metrics.v1.IScopeMetrics} message ScopeMetrics message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ScopeMetrics.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes a ScopeMetrics message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.metrics.v1.ScopeMetrics + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.metrics.v1.ScopeMetrics} ScopeMetrics + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ScopeMetrics.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.ScopeMetrics(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.decode(reader, reader.uint32()); + break; + } + case 2: { + if (!(message.metrics && message.metrics.length)) + message.metrics = []; + message.metrics.push($root.opentelemetry.proto.metrics.v1.Metric.decode(reader, reader.uint32())); + break; + } + case 3: { + message.schemaUrl = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes a ScopeMetrics message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.metrics.v1.ScopeMetrics + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.metrics.v1.ScopeMetrics} ScopeMetrics + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ScopeMetrics.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies a ScopeMetrics message. + * @function verify + * @memberof opentelemetry.proto.metrics.v1.ScopeMetrics + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ScopeMetrics.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.scope != null && message.hasOwnProperty("scope")) { + var error = $root.opentelemetry.proto.common.v1.InstrumentationScope.verify(message.scope); + if (error) + return "scope." + error; + } + if (message.metrics != null && message.hasOwnProperty("metrics")) { + if (!Array.isArray(message.metrics)) + return "metrics: array expected"; + for (var i = 0; i < message.metrics.length; ++i) { + var error = $root.opentelemetry.proto.metrics.v1.Metric.verify(message.metrics[i]); + if (error) + return "metrics." + error; + } + } + if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) + if (!$util.isString(message.schemaUrl)) + return "schemaUrl: string expected"; + return null; + }; + /** + * Creates a ScopeMetrics message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.metrics.v1.ScopeMetrics + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.metrics.v1.ScopeMetrics} ScopeMetrics + */ + ScopeMetrics.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.metrics.v1.ScopeMetrics) + return object; + var message = new $root.opentelemetry.proto.metrics.v1.ScopeMetrics(); + if (object.scope != null) { + if (typeof object.scope !== "object") + throw TypeError(".opentelemetry.proto.metrics.v1.ScopeMetrics.scope: object expected"); + message.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.fromObject(object.scope); + } + if (object.metrics) { + if (!Array.isArray(object.metrics)) + throw TypeError(".opentelemetry.proto.metrics.v1.ScopeMetrics.metrics: array expected"); + message.metrics = []; + for (var i = 0; i < object.metrics.length; ++i) { + if (typeof object.metrics[i] !== "object") + throw TypeError(".opentelemetry.proto.metrics.v1.ScopeMetrics.metrics: object expected"); + message.metrics[i] = $root.opentelemetry.proto.metrics.v1.Metric.fromObject(object.metrics[i]); + } + } + if (object.schemaUrl != null) + message.schemaUrl = String(object.schemaUrl); + return message; + }; + /** + * Creates a plain object from a ScopeMetrics message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.metrics.v1.ScopeMetrics + * @static + * @param {opentelemetry.proto.metrics.v1.ScopeMetrics} message ScopeMetrics + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ScopeMetrics.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.metrics = []; + if (options.defaults) { + object.scope = null; + object.schemaUrl = ""; + } + if (message.scope != null && message.hasOwnProperty("scope")) + object.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.toObject(message.scope, options); + if (message.metrics && message.metrics.length) { + object.metrics = []; + for (var j = 0; j < message.metrics.length; ++j) + object.metrics[j] = $root.opentelemetry.proto.metrics.v1.Metric.toObject(message.metrics[j], options); + } + if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) + object.schemaUrl = message.schemaUrl; + return object; + }; + /** + * Converts this ScopeMetrics to JSON. + * @function toJSON + * @memberof opentelemetry.proto.metrics.v1.ScopeMetrics + * @instance + * @returns {Object.} JSON object + */ + ScopeMetrics.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for ScopeMetrics + * @function getTypeUrl + * @memberof opentelemetry.proto.metrics.v1.ScopeMetrics + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ScopeMetrics.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.ScopeMetrics"; + }; + return ScopeMetrics; + })(); + v1.Metric = (function () { + /** + * Properties of a Metric. + * @memberof opentelemetry.proto.metrics.v1 + * @interface IMetric + * @property {string|null} [name] Metric name + * @property {string|null} [description] Metric description + * @property {string|null} [unit] Metric unit + * @property {opentelemetry.proto.metrics.v1.IGauge|null} [gauge] Metric gauge + * @property {opentelemetry.proto.metrics.v1.ISum|null} [sum] Metric sum + * @property {opentelemetry.proto.metrics.v1.IHistogram|null} [histogram] Metric histogram + * @property {opentelemetry.proto.metrics.v1.IExponentialHistogram|null} [exponentialHistogram] Metric exponentialHistogram + * @property {opentelemetry.proto.metrics.v1.ISummary|null} [summary] Metric summary + * @property {Array.|null} [metadata] Metric metadata + */ + /** + * Constructs a new Metric. + * @memberof opentelemetry.proto.metrics.v1 + * @classdesc Represents a Metric. + * @implements IMetric + * @constructor + * @param {opentelemetry.proto.metrics.v1.IMetric=} [properties] Properties to set + */ + function Metric(properties) { + this.metadata = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * Metric name. + * @member {string|null|undefined} name + * @memberof opentelemetry.proto.metrics.v1.Metric + * @instance + */ + Metric.prototype.name = null; + /** + * Metric description. + * @member {string|null|undefined} description + * @memberof opentelemetry.proto.metrics.v1.Metric + * @instance + */ + Metric.prototype.description = null; + /** + * Metric unit. + * @member {string|null|undefined} unit + * @memberof opentelemetry.proto.metrics.v1.Metric + * @instance + */ + Metric.prototype.unit = null; + /** + * Metric gauge. + * @member {opentelemetry.proto.metrics.v1.IGauge|null|undefined} gauge + * @memberof opentelemetry.proto.metrics.v1.Metric + * @instance + */ + Metric.prototype.gauge = null; + /** + * Metric sum. + * @member {opentelemetry.proto.metrics.v1.ISum|null|undefined} sum + * @memberof opentelemetry.proto.metrics.v1.Metric + * @instance + */ + Metric.prototype.sum = null; + /** + * Metric histogram. + * @member {opentelemetry.proto.metrics.v1.IHistogram|null|undefined} histogram + * @memberof opentelemetry.proto.metrics.v1.Metric + * @instance + */ + Metric.prototype.histogram = null; + /** + * Metric exponentialHistogram. + * @member {opentelemetry.proto.metrics.v1.IExponentialHistogram|null|undefined} exponentialHistogram + * @memberof opentelemetry.proto.metrics.v1.Metric + * @instance + */ + Metric.prototype.exponentialHistogram = null; + /** + * Metric summary. + * @member {opentelemetry.proto.metrics.v1.ISummary|null|undefined} summary + * @memberof opentelemetry.proto.metrics.v1.Metric + * @instance + */ + Metric.prototype.summary = null; + /** + * Metric metadata. + * @member {Array.} metadata + * @memberof opentelemetry.proto.metrics.v1.Metric + * @instance + */ + Metric.prototype.metadata = $util.emptyArray; + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + /** + * Metric data. + * @member {"gauge"|"sum"|"histogram"|"exponentialHistogram"|"summary"|undefined} data + * @memberof opentelemetry.proto.metrics.v1.Metric + * @instance + */ + Object.defineProperty(Metric.prototype, "data", { + get: $util.oneOfGetter($oneOfFields = ["gauge", "sum", "histogram", "exponentialHistogram", "summary"]), + set: $util.oneOfSetter($oneOfFields) + }); + /** + * Creates a new Metric instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.metrics.v1.Metric + * @static + * @param {opentelemetry.proto.metrics.v1.IMetric=} [properties] Properties to set + * @returns {opentelemetry.proto.metrics.v1.Metric} Metric instance + */ + Metric.create = function create(properties) { + return new Metric(properties); + }; + /** + * Encodes the specified Metric message. Does not implicitly {@link opentelemetry.proto.metrics.v1.Metric.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.metrics.v1.Metric + * @static + * @param {opentelemetry.proto.metrics.v1.IMetric} message Metric message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Metric.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/ 10).string(message.name); + if (message.description != null && Object.hasOwnProperty.call(message, "description")) + writer.uint32(/* id 2, wireType 2 =*/ 18).string(message.description); + if (message.unit != null && Object.hasOwnProperty.call(message, "unit")) + writer.uint32(/* id 3, wireType 2 =*/ 26).string(message.unit); + if (message.gauge != null && Object.hasOwnProperty.call(message, "gauge")) + $root.opentelemetry.proto.metrics.v1.Gauge.encode(message.gauge, writer.uint32(/* id 5, wireType 2 =*/ 42).fork()).ldelim(); + if (message.sum != null && Object.hasOwnProperty.call(message, "sum")) + $root.opentelemetry.proto.metrics.v1.Sum.encode(message.sum, writer.uint32(/* id 7, wireType 2 =*/ 58).fork()).ldelim(); + if (message.histogram != null && Object.hasOwnProperty.call(message, "histogram")) + $root.opentelemetry.proto.metrics.v1.Histogram.encode(message.histogram, writer.uint32(/* id 9, wireType 2 =*/ 74).fork()).ldelim(); + if (message.exponentialHistogram != null && Object.hasOwnProperty.call(message, "exponentialHistogram")) + $root.opentelemetry.proto.metrics.v1.ExponentialHistogram.encode(message.exponentialHistogram, writer.uint32(/* id 10, wireType 2 =*/ 82).fork()).ldelim(); + if (message.summary != null && Object.hasOwnProperty.call(message, "summary")) + $root.opentelemetry.proto.metrics.v1.Summary.encode(message.summary, writer.uint32(/* id 11, wireType 2 =*/ 90).fork()).ldelim(); + if (message.metadata != null && message.metadata.length) + for (var i = 0; i < message.metadata.length; ++i) + $root.opentelemetry.proto.common.v1.KeyValue.encode(message.metadata[i], writer.uint32(/* id 12, wireType 2 =*/ 98).fork()).ldelim(); + return writer; + }; + /** + * Encodes the specified Metric message, length delimited. Does not implicitly {@link opentelemetry.proto.metrics.v1.Metric.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.metrics.v1.Metric + * @static + * @param {opentelemetry.proto.metrics.v1.IMetric} message Metric message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Metric.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes a Metric message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.metrics.v1.Metric + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.metrics.v1.Metric} Metric + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Metric.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.Metric(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + case 2: { + message.description = reader.string(); + break; + } + case 3: { + message.unit = reader.string(); + break; + } + case 5: { + message.gauge = $root.opentelemetry.proto.metrics.v1.Gauge.decode(reader, reader.uint32()); + break; + } + case 7: { + message.sum = $root.opentelemetry.proto.metrics.v1.Sum.decode(reader, reader.uint32()); + break; + } + case 9: { + message.histogram = $root.opentelemetry.proto.metrics.v1.Histogram.decode(reader, reader.uint32()); + break; + } + case 10: { + message.exponentialHistogram = $root.opentelemetry.proto.metrics.v1.ExponentialHistogram.decode(reader, reader.uint32()); + break; + } + case 11: { + message.summary = $root.opentelemetry.proto.metrics.v1.Summary.decode(reader, reader.uint32()); + break; + } + case 12: { + if (!(message.metadata && message.metadata.length)) + message.metadata = []; + message.metadata.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes a Metric message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.metrics.v1.Metric + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.metrics.v1.Metric} Metric + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Metric.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies a Metric message. + * @function verify + * @memberof opentelemetry.proto.metrics.v1.Metric + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Metric.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.description != null && message.hasOwnProperty("description")) + if (!$util.isString(message.description)) + return "description: string expected"; + if (message.unit != null && message.hasOwnProperty("unit")) + if (!$util.isString(message.unit)) + return "unit: string expected"; + if (message.gauge != null && message.hasOwnProperty("gauge")) { + properties.data = 1; + { + var error = $root.opentelemetry.proto.metrics.v1.Gauge.verify(message.gauge); + if (error) + return "gauge." + error; + } + } + if (message.sum != null && message.hasOwnProperty("sum")) { + if (properties.data === 1) + return "data: multiple values"; + properties.data = 1; + { + var error = $root.opentelemetry.proto.metrics.v1.Sum.verify(message.sum); + if (error) + return "sum." + error; + } + } + if (message.histogram != null && message.hasOwnProperty("histogram")) { + if (properties.data === 1) + return "data: multiple values"; + properties.data = 1; + { + var error = $root.opentelemetry.proto.metrics.v1.Histogram.verify(message.histogram); + if (error) + return "histogram." + error; + } + } + if (message.exponentialHistogram != null && message.hasOwnProperty("exponentialHistogram")) { + if (properties.data === 1) + return "data: multiple values"; + properties.data = 1; + { + var error = $root.opentelemetry.proto.metrics.v1.ExponentialHistogram.verify(message.exponentialHistogram); + if (error) + return "exponentialHistogram." + error; + } + } + if (message.summary != null && message.hasOwnProperty("summary")) { + if (properties.data === 1) + return "data: multiple values"; + properties.data = 1; + { + var error = $root.opentelemetry.proto.metrics.v1.Summary.verify(message.summary); + if (error) + return "summary." + error; + } + } + if (message.metadata != null && message.hasOwnProperty("metadata")) { + if (!Array.isArray(message.metadata)) + return "metadata: array expected"; + for (var i = 0; i < message.metadata.length; ++i) { + var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.metadata[i]); + if (error) + return "metadata." + error; + } + } + return null; + }; + /** + * Creates a Metric message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.metrics.v1.Metric + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.metrics.v1.Metric} Metric + */ + Metric.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.metrics.v1.Metric) + return object; + var message = new $root.opentelemetry.proto.metrics.v1.Metric(); + if (object.name != null) + message.name = String(object.name); + if (object.description != null) + message.description = String(object.description); + if (object.unit != null) + message.unit = String(object.unit); + if (object.gauge != null) { + if (typeof object.gauge !== "object") + throw TypeError(".opentelemetry.proto.metrics.v1.Metric.gauge: object expected"); + message.gauge = $root.opentelemetry.proto.metrics.v1.Gauge.fromObject(object.gauge); + } + if (object.sum != null) { + if (typeof object.sum !== "object") + throw TypeError(".opentelemetry.proto.metrics.v1.Metric.sum: object expected"); + message.sum = $root.opentelemetry.proto.metrics.v1.Sum.fromObject(object.sum); + } + if (object.histogram != null) { + if (typeof object.histogram !== "object") + throw TypeError(".opentelemetry.proto.metrics.v1.Metric.histogram: object expected"); + message.histogram = $root.opentelemetry.proto.metrics.v1.Histogram.fromObject(object.histogram); + } + if (object.exponentialHistogram != null) { + if (typeof object.exponentialHistogram !== "object") + throw TypeError(".opentelemetry.proto.metrics.v1.Metric.exponentialHistogram: object expected"); + message.exponentialHistogram = $root.opentelemetry.proto.metrics.v1.ExponentialHistogram.fromObject(object.exponentialHistogram); + } + if (object.summary != null) { + if (typeof object.summary !== "object") + throw TypeError(".opentelemetry.proto.metrics.v1.Metric.summary: object expected"); + message.summary = $root.opentelemetry.proto.metrics.v1.Summary.fromObject(object.summary); + } + if (object.metadata) { + if (!Array.isArray(object.metadata)) + throw TypeError(".opentelemetry.proto.metrics.v1.Metric.metadata: array expected"); + message.metadata = []; + for (var i = 0; i < object.metadata.length; ++i) { + if (typeof object.metadata[i] !== "object") + throw TypeError(".opentelemetry.proto.metrics.v1.Metric.metadata: object expected"); + message.metadata[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.metadata[i]); + } + } + return message; + }; + /** + * Creates a plain object from a Metric message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.metrics.v1.Metric + * @static + * @param {opentelemetry.proto.metrics.v1.Metric} message Metric + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Metric.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.metadata = []; + if (options.defaults) { + object.name = ""; + object.description = ""; + object.unit = ""; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.description != null && message.hasOwnProperty("description")) + object.description = message.description; + if (message.unit != null && message.hasOwnProperty("unit")) + object.unit = message.unit; + if (message.gauge != null && message.hasOwnProperty("gauge")) { + object.gauge = $root.opentelemetry.proto.metrics.v1.Gauge.toObject(message.gauge, options); + if (options.oneofs) + object.data = "gauge"; + } + if (message.sum != null && message.hasOwnProperty("sum")) { + object.sum = $root.opentelemetry.proto.metrics.v1.Sum.toObject(message.sum, options); + if (options.oneofs) + object.data = "sum"; + } + if (message.histogram != null && message.hasOwnProperty("histogram")) { + object.histogram = $root.opentelemetry.proto.metrics.v1.Histogram.toObject(message.histogram, options); + if (options.oneofs) + object.data = "histogram"; + } + if (message.exponentialHistogram != null && message.hasOwnProperty("exponentialHistogram")) { + object.exponentialHistogram = $root.opentelemetry.proto.metrics.v1.ExponentialHistogram.toObject(message.exponentialHistogram, options); + if (options.oneofs) + object.data = "exponentialHistogram"; + } + if (message.summary != null && message.hasOwnProperty("summary")) { + object.summary = $root.opentelemetry.proto.metrics.v1.Summary.toObject(message.summary, options); + if (options.oneofs) + object.data = "summary"; + } + if (message.metadata && message.metadata.length) { + object.metadata = []; + for (var j = 0; j < message.metadata.length; ++j) + object.metadata[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.metadata[j], options); + } + return object; + }; + /** + * Converts this Metric to JSON. + * @function toJSON + * @memberof opentelemetry.proto.metrics.v1.Metric + * @instance + * @returns {Object.} JSON object + */ + Metric.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for Metric + * @function getTypeUrl + * @memberof opentelemetry.proto.metrics.v1.Metric + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Metric.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.Metric"; + }; + return Metric; + })(); + v1.Gauge = (function () { + /** + * Properties of a Gauge. + * @memberof opentelemetry.proto.metrics.v1 + * @interface IGauge + * @property {Array.|null} [dataPoints] Gauge dataPoints + */ + /** + * Constructs a new Gauge. + * @memberof opentelemetry.proto.metrics.v1 + * @classdesc Represents a Gauge. + * @implements IGauge + * @constructor + * @param {opentelemetry.proto.metrics.v1.IGauge=} [properties] Properties to set + */ + function Gauge(properties) { + this.dataPoints = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * Gauge dataPoints. + * @member {Array.} dataPoints + * @memberof opentelemetry.proto.metrics.v1.Gauge + * @instance + */ + Gauge.prototype.dataPoints = $util.emptyArray; + /** + * Creates a new Gauge instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.metrics.v1.Gauge + * @static + * @param {opentelemetry.proto.metrics.v1.IGauge=} [properties] Properties to set + * @returns {opentelemetry.proto.metrics.v1.Gauge} Gauge instance + */ + Gauge.create = function create(properties) { + return new Gauge(properties); + }; + /** + * Encodes the specified Gauge message. Does not implicitly {@link opentelemetry.proto.metrics.v1.Gauge.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.metrics.v1.Gauge + * @static + * @param {opentelemetry.proto.metrics.v1.IGauge} message Gauge message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Gauge.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.dataPoints != null && message.dataPoints.length) + for (var i = 0; i < message.dataPoints.length; ++i) + $root.opentelemetry.proto.metrics.v1.NumberDataPoint.encode(message.dataPoints[i], writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); + return writer; + }; + /** + * Encodes the specified Gauge message, length delimited. Does not implicitly {@link opentelemetry.proto.metrics.v1.Gauge.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.metrics.v1.Gauge + * @static + * @param {opentelemetry.proto.metrics.v1.IGauge} message Gauge message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Gauge.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes a Gauge message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.metrics.v1.Gauge + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.metrics.v1.Gauge} Gauge + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Gauge.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.Gauge(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.dataPoints && message.dataPoints.length)) + message.dataPoints = []; + message.dataPoints.push($root.opentelemetry.proto.metrics.v1.NumberDataPoint.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes a Gauge message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.metrics.v1.Gauge + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.metrics.v1.Gauge} Gauge + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Gauge.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies a Gauge message. + * @function verify + * @memberof opentelemetry.proto.metrics.v1.Gauge + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Gauge.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.dataPoints != null && message.hasOwnProperty("dataPoints")) { + if (!Array.isArray(message.dataPoints)) + return "dataPoints: array expected"; + for (var i = 0; i < message.dataPoints.length; ++i) { + var error = $root.opentelemetry.proto.metrics.v1.NumberDataPoint.verify(message.dataPoints[i]); + if (error) + return "dataPoints." + error; + } + } + return null; + }; + /** + * Creates a Gauge message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.metrics.v1.Gauge + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.metrics.v1.Gauge} Gauge + */ + Gauge.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.metrics.v1.Gauge) + return object; + var message = new $root.opentelemetry.proto.metrics.v1.Gauge(); + if (object.dataPoints) { + if (!Array.isArray(object.dataPoints)) + throw TypeError(".opentelemetry.proto.metrics.v1.Gauge.dataPoints: array expected"); + message.dataPoints = []; + for (var i = 0; i < object.dataPoints.length; ++i) { + if (typeof object.dataPoints[i] !== "object") + throw TypeError(".opentelemetry.proto.metrics.v1.Gauge.dataPoints: object expected"); + message.dataPoints[i] = $root.opentelemetry.proto.metrics.v1.NumberDataPoint.fromObject(object.dataPoints[i]); + } + } + return message; + }; + /** + * Creates a plain object from a Gauge message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.metrics.v1.Gauge + * @static + * @param {opentelemetry.proto.metrics.v1.Gauge} message Gauge + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Gauge.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.dataPoints = []; + if (message.dataPoints && message.dataPoints.length) { + object.dataPoints = []; + for (var j = 0; j < message.dataPoints.length; ++j) + object.dataPoints[j] = $root.opentelemetry.proto.metrics.v1.NumberDataPoint.toObject(message.dataPoints[j], options); + } + return object; + }; + /** + * Converts this Gauge to JSON. + * @function toJSON + * @memberof opentelemetry.proto.metrics.v1.Gauge + * @instance + * @returns {Object.} JSON object + */ + Gauge.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for Gauge + * @function getTypeUrl + * @memberof opentelemetry.proto.metrics.v1.Gauge + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Gauge.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.Gauge"; + }; + return Gauge; + })(); + v1.Sum = (function () { + /** + * Properties of a Sum. + * @memberof opentelemetry.proto.metrics.v1 + * @interface ISum + * @property {Array.|null} [dataPoints] Sum dataPoints + * @property {opentelemetry.proto.metrics.v1.AggregationTemporality|null} [aggregationTemporality] Sum aggregationTemporality + * @property {boolean|null} [isMonotonic] Sum isMonotonic + */ + /** + * Constructs a new Sum. + * @memberof opentelemetry.proto.metrics.v1 + * @classdesc Represents a Sum. + * @implements ISum + * @constructor + * @param {opentelemetry.proto.metrics.v1.ISum=} [properties] Properties to set + */ + function Sum(properties) { + this.dataPoints = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * Sum dataPoints. + * @member {Array.} dataPoints + * @memberof opentelemetry.proto.metrics.v1.Sum + * @instance + */ + Sum.prototype.dataPoints = $util.emptyArray; + /** + * Sum aggregationTemporality. + * @member {opentelemetry.proto.metrics.v1.AggregationTemporality|null|undefined} aggregationTemporality + * @memberof opentelemetry.proto.metrics.v1.Sum + * @instance + */ + Sum.prototype.aggregationTemporality = null; + /** + * Sum isMonotonic. + * @member {boolean|null|undefined} isMonotonic + * @memberof opentelemetry.proto.metrics.v1.Sum + * @instance + */ + Sum.prototype.isMonotonic = null; + /** + * Creates a new Sum instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.metrics.v1.Sum + * @static + * @param {opentelemetry.proto.metrics.v1.ISum=} [properties] Properties to set + * @returns {opentelemetry.proto.metrics.v1.Sum} Sum instance + */ + Sum.create = function create(properties) { + return new Sum(properties); + }; + /** + * Encodes the specified Sum message. Does not implicitly {@link opentelemetry.proto.metrics.v1.Sum.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.metrics.v1.Sum + * @static + * @param {opentelemetry.proto.metrics.v1.ISum} message Sum message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Sum.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.dataPoints != null && message.dataPoints.length) + for (var i = 0; i < message.dataPoints.length; ++i) + $root.opentelemetry.proto.metrics.v1.NumberDataPoint.encode(message.dataPoints[i], writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); + if (message.aggregationTemporality != null && Object.hasOwnProperty.call(message, "aggregationTemporality")) + writer.uint32(/* id 2, wireType 0 =*/ 16).int32(message.aggregationTemporality); + if (message.isMonotonic != null && Object.hasOwnProperty.call(message, "isMonotonic")) + writer.uint32(/* id 3, wireType 0 =*/ 24).bool(message.isMonotonic); + return writer; + }; + /** + * Encodes the specified Sum message, length delimited. Does not implicitly {@link opentelemetry.proto.metrics.v1.Sum.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.metrics.v1.Sum + * @static + * @param {opentelemetry.proto.metrics.v1.ISum} message Sum message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Sum.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes a Sum message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.metrics.v1.Sum + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.metrics.v1.Sum} Sum + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Sum.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.Sum(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.dataPoints && message.dataPoints.length)) + message.dataPoints = []; + message.dataPoints.push($root.opentelemetry.proto.metrics.v1.NumberDataPoint.decode(reader, reader.uint32())); + break; + } + case 2: { + message.aggregationTemporality = reader.int32(); + break; + } + case 3: { + message.isMonotonic = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes a Sum message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.metrics.v1.Sum + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.metrics.v1.Sum} Sum + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Sum.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies a Sum message. + * @function verify + * @memberof opentelemetry.proto.metrics.v1.Sum + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Sum.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.dataPoints != null && message.hasOwnProperty("dataPoints")) { + if (!Array.isArray(message.dataPoints)) + return "dataPoints: array expected"; + for (var i = 0; i < message.dataPoints.length; ++i) { + var error = $root.opentelemetry.proto.metrics.v1.NumberDataPoint.verify(message.dataPoints[i]); + if (error) + return "dataPoints." + error; + } + } + if (message.aggregationTemporality != null && message.hasOwnProperty("aggregationTemporality")) + switch (message.aggregationTemporality) { + default: + return "aggregationTemporality: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.isMonotonic != null && message.hasOwnProperty("isMonotonic")) + if (typeof message.isMonotonic !== "boolean") + return "isMonotonic: boolean expected"; + return null; + }; + /** + * Creates a Sum message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.metrics.v1.Sum + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.metrics.v1.Sum} Sum + */ + Sum.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.metrics.v1.Sum) + return object; + var message = new $root.opentelemetry.proto.metrics.v1.Sum(); + if (object.dataPoints) { + if (!Array.isArray(object.dataPoints)) + throw TypeError(".opentelemetry.proto.metrics.v1.Sum.dataPoints: array expected"); + message.dataPoints = []; + for (var i = 0; i < object.dataPoints.length; ++i) { + if (typeof object.dataPoints[i] !== "object") + throw TypeError(".opentelemetry.proto.metrics.v1.Sum.dataPoints: object expected"); + message.dataPoints[i] = $root.opentelemetry.proto.metrics.v1.NumberDataPoint.fromObject(object.dataPoints[i]); + } + } + switch (object.aggregationTemporality) { + default: + if (typeof object.aggregationTemporality === "number") { + message.aggregationTemporality = object.aggregationTemporality; + break; + } + break; + case "AGGREGATION_TEMPORALITY_UNSPECIFIED": + case 0: + message.aggregationTemporality = 0; + break; + case "AGGREGATION_TEMPORALITY_DELTA": + case 1: + message.aggregationTemporality = 1; + break; + case "AGGREGATION_TEMPORALITY_CUMULATIVE": + case 2: + message.aggregationTemporality = 2; + break; + } + if (object.isMonotonic != null) + message.isMonotonic = Boolean(object.isMonotonic); + return message; + }; + /** + * Creates a plain object from a Sum message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.metrics.v1.Sum + * @static + * @param {opentelemetry.proto.metrics.v1.Sum} message Sum + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Sum.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.dataPoints = []; + if (options.defaults) { + object.aggregationTemporality = options.enums === String ? "AGGREGATION_TEMPORALITY_UNSPECIFIED" : 0; + object.isMonotonic = false; + } + if (message.dataPoints && message.dataPoints.length) { + object.dataPoints = []; + for (var j = 0; j < message.dataPoints.length; ++j) + object.dataPoints[j] = $root.opentelemetry.proto.metrics.v1.NumberDataPoint.toObject(message.dataPoints[j], options); + } + if (message.aggregationTemporality != null && message.hasOwnProperty("aggregationTemporality")) + object.aggregationTemporality = options.enums === String ? $root.opentelemetry.proto.metrics.v1.AggregationTemporality[message.aggregationTemporality] === undefined ? message.aggregationTemporality : $root.opentelemetry.proto.metrics.v1.AggregationTemporality[message.aggregationTemporality] : message.aggregationTemporality; + if (message.isMonotonic != null && message.hasOwnProperty("isMonotonic")) + object.isMonotonic = message.isMonotonic; + return object; + }; + /** + * Converts this Sum to JSON. + * @function toJSON + * @memberof opentelemetry.proto.metrics.v1.Sum + * @instance + * @returns {Object.} JSON object + */ + Sum.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for Sum + * @function getTypeUrl + * @memberof opentelemetry.proto.metrics.v1.Sum + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Sum.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.Sum"; + }; + return Sum; + })(); + v1.Histogram = (function () { + /** + * Properties of a Histogram. + * @memberof opentelemetry.proto.metrics.v1 + * @interface IHistogram + * @property {Array.|null} [dataPoints] Histogram dataPoints + * @property {opentelemetry.proto.metrics.v1.AggregationTemporality|null} [aggregationTemporality] Histogram aggregationTemporality + */ + /** + * Constructs a new Histogram. + * @memberof opentelemetry.proto.metrics.v1 + * @classdesc Represents a Histogram. + * @implements IHistogram + * @constructor + * @param {opentelemetry.proto.metrics.v1.IHistogram=} [properties] Properties to set + */ + function Histogram(properties) { + this.dataPoints = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * Histogram dataPoints. + * @member {Array.} dataPoints + * @memberof opentelemetry.proto.metrics.v1.Histogram + * @instance + */ + Histogram.prototype.dataPoints = $util.emptyArray; + /** + * Histogram aggregationTemporality. + * @member {opentelemetry.proto.metrics.v1.AggregationTemporality|null|undefined} aggregationTemporality + * @memberof opentelemetry.proto.metrics.v1.Histogram + * @instance + */ + Histogram.prototype.aggregationTemporality = null; + /** + * Creates a new Histogram instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.metrics.v1.Histogram + * @static + * @param {opentelemetry.proto.metrics.v1.IHistogram=} [properties] Properties to set + * @returns {opentelemetry.proto.metrics.v1.Histogram} Histogram instance + */ + Histogram.create = function create(properties) { + return new Histogram(properties); + }; + /** + * Encodes the specified Histogram message. Does not implicitly {@link opentelemetry.proto.metrics.v1.Histogram.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.metrics.v1.Histogram + * @static + * @param {opentelemetry.proto.metrics.v1.IHistogram} message Histogram message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Histogram.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.dataPoints != null && message.dataPoints.length) + for (var i = 0; i < message.dataPoints.length; ++i) + $root.opentelemetry.proto.metrics.v1.HistogramDataPoint.encode(message.dataPoints[i], writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); + if (message.aggregationTemporality != null && Object.hasOwnProperty.call(message, "aggregationTemporality")) + writer.uint32(/* id 2, wireType 0 =*/ 16).int32(message.aggregationTemporality); + return writer; + }; + /** + * Encodes the specified Histogram message, length delimited. Does not implicitly {@link opentelemetry.proto.metrics.v1.Histogram.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.metrics.v1.Histogram + * @static + * @param {opentelemetry.proto.metrics.v1.IHistogram} message Histogram message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Histogram.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes a Histogram message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.metrics.v1.Histogram + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.metrics.v1.Histogram} Histogram + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Histogram.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.Histogram(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.dataPoints && message.dataPoints.length)) + message.dataPoints = []; + message.dataPoints.push($root.opentelemetry.proto.metrics.v1.HistogramDataPoint.decode(reader, reader.uint32())); + break; + } + case 2: { + message.aggregationTemporality = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes a Histogram message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.metrics.v1.Histogram + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.metrics.v1.Histogram} Histogram + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Histogram.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies a Histogram message. + * @function verify + * @memberof opentelemetry.proto.metrics.v1.Histogram + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Histogram.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.dataPoints != null && message.hasOwnProperty("dataPoints")) { + if (!Array.isArray(message.dataPoints)) + return "dataPoints: array expected"; + for (var i = 0; i < message.dataPoints.length; ++i) { + var error = $root.opentelemetry.proto.metrics.v1.HistogramDataPoint.verify(message.dataPoints[i]); + if (error) + return "dataPoints." + error; + } + } + if (message.aggregationTemporality != null && message.hasOwnProperty("aggregationTemporality")) + switch (message.aggregationTemporality) { + default: + return "aggregationTemporality: enum value expected"; + case 0: + case 1: + case 2: + break; + } + return null; + }; + /** + * Creates a Histogram message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.metrics.v1.Histogram + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.metrics.v1.Histogram} Histogram + */ + Histogram.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.metrics.v1.Histogram) + return object; + var message = new $root.opentelemetry.proto.metrics.v1.Histogram(); + if (object.dataPoints) { + if (!Array.isArray(object.dataPoints)) + throw TypeError(".opentelemetry.proto.metrics.v1.Histogram.dataPoints: array expected"); + message.dataPoints = []; + for (var i = 0; i < object.dataPoints.length; ++i) { + if (typeof object.dataPoints[i] !== "object") + throw TypeError(".opentelemetry.proto.metrics.v1.Histogram.dataPoints: object expected"); + message.dataPoints[i] = $root.opentelemetry.proto.metrics.v1.HistogramDataPoint.fromObject(object.dataPoints[i]); + } + } + switch (object.aggregationTemporality) { + default: + if (typeof object.aggregationTemporality === "number") { + message.aggregationTemporality = object.aggregationTemporality; + break; + } + break; + case "AGGREGATION_TEMPORALITY_UNSPECIFIED": + case 0: + message.aggregationTemporality = 0; + break; + case "AGGREGATION_TEMPORALITY_DELTA": + case 1: + message.aggregationTemporality = 1; + break; + case "AGGREGATION_TEMPORALITY_CUMULATIVE": + case 2: + message.aggregationTemporality = 2; + break; + } + return message; + }; + /** + * Creates a plain object from a Histogram message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.metrics.v1.Histogram + * @static + * @param {opentelemetry.proto.metrics.v1.Histogram} message Histogram + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Histogram.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.dataPoints = []; + if (options.defaults) + object.aggregationTemporality = options.enums === String ? "AGGREGATION_TEMPORALITY_UNSPECIFIED" : 0; + if (message.dataPoints && message.dataPoints.length) { + object.dataPoints = []; + for (var j = 0; j < message.dataPoints.length; ++j) + object.dataPoints[j] = $root.opentelemetry.proto.metrics.v1.HistogramDataPoint.toObject(message.dataPoints[j], options); + } + if (message.aggregationTemporality != null && message.hasOwnProperty("aggregationTemporality")) + object.aggregationTemporality = options.enums === String ? $root.opentelemetry.proto.metrics.v1.AggregationTemporality[message.aggregationTemporality] === undefined ? message.aggregationTemporality : $root.opentelemetry.proto.metrics.v1.AggregationTemporality[message.aggregationTemporality] : message.aggregationTemporality; + return object; + }; + /** + * Converts this Histogram to JSON. + * @function toJSON + * @memberof opentelemetry.proto.metrics.v1.Histogram + * @instance + * @returns {Object.} JSON object + */ + Histogram.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for Histogram + * @function getTypeUrl + * @memberof opentelemetry.proto.metrics.v1.Histogram + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Histogram.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.Histogram"; + }; + return Histogram; + })(); + v1.ExponentialHistogram = (function () { + /** + * Properties of an ExponentialHistogram. + * @memberof opentelemetry.proto.metrics.v1 + * @interface IExponentialHistogram + * @property {Array.|null} [dataPoints] ExponentialHistogram dataPoints + * @property {opentelemetry.proto.metrics.v1.AggregationTemporality|null} [aggregationTemporality] ExponentialHistogram aggregationTemporality + */ + /** + * Constructs a new ExponentialHistogram. + * @memberof opentelemetry.proto.metrics.v1 + * @classdesc Represents an ExponentialHistogram. + * @implements IExponentialHistogram + * @constructor + * @param {opentelemetry.proto.metrics.v1.IExponentialHistogram=} [properties] Properties to set + */ + function ExponentialHistogram(properties) { + this.dataPoints = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * ExponentialHistogram dataPoints. + * @member {Array.} dataPoints + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogram + * @instance + */ + ExponentialHistogram.prototype.dataPoints = $util.emptyArray; + /** + * ExponentialHistogram aggregationTemporality. + * @member {opentelemetry.proto.metrics.v1.AggregationTemporality|null|undefined} aggregationTemporality + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogram + * @instance + */ + ExponentialHistogram.prototype.aggregationTemporality = null; + /** + * Creates a new ExponentialHistogram instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogram + * @static + * @param {opentelemetry.proto.metrics.v1.IExponentialHistogram=} [properties] Properties to set + * @returns {opentelemetry.proto.metrics.v1.ExponentialHistogram} ExponentialHistogram instance + */ + ExponentialHistogram.create = function create(properties) { + return new ExponentialHistogram(properties); + }; + /** + * Encodes the specified ExponentialHistogram message. Does not implicitly {@link opentelemetry.proto.metrics.v1.ExponentialHistogram.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogram + * @static + * @param {opentelemetry.proto.metrics.v1.IExponentialHistogram} message ExponentialHistogram message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExponentialHistogram.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.dataPoints != null && message.dataPoints.length) + for (var i = 0; i < message.dataPoints.length; ++i) + $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.encode(message.dataPoints[i], writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); + if (message.aggregationTemporality != null && Object.hasOwnProperty.call(message, "aggregationTemporality")) + writer.uint32(/* id 2, wireType 0 =*/ 16).int32(message.aggregationTemporality); + return writer; + }; + /** + * Encodes the specified ExponentialHistogram message, length delimited. Does not implicitly {@link opentelemetry.proto.metrics.v1.ExponentialHistogram.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogram + * @static + * @param {opentelemetry.proto.metrics.v1.IExponentialHistogram} message ExponentialHistogram message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExponentialHistogram.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes an ExponentialHistogram message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogram + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.metrics.v1.ExponentialHistogram} ExponentialHistogram + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExponentialHistogram.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.ExponentialHistogram(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.dataPoints && message.dataPoints.length)) + message.dataPoints = []; + message.dataPoints.push($root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.decode(reader, reader.uint32())); + break; + } + case 2: { + message.aggregationTemporality = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes an ExponentialHistogram message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogram + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.metrics.v1.ExponentialHistogram} ExponentialHistogram + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExponentialHistogram.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies an ExponentialHistogram message. + * @function verify + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogram + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ExponentialHistogram.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.dataPoints != null && message.hasOwnProperty("dataPoints")) { + if (!Array.isArray(message.dataPoints)) + return "dataPoints: array expected"; + for (var i = 0; i < message.dataPoints.length; ++i) { + var error = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.verify(message.dataPoints[i]); + if (error) + return "dataPoints." + error; + } + } + if (message.aggregationTemporality != null && message.hasOwnProperty("aggregationTemporality")) + switch (message.aggregationTemporality) { + default: + return "aggregationTemporality: enum value expected"; + case 0: + case 1: + case 2: + break; + } + return null; + }; + /** + * Creates an ExponentialHistogram message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogram + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.metrics.v1.ExponentialHistogram} ExponentialHistogram + */ + ExponentialHistogram.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.metrics.v1.ExponentialHistogram) + return object; + var message = new $root.opentelemetry.proto.metrics.v1.ExponentialHistogram(); + if (object.dataPoints) { + if (!Array.isArray(object.dataPoints)) + throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogram.dataPoints: array expected"); + message.dataPoints = []; + for (var i = 0; i < object.dataPoints.length; ++i) { + if (typeof object.dataPoints[i] !== "object") + throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogram.dataPoints: object expected"); + message.dataPoints[i] = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.fromObject(object.dataPoints[i]); + } + } + switch (object.aggregationTemporality) { + default: + if (typeof object.aggregationTemporality === "number") { + message.aggregationTemporality = object.aggregationTemporality; + break; + } + break; + case "AGGREGATION_TEMPORALITY_UNSPECIFIED": + case 0: + message.aggregationTemporality = 0; + break; + case "AGGREGATION_TEMPORALITY_DELTA": + case 1: + message.aggregationTemporality = 1; + break; + case "AGGREGATION_TEMPORALITY_CUMULATIVE": + case 2: + message.aggregationTemporality = 2; + break; + } + return message; + }; + /** + * Creates a plain object from an ExponentialHistogram message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogram + * @static + * @param {opentelemetry.proto.metrics.v1.ExponentialHistogram} message ExponentialHistogram + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExponentialHistogram.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.dataPoints = []; + if (options.defaults) + object.aggregationTemporality = options.enums === String ? "AGGREGATION_TEMPORALITY_UNSPECIFIED" : 0; + if (message.dataPoints && message.dataPoints.length) { + object.dataPoints = []; + for (var j = 0; j < message.dataPoints.length; ++j) + object.dataPoints[j] = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.toObject(message.dataPoints[j], options); + } + if (message.aggregationTemporality != null && message.hasOwnProperty("aggregationTemporality")) + object.aggregationTemporality = options.enums === String ? $root.opentelemetry.proto.metrics.v1.AggregationTemporality[message.aggregationTemporality] === undefined ? message.aggregationTemporality : $root.opentelemetry.proto.metrics.v1.AggregationTemporality[message.aggregationTemporality] : message.aggregationTemporality; + return object; + }; + /** + * Converts this ExponentialHistogram to JSON. + * @function toJSON + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogram + * @instance + * @returns {Object.} JSON object + */ + ExponentialHistogram.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for ExponentialHistogram + * @function getTypeUrl + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogram + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExponentialHistogram.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.ExponentialHistogram"; + }; + return ExponentialHistogram; + })(); + v1.Summary = (function () { + /** + * Properties of a Summary. + * @memberof opentelemetry.proto.metrics.v1 + * @interface ISummary + * @property {Array.|null} [dataPoints] Summary dataPoints + */ + /** + * Constructs a new Summary. + * @memberof opentelemetry.proto.metrics.v1 + * @classdesc Represents a Summary. + * @implements ISummary + * @constructor + * @param {opentelemetry.proto.metrics.v1.ISummary=} [properties] Properties to set + */ + function Summary(properties) { + this.dataPoints = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * Summary dataPoints. + * @member {Array.} dataPoints + * @memberof opentelemetry.proto.metrics.v1.Summary + * @instance + */ + Summary.prototype.dataPoints = $util.emptyArray; + /** + * Creates a new Summary instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.metrics.v1.Summary + * @static + * @param {opentelemetry.proto.metrics.v1.ISummary=} [properties] Properties to set + * @returns {opentelemetry.proto.metrics.v1.Summary} Summary instance + */ + Summary.create = function create(properties) { + return new Summary(properties); + }; + /** + * Encodes the specified Summary message. Does not implicitly {@link opentelemetry.proto.metrics.v1.Summary.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.metrics.v1.Summary + * @static + * @param {opentelemetry.proto.metrics.v1.ISummary} message Summary message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Summary.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.dataPoints != null && message.dataPoints.length) + for (var i = 0; i < message.dataPoints.length; ++i) + $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.encode(message.dataPoints[i], writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); + return writer; + }; + /** + * Encodes the specified Summary message, length delimited. Does not implicitly {@link opentelemetry.proto.metrics.v1.Summary.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.metrics.v1.Summary + * @static + * @param {opentelemetry.proto.metrics.v1.ISummary} message Summary message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Summary.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes a Summary message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.metrics.v1.Summary + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.metrics.v1.Summary} Summary + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Summary.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.Summary(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.dataPoints && message.dataPoints.length)) + message.dataPoints = []; + message.dataPoints.push($root.opentelemetry.proto.metrics.v1.SummaryDataPoint.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes a Summary message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.metrics.v1.Summary + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.metrics.v1.Summary} Summary + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Summary.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies a Summary message. + * @function verify + * @memberof opentelemetry.proto.metrics.v1.Summary + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Summary.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.dataPoints != null && message.hasOwnProperty("dataPoints")) { + if (!Array.isArray(message.dataPoints)) + return "dataPoints: array expected"; + for (var i = 0; i < message.dataPoints.length; ++i) { + var error = $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.verify(message.dataPoints[i]); + if (error) + return "dataPoints." + error; + } + } + return null; + }; + /** + * Creates a Summary message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.metrics.v1.Summary + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.metrics.v1.Summary} Summary + */ + Summary.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.metrics.v1.Summary) + return object; + var message = new $root.opentelemetry.proto.metrics.v1.Summary(); + if (object.dataPoints) { + if (!Array.isArray(object.dataPoints)) + throw TypeError(".opentelemetry.proto.metrics.v1.Summary.dataPoints: array expected"); + message.dataPoints = []; + for (var i = 0; i < object.dataPoints.length; ++i) { + if (typeof object.dataPoints[i] !== "object") + throw TypeError(".opentelemetry.proto.metrics.v1.Summary.dataPoints: object expected"); + message.dataPoints[i] = $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.fromObject(object.dataPoints[i]); + } + } + return message; + }; + /** + * Creates a plain object from a Summary message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.metrics.v1.Summary + * @static + * @param {opentelemetry.proto.metrics.v1.Summary} message Summary + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Summary.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.dataPoints = []; + if (message.dataPoints && message.dataPoints.length) { + object.dataPoints = []; + for (var j = 0; j < message.dataPoints.length; ++j) + object.dataPoints[j] = $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.toObject(message.dataPoints[j], options); + } + return object; + }; + /** + * Converts this Summary to JSON. + * @function toJSON + * @memberof opentelemetry.proto.metrics.v1.Summary + * @instance + * @returns {Object.} JSON object + */ + Summary.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for Summary + * @function getTypeUrl + * @memberof opentelemetry.proto.metrics.v1.Summary + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Summary.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.Summary"; + }; + return Summary; + })(); + /** + * AggregationTemporality enum. + * @name opentelemetry.proto.metrics.v1.AggregationTemporality + * @enum {number} + * @property {number} AGGREGATION_TEMPORALITY_UNSPECIFIED=0 AGGREGATION_TEMPORALITY_UNSPECIFIED value + * @property {number} AGGREGATION_TEMPORALITY_DELTA=1 AGGREGATION_TEMPORALITY_DELTA value + * @property {number} AGGREGATION_TEMPORALITY_CUMULATIVE=2 AGGREGATION_TEMPORALITY_CUMULATIVE value + */ + v1.AggregationTemporality = (function () { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "AGGREGATION_TEMPORALITY_UNSPECIFIED"] = 0; + values[valuesById[1] = "AGGREGATION_TEMPORALITY_DELTA"] = 1; + values[valuesById[2] = "AGGREGATION_TEMPORALITY_CUMULATIVE"] = 2; + return values; + })(); + /** + * DataPointFlags enum. + * @name opentelemetry.proto.metrics.v1.DataPointFlags + * @enum {number} + * @property {number} DATA_POINT_FLAGS_DO_NOT_USE=0 DATA_POINT_FLAGS_DO_NOT_USE value + * @property {number} DATA_POINT_FLAGS_NO_RECORDED_VALUE_MASK=1 DATA_POINT_FLAGS_NO_RECORDED_VALUE_MASK value + */ + v1.DataPointFlags = (function () { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "DATA_POINT_FLAGS_DO_NOT_USE"] = 0; + values[valuesById[1] = "DATA_POINT_FLAGS_NO_RECORDED_VALUE_MASK"] = 1; + return values; + })(); + v1.NumberDataPoint = (function () { + /** + * Properties of a NumberDataPoint. + * @memberof opentelemetry.proto.metrics.v1 + * @interface INumberDataPoint + * @property {Array.|null} [attributes] NumberDataPoint attributes + * @property {number|Long|null} [startTimeUnixNano] NumberDataPoint startTimeUnixNano + * @property {number|Long|null} [timeUnixNano] NumberDataPoint timeUnixNano + * @property {number|null} [asDouble] NumberDataPoint asDouble + * @property {number|Long|null} [asInt] NumberDataPoint asInt + * @property {Array.|null} [exemplars] NumberDataPoint exemplars + * @property {number|null} [flags] NumberDataPoint flags + */ + /** + * Constructs a new NumberDataPoint. + * @memberof opentelemetry.proto.metrics.v1 + * @classdesc Represents a NumberDataPoint. + * @implements INumberDataPoint + * @constructor + * @param {opentelemetry.proto.metrics.v1.INumberDataPoint=} [properties] Properties to set + */ + function NumberDataPoint(properties) { + this.attributes = []; + this.exemplars = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * NumberDataPoint attributes. + * @member {Array.} attributes + * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint + * @instance + */ + NumberDataPoint.prototype.attributes = $util.emptyArray; + /** + * NumberDataPoint startTimeUnixNano. + * @member {number|Long|null|undefined} startTimeUnixNano + * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint + * @instance + */ + NumberDataPoint.prototype.startTimeUnixNano = null; + /** + * NumberDataPoint timeUnixNano. + * @member {number|Long|null|undefined} timeUnixNano + * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint + * @instance + */ + NumberDataPoint.prototype.timeUnixNano = null; + /** + * NumberDataPoint asDouble. + * @member {number|null|undefined} asDouble + * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint + * @instance + */ + NumberDataPoint.prototype.asDouble = null; + /** + * NumberDataPoint asInt. + * @member {number|Long|null|undefined} asInt + * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint + * @instance + */ + NumberDataPoint.prototype.asInt = null; + /** + * NumberDataPoint exemplars. + * @member {Array.} exemplars + * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint + * @instance + */ + NumberDataPoint.prototype.exemplars = $util.emptyArray; + /** + * NumberDataPoint flags. + * @member {number|null|undefined} flags + * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint + * @instance + */ + NumberDataPoint.prototype.flags = null; + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + /** + * NumberDataPoint value. + * @member {"asDouble"|"asInt"|undefined} value + * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint + * @instance + */ + Object.defineProperty(NumberDataPoint.prototype, "value", { + get: $util.oneOfGetter($oneOfFields = ["asDouble", "asInt"]), + set: $util.oneOfSetter($oneOfFields) + }); + /** + * Creates a new NumberDataPoint instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint + * @static + * @param {opentelemetry.proto.metrics.v1.INumberDataPoint=} [properties] Properties to set + * @returns {opentelemetry.proto.metrics.v1.NumberDataPoint} NumberDataPoint instance + */ + NumberDataPoint.create = function create(properties) { + return new NumberDataPoint(properties); + }; + /** + * Encodes the specified NumberDataPoint message. Does not implicitly {@link opentelemetry.proto.metrics.v1.NumberDataPoint.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint + * @static + * @param {opentelemetry.proto.metrics.v1.INumberDataPoint} message NumberDataPoint message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + NumberDataPoint.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.startTimeUnixNano != null && Object.hasOwnProperty.call(message, "startTimeUnixNano")) + writer.uint32(/* id 2, wireType 1 =*/ 17).fixed64(message.startTimeUnixNano); + if (message.timeUnixNano != null && Object.hasOwnProperty.call(message, "timeUnixNano")) + writer.uint32(/* id 3, wireType 1 =*/ 25).fixed64(message.timeUnixNano); + if (message.asDouble != null && Object.hasOwnProperty.call(message, "asDouble")) + writer.uint32(/* id 4, wireType 1 =*/ 33).double(message.asDouble); + if (message.exemplars != null && message.exemplars.length) + for (var i = 0; i < message.exemplars.length; ++i) + $root.opentelemetry.proto.metrics.v1.Exemplar.encode(message.exemplars[i], writer.uint32(/* id 5, wireType 2 =*/ 42).fork()).ldelim(); + if (message.asInt != null && Object.hasOwnProperty.call(message, "asInt")) + writer.uint32(/* id 6, wireType 1 =*/ 49).sfixed64(message.asInt); + if (message.attributes != null && message.attributes.length) + for (var i = 0; i < message.attributes.length; ++i) + $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(/* id 7, wireType 2 =*/ 58).fork()).ldelim(); + if (message.flags != null && Object.hasOwnProperty.call(message, "flags")) + writer.uint32(/* id 8, wireType 0 =*/ 64).uint32(message.flags); + return writer; + }; + /** + * Encodes the specified NumberDataPoint message, length delimited. Does not implicitly {@link opentelemetry.proto.metrics.v1.NumberDataPoint.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint + * @static + * @param {opentelemetry.proto.metrics.v1.INumberDataPoint} message NumberDataPoint message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + NumberDataPoint.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes a NumberDataPoint message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.metrics.v1.NumberDataPoint} NumberDataPoint + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + NumberDataPoint.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.NumberDataPoint(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 7: { + if (!(message.attributes && message.attributes.length)) + message.attributes = []; + message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32())); + break; + } + case 2: { + message.startTimeUnixNano = reader.fixed64(); + break; + } + case 3: { + message.timeUnixNano = reader.fixed64(); + break; + } + case 4: { + message.asDouble = reader.double(); + break; + } + case 6: { + message.asInt = reader.sfixed64(); + break; + } + case 5: { + if (!(message.exemplars && message.exemplars.length)) + message.exemplars = []; + message.exemplars.push($root.opentelemetry.proto.metrics.v1.Exemplar.decode(reader, reader.uint32())); + break; + } + case 8: { + message.flags = reader.uint32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes a NumberDataPoint message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.metrics.v1.NumberDataPoint} NumberDataPoint + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + NumberDataPoint.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies a NumberDataPoint message. + * @function verify + * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + NumberDataPoint.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.attributes != null && message.hasOwnProperty("attributes")) { + if (!Array.isArray(message.attributes)) + return "attributes: array expected"; + for (var i = 0; i < message.attributes.length; ++i) { + var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]); + if (error) + return "attributes." + error; + } + } + if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano")) + if (!$util.isInteger(message.startTimeUnixNano) && !(message.startTimeUnixNano && $util.isInteger(message.startTimeUnixNano.low) && $util.isInteger(message.startTimeUnixNano.high))) + return "startTimeUnixNano: integer|Long expected"; + if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) + if (!$util.isInteger(message.timeUnixNano) && !(message.timeUnixNano && $util.isInteger(message.timeUnixNano.low) && $util.isInteger(message.timeUnixNano.high))) + return "timeUnixNano: integer|Long expected"; + if (message.asDouble != null && message.hasOwnProperty("asDouble")) { + properties.value = 1; + if (typeof message.asDouble !== "number") + return "asDouble: number expected"; + } + if (message.asInt != null && message.hasOwnProperty("asInt")) { + if (properties.value === 1) + return "value: multiple values"; + properties.value = 1; + if (!$util.isInteger(message.asInt) && !(message.asInt && $util.isInteger(message.asInt.low) && $util.isInteger(message.asInt.high))) + return "asInt: integer|Long expected"; + } + if (message.exemplars != null && message.hasOwnProperty("exemplars")) { + if (!Array.isArray(message.exemplars)) + return "exemplars: array expected"; + for (var i = 0; i < message.exemplars.length; ++i) { + var error = $root.opentelemetry.proto.metrics.v1.Exemplar.verify(message.exemplars[i]); + if (error) + return "exemplars." + error; + } + } + if (message.flags != null && message.hasOwnProperty("flags")) + if (!$util.isInteger(message.flags)) + return "flags: integer expected"; + return null; + }; + /** + * Creates a NumberDataPoint message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.metrics.v1.NumberDataPoint} NumberDataPoint + */ + NumberDataPoint.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.metrics.v1.NumberDataPoint) + return object; + var message = new $root.opentelemetry.proto.metrics.v1.NumberDataPoint(); + if (object.attributes) { + if (!Array.isArray(object.attributes)) + throw TypeError(".opentelemetry.proto.metrics.v1.NumberDataPoint.attributes: array expected"); + message.attributes = []; + for (var i = 0; i < object.attributes.length; ++i) { + if (typeof object.attributes[i] !== "object") + throw TypeError(".opentelemetry.proto.metrics.v1.NumberDataPoint.attributes: object expected"); + message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]); + } + } + if (object.startTimeUnixNano != null) + if ($util.Long) + (message.startTimeUnixNano = $util.Long.fromValue(object.startTimeUnixNano)).unsigned = false; + else if (typeof object.startTimeUnixNano === "string") + message.startTimeUnixNano = parseInt(object.startTimeUnixNano, 10); + else if (typeof object.startTimeUnixNano === "number") + message.startTimeUnixNano = object.startTimeUnixNano; + else if (typeof object.startTimeUnixNano === "object") + message.startTimeUnixNano = new $util.LongBits(object.startTimeUnixNano.low >>> 0, object.startTimeUnixNano.high >>> 0).toNumber(); + if (object.timeUnixNano != null) + if ($util.Long) + (message.timeUnixNano = $util.Long.fromValue(object.timeUnixNano)).unsigned = false; + else if (typeof object.timeUnixNano === "string") + message.timeUnixNano = parseInt(object.timeUnixNano, 10); + else if (typeof object.timeUnixNano === "number") + message.timeUnixNano = object.timeUnixNano; + else if (typeof object.timeUnixNano === "object") + message.timeUnixNano = new $util.LongBits(object.timeUnixNano.low >>> 0, object.timeUnixNano.high >>> 0).toNumber(); + if (object.asDouble != null) + message.asDouble = Number(object.asDouble); + if (object.asInt != null) + if ($util.Long) + (message.asInt = $util.Long.fromValue(object.asInt)).unsigned = false; + else if (typeof object.asInt === "string") + message.asInt = parseInt(object.asInt, 10); + else if (typeof object.asInt === "number") + message.asInt = object.asInt; + else if (typeof object.asInt === "object") + message.asInt = new $util.LongBits(object.asInt.low >>> 0, object.asInt.high >>> 0).toNumber(); + if (object.exemplars) { + if (!Array.isArray(object.exemplars)) + throw TypeError(".opentelemetry.proto.metrics.v1.NumberDataPoint.exemplars: array expected"); + message.exemplars = []; + for (var i = 0; i < object.exemplars.length; ++i) { + if (typeof object.exemplars[i] !== "object") + throw TypeError(".opentelemetry.proto.metrics.v1.NumberDataPoint.exemplars: object expected"); + message.exemplars[i] = $root.opentelemetry.proto.metrics.v1.Exemplar.fromObject(object.exemplars[i]); + } + } + if (object.flags != null) + message.flags = object.flags >>> 0; + return message; + }; + /** + * Creates a plain object from a NumberDataPoint message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint + * @static + * @param {opentelemetry.proto.metrics.v1.NumberDataPoint} message NumberDataPoint + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + NumberDataPoint.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.exemplars = []; + object.attributes = []; + } + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.startTimeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } + else + object.startTimeUnixNano = options.longs === String ? "0" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.timeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } + else + object.timeUnixNano = options.longs === String ? "0" : 0; + object.flags = 0; + } + if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano")) + if (typeof message.startTimeUnixNano === "number") + object.startTimeUnixNano = options.longs === String ? String(message.startTimeUnixNano) : message.startTimeUnixNano; + else + object.startTimeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.startTimeUnixNano) : options.longs === Number ? new $util.LongBits(message.startTimeUnixNano.low >>> 0, message.startTimeUnixNano.high >>> 0).toNumber() : message.startTimeUnixNano; + if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) + if (typeof message.timeUnixNano === "number") + object.timeUnixNano = options.longs === String ? String(message.timeUnixNano) : message.timeUnixNano; + else + object.timeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.timeUnixNano) : options.longs === Number ? new $util.LongBits(message.timeUnixNano.low >>> 0, message.timeUnixNano.high >>> 0).toNumber() : message.timeUnixNano; + if (message.asDouble != null && message.hasOwnProperty("asDouble")) { + object.asDouble = options.json && !isFinite(message.asDouble) ? String(message.asDouble) : message.asDouble; + if (options.oneofs) + object.value = "asDouble"; + } + if (message.exemplars && message.exemplars.length) { + object.exemplars = []; + for (var j = 0; j < message.exemplars.length; ++j) + object.exemplars[j] = $root.opentelemetry.proto.metrics.v1.Exemplar.toObject(message.exemplars[j], options); + } + if (message.asInt != null && message.hasOwnProperty("asInt")) { + if (typeof message.asInt === "number") + object.asInt = options.longs === String ? String(message.asInt) : message.asInt; + else + object.asInt = options.longs === String ? $util.Long.prototype.toString.call(message.asInt) : options.longs === Number ? new $util.LongBits(message.asInt.low >>> 0, message.asInt.high >>> 0).toNumber() : message.asInt; + if (options.oneofs) + object.value = "asInt"; + } + if (message.attributes && message.attributes.length) { + object.attributes = []; + for (var j = 0; j < message.attributes.length; ++j) + object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options); + } + if (message.flags != null && message.hasOwnProperty("flags")) + object.flags = message.flags; + return object; + }; + /** + * Converts this NumberDataPoint to JSON. + * @function toJSON + * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint + * @instance + * @returns {Object.} JSON object + */ + NumberDataPoint.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for NumberDataPoint + * @function getTypeUrl + * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + NumberDataPoint.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.NumberDataPoint"; + }; + return NumberDataPoint; + })(); + v1.HistogramDataPoint = (function () { + /** + * Properties of a HistogramDataPoint. + * @memberof opentelemetry.proto.metrics.v1 + * @interface IHistogramDataPoint + * @property {Array.|null} [attributes] HistogramDataPoint attributes + * @property {number|Long|null} [startTimeUnixNano] HistogramDataPoint startTimeUnixNano + * @property {number|Long|null} [timeUnixNano] HistogramDataPoint timeUnixNano + * @property {number|Long|null} [count] HistogramDataPoint count + * @property {number|null} [sum] HistogramDataPoint sum + * @property {Array.|null} [bucketCounts] HistogramDataPoint bucketCounts + * @property {Array.|null} [explicitBounds] HistogramDataPoint explicitBounds + * @property {Array.|null} [exemplars] HistogramDataPoint exemplars + * @property {number|null} [flags] HistogramDataPoint flags + * @property {number|null} [min] HistogramDataPoint min + * @property {number|null} [max] HistogramDataPoint max + */ + /** + * Constructs a new HistogramDataPoint. + * @memberof opentelemetry.proto.metrics.v1 + * @classdesc Represents a HistogramDataPoint. + * @implements IHistogramDataPoint + * @constructor + * @param {opentelemetry.proto.metrics.v1.IHistogramDataPoint=} [properties] Properties to set + */ + function HistogramDataPoint(properties) { + this.attributes = []; + this.bucketCounts = []; + this.explicitBounds = []; + this.exemplars = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * HistogramDataPoint attributes. + * @member {Array.} attributes + * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint + * @instance + */ + HistogramDataPoint.prototype.attributes = $util.emptyArray; + /** + * HistogramDataPoint startTimeUnixNano. + * @member {number|Long|null|undefined} startTimeUnixNano + * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint + * @instance + */ + HistogramDataPoint.prototype.startTimeUnixNano = null; + /** + * HistogramDataPoint timeUnixNano. + * @member {number|Long|null|undefined} timeUnixNano + * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint + * @instance + */ + HistogramDataPoint.prototype.timeUnixNano = null; + /** + * HistogramDataPoint count. + * @member {number|Long|null|undefined} count + * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint + * @instance + */ + HistogramDataPoint.prototype.count = null; + /** + * HistogramDataPoint sum. + * @member {number|null|undefined} sum + * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint + * @instance + */ + HistogramDataPoint.prototype.sum = null; + /** + * HistogramDataPoint bucketCounts. + * @member {Array.} bucketCounts + * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint + * @instance + */ + HistogramDataPoint.prototype.bucketCounts = $util.emptyArray; + /** + * HistogramDataPoint explicitBounds. + * @member {Array.} explicitBounds + * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint + * @instance + */ + HistogramDataPoint.prototype.explicitBounds = $util.emptyArray; + /** + * HistogramDataPoint exemplars. + * @member {Array.} exemplars + * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint + * @instance + */ + HistogramDataPoint.prototype.exemplars = $util.emptyArray; + /** + * HistogramDataPoint flags. + * @member {number|null|undefined} flags + * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint + * @instance + */ + HistogramDataPoint.prototype.flags = null; + /** + * HistogramDataPoint min. + * @member {number|null|undefined} min + * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint + * @instance + */ + HistogramDataPoint.prototype.min = null; + /** + * HistogramDataPoint max. + * @member {number|null|undefined} max + * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint + * @instance + */ + HistogramDataPoint.prototype.max = null; + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + /** + * HistogramDataPoint _sum. + * @member {"sum"|undefined} _sum + * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint + * @instance + */ + Object.defineProperty(HistogramDataPoint.prototype, "_sum", { + get: $util.oneOfGetter($oneOfFields = ["sum"]), + set: $util.oneOfSetter($oneOfFields) + }); + /** + * HistogramDataPoint _min. + * @member {"min"|undefined} _min + * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint + * @instance + */ + Object.defineProperty(HistogramDataPoint.prototype, "_min", { + get: $util.oneOfGetter($oneOfFields = ["min"]), + set: $util.oneOfSetter($oneOfFields) + }); + /** + * HistogramDataPoint _max. + * @member {"max"|undefined} _max + * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint + * @instance + */ + Object.defineProperty(HistogramDataPoint.prototype, "_max", { + get: $util.oneOfGetter($oneOfFields = ["max"]), + set: $util.oneOfSetter($oneOfFields) + }); + /** + * Creates a new HistogramDataPoint instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint + * @static + * @param {opentelemetry.proto.metrics.v1.IHistogramDataPoint=} [properties] Properties to set + * @returns {opentelemetry.proto.metrics.v1.HistogramDataPoint} HistogramDataPoint instance + */ + HistogramDataPoint.create = function create(properties) { + return new HistogramDataPoint(properties); + }; + /** + * Encodes the specified HistogramDataPoint message. Does not implicitly {@link opentelemetry.proto.metrics.v1.HistogramDataPoint.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint + * @static + * @param {opentelemetry.proto.metrics.v1.IHistogramDataPoint} message HistogramDataPoint message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + HistogramDataPoint.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.startTimeUnixNano != null && Object.hasOwnProperty.call(message, "startTimeUnixNano")) + writer.uint32(/* id 2, wireType 1 =*/ 17).fixed64(message.startTimeUnixNano); + if (message.timeUnixNano != null && Object.hasOwnProperty.call(message, "timeUnixNano")) + writer.uint32(/* id 3, wireType 1 =*/ 25).fixed64(message.timeUnixNano); + if (message.count != null && Object.hasOwnProperty.call(message, "count")) + writer.uint32(/* id 4, wireType 1 =*/ 33).fixed64(message.count); + if (message.sum != null && Object.hasOwnProperty.call(message, "sum")) + writer.uint32(/* id 5, wireType 1 =*/ 41).double(message.sum); + if (message.bucketCounts != null && message.bucketCounts.length) { + writer.uint32(/* id 6, wireType 2 =*/ 50).fork(); + for (var i = 0; i < message.bucketCounts.length; ++i) + writer.fixed64(message.bucketCounts[i]); + writer.ldelim(); + } + if (message.explicitBounds != null && message.explicitBounds.length) { + writer.uint32(/* id 7, wireType 2 =*/ 58).fork(); + for (var i = 0; i < message.explicitBounds.length; ++i) + writer.double(message.explicitBounds[i]); + writer.ldelim(); + } + if (message.exemplars != null && message.exemplars.length) + for (var i = 0; i < message.exemplars.length; ++i) + $root.opentelemetry.proto.metrics.v1.Exemplar.encode(message.exemplars[i], writer.uint32(/* id 8, wireType 2 =*/ 66).fork()).ldelim(); + if (message.attributes != null && message.attributes.length) + for (var i = 0; i < message.attributes.length; ++i) + $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(/* id 9, wireType 2 =*/ 74).fork()).ldelim(); + if (message.flags != null && Object.hasOwnProperty.call(message, "flags")) + writer.uint32(/* id 10, wireType 0 =*/ 80).uint32(message.flags); + if (message.min != null && Object.hasOwnProperty.call(message, "min")) + writer.uint32(/* id 11, wireType 1 =*/ 89).double(message.min); + if (message.max != null && Object.hasOwnProperty.call(message, "max")) + writer.uint32(/* id 12, wireType 1 =*/ 97).double(message.max); + return writer; + }; + /** + * Encodes the specified HistogramDataPoint message, length delimited. Does not implicitly {@link opentelemetry.proto.metrics.v1.HistogramDataPoint.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint + * @static + * @param {opentelemetry.proto.metrics.v1.IHistogramDataPoint} message HistogramDataPoint message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + HistogramDataPoint.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes a HistogramDataPoint message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.metrics.v1.HistogramDataPoint} HistogramDataPoint + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + HistogramDataPoint.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.HistogramDataPoint(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 9: { + if (!(message.attributes && message.attributes.length)) + message.attributes = []; + message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32())); + break; + } + case 2: { + message.startTimeUnixNano = reader.fixed64(); + break; + } + case 3: { + message.timeUnixNano = reader.fixed64(); + break; + } + case 4: { + message.count = reader.fixed64(); + break; + } + case 5: { + message.sum = reader.double(); + break; + } + case 6: { + if (!(message.bucketCounts && message.bucketCounts.length)) + message.bucketCounts = []; + if ((tag & 7) === 2) { + var end2 = reader.uint32() + reader.pos; + while (reader.pos < end2) + message.bucketCounts.push(reader.fixed64()); + } + else + message.bucketCounts.push(reader.fixed64()); + break; + } + case 7: { + if (!(message.explicitBounds && message.explicitBounds.length)) + message.explicitBounds = []; + if ((tag & 7) === 2) { + var end2 = reader.uint32() + reader.pos; + while (reader.pos < end2) + message.explicitBounds.push(reader.double()); + } + else + message.explicitBounds.push(reader.double()); + break; + } + case 8: { + if (!(message.exemplars && message.exemplars.length)) + message.exemplars = []; + message.exemplars.push($root.opentelemetry.proto.metrics.v1.Exemplar.decode(reader, reader.uint32())); + break; + } + case 10: { + message.flags = reader.uint32(); + break; + } + case 11: { + message.min = reader.double(); + break; + } + case 12: { + message.max = reader.double(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes a HistogramDataPoint message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.metrics.v1.HistogramDataPoint} HistogramDataPoint + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + HistogramDataPoint.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies a HistogramDataPoint message. + * @function verify + * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + HistogramDataPoint.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.attributes != null && message.hasOwnProperty("attributes")) { + if (!Array.isArray(message.attributes)) + return "attributes: array expected"; + for (var i = 0; i < message.attributes.length; ++i) { + var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]); + if (error) + return "attributes." + error; + } + } + if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano")) + if (!$util.isInteger(message.startTimeUnixNano) && !(message.startTimeUnixNano && $util.isInteger(message.startTimeUnixNano.low) && $util.isInteger(message.startTimeUnixNano.high))) + return "startTimeUnixNano: integer|Long expected"; + if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) + if (!$util.isInteger(message.timeUnixNano) && !(message.timeUnixNano && $util.isInteger(message.timeUnixNano.low) && $util.isInteger(message.timeUnixNano.high))) + return "timeUnixNano: integer|Long expected"; + if (message.count != null && message.hasOwnProperty("count")) + if (!$util.isInteger(message.count) && !(message.count && $util.isInteger(message.count.low) && $util.isInteger(message.count.high))) + return "count: integer|Long expected"; + if (message.sum != null && message.hasOwnProperty("sum")) { + properties._sum = 1; + if (typeof message.sum !== "number") + return "sum: number expected"; + } + if (message.bucketCounts != null && message.hasOwnProperty("bucketCounts")) { + if (!Array.isArray(message.bucketCounts)) + return "bucketCounts: array expected"; + for (var i = 0; i < message.bucketCounts.length; ++i) + if (!$util.isInteger(message.bucketCounts[i]) && !(message.bucketCounts[i] && $util.isInteger(message.bucketCounts[i].low) && $util.isInteger(message.bucketCounts[i].high))) + return "bucketCounts: integer|Long[] expected"; + } + if (message.explicitBounds != null && message.hasOwnProperty("explicitBounds")) { + if (!Array.isArray(message.explicitBounds)) + return "explicitBounds: array expected"; + for (var i = 0; i < message.explicitBounds.length; ++i) + if (typeof message.explicitBounds[i] !== "number") + return "explicitBounds: number[] expected"; + } + if (message.exemplars != null && message.hasOwnProperty("exemplars")) { + if (!Array.isArray(message.exemplars)) + return "exemplars: array expected"; + for (var i = 0; i < message.exemplars.length; ++i) { + var error = $root.opentelemetry.proto.metrics.v1.Exemplar.verify(message.exemplars[i]); + if (error) + return "exemplars." + error; + } + } + if (message.flags != null && message.hasOwnProperty("flags")) + if (!$util.isInteger(message.flags)) + return "flags: integer expected"; + if (message.min != null && message.hasOwnProperty("min")) { + properties._min = 1; + if (typeof message.min !== "number") + return "min: number expected"; + } + if (message.max != null && message.hasOwnProperty("max")) { + properties._max = 1; + if (typeof message.max !== "number") + return "max: number expected"; + } + return null; + }; + /** + * Creates a HistogramDataPoint message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.metrics.v1.HistogramDataPoint} HistogramDataPoint + */ + HistogramDataPoint.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.metrics.v1.HistogramDataPoint) + return object; + var message = new $root.opentelemetry.proto.metrics.v1.HistogramDataPoint(); + if (object.attributes) { + if (!Array.isArray(object.attributes)) + throw TypeError(".opentelemetry.proto.metrics.v1.HistogramDataPoint.attributes: array expected"); + message.attributes = []; + for (var i = 0; i < object.attributes.length; ++i) { + if (typeof object.attributes[i] !== "object") + throw TypeError(".opentelemetry.proto.metrics.v1.HistogramDataPoint.attributes: object expected"); + message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]); + } + } + if (object.startTimeUnixNano != null) + if ($util.Long) + (message.startTimeUnixNano = $util.Long.fromValue(object.startTimeUnixNano)).unsigned = false; + else if (typeof object.startTimeUnixNano === "string") + message.startTimeUnixNano = parseInt(object.startTimeUnixNano, 10); + else if (typeof object.startTimeUnixNano === "number") + message.startTimeUnixNano = object.startTimeUnixNano; + else if (typeof object.startTimeUnixNano === "object") + message.startTimeUnixNano = new $util.LongBits(object.startTimeUnixNano.low >>> 0, object.startTimeUnixNano.high >>> 0).toNumber(); + if (object.timeUnixNano != null) + if ($util.Long) + (message.timeUnixNano = $util.Long.fromValue(object.timeUnixNano)).unsigned = false; + else if (typeof object.timeUnixNano === "string") + message.timeUnixNano = parseInt(object.timeUnixNano, 10); + else if (typeof object.timeUnixNano === "number") + message.timeUnixNano = object.timeUnixNano; + else if (typeof object.timeUnixNano === "object") + message.timeUnixNano = new $util.LongBits(object.timeUnixNano.low >>> 0, object.timeUnixNano.high >>> 0).toNumber(); + if (object.count != null) + if ($util.Long) + (message.count = $util.Long.fromValue(object.count)).unsigned = false; + else if (typeof object.count === "string") + message.count = parseInt(object.count, 10); + else if (typeof object.count === "number") + message.count = object.count; + else if (typeof object.count === "object") + message.count = new $util.LongBits(object.count.low >>> 0, object.count.high >>> 0).toNumber(); + if (object.sum != null) + message.sum = Number(object.sum); + if (object.bucketCounts) { + if (!Array.isArray(object.bucketCounts)) + throw TypeError(".opentelemetry.proto.metrics.v1.HistogramDataPoint.bucketCounts: array expected"); + message.bucketCounts = []; + for (var i = 0; i < object.bucketCounts.length; ++i) + if ($util.Long) + (message.bucketCounts[i] = $util.Long.fromValue(object.bucketCounts[i])).unsigned = false; + else if (typeof object.bucketCounts[i] === "string") + message.bucketCounts[i] = parseInt(object.bucketCounts[i], 10); + else if (typeof object.bucketCounts[i] === "number") + message.bucketCounts[i] = object.bucketCounts[i]; + else if (typeof object.bucketCounts[i] === "object") + message.bucketCounts[i] = new $util.LongBits(object.bucketCounts[i].low >>> 0, object.bucketCounts[i].high >>> 0).toNumber(); + } + if (object.explicitBounds) { + if (!Array.isArray(object.explicitBounds)) + throw TypeError(".opentelemetry.proto.metrics.v1.HistogramDataPoint.explicitBounds: array expected"); + message.explicitBounds = []; + for (var i = 0; i < object.explicitBounds.length; ++i) + message.explicitBounds[i] = Number(object.explicitBounds[i]); + } + if (object.exemplars) { + if (!Array.isArray(object.exemplars)) + throw TypeError(".opentelemetry.proto.metrics.v1.HistogramDataPoint.exemplars: array expected"); + message.exemplars = []; + for (var i = 0; i < object.exemplars.length; ++i) { + if (typeof object.exemplars[i] !== "object") + throw TypeError(".opentelemetry.proto.metrics.v1.HistogramDataPoint.exemplars: object expected"); + message.exemplars[i] = $root.opentelemetry.proto.metrics.v1.Exemplar.fromObject(object.exemplars[i]); + } + } + if (object.flags != null) + message.flags = object.flags >>> 0; + if (object.min != null) + message.min = Number(object.min); + if (object.max != null) + message.max = Number(object.max); + return message; + }; + /** + * Creates a plain object from a HistogramDataPoint message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint + * @static + * @param {opentelemetry.proto.metrics.v1.HistogramDataPoint} message HistogramDataPoint + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + HistogramDataPoint.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.bucketCounts = []; + object.explicitBounds = []; + object.exemplars = []; + object.attributes = []; + } + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.startTimeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } + else + object.startTimeUnixNano = options.longs === String ? "0" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.timeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } + else + object.timeUnixNano = options.longs === String ? "0" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.count = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } + else + object.count = options.longs === String ? "0" : 0; + object.flags = 0; + } + if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano")) + if (typeof message.startTimeUnixNano === "number") + object.startTimeUnixNano = options.longs === String ? String(message.startTimeUnixNano) : message.startTimeUnixNano; + else + object.startTimeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.startTimeUnixNano) : options.longs === Number ? new $util.LongBits(message.startTimeUnixNano.low >>> 0, message.startTimeUnixNano.high >>> 0).toNumber() : message.startTimeUnixNano; + if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) + if (typeof message.timeUnixNano === "number") + object.timeUnixNano = options.longs === String ? String(message.timeUnixNano) : message.timeUnixNano; + else + object.timeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.timeUnixNano) : options.longs === Number ? new $util.LongBits(message.timeUnixNano.low >>> 0, message.timeUnixNano.high >>> 0).toNumber() : message.timeUnixNano; + if (message.count != null && message.hasOwnProperty("count")) + if (typeof message.count === "number") + object.count = options.longs === String ? String(message.count) : message.count; + else + object.count = options.longs === String ? $util.Long.prototype.toString.call(message.count) : options.longs === Number ? new $util.LongBits(message.count.low >>> 0, message.count.high >>> 0).toNumber() : message.count; + if (message.sum != null && message.hasOwnProperty("sum")) { + object.sum = options.json && !isFinite(message.sum) ? String(message.sum) : message.sum; + if (options.oneofs) + object._sum = "sum"; + } + if (message.bucketCounts && message.bucketCounts.length) { + object.bucketCounts = []; + for (var j = 0; j < message.bucketCounts.length; ++j) + if (typeof message.bucketCounts[j] === "number") + object.bucketCounts[j] = options.longs === String ? String(message.bucketCounts[j]) : message.bucketCounts[j]; + else + object.bucketCounts[j] = options.longs === String ? $util.Long.prototype.toString.call(message.bucketCounts[j]) : options.longs === Number ? new $util.LongBits(message.bucketCounts[j].low >>> 0, message.bucketCounts[j].high >>> 0).toNumber() : message.bucketCounts[j]; + } + if (message.explicitBounds && message.explicitBounds.length) { + object.explicitBounds = []; + for (var j = 0; j < message.explicitBounds.length; ++j) + object.explicitBounds[j] = options.json && !isFinite(message.explicitBounds[j]) ? String(message.explicitBounds[j]) : message.explicitBounds[j]; + } + if (message.exemplars && message.exemplars.length) { + object.exemplars = []; + for (var j = 0; j < message.exemplars.length; ++j) + object.exemplars[j] = $root.opentelemetry.proto.metrics.v1.Exemplar.toObject(message.exemplars[j], options); + } + if (message.attributes && message.attributes.length) { + object.attributes = []; + for (var j = 0; j < message.attributes.length; ++j) + object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options); + } + if (message.flags != null && message.hasOwnProperty("flags")) + object.flags = message.flags; + if (message.min != null && message.hasOwnProperty("min")) { + object.min = options.json && !isFinite(message.min) ? String(message.min) : message.min; + if (options.oneofs) + object._min = "min"; + } + if (message.max != null && message.hasOwnProperty("max")) { + object.max = options.json && !isFinite(message.max) ? String(message.max) : message.max; + if (options.oneofs) + object._max = "max"; + } + return object; + }; + /** + * Converts this HistogramDataPoint to JSON. + * @function toJSON + * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint + * @instance + * @returns {Object.} JSON object + */ + HistogramDataPoint.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for HistogramDataPoint + * @function getTypeUrl + * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + HistogramDataPoint.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.HistogramDataPoint"; + }; + return HistogramDataPoint; + })(); + v1.ExponentialHistogramDataPoint = (function () { + /** + * Properties of an ExponentialHistogramDataPoint. + * @memberof opentelemetry.proto.metrics.v1 + * @interface IExponentialHistogramDataPoint + * @property {Array.|null} [attributes] ExponentialHistogramDataPoint attributes + * @property {number|Long|null} [startTimeUnixNano] ExponentialHistogramDataPoint startTimeUnixNano + * @property {number|Long|null} [timeUnixNano] ExponentialHistogramDataPoint timeUnixNano + * @property {number|Long|null} [count] ExponentialHistogramDataPoint count + * @property {number|null} [sum] ExponentialHistogramDataPoint sum + * @property {number|null} [scale] ExponentialHistogramDataPoint scale + * @property {number|Long|null} [zeroCount] ExponentialHistogramDataPoint zeroCount + * @property {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.IBuckets|null} [positive] ExponentialHistogramDataPoint positive + * @property {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.IBuckets|null} [negative] ExponentialHistogramDataPoint negative + * @property {number|null} [flags] ExponentialHistogramDataPoint flags + * @property {Array.|null} [exemplars] ExponentialHistogramDataPoint exemplars + * @property {number|null} [min] ExponentialHistogramDataPoint min + * @property {number|null} [max] ExponentialHistogramDataPoint max + * @property {number|null} [zeroThreshold] ExponentialHistogramDataPoint zeroThreshold + */ + /** + * Constructs a new ExponentialHistogramDataPoint. + * @memberof opentelemetry.proto.metrics.v1 + * @classdesc Represents an ExponentialHistogramDataPoint. + * @implements IExponentialHistogramDataPoint + * @constructor + * @param {opentelemetry.proto.metrics.v1.IExponentialHistogramDataPoint=} [properties] Properties to set + */ + function ExponentialHistogramDataPoint(properties) { + this.attributes = []; + this.exemplars = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * ExponentialHistogramDataPoint attributes. + * @member {Array.} attributes + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint + * @instance + */ + ExponentialHistogramDataPoint.prototype.attributes = $util.emptyArray; + /** + * ExponentialHistogramDataPoint startTimeUnixNano. + * @member {number|Long|null|undefined} startTimeUnixNano + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint + * @instance + */ + ExponentialHistogramDataPoint.prototype.startTimeUnixNano = null; + /** + * ExponentialHistogramDataPoint timeUnixNano. + * @member {number|Long|null|undefined} timeUnixNano + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint + * @instance + */ + ExponentialHistogramDataPoint.prototype.timeUnixNano = null; + /** + * ExponentialHistogramDataPoint count. + * @member {number|Long|null|undefined} count + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint + * @instance + */ + ExponentialHistogramDataPoint.prototype.count = null; + /** + * ExponentialHistogramDataPoint sum. + * @member {number|null|undefined} sum + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint + * @instance + */ + ExponentialHistogramDataPoint.prototype.sum = null; + /** + * ExponentialHistogramDataPoint scale. + * @member {number|null|undefined} scale + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint + * @instance + */ + ExponentialHistogramDataPoint.prototype.scale = null; + /** + * ExponentialHistogramDataPoint zeroCount. + * @member {number|Long|null|undefined} zeroCount + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint + * @instance + */ + ExponentialHistogramDataPoint.prototype.zeroCount = null; + /** + * ExponentialHistogramDataPoint positive. + * @member {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.IBuckets|null|undefined} positive + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint + * @instance + */ + ExponentialHistogramDataPoint.prototype.positive = null; + /** + * ExponentialHistogramDataPoint negative. + * @member {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.IBuckets|null|undefined} negative + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint + * @instance + */ + ExponentialHistogramDataPoint.prototype.negative = null; + /** + * ExponentialHistogramDataPoint flags. + * @member {number|null|undefined} flags + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint + * @instance + */ + ExponentialHistogramDataPoint.prototype.flags = null; + /** + * ExponentialHistogramDataPoint exemplars. + * @member {Array.} exemplars + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint + * @instance + */ + ExponentialHistogramDataPoint.prototype.exemplars = $util.emptyArray; + /** + * ExponentialHistogramDataPoint min. + * @member {number|null|undefined} min + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint + * @instance + */ + ExponentialHistogramDataPoint.prototype.min = null; + /** + * ExponentialHistogramDataPoint max. + * @member {number|null|undefined} max + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint + * @instance + */ + ExponentialHistogramDataPoint.prototype.max = null; + /** + * ExponentialHistogramDataPoint zeroThreshold. + * @member {number|null|undefined} zeroThreshold + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint + * @instance + */ + ExponentialHistogramDataPoint.prototype.zeroThreshold = null; + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + /** + * ExponentialHistogramDataPoint _sum. + * @member {"sum"|undefined} _sum + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint + * @instance + */ + Object.defineProperty(ExponentialHistogramDataPoint.prototype, "_sum", { + get: $util.oneOfGetter($oneOfFields = ["sum"]), + set: $util.oneOfSetter($oneOfFields) + }); + /** + * ExponentialHistogramDataPoint _min. + * @member {"min"|undefined} _min + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint + * @instance + */ + Object.defineProperty(ExponentialHistogramDataPoint.prototype, "_min", { + get: $util.oneOfGetter($oneOfFields = ["min"]), + set: $util.oneOfSetter($oneOfFields) + }); + /** + * ExponentialHistogramDataPoint _max. + * @member {"max"|undefined} _max + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint + * @instance + */ + Object.defineProperty(ExponentialHistogramDataPoint.prototype, "_max", { + get: $util.oneOfGetter($oneOfFields = ["max"]), + set: $util.oneOfSetter($oneOfFields) + }); + /** + * Creates a new ExponentialHistogramDataPoint instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint + * @static + * @param {opentelemetry.proto.metrics.v1.IExponentialHistogramDataPoint=} [properties] Properties to set + * @returns {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint} ExponentialHistogramDataPoint instance + */ + ExponentialHistogramDataPoint.create = function create(properties) { + return new ExponentialHistogramDataPoint(properties); + }; + /** + * Encodes the specified ExponentialHistogramDataPoint message. Does not implicitly {@link opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint + * @static + * @param {opentelemetry.proto.metrics.v1.IExponentialHistogramDataPoint} message ExponentialHistogramDataPoint message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExponentialHistogramDataPoint.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.attributes != null && message.attributes.length) + for (var i = 0; i < message.attributes.length; ++i) + $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); + if (message.startTimeUnixNano != null && Object.hasOwnProperty.call(message, "startTimeUnixNano")) + writer.uint32(/* id 2, wireType 1 =*/ 17).fixed64(message.startTimeUnixNano); + if (message.timeUnixNano != null && Object.hasOwnProperty.call(message, "timeUnixNano")) + writer.uint32(/* id 3, wireType 1 =*/ 25).fixed64(message.timeUnixNano); + if (message.count != null && Object.hasOwnProperty.call(message, "count")) + writer.uint32(/* id 4, wireType 1 =*/ 33).fixed64(message.count); + if (message.sum != null && Object.hasOwnProperty.call(message, "sum")) + writer.uint32(/* id 5, wireType 1 =*/ 41).double(message.sum); + if (message.scale != null && Object.hasOwnProperty.call(message, "scale")) + writer.uint32(/* id 6, wireType 0 =*/ 48).sint32(message.scale); + if (message.zeroCount != null && Object.hasOwnProperty.call(message, "zeroCount")) + writer.uint32(/* id 7, wireType 1 =*/ 57).fixed64(message.zeroCount); + if (message.positive != null && Object.hasOwnProperty.call(message, "positive")) + $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.encode(message.positive, writer.uint32(/* id 8, wireType 2 =*/ 66).fork()).ldelim(); + if (message.negative != null && Object.hasOwnProperty.call(message, "negative")) + $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.encode(message.negative, writer.uint32(/* id 9, wireType 2 =*/ 74).fork()).ldelim(); + if (message.flags != null && Object.hasOwnProperty.call(message, "flags")) + writer.uint32(/* id 10, wireType 0 =*/ 80).uint32(message.flags); + if (message.exemplars != null && message.exemplars.length) + for (var i = 0; i < message.exemplars.length; ++i) + $root.opentelemetry.proto.metrics.v1.Exemplar.encode(message.exemplars[i], writer.uint32(/* id 11, wireType 2 =*/ 90).fork()).ldelim(); + if (message.min != null && Object.hasOwnProperty.call(message, "min")) + writer.uint32(/* id 12, wireType 1 =*/ 97).double(message.min); + if (message.max != null && Object.hasOwnProperty.call(message, "max")) + writer.uint32(/* id 13, wireType 1 =*/ 105).double(message.max); + if (message.zeroThreshold != null && Object.hasOwnProperty.call(message, "zeroThreshold")) + writer.uint32(/* id 14, wireType 1 =*/ 113).double(message.zeroThreshold); + return writer; + }; + /** + * Encodes the specified ExponentialHistogramDataPoint message, length delimited. Does not implicitly {@link opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint + * @static + * @param {opentelemetry.proto.metrics.v1.IExponentialHistogramDataPoint} message ExponentialHistogramDataPoint message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExponentialHistogramDataPoint.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes an ExponentialHistogramDataPoint message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint} ExponentialHistogramDataPoint + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExponentialHistogramDataPoint.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.attributes && message.attributes.length)) + message.attributes = []; + message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32())); + break; + } + case 2: { + message.startTimeUnixNano = reader.fixed64(); + break; + } + case 3: { + message.timeUnixNano = reader.fixed64(); + break; + } + case 4: { + message.count = reader.fixed64(); + break; + } + case 5: { + message.sum = reader.double(); + break; + } + case 6: { + message.scale = reader.sint32(); + break; + } + case 7: { + message.zeroCount = reader.fixed64(); + break; + } + case 8: { + message.positive = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.decode(reader, reader.uint32()); + break; + } + case 9: { + message.negative = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.decode(reader, reader.uint32()); + break; + } + case 10: { + message.flags = reader.uint32(); + break; + } + case 11: { + if (!(message.exemplars && message.exemplars.length)) + message.exemplars = []; + message.exemplars.push($root.opentelemetry.proto.metrics.v1.Exemplar.decode(reader, reader.uint32())); + break; + } + case 12: { + message.min = reader.double(); + break; + } + case 13: { + message.max = reader.double(); + break; + } + case 14: { + message.zeroThreshold = reader.double(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes an ExponentialHistogramDataPoint message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint} ExponentialHistogramDataPoint + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExponentialHistogramDataPoint.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies an ExponentialHistogramDataPoint message. + * @function verify + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ExponentialHistogramDataPoint.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.attributes != null && message.hasOwnProperty("attributes")) { + if (!Array.isArray(message.attributes)) + return "attributes: array expected"; + for (var i = 0; i < message.attributes.length; ++i) { + var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]); + if (error) + return "attributes." + error; + } + } + if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano")) + if (!$util.isInteger(message.startTimeUnixNano) && !(message.startTimeUnixNano && $util.isInteger(message.startTimeUnixNano.low) && $util.isInteger(message.startTimeUnixNano.high))) + return "startTimeUnixNano: integer|Long expected"; + if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) + if (!$util.isInteger(message.timeUnixNano) && !(message.timeUnixNano && $util.isInteger(message.timeUnixNano.low) && $util.isInteger(message.timeUnixNano.high))) + return "timeUnixNano: integer|Long expected"; + if (message.count != null && message.hasOwnProperty("count")) + if (!$util.isInteger(message.count) && !(message.count && $util.isInteger(message.count.low) && $util.isInteger(message.count.high))) + return "count: integer|Long expected"; + if (message.sum != null && message.hasOwnProperty("sum")) { + properties._sum = 1; + if (typeof message.sum !== "number") + return "sum: number expected"; + } + if (message.scale != null && message.hasOwnProperty("scale")) + if (!$util.isInteger(message.scale)) + return "scale: integer expected"; + if (message.zeroCount != null && message.hasOwnProperty("zeroCount")) + if (!$util.isInteger(message.zeroCount) && !(message.zeroCount && $util.isInteger(message.zeroCount.low) && $util.isInteger(message.zeroCount.high))) + return "zeroCount: integer|Long expected"; + if (message.positive != null && message.hasOwnProperty("positive")) { + var error = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.verify(message.positive); + if (error) + return "positive." + error; + } + if (message.negative != null && message.hasOwnProperty("negative")) { + var error = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.verify(message.negative); + if (error) + return "negative." + error; + } + if (message.flags != null && message.hasOwnProperty("flags")) + if (!$util.isInteger(message.flags)) + return "flags: integer expected"; + if (message.exemplars != null && message.hasOwnProperty("exemplars")) { + if (!Array.isArray(message.exemplars)) + return "exemplars: array expected"; + for (var i = 0; i < message.exemplars.length; ++i) { + var error = $root.opentelemetry.proto.metrics.v1.Exemplar.verify(message.exemplars[i]); + if (error) + return "exemplars." + error; + } + } + if (message.min != null && message.hasOwnProperty("min")) { + properties._min = 1; + if (typeof message.min !== "number") + return "min: number expected"; + } + if (message.max != null && message.hasOwnProperty("max")) { + properties._max = 1; + if (typeof message.max !== "number") + return "max: number expected"; + } + if (message.zeroThreshold != null && message.hasOwnProperty("zeroThreshold")) + if (typeof message.zeroThreshold !== "number") + return "zeroThreshold: number expected"; + return null; + }; + /** + * Creates an ExponentialHistogramDataPoint message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint} ExponentialHistogramDataPoint + */ + ExponentialHistogramDataPoint.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint) + return object; + var message = new $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint(); + if (object.attributes) { + if (!Array.isArray(object.attributes)) + throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.attributes: array expected"); + message.attributes = []; + for (var i = 0; i < object.attributes.length; ++i) { + if (typeof object.attributes[i] !== "object") + throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.attributes: object expected"); + message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]); + } + } + if (object.startTimeUnixNano != null) + if ($util.Long) + (message.startTimeUnixNano = $util.Long.fromValue(object.startTimeUnixNano)).unsigned = false; + else if (typeof object.startTimeUnixNano === "string") + message.startTimeUnixNano = parseInt(object.startTimeUnixNano, 10); + else if (typeof object.startTimeUnixNano === "number") + message.startTimeUnixNano = object.startTimeUnixNano; + else if (typeof object.startTimeUnixNano === "object") + message.startTimeUnixNano = new $util.LongBits(object.startTimeUnixNano.low >>> 0, object.startTimeUnixNano.high >>> 0).toNumber(); + if (object.timeUnixNano != null) + if ($util.Long) + (message.timeUnixNano = $util.Long.fromValue(object.timeUnixNano)).unsigned = false; + else if (typeof object.timeUnixNano === "string") + message.timeUnixNano = parseInt(object.timeUnixNano, 10); + else if (typeof object.timeUnixNano === "number") + message.timeUnixNano = object.timeUnixNano; + else if (typeof object.timeUnixNano === "object") + message.timeUnixNano = new $util.LongBits(object.timeUnixNano.low >>> 0, object.timeUnixNano.high >>> 0).toNumber(); + if (object.count != null) + if ($util.Long) + (message.count = $util.Long.fromValue(object.count)).unsigned = false; + else if (typeof object.count === "string") + message.count = parseInt(object.count, 10); + else if (typeof object.count === "number") + message.count = object.count; + else if (typeof object.count === "object") + message.count = new $util.LongBits(object.count.low >>> 0, object.count.high >>> 0).toNumber(); + if (object.sum != null) + message.sum = Number(object.sum); + if (object.scale != null) + message.scale = object.scale | 0; + if (object.zeroCount != null) + if ($util.Long) + (message.zeroCount = $util.Long.fromValue(object.zeroCount)).unsigned = false; + else if (typeof object.zeroCount === "string") + message.zeroCount = parseInt(object.zeroCount, 10); + else if (typeof object.zeroCount === "number") + message.zeroCount = object.zeroCount; + else if (typeof object.zeroCount === "object") + message.zeroCount = new $util.LongBits(object.zeroCount.low >>> 0, object.zeroCount.high >>> 0).toNumber(); + if (object.positive != null) { + if (typeof object.positive !== "object") + throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.positive: object expected"); + message.positive = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.fromObject(object.positive); + } + if (object.negative != null) { + if (typeof object.negative !== "object") + throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.negative: object expected"); + message.negative = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.fromObject(object.negative); + } + if (object.flags != null) + message.flags = object.flags >>> 0; + if (object.exemplars) { + if (!Array.isArray(object.exemplars)) + throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.exemplars: array expected"); + message.exemplars = []; + for (var i = 0; i < object.exemplars.length; ++i) { + if (typeof object.exemplars[i] !== "object") + throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.exemplars: object expected"); + message.exemplars[i] = $root.opentelemetry.proto.metrics.v1.Exemplar.fromObject(object.exemplars[i]); + } + } + if (object.min != null) + message.min = Number(object.min); + if (object.max != null) + message.max = Number(object.max); + if (object.zeroThreshold != null) + message.zeroThreshold = Number(object.zeroThreshold); + return message; + }; + /** + * Creates a plain object from an ExponentialHistogramDataPoint message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint + * @static + * @param {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint} message ExponentialHistogramDataPoint + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExponentialHistogramDataPoint.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.attributes = []; + object.exemplars = []; + } + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.startTimeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } + else + object.startTimeUnixNano = options.longs === String ? "0" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.timeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } + else + object.timeUnixNano = options.longs === String ? "0" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.count = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } + else + object.count = options.longs === String ? "0" : 0; + object.scale = 0; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.zeroCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } + else + object.zeroCount = options.longs === String ? "0" : 0; + object.positive = null; + object.negative = null; + object.flags = 0; + object.zeroThreshold = 0; + } + if (message.attributes && message.attributes.length) { + object.attributes = []; + for (var j = 0; j < message.attributes.length; ++j) + object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options); + } + if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano")) + if (typeof message.startTimeUnixNano === "number") + object.startTimeUnixNano = options.longs === String ? String(message.startTimeUnixNano) : message.startTimeUnixNano; + else + object.startTimeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.startTimeUnixNano) : options.longs === Number ? new $util.LongBits(message.startTimeUnixNano.low >>> 0, message.startTimeUnixNano.high >>> 0).toNumber() : message.startTimeUnixNano; + if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) + if (typeof message.timeUnixNano === "number") + object.timeUnixNano = options.longs === String ? String(message.timeUnixNano) : message.timeUnixNano; + else + object.timeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.timeUnixNano) : options.longs === Number ? new $util.LongBits(message.timeUnixNano.low >>> 0, message.timeUnixNano.high >>> 0).toNumber() : message.timeUnixNano; + if (message.count != null && message.hasOwnProperty("count")) + if (typeof message.count === "number") + object.count = options.longs === String ? String(message.count) : message.count; + else + object.count = options.longs === String ? $util.Long.prototype.toString.call(message.count) : options.longs === Number ? new $util.LongBits(message.count.low >>> 0, message.count.high >>> 0).toNumber() : message.count; + if (message.sum != null && message.hasOwnProperty("sum")) { + object.sum = options.json && !isFinite(message.sum) ? String(message.sum) : message.sum; + if (options.oneofs) + object._sum = "sum"; + } + if (message.scale != null && message.hasOwnProperty("scale")) + object.scale = message.scale; + if (message.zeroCount != null && message.hasOwnProperty("zeroCount")) + if (typeof message.zeroCount === "number") + object.zeroCount = options.longs === String ? String(message.zeroCount) : message.zeroCount; + else + object.zeroCount = options.longs === String ? $util.Long.prototype.toString.call(message.zeroCount) : options.longs === Number ? new $util.LongBits(message.zeroCount.low >>> 0, message.zeroCount.high >>> 0).toNumber() : message.zeroCount; + if (message.positive != null && message.hasOwnProperty("positive")) + object.positive = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.toObject(message.positive, options); + if (message.negative != null && message.hasOwnProperty("negative")) + object.negative = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.toObject(message.negative, options); + if (message.flags != null && message.hasOwnProperty("flags")) + object.flags = message.flags; + if (message.exemplars && message.exemplars.length) { + object.exemplars = []; + for (var j = 0; j < message.exemplars.length; ++j) + object.exemplars[j] = $root.opentelemetry.proto.metrics.v1.Exemplar.toObject(message.exemplars[j], options); + } + if (message.min != null && message.hasOwnProperty("min")) { + object.min = options.json && !isFinite(message.min) ? String(message.min) : message.min; + if (options.oneofs) + object._min = "min"; + } + if (message.max != null && message.hasOwnProperty("max")) { + object.max = options.json && !isFinite(message.max) ? String(message.max) : message.max; + if (options.oneofs) + object._max = "max"; + } + if (message.zeroThreshold != null && message.hasOwnProperty("zeroThreshold")) + object.zeroThreshold = options.json && !isFinite(message.zeroThreshold) ? String(message.zeroThreshold) : message.zeroThreshold; + return object; + }; + /** + * Converts this ExponentialHistogramDataPoint to JSON. + * @function toJSON + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint + * @instance + * @returns {Object.} JSON object + */ + ExponentialHistogramDataPoint.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for ExponentialHistogramDataPoint + * @function getTypeUrl + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExponentialHistogramDataPoint.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint"; + }; + ExponentialHistogramDataPoint.Buckets = (function () { + /** + * Properties of a Buckets. + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint + * @interface IBuckets + * @property {number|null} [offset] Buckets offset + * @property {Array.|null} [bucketCounts] Buckets bucketCounts + */ + /** + * Constructs a new Buckets. + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint + * @classdesc Represents a Buckets. + * @implements IBuckets + * @constructor + * @param {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.IBuckets=} [properties] Properties to set + */ + function Buckets(properties) { + this.bucketCounts = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * Buckets offset. + * @member {number|null|undefined} offset + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets + * @instance + */ + Buckets.prototype.offset = null; + /** + * Buckets bucketCounts. + * @member {Array.} bucketCounts + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets + * @instance + */ + Buckets.prototype.bucketCounts = $util.emptyArray; + /** + * Creates a new Buckets instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets + * @static + * @param {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.IBuckets=} [properties] Properties to set + * @returns {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets} Buckets instance + */ + Buckets.create = function create(properties) { + return new Buckets(properties); + }; + /** + * Encodes the specified Buckets message. Does not implicitly {@link opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets + * @static + * @param {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.IBuckets} message Buckets message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Buckets.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.offset != null && Object.hasOwnProperty.call(message, "offset")) + writer.uint32(/* id 1, wireType 0 =*/ 8).sint32(message.offset); + if (message.bucketCounts != null && message.bucketCounts.length) { + writer.uint32(/* id 2, wireType 2 =*/ 18).fork(); + for (var i = 0; i < message.bucketCounts.length; ++i) + writer.uint64(message.bucketCounts[i]); + writer.ldelim(); + } + return writer; + }; + /** + * Encodes the specified Buckets message, length delimited. Does not implicitly {@link opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets + * @static + * @param {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.IBuckets} message Buckets message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Buckets.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes a Buckets message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets} Buckets + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Buckets.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.offset = reader.sint32(); + break; + } + case 2: { + if (!(message.bucketCounts && message.bucketCounts.length)) + message.bucketCounts = []; + if ((tag & 7) === 2) { + var end2 = reader.uint32() + reader.pos; + while (reader.pos < end2) + message.bucketCounts.push(reader.uint64()); + } + else + message.bucketCounts.push(reader.uint64()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes a Buckets message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets} Buckets + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Buckets.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies a Buckets message. + * @function verify + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Buckets.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.offset != null && message.hasOwnProperty("offset")) + if (!$util.isInteger(message.offset)) + return "offset: integer expected"; + if (message.bucketCounts != null && message.hasOwnProperty("bucketCounts")) { + if (!Array.isArray(message.bucketCounts)) + return "bucketCounts: array expected"; + for (var i = 0; i < message.bucketCounts.length; ++i) + if (!$util.isInteger(message.bucketCounts[i]) && !(message.bucketCounts[i] && $util.isInteger(message.bucketCounts[i].low) && $util.isInteger(message.bucketCounts[i].high))) + return "bucketCounts: integer|Long[] expected"; + } + return null; + }; + /** + * Creates a Buckets message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets} Buckets + */ + Buckets.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets) + return object; + var message = new $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets(); + if (object.offset != null) + message.offset = object.offset | 0; + if (object.bucketCounts) { + if (!Array.isArray(object.bucketCounts)) + throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.bucketCounts: array expected"); + message.bucketCounts = []; + for (var i = 0; i < object.bucketCounts.length; ++i) + if ($util.Long) + (message.bucketCounts[i] = $util.Long.fromValue(object.bucketCounts[i])).unsigned = true; + else if (typeof object.bucketCounts[i] === "string") + message.bucketCounts[i] = parseInt(object.bucketCounts[i], 10); + else if (typeof object.bucketCounts[i] === "number") + message.bucketCounts[i] = object.bucketCounts[i]; + else if (typeof object.bucketCounts[i] === "object") + message.bucketCounts[i] = new $util.LongBits(object.bucketCounts[i].low >>> 0, object.bucketCounts[i].high >>> 0).toNumber(true); + } + return message; + }; + /** + * Creates a plain object from a Buckets message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets + * @static + * @param {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets} message Buckets + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Buckets.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.bucketCounts = []; + if (options.defaults) + object.offset = 0; + if (message.offset != null && message.hasOwnProperty("offset")) + object.offset = message.offset; + if (message.bucketCounts && message.bucketCounts.length) { + object.bucketCounts = []; + for (var j = 0; j < message.bucketCounts.length; ++j) + if (typeof message.bucketCounts[j] === "number") + object.bucketCounts[j] = options.longs === String ? String(message.bucketCounts[j]) : message.bucketCounts[j]; + else + object.bucketCounts[j] = options.longs === String ? $util.Long.prototype.toString.call(message.bucketCounts[j]) : options.longs === Number ? new $util.LongBits(message.bucketCounts[j].low >>> 0, message.bucketCounts[j].high >>> 0).toNumber(true) : message.bucketCounts[j]; + } + return object; + }; + /** + * Converts this Buckets to JSON. + * @function toJSON + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets + * @instance + * @returns {Object.} JSON object + */ + Buckets.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for Buckets + * @function getTypeUrl + * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Buckets.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets"; + }; + return Buckets; + })(); + return ExponentialHistogramDataPoint; + })(); + v1.SummaryDataPoint = (function () { + /** + * Properties of a SummaryDataPoint. + * @memberof opentelemetry.proto.metrics.v1 + * @interface ISummaryDataPoint + * @property {Array.|null} [attributes] SummaryDataPoint attributes + * @property {number|Long|null} [startTimeUnixNano] SummaryDataPoint startTimeUnixNano + * @property {number|Long|null} [timeUnixNano] SummaryDataPoint timeUnixNano + * @property {number|Long|null} [count] SummaryDataPoint count + * @property {number|null} [sum] SummaryDataPoint sum + * @property {Array.|null} [quantileValues] SummaryDataPoint quantileValues + * @property {number|null} [flags] SummaryDataPoint flags + */ + /** + * Constructs a new SummaryDataPoint. + * @memberof opentelemetry.proto.metrics.v1 + * @classdesc Represents a SummaryDataPoint. + * @implements ISummaryDataPoint + * @constructor + * @param {opentelemetry.proto.metrics.v1.ISummaryDataPoint=} [properties] Properties to set + */ + function SummaryDataPoint(properties) { + this.attributes = []; + this.quantileValues = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * SummaryDataPoint attributes. + * @member {Array.} attributes + * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint + * @instance + */ + SummaryDataPoint.prototype.attributes = $util.emptyArray; + /** + * SummaryDataPoint startTimeUnixNano. + * @member {number|Long|null|undefined} startTimeUnixNano + * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint + * @instance + */ + SummaryDataPoint.prototype.startTimeUnixNano = null; + /** + * SummaryDataPoint timeUnixNano. + * @member {number|Long|null|undefined} timeUnixNano + * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint + * @instance + */ + SummaryDataPoint.prototype.timeUnixNano = null; + /** + * SummaryDataPoint count. + * @member {number|Long|null|undefined} count + * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint + * @instance + */ + SummaryDataPoint.prototype.count = null; + /** + * SummaryDataPoint sum. + * @member {number|null|undefined} sum + * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint + * @instance + */ + SummaryDataPoint.prototype.sum = null; + /** + * SummaryDataPoint quantileValues. + * @member {Array.} quantileValues + * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint + * @instance + */ + SummaryDataPoint.prototype.quantileValues = $util.emptyArray; + /** + * SummaryDataPoint flags. + * @member {number|null|undefined} flags + * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint + * @instance + */ + SummaryDataPoint.prototype.flags = null; + /** + * Creates a new SummaryDataPoint instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint + * @static + * @param {opentelemetry.proto.metrics.v1.ISummaryDataPoint=} [properties] Properties to set + * @returns {opentelemetry.proto.metrics.v1.SummaryDataPoint} SummaryDataPoint instance + */ + SummaryDataPoint.create = function create(properties) { + return new SummaryDataPoint(properties); + }; + /** + * Encodes the specified SummaryDataPoint message. Does not implicitly {@link opentelemetry.proto.metrics.v1.SummaryDataPoint.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint + * @static + * @param {opentelemetry.proto.metrics.v1.ISummaryDataPoint} message SummaryDataPoint message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SummaryDataPoint.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.startTimeUnixNano != null && Object.hasOwnProperty.call(message, "startTimeUnixNano")) + writer.uint32(/* id 2, wireType 1 =*/ 17).fixed64(message.startTimeUnixNano); + if (message.timeUnixNano != null && Object.hasOwnProperty.call(message, "timeUnixNano")) + writer.uint32(/* id 3, wireType 1 =*/ 25).fixed64(message.timeUnixNano); + if (message.count != null && Object.hasOwnProperty.call(message, "count")) + writer.uint32(/* id 4, wireType 1 =*/ 33).fixed64(message.count); + if (message.sum != null && Object.hasOwnProperty.call(message, "sum")) + writer.uint32(/* id 5, wireType 1 =*/ 41).double(message.sum); + if (message.quantileValues != null && message.quantileValues.length) + for (var i = 0; i < message.quantileValues.length; ++i) + $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.encode(message.quantileValues[i], writer.uint32(/* id 6, wireType 2 =*/ 50).fork()).ldelim(); + if (message.attributes != null && message.attributes.length) + for (var i = 0; i < message.attributes.length; ++i) + $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(/* id 7, wireType 2 =*/ 58).fork()).ldelim(); + if (message.flags != null && Object.hasOwnProperty.call(message, "flags")) + writer.uint32(/* id 8, wireType 0 =*/ 64).uint32(message.flags); + return writer; + }; + /** + * Encodes the specified SummaryDataPoint message, length delimited. Does not implicitly {@link opentelemetry.proto.metrics.v1.SummaryDataPoint.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint + * @static + * @param {opentelemetry.proto.metrics.v1.ISummaryDataPoint} message SummaryDataPoint message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SummaryDataPoint.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes a SummaryDataPoint message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.metrics.v1.SummaryDataPoint} SummaryDataPoint + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SummaryDataPoint.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.SummaryDataPoint(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 7: { + if (!(message.attributes && message.attributes.length)) + message.attributes = []; + message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32())); + break; + } + case 2: { + message.startTimeUnixNano = reader.fixed64(); + break; + } + case 3: { + message.timeUnixNano = reader.fixed64(); + break; + } + case 4: { + message.count = reader.fixed64(); + break; + } + case 5: { + message.sum = reader.double(); + break; + } + case 6: { + if (!(message.quantileValues && message.quantileValues.length)) + message.quantileValues = []; + message.quantileValues.push($root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.decode(reader, reader.uint32())); + break; + } + case 8: { + message.flags = reader.uint32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes a SummaryDataPoint message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.metrics.v1.SummaryDataPoint} SummaryDataPoint + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SummaryDataPoint.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies a SummaryDataPoint message. + * @function verify + * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + SummaryDataPoint.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.attributes != null && message.hasOwnProperty("attributes")) { + if (!Array.isArray(message.attributes)) + return "attributes: array expected"; + for (var i = 0; i < message.attributes.length; ++i) { + var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]); + if (error) + return "attributes." + error; + } + } + if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano")) + if (!$util.isInteger(message.startTimeUnixNano) && !(message.startTimeUnixNano && $util.isInteger(message.startTimeUnixNano.low) && $util.isInteger(message.startTimeUnixNano.high))) + return "startTimeUnixNano: integer|Long expected"; + if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) + if (!$util.isInteger(message.timeUnixNano) && !(message.timeUnixNano && $util.isInteger(message.timeUnixNano.low) && $util.isInteger(message.timeUnixNano.high))) + return "timeUnixNano: integer|Long expected"; + if (message.count != null && message.hasOwnProperty("count")) + if (!$util.isInteger(message.count) && !(message.count && $util.isInteger(message.count.low) && $util.isInteger(message.count.high))) + return "count: integer|Long expected"; + if (message.sum != null && message.hasOwnProperty("sum")) + if (typeof message.sum !== "number") + return "sum: number expected"; + if (message.quantileValues != null && message.hasOwnProperty("quantileValues")) { + if (!Array.isArray(message.quantileValues)) + return "quantileValues: array expected"; + for (var i = 0; i < message.quantileValues.length; ++i) { + var error = $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.verify(message.quantileValues[i]); + if (error) + return "quantileValues." + error; + } + } + if (message.flags != null && message.hasOwnProperty("flags")) + if (!$util.isInteger(message.flags)) + return "flags: integer expected"; + return null; + }; + /** + * Creates a SummaryDataPoint message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.metrics.v1.SummaryDataPoint} SummaryDataPoint + */ + SummaryDataPoint.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.metrics.v1.SummaryDataPoint) + return object; + var message = new $root.opentelemetry.proto.metrics.v1.SummaryDataPoint(); + if (object.attributes) { + if (!Array.isArray(object.attributes)) + throw TypeError(".opentelemetry.proto.metrics.v1.SummaryDataPoint.attributes: array expected"); + message.attributes = []; + for (var i = 0; i < object.attributes.length; ++i) { + if (typeof object.attributes[i] !== "object") + throw TypeError(".opentelemetry.proto.metrics.v1.SummaryDataPoint.attributes: object expected"); + message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]); + } + } + if (object.startTimeUnixNano != null) + if ($util.Long) + (message.startTimeUnixNano = $util.Long.fromValue(object.startTimeUnixNano)).unsigned = false; + else if (typeof object.startTimeUnixNano === "string") + message.startTimeUnixNano = parseInt(object.startTimeUnixNano, 10); + else if (typeof object.startTimeUnixNano === "number") + message.startTimeUnixNano = object.startTimeUnixNano; + else if (typeof object.startTimeUnixNano === "object") + message.startTimeUnixNano = new $util.LongBits(object.startTimeUnixNano.low >>> 0, object.startTimeUnixNano.high >>> 0).toNumber(); + if (object.timeUnixNano != null) + if ($util.Long) + (message.timeUnixNano = $util.Long.fromValue(object.timeUnixNano)).unsigned = false; + else if (typeof object.timeUnixNano === "string") + message.timeUnixNano = parseInt(object.timeUnixNano, 10); + else if (typeof object.timeUnixNano === "number") + message.timeUnixNano = object.timeUnixNano; + else if (typeof object.timeUnixNano === "object") + message.timeUnixNano = new $util.LongBits(object.timeUnixNano.low >>> 0, object.timeUnixNano.high >>> 0).toNumber(); + if (object.count != null) + if ($util.Long) + (message.count = $util.Long.fromValue(object.count)).unsigned = false; + else if (typeof object.count === "string") + message.count = parseInt(object.count, 10); + else if (typeof object.count === "number") + message.count = object.count; + else if (typeof object.count === "object") + message.count = new $util.LongBits(object.count.low >>> 0, object.count.high >>> 0).toNumber(); + if (object.sum != null) + message.sum = Number(object.sum); + if (object.quantileValues) { + if (!Array.isArray(object.quantileValues)) + throw TypeError(".opentelemetry.proto.metrics.v1.SummaryDataPoint.quantileValues: array expected"); + message.quantileValues = []; + for (var i = 0; i < object.quantileValues.length; ++i) { + if (typeof object.quantileValues[i] !== "object") + throw TypeError(".opentelemetry.proto.metrics.v1.SummaryDataPoint.quantileValues: object expected"); + message.quantileValues[i] = $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.fromObject(object.quantileValues[i]); + } + } + if (object.flags != null) + message.flags = object.flags >>> 0; + return message; + }; + /** + * Creates a plain object from a SummaryDataPoint message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint + * @static + * @param {opentelemetry.proto.metrics.v1.SummaryDataPoint} message SummaryDataPoint + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + SummaryDataPoint.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.quantileValues = []; + object.attributes = []; + } + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.startTimeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } + else + object.startTimeUnixNano = options.longs === String ? "0" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.timeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } + else + object.timeUnixNano = options.longs === String ? "0" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.count = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } + else + object.count = options.longs === String ? "0" : 0; + object.sum = 0; + object.flags = 0; + } + if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano")) + if (typeof message.startTimeUnixNano === "number") + object.startTimeUnixNano = options.longs === String ? String(message.startTimeUnixNano) : message.startTimeUnixNano; + else + object.startTimeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.startTimeUnixNano) : options.longs === Number ? new $util.LongBits(message.startTimeUnixNano.low >>> 0, message.startTimeUnixNano.high >>> 0).toNumber() : message.startTimeUnixNano; + if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) + if (typeof message.timeUnixNano === "number") + object.timeUnixNano = options.longs === String ? String(message.timeUnixNano) : message.timeUnixNano; + else + object.timeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.timeUnixNano) : options.longs === Number ? new $util.LongBits(message.timeUnixNano.low >>> 0, message.timeUnixNano.high >>> 0).toNumber() : message.timeUnixNano; + if (message.count != null && message.hasOwnProperty("count")) + if (typeof message.count === "number") + object.count = options.longs === String ? String(message.count) : message.count; + else + object.count = options.longs === String ? $util.Long.prototype.toString.call(message.count) : options.longs === Number ? new $util.LongBits(message.count.low >>> 0, message.count.high >>> 0).toNumber() : message.count; + if (message.sum != null && message.hasOwnProperty("sum")) + object.sum = options.json && !isFinite(message.sum) ? String(message.sum) : message.sum; + if (message.quantileValues && message.quantileValues.length) { + object.quantileValues = []; + for (var j = 0; j < message.quantileValues.length; ++j) + object.quantileValues[j] = $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.toObject(message.quantileValues[j], options); + } + if (message.attributes && message.attributes.length) { + object.attributes = []; + for (var j = 0; j < message.attributes.length; ++j) + object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options); + } + if (message.flags != null && message.hasOwnProperty("flags")) + object.flags = message.flags; + return object; + }; + /** + * Converts this SummaryDataPoint to JSON. + * @function toJSON + * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint + * @instance + * @returns {Object.} JSON object + */ + SummaryDataPoint.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for SummaryDataPoint + * @function getTypeUrl + * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + SummaryDataPoint.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.SummaryDataPoint"; + }; + SummaryDataPoint.ValueAtQuantile = (function () { + /** + * Properties of a ValueAtQuantile. + * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint + * @interface IValueAtQuantile + * @property {number|null} [quantile] ValueAtQuantile quantile + * @property {number|null} [value] ValueAtQuantile value + */ + /** + * Constructs a new ValueAtQuantile. + * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint + * @classdesc Represents a ValueAtQuantile. + * @implements IValueAtQuantile + * @constructor + * @param {opentelemetry.proto.metrics.v1.SummaryDataPoint.IValueAtQuantile=} [properties] Properties to set + */ + function ValueAtQuantile(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * ValueAtQuantile quantile. + * @member {number|null|undefined} quantile + * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile + * @instance + */ + ValueAtQuantile.prototype.quantile = null; + /** + * ValueAtQuantile value. + * @member {number|null|undefined} value + * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile + * @instance + */ + ValueAtQuantile.prototype.value = null; + /** + * Creates a new ValueAtQuantile instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile + * @static + * @param {opentelemetry.proto.metrics.v1.SummaryDataPoint.IValueAtQuantile=} [properties] Properties to set + * @returns {opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile} ValueAtQuantile instance + */ + ValueAtQuantile.create = function create(properties) { + return new ValueAtQuantile(properties); + }; + /** + * Encodes the specified ValueAtQuantile message. Does not implicitly {@link opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile + * @static + * @param {opentelemetry.proto.metrics.v1.SummaryDataPoint.IValueAtQuantile} message ValueAtQuantile message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ValueAtQuantile.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.quantile != null && Object.hasOwnProperty.call(message, "quantile")) + writer.uint32(/* id 1, wireType 1 =*/ 9).double(message.quantile); + if (message.value != null && Object.hasOwnProperty.call(message, "value")) + writer.uint32(/* id 2, wireType 1 =*/ 17).double(message.value); + return writer; + }; + /** + * Encodes the specified ValueAtQuantile message, length delimited. Does not implicitly {@link opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile + * @static + * @param {opentelemetry.proto.metrics.v1.SummaryDataPoint.IValueAtQuantile} message ValueAtQuantile message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ValueAtQuantile.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes a ValueAtQuantile message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile} ValueAtQuantile + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ValueAtQuantile.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.quantile = reader.double(); + break; + } + case 2: { + message.value = reader.double(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes a ValueAtQuantile message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile} ValueAtQuantile + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ValueAtQuantile.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies a ValueAtQuantile message. + * @function verify + * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ValueAtQuantile.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.quantile != null && message.hasOwnProperty("quantile")) + if (typeof message.quantile !== "number") + return "quantile: number expected"; + if (message.value != null && message.hasOwnProperty("value")) + if (typeof message.value !== "number") + return "value: number expected"; + return null; + }; + /** + * Creates a ValueAtQuantile message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile} ValueAtQuantile + */ + ValueAtQuantile.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile) + return object; + var message = new $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile(); + if (object.quantile != null) + message.quantile = Number(object.quantile); + if (object.value != null) + message.value = Number(object.value); + return message; + }; + /** + * Creates a plain object from a ValueAtQuantile message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile + * @static + * @param {opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile} message ValueAtQuantile + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ValueAtQuantile.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.quantile = 0; + object.value = 0; + } + if (message.quantile != null && message.hasOwnProperty("quantile")) + object.quantile = options.json && !isFinite(message.quantile) ? String(message.quantile) : message.quantile; + if (message.value != null && message.hasOwnProperty("value")) + object.value = options.json && !isFinite(message.value) ? String(message.value) : message.value; + return object; + }; + /** + * Converts this ValueAtQuantile to JSON. + * @function toJSON + * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile + * @instance + * @returns {Object.} JSON object + */ + ValueAtQuantile.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for ValueAtQuantile + * @function getTypeUrl + * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ValueAtQuantile.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile"; + }; + return ValueAtQuantile; + })(); + return SummaryDataPoint; + })(); + v1.Exemplar = (function () { + /** + * Properties of an Exemplar. + * @memberof opentelemetry.proto.metrics.v1 + * @interface IExemplar + * @property {Array.|null} [filteredAttributes] Exemplar filteredAttributes + * @property {number|Long|null} [timeUnixNano] Exemplar timeUnixNano + * @property {number|null} [asDouble] Exemplar asDouble + * @property {number|Long|null} [asInt] Exemplar asInt + * @property {Uint8Array|null} [spanId] Exemplar spanId + * @property {Uint8Array|null} [traceId] Exemplar traceId + */ + /** + * Constructs a new Exemplar. + * @memberof opentelemetry.proto.metrics.v1 + * @classdesc Represents an Exemplar. + * @implements IExemplar + * @constructor + * @param {opentelemetry.proto.metrics.v1.IExemplar=} [properties] Properties to set + */ + function Exemplar(properties) { + this.filteredAttributes = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * Exemplar filteredAttributes. + * @member {Array.} filteredAttributes + * @memberof opentelemetry.proto.metrics.v1.Exemplar + * @instance + */ + Exemplar.prototype.filteredAttributes = $util.emptyArray; + /** + * Exemplar timeUnixNano. + * @member {number|Long|null|undefined} timeUnixNano + * @memberof opentelemetry.proto.metrics.v1.Exemplar + * @instance + */ + Exemplar.prototype.timeUnixNano = null; + /** + * Exemplar asDouble. + * @member {number|null|undefined} asDouble + * @memberof opentelemetry.proto.metrics.v1.Exemplar + * @instance + */ + Exemplar.prototype.asDouble = null; + /** + * Exemplar asInt. + * @member {number|Long|null|undefined} asInt + * @memberof opentelemetry.proto.metrics.v1.Exemplar + * @instance + */ + Exemplar.prototype.asInt = null; + /** + * Exemplar spanId. + * @member {Uint8Array|null|undefined} spanId + * @memberof opentelemetry.proto.metrics.v1.Exemplar + * @instance + */ + Exemplar.prototype.spanId = null; + /** + * Exemplar traceId. + * @member {Uint8Array|null|undefined} traceId + * @memberof opentelemetry.proto.metrics.v1.Exemplar + * @instance + */ + Exemplar.prototype.traceId = null; + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + /** + * Exemplar value. + * @member {"asDouble"|"asInt"|undefined} value + * @memberof opentelemetry.proto.metrics.v1.Exemplar + * @instance + */ + Object.defineProperty(Exemplar.prototype, "value", { + get: $util.oneOfGetter($oneOfFields = ["asDouble", "asInt"]), + set: $util.oneOfSetter($oneOfFields) + }); + /** + * Creates a new Exemplar instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.metrics.v1.Exemplar + * @static + * @param {opentelemetry.proto.metrics.v1.IExemplar=} [properties] Properties to set + * @returns {opentelemetry.proto.metrics.v1.Exemplar} Exemplar instance + */ + Exemplar.create = function create(properties) { + return new Exemplar(properties); + }; + /** + * Encodes the specified Exemplar message. Does not implicitly {@link opentelemetry.proto.metrics.v1.Exemplar.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.metrics.v1.Exemplar + * @static + * @param {opentelemetry.proto.metrics.v1.IExemplar} message Exemplar message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Exemplar.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.timeUnixNano != null && Object.hasOwnProperty.call(message, "timeUnixNano")) + writer.uint32(/* id 2, wireType 1 =*/ 17).fixed64(message.timeUnixNano); + if (message.asDouble != null && Object.hasOwnProperty.call(message, "asDouble")) + writer.uint32(/* id 3, wireType 1 =*/ 25).double(message.asDouble); + if (message.spanId != null && Object.hasOwnProperty.call(message, "spanId")) + writer.uint32(/* id 4, wireType 2 =*/ 34).bytes(message.spanId); + if (message.traceId != null && Object.hasOwnProperty.call(message, "traceId")) + writer.uint32(/* id 5, wireType 2 =*/ 42).bytes(message.traceId); + if (message.asInt != null && Object.hasOwnProperty.call(message, "asInt")) + writer.uint32(/* id 6, wireType 1 =*/ 49).sfixed64(message.asInt); + if (message.filteredAttributes != null && message.filteredAttributes.length) + for (var i = 0; i < message.filteredAttributes.length; ++i) + $root.opentelemetry.proto.common.v1.KeyValue.encode(message.filteredAttributes[i], writer.uint32(/* id 7, wireType 2 =*/ 58).fork()).ldelim(); + return writer; + }; + /** + * Encodes the specified Exemplar message, length delimited. Does not implicitly {@link opentelemetry.proto.metrics.v1.Exemplar.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.metrics.v1.Exemplar + * @static + * @param {opentelemetry.proto.metrics.v1.IExemplar} message Exemplar message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Exemplar.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes an Exemplar message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.metrics.v1.Exemplar + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.metrics.v1.Exemplar} Exemplar + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Exemplar.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.Exemplar(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 7: { + if (!(message.filteredAttributes && message.filteredAttributes.length)) + message.filteredAttributes = []; + message.filteredAttributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32())); + break; + } + case 2: { + message.timeUnixNano = reader.fixed64(); + break; + } + case 3: { + message.asDouble = reader.double(); + break; + } + case 6: { + message.asInt = reader.sfixed64(); + break; + } + case 4: { + message.spanId = reader.bytes(); + break; + } + case 5: { + message.traceId = reader.bytes(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes an Exemplar message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.metrics.v1.Exemplar + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.metrics.v1.Exemplar} Exemplar + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Exemplar.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies an Exemplar message. + * @function verify + * @memberof opentelemetry.proto.metrics.v1.Exemplar + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Exemplar.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.filteredAttributes != null && message.hasOwnProperty("filteredAttributes")) { + if (!Array.isArray(message.filteredAttributes)) + return "filteredAttributes: array expected"; + for (var i = 0; i < message.filteredAttributes.length; ++i) { + var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.filteredAttributes[i]); + if (error) + return "filteredAttributes." + error; + } + } + if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) + if (!$util.isInteger(message.timeUnixNano) && !(message.timeUnixNano && $util.isInteger(message.timeUnixNano.low) && $util.isInteger(message.timeUnixNano.high))) + return "timeUnixNano: integer|Long expected"; + if (message.asDouble != null && message.hasOwnProperty("asDouble")) { + properties.value = 1; + if (typeof message.asDouble !== "number") + return "asDouble: number expected"; + } + if (message.asInt != null && message.hasOwnProperty("asInt")) { + if (properties.value === 1) + return "value: multiple values"; + properties.value = 1; + if (!$util.isInteger(message.asInt) && !(message.asInt && $util.isInteger(message.asInt.low) && $util.isInteger(message.asInt.high))) + return "asInt: integer|Long expected"; + } + if (message.spanId != null && message.hasOwnProperty("spanId")) + if (!(message.spanId && typeof message.spanId.length === "number" || $util.isString(message.spanId))) + return "spanId: buffer expected"; + if (message.traceId != null && message.hasOwnProperty("traceId")) + if (!(message.traceId && typeof message.traceId.length === "number" || $util.isString(message.traceId))) + return "traceId: buffer expected"; + return null; + }; + /** + * Creates an Exemplar message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.metrics.v1.Exemplar + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.metrics.v1.Exemplar} Exemplar + */ + Exemplar.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.metrics.v1.Exemplar) + return object; + var message = new $root.opentelemetry.proto.metrics.v1.Exemplar(); + if (object.filteredAttributes) { + if (!Array.isArray(object.filteredAttributes)) + throw TypeError(".opentelemetry.proto.metrics.v1.Exemplar.filteredAttributes: array expected"); + message.filteredAttributes = []; + for (var i = 0; i < object.filteredAttributes.length; ++i) { + if (typeof object.filteredAttributes[i] !== "object") + throw TypeError(".opentelemetry.proto.metrics.v1.Exemplar.filteredAttributes: object expected"); + message.filteredAttributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.filteredAttributes[i]); + } + } + if (object.timeUnixNano != null) + if ($util.Long) + (message.timeUnixNano = $util.Long.fromValue(object.timeUnixNano)).unsigned = false; + else if (typeof object.timeUnixNano === "string") + message.timeUnixNano = parseInt(object.timeUnixNano, 10); + else if (typeof object.timeUnixNano === "number") + message.timeUnixNano = object.timeUnixNano; + else if (typeof object.timeUnixNano === "object") + message.timeUnixNano = new $util.LongBits(object.timeUnixNano.low >>> 0, object.timeUnixNano.high >>> 0).toNumber(); + if (object.asDouble != null) + message.asDouble = Number(object.asDouble); + if (object.asInt != null) + if ($util.Long) + (message.asInt = $util.Long.fromValue(object.asInt)).unsigned = false; + else if (typeof object.asInt === "string") + message.asInt = parseInt(object.asInt, 10); + else if (typeof object.asInt === "number") + message.asInt = object.asInt; + else if (typeof object.asInt === "object") + message.asInt = new $util.LongBits(object.asInt.low >>> 0, object.asInt.high >>> 0).toNumber(); + if (object.spanId != null) + if (typeof object.spanId === "string") + $util.base64.decode(object.spanId, message.spanId = $util.newBuffer($util.base64.length(object.spanId)), 0); + else if (object.spanId.length >= 0) + message.spanId = object.spanId; + if (object.traceId != null) + if (typeof object.traceId === "string") + $util.base64.decode(object.traceId, message.traceId = $util.newBuffer($util.base64.length(object.traceId)), 0); + else if (object.traceId.length >= 0) + message.traceId = object.traceId; + return message; + }; + /** + * Creates a plain object from an Exemplar message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.metrics.v1.Exemplar + * @static + * @param {opentelemetry.proto.metrics.v1.Exemplar} message Exemplar + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Exemplar.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.filteredAttributes = []; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.timeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } + else + object.timeUnixNano = options.longs === String ? "0" : 0; + if (options.bytes === String) + object.spanId = ""; + else { + object.spanId = []; + if (options.bytes !== Array) + object.spanId = $util.newBuffer(object.spanId); + } + if (options.bytes === String) + object.traceId = ""; + else { + object.traceId = []; + if (options.bytes !== Array) + object.traceId = $util.newBuffer(object.traceId); + } + } + if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) + if (typeof message.timeUnixNano === "number") + object.timeUnixNano = options.longs === String ? String(message.timeUnixNano) : message.timeUnixNano; + else + object.timeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.timeUnixNano) : options.longs === Number ? new $util.LongBits(message.timeUnixNano.low >>> 0, message.timeUnixNano.high >>> 0).toNumber() : message.timeUnixNano; + if (message.asDouble != null && message.hasOwnProperty("asDouble")) { + object.asDouble = options.json && !isFinite(message.asDouble) ? String(message.asDouble) : message.asDouble; + if (options.oneofs) + object.value = "asDouble"; + } + if (message.spanId != null && message.hasOwnProperty("spanId")) + object.spanId = options.bytes === String ? $util.base64.encode(message.spanId, 0, message.spanId.length) : options.bytes === Array ? Array.prototype.slice.call(message.spanId) : message.spanId; + if (message.traceId != null && message.hasOwnProperty("traceId")) + object.traceId = options.bytes === String ? $util.base64.encode(message.traceId, 0, message.traceId.length) : options.bytes === Array ? Array.prototype.slice.call(message.traceId) : message.traceId; + if (message.asInt != null && message.hasOwnProperty("asInt")) { + if (typeof message.asInt === "number") + object.asInt = options.longs === String ? String(message.asInt) : message.asInt; + else + object.asInt = options.longs === String ? $util.Long.prototype.toString.call(message.asInt) : options.longs === Number ? new $util.LongBits(message.asInt.low >>> 0, message.asInt.high >>> 0).toNumber() : message.asInt; + if (options.oneofs) + object.value = "asInt"; + } + if (message.filteredAttributes && message.filteredAttributes.length) { + object.filteredAttributes = []; + for (var j = 0; j < message.filteredAttributes.length; ++j) + object.filteredAttributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.filteredAttributes[j], options); + } + return object; + }; + /** + * Converts this Exemplar to JSON. + * @function toJSON + * @memberof opentelemetry.proto.metrics.v1.Exemplar + * @instance + * @returns {Object.} JSON object + */ + Exemplar.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for Exemplar + * @function getTypeUrl + * @memberof opentelemetry.proto.metrics.v1.Exemplar + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Exemplar.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.Exemplar"; + }; + return Exemplar; + })(); + return v1; + })(); + return metrics; + })(); + proto.logs = (function () { + /** + * Namespace logs. + * @memberof opentelemetry.proto + * @namespace + */ + var logs = {}; + logs.v1 = (function () { + /** + * Namespace v1. + * @memberof opentelemetry.proto.logs + * @namespace + */ + var v1 = {}; + v1.LogsData = (function () { + /** + * Properties of a LogsData. + * @memberof opentelemetry.proto.logs.v1 + * @interface ILogsData + * @property {Array.|null} [resourceLogs] LogsData resourceLogs + */ + /** + * Constructs a new LogsData. + * @memberof opentelemetry.proto.logs.v1 + * @classdesc Represents a LogsData. + * @implements ILogsData + * @constructor + * @param {opentelemetry.proto.logs.v1.ILogsData=} [properties] Properties to set + */ + function LogsData(properties) { + this.resourceLogs = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * LogsData resourceLogs. + * @member {Array.} resourceLogs + * @memberof opentelemetry.proto.logs.v1.LogsData + * @instance + */ + LogsData.prototype.resourceLogs = $util.emptyArray; + /** + * Creates a new LogsData instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.logs.v1.LogsData + * @static + * @param {opentelemetry.proto.logs.v1.ILogsData=} [properties] Properties to set + * @returns {opentelemetry.proto.logs.v1.LogsData} LogsData instance + */ + LogsData.create = function create(properties) { + return new LogsData(properties); + }; + /** + * Encodes the specified LogsData message. Does not implicitly {@link opentelemetry.proto.logs.v1.LogsData.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.logs.v1.LogsData + * @static + * @param {opentelemetry.proto.logs.v1.ILogsData} message LogsData message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + LogsData.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.resourceLogs != null && message.resourceLogs.length) + for (var i = 0; i < message.resourceLogs.length; ++i) + $root.opentelemetry.proto.logs.v1.ResourceLogs.encode(message.resourceLogs[i], writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); + return writer; + }; + /** + * Encodes the specified LogsData message, length delimited. Does not implicitly {@link opentelemetry.proto.logs.v1.LogsData.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.logs.v1.LogsData + * @static + * @param {opentelemetry.proto.logs.v1.ILogsData} message LogsData message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + LogsData.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes a LogsData message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.logs.v1.LogsData + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.logs.v1.LogsData} LogsData + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + LogsData.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.logs.v1.LogsData(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.resourceLogs && message.resourceLogs.length)) + message.resourceLogs = []; + message.resourceLogs.push($root.opentelemetry.proto.logs.v1.ResourceLogs.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes a LogsData message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.logs.v1.LogsData + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.logs.v1.LogsData} LogsData + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + LogsData.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies a LogsData message. + * @function verify + * @memberof opentelemetry.proto.logs.v1.LogsData + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + LogsData.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.resourceLogs != null && message.hasOwnProperty("resourceLogs")) { + if (!Array.isArray(message.resourceLogs)) + return "resourceLogs: array expected"; + for (var i = 0; i < message.resourceLogs.length; ++i) { + var error = $root.opentelemetry.proto.logs.v1.ResourceLogs.verify(message.resourceLogs[i]); + if (error) + return "resourceLogs." + error; + } + } + return null; + }; + /** + * Creates a LogsData message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.logs.v1.LogsData + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.logs.v1.LogsData} LogsData + */ + LogsData.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.logs.v1.LogsData) + return object; + var message = new $root.opentelemetry.proto.logs.v1.LogsData(); + if (object.resourceLogs) { + if (!Array.isArray(object.resourceLogs)) + throw TypeError(".opentelemetry.proto.logs.v1.LogsData.resourceLogs: array expected"); + message.resourceLogs = []; + for (var i = 0; i < object.resourceLogs.length; ++i) { + if (typeof object.resourceLogs[i] !== "object") + throw TypeError(".opentelemetry.proto.logs.v1.LogsData.resourceLogs: object expected"); + message.resourceLogs[i] = $root.opentelemetry.proto.logs.v1.ResourceLogs.fromObject(object.resourceLogs[i]); + } + } + return message; + }; + /** + * Creates a plain object from a LogsData message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.logs.v1.LogsData + * @static + * @param {opentelemetry.proto.logs.v1.LogsData} message LogsData + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + LogsData.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.resourceLogs = []; + if (message.resourceLogs && message.resourceLogs.length) { + object.resourceLogs = []; + for (var j = 0; j < message.resourceLogs.length; ++j) + object.resourceLogs[j] = $root.opentelemetry.proto.logs.v1.ResourceLogs.toObject(message.resourceLogs[j], options); + } + return object; + }; + /** + * Converts this LogsData to JSON. + * @function toJSON + * @memberof opentelemetry.proto.logs.v1.LogsData + * @instance + * @returns {Object.} JSON object + */ + LogsData.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for LogsData + * @function getTypeUrl + * @memberof opentelemetry.proto.logs.v1.LogsData + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + LogsData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.logs.v1.LogsData"; + }; + return LogsData; + })(); + v1.ResourceLogs = (function () { + /** + * Properties of a ResourceLogs. + * @memberof opentelemetry.proto.logs.v1 + * @interface IResourceLogs + * @property {opentelemetry.proto.resource.v1.IResource|null} [resource] ResourceLogs resource + * @property {Array.|null} [scopeLogs] ResourceLogs scopeLogs + * @property {string|null} [schemaUrl] ResourceLogs schemaUrl + */ + /** + * Constructs a new ResourceLogs. + * @memberof opentelemetry.proto.logs.v1 + * @classdesc Represents a ResourceLogs. + * @implements IResourceLogs + * @constructor + * @param {opentelemetry.proto.logs.v1.IResourceLogs=} [properties] Properties to set + */ + function ResourceLogs(properties) { + this.scopeLogs = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * ResourceLogs resource. + * @member {opentelemetry.proto.resource.v1.IResource|null|undefined} resource + * @memberof opentelemetry.proto.logs.v1.ResourceLogs + * @instance + */ + ResourceLogs.prototype.resource = null; + /** + * ResourceLogs scopeLogs. + * @member {Array.} scopeLogs + * @memberof opentelemetry.proto.logs.v1.ResourceLogs + * @instance + */ + ResourceLogs.prototype.scopeLogs = $util.emptyArray; + /** + * ResourceLogs schemaUrl. + * @member {string|null|undefined} schemaUrl + * @memberof opentelemetry.proto.logs.v1.ResourceLogs + * @instance + */ + ResourceLogs.prototype.schemaUrl = null; + /** + * Creates a new ResourceLogs instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.logs.v1.ResourceLogs + * @static + * @param {opentelemetry.proto.logs.v1.IResourceLogs=} [properties] Properties to set + * @returns {opentelemetry.proto.logs.v1.ResourceLogs} ResourceLogs instance + */ + ResourceLogs.create = function create(properties) { + return new ResourceLogs(properties); + }; + /** + * Encodes the specified ResourceLogs message. Does not implicitly {@link opentelemetry.proto.logs.v1.ResourceLogs.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.logs.v1.ResourceLogs + * @static + * @param {opentelemetry.proto.logs.v1.IResourceLogs} message ResourceLogs message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ResourceLogs.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.resource != null && Object.hasOwnProperty.call(message, "resource")) + $root.opentelemetry.proto.resource.v1.Resource.encode(message.resource, writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); + if (message.scopeLogs != null && message.scopeLogs.length) + for (var i = 0; i < message.scopeLogs.length; ++i) + $root.opentelemetry.proto.logs.v1.ScopeLogs.encode(message.scopeLogs[i], writer.uint32(/* id 2, wireType 2 =*/ 18).fork()).ldelim(); + if (message.schemaUrl != null && Object.hasOwnProperty.call(message, "schemaUrl")) + writer.uint32(/* id 3, wireType 2 =*/ 26).string(message.schemaUrl); + return writer; + }; + /** + * Encodes the specified ResourceLogs message, length delimited. Does not implicitly {@link opentelemetry.proto.logs.v1.ResourceLogs.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.logs.v1.ResourceLogs + * @static + * @param {opentelemetry.proto.logs.v1.IResourceLogs} message ResourceLogs message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ResourceLogs.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes a ResourceLogs message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.logs.v1.ResourceLogs + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.logs.v1.ResourceLogs} ResourceLogs + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ResourceLogs.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.logs.v1.ResourceLogs(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.resource = $root.opentelemetry.proto.resource.v1.Resource.decode(reader, reader.uint32()); + break; + } + case 2: { + if (!(message.scopeLogs && message.scopeLogs.length)) + message.scopeLogs = []; + message.scopeLogs.push($root.opentelemetry.proto.logs.v1.ScopeLogs.decode(reader, reader.uint32())); + break; + } + case 3: { + message.schemaUrl = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes a ResourceLogs message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.logs.v1.ResourceLogs + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.logs.v1.ResourceLogs} ResourceLogs + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ResourceLogs.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies a ResourceLogs message. + * @function verify + * @memberof opentelemetry.proto.logs.v1.ResourceLogs + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ResourceLogs.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.resource != null && message.hasOwnProperty("resource")) { + var error = $root.opentelemetry.proto.resource.v1.Resource.verify(message.resource); + if (error) + return "resource." + error; + } + if (message.scopeLogs != null && message.hasOwnProperty("scopeLogs")) { + if (!Array.isArray(message.scopeLogs)) + return "scopeLogs: array expected"; + for (var i = 0; i < message.scopeLogs.length; ++i) { + var error = $root.opentelemetry.proto.logs.v1.ScopeLogs.verify(message.scopeLogs[i]); + if (error) + return "scopeLogs." + error; + } + } + if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) + if (!$util.isString(message.schemaUrl)) + return "schemaUrl: string expected"; + return null; + }; + /** + * Creates a ResourceLogs message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.logs.v1.ResourceLogs + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.logs.v1.ResourceLogs} ResourceLogs + */ + ResourceLogs.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.logs.v1.ResourceLogs) + return object; + var message = new $root.opentelemetry.proto.logs.v1.ResourceLogs(); + if (object.resource != null) { + if (typeof object.resource !== "object") + throw TypeError(".opentelemetry.proto.logs.v1.ResourceLogs.resource: object expected"); + message.resource = $root.opentelemetry.proto.resource.v1.Resource.fromObject(object.resource); + } + if (object.scopeLogs) { + if (!Array.isArray(object.scopeLogs)) + throw TypeError(".opentelemetry.proto.logs.v1.ResourceLogs.scopeLogs: array expected"); + message.scopeLogs = []; + for (var i = 0; i < object.scopeLogs.length; ++i) { + if (typeof object.scopeLogs[i] !== "object") + throw TypeError(".opentelemetry.proto.logs.v1.ResourceLogs.scopeLogs: object expected"); + message.scopeLogs[i] = $root.opentelemetry.proto.logs.v1.ScopeLogs.fromObject(object.scopeLogs[i]); + } + } + if (object.schemaUrl != null) + message.schemaUrl = String(object.schemaUrl); + return message; + }; + /** + * Creates a plain object from a ResourceLogs message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.logs.v1.ResourceLogs + * @static + * @param {opentelemetry.proto.logs.v1.ResourceLogs} message ResourceLogs + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ResourceLogs.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.scopeLogs = []; + if (options.defaults) { + object.resource = null; + object.schemaUrl = ""; + } + if (message.resource != null && message.hasOwnProperty("resource")) + object.resource = $root.opentelemetry.proto.resource.v1.Resource.toObject(message.resource, options); + if (message.scopeLogs && message.scopeLogs.length) { + object.scopeLogs = []; + for (var j = 0; j < message.scopeLogs.length; ++j) + object.scopeLogs[j] = $root.opentelemetry.proto.logs.v1.ScopeLogs.toObject(message.scopeLogs[j], options); + } + if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) + object.schemaUrl = message.schemaUrl; + return object; + }; + /** + * Converts this ResourceLogs to JSON. + * @function toJSON + * @memberof opentelemetry.proto.logs.v1.ResourceLogs + * @instance + * @returns {Object.} JSON object + */ + ResourceLogs.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for ResourceLogs + * @function getTypeUrl + * @memberof opentelemetry.proto.logs.v1.ResourceLogs + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ResourceLogs.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.logs.v1.ResourceLogs"; + }; + return ResourceLogs; + })(); + v1.ScopeLogs = (function () { + /** + * Properties of a ScopeLogs. + * @memberof opentelemetry.proto.logs.v1 + * @interface IScopeLogs + * @property {opentelemetry.proto.common.v1.IInstrumentationScope|null} [scope] ScopeLogs scope + * @property {Array.|null} [logRecords] ScopeLogs logRecords + * @property {string|null} [schemaUrl] ScopeLogs schemaUrl + */ + /** + * Constructs a new ScopeLogs. + * @memberof opentelemetry.proto.logs.v1 + * @classdesc Represents a ScopeLogs. + * @implements IScopeLogs + * @constructor + * @param {opentelemetry.proto.logs.v1.IScopeLogs=} [properties] Properties to set + */ + function ScopeLogs(properties) { + this.logRecords = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * ScopeLogs scope. + * @member {opentelemetry.proto.common.v1.IInstrumentationScope|null|undefined} scope + * @memberof opentelemetry.proto.logs.v1.ScopeLogs + * @instance + */ + ScopeLogs.prototype.scope = null; + /** + * ScopeLogs logRecords. + * @member {Array.} logRecords + * @memberof opentelemetry.proto.logs.v1.ScopeLogs + * @instance + */ + ScopeLogs.prototype.logRecords = $util.emptyArray; + /** + * ScopeLogs schemaUrl. + * @member {string|null|undefined} schemaUrl + * @memberof opentelemetry.proto.logs.v1.ScopeLogs + * @instance + */ + ScopeLogs.prototype.schemaUrl = null; + /** + * Creates a new ScopeLogs instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.logs.v1.ScopeLogs + * @static + * @param {opentelemetry.proto.logs.v1.IScopeLogs=} [properties] Properties to set + * @returns {opentelemetry.proto.logs.v1.ScopeLogs} ScopeLogs instance + */ + ScopeLogs.create = function create(properties) { + return new ScopeLogs(properties); + }; + /** + * Encodes the specified ScopeLogs message. Does not implicitly {@link opentelemetry.proto.logs.v1.ScopeLogs.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.logs.v1.ScopeLogs + * @static + * @param {opentelemetry.proto.logs.v1.IScopeLogs} message ScopeLogs message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ScopeLogs.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.scope != null && Object.hasOwnProperty.call(message, "scope")) + $root.opentelemetry.proto.common.v1.InstrumentationScope.encode(message.scope, writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); + if (message.logRecords != null && message.logRecords.length) + for (var i = 0; i < message.logRecords.length; ++i) + $root.opentelemetry.proto.logs.v1.LogRecord.encode(message.logRecords[i], writer.uint32(/* id 2, wireType 2 =*/ 18).fork()).ldelim(); + if (message.schemaUrl != null && Object.hasOwnProperty.call(message, "schemaUrl")) + writer.uint32(/* id 3, wireType 2 =*/ 26).string(message.schemaUrl); + return writer; + }; + /** + * Encodes the specified ScopeLogs message, length delimited. Does not implicitly {@link opentelemetry.proto.logs.v1.ScopeLogs.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.logs.v1.ScopeLogs + * @static + * @param {opentelemetry.proto.logs.v1.IScopeLogs} message ScopeLogs message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ScopeLogs.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes a ScopeLogs message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.logs.v1.ScopeLogs + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.logs.v1.ScopeLogs} ScopeLogs + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ScopeLogs.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.logs.v1.ScopeLogs(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.decode(reader, reader.uint32()); + break; + } + case 2: { + if (!(message.logRecords && message.logRecords.length)) + message.logRecords = []; + message.logRecords.push($root.opentelemetry.proto.logs.v1.LogRecord.decode(reader, reader.uint32())); + break; + } + case 3: { + message.schemaUrl = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes a ScopeLogs message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.logs.v1.ScopeLogs + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.logs.v1.ScopeLogs} ScopeLogs + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ScopeLogs.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies a ScopeLogs message. + * @function verify + * @memberof opentelemetry.proto.logs.v1.ScopeLogs + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ScopeLogs.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.scope != null && message.hasOwnProperty("scope")) { + var error = $root.opentelemetry.proto.common.v1.InstrumentationScope.verify(message.scope); + if (error) + return "scope." + error; + } + if (message.logRecords != null && message.hasOwnProperty("logRecords")) { + if (!Array.isArray(message.logRecords)) + return "logRecords: array expected"; + for (var i = 0; i < message.logRecords.length; ++i) { + var error = $root.opentelemetry.proto.logs.v1.LogRecord.verify(message.logRecords[i]); + if (error) + return "logRecords." + error; + } + } + if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) + if (!$util.isString(message.schemaUrl)) + return "schemaUrl: string expected"; + return null; + }; + /** + * Creates a ScopeLogs message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.logs.v1.ScopeLogs + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.logs.v1.ScopeLogs} ScopeLogs + */ + ScopeLogs.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.logs.v1.ScopeLogs) + return object; + var message = new $root.opentelemetry.proto.logs.v1.ScopeLogs(); + if (object.scope != null) { + if (typeof object.scope !== "object") + throw TypeError(".opentelemetry.proto.logs.v1.ScopeLogs.scope: object expected"); + message.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.fromObject(object.scope); + } + if (object.logRecords) { + if (!Array.isArray(object.logRecords)) + throw TypeError(".opentelemetry.proto.logs.v1.ScopeLogs.logRecords: array expected"); + message.logRecords = []; + for (var i = 0; i < object.logRecords.length; ++i) { + if (typeof object.logRecords[i] !== "object") + throw TypeError(".opentelemetry.proto.logs.v1.ScopeLogs.logRecords: object expected"); + message.logRecords[i] = $root.opentelemetry.proto.logs.v1.LogRecord.fromObject(object.logRecords[i]); + } + } + if (object.schemaUrl != null) + message.schemaUrl = String(object.schemaUrl); + return message; + }; + /** + * Creates a plain object from a ScopeLogs message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.logs.v1.ScopeLogs + * @static + * @param {opentelemetry.proto.logs.v1.ScopeLogs} message ScopeLogs + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ScopeLogs.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.logRecords = []; + if (options.defaults) { + object.scope = null; + object.schemaUrl = ""; + } + if (message.scope != null && message.hasOwnProperty("scope")) + object.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.toObject(message.scope, options); + if (message.logRecords && message.logRecords.length) { + object.logRecords = []; + for (var j = 0; j < message.logRecords.length; ++j) + object.logRecords[j] = $root.opentelemetry.proto.logs.v1.LogRecord.toObject(message.logRecords[j], options); + } + if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) + object.schemaUrl = message.schemaUrl; + return object; + }; + /** + * Converts this ScopeLogs to JSON. + * @function toJSON + * @memberof opentelemetry.proto.logs.v1.ScopeLogs + * @instance + * @returns {Object.} JSON object + */ + ScopeLogs.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for ScopeLogs + * @function getTypeUrl + * @memberof opentelemetry.proto.logs.v1.ScopeLogs + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ScopeLogs.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.logs.v1.ScopeLogs"; + }; + return ScopeLogs; + })(); + /** + * SeverityNumber enum. + * @name opentelemetry.proto.logs.v1.SeverityNumber + * @enum {number} + * @property {number} SEVERITY_NUMBER_UNSPECIFIED=0 SEVERITY_NUMBER_UNSPECIFIED value + * @property {number} SEVERITY_NUMBER_TRACE=1 SEVERITY_NUMBER_TRACE value + * @property {number} SEVERITY_NUMBER_TRACE2=2 SEVERITY_NUMBER_TRACE2 value + * @property {number} SEVERITY_NUMBER_TRACE3=3 SEVERITY_NUMBER_TRACE3 value + * @property {number} SEVERITY_NUMBER_TRACE4=4 SEVERITY_NUMBER_TRACE4 value + * @property {number} SEVERITY_NUMBER_DEBUG=5 SEVERITY_NUMBER_DEBUG value + * @property {number} SEVERITY_NUMBER_DEBUG2=6 SEVERITY_NUMBER_DEBUG2 value + * @property {number} SEVERITY_NUMBER_DEBUG3=7 SEVERITY_NUMBER_DEBUG3 value + * @property {number} SEVERITY_NUMBER_DEBUG4=8 SEVERITY_NUMBER_DEBUG4 value + * @property {number} SEVERITY_NUMBER_INFO=9 SEVERITY_NUMBER_INFO value + * @property {number} SEVERITY_NUMBER_INFO2=10 SEVERITY_NUMBER_INFO2 value + * @property {number} SEVERITY_NUMBER_INFO3=11 SEVERITY_NUMBER_INFO3 value + * @property {number} SEVERITY_NUMBER_INFO4=12 SEVERITY_NUMBER_INFO4 value + * @property {number} SEVERITY_NUMBER_WARN=13 SEVERITY_NUMBER_WARN value + * @property {number} SEVERITY_NUMBER_WARN2=14 SEVERITY_NUMBER_WARN2 value + * @property {number} SEVERITY_NUMBER_WARN3=15 SEVERITY_NUMBER_WARN3 value + * @property {number} SEVERITY_NUMBER_WARN4=16 SEVERITY_NUMBER_WARN4 value + * @property {number} SEVERITY_NUMBER_ERROR=17 SEVERITY_NUMBER_ERROR value + * @property {number} SEVERITY_NUMBER_ERROR2=18 SEVERITY_NUMBER_ERROR2 value + * @property {number} SEVERITY_NUMBER_ERROR3=19 SEVERITY_NUMBER_ERROR3 value + * @property {number} SEVERITY_NUMBER_ERROR4=20 SEVERITY_NUMBER_ERROR4 value + * @property {number} SEVERITY_NUMBER_FATAL=21 SEVERITY_NUMBER_FATAL value + * @property {number} SEVERITY_NUMBER_FATAL2=22 SEVERITY_NUMBER_FATAL2 value + * @property {number} SEVERITY_NUMBER_FATAL3=23 SEVERITY_NUMBER_FATAL3 value + * @property {number} SEVERITY_NUMBER_FATAL4=24 SEVERITY_NUMBER_FATAL4 value + */ + v1.SeverityNumber = (function () { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "SEVERITY_NUMBER_UNSPECIFIED"] = 0; + values[valuesById[1] = "SEVERITY_NUMBER_TRACE"] = 1; + values[valuesById[2] = "SEVERITY_NUMBER_TRACE2"] = 2; + values[valuesById[3] = "SEVERITY_NUMBER_TRACE3"] = 3; + values[valuesById[4] = "SEVERITY_NUMBER_TRACE4"] = 4; + values[valuesById[5] = "SEVERITY_NUMBER_DEBUG"] = 5; + values[valuesById[6] = "SEVERITY_NUMBER_DEBUG2"] = 6; + values[valuesById[7] = "SEVERITY_NUMBER_DEBUG3"] = 7; + values[valuesById[8] = "SEVERITY_NUMBER_DEBUG4"] = 8; + values[valuesById[9] = "SEVERITY_NUMBER_INFO"] = 9; + values[valuesById[10] = "SEVERITY_NUMBER_INFO2"] = 10; + values[valuesById[11] = "SEVERITY_NUMBER_INFO3"] = 11; + values[valuesById[12] = "SEVERITY_NUMBER_INFO4"] = 12; + values[valuesById[13] = "SEVERITY_NUMBER_WARN"] = 13; + values[valuesById[14] = "SEVERITY_NUMBER_WARN2"] = 14; + values[valuesById[15] = "SEVERITY_NUMBER_WARN3"] = 15; + values[valuesById[16] = "SEVERITY_NUMBER_WARN4"] = 16; + values[valuesById[17] = "SEVERITY_NUMBER_ERROR"] = 17; + values[valuesById[18] = "SEVERITY_NUMBER_ERROR2"] = 18; + values[valuesById[19] = "SEVERITY_NUMBER_ERROR3"] = 19; + values[valuesById[20] = "SEVERITY_NUMBER_ERROR4"] = 20; + values[valuesById[21] = "SEVERITY_NUMBER_FATAL"] = 21; + values[valuesById[22] = "SEVERITY_NUMBER_FATAL2"] = 22; + values[valuesById[23] = "SEVERITY_NUMBER_FATAL3"] = 23; + values[valuesById[24] = "SEVERITY_NUMBER_FATAL4"] = 24; + return values; + })(); + /** + * LogRecordFlags enum. + * @name opentelemetry.proto.logs.v1.LogRecordFlags + * @enum {number} + * @property {number} LOG_RECORD_FLAGS_DO_NOT_USE=0 LOG_RECORD_FLAGS_DO_NOT_USE value + * @property {number} LOG_RECORD_FLAGS_TRACE_FLAGS_MASK=255 LOG_RECORD_FLAGS_TRACE_FLAGS_MASK value + */ + v1.LogRecordFlags = (function () { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "LOG_RECORD_FLAGS_DO_NOT_USE"] = 0; + values[valuesById[255] = "LOG_RECORD_FLAGS_TRACE_FLAGS_MASK"] = 255; + return values; + })(); + v1.LogRecord = (function () { + /** + * Properties of a LogRecord. + * @memberof opentelemetry.proto.logs.v1 + * @interface ILogRecord + * @property {number|Long|null} [timeUnixNano] LogRecord timeUnixNano + * @property {number|Long|null} [observedTimeUnixNano] LogRecord observedTimeUnixNano + * @property {opentelemetry.proto.logs.v1.SeverityNumber|null} [severityNumber] LogRecord severityNumber + * @property {string|null} [severityText] LogRecord severityText + * @property {opentelemetry.proto.common.v1.IAnyValue|null} [body] LogRecord body + * @property {Array.|null} [attributes] LogRecord attributes + * @property {number|null} [droppedAttributesCount] LogRecord droppedAttributesCount + * @property {number|null} [flags] LogRecord flags + * @property {Uint8Array|null} [traceId] LogRecord traceId + * @property {Uint8Array|null} [spanId] LogRecord spanId + * @property {string|null} [eventName] LogRecord eventName + */ + /** + * Constructs a new LogRecord. + * @memberof opentelemetry.proto.logs.v1 + * @classdesc Represents a LogRecord. + * @implements ILogRecord + * @constructor + * @param {opentelemetry.proto.logs.v1.ILogRecord=} [properties] Properties to set + */ + function LogRecord(properties) { + this.attributes = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + /** + * LogRecord timeUnixNano. + * @member {number|Long|null|undefined} timeUnixNano + * @memberof opentelemetry.proto.logs.v1.LogRecord + * @instance + */ + LogRecord.prototype.timeUnixNano = null; + /** + * LogRecord observedTimeUnixNano. + * @member {number|Long|null|undefined} observedTimeUnixNano + * @memberof opentelemetry.proto.logs.v1.LogRecord + * @instance + */ + LogRecord.prototype.observedTimeUnixNano = null; + /** + * LogRecord severityNumber. + * @member {opentelemetry.proto.logs.v1.SeverityNumber|null|undefined} severityNumber + * @memberof opentelemetry.proto.logs.v1.LogRecord + * @instance + */ + LogRecord.prototype.severityNumber = null; + /** + * LogRecord severityText. + * @member {string|null|undefined} severityText + * @memberof opentelemetry.proto.logs.v1.LogRecord + * @instance + */ + LogRecord.prototype.severityText = null; + /** + * LogRecord body. + * @member {opentelemetry.proto.common.v1.IAnyValue|null|undefined} body + * @memberof opentelemetry.proto.logs.v1.LogRecord + * @instance + */ + LogRecord.prototype.body = null; + /** + * LogRecord attributes. + * @member {Array.} attributes + * @memberof opentelemetry.proto.logs.v1.LogRecord + * @instance + */ + LogRecord.prototype.attributes = $util.emptyArray; + /** + * LogRecord droppedAttributesCount. + * @member {number|null|undefined} droppedAttributesCount + * @memberof opentelemetry.proto.logs.v1.LogRecord + * @instance + */ + LogRecord.prototype.droppedAttributesCount = null; + /** + * LogRecord flags. + * @member {number|null|undefined} flags + * @memberof opentelemetry.proto.logs.v1.LogRecord + * @instance + */ + LogRecord.prototype.flags = null; + /** + * LogRecord traceId. + * @member {Uint8Array|null|undefined} traceId + * @memberof opentelemetry.proto.logs.v1.LogRecord + * @instance + */ + LogRecord.prototype.traceId = null; + /** + * LogRecord spanId. + * @member {Uint8Array|null|undefined} spanId + * @memberof opentelemetry.proto.logs.v1.LogRecord + * @instance + */ + LogRecord.prototype.spanId = null; + /** + * LogRecord eventName. + * @member {string|null|undefined} eventName + * @memberof opentelemetry.proto.logs.v1.LogRecord + * @instance + */ + LogRecord.prototype.eventName = null; + /** + * Creates a new LogRecord instance using the specified properties. + * @function create + * @memberof opentelemetry.proto.logs.v1.LogRecord + * @static + * @param {opentelemetry.proto.logs.v1.ILogRecord=} [properties] Properties to set + * @returns {opentelemetry.proto.logs.v1.LogRecord} LogRecord instance + */ + LogRecord.create = function create(properties) { + return new LogRecord(properties); + }; + /** + * Encodes the specified LogRecord message. Does not implicitly {@link opentelemetry.proto.logs.v1.LogRecord.verify|verify} messages. + * @function encode + * @memberof opentelemetry.proto.logs.v1.LogRecord + * @static + * @param {opentelemetry.proto.logs.v1.ILogRecord} message LogRecord message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + LogRecord.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.timeUnixNano != null && Object.hasOwnProperty.call(message, "timeUnixNano")) + writer.uint32(/* id 1, wireType 1 =*/ 9).fixed64(message.timeUnixNano); + if (message.severityNumber != null && Object.hasOwnProperty.call(message, "severityNumber")) + writer.uint32(/* id 2, wireType 0 =*/ 16).int32(message.severityNumber); + if (message.severityText != null && Object.hasOwnProperty.call(message, "severityText")) + writer.uint32(/* id 3, wireType 2 =*/ 26).string(message.severityText); + if (message.body != null && Object.hasOwnProperty.call(message, "body")) + $root.opentelemetry.proto.common.v1.AnyValue.encode(message.body, writer.uint32(/* id 5, wireType 2 =*/ 42).fork()).ldelim(); + if (message.attributes != null && message.attributes.length) + for (var i = 0; i < message.attributes.length; ++i) + $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(/* id 6, wireType 2 =*/ 50).fork()).ldelim(); + if (message.droppedAttributesCount != null && Object.hasOwnProperty.call(message, "droppedAttributesCount")) + writer.uint32(/* id 7, wireType 0 =*/ 56).uint32(message.droppedAttributesCount); + if (message.flags != null && Object.hasOwnProperty.call(message, "flags")) + writer.uint32(/* id 8, wireType 5 =*/ 69).fixed32(message.flags); + if (message.traceId != null && Object.hasOwnProperty.call(message, "traceId")) + writer.uint32(/* id 9, wireType 2 =*/ 74).bytes(message.traceId); + if (message.spanId != null && Object.hasOwnProperty.call(message, "spanId")) + writer.uint32(/* id 10, wireType 2 =*/ 82).bytes(message.spanId); + if (message.observedTimeUnixNano != null && Object.hasOwnProperty.call(message, "observedTimeUnixNano")) + writer.uint32(/* id 11, wireType 1 =*/ 89).fixed64(message.observedTimeUnixNano); + if (message.eventName != null && Object.hasOwnProperty.call(message, "eventName")) + writer.uint32(/* id 12, wireType 2 =*/ 98).string(message.eventName); + return writer; + }; + /** + * Encodes the specified LogRecord message, length delimited. Does not implicitly {@link opentelemetry.proto.logs.v1.LogRecord.verify|verify} messages. + * @function encodeDelimited + * @memberof opentelemetry.proto.logs.v1.LogRecord + * @static + * @param {opentelemetry.proto.logs.v1.ILogRecord} message LogRecord message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + LogRecord.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + /** + * Decodes a LogRecord message from the specified reader or buffer. + * @function decode + * @memberof opentelemetry.proto.logs.v1.LogRecord + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {opentelemetry.proto.logs.v1.LogRecord} LogRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + LogRecord.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.logs.v1.LogRecord(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.timeUnixNano = reader.fixed64(); + break; + } + case 11: { + message.observedTimeUnixNano = reader.fixed64(); + break; + } + case 2: { + message.severityNumber = reader.int32(); + break; + } + case 3: { + message.severityText = reader.string(); + break; + } + case 5: { + message.body = $root.opentelemetry.proto.common.v1.AnyValue.decode(reader, reader.uint32()); + break; + } + case 6: { + if (!(message.attributes && message.attributes.length)) + message.attributes = []; + message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32())); + break; + } + case 7: { + message.droppedAttributesCount = reader.uint32(); + break; + } + case 8: { + message.flags = reader.fixed32(); + break; + } + case 9: { + message.traceId = reader.bytes(); + break; + } + case 10: { + message.spanId = reader.bytes(); + break; + } + case 12: { + message.eventName = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + /** + * Decodes a LogRecord message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof opentelemetry.proto.logs.v1.LogRecord + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {opentelemetry.proto.logs.v1.LogRecord} LogRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + LogRecord.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + /** + * Verifies a LogRecord message. + * @function verify + * @memberof opentelemetry.proto.logs.v1.LogRecord + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + LogRecord.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) + if (!$util.isInteger(message.timeUnixNano) && !(message.timeUnixNano && $util.isInteger(message.timeUnixNano.low) && $util.isInteger(message.timeUnixNano.high))) + return "timeUnixNano: integer|Long expected"; + if (message.observedTimeUnixNano != null && message.hasOwnProperty("observedTimeUnixNano")) + if (!$util.isInteger(message.observedTimeUnixNano) && !(message.observedTimeUnixNano && $util.isInteger(message.observedTimeUnixNano.low) && $util.isInteger(message.observedTimeUnixNano.high))) + return "observedTimeUnixNano: integer|Long expected"; + if (message.severityNumber != null && message.hasOwnProperty("severityNumber")) + switch (message.severityNumber) { + default: + return "severityNumber: enum value expected"; + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + case 9: + case 10: + case 11: + case 12: + case 13: + case 14: + case 15: + case 16: + case 17: + case 18: + case 19: + case 20: + case 21: + case 22: + case 23: + case 24: + break; + } + if (message.severityText != null && message.hasOwnProperty("severityText")) + if (!$util.isString(message.severityText)) + return "severityText: string expected"; + if (message.body != null && message.hasOwnProperty("body")) { + var error = $root.opentelemetry.proto.common.v1.AnyValue.verify(message.body); + if (error) + return "body." + error; + } + if (message.attributes != null && message.hasOwnProperty("attributes")) { + if (!Array.isArray(message.attributes)) + return "attributes: array expected"; + for (var i = 0; i < message.attributes.length; ++i) { + var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]); + if (error) + return "attributes." + error; + } + } + if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) + if (!$util.isInteger(message.droppedAttributesCount)) + return "droppedAttributesCount: integer expected"; + if (message.flags != null && message.hasOwnProperty("flags")) + if (!$util.isInteger(message.flags)) + return "flags: integer expected"; + if (message.traceId != null && message.hasOwnProperty("traceId")) + if (!(message.traceId && typeof message.traceId.length === "number" || $util.isString(message.traceId))) + return "traceId: buffer expected"; + if (message.spanId != null && message.hasOwnProperty("spanId")) + if (!(message.spanId && typeof message.spanId.length === "number" || $util.isString(message.spanId))) + return "spanId: buffer expected"; + if (message.eventName != null && message.hasOwnProperty("eventName")) + if (!$util.isString(message.eventName)) + return "eventName: string expected"; + return null; + }; + /** + * Creates a LogRecord message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof opentelemetry.proto.logs.v1.LogRecord + * @static + * @param {Object.} object Plain object + * @returns {opentelemetry.proto.logs.v1.LogRecord} LogRecord + */ + LogRecord.fromObject = function fromObject(object) { + if (object instanceof $root.opentelemetry.proto.logs.v1.LogRecord) + return object; + var message = new $root.opentelemetry.proto.logs.v1.LogRecord(); + if (object.timeUnixNano != null) + if ($util.Long) + (message.timeUnixNano = $util.Long.fromValue(object.timeUnixNano)).unsigned = false; + else if (typeof object.timeUnixNano === "string") + message.timeUnixNano = parseInt(object.timeUnixNano, 10); + else if (typeof object.timeUnixNano === "number") + message.timeUnixNano = object.timeUnixNano; + else if (typeof object.timeUnixNano === "object") + message.timeUnixNano = new $util.LongBits(object.timeUnixNano.low >>> 0, object.timeUnixNano.high >>> 0).toNumber(); + if (object.observedTimeUnixNano != null) + if ($util.Long) + (message.observedTimeUnixNano = $util.Long.fromValue(object.observedTimeUnixNano)).unsigned = false; + else if (typeof object.observedTimeUnixNano === "string") + message.observedTimeUnixNano = parseInt(object.observedTimeUnixNano, 10); + else if (typeof object.observedTimeUnixNano === "number") + message.observedTimeUnixNano = object.observedTimeUnixNano; + else if (typeof object.observedTimeUnixNano === "object") + message.observedTimeUnixNano = new $util.LongBits(object.observedTimeUnixNano.low >>> 0, object.observedTimeUnixNano.high >>> 0).toNumber(); + switch (object.severityNumber) { + default: + if (typeof object.severityNumber === "number") { + message.severityNumber = object.severityNumber; + break; + } + break; + case "SEVERITY_NUMBER_UNSPECIFIED": + case 0: + message.severityNumber = 0; + break; + case "SEVERITY_NUMBER_TRACE": + case 1: + message.severityNumber = 1; + break; + case "SEVERITY_NUMBER_TRACE2": + case 2: + message.severityNumber = 2; + break; + case "SEVERITY_NUMBER_TRACE3": + case 3: + message.severityNumber = 3; + break; + case "SEVERITY_NUMBER_TRACE4": + case 4: + message.severityNumber = 4; + break; + case "SEVERITY_NUMBER_DEBUG": + case 5: + message.severityNumber = 5; + break; + case "SEVERITY_NUMBER_DEBUG2": + case 6: + message.severityNumber = 6; + break; + case "SEVERITY_NUMBER_DEBUG3": + case 7: + message.severityNumber = 7; + break; + case "SEVERITY_NUMBER_DEBUG4": + case 8: + message.severityNumber = 8; + break; + case "SEVERITY_NUMBER_INFO": + case 9: + message.severityNumber = 9; + break; + case "SEVERITY_NUMBER_INFO2": + case 10: + message.severityNumber = 10; + break; + case "SEVERITY_NUMBER_INFO3": + case 11: + message.severityNumber = 11; + break; + case "SEVERITY_NUMBER_INFO4": + case 12: + message.severityNumber = 12; + break; + case "SEVERITY_NUMBER_WARN": + case 13: + message.severityNumber = 13; + break; + case "SEVERITY_NUMBER_WARN2": + case 14: + message.severityNumber = 14; + break; + case "SEVERITY_NUMBER_WARN3": + case 15: + message.severityNumber = 15; + break; + case "SEVERITY_NUMBER_WARN4": + case 16: + message.severityNumber = 16; + break; + case "SEVERITY_NUMBER_ERROR": + case 17: + message.severityNumber = 17; + break; + case "SEVERITY_NUMBER_ERROR2": + case 18: + message.severityNumber = 18; + break; + case "SEVERITY_NUMBER_ERROR3": + case 19: + message.severityNumber = 19; + break; + case "SEVERITY_NUMBER_ERROR4": + case 20: + message.severityNumber = 20; + break; + case "SEVERITY_NUMBER_FATAL": + case 21: + message.severityNumber = 21; + break; + case "SEVERITY_NUMBER_FATAL2": + case 22: + message.severityNumber = 22; + break; + case "SEVERITY_NUMBER_FATAL3": + case 23: + message.severityNumber = 23; + break; + case "SEVERITY_NUMBER_FATAL4": + case 24: + message.severityNumber = 24; + break; + } + if (object.severityText != null) + message.severityText = String(object.severityText); + if (object.body != null) { + if (typeof object.body !== "object") + throw TypeError(".opentelemetry.proto.logs.v1.LogRecord.body: object expected"); + message.body = $root.opentelemetry.proto.common.v1.AnyValue.fromObject(object.body); + } + if (object.attributes) { + if (!Array.isArray(object.attributes)) + throw TypeError(".opentelemetry.proto.logs.v1.LogRecord.attributes: array expected"); + message.attributes = []; + for (var i = 0; i < object.attributes.length; ++i) { + if (typeof object.attributes[i] !== "object") + throw TypeError(".opentelemetry.proto.logs.v1.LogRecord.attributes: object expected"); + message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]); + } + } + if (object.droppedAttributesCount != null) + message.droppedAttributesCount = object.droppedAttributesCount >>> 0; + if (object.flags != null) + message.flags = object.flags >>> 0; + if (object.traceId != null) + if (typeof object.traceId === "string") + $util.base64.decode(object.traceId, message.traceId = $util.newBuffer($util.base64.length(object.traceId)), 0); + else if (object.traceId.length >= 0) + message.traceId = object.traceId; + if (object.spanId != null) + if (typeof object.spanId === "string") + $util.base64.decode(object.spanId, message.spanId = $util.newBuffer($util.base64.length(object.spanId)), 0); + else if (object.spanId.length >= 0) + message.spanId = object.spanId; + if (object.eventName != null) + message.eventName = String(object.eventName); + return message; + }; + /** + * Creates a plain object from a LogRecord message. Also converts values to other types if specified. + * @function toObject + * @memberof opentelemetry.proto.logs.v1.LogRecord + * @static + * @param {opentelemetry.proto.logs.v1.LogRecord} message LogRecord + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + LogRecord.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.attributes = []; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.timeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } + else + object.timeUnixNano = options.longs === String ? "0" : 0; + object.severityNumber = options.enums === String ? "SEVERITY_NUMBER_UNSPECIFIED" : 0; + object.severityText = ""; + object.body = null; + object.droppedAttributesCount = 0; + object.flags = 0; + if (options.bytes === String) + object.traceId = ""; + else { + object.traceId = []; + if (options.bytes !== Array) + object.traceId = $util.newBuffer(object.traceId); + } + if (options.bytes === String) + object.spanId = ""; + else { + object.spanId = []; + if (options.bytes !== Array) + object.spanId = $util.newBuffer(object.spanId); + } + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.observedTimeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } + else + object.observedTimeUnixNano = options.longs === String ? "0" : 0; + object.eventName = ""; + } + if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) + if (typeof message.timeUnixNano === "number") + object.timeUnixNano = options.longs === String ? String(message.timeUnixNano) : message.timeUnixNano; + else + object.timeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.timeUnixNano) : options.longs === Number ? new $util.LongBits(message.timeUnixNano.low >>> 0, message.timeUnixNano.high >>> 0).toNumber() : message.timeUnixNano; + if (message.severityNumber != null && message.hasOwnProperty("severityNumber")) + object.severityNumber = options.enums === String ? $root.opentelemetry.proto.logs.v1.SeverityNumber[message.severityNumber] === undefined ? message.severityNumber : $root.opentelemetry.proto.logs.v1.SeverityNumber[message.severityNumber] : message.severityNumber; + if (message.severityText != null && message.hasOwnProperty("severityText")) + object.severityText = message.severityText; + if (message.body != null && message.hasOwnProperty("body")) + object.body = $root.opentelemetry.proto.common.v1.AnyValue.toObject(message.body, options); + if (message.attributes && message.attributes.length) { + object.attributes = []; + for (var j = 0; j < message.attributes.length; ++j) + object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options); + } + if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) + object.droppedAttributesCount = message.droppedAttributesCount; + if (message.flags != null && message.hasOwnProperty("flags")) + object.flags = message.flags; + if (message.traceId != null && message.hasOwnProperty("traceId")) + object.traceId = options.bytes === String ? $util.base64.encode(message.traceId, 0, message.traceId.length) : options.bytes === Array ? Array.prototype.slice.call(message.traceId) : message.traceId; + if (message.spanId != null && message.hasOwnProperty("spanId")) + object.spanId = options.bytes === String ? $util.base64.encode(message.spanId, 0, message.spanId.length) : options.bytes === Array ? Array.prototype.slice.call(message.spanId) : message.spanId; + if (message.observedTimeUnixNano != null && message.hasOwnProperty("observedTimeUnixNano")) + if (typeof message.observedTimeUnixNano === "number") + object.observedTimeUnixNano = options.longs === String ? String(message.observedTimeUnixNano) : message.observedTimeUnixNano; + else + object.observedTimeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.observedTimeUnixNano) : options.longs === Number ? new $util.LongBits(message.observedTimeUnixNano.low >>> 0, message.observedTimeUnixNano.high >>> 0).toNumber() : message.observedTimeUnixNano; + if (message.eventName != null && message.hasOwnProperty("eventName")) + object.eventName = message.eventName; + return object; + }; + /** + * Converts this LogRecord to JSON. + * @function toJSON + * @memberof opentelemetry.proto.logs.v1.LogRecord + * @instance + * @returns {Object.} JSON object + */ + LogRecord.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + /** + * Gets the default type url for LogRecord + * @function getTypeUrl + * @memberof opentelemetry.proto.logs.v1.LogRecord + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + LogRecord.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/opentelemetry.proto.logs.v1.LogRecord"; + }; + return LogRecord; + })(); + return v1; + })(); + return logs; + })(); + return proto; + })(); + return opentelemetry; +})(); +module.exports = $root; +//# sourceMappingURL=root.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/index.js new file mode 100644 index 00000000..eaa486c8 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/index.js @@ -0,0 +1,31 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.JsonTraceSerializer = exports.JsonMetricsSerializer = exports.JsonLogsSerializer = exports.ProtobufTraceSerializer = exports.ProtobufMetricsSerializer = exports.ProtobufLogsSerializer = void 0; +var protobuf_1 = require("./logs/protobuf"); +Object.defineProperty(exports, "ProtobufLogsSerializer", { enumerable: true, get: function () { return protobuf_1.ProtobufLogsSerializer; } }); +var protobuf_2 = require("./metrics/protobuf"); +Object.defineProperty(exports, "ProtobufMetricsSerializer", { enumerable: true, get: function () { return protobuf_2.ProtobufMetricsSerializer; } }); +var protobuf_3 = require("./trace/protobuf"); +Object.defineProperty(exports, "ProtobufTraceSerializer", { enumerable: true, get: function () { return protobuf_3.ProtobufTraceSerializer; } }); +var json_1 = require("./logs/json"); +Object.defineProperty(exports, "JsonLogsSerializer", { enumerable: true, get: function () { return json_1.JsonLogsSerializer; } }); +var json_2 = require("./metrics/json"); +Object.defineProperty(exports, "JsonMetricsSerializer", { enumerable: true, get: function () { return json_2.JsonMetricsSerializer; } }); +var json_3 = require("./trace/json"); +Object.defineProperty(exports, "JsonTraceSerializer", { enumerable: true, get: function () { return json_3.JsonTraceSerializer; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/internal.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/internal.js new file mode 100644 index 00000000..d9f60ea1 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/internal.js @@ -0,0 +1,86 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.toLogAttributes = exports.createExportLogsServiceRequest = void 0; +const utils_1 = require("../common/utils"); +const internal_1 = require("../common/internal"); +function createExportLogsServiceRequest(logRecords, options) { + const encoder = (0, utils_1.getOtlpEncoder)(options); + return { + resourceLogs: logRecordsToResourceLogs(logRecords, encoder), + }; +} +exports.createExportLogsServiceRequest = createExportLogsServiceRequest; +function createResourceMap(logRecords) { + const resourceMap = new Map(); + for (const record of logRecords) { + const { resource, instrumentationScope: { name, version = '', schemaUrl = '' }, } = record; + let ismMap = resourceMap.get(resource); + if (!ismMap) { + ismMap = new Map(); + resourceMap.set(resource, ismMap); + } + const ismKey = `${name}@${version}:${schemaUrl}`; + let records = ismMap.get(ismKey); + if (!records) { + records = []; + ismMap.set(ismKey, records); + } + records.push(record); + } + return resourceMap; +} +function logRecordsToResourceLogs(logRecords, encoder) { + const resourceMap = createResourceMap(logRecords); + return Array.from(resourceMap, ([resource, ismMap]) => { + const processedResource = (0, internal_1.createResource)(resource); + return { + resource: processedResource, + scopeLogs: Array.from(ismMap, ([, scopeLogs]) => { + return { + scope: (0, internal_1.createInstrumentationScope)(scopeLogs[0].instrumentationScope), + logRecords: scopeLogs.map(log => toLogRecord(log, encoder)), + schemaUrl: scopeLogs[0].instrumentationScope.schemaUrl, + }; + }), + schemaUrl: processedResource.schemaUrl, + }; + }); +} +function toLogRecord(log, encoder) { + return { + timeUnixNano: encoder.encodeHrTime(log.hrTime), + observedTimeUnixNano: encoder.encodeHrTime(log.hrTimeObserved), + severityNumber: toSeverityNumber(log.severityNumber), + severityText: log.severityText, + body: (0, internal_1.toAnyValue)(log.body), + eventName: log.eventName, + attributes: toLogAttributes(log.attributes), + droppedAttributesCount: log.droppedAttributesCount, + flags: log.spanContext?.traceFlags, + traceId: encoder.encodeOptionalSpanContext(log.spanContext?.traceId), + spanId: encoder.encodeOptionalSpanContext(log.spanContext?.spanId), + }; +} +function toSeverityNumber(severityNumber) { + return severityNumber; +} +function toLogAttributes(attributes) { + return Object.keys(attributes).map(key => (0, internal_1.toKeyValue)(key, attributes[key])); +} +exports.toLogAttributes = toLogAttributes; +//# sourceMappingURL=internal.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/json/index.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/json/index.js new file mode 100644 index 00000000..80688f86 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/json/index.js @@ -0,0 +1,22 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.JsonLogsSerializer = void 0; +// IMPORTANT: exports added here are public +var logs_1 = require("./logs"); +Object.defineProperty(exports, "JsonLogsSerializer", { enumerable: true, get: function () { return logs_1.JsonLogsSerializer; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/json/logs.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/json/logs.js new file mode 100644 index 00000000..36c3e6d4 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/json/logs.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.JsonLogsSerializer = void 0; +const internal_1 = require("../internal"); +/* + * @experimental this serializer may receive breaking changes in minor versions, pin this package's version when using this constant + */ +exports.JsonLogsSerializer = { + serializeRequest: (arg) => { + const request = (0, internal_1.createExportLogsServiceRequest)(arg, { + useHex: true, + useLongBits: false, + }); + const encoder = new TextEncoder(); + return encoder.encode(JSON.stringify(request)); + }, + deserializeResponse: (arg) => { + if (arg.length === 0) { + return {}; + } + const decoder = new TextDecoder(); + return JSON.parse(decoder.decode(arg)); + }, +}; +//# sourceMappingURL=logs.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/protobuf/index.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/protobuf/index.js new file mode 100644 index 00000000..0bc6a597 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/protobuf/index.js @@ -0,0 +1,21 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ProtobufLogsSerializer = void 0; +var logs_1 = require("./logs"); +Object.defineProperty(exports, "ProtobufLogsSerializer", { enumerable: true, get: function () { return logs_1.ProtobufLogsSerializer; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/protobuf/logs.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/protobuf/logs.js new file mode 100644 index 00000000..afccb35c --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/protobuf/logs.js @@ -0,0 +1,37 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ProtobufLogsSerializer = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const root = require("../../generated/root"); +const internal_1 = require("../internal"); +const logsResponseType = root.opentelemetry.proto.collector.logs.v1 + .ExportLogsServiceResponse; +const logsRequestType = root.opentelemetry.proto.collector.logs.v1 + .ExportLogsServiceRequest; +/* + * @experimental this serializer may receive breaking changes in minor versions, pin this package's version when using this constant + */ +exports.ProtobufLogsSerializer = { + serializeRequest: (arg) => { + const request = (0, internal_1.createExportLogsServiceRequest)(arg); + return logsRequestType.encode(request).finish(); + }, + deserializeResponse: (arg) => { + return logsResponseType.decode(arg); + }, +}; +//# sourceMappingURL=logs.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/internal-types.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/internal-types.js new file mode 100644 index 00000000..b5bcaefb --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/internal-types.js @@ -0,0 +1,75 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EAggregationTemporality = void 0; +/** + * AggregationTemporality defines how a metric aggregator reports aggregated + * values. It describes how those values relate to the time interval over + * which they are aggregated. + */ +var EAggregationTemporality; +(function (EAggregationTemporality) { + /* UNSPECIFIED is the default AggregationTemporality, it MUST not be used. */ + EAggregationTemporality[EAggregationTemporality["AGGREGATION_TEMPORALITY_UNSPECIFIED"] = 0] = "AGGREGATION_TEMPORALITY_UNSPECIFIED"; + /** DELTA is an AggregationTemporality for a metric aggregator which reports + changes since last report time. Successive metrics contain aggregation of + values from continuous and non-overlapping intervals. + + The values for a DELTA metric are based only on the time interval + associated with one measurement cycle. There is no dependency on + previous measurements like is the case for CUMULATIVE metrics. + + For example, consider a system measuring the number of requests that + it receives and reports the sum of these requests every second as a + DELTA metric: + + 1. The system starts receiving at time=t_0. + 2. A request is received, the system measures 1 request. + 3. A request is received, the system measures 1 request. + 4. A request is received, the system measures 1 request. + 5. The 1 second collection cycle ends. A metric is exported for the + number of requests received over the interval of time t_0 to + t_0+1 with a value of 3. + 6. A request is received, the system measures 1 request. + 7. A request is received, the system measures 1 request. + 8. The 1 second collection cycle ends. A metric is exported for the + number of requests received over the interval of time t_0+1 to + t_0+2 with a value of 2. */ + EAggregationTemporality[EAggregationTemporality["AGGREGATION_TEMPORALITY_DELTA"] = 1] = "AGGREGATION_TEMPORALITY_DELTA"; + /** CUMULATIVE is an AggregationTemporality for a metric aggregator which + reports changes since a fixed start time. This means that current values + of a CUMULATIVE metric depend on all previous measurements since the + start time. Because of this, the sender is required to retain this state + in some form. If this state is lost or invalidated, the CUMULATIVE metric + values MUST be reset and a new fixed start time following the last + reported measurement time sent MUST be used. + + For example, consider a system measuring the number of requests that + it receives and reports the sum of these requests every second as a + CUMULATIVE metric: + + 1. The system starts receiving at time=t_0. + 2. A request is received, the system measures 1 request. + 3. A request is received, the system measures 1 request. + 4. A request is received, the system measures 1 request. + 5. The 1 second collection cycle ends. A metric is exported for the + number of requests received over the interval of time t_0 to + t_0+1 with a value of 3. + 6. A request is received, the system measures 1 request. + 7. A request is received, the system measures 1 request. + 8. The 1 second collection cycle ends. A metric is exported for the + number of requests received over the interval of time t_0 to + t_0+2 with a value of 5. + 9. The system experiences a fault and loses state. + 10. The system recovers and resumes receiving at time=t_1. + 11. A request is received, the system measures 1 request. + 12. The 1 second collection cycle ends. A metric is exported for the + number of requests received over the interval of time t_1 to + t_0+1 with a value of 1. + + Note: Even though, when reporting changes since last report time, using + CUMULATIVE is valid, it is not recommended. This may cause problems for + systems that do not use start_time to determine when the aggregation + value was reset (e.g. Prometheus). */ + EAggregationTemporality[EAggregationTemporality["AGGREGATION_TEMPORALITY_CUMULATIVE"] = 2] = "AGGREGATION_TEMPORALITY_CUMULATIVE"; +})(EAggregationTemporality = exports.EAggregationTemporality || (exports.EAggregationTemporality = {})); +//# sourceMappingURL=internal-types.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/internal.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/internal.js new file mode 100644 index 00000000..0192a262 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/internal.js @@ -0,0 +1,138 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createExportMetricsServiceRequest = exports.toMetric = exports.toScopeMetrics = exports.toResourceMetrics = void 0; +const api_1 = require("@opentelemetry/api"); +const sdk_metrics_1 = require("@opentelemetry/sdk-metrics"); +const internal_types_1 = require("./internal-types"); +const utils_1 = require("../common/utils"); +const internal_1 = require("../common/internal"); +function toResourceMetrics(resourceMetrics, options) { + const encoder = (0, utils_1.getOtlpEncoder)(options); + const processedResource = (0, internal_1.createResource)(resourceMetrics.resource); + return { + resource: processedResource, + schemaUrl: processedResource.schemaUrl, + scopeMetrics: toScopeMetrics(resourceMetrics.scopeMetrics, encoder), + }; +} +exports.toResourceMetrics = toResourceMetrics; +function toScopeMetrics(scopeMetrics, encoder) { + return Array.from(scopeMetrics.map(metrics => ({ + scope: (0, internal_1.createInstrumentationScope)(metrics.scope), + metrics: metrics.metrics.map(metricData => toMetric(metricData, encoder)), + schemaUrl: metrics.scope.schemaUrl, + }))); +} +exports.toScopeMetrics = toScopeMetrics; +function toMetric(metricData, encoder) { + const out = { + name: metricData.descriptor.name, + description: metricData.descriptor.description, + unit: metricData.descriptor.unit, + }; + const aggregationTemporality = toAggregationTemporality(metricData.aggregationTemporality); + switch (metricData.dataPointType) { + case sdk_metrics_1.DataPointType.SUM: + out.sum = { + aggregationTemporality, + isMonotonic: metricData.isMonotonic, + dataPoints: toSingularDataPoints(metricData, encoder), + }; + break; + case sdk_metrics_1.DataPointType.GAUGE: + out.gauge = { + dataPoints: toSingularDataPoints(metricData, encoder), + }; + break; + case sdk_metrics_1.DataPointType.HISTOGRAM: + out.histogram = { + aggregationTemporality, + dataPoints: toHistogramDataPoints(metricData, encoder), + }; + break; + case sdk_metrics_1.DataPointType.EXPONENTIAL_HISTOGRAM: + out.exponentialHistogram = { + aggregationTemporality, + dataPoints: toExponentialHistogramDataPoints(metricData, encoder), + }; + break; + } + return out; +} +exports.toMetric = toMetric; +function toSingularDataPoint(dataPoint, valueType, encoder) { + const out = { + attributes: (0, internal_1.toAttributes)(dataPoint.attributes), + startTimeUnixNano: encoder.encodeHrTime(dataPoint.startTime), + timeUnixNano: encoder.encodeHrTime(dataPoint.endTime), + }; + switch (valueType) { + case api_1.ValueType.INT: + out.asInt = dataPoint.value; + break; + case api_1.ValueType.DOUBLE: + out.asDouble = dataPoint.value; + break; + } + return out; +} +function toSingularDataPoints(metricData, encoder) { + return metricData.dataPoints.map(dataPoint => { + return toSingularDataPoint(dataPoint, metricData.descriptor.valueType, encoder); + }); +} +function toHistogramDataPoints(metricData, encoder) { + return metricData.dataPoints.map(dataPoint => { + const histogram = dataPoint.value; + return { + attributes: (0, internal_1.toAttributes)(dataPoint.attributes), + bucketCounts: histogram.buckets.counts, + explicitBounds: histogram.buckets.boundaries, + count: histogram.count, + sum: histogram.sum, + min: histogram.min, + max: histogram.max, + startTimeUnixNano: encoder.encodeHrTime(dataPoint.startTime), + timeUnixNano: encoder.encodeHrTime(dataPoint.endTime), + }; + }); +} +function toExponentialHistogramDataPoints(metricData, encoder) { + return metricData.dataPoints.map(dataPoint => { + const histogram = dataPoint.value; + return { + attributes: (0, internal_1.toAttributes)(dataPoint.attributes), + count: histogram.count, + min: histogram.min, + max: histogram.max, + sum: histogram.sum, + positive: { + offset: histogram.positive.offset, + bucketCounts: histogram.positive.bucketCounts, + }, + negative: { + offset: histogram.negative.offset, + bucketCounts: histogram.negative.bucketCounts, + }, + scale: histogram.scale, + zeroCount: histogram.zeroCount, + startTimeUnixNano: encoder.encodeHrTime(dataPoint.startTime), + timeUnixNano: encoder.encodeHrTime(dataPoint.endTime), + }; + }); +} +function toAggregationTemporality(temporality) { + switch (temporality) { + case sdk_metrics_1.AggregationTemporality.DELTA: + return internal_types_1.EAggregationTemporality.AGGREGATION_TEMPORALITY_DELTA; + case sdk_metrics_1.AggregationTemporality.CUMULATIVE: + return internal_types_1.EAggregationTemporality.AGGREGATION_TEMPORALITY_CUMULATIVE; + } +} +function createExportMetricsServiceRequest(resourceMetrics, options) { + return { + resourceMetrics: resourceMetrics.map(metrics => toResourceMetrics(metrics, options)), + }; +} +exports.createExportMetricsServiceRequest = createExportMetricsServiceRequest; +//# sourceMappingURL=internal.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/json/index.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/json/index.js new file mode 100644 index 00000000..40747ae8 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/json/index.js @@ -0,0 +1,22 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.JsonMetricsSerializer = void 0; +// IMPORTANT: exports added here are public +var metrics_1 = require("./metrics"); +Object.defineProperty(exports, "JsonMetricsSerializer", { enumerable: true, get: function () { return metrics_1.JsonMetricsSerializer; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/json/metrics.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/json/metrics.js new file mode 100644 index 00000000..e97feb9b --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/json/metrics.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.JsonMetricsSerializer = void 0; +const internal_1 = require("../internal"); +exports.JsonMetricsSerializer = { + serializeRequest: (arg) => { + const request = (0, internal_1.createExportMetricsServiceRequest)([arg], { + useLongBits: false, + }); + const encoder = new TextEncoder(); + return encoder.encode(JSON.stringify(request)); + }, + deserializeResponse: (arg) => { + if (arg.length === 0) { + return {}; + } + const decoder = new TextDecoder(); + return JSON.parse(decoder.decode(arg)); + }, +}; +//# sourceMappingURL=metrics.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/protobuf/index.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/protobuf/index.js new file mode 100644 index 00000000..54a2467d --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/protobuf/index.js @@ -0,0 +1,22 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ProtobufMetricsSerializer = void 0; +// IMPORTANT: exports added here are public +var metrics_1 = require("./metrics"); +Object.defineProperty(exports, "ProtobufMetricsSerializer", { enumerable: true, get: function () { return metrics_1.ProtobufMetricsSerializer; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/protobuf/metrics.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/protobuf/metrics.js new file mode 100644 index 00000000..5b5ea249 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/protobuf/metrics.js @@ -0,0 +1,34 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ProtobufMetricsSerializer = void 0; +const root = require("../../generated/root"); +const internal_1 = require("../internal"); +const metricsResponseType = root.opentelemetry.proto.collector.metrics.v1 + .ExportMetricsServiceResponse; +const metricsRequestType = root.opentelemetry.proto.collector.metrics.v1 + .ExportMetricsServiceRequest; +exports.ProtobufMetricsSerializer = { + serializeRequest: (arg) => { + const request = (0, internal_1.createExportMetricsServiceRequest)([arg]); + return metricsRequestType.encode(request).finish(); + }, + deserializeResponse: (arg) => { + return metricsResponseType.decode(arg); + }, +}; +//# sourceMappingURL=metrics.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/internal.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/internal.js new file mode 100644 index 00000000..2737bb10 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/internal.js @@ -0,0 +1,148 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createExportTraceServiceRequest = exports.toOtlpSpanEvent = exports.toOtlpLink = exports.sdkSpanToOtlpSpan = void 0; +const internal_1 = require("../common/internal"); +const utils_1 = require("../common/utils"); +// Span flags constants matching the OTLP specification +const SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK = 0x100; +const SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK = 0x200; +/** + * Builds the 32-bit span flags value combining the low 8-bit W3C TraceFlags + * with the HAS_IS_REMOTE and IS_REMOTE bits according to the OTLP spec. + */ +function buildSpanFlagsFrom(traceFlags, isRemote) { + // low 8 bits are W3C TraceFlags (e.g., sampled) + let flags = (traceFlags & 0xff) | SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK; + if (isRemote) { + flags |= SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK; + } + return flags; +} +function sdkSpanToOtlpSpan(span, encoder) { + const ctx = span.spanContext(); + const status = span.status; + const parentSpanId = span.parentSpanContext?.spanId + ? encoder.encodeSpanContext(span.parentSpanContext?.spanId) + : undefined; + return { + traceId: encoder.encodeSpanContext(ctx.traceId), + spanId: encoder.encodeSpanContext(ctx.spanId), + parentSpanId: parentSpanId, + traceState: ctx.traceState?.serialize(), + name: span.name, + // Span kind is offset by 1 because the API does not define a value for unset + kind: span.kind == null ? 0 : span.kind + 1, + startTimeUnixNano: encoder.encodeHrTime(span.startTime), + endTimeUnixNano: encoder.encodeHrTime(span.endTime), + attributes: (0, internal_1.toAttributes)(span.attributes), + droppedAttributesCount: span.droppedAttributesCount, + events: span.events.map(event => toOtlpSpanEvent(event, encoder)), + droppedEventsCount: span.droppedEventsCount, + status: { + // API and proto enums share the same values + code: status.code, + message: status.message, + }, + links: span.links.map(link => toOtlpLink(link, encoder)), + droppedLinksCount: span.droppedLinksCount, + flags: buildSpanFlagsFrom(ctx.traceFlags, span.parentSpanContext?.isRemote), + }; +} +exports.sdkSpanToOtlpSpan = sdkSpanToOtlpSpan; +function toOtlpLink(link, encoder) { + return { + attributes: link.attributes ? (0, internal_1.toAttributes)(link.attributes) : [], + spanId: encoder.encodeSpanContext(link.context.spanId), + traceId: encoder.encodeSpanContext(link.context.traceId), + traceState: link.context.traceState?.serialize(), + droppedAttributesCount: link.droppedAttributesCount || 0, + flags: buildSpanFlagsFrom(link.context.traceFlags, link.context.isRemote), + }; +} +exports.toOtlpLink = toOtlpLink; +function toOtlpSpanEvent(timedEvent, encoder) { + return { + attributes: timedEvent.attributes + ? (0, internal_1.toAttributes)(timedEvent.attributes) + : [], + name: timedEvent.name, + timeUnixNano: encoder.encodeHrTime(timedEvent.time), + droppedAttributesCount: timedEvent.droppedAttributesCount || 0, + }; +} +exports.toOtlpSpanEvent = toOtlpSpanEvent; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function createExportTraceServiceRequest(spans, options) { + const encoder = (0, utils_1.getOtlpEncoder)(options); + return { + resourceSpans: spanRecordsToResourceSpans(spans, encoder), + }; +} +exports.createExportTraceServiceRequest = createExportTraceServiceRequest; +function createResourceMap(readableSpans) { + const resourceMap = new Map(); + for (const record of readableSpans) { + let ilsMap = resourceMap.get(record.resource); + if (!ilsMap) { + ilsMap = new Map(); + resourceMap.set(record.resource, ilsMap); + } + // TODO this is duplicated in basic tracer. Consolidate on a common helper in core + const instrumentationScopeKey = `${record.instrumentationScope.name}@${record.instrumentationScope.version || ''}:${record.instrumentationScope.schemaUrl || ''}`; + let records = ilsMap.get(instrumentationScopeKey); + if (!records) { + records = []; + ilsMap.set(instrumentationScopeKey, records); + } + records.push(record); + } + return resourceMap; +} +function spanRecordsToResourceSpans(readableSpans, encoder) { + const resourceMap = createResourceMap(readableSpans); + const out = []; + const entryIterator = resourceMap.entries(); + let entry = entryIterator.next(); + while (!entry.done) { + const [resource, ilmMap] = entry.value; + const scopeResourceSpans = []; + const ilmIterator = ilmMap.values(); + let ilmEntry = ilmIterator.next(); + while (!ilmEntry.done) { + const scopeSpans = ilmEntry.value; + if (scopeSpans.length > 0) { + const spans = scopeSpans.map(readableSpan => sdkSpanToOtlpSpan(readableSpan, encoder)); + scopeResourceSpans.push({ + scope: (0, internal_1.createInstrumentationScope)(scopeSpans[0].instrumentationScope), + spans: spans, + schemaUrl: scopeSpans[0].instrumentationScope.schemaUrl, + }); + } + ilmEntry = ilmIterator.next(); + } + const processedResource = (0, internal_1.createResource)(resource); + const transformedSpans = { + resource: processedResource, + scopeSpans: scopeResourceSpans, + schemaUrl: processedResource.schemaUrl, + }; + out.push(transformedSpans); + entry = entryIterator.next(); + } + return out; +} +//# sourceMappingURL=internal.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/json/index.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/json/index.js new file mode 100644 index 00000000..2dcfdbc4 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/json/index.js @@ -0,0 +1,22 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.JsonTraceSerializer = void 0; +// IMPORTANT: exports added here are public +var trace_1 = require("./trace"); +Object.defineProperty(exports, "JsonTraceSerializer", { enumerable: true, get: function () { return trace_1.JsonTraceSerializer; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/json/trace.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/json/trace.js new file mode 100644 index 00000000..490c8248 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/json/trace.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.JsonTraceSerializer = void 0; +const internal_1 = require("../internal"); +exports.JsonTraceSerializer = { + serializeRequest: (arg) => { + const request = (0, internal_1.createExportTraceServiceRequest)(arg, { + useHex: true, + useLongBits: false, + }); + const encoder = new TextEncoder(); + return encoder.encode(JSON.stringify(request)); + }, + deserializeResponse: (arg) => { + if (arg.length === 0) { + return {}; + } + const decoder = new TextDecoder(); + return JSON.parse(decoder.decode(arg)); + }, +}; +//# sourceMappingURL=trace.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/protobuf/index.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/protobuf/index.js new file mode 100644 index 00000000..cd1baa1b --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/protobuf/index.js @@ -0,0 +1,22 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ProtobufTraceSerializer = void 0; +// IMPORTANT: exports added here are public +var trace_1 = require("./trace"); +Object.defineProperty(exports, "ProtobufTraceSerializer", { enumerable: true, get: function () { return trace_1.ProtobufTraceSerializer; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/protobuf/trace.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/protobuf/trace.js new file mode 100644 index 00000000..f4b79ddd --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/protobuf/trace.js @@ -0,0 +1,34 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ProtobufTraceSerializer = void 0; +const root = require("../../generated/root"); +const internal_1 = require("../internal"); +const traceResponseType = root.opentelemetry.proto.collector.trace.v1 + .ExportTraceServiceResponse; +const traceRequestType = root.opentelemetry.proto.collector.trace.v1 + .ExportTraceServiceRequest; +exports.ProtobufTraceSerializer = { + serializeRequest: (arg) => { + const request = (0, internal_1.createExportTraceServiceRequest)(arg); + return traceRequestType.encode(request).finish(); + }, + deserializeResponse: (arg) => { + return traceResponseType.decode(arg); + }, +}; +//# sourceMappingURL=trace.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/ResourceImpl.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/ResourceImpl.js new file mode 100644 index 00000000..378ce6b5 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/resources/build/src/ResourceImpl.js @@ -0,0 +1,167 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defaultResource = exports.emptyResource = exports.resourceFromDetectedResource = exports.resourceFromAttributes = void 0; +const api_1 = require("@opentelemetry/api"); +const core_1 = require("@opentelemetry/core"); +const semantic_conventions_1 = require("@opentelemetry/semantic-conventions"); +const platform_1 = require("./platform"); +const utils_1 = require("./utils"); +class ResourceImpl { + _rawAttributes; + _asyncAttributesPending = false; + _schemaUrl; + _memoizedAttributes; + static FromAttributeList(attributes, options) { + const res = new ResourceImpl({}, options); + res._rawAttributes = guardedRawAttributes(attributes); + res._asyncAttributesPending = + attributes.filter(([_, val]) => (0, utils_1.isPromiseLike)(val)).length > 0; + return res; + } + constructor( + /** + * A dictionary of attributes with string keys and values that provide + * information about the entity as numbers, strings or booleans + * TODO: Consider to add check/validation on attributes. + */ + resource, options) { + const attributes = resource.attributes ?? {}; + this._rawAttributes = Object.entries(attributes).map(([k, v]) => { + if ((0, utils_1.isPromiseLike)(v)) { + // side-effect + this._asyncAttributesPending = true; + } + return [k, v]; + }); + this._rawAttributes = guardedRawAttributes(this._rawAttributes); + this._schemaUrl = validateSchemaUrl(options?.schemaUrl); + } + get asyncAttributesPending() { + return this._asyncAttributesPending; + } + async waitForAsyncAttributes() { + if (!this.asyncAttributesPending) { + return; + } + for (let i = 0; i < this._rawAttributes.length; i++) { + const [k, v] = this._rawAttributes[i]; + this._rawAttributes[i] = [k, (0, utils_1.isPromiseLike)(v) ? await v : v]; + } + this._asyncAttributesPending = false; + } + get attributes() { + if (this.asyncAttributesPending) { + api_1.diag.error('Accessing resource attributes before async attributes settled'); + } + if (this._memoizedAttributes) { + return this._memoizedAttributes; + } + const attrs = {}; + for (const [k, v] of this._rawAttributes) { + if ((0, utils_1.isPromiseLike)(v)) { + api_1.diag.debug(`Unsettled resource attribute ${k} skipped`); + continue; + } + if (v != null) { + attrs[k] ??= v; + } + } + // only memoize output if all attributes are settled + if (!this._asyncAttributesPending) { + this._memoizedAttributes = attrs; + } + return attrs; + } + getRawAttributes() { + return this._rawAttributes; + } + get schemaUrl() { + return this._schemaUrl; + } + merge(resource) { + if (resource == null) + return this; + // Order is important + // Spec states incoming attributes override existing attributes + const mergedSchemaUrl = mergeSchemaUrl(this, resource); + const mergedOptions = mergedSchemaUrl + ? { schemaUrl: mergedSchemaUrl } + : undefined; + return ResourceImpl.FromAttributeList([...resource.getRawAttributes(), ...this.getRawAttributes()], mergedOptions); + } +} +function resourceFromAttributes(attributes, options) { + return ResourceImpl.FromAttributeList(Object.entries(attributes), options); +} +exports.resourceFromAttributes = resourceFromAttributes; +function resourceFromDetectedResource(detectedResource, options) { + return new ResourceImpl(detectedResource, options); +} +exports.resourceFromDetectedResource = resourceFromDetectedResource; +function emptyResource() { + return resourceFromAttributes({}); +} +exports.emptyResource = emptyResource; +function defaultResource() { + return resourceFromAttributes({ + [semantic_conventions_1.ATTR_SERVICE_NAME]: (0, platform_1.defaultServiceName)(), + [semantic_conventions_1.ATTR_TELEMETRY_SDK_LANGUAGE]: core_1.SDK_INFO[semantic_conventions_1.ATTR_TELEMETRY_SDK_LANGUAGE], + [semantic_conventions_1.ATTR_TELEMETRY_SDK_NAME]: core_1.SDK_INFO[semantic_conventions_1.ATTR_TELEMETRY_SDK_NAME], + [semantic_conventions_1.ATTR_TELEMETRY_SDK_VERSION]: core_1.SDK_INFO[semantic_conventions_1.ATTR_TELEMETRY_SDK_VERSION], + }); +} +exports.defaultResource = defaultResource; +function guardedRawAttributes(attributes) { + return attributes.map(([k, v]) => { + if ((0, utils_1.isPromiseLike)(v)) { + return [ + k, + v.catch(err => { + api_1.diag.debug('promise rejection for resource attribute: %s - %s', k, err); + return undefined; + }), + ]; + } + return [k, v]; + }); +} +function validateSchemaUrl(schemaUrl) { + if (typeof schemaUrl === 'string' || schemaUrl === undefined) { + return schemaUrl; + } + api_1.diag.warn('Schema URL must be string or undefined, got %s. Schema URL will be ignored.', schemaUrl); + return undefined; +} +function mergeSchemaUrl(old, updating) { + const oldSchemaUrl = old?.schemaUrl; + const updatingSchemaUrl = updating?.schemaUrl; + const isOldEmpty = oldSchemaUrl === undefined || oldSchemaUrl === ''; + const isUpdatingEmpty = updatingSchemaUrl === undefined || updatingSchemaUrl === ''; + if (isOldEmpty) { + return updatingSchemaUrl; + } + if (isUpdatingEmpty) { + return oldSchemaUrl; + } + if (oldSchemaUrl === updatingSchemaUrl) { + return oldSchemaUrl; + } + api_1.diag.warn('Schema URL merge conflict: old resource has "%s", updating resource has "%s". Resulting resource will have undefined Schema URL.', oldSchemaUrl, updatingSchemaUrl); + return undefined; +} +//# sourceMappingURL=ResourceImpl.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detect-resources.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detect-resources.js new file mode 100644 index 00000000..0e9d28db --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detect-resources.js @@ -0,0 +1,41 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.detectResources = void 0; +const api_1 = require("@opentelemetry/api"); +const ResourceImpl_1 = require("./ResourceImpl"); +/** + * Runs all resource detectors and returns the results merged into a single Resource. + * + * @param config Configuration for resource detection + */ +const detectResources = (config = {}) => { + const resources = (config.detectors || []).map(d => { + try { + const resource = (0, ResourceImpl_1.resourceFromDetectedResource)(d.detect(config)); + api_1.diag.debug(`${d.constructor.name} found resource.`, resource); + return resource; + } + catch (e) { + api_1.diag.debug(`${d.constructor.name} failed: ${e.message}`); + return (0, ResourceImpl_1.emptyResource)(); + } + }); + return resources.reduce((acc, resource) => acc.merge(resource), (0, ResourceImpl_1.emptyResource)()); +}; +exports.detectResources = detectResources; +//# sourceMappingURL=detect-resources.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/EnvDetector.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/EnvDetector.js new file mode 100644 index 00000000..d88be5c9 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/EnvDetector.js @@ -0,0 +1,134 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.envDetector = void 0; +const api_1 = require("@opentelemetry/api"); +const semantic_conventions_1 = require("@opentelemetry/semantic-conventions"); +const core_1 = require("@opentelemetry/core"); +/** + * EnvDetector can be used to detect the presence of and create a Resource + * from the OTEL_RESOURCE_ATTRIBUTES environment variable. + */ +class EnvDetector { + // Type, attribute keys, and attribute values should not exceed 256 characters. + _MAX_LENGTH = 255; + // OTEL_RESOURCE_ATTRIBUTES is a comma-separated list of attributes. + _COMMA_SEPARATOR = ','; + // OTEL_RESOURCE_ATTRIBUTES contains key value pair separated by '='. + _LABEL_KEY_VALUE_SPLITTER = '='; + _ERROR_MESSAGE_INVALID_CHARS = 'should be a ASCII string with a length greater than 0 and not exceed ' + + this._MAX_LENGTH + + ' characters.'; + _ERROR_MESSAGE_INVALID_VALUE = 'should be a ASCII string with a length not exceed ' + + this._MAX_LENGTH + + ' characters.'; + /** + * Returns a {@link Resource} populated with attributes from the + * OTEL_RESOURCE_ATTRIBUTES environment variable. Note this is an async + * function to conform to the Detector interface. + * + * @param config The resource detection config + */ + detect(_config) { + const attributes = {}; + const rawAttributes = (0, core_1.getStringFromEnv)('OTEL_RESOURCE_ATTRIBUTES'); + const serviceName = (0, core_1.getStringFromEnv)('OTEL_SERVICE_NAME'); + if (rawAttributes) { + try { + const parsedAttributes = this._parseResourceAttributes(rawAttributes); + Object.assign(attributes, parsedAttributes); + } + catch (e) { + api_1.diag.debug(`EnvDetector failed: ${e.message}`); + } + } + if (serviceName) { + attributes[semantic_conventions_1.ATTR_SERVICE_NAME] = serviceName; + } + return { attributes }; + } + /** + * Creates an attribute map from the OTEL_RESOURCE_ATTRIBUTES environment + * variable. + * + * OTEL_RESOURCE_ATTRIBUTES: A comma-separated list of attributes describing + * the source in more detail, e.g. “key1=val1,key2=val2”. Domain names and + * paths are accepted as attribute keys. Values may be quoted or unquoted in + * general. If a value contains whitespace, =, or " characters, it must + * always be quoted. + * + * @param rawEnvAttributes The resource attributes as a comma-separated list + * of key/value pairs. + * @returns The sanitized resource attributes. + */ + _parseResourceAttributes(rawEnvAttributes) { + if (!rawEnvAttributes) + return {}; + const attributes = {}; + const rawAttributes = rawEnvAttributes.split(this._COMMA_SEPARATOR, -1); + for (const rawAttribute of rawAttributes) { + const keyValuePair = rawAttribute.split(this._LABEL_KEY_VALUE_SPLITTER, -1); + if (keyValuePair.length !== 2) { + continue; + } + let [key, value] = keyValuePair; + // Leading and trailing whitespaces are trimmed. + key = key.trim(); + value = value.trim().split(/^"|"$/).join(''); + if (!this._isValidAndNotEmpty(key)) { + throw new Error(`Attribute key ${this._ERROR_MESSAGE_INVALID_CHARS}`); + } + if (!this._isValid(value)) { + throw new Error(`Attribute value ${this._ERROR_MESSAGE_INVALID_VALUE}`); + } + attributes[key] = decodeURIComponent(value); + } + return attributes; + } + /** + * Determines whether the given String is a valid printable ASCII string with + * a length not exceed _MAX_LENGTH characters. + * + * @param str The String to be validated. + * @returns Whether the String is valid. + */ + _isValid(name) { + return name.length <= this._MAX_LENGTH && this._isBaggageOctetString(name); + } + // https://www.w3.org/TR/baggage/#definition + _isBaggageOctetString(str) { + for (let i = 0; i < str.length; i++) { + const ch = str.charCodeAt(i); + if (ch < 0x21 || ch === 0x2c || ch === 0x3b || ch === 0x5c || ch > 0x7e) { + return false; + } + } + return true; + } + /** + * Determines whether the given String is a valid printable ASCII string with + * a length greater than 0 and not exceed _MAX_LENGTH characters. + * + * @param str The String to be validated. + * @returns Whether the String is valid and not empty. + */ + _isValidAndNotEmpty(str) { + return str.length > 0 && this._isValid(str); + } +} +exports.envDetector = new EnvDetector(); +//# sourceMappingURL=EnvDetector.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/NoopDetector.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/NoopDetector.js new file mode 100644 index 00000000..eb2cd7df --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/NoopDetector.js @@ -0,0 +1,28 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.noopDetector = exports.NoopDetector = void 0; +class NoopDetector { + detect() { + return { + attributes: {}, + }; + } +} +exports.NoopDetector = NoopDetector; +exports.noopDetector = new NoopDetector(); +//# sourceMappingURL=NoopDetector.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/index.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/index.js new file mode 100644 index 00000000..73da00da --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/index.js @@ -0,0 +1,28 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.noopDetector = exports.serviceInstanceIdDetector = exports.processDetector = exports.osDetector = exports.hostDetector = exports.envDetector = void 0; +var EnvDetector_1 = require("./EnvDetector"); +Object.defineProperty(exports, "envDetector", { enumerable: true, get: function () { return EnvDetector_1.envDetector; } }); +var platform_1 = require("./platform"); +Object.defineProperty(exports, "hostDetector", { enumerable: true, get: function () { return platform_1.hostDetector; } }); +Object.defineProperty(exports, "osDetector", { enumerable: true, get: function () { return platform_1.osDetector; } }); +Object.defineProperty(exports, "processDetector", { enumerable: true, get: function () { return platform_1.processDetector; } }); +Object.defineProperty(exports, "serviceInstanceIdDetector", { enumerable: true, get: function () { return platform_1.serviceInstanceIdDetector; } }); +var NoopDetector_1 = require("./NoopDetector"); +Object.defineProperty(exports, "noopDetector", { enumerable: true, get: function () { return NoopDetector_1.noopDetector; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/index.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/index.js new file mode 100644 index 00000000..333c428d --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/index.js @@ -0,0 +1,24 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.serviceInstanceIdDetector = exports.processDetector = exports.osDetector = exports.hostDetector = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var node_1 = require("./node"); +Object.defineProperty(exports, "hostDetector", { enumerable: true, get: function () { return node_1.hostDetector; } }); +Object.defineProperty(exports, "osDetector", { enumerable: true, get: function () { return node_1.osDetector; } }); +Object.defineProperty(exports, "processDetector", { enumerable: true, get: function () { return node_1.processDetector; } }); +Object.defineProperty(exports, "serviceInstanceIdDetector", { enumerable: true, get: function () { return node_1.serviceInstanceIdDetector; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/HostDetector.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/HostDetector.js new file mode 100644 index 00000000..da3f41d9 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/HostDetector.js @@ -0,0 +1,38 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hostDetector = void 0; +const semconv_1 = require("../../../semconv"); +const os_1 = require("os"); +const getMachineId_1 = require("./machine-id/getMachineId"); +const utils_1 = require("./utils"); +/** + * HostDetector detects the resources related to the host current process is + * running on. Currently only non-cloud-based attributes are included. + */ +class HostDetector { + detect(_config) { + const attributes = { + [semconv_1.ATTR_HOST_NAME]: (0, os_1.hostname)(), + [semconv_1.ATTR_HOST_ARCH]: (0, utils_1.normalizeArch)((0, os_1.arch)()), + [semconv_1.ATTR_HOST_ID]: (0, getMachineId_1.getMachineId)(), + }; + return { attributes }; + } +} +exports.hostDetector = new HostDetector(); +//# sourceMappingURL=HostDetector.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/OSDetector.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/OSDetector.js new file mode 100644 index 00000000..2af15dc4 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/OSDetector.js @@ -0,0 +1,36 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.osDetector = void 0; +const semconv_1 = require("../../../semconv"); +const os_1 = require("os"); +const utils_1 = require("./utils"); +/** + * OSDetector detects the resources related to the operating system (OS) on + * which the process represented by this resource is running. + */ +class OSDetector { + detect(_config) { + const attributes = { + [semconv_1.ATTR_OS_TYPE]: (0, utils_1.normalizeType)((0, os_1.platform)()), + [semconv_1.ATTR_OS_VERSION]: (0, os_1.release)(), + }; + return { attributes }; + } +} +exports.osDetector = new OSDetector(); +//# sourceMappingURL=OSDetector.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/ProcessDetector.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/ProcessDetector.js new file mode 100644 index 00000000..32c3aaa3 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/ProcessDetector.js @@ -0,0 +1,55 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.processDetector = void 0; +const api_1 = require("@opentelemetry/api"); +const semconv_1 = require("../../../semconv"); +const os = require("os"); +/** + * ProcessDetector will be used to detect the resources related current process running + * and being instrumented from the NodeJS Process module. + */ +class ProcessDetector { + detect(_config) { + const attributes = { + [semconv_1.ATTR_PROCESS_PID]: process.pid, + [semconv_1.ATTR_PROCESS_EXECUTABLE_NAME]: process.title, + [semconv_1.ATTR_PROCESS_EXECUTABLE_PATH]: process.execPath, + [semconv_1.ATTR_PROCESS_COMMAND_ARGS]: [ + process.argv[0], + ...process.execArgv, + ...process.argv.slice(1), + ], + [semconv_1.ATTR_PROCESS_RUNTIME_VERSION]: process.versions.node, + [semconv_1.ATTR_PROCESS_RUNTIME_NAME]: 'nodejs', + [semconv_1.ATTR_PROCESS_RUNTIME_DESCRIPTION]: 'Node.js', + }; + if (process.argv.length > 1) { + attributes[semconv_1.ATTR_PROCESS_COMMAND] = process.argv[1]; + } + try { + const userInfo = os.userInfo(); + attributes[semconv_1.ATTR_PROCESS_OWNER] = userInfo.username; + } + catch (e) { + api_1.diag.debug(`error obtaining process owner: ${e}`); + } + return { attributes }; + } +} +exports.processDetector = new ProcessDetector(); +//# sourceMappingURL=ProcessDetector.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/ServiceInstanceIdDetector.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/ServiceInstanceIdDetector.js new file mode 100644 index 00000000..c849fe4c --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/ServiceInstanceIdDetector.js @@ -0,0 +1,37 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.serviceInstanceIdDetector = void 0; +const semconv_1 = require("../../../semconv"); +const crypto_1 = require("crypto"); +/** + * ServiceInstanceIdDetector detects the resources related to the service instance ID. + */ +class ServiceInstanceIdDetector { + detect(_config) { + return { + attributes: { + [semconv_1.ATTR_SERVICE_INSTANCE_ID]: (0, crypto_1.randomUUID)(), + }, + }; + } +} +/** + * @experimental + */ +exports.serviceInstanceIdDetector = new ServiceInstanceIdDetector(); +//# sourceMappingURL=ServiceInstanceIdDetector.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/index.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/index.js new file mode 100644 index 00000000..9fc4c70e --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/index.js @@ -0,0 +1,27 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.serviceInstanceIdDetector = exports.processDetector = exports.osDetector = exports.hostDetector = void 0; +var HostDetector_1 = require("./HostDetector"); +Object.defineProperty(exports, "hostDetector", { enumerable: true, get: function () { return HostDetector_1.hostDetector; } }); +var OSDetector_1 = require("./OSDetector"); +Object.defineProperty(exports, "osDetector", { enumerable: true, get: function () { return OSDetector_1.osDetector; } }); +var ProcessDetector_1 = require("./ProcessDetector"); +Object.defineProperty(exports, "processDetector", { enumerable: true, get: function () { return ProcessDetector_1.processDetector; } }); +var ServiceInstanceIdDetector_1 = require("./ServiceInstanceIdDetector"); +Object.defineProperty(exports, "serviceInstanceIdDetector", { enumerable: true, get: function () { return ServiceInstanceIdDetector_1.serviceInstanceIdDetector; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/execAsync.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/execAsync.js new file mode 100644 index 00000000..6688a2a0 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/execAsync.js @@ -0,0 +1,22 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.execAsync = void 0; +const child_process = require("child_process"); +const util = require("util"); +exports.execAsync = util.promisify(child_process.exec); +//# sourceMappingURL=execAsync.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-bsd.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-bsd.js new file mode 100644 index 00000000..282aa321 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-bsd.js @@ -0,0 +1,40 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getMachineId = void 0; +const fs_1 = require("fs"); +const execAsync_1 = require("./execAsync"); +const api_1 = require("@opentelemetry/api"); +async function getMachineId() { + try { + const result = await fs_1.promises.readFile('/etc/hostid', { encoding: 'utf8' }); + return result.trim(); + } + catch (e) { + api_1.diag.debug(`error reading machine id: ${e}`); + } + try { + const result = await (0, execAsync_1.execAsync)('kenv -q smbios.system.uuid'); + return result.stdout.trim(); + } + catch (e) { + api_1.diag.debug(`error reading machine id: ${e}`); + } + return undefined; +} +exports.getMachineId = getMachineId; +//# sourceMappingURL=getMachineId-bsd.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-darwin.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-darwin.js new file mode 100644 index 00000000..143945e6 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-darwin.js @@ -0,0 +1,41 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getMachineId = void 0; +const execAsync_1 = require("./execAsync"); +const api_1 = require("@opentelemetry/api"); +async function getMachineId() { + try { + const result = await (0, execAsync_1.execAsync)('ioreg -rd1 -c "IOPlatformExpertDevice"'); + const idLine = result.stdout + .split('\n') + .find(line => line.includes('IOPlatformUUID')); + if (!idLine) { + return undefined; + } + const parts = idLine.split('" = "'); + if (parts.length === 2) { + return parts[1].slice(0, -1); + } + } + catch (e) { + api_1.diag.debug(`error reading machine id: ${e}`); + } + return undefined; +} +exports.getMachineId = getMachineId; +//# sourceMappingURL=getMachineId-darwin.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-linux.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-linux.js new file mode 100644 index 00000000..8214dd37 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-linux.js @@ -0,0 +1,35 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getMachineId = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const fs_1 = require("fs"); +const api_1 = require("@opentelemetry/api"); +async function getMachineId() { + const paths = ['/etc/machine-id', '/var/lib/dbus/machine-id']; + for (const path of paths) { + try { + const result = await fs_1.promises.readFile(path, { encoding: 'utf8' }); + return result.trim(); + } + catch (e) { + api_1.diag.debug(`error reading machine id: ${e}`); + } + } + return undefined; +} +exports.getMachineId = getMachineId; +//# sourceMappingURL=getMachineId-linux.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-unsupported.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-unsupported.js new file mode 100644 index 00000000..f68a1fa2 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-unsupported.js @@ -0,0 +1,25 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getMachineId = void 0; +const api_1 = require("@opentelemetry/api"); +async function getMachineId() { + api_1.diag.debug('could not read machine-id: unsupported platform'); + return undefined; +} +exports.getMachineId = getMachineId; +//# sourceMappingURL=getMachineId-unsupported.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-win.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-win.js new file mode 100644 index 00000000..1d3f784b --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-win.js @@ -0,0 +1,41 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getMachineId = void 0; +const process = require("process"); +const execAsync_1 = require("./execAsync"); +const api_1 = require("@opentelemetry/api"); +async function getMachineId() { + const args = 'QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid'; + let command = '%windir%\\System32\\REG.exe'; + if (process.arch === 'ia32' && 'PROCESSOR_ARCHITEW6432' in process.env) { + command = '%windir%\\sysnative\\cmd.exe /c ' + command; + } + try { + const result = await (0, execAsync_1.execAsync)(`${command} ${args}`); + const parts = result.stdout.split('REG_SZ'); + if (parts.length === 2) { + return parts[1].trim(); + } + } + catch (e) { + api_1.diag.debug(`error reading machine id: ${e}`); + } + return undefined; +} +exports.getMachineId = getMachineId; +//# sourceMappingURL=getMachineId-win.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId.js new file mode 100644 index 00000000..e10c3f9a --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId.js @@ -0,0 +1,47 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getMachineId = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const process = require("process"); +let getMachineIdImpl; +async function getMachineId() { + if (!getMachineIdImpl) { + switch (process.platform) { + case 'darwin': + getMachineIdImpl = (await import('./getMachineId-darwin.js')) + .getMachineId; + break; + case 'linux': + getMachineIdImpl = (await import('./getMachineId-linux.js')) + .getMachineId; + break; + case 'freebsd': + getMachineIdImpl = (await import('./getMachineId-bsd.js')).getMachineId; + break; + case 'win32': + getMachineIdImpl = (await import('./getMachineId-win.js')).getMachineId; + break; + default: + getMachineIdImpl = (await import('./getMachineId-unsupported.js')) + .getMachineId; + break; + } + } + return getMachineIdImpl(); +} +exports.getMachineId = getMachineId; +//# sourceMappingURL=getMachineId.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/utils.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/utils.js new file mode 100644 index 00000000..33675c98 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/utils.js @@ -0,0 +1,47 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.normalizeType = exports.normalizeArch = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const normalizeArch = (nodeArchString) => { + // Maps from https://nodejs.org/api/os.html#osarch to arch values in spec: + // https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/semantic_conventions/host.md + switch (nodeArchString) { + case 'arm': + return 'arm32'; + case 'ppc': + return 'ppc32'; + case 'x64': + return 'amd64'; + default: + return nodeArchString; + } +}; +exports.normalizeArch = normalizeArch; +const normalizeType = (nodePlatform) => { + // Maps from https://nodejs.org/api/os.html#osplatform to arch values in spec: + // https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/semantic_conventions/os.md + switch (nodePlatform) { + case 'sunos': + return 'solaris'; + case 'win32': + return 'windows'; + default: + return nodePlatform; + } +}; +exports.normalizeType = normalizeType; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/index.js new file mode 100644 index 00000000..11e3d56b --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/resources/build/src/index.js @@ -0,0 +1,33 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defaultServiceName = exports.emptyResource = exports.defaultResource = exports.resourceFromAttributes = exports.serviceInstanceIdDetector = exports.processDetector = exports.osDetector = exports.hostDetector = exports.envDetector = exports.detectResources = void 0; +var detect_resources_1 = require("./detect-resources"); +Object.defineProperty(exports, "detectResources", { enumerable: true, get: function () { return detect_resources_1.detectResources; } }); +var detectors_1 = require("./detectors"); +Object.defineProperty(exports, "envDetector", { enumerable: true, get: function () { return detectors_1.envDetector; } }); +Object.defineProperty(exports, "hostDetector", { enumerable: true, get: function () { return detectors_1.hostDetector; } }); +Object.defineProperty(exports, "osDetector", { enumerable: true, get: function () { return detectors_1.osDetector; } }); +Object.defineProperty(exports, "processDetector", { enumerable: true, get: function () { return detectors_1.processDetector; } }); +Object.defineProperty(exports, "serviceInstanceIdDetector", { enumerable: true, get: function () { return detectors_1.serviceInstanceIdDetector; } }); +var ResourceImpl_1 = require("./ResourceImpl"); +Object.defineProperty(exports, "resourceFromAttributes", { enumerable: true, get: function () { return ResourceImpl_1.resourceFromAttributes; } }); +Object.defineProperty(exports, "defaultResource", { enumerable: true, get: function () { return ResourceImpl_1.defaultResource; } }); +Object.defineProperty(exports, "emptyResource", { enumerable: true, get: function () { return ResourceImpl_1.emptyResource; } }); +var platform_1 = require("./platform"); +Object.defineProperty(exports, "defaultServiceName", { enumerable: true, get: function () { return platform_1.defaultServiceName; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/platform/index.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/platform/index.js new file mode 100644 index 00000000..50930322 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/resources/build/src/platform/index.js @@ -0,0 +1,21 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defaultServiceName = void 0; +var node_1 = require("./node"); +Object.defineProperty(exports, "defaultServiceName", { enumerable: true, get: function () { return node_1.defaultServiceName; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/platform/node/default-service-name.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/platform/node/default-service-name.js new file mode 100644 index 00000000..8b1f0d3f --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/resources/build/src/platform/node/default-service-name.js @@ -0,0 +1,23 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defaultServiceName = void 0; +function defaultServiceName() { + return `unknown_service:${process.argv0}`; +} +exports.defaultServiceName = defaultServiceName; +//# sourceMappingURL=default-service-name.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/platform/node/index.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/platform/node/index.js new file mode 100644 index 00000000..6f5a2814 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/resources/build/src/platform/node/index.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defaultServiceName = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var default_service_name_1 = require("./default-service-name"); +Object.defineProperty(exports, "defaultServiceName", { enumerable: true, get: function () { return default_service_name_1.defaultServiceName; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/semconv.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/semconv.js new file mode 100644 index 00000000..73c98da2 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/resources/build/src/semconv.js @@ -0,0 +1,335 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ATTR_WEBENGINE_VERSION = exports.ATTR_WEBENGINE_NAME = exports.ATTR_WEBENGINE_DESCRIPTION = exports.ATTR_SERVICE_NAMESPACE = exports.ATTR_SERVICE_INSTANCE_ID = exports.ATTR_PROCESS_RUNTIME_VERSION = exports.ATTR_PROCESS_RUNTIME_NAME = exports.ATTR_PROCESS_RUNTIME_DESCRIPTION = exports.ATTR_PROCESS_PID = exports.ATTR_PROCESS_OWNER = exports.ATTR_PROCESS_EXECUTABLE_PATH = exports.ATTR_PROCESS_EXECUTABLE_NAME = exports.ATTR_PROCESS_COMMAND_ARGS = exports.ATTR_PROCESS_COMMAND = exports.ATTR_OS_VERSION = exports.ATTR_OS_TYPE = exports.ATTR_K8S_POD_NAME = exports.ATTR_K8S_NAMESPACE_NAME = exports.ATTR_K8S_DEPLOYMENT_NAME = exports.ATTR_K8S_CLUSTER_NAME = exports.ATTR_HOST_TYPE = exports.ATTR_HOST_NAME = exports.ATTR_HOST_IMAGE_VERSION = exports.ATTR_HOST_IMAGE_NAME = exports.ATTR_HOST_IMAGE_ID = exports.ATTR_HOST_ID = exports.ATTR_HOST_ARCH = exports.ATTR_CONTAINER_NAME = exports.ATTR_CONTAINER_IMAGE_TAGS = exports.ATTR_CONTAINER_IMAGE_NAME = exports.ATTR_CONTAINER_ID = exports.ATTR_CLOUD_REGION = exports.ATTR_CLOUD_PROVIDER = exports.ATTR_CLOUD_AVAILABILITY_ZONE = exports.ATTR_CLOUD_ACCOUNT_ID = void 0; +/* + * This file contains a copy of unstable semantic convention definitions + * used by this package. + * @see https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions#unstable-semconv + */ +/** + * The cloud account ID the resource is assigned to. + * + * @example 111111111111 + * @example opentelemetry + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_CLOUD_ACCOUNT_ID = 'cloud.account.id'; +/** + * Cloud regions often have multiple, isolated locations known as zones to increase availability. Availability zone represents the zone where the resource is running. + * + * @example us-east-1c + * + * @note Availability zones are called "zones" on Alibaba Cloud and Google Cloud. + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_CLOUD_AVAILABILITY_ZONE = 'cloud.availability_zone'; +/** + * Name of the cloud provider. + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_CLOUD_PROVIDER = 'cloud.provider'; +/** + * The geographical region the resource is running. + * + * @example us-central1 + * @example us-east-1 + * + * @note Refer to your provider's docs to see the available regions, for example [Alibaba Cloud regions](https://www.alibabacloud.com/help/doc-detail/40654.htm), [AWS regions](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/), [Azure regions](https://azure.microsoft.com/global-infrastructure/geographies/), [Google Cloud regions](https://cloud.google.com/about/locations), or [Tencent Cloud regions](https://www.tencentcloud.com/document/product/213/6091). + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_CLOUD_REGION = 'cloud.region'; +/** + * Container ID. Usually a UUID, as for example used to [identify Docker containers](https://docs.docker.com/engine/containers/run/#container-identification). The UUID might be abbreviated. + * + * @example a3bf90e006b2 + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_CONTAINER_ID = 'container.id'; +/** + * Name of the image the container was built on. + * + * @example gcr.io/opentelemetry/operator + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_CONTAINER_IMAGE_NAME = 'container.image.name'; +/** + * Container image tags. An example can be found in [Docker Image Inspect](https://docs.docker.com/engine/api/v1.43/#tag/Image/operation/ImageInspect). Should be only the `` section of the full name for example from `registry.example.com/my-org/my-image:`. + * + * @example ["v1.27.1", "3.5.7-0"] + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_CONTAINER_IMAGE_TAGS = 'container.image.tags'; +/** + * Container name used by container runtime. + * + * @example opentelemetry-autoconf + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_CONTAINER_NAME = 'container.name'; +/** + * The CPU architecture the host system is running on. + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_HOST_ARCH = 'host.arch'; +/** + * Unique host ID. For Cloud, this must be the instance_id assigned by the cloud provider. For non-containerized systems, this should be the `machine-id`. See the table below for the sources to use to determine the `machine-id` based on operating system. + * + * @example fdbf79e8af94cb7f9e8df36789187052 + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_HOST_ID = 'host.id'; +/** + * VM image ID or host OS image ID. For Cloud, this value is from the provider. + * + * @example ami-07b06b442921831e5 + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_HOST_IMAGE_ID = 'host.image.id'; +/** + * Name of the VM image or OS install the host was instantiated from. + * + * @example infra-ami-eks-worker-node-7d4ec78312 + * @example CentOS-8-x86_64-1905 + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_HOST_IMAGE_NAME = 'host.image.name'; +/** + * The version string of the VM image or host OS as defined in [Version Attributes](/docs/resource/README.md#version-attributes). + * + * @example 0.1 + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_HOST_IMAGE_VERSION = 'host.image.version'; +/** + * Name of the host. On Unix systems, it may contain what the hostname command returns, or the fully qualified hostname, or another name specified by the user. + * + * @example opentelemetry-test + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_HOST_NAME = 'host.name'; +/** + * Type of host. For Cloud, this must be the machine type. + * + * @example n1-standard-1 + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_HOST_TYPE = 'host.type'; +/** + * The name of the cluster. + * + * @example opentelemetry-cluster + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_K8S_CLUSTER_NAME = 'k8s.cluster.name'; +/** + * The name of the Deployment. + * + * @example opentelemetry + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_K8S_DEPLOYMENT_NAME = 'k8s.deployment.name'; +/** + * The name of the namespace that the pod is running in. + * + * @example default + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_K8S_NAMESPACE_NAME = 'k8s.namespace.name'; +/** + * The name of the Pod. + * + * @example opentelemetry-pod-autoconf + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_K8S_POD_NAME = 'k8s.pod.name'; +/** + * The operating system type. + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_OS_TYPE = 'os.type'; +/** + * The version string of the operating system as defined in [Version Attributes](/docs/resource/README.md#version-attributes). + * + * @example 14.2.1 + * @example 18.04.1 + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_OS_VERSION = 'os.version'; +/** + * The command used to launch the process (i.e. the command name). On Linux based systems, can be set to the zeroth string in `proc/[pid]/cmdline`. On Windows, can be set to the first parameter extracted from `GetCommandLineW`. + * + * @example cmd/otelcol + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_PROCESS_COMMAND = 'process.command'; +/** + * All the command arguments (including the command/executable itself) as received by the process. On Linux-based systems (and some other Unixoid systems supporting procfs), can be set according to the list of null-delimited strings extracted from `proc/[pid]/cmdline`. For libc-based executables, this would be the full argv vector passed to `main`. + * + * @example ["cmd/otecol", "--config=config.yaml"] + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_PROCESS_COMMAND_ARGS = 'process.command_args'; +/** + * The name of the process executable. On Linux based systems, this **SHOULD** be set to the base name of the target of `/proc/[pid]/exe`. On Windows, this **SHOULD** be set to the base name of `GetProcessImageFileNameW`. + * + * @example otelcol + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_PROCESS_EXECUTABLE_NAME = 'process.executable.name'; +/** + * The full path to the process executable. On Linux based systems, can be set to the target of `proc/[pid]/exe`. On Windows, can be set to the result of `GetProcessImageFileNameW`. + * + * @example /usr/bin/cmd/otelcol + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_PROCESS_EXECUTABLE_PATH = 'process.executable.path'; +/** + * The username of the user that owns the process. + * + * @example root + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_PROCESS_OWNER = 'process.owner'; +/** + * Process identifier (PID). + * + * @example 1234 + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_PROCESS_PID = 'process.pid'; +/** + * An additional description about the runtime of the process, for example a specific vendor customization of the runtime environment. + * + * @example "Eclipse OpenJ9 Eclipse OpenJ9 VM openj9-0.21.0" + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_PROCESS_RUNTIME_DESCRIPTION = 'process.runtime.description'; +/** + * The name of the runtime of this process. + * + * @example OpenJDK Runtime Environment + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_PROCESS_RUNTIME_NAME = 'process.runtime.name'; +/** + * The version of the runtime of this process, as returned by the runtime without modification. + * + * @example "14.0.2" + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_PROCESS_RUNTIME_VERSION = 'process.runtime.version'; +/** + * The string ID of the service instance. + * + * @example 627cc493-f310-47de-96bd-71410b7dec09 + * + * @note **MUST** be unique for each instance of the same `service.namespace,service.name` pair (in other words + * `service.namespace,service.name,service.instance.id` triplet **MUST** be globally unique). The ID helps to + * distinguish instances of the same service that exist at the same time (e.g. instances of a horizontally scaled + * service). + * + * Implementations, such as SDKs, are recommended to generate a random Version 1 or Version 4 [RFC + * 4122](https://www.ietf.org/rfc/rfc4122.txt) UUID, but are free to use an inherent unique ID as the source of + * this value if stability is desirable. In that case, the ID **SHOULD** be used as source of a UUID Version 5 and + * **SHOULD** use the following UUID as the namespace: `4d63009a-8d0f-11ee-aad7-4c796ed8e320`. + * + * UUIDs are typically recommended, as only an opaque value for the purposes of identifying a service instance is + * needed. Similar to what can be seen in the man page for the + * [`/etc/machine-id`](https://www.freedesktop.org/software/systemd/man/latest/machine-id.html) file, the underlying + * data, such as pod name and namespace should be treated as confidential, being the user's choice to expose it + * or not via another resource attribute. + * + * For applications running behind an application server (like unicorn), we do not recommend using one identifier + * for all processes participating in the application. Instead, it's recommended each division (e.g. a worker + * thread in unicorn) to have its own instance.id. + * + * It's not recommended for a Collector to set `service.instance.id` if it can't unambiguously determine the + * service instance that is generating that telemetry. For instance, creating an UUID based on `pod.name` will + * likely be wrong, as the Collector might not know from which container within that pod the telemetry originated. + * However, Collectors can set the `service.instance.id` if they can unambiguously determine the service instance + * for that telemetry. This is typically the case for scraping receivers, as they know the target address and + * port. + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_SERVICE_INSTANCE_ID = 'service.instance.id'; +/** + * A namespace for `service.name`. + * + * @example Shop + * + * @note A string value having a meaning that helps to distinguish a group of services, for example the team name that owns a group of services. `service.name` is expected to be unique within the same namespace. If `service.namespace` is not specified in the Resource then `service.name` is expected to be unique for all services that have no explicit namespace defined (so the empty/unspecified namespace is simply one more valid namespace). Zero-length namespace string is assumed equal to unspecified namespace. + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_SERVICE_NAMESPACE = 'service.namespace'; +/** + * Additional description of the web engine (e.g. detailed version and edition information). + * + * @example WildFly Full 21.0.0.Final (WildFly Core 13.0.1.Final) - 2.2.2.Final + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_WEBENGINE_DESCRIPTION = 'webengine.description'; +/** + * The name of the web engine. + * + * @example WildFly + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_WEBENGINE_NAME = 'webengine.name'; +/** + * The version of the web engine. + * + * @example 21.0.0 + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ +exports.ATTR_WEBENGINE_VERSION = 'webengine.version'; +//# sourceMappingURL=semconv.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/utils.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/utils.js new file mode 100644 index 00000000..3344e5e7 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/resources/build/src/utils.js @@ -0,0 +1,29 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.identity = exports.isPromiseLike = void 0; +const isPromiseLike = (val) => { + return (val !== null && + typeof val === 'object' && + typeof val.then === 'function'); +}; +exports.isPromiseLike = isPromiseLike; +function identity(_) { + return _; +} +exports.identity = identity; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/LogRecordImpl.js b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/LogRecordImpl.js new file mode 100644 index 00000000..2252257c --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/LogRecordImpl.js @@ -0,0 +1,193 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LogRecordImpl = void 0; +const api = require("@opentelemetry/api"); +const core_1 = require("@opentelemetry/core"); +class LogRecordImpl { + hrTime; + hrTimeObserved; + spanContext; + resource; + instrumentationScope; + attributes = {}; + _severityText; + _severityNumber; + _body; + _eventName; + totalAttributesCount = 0; + _isReadonly = false; + _logRecordLimits; + set severityText(severityText) { + if (this._isLogRecordReadonly()) { + return; + } + this._severityText = severityText; + } + get severityText() { + return this._severityText; + } + set severityNumber(severityNumber) { + if (this._isLogRecordReadonly()) { + return; + } + this._severityNumber = severityNumber; + } + get severityNumber() { + return this._severityNumber; + } + set body(body) { + if (this._isLogRecordReadonly()) { + return; + } + this._body = body; + } + get body() { + return this._body; + } + get eventName() { + return this._eventName; + } + set eventName(eventName) { + if (this._isLogRecordReadonly()) { + return; + } + this._eventName = eventName; + } + get droppedAttributesCount() { + return this.totalAttributesCount - Object.keys(this.attributes).length; + } + constructor(_sharedState, instrumentationScope, logRecord) { + const { timestamp, observedTimestamp, eventName, severityNumber, severityText, body, attributes = {}, context, } = logRecord; + const now = Date.now(); + this.hrTime = (0, core_1.timeInputToHrTime)(timestamp ?? now); + this.hrTimeObserved = (0, core_1.timeInputToHrTime)(observedTimestamp ?? now); + if (context) { + const spanContext = api.trace.getSpanContext(context); + if (spanContext && api.isSpanContextValid(spanContext)) { + this.spanContext = spanContext; + } + } + this.severityNumber = severityNumber; + this.severityText = severityText; + this.body = body; + this.resource = _sharedState.resource; + this.instrumentationScope = instrumentationScope; + this._logRecordLimits = _sharedState.logRecordLimits; + this._eventName = eventName; + this.setAttributes(attributes); + } + setAttribute(key, value) { + if (this._isLogRecordReadonly()) { + return this; + } + if (value === null) { + return this; + } + if (key.length === 0) { + api.diag.warn(`Invalid attribute key: ${key}`); + return this; + } + if (!(0, core_1.isAttributeValue)(value) && + !(typeof value === 'object' && + !Array.isArray(value) && + Object.keys(value).length > 0)) { + api.diag.warn(`Invalid attribute value set for key: ${key}`); + return this; + } + this.totalAttributesCount += 1; + if (Object.keys(this.attributes).length >= + this._logRecordLimits.attributeCountLimit && + !Object.prototype.hasOwnProperty.call(this.attributes, key)) { + // This logic is to create drop message at most once per LogRecord to prevent excessive logging. + if (this.droppedAttributesCount === 1) { + api.diag.warn('Dropping extra attributes.'); + } + return this; + } + if ((0, core_1.isAttributeValue)(value)) { + this.attributes[key] = this._truncateToSize(value); + } + else { + this.attributes[key] = value; + } + return this; + } + setAttributes(attributes) { + for (const [k, v] of Object.entries(attributes)) { + this.setAttribute(k, v); + } + return this; + } + setBody(body) { + this.body = body; + return this; + } + setEventName(eventName) { + this.eventName = eventName; + return this; + } + setSeverityNumber(severityNumber) { + this.severityNumber = severityNumber; + return this; + } + setSeverityText(severityText) { + this.severityText = severityText; + return this; + } + /** + * @internal + * A LogRecordProcessor may freely modify logRecord for the duration of the OnEmit call. + * If logRecord is needed after OnEmit returns (i.e. for asynchronous processing) only reads are permitted. + */ + _makeReadonly() { + this._isReadonly = true; + } + _truncateToSize(value) { + const limit = this._logRecordLimits.attributeValueLengthLimit; + // Check limit + if (limit <= 0) { + // Negative values are invalid, so do not truncate + api.diag.warn(`Attribute value limit must be positive, got ${limit}`); + return value; + } + // String + if (typeof value === 'string') { + return this._truncateToLimitUtil(value, limit); + } + // Array of strings + if (Array.isArray(value)) { + return value.map(val => typeof val === 'string' ? this._truncateToLimitUtil(val, limit) : val); + } + // Other types, no need to apply value length limit + return value; + } + _truncateToLimitUtil(value, limit) { + if (value.length <= limit) { + return value; + } + return value.substring(0, limit); + } + _isLogRecordReadonly() { + if (this._isReadonly) { + api.diag.warn('Can not execute the operation on emitted log record'); + } + return this._isReadonly; + } +} +exports.LogRecordImpl = LogRecordImpl; +//# sourceMappingURL=LogRecordImpl.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/Logger.js b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/Logger.js new file mode 100644 index 00000000..1a1c6357 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/Logger.js @@ -0,0 +1,52 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Logger = void 0; +const api_1 = require("@opentelemetry/api"); +const LogRecordImpl_1 = require("./LogRecordImpl"); +class Logger { + instrumentationScope; + _sharedState; + constructor(instrumentationScope, _sharedState) { + this.instrumentationScope = instrumentationScope; + this._sharedState = _sharedState; + } + emit(logRecord) { + const currentContext = logRecord.context || api_1.context.active(); + /** + * If a Logger was obtained with include_trace_context=true, + * the LogRecords it emits MUST automatically include the Trace Context from the active Context, + * if Context has not been explicitly set. + */ + const logRecordInstance = new LogRecordImpl_1.LogRecordImpl(this._sharedState, this.instrumentationScope, { + context: currentContext, + ...logRecord, + }); + /** + * the explicitly passed Context, + * the current Context, or an empty Context if the Logger was obtained with include_trace_context=false + */ + this._sharedState.activeProcessor.onEmit(logRecordInstance, currentContext); + /** + * A LogRecordProcessor may freely modify logRecord for the duration of the OnEmit call. + * If logRecord is needed after OnEmit returns (i.e. for asynchronous processing) only reads are permitted. + */ + logRecordInstance._makeReadonly(); + } +} +exports.Logger = Logger; +//# sourceMappingURL=Logger.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/LoggerProvider.js b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/LoggerProvider.js new file mode 100644 index 00000000..02d0b6fa --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/LoggerProvider.js @@ -0,0 +1,86 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LoggerProvider = exports.DEFAULT_LOGGER_NAME = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const api_1 = require("@opentelemetry/api"); +const api_logs_1 = require("@opentelemetry/api-logs"); +const resources_1 = require("@opentelemetry/resources"); +const core_1 = require("@opentelemetry/core"); +const Logger_1 = require("./Logger"); +const config_1 = require("./config"); +const LoggerProviderSharedState_1 = require("./internal/LoggerProviderSharedState"); +exports.DEFAULT_LOGGER_NAME = 'unknown'; +class LoggerProvider { + _shutdownOnce; + _sharedState; + constructor(config = {}) { + const mergedConfig = (0, core_1.merge)({}, (0, config_1.loadDefaultConfig)(), config); + const resource = config.resource ?? (0, resources_1.defaultResource)(); + this._sharedState = new LoggerProviderSharedState_1.LoggerProviderSharedState(resource, mergedConfig.forceFlushTimeoutMillis, (0, config_1.reconfigureLimits)(mergedConfig.logRecordLimits), config?.processors ?? []); + this._shutdownOnce = new core_1.BindOnceFuture(this._shutdown, this); + } + /** + * Get a logger with the configuration of the LoggerProvider. + */ + getLogger(name, version, options) { + if (this._shutdownOnce.isCalled) { + api_1.diag.warn('A shutdown LoggerProvider cannot provide a Logger'); + return api_logs_1.NOOP_LOGGER; + } + if (!name) { + api_1.diag.warn('Logger requested without instrumentation scope name.'); + } + const loggerName = name || exports.DEFAULT_LOGGER_NAME; + const key = `${loggerName}@${version || ''}:${options?.schemaUrl || ''}`; + if (!this._sharedState.loggers.has(key)) { + this._sharedState.loggers.set(key, new Logger_1.Logger({ name: loggerName, version, schemaUrl: options?.schemaUrl }, this._sharedState)); + } + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + return this._sharedState.loggers.get(key); + } + /** + * Notifies all registered LogRecordProcessor to flush any buffered data. + * + * Returns a promise which is resolved when all flushes are complete. + */ + forceFlush() { + // do not flush after shutdown + if (this._shutdownOnce.isCalled) { + api_1.diag.warn('invalid attempt to force flush after LoggerProvider shutdown'); + return this._shutdownOnce.promise; + } + return this._sharedState.activeProcessor.forceFlush(); + } + /** + * Flush all buffered data and shut down the LoggerProvider and all registered + * LogRecordProcessor. + * + * Returns a promise which is resolved when all flushes are complete. + */ + shutdown() { + if (this._shutdownOnce.isCalled) { + api_1.diag.warn('shutdown may only be called once per LoggerProvider'); + return this._shutdownOnce.promise; + } + return this._shutdownOnce.call(); + } + _shutdown() { + return this._sharedState.activeProcessor.shutdown(); + } +} +exports.LoggerProvider = LoggerProvider; +//# sourceMappingURL=LoggerProvider.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/MultiLogRecordProcessor.js b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/MultiLogRecordProcessor.js new file mode 100644 index 00000000..9852dbd6 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/MultiLogRecordProcessor.js @@ -0,0 +1,43 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MultiLogRecordProcessor = void 0; +const core_1 = require("@opentelemetry/core"); +/** + * Implementation of the {@link LogRecordProcessor} that simply forwards all + * received events to a list of {@link LogRecordProcessor}s. + */ +class MultiLogRecordProcessor { + processors; + forceFlushTimeoutMillis; + constructor(processors, forceFlushTimeoutMillis) { + this.processors = processors; + this.forceFlushTimeoutMillis = forceFlushTimeoutMillis; + } + async forceFlush() { + const timeout = this.forceFlushTimeoutMillis; + await Promise.all(this.processors.map(processor => (0, core_1.callWithTimeout)(processor.forceFlush(), timeout))); + } + onEmit(logRecord, context) { + this.processors.forEach(processors => processors.onEmit(logRecord, context)); + } + async shutdown() { + await Promise.all(this.processors.map(processor => processor.shutdown())); + } +} +exports.MultiLogRecordProcessor = MultiLogRecordProcessor; +//# sourceMappingURL=MultiLogRecordProcessor.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/config.js b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/config.js new file mode 100644 index 00000000..e3433b7e --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/config.js @@ -0,0 +1,56 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.reconfigureLimits = exports.loadDefaultConfig = void 0; +const core_1 = require("@opentelemetry/core"); +function loadDefaultConfig() { + return { + forceFlushTimeoutMillis: 30000, + logRecordLimits: { + attributeValueLengthLimit: (0, core_1.getNumberFromEnv)('OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? + Infinity, + attributeCountLimit: (0, core_1.getNumberFromEnv)('OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT') ?? 128, + }, + includeTraceContext: true, + }; +} +exports.loadDefaultConfig = loadDefaultConfig; +/** + * When general limits are provided and model specific limits are not, + * configures the model specific limits by using the values from the general ones. + * @param logRecordLimits User provided limits configuration + */ +function reconfigureLimits(logRecordLimits) { + return { + /** + * Reassign log record attribute count limit to use first non null value defined by user or use default value + */ + attributeCountLimit: logRecordLimits.attributeCountLimit ?? + (0, core_1.getNumberFromEnv)('OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT') ?? + (0, core_1.getNumberFromEnv)('OTEL_ATTRIBUTE_COUNT_LIMIT') ?? + 128, + /** + * Reassign log record attribute value length limit to use first non null value defined by user or use default value + */ + attributeValueLengthLimit: logRecordLimits.attributeValueLengthLimit ?? + (0, core_1.getNumberFromEnv)('OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? + (0, core_1.getNumberFromEnv)('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? + Infinity, + }; +} +exports.reconfigureLimits = reconfigureLimits; +//# sourceMappingURL=config.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/BatchLogRecordProcessorBase.js b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/BatchLogRecordProcessorBase.js new file mode 100644 index 00000000..47156d0e --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/BatchLogRecordProcessorBase.js @@ -0,0 +1,172 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BatchLogRecordProcessorBase = void 0; +const api_1 = require("@opentelemetry/api"); +const core_1 = require("@opentelemetry/core"); +class BatchLogRecordProcessorBase { + _exporter; + _maxExportBatchSize; + _maxQueueSize; + _scheduledDelayMillis; + _exportTimeoutMillis; + _isExporting = false; + _finishedLogRecords = []; + _timer; + _shutdownOnce; + constructor(_exporter, config) { + this._exporter = _exporter; + this._maxExportBatchSize = + config?.maxExportBatchSize ?? + (0, core_1.getNumberFromEnv)('OTEL_BLRP_MAX_EXPORT_BATCH_SIZE') ?? + 512; + this._maxQueueSize = + config?.maxQueueSize ?? + (0, core_1.getNumberFromEnv)('OTEL_BLRP_MAX_QUEUE_SIZE') ?? + 2048; + this._scheduledDelayMillis = + config?.scheduledDelayMillis ?? + (0, core_1.getNumberFromEnv)('OTEL_BLRP_SCHEDULE_DELAY') ?? + 5000; + this._exportTimeoutMillis = + config?.exportTimeoutMillis ?? + (0, core_1.getNumberFromEnv)('OTEL_BLRP_EXPORT_TIMEOUT') ?? + 30000; + this._shutdownOnce = new core_1.BindOnceFuture(this._shutdown, this); + if (this._maxExportBatchSize > this._maxQueueSize) { + api_1.diag.warn('BatchLogRecordProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize'); + this._maxExportBatchSize = this._maxQueueSize; + } + } + onEmit(logRecord) { + if (this._shutdownOnce.isCalled) { + return; + } + this._addToBuffer(logRecord); + } + forceFlush() { + if (this._shutdownOnce.isCalled) { + return this._shutdownOnce.promise; + } + return this._flushAll(); + } + shutdown() { + return this._shutdownOnce.call(); + } + async _shutdown() { + this.onShutdown(); + await this._flushAll(); + await this._exporter.shutdown(); + } + /** Add a LogRecord in the buffer. */ + _addToBuffer(logRecord) { + if (this._finishedLogRecords.length >= this._maxQueueSize) { + return; + } + this._finishedLogRecords.push(logRecord); + this._maybeStartTimer(); + } + /** + * Send all LogRecords to the exporter respecting the batch size limit + * This function is used only on forceFlush or shutdown, + * for all other cases _flush should be used + * */ + _flushAll() { + return new Promise((resolve, reject) => { + const promises = []; + const batchCount = Math.ceil(this._finishedLogRecords.length / this._maxExportBatchSize); + for (let i = 0; i < batchCount; i++) { + promises.push(this._flushOneBatch()); + } + Promise.all(promises) + .then(() => { + resolve(); + }) + .catch(reject); + }); + } + _flushOneBatch() { + this._clearTimer(); + if (this._finishedLogRecords.length === 0) { + return Promise.resolve(); + } + return new Promise((resolve, reject) => { + (0, core_1.callWithTimeout)(this._export(this._finishedLogRecords.splice(0, this._maxExportBatchSize)), this._exportTimeoutMillis) + .then(() => resolve()) + .catch(reject); + }); + } + _maybeStartTimer() { + if (this._isExporting) + return; + const flush = () => { + this._isExporting = true; + this._flushOneBatch() + .then(() => { + this._isExporting = false; + if (this._finishedLogRecords.length > 0) { + this._clearTimer(); + this._maybeStartTimer(); + } + }) + .catch(e => { + this._isExporting = false; + (0, core_1.globalErrorHandler)(e); + }); + }; + // we only wait if the queue doesn't have enough elements yet + if (this._finishedLogRecords.length >= this._maxExportBatchSize) { + return flush(); + } + if (this._timer !== undefined) + return; + this._timer = setTimeout(() => flush(), this._scheduledDelayMillis); + // depending on runtime, this may be a 'number' or NodeJS.Timeout + if (typeof this._timer !== 'number') { + this._timer.unref(); + } + } + _clearTimer() { + if (this._timer !== undefined) { + clearTimeout(this._timer); + this._timer = undefined; + } + } + _export(logRecords) { + const doExport = () => core_1.internal + ._export(this._exporter, logRecords) + .then((result) => { + if (result.code !== core_1.ExportResultCode.SUCCESS) { + (0, core_1.globalErrorHandler)(result.error ?? + new Error(`BatchLogRecordProcessor: log record export failed (status ${result})`)); + } + }) + .catch(core_1.globalErrorHandler); + const pendingResources = logRecords + .map(logRecord => logRecord.resource) + .filter(resource => resource.asyncAttributesPending); + // Avoid scheduling a promise to make the behavior more predictable and easier to test + if (pendingResources.length === 0) { + return doExport(); + } + else { + return Promise.all(pendingResources.map(resource => resource.waitForAsyncAttributes?.())).then(doExport, core_1.globalErrorHandler); + } + } +} +exports.BatchLogRecordProcessorBase = BatchLogRecordProcessorBase; +//# sourceMappingURL=BatchLogRecordProcessorBase.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/ConsoleLogRecordExporter.js b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/ConsoleLogRecordExporter.js new file mode 100644 index 00000000..45ad2268 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/ConsoleLogRecordExporter.js @@ -0,0 +1,75 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ConsoleLogRecordExporter = void 0; +const core_1 = require("@opentelemetry/core"); +/** + * This is implementation of {@link LogRecordExporter} that prints LogRecords to the + * console. This class can be used for diagnostic purposes. + * + * NOTE: This {@link LogRecordExporter} is intended for diagnostics use only, output rendered to the console may change at any time. + */ +/* eslint-disable no-console */ +class ConsoleLogRecordExporter { + /** + * Export logs. + * @param logs + * @param resultCallback + */ + export(logs, resultCallback) { + this._sendLogRecords(logs, resultCallback); + } + /** + * Shutdown the exporter. + */ + shutdown() { + return Promise.resolve(); + } + /** + * converts logRecord info into more readable format + * @param logRecord + */ + _exportInfo(logRecord) { + return { + resource: { + attributes: logRecord.resource.attributes, + }, + instrumentationScope: logRecord.instrumentationScope, + timestamp: (0, core_1.hrTimeToMicroseconds)(logRecord.hrTime), + traceId: logRecord.spanContext?.traceId, + spanId: logRecord.spanContext?.spanId, + traceFlags: logRecord.spanContext?.traceFlags, + severityText: logRecord.severityText, + severityNumber: logRecord.severityNumber, + body: logRecord.body, + attributes: logRecord.attributes, + }; + } + /** + * Showing logs in console + * @param logRecords + * @param done + */ + _sendLogRecords(logRecords, done) { + for (const logRecord of logRecords) { + console.dir(this._exportInfo(logRecord), { depth: 3 }); + } + done?.({ code: core_1.ExportResultCode.SUCCESS }); + } +} +exports.ConsoleLogRecordExporter = ConsoleLogRecordExporter; +//# sourceMappingURL=ConsoleLogRecordExporter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/InMemoryLogRecordExporter.js b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/InMemoryLogRecordExporter.js new file mode 100644 index 00000000..ffe46bbd --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/InMemoryLogRecordExporter.js @@ -0,0 +1,55 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InMemoryLogRecordExporter = void 0; +const core_1 = require("@opentelemetry/core"); +/** + * This class can be used for testing purposes. It stores the exported LogRecords + * in a list in memory that can be retrieved using the `getFinishedLogRecords()` + * method. + */ +class InMemoryLogRecordExporter { + _finishedLogRecords = []; + /** + * Indicates if the exporter has been "shutdown." + * When false, exported log records will not be stored in-memory. + */ + _stopped = false; + export(logs, resultCallback) { + if (this._stopped) { + return resultCallback({ + code: core_1.ExportResultCode.FAILED, + error: new Error('Exporter has been stopped'), + }); + } + this._finishedLogRecords.push(...logs); + resultCallback({ code: core_1.ExportResultCode.SUCCESS }); + } + shutdown() { + this._stopped = true; + this.reset(); + return Promise.resolve(); + } + getFinishedLogRecords() { + return this._finishedLogRecords; + } + reset() { + this._finishedLogRecords = []; + } +} +exports.InMemoryLogRecordExporter = InMemoryLogRecordExporter; +//# sourceMappingURL=InMemoryLogRecordExporter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/NoopLogRecordProcessor.js b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/NoopLogRecordProcessor.js new file mode 100644 index 00000000..a845099a --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/NoopLogRecordProcessor.js @@ -0,0 +1,29 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NoopLogRecordProcessor = void 0; +class NoopLogRecordProcessor { + forceFlush() { + return Promise.resolve(); + } + onEmit(_logRecord, _context) { } + shutdown() { + return Promise.resolve(); + } +} +exports.NoopLogRecordProcessor = NoopLogRecordProcessor; +//# sourceMappingURL=NoopLogRecordProcessor.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/SimpleLogRecordProcessor.js b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/SimpleLogRecordProcessor.js new file mode 100644 index 00000000..5b4490e6 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/SimpleLogRecordProcessor.js @@ -0,0 +1,83 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SimpleLogRecordProcessor = void 0; +const core_1 = require("@opentelemetry/core"); +/** + * An implementation of the {@link LogRecordProcessor} interface that exports + * each {@link LogRecord} as it is emitted. + * + * NOTE: This {@link LogRecordProcessor} exports every {@link LogRecord} + * individually instead of batching them together, which can cause significant + * performance overhead with most exporters. For production use, please consider + * using the {@link BatchLogRecordProcessor} instead. + */ +class SimpleLogRecordProcessor { + _exporter; + _shutdownOnce; + _unresolvedExports; + constructor(_exporter) { + this._exporter = _exporter; + this._shutdownOnce = new core_1.BindOnceFuture(this._shutdown, this); + this._unresolvedExports = new Set(); + } + onEmit(logRecord) { + if (this._shutdownOnce.isCalled) { + return; + } + const doExport = () => core_1.internal + ._export(this._exporter, [logRecord]) + .then((result) => { + if (result.code !== core_1.ExportResultCode.SUCCESS) { + (0, core_1.globalErrorHandler)(result.error ?? + new Error(`SimpleLogRecordProcessor: log record export failed (status ${result})`)); + } + }) + .catch(core_1.globalErrorHandler); + // Avoid scheduling a promise to make the behavior more predictable and easier to test + if (logRecord.resource.asyncAttributesPending) { + const exportPromise = logRecord.resource + .waitForAsyncAttributes?.() + .then(() => { + // Using TS Non-null assertion operator because exportPromise could not be null in here + // if waitForAsyncAttributes is not present this code will never be reached + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + this._unresolvedExports.delete(exportPromise); + return doExport(); + }, core_1.globalErrorHandler); + // store the unresolved exports + if (exportPromise != null) { + this._unresolvedExports.add(exportPromise); + } + } + else { + void doExport(); + } + } + async forceFlush() { + // await unresolved resources before resolving + await Promise.all(Array.from(this._unresolvedExports)); + } + shutdown() { + return this._shutdownOnce.call(); + } + _shutdown() { + return this._exporter.shutdown(); + } +} +exports.SimpleLogRecordProcessor = SimpleLogRecordProcessor; +//# sourceMappingURL=SimpleLogRecordProcessor.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/index.js new file mode 100644 index 00000000..5bb9f418 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/index.js @@ -0,0 +1,29 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BatchLogRecordProcessor = exports.InMemoryLogRecordExporter = exports.SimpleLogRecordProcessor = exports.ConsoleLogRecordExporter = exports.LoggerProvider = void 0; +var LoggerProvider_1 = require("./LoggerProvider"); +Object.defineProperty(exports, "LoggerProvider", { enumerable: true, get: function () { return LoggerProvider_1.LoggerProvider; } }); +var ConsoleLogRecordExporter_1 = require("./export/ConsoleLogRecordExporter"); +Object.defineProperty(exports, "ConsoleLogRecordExporter", { enumerable: true, get: function () { return ConsoleLogRecordExporter_1.ConsoleLogRecordExporter; } }); +var SimpleLogRecordProcessor_1 = require("./export/SimpleLogRecordProcessor"); +Object.defineProperty(exports, "SimpleLogRecordProcessor", { enumerable: true, get: function () { return SimpleLogRecordProcessor_1.SimpleLogRecordProcessor; } }); +var InMemoryLogRecordExporter_1 = require("./export/InMemoryLogRecordExporter"); +Object.defineProperty(exports, "InMemoryLogRecordExporter", { enumerable: true, get: function () { return InMemoryLogRecordExporter_1.InMemoryLogRecordExporter; } }); +var platform_1 = require("./platform"); +Object.defineProperty(exports, "BatchLogRecordProcessor", { enumerable: true, get: function () { return platform_1.BatchLogRecordProcessor; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/internal/LoggerProviderSharedState.js b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/internal/LoggerProviderSharedState.js new file mode 100644 index 00000000..9a58a2e0 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/internal/LoggerProviderSharedState.js @@ -0,0 +1,44 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LoggerProviderSharedState = void 0; +const NoopLogRecordProcessor_1 = require("../export/NoopLogRecordProcessor"); +const MultiLogRecordProcessor_1 = require("../MultiLogRecordProcessor"); +class LoggerProviderSharedState { + resource; + forceFlushTimeoutMillis; + logRecordLimits; + processors; + loggers = new Map(); + activeProcessor; + registeredLogRecordProcessors = []; + constructor(resource, forceFlushTimeoutMillis, logRecordLimits, processors) { + this.resource = resource; + this.forceFlushTimeoutMillis = forceFlushTimeoutMillis; + this.logRecordLimits = logRecordLimits; + this.processors = processors; + if (processors.length > 0) { + this.registeredLogRecordProcessors = processors; + this.activeProcessor = new MultiLogRecordProcessor_1.MultiLogRecordProcessor(this.registeredLogRecordProcessors, this.forceFlushTimeoutMillis); + } + else { + this.activeProcessor = new NoopLogRecordProcessor_1.NoopLogRecordProcessor(); + } + } +} +exports.LoggerProviderSharedState = LoggerProviderSharedState; +//# sourceMappingURL=LoggerProviderSharedState.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/platform/index.js b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/platform/index.js new file mode 100644 index 00000000..b76b4fc5 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/platform/index.js @@ -0,0 +1,21 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BatchLogRecordProcessor = void 0; +var node_1 = require("./node"); +Object.defineProperty(exports, "BatchLogRecordProcessor", { enumerable: true, get: function () { return node_1.BatchLogRecordProcessor; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/platform/node/export/BatchLogRecordProcessor.js b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/platform/node/export/BatchLogRecordProcessor.js new file mode 100644 index 00000000..b6d2413a --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/platform/node/export/BatchLogRecordProcessor.js @@ -0,0 +1,24 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BatchLogRecordProcessor = void 0; +const BatchLogRecordProcessorBase_1 = require("../../../export/BatchLogRecordProcessorBase"); +class BatchLogRecordProcessor extends BatchLogRecordProcessorBase_1.BatchLogRecordProcessorBase { + onShutdown() { } +} +exports.BatchLogRecordProcessor = BatchLogRecordProcessor; +//# sourceMappingURL=BatchLogRecordProcessor.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/platform/node/index.js b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/platform/node/index.js new file mode 100644 index 00000000..b23b699c --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/platform/node/index.js @@ -0,0 +1,21 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BatchLogRecordProcessor = void 0; +var BatchLogRecordProcessor_1 = require("./export/BatchLogRecordProcessor"); +Object.defineProperty(exports, "BatchLogRecordProcessor", { enumerable: true, get: function () { return BatchLogRecordProcessor_1.BatchLogRecordProcessor; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/InstrumentDescriptor.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/InstrumentDescriptor.js new file mode 100644 index 00000000..b429f2ea --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/InstrumentDescriptor.js @@ -0,0 +1,61 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isValidName = exports.isDescriptorCompatibleWith = exports.createInstrumentDescriptorWithView = exports.createInstrumentDescriptor = void 0; +const api_1 = require("@opentelemetry/api"); +const utils_1 = require("./utils"); +function createInstrumentDescriptor(name, type, options) { + if (!isValidName(name)) { + api_1.diag.warn(`Invalid metric name: "${name}". The metric name should be a ASCII string with a length no greater than 255 characters.`); + } + return { + name, + type, + description: options?.description ?? '', + unit: options?.unit ?? '', + valueType: options?.valueType ?? api_1.ValueType.DOUBLE, + advice: options?.advice ?? {}, + }; +} +exports.createInstrumentDescriptor = createInstrumentDescriptor; +function createInstrumentDescriptorWithView(view, instrument) { + return { + name: view.name ?? instrument.name, + description: view.description ?? instrument.description, + type: instrument.type, + unit: instrument.unit, + valueType: instrument.valueType, + advice: instrument.advice, + }; +} +exports.createInstrumentDescriptorWithView = createInstrumentDescriptorWithView; +function isDescriptorCompatibleWith(descriptor, otherDescriptor) { + // Names are case-insensitive strings. + return ((0, utils_1.equalsCaseInsensitive)(descriptor.name, otherDescriptor.name) && + descriptor.unit === otherDescriptor.unit && + descriptor.type === otherDescriptor.type && + descriptor.valueType === otherDescriptor.valueType); +} +exports.isDescriptorCompatibleWith = isDescriptorCompatibleWith; +// ASCII string with a length no greater than 255 characters. +// NB: the first character counted separately from the rest. +const NAME_REGEXP = /^[a-z][a-z0-9_.\-/]{0,254}$/i; +function isValidName(name) { + return name.match(NAME_REGEXP) != null; +} +exports.isValidName = isValidName; +//# sourceMappingURL=InstrumentDescriptor.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/Instruments.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/Instruments.js new file mode 100644 index 00000000..22f32e4b --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/Instruments.js @@ -0,0 +1,140 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isObservableInstrument = exports.ObservableUpDownCounterInstrument = exports.ObservableGaugeInstrument = exports.ObservableCounterInstrument = exports.ObservableInstrument = exports.HistogramInstrument = exports.GaugeInstrument = exports.CounterInstrument = exports.UpDownCounterInstrument = exports.SyncInstrument = void 0; +const api_1 = require("@opentelemetry/api"); +const core_1 = require("@opentelemetry/core"); +class SyncInstrument { + _writableMetricStorage; + _descriptor; + constructor(_writableMetricStorage, _descriptor) { + this._writableMetricStorage = _writableMetricStorage; + this._descriptor = _descriptor; + } + _record(value, attributes = {}, context = api_1.context.active()) { + if (typeof value !== 'number') { + api_1.diag.warn(`non-number value provided to metric ${this._descriptor.name}: ${value}`); + return; + } + if (this._descriptor.valueType === api_1.ValueType.INT && + !Number.isInteger(value)) { + api_1.diag.warn(`INT value type cannot accept a floating-point value for ${this._descriptor.name}, ignoring the fractional digits.`); + value = Math.trunc(value); + // ignore non-finite values. + if (!Number.isInteger(value)) { + return; + } + } + this._writableMetricStorage.record(value, attributes, context, (0, core_1.millisToHrTime)(Date.now())); + } +} +exports.SyncInstrument = SyncInstrument; +/** + * The class implements {@link UpDownCounter} interface. + */ +class UpDownCounterInstrument extends SyncInstrument { + /** + * Increment value of counter by the input. Inputs may be negative. + */ + add(value, attributes, ctx) { + this._record(value, attributes, ctx); + } +} +exports.UpDownCounterInstrument = UpDownCounterInstrument; +/** + * The class implements {@link Counter} interface. + */ +class CounterInstrument extends SyncInstrument { + /** + * Increment value of counter by the input. Inputs may not be negative. + */ + add(value, attributes, ctx) { + if (value < 0) { + api_1.diag.warn(`negative value provided to counter ${this._descriptor.name}: ${value}`); + return; + } + this._record(value, attributes, ctx); + } +} +exports.CounterInstrument = CounterInstrument; +/** + * The class implements {@link Gauge} interface. + */ +class GaugeInstrument extends SyncInstrument { + /** + * Records a measurement. + */ + record(value, attributes, ctx) { + this._record(value, attributes, ctx); + } +} +exports.GaugeInstrument = GaugeInstrument; +/** + * The class implements {@link Histogram} interface. + */ +class HistogramInstrument extends SyncInstrument { + /** + * Records a measurement. Value of the measurement must not be negative. + */ + record(value, attributes, ctx) { + if (value < 0) { + api_1.diag.warn(`negative value provided to histogram ${this._descriptor.name}: ${value}`); + return; + } + this._record(value, attributes, ctx); + } +} +exports.HistogramInstrument = HistogramInstrument; +class ObservableInstrument { + _observableRegistry; + /** @internal */ + _metricStorages; + /** @internal */ + _descriptor; + constructor(descriptor, metricStorages, _observableRegistry) { + this._observableRegistry = _observableRegistry; + this._descriptor = descriptor; + this._metricStorages = metricStorages; + } + /** + * @see {Observable.addCallback} + */ + addCallback(callback) { + this._observableRegistry.addCallback(callback, this); + } + /** + * @see {Observable.removeCallback} + */ + removeCallback(callback) { + this._observableRegistry.removeCallback(callback, this); + } +} +exports.ObservableInstrument = ObservableInstrument; +class ObservableCounterInstrument extends ObservableInstrument { +} +exports.ObservableCounterInstrument = ObservableCounterInstrument; +class ObservableGaugeInstrument extends ObservableInstrument { +} +exports.ObservableGaugeInstrument = ObservableGaugeInstrument; +class ObservableUpDownCounterInstrument extends ObservableInstrument { +} +exports.ObservableUpDownCounterInstrument = ObservableUpDownCounterInstrument; +function isObservableInstrument(it) { + return it instanceof ObservableInstrument; +} +exports.isObservableInstrument = isObservableInstrument; +//# sourceMappingURL=Instruments.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/Meter.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/Meter.js new file mode 100644 index 00000000..63f1909c --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/Meter.js @@ -0,0 +1,100 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Meter = void 0; +const InstrumentDescriptor_1 = require("./InstrumentDescriptor"); +const Instruments_1 = require("./Instruments"); +const MetricData_1 = require("./export/MetricData"); +/** + * This class implements the {@link IMeter} interface. + */ +class Meter { + _meterSharedState; + constructor(_meterSharedState) { + this._meterSharedState = _meterSharedState; + } + /** + * Create a {@link Gauge} instrument. + */ + createGauge(name, options) { + const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, MetricData_1.InstrumentType.GAUGE, options); + const storage = this._meterSharedState.registerMetricStorage(descriptor); + return new Instruments_1.GaugeInstrument(storage, descriptor); + } + /** + * Create a {@link Histogram} instrument. + */ + createHistogram(name, options) { + const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, MetricData_1.InstrumentType.HISTOGRAM, options); + const storage = this._meterSharedState.registerMetricStorage(descriptor); + return new Instruments_1.HistogramInstrument(storage, descriptor); + } + /** + * Create a {@link Counter} instrument. + */ + createCounter(name, options) { + const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, MetricData_1.InstrumentType.COUNTER, options); + const storage = this._meterSharedState.registerMetricStorage(descriptor); + return new Instruments_1.CounterInstrument(storage, descriptor); + } + /** + * Create a {@link UpDownCounter} instrument. + */ + createUpDownCounter(name, options) { + const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, MetricData_1.InstrumentType.UP_DOWN_COUNTER, options); + const storage = this._meterSharedState.registerMetricStorage(descriptor); + return new Instruments_1.UpDownCounterInstrument(storage, descriptor); + } + /** + * Create a {@link ObservableGauge} instrument. + */ + createObservableGauge(name, options) { + const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, MetricData_1.InstrumentType.OBSERVABLE_GAUGE, options); + const storages = this._meterSharedState.registerAsyncMetricStorage(descriptor); + return new Instruments_1.ObservableGaugeInstrument(descriptor, storages, this._meterSharedState.observableRegistry); + } + /** + * Create a {@link ObservableCounter} instrument. + */ + createObservableCounter(name, options) { + const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, MetricData_1.InstrumentType.OBSERVABLE_COUNTER, options); + const storages = this._meterSharedState.registerAsyncMetricStorage(descriptor); + return new Instruments_1.ObservableCounterInstrument(descriptor, storages, this._meterSharedState.observableRegistry); + } + /** + * Create a {@link ObservableUpDownCounter} instrument. + */ + createObservableUpDownCounter(name, options) { + const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, MetricData_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER, options); + const storages = this._meterSharedState.registerAsyncMetricStorage(descriptor); + return new Instruments_1.ObservableUpDownCounterInstrument(descriptor, storages, this._meterSharedState.observableRegistry); + } + /** + * @see {@link Meter.addBatchObservableCallback} + */ + addBatchObservableCallback(callback, observables) { + this._meterSharedState.observableRegistry.addBatchCallback(callback, observables); + } + /** + * @see {@link Meter.removeBatchObservableCallback} + */ + removeBatchObservableCallback(callback, observables) { + this._meterSharedState.observableRegistry.removeBatchCallback(callback, observables); + } +} +exports.Meter = Meter; +//# sourceMappingURL=Meter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/MeterProvider.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/MeterProvider.js new file mode 100644 index 00000000..068cca7f --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/MeterProvider.js @@ -0,0 +1,93 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MeterProvider = void 0; +const api_1 = require("@opentelemetry/api"); +const resources_1 = require("@opentelemetry/resources"); +const MeterProviderSharedState_1 = require("./state/MeterProviderSharedState"); +const MetricCollector_1 = require("./state/MetricCollector"); +const View_1 = require("./view/View"); +/** + * This class implements the {@link MeterProvider} interface. + */ +class MeterProvider { + _sharedState; + _shutdown = false; + constructor(options) { + this._sharedState = new MeterProviderSharedState_1.MeterProviderSharedState(options?.resource ?? (0, resources_1.defaultResource)()); + if (options?.views != null && options.views.length > 0) { + for (const viewOption of options.views) { + this._sharedState.viewRegistry.addView(new View_1.View(viewOption)); + } + } + if (options?.readers != null && options.readers.length > 0) { + for (const metricReader of options.readers) { + const collector = new MetricCollector_1.MetricCollector(this._sharedState, metricReader); + metricReader.setMetricProducer(collector); + this._sharedState.metricCollectors.push(collector); + } + } + } + /** + * Get a meter with the configuration of the MeterProvider. + */ + getMeter(name, version = '', options = {}) { + // https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#meter-creation + if (this._shutdown) { + api_1.diag.warn('A shutdown MeterProvider cannot provide a Meter'); + return (0, api_1.createNoopMeter)(); + } + return this._sharedState.getMeterSharedState({ + name, + version, + schemaUrl: options.schemaUrl, + }).meter; + } + /** + * Shut down the MeterProvider and all registered + * MetricReaders. + * + * Returns a promise which is resolved when all flushes are complete. + */ + async shutdown(options) { + if (this._shutdown) { + api_1.diag.warn('shutdown may only be called once per MeterProvider'); + return; + } + this._shutdown = true; + await Promise.all(this._sharedState.metricCollectors.map(collector => { + return collector.shutdown(options); + })); + } + /** + * Notifies all registered MetricReaders to flush any buffered data. + * + * Returns a promise which is resolved when all flushes are complete. + */ + async forceFlush(options) { + // do not flush after shutdown + if (this._shutdown) { + api_1.diag.warn('invalid attempt to force flush after MeterProvider shutdown'); + return; + } + await Promise.all(this._sharedState.metricCollectors.map(collector => { + return collector.forceFlush(options); + })); + } +} +exports.MeterProvider = MeterProvider; +//# sourceMappingURL=MeterProvider.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/ObservableResult.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/ObservableResult.js new file mode 100644 index 00000000..3203e1ac --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/ObservableResult.js @@ -0,0 +1,93 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BatchObservableResultImpl = exports.ObservableResultImpl = void 0; +const api_1 = require("@opentelemetry/api"); +const HashMap_1 = require("./state/HashMap"); +const Instruments_1 = require("./Instruments"); +/** + * The class implements {@link ObservableResult} interface. + */ +class ObservableResultImpl { + _instrumentName; + _valueType; + /** + * @internal + */ + _buffer = new HashMap_1.AttributeHashMap(); + constructor(_instrumentName, _valueType) { + this._instrumentName = _instrumentName; + this._valueType = _valueType; + } + /** + * Observe a measurement of the value associated with the given attributes. + */ + observe(value, attributes = {}) { + if (typeof value !== 'number') { + api_1.diag.warn(`non-number value provided to metric ${this._instrumentName}: ${value}`); + return; + } + if (this._valueType === api_1.ValueType.INT && !Number.isInteger(value)) { + api_1.diag.warn(`INT value type cannot accept a floating-point value for ${this._instrumentName}, ignoring the fractional digits.`); + value = Math.trunc(value); + // ignore non-finite values. + if (!Number.isInteger(value)) { + return; + } + } + this._buffer.set(attributes, value); + } +} +exports.ObservableResultImpl = ObservableResultImpl; +/** + * The class implements {@link BatchObservableCallback} interface. + */ +class BatchObservableResultImpl { + /** + * @internal + */ + _buffer = new Map(); + /** + * Observe a measurement of the value associated with the given attributes. + */ + observe(metric, value, attributes = {}) { + if (!(0, Instruments_1.isObservableInstrument)(metric)) { + return; + } + let map = this._buffer.get(metric); + if (map == null) { + map = new HashMap_1.AttributeHashMap(); + this._buffer.set(metric, map); + } + if (typeof value !== 'number') { + api_1.diag.warn(`non-number value provided to metric ${metric._descriptor.name}: ${value}`); + return; + } + if (metric._descriptor.valueType === api_1.ValueType.INT && + !Number.isInteger(value)) { + api_1.diag.warn(`INT value type cannot accept a floating-point value for ${metric._descriptor.name}, ignoring the fractional digits.`); + value = Math.trunc(value); + // ignore non-finite values. + if (!Number.isInteger(value)) { + return; + } + } + map.set(attributes, value); + } +} +exports.BatchObservableResultImpl = BatchObservableResultImpl; +//# sourceMappingURL=ObservableResult.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Drop.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Drop.js new file mode 100644 index 00000000..ff68a76f --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Drop.js @@ -0,0 +1,37 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DropAggregator = void 0; +const types_1 = require("./types"); +/** Basic aggregator for None which keeps no recorded value. */ +class DropAggregator { + kind = types_1.AggregatorKind.DROP; + createAccumulation() { + return undefined; + } + merge(_previous, _delta) { + return undefined; + } + diff(_previous, _current) { + return undefined; + } + toMetricData(_descriptor, _aggregationTemporality, _accumulationByAttributes, _endTime) { + return undefined; + } +} +exports.DropAggregator = DropAggregator; +//# sourceMappingURL=Drop.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/ExponentialHistogram.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/ExponentialHistogram.js new file mode 100644 index 00000000..2c563666 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/ExponentialHistogram.js @@ -0,0 +1,480 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ExponentialHistogramAggregator = exports.ExponentialHistogramAccumulation = void 0; +const types_1 = require("./types"); +const MetricData_1 = require("../export/MetricData"); +const api_1 = require("@opentelemetry/api"); +const Buckets_1 = require("./exponential-histogram/Buckets"); +const getMapping_1 = require("./exponential-histogram/mapping/getMapping"); +const util_1 = require("./exponential-histogram/util"); +// HighLow is a utility class used for computing a common scale for +// two exponential histogram accumulations +class HighLow { + low; + high; + static combine(h1, h2) { + return new HighLow(Math.min(h1.low, h2.low), Math.max(h1.high, h2.high)); + } + constructor(low, high) { + this.low = low; + this.high = high; + } +} +const MAX_SCALE = 20; +const DEFAULT_MAX_SIZE = 160; +const MIN_MAX_SIZE = 2; +class ExponentialHistogramAccumulation { + startTime; + _maxSize; + _recordMinMax; + _sum; + _count; + _zeroCount; + _min; + _max; + _positive; + _negative; + _mapping; + constructor(startTime, _maxSize = DEFAULT_MAX_SIZE, _recordMinMax = true, _sum = 0, _count = 0, _zeroCount = 0, _min = Number.POSITIVE_INFINITY, _max = Number.NEGATIVE_INFINITY, _positive = new Buckets_1.Buckets(), _negative = new Buckets_1.Buckets(), _mapping = (0, getMapping_1.getMapping)(MAX_SCALE)) { + this.startTime = startTime; + this._maxSize = _maxSize; + this._recordMinMax = _recordMinMax; + this._sum = _sum; + this._count = _count; + this._zeroCount = _zeroCount; + this._min = _min; + this._max = _max; + this._positive = _positive; + this._negative = _negative; + this._mapping = _mapping; + if (this._maxSize < MIN_MAX_SIZE) { + api_1.diag.warn(`Exponential Histogram Max Size set to ${this._maxSize}, \ + changing to the minimum size of: ${MIN_MAX_SIZE}`); + this._maxSize = MIN_MAX_SIZE; + } + } + /** + * record updates a histogram with a single count + * @param {Number} value + */ + record(value) { + this.updateByIncrement(value, 1); + } + /** + * Sets the start time for this accumulation + * @param {HrTime} startTime + */ + setStartTime(startTime) { + this.startTime = startTime; + } + /** + * Returns the datapoint representation of this accumulation + * @param {HrTime} startTime + */ + toPointValue() { + return { + hasMinMax: this._recordMinMax, + min: this.min, + max: this.max, + sum: this.sum, + positive: { + offset: this.positive.offset, + bucketCounts: this.positive.counts(), + }, + negative: { + offset: this.negative.offset, + bucketCounts: this.negative.counts(), + }, + count: this.count, + scale: this.scale, + zeroCount: this.zeroCount, + }; + } + /** + * @returns {Number} The sum of values recorded by this accumulation + */ + get sum() { + return this._sum; + } + /** + * @returns {Number} The minimum value recorded by this accumulation + */ + get min() { + return this._min; + } + /** + * @returns {Number} The maximum value recorded by this accumulation + */ + get max() { + return this._max; + } + /** + * @returns {Number} The count of values recorded by this accumulation + */ + get count() { + return this._count; + } + /** + * @returns {Number} The number of 0 values recorded by this accumulation + */ + get zeroCount() { + return this._zeroCount; + } + /** + * @returns {Number} The scale used by this accumulation + */ + get scale() { + if (this._count === this._zeroCount) { + // all zeros! scale doesn't matter, use zero + return 0; + } + return this._mapping.scale; + } + /** + * positive holds the positive values + * @returns {Buckets} + */ + get positive() { + return this._positive; + } + /** + * negative holds the negative values by their absolute value + * @returns {Buckets} + */ + get negative() { + return this._negative; + } + /** + * updateByIncr supports updating a histogram with a non-negative + * increment. + * @param value + * @param increment + */ + updateByIncrement(value, increment) { + // NaN does not fall into any bucket, is not zero and should not be counted, + // NaN is never greater than max nor less than min, therefore return as there's nothing for us to do. + if (Number.isNaN(value)) { + return; + } + if (value > this._max) { + this._max = value; + } + if (value < this._min) { + this._min = value; + } + this._count += increment; + if (value === 0) { + this._zeroCount += increment; + return; + } + this._sum += value * increment; + if (value > 0) { + this._updateBuckets(this._positive, value, increment); + } + else { + this._updateBuckets(this._negative, -value, increment); + } + } + /** + * merge combines data from previous value into self + * @param {ExponentialHistogramAccumulation} previous + */ + merge(previous) { + if (this._count === 0) { + this._min = previous.min; + this._max = previous.max; + } + else if (previous.count !== 0) { + if (previous.min < this.min) { + this._min = previous.min; + } + if (previous.max > this.max) { + this._max = previous.max; + } + } + this.startTime = previous.startTime; + this._sum += previous.sum; + this._count += previous.count; + this._zeroCount += previous.zeroCount; + const minScale = this._minScale(previous); + this._downscale(this.scale - minScale); + this._mergeBuckets(this.positive, previous, previous.positive, minScale); + this._mergeBuckets(this.negative, previous, previous.negative, minScale); + } + /** + * diff subtracts other from self + * @param {ExponentialHistogramAccumulation} other + */ + diff(other) { + this._min = Infinity; + this._max = -Infinity; + this._sum -= other.sum; + this._count -= other.count; + this._zeroCount -= other.zeroCount; + const minScale = this._minScale(other); + this._downscale(this.scale - minScale); + this._diffBuckets(this.positive, other, other.positive, minScale); + this._diffBuckets(this.negative, other, other.negative, minScale); + } + /** + * clone returns a deep copy of self + * @returns {ExponentialHistogramAccumulation} + */ + clone() { + return new ExponentialHistogramAccumulation(this.startTime, this._maxSize, this._recordMinMax, this._sum, this._count, this._zeroCount, this._min, this._max, this.positive.clone(), this.negative.clone(), this._mapping); + } + /** + * _updateBuckets maps the incoming value to a bucket index for the current + * scale. If the bucket index is outside of the range of the backing array, + * it will rescale the backing array and update the mapping for the new scale. + */ + _updateBuckets(buckets, value, increment) { + let index = this._mapping.mapToIndex(value); + // rescale the mapping if needed + let rescalingNeeded = false; + let high = 0; + let low = 0; + if (buckets.length === 0) { + buckets.indexStart = index; + buckets.indexEnd = buckets.indexStart; + buckets.indexBase = buckets.indexStart; + } + else if (index < buckets.indexStart && + buckets.indexEnd - index >= this._maxSize) { + rescalingNeeded = true; + low = index; + high = buckets.indexEnd; + } + else if (index > buckets.indexEnd && + index - buckets.indexStart >= this._maxSize) { + rescalingNeeded = true; + low = buckets.indexStart; + high = index; + } + // rescale and compute index at new scale + if (rescalingNeeded) { + const change = this._changeScale(high, low); + this._downscale(change); + index = this._mapping.mapToIndex(value); + } + this._incrementIndexBy(buckets, index, increment); + } + /** + * _incrementIndexBy increments the count of the bucket specified by `index`. + * If the index is outside of the range [buckets.indexStart, buckets.indexEnd] + * the boundaries of the backing array will be adjusted and more buckets will + * be added if needed. + */ + _incrementIndexBy(buckets, index, increment) { + if (increment === 0) { + // nothing to do for a zero increment, can happen during a merge operation + return; + } + if (buckets.length === 0) { + buckets.indexStart = buckets.indexEnd = buckets.indexBase = index; + } + if (index < buckets.indexStart) { + const span = buckets.indexEnd - index; + if (span >= buckets.backing.length) { + this._grow(buckets, span + 1); + } + buckets.indexStart = index; + } + else if (index > buckets.indexEnd) { + const span = index - buckets.indexStart; + if (span >= buckets.backing.length) { + this._grow(buckets, span + 1); + } + buckets.indexEnd = index; + } + let bucketIndex = index - buckets.indexBase; + if (bucketIndex < 0) { + bucketIndex += buckets.backing.length; + } + buckets.incrementBucket(bucketIndex, increment); + } + /** + * grow resizes the backing array by doubling in size up to maxSize. + * This extends the array with a bunch of zeros and copies the + * existing counts to the same position. + */ + _grow(buckets, needed) { + const size = buckets.backing.length; + const bias = buckets.indexBase - buckets.indexStart; + const oldPositiveLimit = size - bias; + let newSize = (0, util_1.nextGreaterSquare)(needed); + if (newSize > this._maxSize) { + newSize = this._maxSize; + } + const newPositiveLimit = newSize - bias; + buckets.backing.growTo(newSize, oldPositiveLimit, newPositiveLimit); + } + /** + * _changeScale computes how much downscaling is needed by shifting the + * high and low values until they are separated by no more than size. + */ + _changeScale(high, low) { + let change = 0; + while (high - low >= this._maxSize) { + high >>= 1; + low >>= 1; + change++; + } + return change; + } + /** + * _downscale subtracts `change` from the current mapping scale. + */ + _downscale(change) { + if (change === 0) { + return; + } + if (change < 0) { + // Note: this should be impossible. If we get here it's because + // there is a bug in the implementation. + throw new Error(`impossible change of scale: ${this.scale}`); + } + const newScale = this._mapping.scale - change; + this._positive.downscale(change); + this._negative.downscale(change); + this._mapping = (0, getMapping_1.getMapping)(newScale); + } + /** + * _minScale is used by diff and merge to compute an ideal combined scale + */ + _minScale(other) { + const minScale = Math.min(this.scale, other.scale); + const highLowPos = HighLow.combine(this._highLowAtScale(this.positive, this.scale, minScale), this._highLowAtScale(other.positive, other.scale, minScale)); + const highLowNeg = HighLow.combine(this._highLowAtScale(this.negative, this.scale, minScale), this._highLowAtScale(other.negative, other.scale, minScale)); + return Math.min(minScale - this._changeScale(highLowPos.high, highLowPos.low), minScale - this._changeScale(highLowNeg.high, highLowNeg.low)); + } + /** + * _highLowAtScale is used by diff and merge to compute an ideal combined scale. + */ + _highLowAtScale(buckets, currentScale, newScale) { + if (buckets.length === 0) { + return new HighLow(0, -1); + } + const shift = currentScale - newScale; + return new HighLow(buckets.indexStart >> shift, buckets.indexEnd >> shift); + } + /** + * _mergeBuckets translates index values from another histogram and + * adds the values into the corresponding buckets of this histogram. + */ + _mergeBuckets(ours, other, theirs, scale) { + const theirOffset = theirs.offset; + const theirChange = other.scale - scale; + for (let i = 0; i < theirs.length; i++) { + this._incrementIndexBy(ours, (theirOffset + i) >> theirChange, theirs.at(i)); + } + } + /** + * _diffBuckets translates index values from another histogram and + * subtracts the values in the corresponding buckets of this histogram. + */ + _diffBuckets(ours, other, theirs, scale) { + const theirOffset = theirs.offset; + const theirChange = other.scale - scale; + for (let i = 0; i < theirs.length; i++) { + const ourIndex = (theirOffset + i) >> theirChange; + let bucketIndex = ourIndex - ours.indexBase; + if (bucketIndex < 0) { + bucketIndex += ours.backing.length; + } + ours.decrementBucket(bucketIndex, theirs.at(i)); + } + ours.trim(); + } +} +exports.ExponentialHistogramAccumulation = ExponentialHistogramAccumulation; +/** + * Aggregator for ExponentialHistogramAccumulations + */ +class ExponentialHistogramAggregator { + _maxSize; + _recordMinMax; + kind = types_1.AggregatorKind.EXPONENTIAL_HISTOGRAM; + /** + * @param _maxSize Maximum number of buckets for each of the positive + * and negative ranges, exclusive of the zero-bucket. + * @param _recordMinMax If set to true, min and max will be recorded. + * Otherwise, min and max will not be recorded. + */ + constructor(_maxSize, _recordMinMax) { + this._maxSize = _maxSize; + this._recordMinMax = _recordMinMax; + } + createAccumulation(startTime) { + return new ExponentialHistogramAccumulation(startTime, this._maxSize, this._recordMinMax); + } + /** + * Return the result of the merge of two exponential histogram accumulations. + */ + merge(previous, delta) { + const result = delta.clone(); + result.merge(previous); + return result; + } + /** + * Returns a new DELTA aggregation by comparing two cumulative measurements. + */ + diff(previous, current) { + const result = current.clone(); + result.diff(previous); + return result; + } + toMetricData(descriptor, aggregationTemporality, accumulationByAttributes, endTime) { + return { + descriptor, + aggregationTemporality, + dataPointType: MetricData_1.DataPointType.EXPONENTIAL_HISTOGRAM, + dataPoints: accumulationByAttributes.map(([attributes, accumulation]) => { + const pointValue = accumulation.toPointValue(); + // determine if instrument allows negative values. + const allowsNegativeValues = descriptor.type === MetricData_1.InstrumentType.GAUGE || + descriptor.type === MetricData_1.InstrumentType.UP_DOWN_COUNTER || + descriptor.type === MetricData_1.InstrumentType.OBSERVABLE_GAUGE || + descriptor.type === MetricData_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER; + return { + attributes, + startTime: accumulation.startTime, + endTime, + value: { + min: pointValue.hasMinMax ? pointValue.min : undefined, + max: pointValue.hasMinMax ? pointValue.max : undefined, + sum: !allowsNegativeValues ? pointValue.sum : undefined, + positive: { + offset: pointValue.positive.offset, + bucketCounts: pointValue.positive.bucketCounts, + }, + negative: { + offset: pointValue.negative.offset, + bucketCounts: pointValue.negative.bucketCounts, + }, + count: pointValue.count, + scale: pointValue.scale, + zeroCount: pointValue.zeroCount, + }, + }; + }), + }; + } +} +exports.ExponentialHistogramAggregator = ExponentialHistogramAggregator; +//# sourceMappingURL=ExponentialHistogram.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Histogram.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Histogram.js new file mode 100644 index 00000000..250a2b95 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Histogram.js @@ -0,0 +1,187 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.HistogramAggregator = exports.HistogramAccumulation = void 0; +const types_1 = require("./types"); +const MetricData_1 = require("../export/MetricData"); +const utils_1 = require("../utils"); +function createNewEmptyCheckpoint(boundaries) { + const counts = boundaries.map(() => 0); + counts.push(0); + return { + buckets: { + boundaries, + counts, + }, + sum: 0, + count: 0, + hasMinMax: false, + min: Infinity, + max: -Infinity, + }; +} +class HistogramAccumulation { + startTime; + _boundaries; + _recordMinMax; + _current; + constructor(startTime, _boundaries, _recordMinMax = true, _current = createNewEmptyCheckpoint(_boundaries)) { + this.startTime = startTime; + this._boundaries = _boundaries; + this._recordMinMax = _recordMinMax; + this._current = _current; + } + record(value) { + // NaN does not fall into any bucket, is not zero and should not be counted, + // NaN is never greater than max nor less than min, therefore return as there's nothing for us to do. + if (Number.isNaN(value)) { + return; + } + this._current.count += 1; + this._current.sum += value; + if (this._recordMinMax) { + this._current.min = Math.min(value, this._current.min); + this._current.max = Math.max(value, this._current.max); + this._current.hasMinMax = true; + } + const idx = (0, utils_1.binarySearchUB)(this._boundaries, value); + this._current.buckets.counts[idx] += 1; + } + setStartTime(startTime) { + this.startTime = startTime; + } + toPointValue() { + return this._current; + } +} +exports.HistogramAccumulation = HistogramAccumulation; +/** + * Basic aggregator which observes events and counts them in pre-defined buckets + * and provides the total sum and count of all observations. + */ +class HistogramAggregator { + _boundaries; + _recordMinMax; + kind = types_1.AggregatorKind.HISTOGRAM; + /** + * @param _boundaries sorted upper bounds of recorded values. + * @param _recordMinMax If set to true, min and max will be recorded. Otherwise, min and max will not be recorded. + */ + constructor(_boundaries, _recordMinMax) { + this._boundaries = _boundaries; + this._recordMinMax = _recordMinMax; + } + createAccumulation(startTime) { + return new HistogramAccumulation(startTime, this._boundaries, this._recordMinMax); + } + /** + * Return the result of the merge of two histogram accumulations. As long as one Aggregator + * instance produces all Accumulations with constant boundaries we don't need to worry about + * merging accumulations with different boundaries. + */ + merge(previous, delta) { + const previousValue = previous.toPointValue(); + const deltaValue = delta.toPointValue(); + const previousCounts = previousValue.buckets.counts; + const deltaCounts = deltaValue.buckets.counts; + const mergedCounts = new Array(previousCounts.length); + for (let idx = 0; idx < previousCounts.length; idx++) { + mergedCounts[idx] = previousCounts[idx] + deltaCounts[idx]; + } + let min = Infinity; + let max = -Infinity; + if (this._recordMinMax) { + if (previousValue.hasMinMax && deltaValue.hasMinMax) { + min = Math.min(previousValue.min, deltaValue.min); + max = Math.max(previousValue.max, deltaValue.max); + } + else if (previousValue.hasMinMax) { + min = previousValue.min; + max = previousValue.max; + } + else if (deltaValue.hasMinMax) { + min = deltaValue.min; + max = deltaValue.max; + } + } + return new HistogramAccumulation(previous.startTime, previousValue.buckets.boundaries, this._recordMinMax, { + buckets: { + boundaries: previousValue.buckets.boundaries, + counts: mergedCounts, + }, + count: previousValue.count + deltaValue.count, + sum: previousValue.sum + deltaValue.sum, + hasMinMax: this._recordMinMax && + (previousValue.hasMinMax || deltaValue.hasMinMax), + min: min, + max: max, + }); + } + /** + * Returns a new DELTA aggregation by comparing two cumulative measurements. + */ + diff(previous, current) { + const previousValue = previous.toPointValue(); + const currentValue = current.toPointValue(); + const previousCounts = previousValue.buckets.counts; + const currentCounts = currentValue.buckets.counts; + const diffedCounts = new Array(previousCounts.length); + for (let idx = 0; idx < previousCounts.length; idx++) { + diffedCounts[idx] = currentCounts[idx] - previousCounts[idx]; + } + return new HistogramAccumulation(current.startTime, previousValue.buckets.boundaries, this._recordMinMax, { + buckets: { + boundaries: previousValue.buckets.boundaries, + counts: diffedCounts, + }, + count: currentValue.count - previousValue.count, + sum: currentValue.sum - previousValue.sum, + hasMinMax: false, + min: Infinity, + max: -Infinity, + }); + } + toMetricData(descriptor, aggregationTemporality, accumulationByAttributes, endTime) { + return { + descriptor, + aggregationTemporality, + dataPointType: MetricData_1.DataPointType.HISTOGRAM, + dataPoints: accumulationByAttributes.map(([attributes, accumulation]) => { + const pointValue = accumulation.toPointValue(); + // determine if instrument allows negative values. + const allowsNegativeValues = descriptor.type === MetricData_1.InstrumentType.GAUGE || + descriptor.type === MetricData_1.InstrumentType.UP_DOWN_COUNTER || + descriptor.type === MetricData_1.InstrumentType.OBSERVABLE_GAUGE || + descriptor.type === MetricData_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER; + return { + attributes, + startTime: accumulation.startTime, + endTime, + value: { + min: pointValue.hasMinMax ? pointValue.min : undefined, + max: pointValue.hasMinMax ? pointValue.max : undefined, + sum: !allowsNegativeValues ? pointValue.sum : undefined, + buckets: pointValue.buckets, + count: pointValue.count, + }, + }; + }), + }; + } +} +exports.HistogramAggregator = HistogramAggregator; +//# sourceMappingURL=Histogram.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/LastValue.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/LastValue.js new file mode 100644 index 00000000..00e945c7 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/LastValue.js @@ -0,0 +1,93 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LastValueAggregator = exports.LastValueAccumulation = void 0; +const types_1 = require("./types"); +const core_1 = require("@opentelemetry/core"); +const MetricData_1 = require("../export/MetricData"); +class LastValueAccumulation { + startTime; + _current; + sampleTime; + constructor(startTime, _current = 0, sampleTime = [0, 0]) { + this.startTime = startTime; + this._current = _current; + this.sampleTime = sampleTime; + } + record(value) { + this._current = value; + this.sampleTime = (0, core_1.millisToHrTime)(Date.now()); + } + setStartTime(startTime) { + this.startTime = startTime; + } + toPointValue() { + return this._current; + } +} +exports.LastValueAccumulation = LastValueAccumulation; +/** Basic aggregator which calculates a LastValue from individual measurements. */ +class LastValueAggregator { + kind = types_1.AggregatorKind.LAST_VALUE; + createAccumulation(startTime) { + return new LastValueAccumulation(startTime); + } + /** + * Returns the result of the merge of the given accumulations. + * + * Return the newly captured (delta) accumulation for LastValueAggregator. + */ + merge(previous, delta) { + // nanoseconds may lose precisions. + const latestAccumulation = (0, core_1.hrTimeToMicroseconds)(delta.sampleTime) >= + (0, core_1.hrTimeToMicroseconds)(previous.sampleTime) + ? delta + : previous; + return new LastValueAccumulation(previous.startTime, latestAccumulation.toPointValue(), latestAccumulation.sampleTime); + } + /** + * Returns a new DELTA aggregation by comparing two cumulative measurements. + * + * A delta aggregation is not meaningful to LastValueAggregator, just return + * the newly captured (delta) accumulation for LastValueAggregator. + */ + diff(previous, current) { + // nanoseconds may lose precisions. + const latestAccumulation = (0, core_1.hrTimeToMicroseconds)(current.sampleTime) >= + (0, core_1.hrTimeToMicroseconds)(previous.sampleTime) + ? current + : previous; + return new LastValueAccumulation(current.startTime, latestAccumulation.toPointValue(), latestAccumulation.sampleTime); + } + toMetricData(descriptor, aggregationTemporality, accumulationByAttributes, endTime) { + return { + descriptor, + aggregationTemporality, + dataPointType: MetricData_1.DataPointType.GAUGE, + dataPoints: accumulationByAttributes.map(([attributes, accumulation]) => { + return { + attributes, + startTime: accumulation.startTime, + endTime, + value: accumulation.toPointValue(), + }; + }), + }; + } +} +exports.LastValueAggregator = LastValueAggregator; +//# sourceMappingURL=LastValue.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Sum.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Sum.js new file mode 100644 index 00000000..9fdb343f --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Sum.js @@ -0,0 +1,101 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SumAggregator = exports.SumAccumulation = void 0; +const types_1 = require("./types"); +const MetricData_1 = require("../export/MetricData"); +class SumAccumulation { + startTime; + monotonic; + _current; + reset; + constructor(startTime, monotonic, _current = 0, reset = false) { + this.startTime = startTime; + this.monotonic = monotonic; + this._current = _current; + this.reset = reset; + } + record(value) { + if (this.monotonic && value < 0) { + return; + } + this._current += value; + } + setStartTime(startTime) { + this.startTime = startTime; + } + toPointValue() { + return this._current; + } +} +exports.SumAccumulation = SumAccumulation; +/** Basic aggregator which calculates a Sum from individual measurements. */ +class SumAggregator { + monotonic; + kind = types_1.AggregatorKind.SUM; + constructor(monotonic) { + this.monotonic = monotonic; + } + createAccumulation(startTime) { + return new SumAccumulation(startTime, this.monotonic); + } + /** + * Returns the result of the merge of the given accumulations. + */ + merge(previous, delta) { + const prevPv = previous.toPointValue(); + const deltaPv = delta.toPointValue(); + if (delta.reset) { + return new SumAccumulation(delta.startTime, this.monotonic, deltaPv, delta.reset); + } + return new SumAccumulation(previous.startTime, this.monotonic, prevPv + deltaPv); + } + /** + * Returns a new DELTA aggregation by comparing two cumulative measurements. + */ + diff(previous, current) { + const prevPv = previous.toPointValue(); + const currPv = current.toPointValue(); + /** + * If the SumAggregator is a monotonic one and the previous point value is + * greater than the current one, a reset is deemed to be happened. + * Return the current point value to prevent the value from been reset. + */ + if (this.monotonic && prevPv > currPv) { + return new SumAccumulation(current.startTime, this.monotonic, currPv, true); + } + return new SumAccumulation(current.startTime, this.monotonic, currPv - prevPv); + } + toMetricData(descriptor, aggregationTemporality, accumulationByAttributes, endTime) { + return { + descriptor, + aggregationTemporality, + dataPointType: MetricData_1.DataPointType.SUM, + dataPoints: accumulationByAttributes.map(([attributes, accumulation]) => { + return { + attributes, + startTime: accumulation.startTime, + endTime, + value: accumulation.toPointValue(), + }; + }), + isMonotonic: this.monotonic, + }; + } +} +exports.SumAggregator = SumAggregator; +//# sourceMappingURL=Sum.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/Buckets.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/Buckets.js new file mode 100644 index 00000000..cf61e328 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/Buckets.js @@ -0,0 +1,277 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Buckets = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Buckets { + backing; + indexBase; + indexStart; + indexEnd; + /** + * The term index refers to the number of the exponential histogram bucket + * used to determine its boundaries. The lower boundary of a bucket is + * determined by base ** index and the upper boundary of a bucket is + * determined by base ** (index + 1). index values are signed to account + * for values less than or equal to 1. + * + * indexBase is the index of the 0th position in the + * backing array, i.e., backing[0] is the count + * in the bucket with index `indexBase`. + * + * indexStart is the smallest index value represented + * in the backing array. + * + * indexEnd is the largest index value represented in + * the backing array. + */ + constructor(backing = new BucketsBacking(), indexBase = 0, indexStart = 0, indexEnd = 0) { + this.backing = backing; + this.indexBase = indexBase; + this.indexStart = indexStart; + this.indexEnd = indexEnd; + } + /** + * Offset is the bucket index of the smallest entry in the counts array + * @returns {number} + */ + get offset() { + return this.indexStart; + } + /** + * Buckets is a view into the backing array. + * @returns {number} + */ + get length() { + if (this.backing.length === 0) { + return 0; + } + if (this.indexEnd === this.indexStart && this.at(0) === 0) { + return 0; + } + return this.indexEnd - this.indexStart + 1; + } + /** + * An array of counts, where count[i] carries the count + * of the bucket at index (offset+i). count[i] is the count of + * values greater than base^(offset+i) and less than or equal to + * base^(offset+i+1). + * @returns {number} The logical counts based on the backing array + */ + counts() { + return Array.from({ length: this.length }, (_, i) => this.at(i)); + } + /** + * At returns the count of the bucket at a position in the logical + * array of counts. + * @param position + * @returns {number} + */ + at(position) { + const bias = this.indexBase - this.indexStart; + if (position < bias) { + position += this.backing.length; + } + position -= bias; + return this.backing.countAt(position); + } + /** + * incrementBucket increments the backing array index by `increment` + * @param bucketIndex + * @param increment + */ + incrementBucket(bucketIndex, increment) { + this.backing.increment(bucketIndex, increment); + } + /** + * decrementBucket decrements the backing array index by `decrement` + * if decrement is greater than the current value, it's set to 0. + * @param bucketIndex + * @param decrement + */ + decrementBucket(bucketIndex, decrement) { + this.backing.decrement(bucketIndex, decrement); + } + /** + * trim removes leading and / or trailing zero buckets (which can occur + * after diffing two histos) and rotates the backing array so that the + * smallest non-zero index is in the 0th position of the backing array + */ + trim() { + for (let i = 0; i < this.length; i++) { + if (this.at(i) !== 0) { + this.indexStart += i; + break; + } + else if (i === this.length - 1) { + //the entire array is zeroed out + this.indexStart = this.indexEnd = this.indexBase = 0; + return; + } + } + for (let i = this.length - 1; i >= 0; i--) { + if (this.at(i) !== 0) { + this.indexEnd -= this.length - i - 1; + break; + } + } + this._rotate(); + } + /** + * downscale first rotates, then collapses 2**`by`-to-1 buckets. + * @param by + */ + downscale(by) { + this._rotate(); + const size = 1 + this.indexEnd - this.indexStart; + const each = 1 << by; + let inpos = 0; + let outpos = 0; + for (let pos = this.indexStart; pos <= this.indexEnd;) { + let mod = pos % each; + if (mod < 0) { + mod += each; + } + for (let i = mod; i < each && inpos < size; i++) { + this._relocateBucket(outpos, inpos); + inpos++; + pos++; + } + outpos++; + } + this.indexStart >>= by; + this.indexEnd >>= by; + this.indexBase = this.indexStart; + } + /** + * Clone returns a deep copy of Buckets + * @returns {Buckets} + */ + clone() { + return new Buckets(this.backing.clone(), this.indexBase, this.indexStart, this.indexEnd); + } + /** + * _rotate shifts the backing array contents so that indexStart == + * indexBase to simplify the downscale logic. + */ + _rotate() { + const bias = this.indexBase - this.indexStart; + if (bias === 0) { + return; + } + else if (bias > 0) { + this.backing.reverse(0, this.backing.length); + this.backing.reverse(0, bias); + this.backing.reverse(bias, this.backing.length); + } + else { + // negative bias, this can happen when diffing two histograms + this.backing.reverse(0, this.backing.length); + this.backing.reverse(0, this.backing.length + bias); + } + this.indexBase = this.indexStart; + } + /** + * _relocateBucket adds the count in counts[src] to counts[dest] and + * resets count[src] to zero. + */ + _relocateBucket(dest, src) { + if (dest === src) { + return; + } + this.incrementBucket(dest, this.backing.emptyBucket(src)); + } +} +exports.Buckets = Buckets; +/** + * BucketsBacking holds the raw buckets and some utility methods to + * manage them. + */ +class BucketsBacking { + _counts; + constructor(_counts = [0]) { + this._counts = _counts; + } + /** + * length returns the physical size of the backing array, which + * is >= buckets.length() + */ + get length() { + return this._counts.length; + } + /** + * countAt returns the count in a specific bucket + */ + countAt(pos) { + return this._counts[pos]; + } + /** + * growTo grows a backing array and copies old entries + * into their correct new positions. + */ + growTo(newSize, oldPositiveLimit, newPositiveLimit) { + const tmp = new Array(newSize).fill(0); + tmp.splice(newPositiveLimit, this._counts.length - oldPositiveLimit, ...this._counts.slice(oldPositiveLimit)); + tmp.splice(0, oldPositiveLimit, ...this._counts.slice(0, oldPositiveLimit)); + this._counts = tmp; + } + /** + * reverse the items in the backing array in the range [from, limit). + */ + reverse(from, limit) { + const num = Math.floor((from + limit) / 2) - from; + for (let i = 0; i < num; i++) { + const tmp = this._counts[from + i]; + this._counts[from + i] = this._counts[limit - i - 1]; + this._counts[limit - i - 1] = tmp; + } + } + /** + * emptyBucket empties the count from a bucket, for + * moving into another. + */ + emptyBucket(src) { + const tmp = this._counts[src]; + this._counts[src] = 0; + return tmp; + } + /** + * increments a bucket by `increment` + */ + increment(bucketIndex, increment) { + this._counts[bucketIndex] += increment; + } + /** + * decrements a bucket by `decrement` + */ + decrement(bucketIndex, decrement) { + if (this._counts[bucketIndex] >= decrement) { + this._counts[bucketIndex] -= decrement; + } + else { + // this should not happen, but we're being defensive against + // negative counts. + this._counts[bucketIndex] = 0; + } + } + /** + * clone returns a deep copy of BucketsBacking + */ + clone() { + return new BucketsBacking([...this._counts]); + } +} +//# sourceMappingURL=Buckets.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/ExponentMapping.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/ExponentMapping.js new file mode 100644 index 00000000..7ce881f0 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/ExponentMapping.js @@ -0,0 +1,90 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ExponentMapping = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const ieee754 = require("./ieee754"); +const util = require("../util"); +const types_1 = require("./types"); +/** + * ExponentMapping implements exponential mapping functions for + * scales <=0. For scales > 0 LogarithmMapping should be used. + */ +class ExponentMapping { + _shift; + constructor(scale) { + this._shift = -scale; + } + /** + * Maps positive floating point values to indexes corresponding to scale + * @param value + * @returns {number} index for provided value at the current scale + */ + mapToIndex(value) { + if (value < ieee754.MIN_VALUE) { + return this._minNormalLowerBoundaryIndex(); + } + const exp = ieee754.getNormalBase2(value); + // In case the value is an exact power of two, compute a + // correction of -1. Note, we are using a custom _rightShift + // to accommodate a 52-bit argument, which the native bitwise + // operators do not support + const correction = this._rightShift(ieee754.getSignificand(value) - 1, ieee754.SIGNIFICAND_WIDTH); + return (exp + correction) >> this._shift; + } + /** + * Returns the lower bucket boundary for the given index for scale + * + * @param index + * @returns {number} + */ + lowerBoundary(index) { + const minIndex = this._minNormalLowerBoundaryIndex(); + if (index < minIndex) { + throw new types_1.MappingError(`underflow: ${index} is < minimum lower boundary: ${minIndex}`); + } + const maxIndex = this._maxNormalLowerBoundaryIndex(); + if (index > maxIndex) { + throw new types_1.MappingError(`overflow: ${index} is > maximum lower boundary: ${maxIndex}`); + } + return util.ldexp(1, index << this._shift); + } + /** + * The scale used by this mapping + * @returns {number} + */ + get scale() { + if (this._shift === 0) { + return 0; + } + return -this._shift; + } + _minNormalLowerBoundaryIndex() { + let index = ieee754.MIN_NORMAL_EXPONENT >> this._shift; + if (this._shift < 2) { + index--; + } + return index; + } + _maxNormalLowerBoundaryIndex() { + return ieee754.MAX_NORMAL_EXPONENT >> this._shift; + } + _rightShift(value, shift) { + return Math.floor(value * Math.pow(2, -shift)); + } +} +exports.ExponentMapping = ExponentMapping; +//# sourceMappingURL=ExponentMapping.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/LogarithmMapping.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/LogarithmMapping.js new file mode 100644 index 00000000..0ce364a9 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/LogarithmMapping.js @@ -0,0 +1,98 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LogarithmMapping = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const ieee754 = require("./ieee754"); +const util = require("../util"); +const types_1 = require("./types"); +/** + * LogarithmMapping implements exponential mapping functions for scale > 0. + * For scales <= 0 the exponent mapping should be used. + */ +class LogarithmMapping { + _scale; + _scaleFactor; + _inverseFactor; + constructor(scale) { + this._scale = scale; + this._scaleFactor = util.ldexp(Math.LOG2E, scale); + this._inverseFactor = util.ldexp(Math.LN2, -scale); + } + /** + * Maps positive floating point values to indexes corresponding to scale + * @param value + * @returns {number} index for provided value at the current scale + */ + mapToIndex(value) { + if (value <= ieee754.MIN_VALUE) { + return this._minNormalLowerBoundaryIndex() - 1; + } + // exact power of two special case + if (ieee754.getSignificand(value) === 0) { + const exp = ieee754.getNormalBase2(value); + return (exp << this._scale) - 1; + } + // non-power of two cases. use Math.floor to round the scaled logarithm + const index = Math.floor(Math.log(value) * this._scaleFactor); + const maxIndex = this._maxNormalLowerBoundaryIndex(); + if (index >= maxIndex) { + return maxIndex; + } + return index; + } + /** + * Returns the lower bucket boundary for the given index for scale + * + * @param index + * @returns {number} + */ + lowerBoundary(index) { + const maxIndex = this._maxNormalLowerBoundaryIndex(); + if (index >= maxIndex) { + if (index === maxIndex) { + return 2 * Math.exp((index - (1 << this._scale)) / this._scaleFactor); + } + throw new types_1.MappingError(`overflow: ${index} is > maximum lower boundary: ${maxIndex}`); + } + const minIndex = this._minNormalLowerBoundaryIndex(); + if (index <= minIndex) { + if (index === minIndex) { + return ieee754.MIN_VALUE; + } + else if (index === minIndex - 1) { + return Math.exp((index + (1 << this._scale)) / this._scaleFactor) / 2; + } + throw new types_1.MappingError(`overflow: ${index} is < minimum lower boundary: ${minIndex}`); + } + return Math.exp(index * this._inverseFactor); + } + /** + * The scale used by this mapping + * @returns {number} + */ + get scale() { + return this._scale; + } + _minNormalLowerBoundaryIndex() { + return ieee754.MIN_NORMAL_EXPONENT << this._scale; + } + _maxNormalLowerBoundaryIndex() { + return ((ieee754.MAX_NORMAL_EXPONENT + 1) << this._scale) - 1; + } +} +exports.LogarithmMapping = LogarithmMapping; +//# sourceMappingURL=LogarithmMapping.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/getMapping.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/getMapping.js new file mode 100644 index 00000000..5ba88f3a --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/getMapping.js @@ -0,0 +1,45 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getMapping = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const ExponentMapping_1 = require("./ExponentMapping"); +const LogarithmMapping_1 = require("./LogarithmMapping"); +const types_1 = require("./types"); +const MIN_SCALE = -10; +const MAX_SCALE = 20; +const PREBUILT_MAPPINGS = Array.from({ length: 31 }, (_, i) => { + if (i > 10) { + return new LogarithmMapping_1.LogarithmMapping(i - 10); + } + return new ExponentMapping_1.ExponentMapping(i - 10); +}); +/** + * getMapping returns an appropriate mapping for the given scale. For scales -10 + * to 0 the underlying type will be ExponentMapping. For scales 1 to 20 the + * underlying type will be LogarithmMapping. + * @param scale a number in the range [-10, 20] + * @returns {Mapping} + */ +function getMapping(scale) { + if (scale > MAX_SCALE || scale < MIN_SCALE) { + throw new types_1.MappingError(`expected scale >= ${MIN_SCALE} && <= ${MAX_SCALE}, got: ${scale}`); + } + // mappings are offset by 10. scale -10 is at position 0 and scale 20 is at 30 + return PREBUILT_MAPPINGS[scale + 10]; +} +exports.getMapping = getMapping; +//# sourceMappingURL=getMapping.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/ieee754.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/ieee754.js new file mode 100644 index 00000000..f5323182 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/ieee754.js @@ -0,0 +1,94 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getSignificand = exports.getNormalBase2 = exports.MIN_VALUE = exports.MAX_NORMAL_EXPONENT = exports.MIN_NORMAL_EXPONENT = exports.SIGNIFICAND_WIDTH = void 0; +/** + * The functions and constants in this file allow us to interact + * with the internal representation of an IEEE 64-bit floating point + * number. We need to work with all 64-bits, thus, care needs to be + * taken when working with Javascript's bitwise operators (<<, >>, &, + * |, etc) as they truncate operands to 32-bits. In order to work around + * this we work with the 64-bits as two 32-bit halves, perform bitwise + * operations on them independently, and combine the results (if needed). + */ +exports.SIGNIFICAND_WIDTH = 52; +/** + * EXPONENT_MASK is set to 1 for the hi 32-bits of an IEEE 754 + * floating point exponent: 0x7ff00000. + */ +const EXPONENT_MASK = 0x7ff00000; +/** + * SIGNIFICAND_MASK is the mask for the significand portion of the hi 32-bits + * of an IEEE 754 double-precision floating-point value: 0xfffff + */ +const SIGNIFICAND_MASK = 0xfffff; +/** + * EXPONENT_BIAS is the exponent bias specified for encoding + * the IEEE 754 double-precision floating point exponent: 1023 + */ +const EXPONENT_BIAS = 1023; +/** + * MIN_NORMAL_EXPONENT is the minimum exponent of a normalized + * floating point: -1022. + */ +exports.MIN_NORMAL_EXPONENT = -EXPONENT_BIAS + 1; +/** + * MAX_NORMAL_EXPONENT is the maximum exponent of a normalized + * floating point: 1023. + */ +exports.MAX_NORMAL_EXPONENT = EXPONENT_BIAS; +/** + * MIN_VALUE is the smallest normal number + */ +exports.MIN_VALUE = Math.pow(2, -1022); +/** + * getNormalBase2 extracts the normalized base-2 fractional exponent. + * This returns k for the equation f x 2**k where f is + * in the range [1, 2). Note that this function is not called for + * subnormal numbers. + * @param {number} value - the value to determine normalized base-2 fractional + * exponent for + * @returns {number} the normalized base-2 exponent + */ +function getNormalBase2(value) { + const dv = new DataView(new ArrayBuffer(8)); + dv.setFloat64(0, value); + // access the raw 64-bit float as 32-bit uints + const hiBits = dv.getUint32(0); + const expBits = (hiBits & EXPONENT_MASK) >> 20; + return expBits - EXPONENT_BIAS; +} +exports.getNormalBase2 = getNormalBase2; +/** + * GetSignificand returns the 52 bit (unsigned) significand as a signed value. + * @param {number} value - the floating point number to extract the significand from + * @returns {number} The 52-bit significand + */ +function getSignificand(value) { + const dv = new DataView(new ArrayBuffer(8)); + dv.setFloat64(0, value); + // access the raw 64-bit float as two 32-bit uints + const hiBits = dv.getUint32(0); + const loBits = dv.getUint32(4); + // extract the significand bits from the hi bits and left shift 32 places note: + // we can't use the native << operator as it will truncate the result to 32-bits + const significandHiBits = (hiBits & SIGNIFICAND_MASK) * Math.pow(2, 32); + // combine the hi and lo bits and return + return significandHiBits + loBits; +} +exports.getSignificand = getSignificand; +//# sourceMappingURL=ieee754.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/types.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/types.js new file mode 100644 index 00000000..49602b80 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/types.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MappingError = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class MappingError extends Error { +} +exports.MappingError = MappingError; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/util.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/util.js new file mode 100644 index 00000000..1c1734d3 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/util.js @@ -0,0 +1,63 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.nextGreaterSquare = exports.ldexp = void 0; +/** + * Note: other languages provide this as a built in function. This is + * a naive, but functionally correct implementation. This is used sparingly, + * when creating a new mapping in a running application. + * + * ldexp returns frac × 2**exp. With the following special cases: + * ldexp(±0, exp) = ±0 + * ldexp(±Inf, exp) = ±Inf + * ldexp(NaN, exp) = NaN + * @param frac + * @param exp + * @returns {number} + */ +function ldexp(frac, exp) { + if (frac === 0 || + frac === Number.POSITIVE_INFINITY || + frac === Number.NEGATIVE_INFINITY || + Number.isNaN(frac)) { + return frac; + } + return frac * Math.pow(2, exp); +} +exports.ldexp = ldexp; +/** + * Computes the next power of two that is greater than or equal to v. + * This implementation more efficient than, but functionally equivalent + * to Math.pow(2, Math.ceil(Math.log(x)/Math.log(2))). + * @param v + * @returns {number} + */ +function nextGreaterSquare(v) { + // The following expression computes the least power-of-two + // that is >= v. There are a number of tricky ways to + // do this, see https://stackoverflow.com/questions/466204/rounding-up-to-next-power-of-2 + v--; + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + v++; + return v; +} +exports.nextGreaterSquare = nextGreaterSquare; +//# sourceMappingURL=util.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/index.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/index.js new file mode 100644 index 00000000..ba6195bc --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/index.js @@ -0,0 +1,33 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SumAggregator = exports.SumAccumulation = exports.LastValueAggregator = exports.LastValueAccumulation = exports.ExponentialHistogramAggregator = exports.ExponentialHistogramAccumulation = exports.HistogramAggregator = exports.HistogramAccumulation = exports.DropAggregator = void 0; +var Drop_1 = require("./Drop"); +Object.defineProperty(exports, "DropAggregator", { enumerable: true, get: function () { return Drop_1.DropAggregator; } }); +var Histogram_1 = require("./Histogram"); +Object.defineProperty(exports, "HistogramAccumulation", { enumerable: true, get: function () { return Histogram_1.HistogramAccumulation; } }); +Object.defineProperty(exports, "HistogramAggregator", { enumerable: true, get: function () { return Histogram_1.HistogramAggregator; } }); +var ExponentialHistogram_1 = require("./ExponentialHistogram"); +Object.defineProperty(exports, "ExponentialHistogramAccumulation", { enumerable: true, get: function () { return ExponentialHistogram_1.ExponentialHistogramAccumulation; } }); +Object.defineProperty(exports, "ExponentialHistogramAggregator", { enumerable: true, get: function () { return ExponentialHistogram_1.ExponentialHistogramAggregator; } }); +var LastValue_1 = require("./LastValue"); +Object.defineProperty(exports, "LastValueAccumulation", { enumerable: true, get: function () { return LastValue_1.LastValueAccumulation; } }); +Object.defineProperty(exports, "LastValueAggregator", { enumerable: true, get: function () { return LastValue_1.LastValueAggregator; } }); +var Sum_1 = require("./Sum"); +Object.defineProperty(exports, "SumAccumulation", { enumerable: true, get: function () { return Sum_1.SumAccumulation; } }); +Object.defineProperty(exports, "SumAggregator", { enumerable: true, get: function () { return Sum_1.SumAggregator; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/types.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/types.js new file mode 100644 index 00000000..5f62e885 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/types.js @@ -0,0 +1,28 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AggregatorKind = void 0; +/** The kind of aggregator. */ +var AggregatorKind; +(function (AggregatorKind) { + AggregatorKind[AggregatorKind["DROP"] = 0] = "DROP"; + AggregatorKind[AggregatorKind["SUM"] = 1] = "SUM"; + AggregatorKind[AggregatorKind["LAST_VALUE"] = 2] = "LAST_VALUE"; + AggregatorKind[AggregatorKind["HISTOGRAM"] = 3] = "HISTOGRAM"; + AggregatorKind[AggregatorKind["EXPONENTIAL_HISTOGRAM"] = 4] = "EXPONENTIAL_HISTOGRAM"; +})(AggregatorKind = exports.AggregatorKind || (exports.AggregatorKind = {})); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/AggregationSelector.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/AggregationSelector.js new file mode 100644 index 00000000..6564b194 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/AggregationSelector.js @@ -0,0 +1,29 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR = exports.DEFAULT_AGGREGATION_SELECTOR = void 0; +const AggregationTemporality_1 = require("./AggregationTemporality"); +const AggregationOption_1 = require("../view/AggregationOption"); +const DEFAULT_AGGREGATION_SELECTOR = _instrumentType => { + return { + type: AggregationOption_1.AggregationType.DEFAULT, + }; +}; +exports.DEFAULT_AGGREGATION_SELECTOR = DEFAULT_AGGREGATION_SELECTOR; +const DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR = _instrumentType => AggregationTemporality_1.AggregationTemporality.CUMULATIVE; +exports.DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR = DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR; +//# sourceMappingURL=AggregationSelector.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/AggregationTemporality.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/AggregationTemporality.js new file mode 100644 index 00000000..e2334706 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/AggregationTemporality.js @@ -0,0 +1,27 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AggregationTemporality = void 0; +/** + * AggregationTemporality indicates the way additive quantities are expressed. + */ +var AggregationTemporality; +(function (AggregationTemporality) { + AggregationTemporality[AggregationTemporality["DELTA"] = 0] = "DELTA"; + AggregationTemporality[AggregationTemporality["CUMULATIVE"] = 1] = "CUMULATIVE"; +})(AggregationTemporality = exports.AggregationTemporality || (exports.AggregationTemporality = {})); +//# sourceMappingURL=AggregationTemporality.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/ConsoleMetricExporter.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/ConsoleMetricExporter.js new file mode 100644 index 00000000..04933858 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/ConsoleMetricExporter.js @@ -0,0 +1,67 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ConsoleMetricExporter = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const core_1 = require("@opentelemetry/core"); +const AggregationSelector_1 = require("./AggregationSelector"); +/** + * This is an implementation of {@link PushMetricExporter} that prints metrics to the + * console. This class can be used for diagnostic purposes. + * + * NOTE: This {@link PushMetricExporter} is intended for diagnostics use only, output rendered to the console may change at any time. + */ +/* eslint-disable no-console */ +class ConsoleMetricExporter { + _shutdown = false; + _temporalitySelector; + constructor(options) { + this._temporalitySelector = + options?.temporalitySelector ?? AggregationSelector_1.DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR; + } + export(metrics, resultCallback) { + if (this._shutdown) { + // If the exporter is shutting down, by spec, we need to return FAILED as export result + setImmediate(resultCallback, { code: core_1.ExportResultCode.FAILED }); + return; + } + return ConsoleMetricExporter._sendMetrics(metrics, resultCallback); + } + forceFlush() { + return Promise.resolve(); + } + selectAggregationTemporality(_instrumentType) { + return this._temporalitySelector(_instrumentType); + } + shutdown() { + this._shutdown = true; + return Promise.resolve(); + } + static _sendMetrics(metrics, done) { + for (const scopeMetrics of metrics.scopeMetrics) { + for (const metric of scopeMetrics.metrics) { + console.dir({ + descriptor: metric.descriptor, + dataPointType: metric.dataPointType, + dataPoints: metric.dataPoints, + }, { depth: null }); + } + } + done({ code: core_1.ExportResultCode.SUCCESS }); + } +} +exports.ConsoleMetricExporter = ConsoleMetricExporter; +//# sourceMappingURL=ConsoleMetricExporter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/InMemoryMetricExporter.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/InMemoryMetricExporter.js new file mode 100644 index 00000000..6033484b --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/InMemoryMetricExporter.js @@ -0,0 +1,66 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InMemoryMetricExporter = void 0; +const core_1 = require("@opentelemetry/core"); +/** + * In-memory Metrics Exporter is a Push Metric Exporter + * which accumulates metrics data in the local memory and + * allows to inspect it (useful for e.g. unit tests). + */ +class InMemoryMetricExporter { + _shutdown = false; + _aggregationTemporality; + _metrics = []; + constructor(aggregationTemporality) { + this._aggregationTemporality = aggregationTemporality; + } + /** + * @inheritedDoc + */ + export(metrics, resultCallback) { + // Avoid storing metrics when exporter is shutdown + if (this._shutdown) { + setTimeout(() => resultCallback({ code: core_1.ExportResultCode.FAILED }), 0); + return; + } + this._metrics.push(metrics); + setTimeout(() => resultCallback({ code: core_1.ExportResultCode.SUCCESS }), 0); + } + /** + * Returns all the collected resource metrics + * @returns ResourceMetrics[] + */ + getMetrics() { + return this._metrics; + } + forceFlush() { + return Promise.resolve(); + } + reset() { + this._metrics = []; + } + selectAggregationTemporality(_instrumentType) { + return this._aggregationTemporality; + } + shutdown() { + this._shutdown = true; + return Promise.resolve(); + } +} +exports.InMemoryMetricExporter = InMemoryMetricExporter; +//# sourceMappingURL=InMemoryMetricExporter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/MetricData.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/MetricData.js new file mode 100644 index 00000000..576dbf0f --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/MetricData.js @@ -0,0 +1,60 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DataPointType = exports.InstrumentType = void 0; +/** + * Supported types of metric instruments. + */ +var InstrumentType; +(function (InstrumentType) { + InstrumentType["COUNTER"] = "COUNTER"; + InstrumentType["GAUGE"] = "GAUGE"; + InstrumentType["HISTOGRAM"] = "HISTOGRAM"; + InstrumentType["UP_DOWN_COUNTER"] = "UP_DOWN_COUNTER"; + InstrumentType["OBSERVABLE_COUNTER"] = "OBSERVABLE_COUNTER"; + InstrumentType["OBSERVABLE_GAUGE"] = "OBSERVABLE_GAUGE"; + InstrumentType["OBSERVABLE_UP_DOWN_COUNTER"] = "OBSERVABLE_UP_DOWN_COUNTER"; +})(InstrumentType = exports.InstrumentType || (exports.InstrumentType = {})); +/** + * The aggregated point data type. + */ +var DataPointType; +(function (DataPointType) { + /** + * A histogram data point contains a histogram statistics of collected + * values with a list of explicit bucket boundaries and statistics such + * as min, max, count, and sum of all collected values. + */ + DataPointType[DataPointType["HISTOGRAM"] = 0] = "HISTOGRAM"; + /** + * An exponential histogram data point contains a histogram statistics of + * collected values where bucket boundaries are automatically calculated + * using an exponential function, and statistics such as min, max, count, + * and sum of all collected values. + */ + DataPointType[DataPointType["EXPONENTIAL_HISTOGRAM"] = 1] = "EXPONENTIAL_HISTOGRAM"; + /** + * A gauge metric data point has only a single numeric value. + */ + DataPointType[DataPointType["GAUGE"] = 2] = "GAUGE"; + /** + * A sum metric data point has a single numeric value and a + * monotonicity-indicator. + */ + DataPointType[DataPointType["SUM"] = 3] = "SUM"; +})(DataPointType = exports.DataPointType || (exports.DataPointType = {})); +//# sourceMappingURL=MetricData.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/MetricReader.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/MetricReader.js new file mode 100644 index 00000000..5417d584 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/MetricReader.js @@ -0,0 +1,128 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MetricReader = void 0; +const api = require("@opentelemetry/api"); +const utils_1 = require("../utils"); +const AggregationSelector_1 = require("./AggregationSelector"); +/** + * A registered reader of metrics that, when linked to a {@link MetricProducer}, offers global + * control over metrics. + */ +class MetricReader { + // Tracks the shutdown state. + // TODO: use BindOncePromise here once a new version of @opentelemetry/core is available. + _shutdown = false; + // Additional MetricProducers which will be combined with the SDK's output + _metricProducers; + // MetricProducer used by this instance which produces metrics from the SDK + _sdkMetricProducer; + _aggregationTemporalitySelector; + _aggregationSelector; + _cardinalitySelector; + constructor(options) { + this._aggregationSelector = + options?.aggregationSelector ?? AggregationSelector_1.DEFAULT_AGGREGATION_SELECTOR; + this._aggregationTemporalitySelector = + options?.aggregationTemporalitySelector ?? + AggregationSelector_1.DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR; + this._metricProducers = options?.metricProducers ?? []; + this._cardinalitySelector = options?.cardinalitySelector; + } + setMetricProducer(metricProducer) { + if (this._sdkMetricProducer) { + throw new Error('MetricReader can not be bound to a MeterProvider again.'); + } + this._sdkMetricProducer = metricProducer; + this.onInitialized(); + } + selectAggregation(instrumentType) { + return this._aggregationSelector(instrumentType); + } + selectAggregationTemporality(instrumentType) { + return this._aggregationTemporalitySelector(instrumentType); + } + selectCardinalityLimit(instrumentType) { + return this._cardinalitySelector + ? this._cardinalitySelector(instrumentType) + : 2000; // default value if no selector is provided + } + /** + * Handle once the SDK has initialized this {@link MetricReader} + * Overriding this method is optional. + */ + onInitialized() { + // Default implementation is empty. + } + async collect(options) { + if (this._sdkMetricProducer === undefined) { + throw new Error('MetricReader is not bound to a MetricProducer'); + } + // Subsequent invocations to collect are not allowed. SDKs SHOULD return some failure for these calls. + if (this._shutdown) { + throw new Error('MetricReader is shutdown'); + } + const [sdkCollectionResults, ...additionalCollectionResults] = await Promise.all([ + this._sdkMetricProducer.collect({ + timeoutMillis: options?.timeoutMillis, + }), + ...this._metricProducers.map(producer => producer.collect({ + timeoutMillis: options?.timeoutMillis, + })), + ]); + // Merge the results, keeping the SDK's Resource + const errors = sdkCollectionResults.errors.concat((0, utils_1.FlatMap)(additionalCollectionResults, result => result.errors)); + const resource = sdkCollectionResults.resourceMetrics.resource; + const scopeMetrics = sdkCollectionResults.resourceMetrics.scopeMetrics.concat((0, utils_1.FlatMap)(additionalCollectionResults, result => result.resourceMetrics.scopeMetrics)); + return { + resourceMetrics: { + resource, + scopeMetrics, + }, + errors, + }; + } + async shutdown(options) { + // Do not call shutdown again if it has already been called. + if (this._shutdown) { + api.diag.error('Cannot call shutdown twice.'); + return; + } + // No timeout if timeoutMillis is undefined or null. + if (options?.timeoutMillis == null) { + await this.onShutdown(); + } + else { + await (0, utils_1.callWithTimeout)(this.onShutdown(), options.timeoutMillis); + } + this._shutdown = true; + } + async forceFlush(options) { + if (this._shutdown) { + api.diag.warn('Cannot forceFlush on already shutdown MetricReader.'); + return; + } + // No timeout if timeoutMillis is undefined or null. + if (options?.timeoutMillis == null) { + await this.onForceFlush(); + return; + } + await (0, utils_1.callWithTimeout)(this.onForceFlush(), options.timeoutMillis); + } +} +exports.MetricReader = MetricReader; +//# sourceMappingURL=MetricReader.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/PeriodicExportingMetricReader.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/PeriodicExportingMetricReader.js new file mode 100644 index 00000000..b8080c78 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/PeriodicExportingMetricReader.js @@ -0,0 +1,115 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PeriodicExportingMetricReader = void 0; +const api = require("@opentelemetry/api"); +const core_1 = require("@opentelemetry/core"); +const MetricReader_1 = require("./MetricReader"); +const utils_1 = require("../utils"); +/** + * {@link MetricReader} which collects metrics based on a user-configurable time interval, and passes the metrics to + * the configured {@link PushMetricExporter} + */ +class PeriodicExportingMetricReader extends MetricReader_1.MetricReader { + _interval; + _exporter; + _exportInterval; + _exportTimeout; + constructor(options) { + super({ + aggregationSelector: options.exporter.selectAggregation?.bind(options.exporter), + aggregationTemporalitySelector: options.exporter.selectAggregationTemporality?.bind(options.exporter), + metricProducers: options.metricProducers, + }); + if (options.exportIntervalMillis !== undefined && + options.exportIntervalMillis <= 0) { + throw Error('exportIntervalMillis must be greater than 0'); + } + if (options.exportTimeoutMillis !== undefined && + options.exportTimeoutMillis <= 0) { + throw Error('exportTimeoutMillis must be greater than 0'); + } + if (options.exportTimeoutMillis !== undefined && + options.exportIntervalMillis !== undefined && + options.exportIntervalMillis < options.exportTimeoutMillis) { + throw Error('exportIntervalMillis must be greater than or equal to exportTimeoutMillis'); + } + this._exportInterval = options.exportIntervalMillis ?? 60000; + this._exportTimeout = options.exportTimeoutMillis ?? 30000; + this._exporter = options.exporter; + } + async _runOnce() { + try { + await (0, utils_1.callWithTimeout)(this._doRun(), this._exportTimeout); + } + catch (err) { + if (err instanceof utils_1.TimeoutError) { + api.diag.error('Export took longer than %s milliseconds and timed out.', this._exportTimeout); + return; + } + (0, core_1.globalErrorHandler)(err); + } + } + async _doRun() { + const { resourceMetrics, errors } = await this.collect({ + timeoutMillis: this._exportTimeout, + }); + if (errors.length > 0) { + api.diag.error('PeriodicExportingMetricReader: metrics collection errors', ...errors); + } + if (resourceMetrics.resource.asyncAttributesPending) { + try { + await resourceMetrics.resource.waitForAsyncAttributes?.(); + } + catch (e) { + api.diag.debug('Error while resolving async portion of resource: ', e); + (0, core_1.globalErrorHandler)(e); + } + } + if (resourceMetrics.scopeMetrics.length === 0) { + return; + } + const result = await core_1.internal._export(this._exporter, resourceMetrics); + if (result.code !== core_1.ExportResultCode.SUCCESS) { + throw new Error(`PeriodicExportingMetricReader: metrics export failed (error ${result.error})`); + } + } + onInitialized() { + // start running the interval as soon as this reader is initialized and keep handle for shutdown. + this._interval = setInterval(() => { + // this._runOnce never rejects. Using void operator to suppress @typescript-eslint/no-floating-promises. + void this._runOnce(); + }, this._exportInterval); + // depending on runtime, this may be a 'number' or NodeJS.Timeout + if (typeof this._interval !== 'number') { + this._interval.unref(); + } + } + async onForceFlush() { + await this._runOnce(); + await this._exporter.forceFlush(); + } + async onShutdown() { + if (this._interval) { + clearInterval(this._interval); + } + await this.onForceFlush(); + await this._exporter.shutdown(); + } +} +exports.PeriodicExportingMetricReader = PeriodicExportingMetricReader; +//# sourceMappingURL=PeriodicExportingMetricReader.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/index.js new file mode 100644 index 00000000..8013d085 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/index.js @@ -0,0 +1,41 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TimeoutError = exports.createDenyListAttributesProcessor = exports.createAllowListAttributesProcessor = exports.AggregationType = exports.MeterProvider = exports.ConsoleMetricExporter = exports.InMemoryMetricExporter = exports.PeriodicExportingMetricReader = exports.MetricReader = exports.InstrumentType = exports.DataPointType = exports.AggregationTemporality = void 0; +var AggregationTemporality_1 = require("./export/AggregationTemporality"); +Object.defineProperty(exports, "AggregationTemporality", { enumerable: true, get: function () { return AggregationTemporality_1.AggregationTemporality; } }); +var MetricData_1 = require("./export/MetricData"); +Object.defineProperty(exports, "DataPointType", { enumerable: true, get: function () { return MetricData_1.DataPointType; } }); +Object.defineProperty(exports, "InstrumentType", { enumerable: true, get: function () { return MetricData_1.InstrumentType; } }); +var MetricReader_1 = require("./export/MetricReader"); +Object.defineProperty(exports, "MetricReader", { enumerable: true, get: function () { return MetricReader_1.MetricReader; } }); +var PeriodicExportingMetricReader_1 = require("./export/PeriodicExportingMetricReader"); +Object.defineProperty(exports, "PeriodicExportingMetricReader", { enumerable: true, get: function () { return PeriodicExportingMetricReader_1.PeriodicExportingMetricReader; } }); +var InMemoryMetricExporter_1 = require("./export/InMemoryMetricExporter"); +Object.defineProperty(exports, "InMemoryMetricExporter", { enumerable: true, get: function () { return InMemoryMetricExporter_1.InMemoryMetricExporter; } }); +var ConsoleMetricExporter_1 = require("./export/ConsoleMetricExporter"); +Object.defineProperty(exports, "ConsoleMetricExporter", { enumerable: true, get: function () { return ConsoleMetricExporter_1.ConsoleMetricExporter; } }); +var MeterProvider_1 = require("./MeterProvider"); +Object.defineProperty(exports, "MeterProvider", { enumerable: true, get: function () { return MeterProvider_1.MeterProvider; } }); +var AggregationOption_1 = require("./view/AggregationOption"); +Object.defineProperty(exports, "AggregationType", { enumerable: true, get: function () { return AggregationOption_1.AggregationType; } }); +var AttributesProcessor_1 = require("./view/AttributesProcessor"); +Object.defineProperty(exports, "createAllowListAttributesProcessor", { enumerable: true, get: function () { return AttributesProcessor_1.createAllowListAttributesProcessor; } }); +Object.defineProperty(exports, "createDenyListAttributesProcessor", { enumerable: true, get: function () { return AttributesProcessor_1.createDenyListAttributesProcessor; } }); +var utils_1 = require("./utils"); +Object.defineProperty(exports, "TimeoutError", { enumerable: true, get: function () { return utils_1.TimeoutError; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/AsyncMetricStorage.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/AsyncMetricStorage.js new file mode 100644 index 00000000..281ac9c1 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/AsyncMetricStorage.js @@ -0,0 +1,60 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AsyncMetricStorage = void 0; +const MetricStorage_1 = require("./MetricStorage"); +const DeltaMetricProcessor_1 = require("./DeltaMetricProcessor"); +const TemporalMetricProcessor_1 = require("./TemporalMetricProcessor"); +const HashMap_1 = require("./HashMap"); +/** + * Internal interface. + * + * Stores and aggregates {@link MetricData} for asynchronous instruments. + */ +class AsyncMetricStorage extends MetricStorage_1.MetricStorage { + _attributesProcessor; + _aggregationCardinalityLimit; + _deltaMetricStorage; + _temporalMetricStorage; + constructor(_instrumentDescriptor, aggregator, _attributesProcessor, collectorHandles, _aggregationCardinalityLimit) { + super(_instrumentDescriptor); + this._attributesProcessor = _attributesProcessor; + this._aggregationCardinalityLimit = _aggregationCardinalityLimit; + this._deltaMetricStorage = new DeltaMetricProcessor_1.DeltaMetricProcessor(aggregator, this._aggregationCardinalityLimit); + this._temporalMetricStorage = new TemporalMetricProcessor_1.TemporalMetricProcessor(aggregator, collectorHandles); + } + record(measurements, observationTime) { + const processed = new HashMap_1.AttributeHashMap(); + Array.from(measurements.entries()).forEach(([attributes, value]) => { + processed.set(this._attributesProcessor.process(attributes), value); + }); + this._deltaMetricStorage.batchCumulate(processed, observationTime); + } + /** + * Collects the metrics from this storage. The ObservableCallback is invoked + * during the collection. + * + * Note: This is a stateful operation and may reset any interval-related + * state for the MetricCollector. + */ + collect(collector, collectionTime) { + const accumulations = this._deltaMetricStorage.collect(); + return this._temporalMetricStorage.buildMetrics(collector, this._instrumentDescriptor, accumulations, collectionTime); + } +} +exports.AsyncMetricStorage = AsyncMetricStorage; +//# sourceMappingURL=AsyncMetricStorage.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/DeltaMetricProcessor.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/DeltaMetricProcessor.js new file mode 100644 index 00000000..a703f06f --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/DeltaMetricProcessor.js @@ -0,0 +1,103 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DeltaMetricProcessor = void 0; +const utils_1 = require("../utils"); +const HashMap_1 = require("./HashMap"); +/** + * Internal interface. + * + * Allows synchronous collection of metrics. This processor should allow + * allocation of new aggregation cells for metrics and convert cumulative + * recording to delta data points. + */ +class DeltaMetricProcessor { + _aggregator; + _activeCollectionStorage = new HashMap_1.AttributeHashMap(); + // TODO: find a reasonable mean to clean the memo; + // https://github.com/open-telemetry/opentelemetry-specification/pull/2208 + _cumulativeMemoStorage = new HashMap_1.AttributeHashMap(); + _cardinalityLimit; + _overflowAttributes = { 'otel.metric.overflow': true }; + _overflowHashCode; + constructor(_aggregator, aggregationCardinalityLimit) { + this._aggregator = _aggregator; + this._cardinalityLimit = (aggregationCardinalityLimit ?? 2000) - 1; + this._overflowHashCode = (0, utils_1.hashAttributes)(this._overflowAttributes); + } + record(value, attributes, _context, collectionTime) { + let accumulation = this._activeCollectionStorage.get(attributes); + if (!accumulation) { + if (this._activeCollectionStorage.size >= this._cardinalityLimit) { + const overflowAccumulation = this._activeCollectionStorage.getOrDefault(this._overflowAttributes, () => this._aggregator.createAccumulation(collectionTime)); + overflowAccumulation?.record(value); + return; + } + accumulation = this._aggregator.createAccumulation(collectionTime); + this._activeCollectionStorage.set(attributes, accumulation); + } + accumulation?.record(value); + } + batchCumulate(measurements, collectionTime) { + Array.from(measurements.entries()).forEach(([attributes, value, hashCode]) => { + const accumulation = this._aggregator.createAccumulation(collectionTime); + accumulation?.record(value); + let delta = accumulation; + // Diff with recorded cumulative memo. + if (this._cumulativeMemoStorage.has(attributes, hashCode)) { + // has() returned true, previous is present. + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const previous = this._cumulativeMemoStorage.get(attributes, hashCode); + delta = this._aggregator.diff(previous, accumulation); + } + else { + // If the cardinality limit is reached, we need to change the attributes + if (this._cumulativeMemoStorage.size >= this._cardinalityLimit) { + attributes = this._overflowAttributes; + hashCode = this._overflowHashCode; + if (this._cumulativeMemoStorage.has(attributes, hashCode)) { + // has() returned true, previous is present. + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const previous = this._cumulativeMemoStorage.get(attributes, hashCode); + delta = this._aggregator.diff(previous, accumulation); + } + } + } + // Merge with uncollected active delta. + if (this._activeCollectionStorage.has(attributes, hashCode)) { + // has() returned true, active is present. + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const active = this._activeCollectionStorage.get(attributes, hashCode); + delta = this._aggregator.merge(active, delta); + } + // Save the current record and the delta record. + this._cumulativeMemoStorage.set(attributes, accumulation, hashCode); + this._activeCollectionStorage.set(attributes, delta, hashCode); + }); + } + /** + * Returns a collection of delta metrics. Start time is the when first + * time event collected. + */ + collect() { + const unreportedDelta = this._activeCollectionStorage; + this._activeCollectionStorage = new HashMap_1.AttributeHashMap(); + return unreportedDelta; + } +} +exports.DeltaMetricProcessor = DeltaMetricProcessor; +//# sourceMappingURL=DeltaMetricProcessor.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/HashMap.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/HashMap.js new file mode 100644 index 00000000..3bf96e35 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/HashMap.js @@ -0,0 +1,83 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AttributeHashMap = exports.HashMap = void 0; +const utils_1 = require("../utils"); +class HashMap { + _hash; + _valueMap = new Map(); + _keyMap = new Map(); + constructor(_hash) { + this._hash = _hash; + } + get(key, hashCode) { + hashCode ??= this._hash(key); + return this._valueMap.get(hashCode); + } + getOrDefault(key, defaultFactory) { + const hash = this._hash(key); + if (this._valueMap.has(hash)) { + return this._valueMap.get(hash); + } + const val = defaultFactory(); + if (!this._keyMap.has(hash)) { + this._keyMap.set(hash, key); + } + this._valueMap.set(hash, val); + return val; + } + set(key, value, hashCode) { + hashCode ??= this._hash(key); + if (!this._keyMap.has(hashCode)) { + this._keyMap.set(hashCode, key); + } + this._valueMap.set(hashCode, value); + } + has(key, hashCode) { + hashCode ??= this._hash(key); + return this._valueMap.has(hashCode); + } + *keys() { + const keyIterator = this._keyMap.entries(); + let next = keyIterator.next(); + while (next.done !== true) { + yield [next.value[1], next.value[0]]; + next = keyIterator.next(); + } + } + *entries() { + const valueIterator = this._valueMap.entries(); + let next = valueIterator.next(); + while (next.done !== true) { + // next.value[0] here can not be undefined + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + yield [this._keyMap.get(next.value[0]), next.value[1], next.value[0]]; + next = valueIterator.next(); + } + } + get size() { + return this._valueMap.size; + } +} +exports.HashMap = HashMap; +class AttributeHashMap extends HashMap { + constructor() { + super(utils_1.hashAttributes); + } +} +exports.AttributeHashMap = AttributeHashMap; +//# sourceMappingURL=HashMap.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MeterProviderSharedState.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MeterProviderSharedState.js new file mode 100644 index 00000000..d617123c --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MeterProviderSharedState.js @@ -0,0 +1,55 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MeterProviderSharedState = void 0; +const utils_1 = require("../utils"); +const ViewRegistry_1 = require("../view/ViewRegistry"); +const MeterSharedState_1 = require("./MeterSharedState"); +const AggregationOption_1 = require("../view/AggregationOption"); +/** + * An internal record for shared meter provider states. + */ +class MeterProviderSharedState { + resource; + viewRegistry = new ViewRegistry_1.ViewRegistry(); + metricCollectors = []; + meterSharedStates = new Map(); + constructor(resource) { + this.resource = resource; + } + getMeterSharedState(instrumentationScope) { + const id = (0, utils_1.instrumentationScopeId)(instrumentationScope); + let meterSharedState = this.meterSharedStates.get(id); + if (meterSharedState == null) { + meterSharedState = new MeterSharedState_1.MeterSharedState(this, instrumentationScope); + this.meterSharedStates.set(id, meterSharedState); + } + return meterSharedState; + } + selectAggregations(instrumentType) { + const result = []; + for (const collector of this.metricCollectors) { + result.push([ + collector, + (0, AggregationOption_1.toAggregation)(collector.selectAggregation(instrumentType)), + ]); + } + return result; + } +} +exports.MeterProviderSharedState = MeterProviderSharedState; +//# sourceMappingURL=MeterProviderSharedState.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MeterSharedState.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MeterSharedState.js new file mode 100644 index 00000000..701204ef --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MeterSharedState.js @@ -0,0 +1,120 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MeterSharedState = void 0; +const InstrumentDescriptor_1 = require("../InstrumentDescriptor"); +const Meter_1 = require("../Meter"); +const utils_1 = require("../utils"); +const AsyncMetricStorage_1 = require("./AsyncMetricStorage"); +const MetricStorageRegistry_1 = require("./MetricStorageRegistry"); +const MultiWritableMetricStorage_1 = require("./MultiWritableMetricStorage"); +const ObservableRegistry_1 = require("./ObservableRegistry"); +const SyncMetricStorage_1 = require("./SyncMetricStorage"); +const AttributesProcessor_1 = require("../view/AttributesProcessor"); +/** + * An internal record for shared meter provider states. + */ +class MeterSharedState { + _meterProviderSharedState; + _instrumentationScope; + metricStorageRegistry = new MetricStorageRegistry_1.MetricStorageRegistry(); + observableRegistry = new ObservableRegistry_1.ObservableRegistry(); + meter; + constructor(_meterProviderSharedState, _instrumentationScope) { + this._meterProviderSharedState = _meterProviderSharedState; + this._instrumentationScope = _instrumentationScope; + this.meter = new Meter_1.Meter(this); + } + registerMetricStorage(descriptor) { + const storages = this._registerMetricStorage(descriptor, SyncMetricStorage_1.SyncMetricStorage); + if (storages.length === 1) { + return storages[0]; + } + return new MultiWritableMetricStorage_1.MultiMetricStorage(storages); + } + registerAsyncMetricStorage(descriptor) { + const storages = this._registerMetricStorage(descriptor, AsyncMetricStorage_1.AsyncMetricStorage); + return storages; + } + /** + * @param collector opaque handle of {@link MetricCollector} which initiated the collection. + * @param collectionTime the HrTime at which the collection was initiated. + * @param options options for collection. + * @returns the list of metric data collected. + */ + async collect(collector, collectionTime, options) { + /** + * 1. Call all observable callbacks first. + * 2. Collect metric result for the collector. + */ + const errors = await this.observableRegistry.observe(collectionTime, options?.timeoutMillis); + const storages = this.metricStorageRegistry.getStorages(collector); + // prevent more allocations if there are no storages. + if (storages.length === 0) { + return null; + } + const metricDataList = storages + .map(metricStorage => { + return metricStorage.collect(collector, collectionTime); + }) + .filter(utils_1.isNotNullish); + // skip this scope if no data was collected (storage created, but no data observed) + if (metricDataList.length === 0) { + return { errors }; + } + return { + scopeMetrics: { + scope: this._instrumentationScope, + metrics: metricDataList, + }, + errors, + }; + } + _registerMetricStorage(descriptor, MetricStorageType) { + const views = this._meterProviderSharedState.viewRegistry.findViews(descriptor, this._instrumentationScope); + let storages = views.map(view => { + const viewDescriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptorWithView)(view, descriptor); + const compatibleStorage = this.metricStorageRegistry.findOrUpdateCompatibleStorage(viewDescriptor); + if (compatibleStorage != null) { + return compatibleStorage; + } + const aggregator = view.aggregation.createAggregator(viewDescriptor); + const viewStorage = new MetricStorageType(viewDescriptor, aggregator, view.attributesProcessor, this._meterProviderSharedState.metricCollectors, view.aggregationCardinalityLimit); + this.metricStorageRegistry.register(viewStorage); + return viewStorage; + }); + // Fallback to the per-collector aggregations if no view is configured for the instrument. + if (storages.length === 0) { + const perCollectorAggregations = this._meterProviderSharedState.selectAggregations(descriptor.type); + const collectorStorages = perCollectorAggregations.map(([collector, aggregation]) => { + const compatibleStorage = this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(collector, descriptor); + if (compatibleStorage != null) { + return compatibleStorage; + } + const aggregator = aggregation.createAggregator(descriptor); + const cardinalityLimit = collector.selectCardinalityLimit(descriptor.type); + const storage = new MetricStorageType(descriptor, aggregator, (0, AttributesProcessor_1.createNoopAttributesProcessor)(), [collector], cardinalityLimit); + this.metricStorageRegistry.registerForCollector(collector, storage); + return storage; + }); + storages = storages.concat(collectorStorages); + } + return storages; + } +} +exports.MeterSharedState = MeterSharedState; +//# sourceMappingURL=MeterSharedState.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricCollector.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricCollector.js new file mode 100644 index 00000000..2bafeb0e --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricCollector.js @@ -0,0 +1,83 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MetricCollector = void 0; +const core_1 = require("@opentelemetry/core"); +/** + * An internal opaque interface that the MetricReader receives as + * MetricProducer. It acts as the storage key to the internal metric stream + * state for each MetricReader. + */ +class MetricCollector { + _sharedState; + _metricReader; + constructor(_sharedState, _metricReader) { + this._sharedState = _sharedState; + this._metricReader = _metricReader; + } + async collect(options) { + const collectionTime = (0, core_1.millisToHrTime)(Date.now()); + const scopeMetrics = []; + const errors = []; + const meterCollectionPromises = Array.from(this._sharedState.meterSharedStates.values()).map(async (meterSharedState) => { + const current = await meterSharedState.collect(this, collectionTime, options); + // only add scope metrics if available + if (current?.scopeMetrics != null) { + scopeMetrics.push(current.scopeMetrics); + } + // only add errors if available + if (current?.errors != null) { + errors.push(...current.errors); + } + }); + await Promise.all(meterCollectionPromises); + return { + resourceMetrics: { + resource: this._sharedState.resource, + scopeMetrics: scopeMetrics, + }, + errors: errors, + }; + } + /** + * Delegates for MetricReader.forceFlush. + */ + async forceFlush(options) { + await this._metricReader.forceFlush(options); + } + /** + * Delegates for MetricReader.shutdown. + */ + async shutdown(options) { + await this._metricReader.shutdown(options); + } + selectAggregationTemporality(instrumentType) { + return this._metricReader.selectAggregationTemporality(instrumentType); + } + selectAggregation(instrumentType) { + return this._metricReader.selectAggregation(instrumentType); + } + /** + * Select the cardinality limit for the given {@link InstrumentType} for this + * collector. + */ + selectCardinalityLimit(instrumentType) { + return this._metricReader.selectCardinalityLimit?.(instrumentType) ?? 2000; + } +} +exports.MetricCollector = MetricCollector; +//# sourceMappingURL=MetricCollector.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricStorage.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricStorage.js new file mode 100644 index 00000000..fdfd8bb2 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricStorage.js @@ -0,0 +1,43 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MetricStorage = void 0; +const InstrumentDescriptor_1 = require("../InstrumentDescriptor"); +/** + * Internal interface. + * + * Represents a storage from which we can collect metrics. + */ +class MetricStorage { + _instrumentDescriptor; + constructor(_instrumentDescriptor) { + this._instrumentDescriptor = _instrumentDescriptor; + } + getInstrumentDescriptor() { + return this._instrumentDescriptor; + } + updateDescription(description) { + this._instrumentDescriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(this._instrumentDescriptor.name, this._instrumentDescriptor.type, { + description: description, + valueType: this._instrumentDescriptor.valueType, + unit: this._instrumentDescriptor.unit, + advice: this._instrumentDescriptor.advice, + }); + } +} +exports.MetricStorage = MetricStorage; +//# sourceMappingURL=MetricStorage.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricStorageRegistry.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricStorageRegistry.js new file mode 100644 index 00000000..3dab0e7a --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricStorageRegistry.js @@ -0,0 +1,112 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MetricStorageRegistry = void 0; +const InstrumentDescriptor_1 = require("../InstrumentDescriptor"); +const api = require("@opentelemetry/api"); +const RegistrationConflicts_1 = require("../view/RegistrationConflicts"); +/** + * Internal class for storing {@link MetricStorage} + */ +class MetricStorageRegistry { + _sharedRegistry = new Map(); + _perCollectorRegistry = new Map(); + static create() { + return new MetricStorageRegistry(); + } + getStorages(collector) { + let storages = []; + for (const metricStorages of this._sharedRegistry.values()) { + storages = storages.concat(metricStorages); + } + const perCollectorStorages = this._perCollectorRegistry.get(collector); + if (perCollectorStorages != null) { + for (const metricStorages of perCollectorStorages.values()) { + storages = storages.concat(metricStorages); + } + } + return storages; + } + register(storage) { + this._registerStorage(storage, this._sharedRegistry); + } + registerForCollector(collector, storage) { + let storageMap = this._perCollectorRegistry.get(collector); + if (storageMap == null) { + storageMap = new Map(); + this._perCollectorRegistry.set(collector, storageMap); + } + this._registerStorage(storage, storageMap); + } + findOrUpdateCompatibleStorage(expectedDescriptor) { + const storages = this._sharedRegistry.get(expectedDescriptor.name); + if (storages === undefined) { + return null; + } + // If the descriptor is compatible, the type of their metric storage + // (either SyncMetricStorage or AsyncMetricStorage) must be compatible. + return this._findOrUpdateCompatibleStorage(expectedDescriptor, storages); + } + findOrUpdateCompatibleCollectorStorage(collector, expectedDescriptor) { + const storageMap = this._perCollectorRegistry.get(collector); + if (storageMap === undefined) { + return null; + } + const storages = storageMap.get(expectedDescriptor.name); + if (storages === undefined) { + return null; + } + // If the descriptor is compatible, the type of their metric storage + // (either SyncMetricStorage or AsyncMetricStorage) must be compatible. + return this._findOrUpdateCompatibleStorage(expectedDescriptor, storages); + } + _registerStorage(storage, storageMap) { + const descriptor = storage.getInstrumentDescriptor(); + const storages = storageMap.get(descriptor.name); + if (storages === undefined) { + storageMap.set(descriptor.name, [storage]); + return; + } + storages.push(storage); + } + _findOrUpdateCompatibleStorage(expectedDescriptor, existingStorages) { + let compatibleStorage = null; + for (const existingStorage of existingStorages) { + const existingDescriptor = existingStorage.getInstrumentDescriptor(); + if ((0, InstrumentDescriptor_1.isDescriptorCompatibleWith)(existingDescriptor, expectedDescriptor)) { + // Use the longer description if it does not match. + if (existingDescriptor.description !== expectedDescriptor.description) { + if (expectedDescriptor.description.length > + existingDescriptor.description.length) { + existingStorage.updateDescription(expectedDescriptor.description); + } + api.diag.warn('A view or instrument with the name ', expectedDescriptor.name, ' has already been registered, but has a different description and is incompatible with another registered view.\n', 'Details:\n', (0, RegistrationConflicts_1.getIncompatibilityDetails)(existingDescriptor, expectedDescriptor), 'The longer description will be used.\nTo resolve the conflict:', (0, RegistrationConflicts_1.getConflictResolutionRecipe)(existingDescriptor, expectedDescriptor)); + } + // Storage is fully compatible. There will never be more than one pre-existing fully compatible storage. + compatibleStorage = existingStorage; + } + else { + // The implementation SHOULD warn about duplicate instrument registration + // conflicts after applying View configuration. + api.diag.warn('A view or instrument with the name ', expectedDescriptor.name, ' has already been registered and is incompatible with another registered view.\n', 'Details:\n', (0, RegistrationConflicts_1.getIncompatibilityDetails)(existingDescriptor, expectedDescriptor), 'To resolve the conflict:\n', (0, RegistrationConflicts_1.getConflictResolutionRecipe)(existingDescriptor, expectedDescriptor)); + } + } + return compatibleStorage; + } +} +exports.MetricStorageRegistry = MetricStorageRegistry; +//# sourceMappingURL=MetricStorageRegistry.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MultiWritableMetricStorage.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MultiWritableMetricStorage.js new file mode 100644 index 00000000..ec9e733c --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MultiWritableMetricStorage.js @@ -0,0 +1,34 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MultiMetricStorage = void 0; +/** + * Internal interface. + */ +class MultiMetricStorage { + _backingStorages; + constructor(_backingStorages) { + this._backingStorages = _backingStorages; + } + record(value, attributes, context, recordTime) { + this._backingStorages.forEach(it => { + it.record(value, attributes, context, recordTime); + }); + } +} +exports.MultiMetricStorage = MultiMetricStorage; +//# sourceMappingURL=MultiWritableMetricStorage.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/ObservableRegistry.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/ObservableRegistry.js new file mode 100644 index 00000000..f33ba010 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/ObservableRegistry.js @@ -0,0 +1,128 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ObservableRegistry = void 0; +const api_1 = require("@opentelemetry/api"); +const Instruments_1 = require("../Instruments"); +const ObservableResult_1 = require("../ObservableResult"); +const utils_1 = require("../utils"); +/** + * An internal interface for managing ObservableCallbacks. + * + * Every registered callback associated with a set of instruments are be evaluated + * exactly once during collection prior to reading data for that instrument. + */ +class ObservableRegistry { + _callbacks = []; + _batchCallbacks = []; + addCallback(callback, instrument) { + const idx = this._findCallback(callback, instrument); + if (idx >= 0) { + return; + } + this._callbacks.push({ callback, instrument }); + } + removeCallback(callback, instrument) { + const idx = this._findCallback(callback, instrument); + if (idx < 0) { + return; + } + this._callbacks.splice(idx, 1); + } + addBatchCallback(callback, instruments) { + // Create a set of unique instruments. + const observableInstruments = new Set(instruments.filter(Instruments_1.isObservableInstrument)); + if (observableInstruments.size === 0) { + api_1.diag.error('BatchObservableCallback is not associated with valid instruments', instruments); + return; + } + const idx = this._findBatchCallback(callback, observableInstruments); + if (idx >= 0) { + return; + } + this._batchCallbacks.push({ callback, instruments: observableInstruments }); + } + removeBatchCallback(callback, instruments) { + // Create a set of unique instruments. + const observableInstruments = new Set(instruments.filter(Instruments_1.isObservableInstrument)); + const idx = this._findBatchCallback(callback, observableInstruments); + if (idx < 0) { + return; + } + this._batchCallbacks.splice(idx, 1); + } + /** + * @returns a promise of rejected reasons for invoking callbacks. + */ + async observe(collectionTime, timeoutMillis) { + const callbackFutures = this._observeCallbacks(collectionTime, timeoutMillis); + const batchCallbackFutures = this._observeBatchCallbacks(collectionTime, timeoutMillis); + const results = await (0, utils_1.PromiseAllSettled)([ + ...callbackFutures, + ...batchCallbackFutures, + ]); + const rejections = results + .filter(utils_1.isPromiseAllSettledRejectionResult) + .map(it => it.reason); + return rejections; + } + _observeCallbacks(observationTime, timeoutMillis) { + return this._callbacks.map(async ({ callback, instrument }) => { + const observableResult = new ObservableResult_1.ObservableResultImpl(instrument._descriptor.name, instrument._descriptor.valueType); + let callPromise = Promise.resolve(callback(observableResult)); + if (timeoutMillis != null) { + callPromise = (0, utils_1.callWithTimeout)(callPromise, timeoutMillis); + } + await callPromise; + instrument._metricStorages.forEach(metricStorage => { + metricStorage.record(observableResult._buffer, observationTime); + }); + }); + } + _observeBatchCallbacks(observationTime, timeoutMillis) { + return this._batchCallbacks.map(async ({ callback, instruments }) => { + const observableResult = new ObservableResult_1.BatchObservableResultImpl(); + let callPromise = Promise.resolve(callback(observableResult)); + if (timeoutMillis != null) { + callPromise = (0, utils_1.callWithTimeout)(callPromise, timeoutMillis); + } + await callPromise; + instruments.forEach(instrument => { + const buffer = observableResult._buffer.get(instrument); + if (buffer == null) { + return; + } + instrument._metricStorages.forEach(metricStorage => { + metricStorage.record(buffer, observationTime); + }); + }); + }); + } + _findCallback(callback, instrument) { + return this._callbacks.findIndex(record => { + return record.callback === callback && record.instrument === instrument; + }); + } + _findBatchCallback(callback, instruments) { + return this._batchCallbacks.findIndex(record => { + return (record.callback === callback && + (0, utils_1.setEquals)(record.instruments, instruments)); + }); + } +} +exports.ObservableRegistry = ObservableRegistry; +//# sourceMappingURL=ObservableRegistry.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/SyncMetricStorage.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/SyncMetricStorage.js new file mode 100644 index 00000000..d075757a --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/SyncMetricStorage.js @@ -0,0 +1,55 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SyncMetricStorage = void 0; +const MetricStorage_1 = require("./MetricStorage"); +const DeltaMetricProcessor_1 = require("./DeltaMetricProcessor"); +const TemporalMetricProcessor_1 = require("./TemporalMetricProcessor"); +/** + * Internal interface. + * + * Stores and aggregates {@link MetricData} for synchronous instruments. + */ +class SyncMetricStorage extends MetricStorage_1.MetricStorage { + _attributesProcessor; + _aggregationCardinalityLimit; + _deltaMetricStorage; + _temporalMetricStorage; + constructor(instrumentDescriptor, aggregator, _attributesProcessor, collectorHandles, _aggregationCardinalityLimit) { + super(instrumentDescriptor); + this._attributesProcessor = _attributesProcessor; + this._aggregationCardinalityLimit = _aggregationCardinalityLimit; + this._deltaMetricStorage = new DeltaMetricProcessor_1.DeltaMetricProcessor(aggregator, this._aggregationCardinalityLimit); + this._temporalMetricStorage = new TemporalMetricProcessor_1.TemporalMetricProcessor(aggregator, collectorHandles); + } + record(value, attributes, context, recordTime) { + attributes = this._attributesProcessor.process(attributes, context); + this._deltaMetricStorage.record(value, attributes, context, recordTime); + } + /** + * Collects the metrics from this storage. + * + * Note: This is a stateful operation and may reset any interval-related + * state for the MetricCollector. + */ + collect(collector, collectionTime) { + const accumulations = this._deltaMetricStorage.collect(); + return this._temporalMetricStorage.buildMetrics(collector, this._instrumentDescriptor, accumulations, collectionTime); + } +} +exports.SyncMetricStorage = SyncMetricStorage; +//# sourceMappingURL=SyncMetricStorage.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/TemporalMetricProcessor.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/TemporalMetricProcessor.js new file mode 100644 index 00000000..b4220218 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/TemporalMetricProcessor.js @@ -0,0 +1,156 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TemporalMetricProcessor = void 0; +const AggregationTemporality_1 = require("../export/AggregationTemporality"); +const HashMap_1 = require("./HashMap"); +/** + * Internal interface. + * + * Provides unique reporting for each collector. Allows synchronous collection + * of metrics and reports given temporality values. + */ +class TemporalMetricProcessor { + _aggregator; + _unreportedAccumulations = new Map(); + _reportHistory = new Map(); + constructor(_aggregator, collectorHandles) { + this._aggregator = _aggregator; + collectorHandles.forEach(handle => { + this._unreportedAccumulations.set(handle, []); + }); + } + /** + * Builds the {@link MetricData} streams to report against a specific MetricCollector. + * @param collector The information of the MetricCollector. + * @param collectors The registered collectors. + * @param instrumentDescriptor The instrumentation descriptor that these metrics generated with. + * @param currentAccumulations The current accumulation of metric data from instruments. + * @param collectionTime The current collection timestamp. + * @returns The {@link MetricData} points or `null`. + */ + buildMetrics(collector, instrumentDescriptor, currentAccumulations, collectionTime) { + this._stashAccumulations(currentAccumulations); + const unreportedAccumulations = this._getMergedUnreportedAccumulations(collector); + let result = unreportedAccumulations; + let aggregationTemporality; + // Check our last report time. + if (this._reportHistory.has(collector)) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const last = this._reportHistory.get(collector); + const lastCollectionTime = last.collectionTime; + aggregationTemporality = last.aggregationTemporality; + // Use aggregation temporality + instrument to determine if we do a merge or a diff of + // previous. We have the following four scenarios: + // 1. Cumulative Aggregation (temporality) + Delta recording (sync instrument). + // Here we merge with our last record to get a cumulative aggregation. + // 2. Cumulative Aggregation + Cumulative recording (async instrument). + // Cumulative records are converted to delta recording with DeltaMetricProcessor. + // Here we merge with our last record to get a cumulative aggregation. + // 3. Delta Aggregation + Delta recording + // Calibrate the startTime of metric streams to be the reader's lastCollectionTime. + // 4. Delta Aggregation + Cumulative recording. + // Cumulative records are converted to delta recording with DeltaMetricProcessor. + // Calibrate the startTime of metric streams to be the reader's lastCollectionTime. + if (aggregationTemporality === AggregationTemporality_1.AggregationTemporality.CUMULATIVE) { + // We need to make sure the current delta recording gets merged into the previous cumulative + // for the next cumulative recording. + result = TemporalMetricProcessor.merge(last.accumulations, unreportedAccumulations, this._aggregator); + } + else { + result = TemporalMetricProcessor.calibrateStartTime(last.accumulations, unreportedAccumulations, lastCollectionTime); + } + } + else { + // Call into user code to select aggregation temporality for the instrument. + aggregationTemporality = collector.selectAggregationTemporality(instrumentDescriptor.type); + } + // Update last reported (cumulative) accumulation. + this._reportHistory.set(collector, { + accumulations: result, + collectionTime, + aggregationTemporality, + }); + const accumulationRecords = AttributesMapToAccumulationRecords(result); + // do not convert to metric data if there is nothing to convert. + if (accumulationRecords.length === 0) { + return undefined; + } + return this._aggregator.toMetricData(instrumentDescriptor, aggregationTemporality, accumulationRecords, + /* endTime */ collectionTime); + } + _stashAccumulations(currentAccumulation) { + const registeredCollectors = this._unreportedAccumulations.keys(); + for (const collector of registeredCollectors) { + let stash = this._unreportedAccumulations.get(collector); + if (stash === undefined) { + stash = []; + this._unreportedAccumulations.set(collector, stash); + } + stash.push(currentAccumulation); + } + } + _getMergedUnreportedAccumulations(collector) { + let result = new HashMap_1.AttributeHashMap(); + const unreportedList = this._unreportedAccumulations.get(collector); + this._unreportedAccumulations.set(collector, []); + if (unreportedList === undefined) { + return result; + } + for (const it of unreportedList) { + result = TemporalMetricProcessor.merge(result, it, this._aggregator); + } + return result; + } + static merge(last, current, aggregator) { + const result = last; + const iterator = current.entries(); + let next = iterator.next(); + while (next.done !== true) { + const [key, record, hash] = next.value; + if (last.has(key, hash)) { + const lastAccumulation = last.get(key, hash); + // last.has() returned true, lastAccumulation is present. + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const accumulation = aggregator.merge(lastAccumulation, record); + result.set(key, accumulation, hash); + } + else { + result.set(key, record, hash); + } + next = iterator.next(); + } + return result; + } + /** + * Calibrate the reported metric streams' startTime to lastCollectionTime. Leaves + * the new stream to be the initial observation time unchanged. + */ + static calibrateStartTime(last, current, lastCollectionTime) { + for (const [key, hash] of last.keys()) { + const currentAccumulation = current.get(key, hash); + currentAccumulation?.setStartTime(lastCollectionTime); + } + return current; + } +} +exports.TemporalMetricProcessor = TemporalMetricProcessor; +// TypeScript complains about converting 3 elements tuple to AccumulationRecord. +function AttributesMapToAccumulationRecords(map) { + return Array.from(map.entries()); +} +//# sourceMappingURL=TemporalMetricProcessor.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/utils.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/utils.js new file mode 100644 index 00000000..a37099b8 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/utils.js @@ -0,0 +1,156 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.equalsCaseInsensitive = exports.binarySearchUB = exports.setEquals = exports.FlatMap = exports.isPromiseAllSettledRejectionResult = exports.PromiseAllSettled = exports.callWithTimeout = exports.TimeoutError = exports.instrumentationScopeId = exports.hashAttributes = exports.isNotNullish = void 0; +function isNotNullish(item) { + return item !== undefined && item !== null; +} +exports.isNotNullish = isNotNullish; +/** + * Converting the unordered attributes into unique identifier string. + * @param attributes user provided unordered Attributes. + */ +function hashAttributes(attributes) { + let keys = Object.keys(attributes); + if (keys.length === 0) + return ''; + // Return a string that is stable on key orders. + keys = keys.sort(); + return JSON.stringify(keys.map(key => [key, attributes[key]])); +} +exports.hashAttributes = hashAttributes; +/** + * Converting the instrumentation scope object to a unique identifier string. + * @param instrumentationScope + */ +function instrumentationScopeId(instrumentationScope) { + return `${instrumentationScope.name}:${instrumentationScope.version ?? ''}:${instrumentationScope.schemaUrl ?? ''}`; +} +exports.instrumentationScopeId = instrumentationScopeId; +/** + * Error that is thrown on timeouts. + */ +class TimeoutError extends Error { + constructor(message) { + super(message); + // manually adjust prototype to retain `instanceof` functionality when targeting ES5, see: + // https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work + Object.setPrototypeOf(this, TimeoutError.prototype); + } +} +exports.TimeoutError = TimeoutError; +/** + * Adds a timeout to a promise and rejects if the specified timeout has elapsed. Also rejects if the specified promise + * rejects, and resolves if the specified promise resolves. + * + *

NOTE: this operation will continue even after it throws a {@link TimeoutError}. + * + * @param promise promise to use with timeout. + * @param timeout the timeout in milliseconds until the returned promise is rejected. + */ +function callWithTimeout(promise, timeout) { + let timeoutHandle; + const timeoutPromise = new Promise(function timeoutFunction(_resolve, reject) { + timeoutHandle = setTimeout(function timeoutHandler() { + reject(new TimeoutError('Operation timed out.')); + }, timeout); + }); + return Promise.race([promise, timeoutPromise]).then(result => { + clearTimeout(timeoutHandle); + return result; + }, reason => { + clearTimeout(timeoutHandle); + throw reason; + }); +} +exports.callWithTimeout = callWithTimeout; +/** + * Node.js v12.9 lower and browser compatible `Promise.allSettled`. + */ +async function PromiseAllSettled(promises) { + return Promise.all(promises.map(async (p) => { + try { + const ret = await p; + return { + status: 'fulfilled', + value: ret, + }; + } + catch (e) { + return { + status: 'rejected', + reason: e, + }; + } + })); +} +exports.PromiseAllSettled = PromiseAllSettled; +function isPromiseAllSettledRejectionResult(it) { + return it.status === 'rejected'; +} +exports.isPromiseAllSettledRejectionResult = isPromiseAllSettledRejectionResult; +/** + * Node.js v11.0 lower and browser compatible `Array.prototype.flatMap`. + */ +function FlatMap(arr, fn) { + const result = []; + arr.forEach(it => { + result.push(...fn(it)); + }); + return result; +} +exports.FlatMap = FlatMap; +function setEquals(lhs, rhs) { + if (lhs.size !== rhs.size) { + return false; + } + for (const item of lhs) { + if (!rhs.has(item)) { + return false; + } + } + return true; +} +exports.setEquals = setEquals; +/** + * Binary search the sorted array to the find upper bound for the value. + * @param arr + * @param value + * @returns + */ +function binarySearchUB(arr, value) { + let lo = 0; + let hi = arr.length - 1; + let ret = arr.length; + while (hi >= lo) { + const mid = lo + Math.trunc((hi - lo) / 2); + if (arr[mid] < value) { + lo = mid + 1; + } + else { + ret = mid; + hi = mid - 1; + } + } + return ret; +} +exports.binarySearchUB = binarySearchUB; +function equalsCaseInsensitive(lhs, rhs) { + return lhs.toLowerCase() === rhs.toLowerCase(); +} +exports.equalsCaseInsensitive = equalsCaseInsensitive; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/Aggregation.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/Aggregation.js new file mode 100644 index 00000000..45086bb6 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/Aggregation.js @@ -0,0 +1,156 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DEFAULT_AGGREGATION = exports.EXPONENTIAL_HISTOGRAM_AGGREGATION = exports.HISTOGRAM_AGGREGATION = exports.LAST_VALUE_AGGREGATION = exports.SUM_AGGREGATION = exports.DROP_AGGREGATION = exports.DefaultAggregation = exports.ExponentialHistogramAggregation = exports.ExplicitBucketHistogramAggregation = exports.HistogramAggregation = exports.LastValueAggregation = exports.SumAggregation = exports.DropAggregation = void 0; +const api = require("@opentelemetry/api"); +const aggregator_1 = require("../aggregator"); +const MetricData_1 = require("../export/MetricData"); +/** + * The default drop aggregation. + */ +class DropAggregation { + static DEFAULT_INSTANCE = new aggregator_1.DropAggregator(); + createAggregator(_instrument) { + return DropAggregation.DEFAULT_INSTANCE; + } +} +exports.DropAggregation = DropAggregation; +/** + * The default sum aggregation. + */ +class SumAggregation { + static MONOTONIC_INSTANCE = new aggregator_1.SumAggregator(true); + static NON_MONOTONIC_INSTANCE = new aggregator_1.SumAggregator(false); + createAggregator(instrument) { + switch (instrument.type) { + case MetricData_1.InstrumentType.COUNTER: + case MetricData_1.InstrumentType.OBSERVABLE_COUNTER: + case MetricData_1.InstrumentType.HISTOGRAM: { + return SumAggregation.MONOTONIC_INSTANCE; + } + default: { + return SumAggregation.NON_MONOTONIC_INSTANCE; + } + } + } +} +exports.SumAggregation = SumAggregation; +/** + * The default last value aggregation. + */ +class LastValueAggregation { + static DEFAULT_INSTANCE = new aggregator_1.LastValueAggregator(); + createAggregator(_instrument) { + return LastValueAggregation.DEFAULT_INSTANCE; + } +} +exports.LastValueAggregation = LastValueAggregation; +/** + * The default histogram aggregation. + + */ +class HistogramAggregation { + static DEFAULT_INSTANCE = new aggregator_1.HistogramAggregator([0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000], true); + createAggregator(_instrument) { + return HistogramAggregation.DEFAULT_INSTANCE; + } +} +exports.HistogramAggregation = HistogramAggregation; +/** + * The explicit bucket histogram aggregation. + */ +class ExplicitBucketHistogramAggregation { + _recordMinMax; + _boundaries; + /** + * @param boundaries the bucket boundaries of the histogram aggregation + * @param _recordMinMax If set to true, min and max will be recorded. Otherwise, min and max will not be recorded. + */ + constructor(boundaries, _recordMinMax = true) { + this._recordMinMax = _recordMinMax; + if (boundaries == null) { + throw new Error('ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array'); + } + // Copy the boundaries array for modification. + boundaries = boundaries.concat(); + // We need to an ordered set to be able to correctly compute count for each + // boundary since we'll iterate on each in order. + boundaries = boundaries.sort((a, b) => a - b); + // Remove all Infinity from the boundaries. + const minusInfinityIndex = boundaries.lastIndexOf(-Infinity); + let infinityIndex = boundaries.indexOf(Infinity); + if (infinityIndex === -1) { + infinityIndex = undefined; + } + this._boundaries = boundaries.slice(minusInfinityIndex + 1, infinityIndex); + } + createAggregator(_instrument) { + return new aggregator_1.HistogramAggregator(this._boundaries, this._recordMinMax); + } +} +exports.ExplicitBucketHistogramAggregation = ExplicitBucketHistogramAggregation; +class ExponentialHistogramAggregation { + _maxSize; + _recordMinMax; + constructor(_maxSize = 160, _recordMinMax = true) { + this._maxSize = _maxSize; + this._recordMinMax = _recordMinMax; + } + createAggregator(_instrument) { + return new aggregator_1.ExponentialHistogramAggregator(this._maxSize, this._recordMinMax); + } +} +exports.ExponentialHistogramAggregation = ExponentialHistogramAggregation; +/** + * The default aggregation. + */ +class DefaultAggregation { + _resolve(instrument) { + // cast to unknown to disable complaints on the (unreachable) fallback. + switch (instrument.type) { + case MetricData_1.InstrumentType.COUNTER: + case MetricData_1.InstrumentType.UP_DOWN_COUNTER: + case MetricData_1.InstrumentType.OBSERVABLE_COUNTER: + case MetricData_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER: { + return exports.SUM_AGGREGATION; + } + case MetricData_1.InstrumentType.GAUGE: + case MetricData_1.InstrumentType.OBSERVABLE_GAUGE: { + return exports.LAST_VALUE_AGGREGATION; + } + case MetricData_1.InstrumentType.HISTOGRAM: { + if (instrument.advice.explicitBucketBoundaries) { + return new ExplicitBucketHistogramAggregation(instrument.advice.explicitBucketBoundaries); + } + return exports.HISTOGRAM_AGGREGATION; + } + } + api.diag.warn(`Unable to recognize instrument type: ${instrument.type}`); + return exports.DROP_AGGREGATION; + } + createAggregator(instrument) { + return this._resolve(instrument).createAggregator(instrument); + } +} +exports.DefaultAggregation = DefaultAggregation; +exports.DROP_AGGREGATION = new DropAggregation(); +exports.SUM_AGGREGATION = new SumAggregation(); +exports.LAST_VALUE_AGGREGATION = new LastValueAggregation(); +exports.HISTOGRAM_AGGREGATION = new HistogramAggregation(); +exports.EXPONENTIAL_HISTOGRAM_AGGREGATION = new ExponentialHistogramAggregation(); +exports.DEFAULT_AGGREGATION = new DefaultAggregation(); +//# sourceMappingURL=Aggregation.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/AggregationOption.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/AggregationOption.js new file mode 100644 index 00000000..fef93f71 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/AggregationOption.js @@ -0,0 +1,57 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.toAggregation = exports.AggregationType = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const Aggregation_1 = require("./Aggregation"); +var AggregationType; +(function (AggregationType) { + AggregationType[AggregationType["DEFAULT"] = 0] = "DEFAULT"; + AggregationType[AggregationType["DROP"] = 1] = "DROP"; + AggregationType[AggregationType["SUM"] = 2] = "SUM"; + AggregationType[AggregationType["LAST_VALUE"] = 3] = "LAST_VALUE"; + AggregationType[AggregationType["EXPLICIT_BUCKET_HISTOGRAM"] = 4] = "EXPLICIT_BUCKET_HISTOGRAM"; + AggregationType[AggregationType["EXPONENTIAL_HISTOGRAM"] = 5] = "EXPONENTIAL_HISTOGRAM"; +})(AggregationType = exports.AggregationType || (exports.AggregationType = {})); +function toAggregation(option) { + switch (option.type) { + case AggregationType.DEFAULT: + return Aggregation_1.DEFAULT_AGGREGATION; + case AggregationType.DROP: + return Aggregation_1.DROP_AGGREGATION; + case AggregationType.SUM: + return Aggregation_1.SUM_AGGREGATION; + case AggregationType.LAST_VALUE: + return Aggregation_1.LAST_VALUE_AGGREGATION; + case AggregationType.EXPONENTIAL_HISTOGRAM: { + const expOption = option; + return new Aggregation_1.ExponentialHistogramAggregation(expOption.options?.maxSize, expOption.options?.recordMinMax); + } + case AggregationType.EXPLICIT_BUCKET_HISTOGRAM: { + const expOption = option; + if (expOption.options == null) { + return Aggregation_1.HISTOGRAM_AGGREGATION; + } + else { + return new Aggregation_1.ExplicitBucketHistogramAggregation(expOption.options?.boundaries, expOption.options?.recordMinMax); + } + } + default: + throw new Error('Unsupported Aggregation'); + } +} +exports.toAggregation = toAggregation; +//# sourceMappingURL=AggregationOption.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/AttributesProcessor.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/AttributesProcessor.js new file mode 100644 index 00000000..43b8cd8c --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/AttributesProcessor.js @@ -0,0 +1,99 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createDenyListAttributesProcessor = exports.createAllowListAttributesProcessor = exports.createMultiAttributesProcessor = exports.createNoopAttributesProcessor = void 0; +class NoopAttributesProcessor { + process(incoming, _context) { + return incoming; + } +} +class MultiAttributesProcessor { + _processors; + constructor(_processors) { + this._processors = _processors; + } + process(incoming, context) { + let filteredAttributes = incoming; + for (const processor of this._processors) { + filteredAttributes = processor.process(filteredAttributes, context); + } + return filteredAttributes; + } +} +class AllowListProcessor { + _allowedAttributeNames; + constructor(_allowedAttributeNames) { + this._allowedAttributeNames = _allowedAttributeNames; + } + process(incoming, _context) { + const filteredAttributes = {}; + Object.keys(incoming) + .filter(attributeName => this._allowedAttributeNames.includes(attributeName)) + .forEach(attributeName => (filteredAttributes[attributeName] = incoming[attributeName])); + return filteredAttributes; + } +} +class DenyListProcessor { + _deniedAttributeNames; + constructor(_deniedAttributeNames) { + this._deniedAttributeNames = _deniedAttributeNames; + } + process(incoming, _context) { + const filteredAttributes = {}; + Object.keys(incoming) + .filter(attributeName => !this._deniedAttributeNames.includes(attributeName)) + .forEach(attributeName => (filteredAttributes[attributeName] = incoming[attributeName])); + return filteredAttributes; + } +} +/** + * @internal + * + * Create an {@link IAttributesProcessor} that acts as a simple pass-through for attributes. + */ +function createNoopAttributesProcessor() { + return NOOP; +} +exports.createNoopAttributesProcessor = createNoopAttributesProcessor; +/** + * @internal + * + * Create an {@link IAttributesProcessor} that applies all processors from the provided list in order. + * + * @param processors Processors to apply in order. + */ +function createMultiAttributesProcessor(processors) { + return new MultiAttributesProcessor(processors); +} +exports.createMultiAttributesProcessor = createMultiAttributesProcessor; +/** + * Create an {@link IAttributesProcessor} that filters by allowed attribute names and drops any names that are not in the + * allow list. + */ +function createAllowListAttributesProcessor(attributeAllowList) { + return new AllowListProcessor(attributeAllowList); +} +exports.createAllowListAttributesProcessor = createAllowListAttributesProcessor; +/** + * Create an {@link IAttributesProcessor} that drops attributes based on the names provided in the deny list + */ +function createDenyListAttributesProcessor(attributeDenyList) { + return new DenyListProcessor(attributeDenyList); +} +exports.createDenyListAttributesProcessor = createDenyListAttributesProcessor; +const NOOP = new NoopAttributesProcessor(); +//# sourceMappingURL=AttributesProcessor.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/InstrumentSelector.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/InstrumentSelector.js new file mode 100644 index 00000000..e9f32603 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/InstrumentSelector.js @@ -0,0 +1,40 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InstrumentSelector = void 0; +const Predicate_1 = require("./Predicate"); +class InstrumentSelector { + _nameFilter; + _type; + _unitFilter; + constructor(criteria) { + this._nameFilter = new Predicate_1.PatternPredicate(criteria?.name ?? '*'); + this._type = criteria?.type; + this._unitFilter = new Predicate_1.ExactPredicate(criteria?.unit); + } + getType() { + return this._type; + } + getNameFilter() { + return this._nameFilter; + } + getUnitFilter() { + return this._unitFilter; + } +} +exports.InstrumentSelector = InstrumentSelector; +//# sourceMappingURL=InstrumentSelector.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/MeterSelector.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/MeterSelector.js new file mode 100644 index 00000000..5dbaaffc --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/MeterSelector.js @@ -0,0 +1,43 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MeterSelector = void 0; +const Predicate_1 = require("./Predicate"); +class MeterSelector { + _nameFilter; + _versionFilter; + _schemaUrlFilter; + constructor(criteria) { + this._nameFilter = new Predicate_1.ExactPredicate(criteria?.name); + this._versionFilter = new Predicate_1.ExactPredicate(criteria?.version); + this._schemaUrlFilter = new Predicate_1.ExactPredicate(criteria?.schemaUrl); + } + getNameFilter() { + return this._nameFilter; + } + /** + * TODO: semver filter? no spec yet. + */ + getVersionFilter() { + return this._versionFilter; + } + getSchemaUrlFilter() { + return this._schemaUrlFilter; + } +} +exports.MeterSelector = MeterSelector; +//# sourceMappingURL=MeterSelector.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/Predicate.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/Predicate.js new file mode 100644 index 00000000..287df97c --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/Predicate.js @@ -0,0 +1,71 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ExactPredicate = exports.PatternPredicate = void 0; +// https://tc39.es/proposal-regex-escaping +// escape ^ $ \ . + ? ( ) [ ] { } | +// do not need to escape * as we interpret it as wildcard +const ESCAPE = /[\^$\\.+?()[\]{}|]/g; +/** + * Wildcard pattern predicate, supports patterns like `*`, `foo*`, `*bar`. + */ +class PatternPredicate { + _matchAll; + _regexp; + constructor(pattern) { + if (pattern === '*') { + this._matchAll = true; + this._regexp = /.*/; + } + else { + this._matchAll = false; + this._regexp = new RegExp(PatternPredicate.escapePattern(pattern)); + } + } + match(str) { + if (this._matchAll) { + return true; + } + return this._regexp.test(str); + } + static escapePattern(pattern) { + return `^${pattern.replace(ESCAPE, '\\$&').replace('*', '.*')}$`; + } + static hasWildcard(pattern) { + return pattern.includes('*'); + } +} +exports.PatternPredicate = PatternPredicate; +class ExactPredicate { + _matchAll; + _pattern; + constructor(pattern) { + this._matchAll = pattern === undefined; + this._pattern = pattern; + } + match(str) { + if (this._matchAll) { + return true; + } + if (str === this._pattern) { + return true; + } + return false; + } +} +exports.ExactPredicate = ExactPredicate; +//# sourceMappingURL=Predicate.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/RegistrationConflicts.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/RegistrationConflicts.js new file mode 100644 index 00000000..d9daedb3 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/RegistrationConflicts.js @@ -0,0 +1,85 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getConflictResolutionRecipe = exports.getDescriptionResolutionRecipe = exports.getTypeConflictResolutionRecipe = exports.getUnitConflictResolutionRecipe = exports.getValueTypeConflictResolutionRecipe = exports.getIncompatibilityDetails = void 0; +function getIncompatibilityDetails(existing, otherDescriptor) { + let incompatibility = ''; + if (existing.unit !== otherDescriptor.unit) { + incompatibility += `\t- Unit '${existing.unit}' does not match '${otherDescriptor.unit}'\n`; + } + if (existing.type !== otherDescriptor.type) { + incompatibility += `\t- Type '${existing.type}' does not match '${otherDescriptor.type}'\n`; + } + if (existing.valueType !== otherDescriptor.valueType) { + incompatibility += `\t- Value Type '${existing.valueType}' does not match '${otherDescriptor.valueType}'\n`; + } + if (existing.description !== otherDescriptor.description) { + incompatibility += `\t- Description '${existing.description}' does not match '${otherDescriptor.description}'\n`; + } + return incompatibility; +} +exports.getIncompatibilityDetails = getIncompatibilityDetails; +function getValueTypeConflictResolutionRecipe(existing, otherDescriptor) { + return `\t- use valueType '${existing.valueType}' on instrument creation or use an instrument name other than '${otherDescriptor.name}'`; +} +exports.getValueTypeConflictResolutionRecipe = getValueTypeConflictResolutionRecipe; +function getUnitConflictResolutionRecipe(existing, otherDescriptor) { + return `\t- use unit '${existing.unit}' on instrument creation or use an instrument name other than '${otherDescriptor.name}'`; +} +exports.getUnitConflictResolutionRecipe = getUnitConflictResolutionRecipe; +function getTypeConflictResolutionRecipe(existing, otherDescriptor) { + const selector = { + name: otherDescriptor.name, + type: otherDescriptor.type, + unit: otherDescriptor.unit, + }; + const selectorString = JSON.stringify(selector); + return `\t- create a new view with a name other than '${existing.name}' and InstrumentSelector '${selectorString}'`; +} +exports.getTypeConflictResolutionRecipe = getTypeConflictResolutionRecipe; +function getDescriptionResolutionRecipe(existing, otherDescriptor) { + const selector = { + name: otherDescriptor.name, + type: otherDescriptor.type, + unit: otherDescriptor.unit, + }; + const selectorString = JSON.stringify(selector); + return `\t- create a new view with a name other than '${existing.name}' and InstrumentSelector '${selectorString}' + \t- OR - create a new view with the name ${existing.name} and description '${existing.description}' and InstrumentSelector ${selectorString} + \t- OR - create a new view with the name ${otherDescriptor.name} and description '${existing.description}' and InstrumentSelector ${selectorString}`; +} +exports.getDescriptionResolutionRecipe = getDescriptionResolutionRecipe; +function getConflictResolutionRecipe(existing, otherDescriptor) { + // Conflicts that cannot be solved via views. + if (existing.valueType !== otherDescriptor.valueType) { + return getValueTypeConflictResolutionRecipe(existing, otherDescriptor); + } + if (existing.unit !== otherDescriptor.unit) { + return getUnitConflictResolutionRecipe(existing, otherDescriptor); + } + // Conflicts that can be solved via views. + if (existing.type !== otherDescriptor.type) { + // this will automatically solve possible description conflicts. + return getTypeConflictResolutionRecipe(existing, otherDescriptor); + } + if (existing.description !== otherDescriptor.description) { + return getDescriptionResolutionRecipe(existing, otherDescriptor); + } + return ''; +} +exports.getConflictResolutionRecipe = getConflictResolutionRecipe; +//# sourceMappingURL=RegistrationConflicts.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/View.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/View.js new file mode 100644 index 00000000..6fbb53c6 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/View.js @@ -0,0 +1,139 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.View = void 0; +const Predicate_1 = require("./Predicate"); +const AttributesProcessor_1 = require("./AttributesProcessor"); +const InstrumentSelector_1 = require("./InstrumentSelector"); +const MeterSelector_1 = require("./MeterSelector"); +const AggregationOption_1 = require("./AggregationOption"); +function isSelectorNotProvided(options) { + return (options.instrumentName == null && + options.instrumentType == null && + options.instrumentUnit == null && + options.meterName == null && + options.meterVersion == null && + options.meterSchemaUrl == null); +} +function validateViewOptions(viewOptions) { + // If no criteria is provided, the SDK SHOULD treat it as an error. + // It is recommended that the SDK implementations fail fast. + if (isSelectorNotProvided(viewOptions)) { + throw new Error('Cannot create view with no selector arguments supplied'); + } + // the SDK SHOULD NOT allow Views with a specified name to be declared with instrument selectors that + // may select more than one instrument (e.g. wild card instrument name) in the same Meter. + if (viewOptions.name != null && + (viewOptions?.instrumentName == null || + Predicate_1.PatternPredicate.hasWildcard(viewOptions.instrumentName))) { + throw new Error('Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.'); + } +} +/** + * Can be passed to a {@link MeterProvider} to select instruments and alter their metric stream. + */ +class View { + name; + description; + aggregation; + attributesProcessor; + instrumentSelector; + meterSelector; + aggregationCardinalityLimit; + /** + * Create a new {@link View} instance. + * + * Parameters can be categorized as two types: + * Instrument selection criteria: Used to describe the instrument(s) this view will be applied to. + * Will be treated as additive (the Instrument has to meet all the provided criteria to be selected). + * + * Metric stream altering: Alter the metric stream of instruments selected by instrument selection criteria. + * + * @param viewOptions {@link ViewOptions} for altering the metric stream and instrument selection. + * @param viewOptions.name + * Alters the metric stream: + * This will be used as the name of the metrics stream. + * If not provided, the original Instrument name will be used. + * @param viewOptions.description + * Alters the metric stream: + * This will be used as the description of the metrics stream. + * If not provided, the original Instrument description will be used by default. + * @param viewOptions.attributesProcessors + * Alters the metric stream: + * If provided, the attributes will be modified as defined by the added processors. + * If not provided, all attribute keys will be used by default. + * @param viewOptions.aggregationCardinalityLimit + * Alters the metric stream: + * Sets a limit on the number of unique attribute combinations (cardinality) that can be aggregated. + * If not provided, the default limit of 2000 will be used. + * @param viewOptions.aggregation + * Alters the metric stream: + * Alters the {@link Aggregation} of the metric stream. + * @param viewOptions.instrumentName + * Instrument selection criteria: + * Original name of the Instrument(s) with wildcard support. + * @param viewOptions.instrumentType + * Instrument selection criteria: + * The original type of the Instrument(s). + * @param viewOptions.instrumentUnit + * Instrument selection criteria: + * The unit of the Instrument(s). + * @param viewOptions.meterName + * Instrument selection criteria: + * The name of the Meter. No wildcard support, name must match the meter exactly. + * @param viewOptions.meterVersion + * Instrument selection criteria: + * The version of the Meter. No wildcard support, version must match exactly. + * @param viewOptions.meterSchemaUrl + * Instrument selection criteria: + * The schema URL of the Meter. No wildcard support, schema URL must match exactly. + * + * @example + * // Create a view that changes the Instrument 'my.instrument' to use to an + * // ExplicitBucketHistogramAggregation with the boundaries [20, 30, 40] + * new View({ + * aggregation: new ExplicitBucketHistogramAggregation([20, 30, 40]), + * instrumentName: 'my.instrument' + * }) + */ + constructor(viewOptions) { + validateViewOptions(viewOptions); + // Create multi-processor if attributesProcessors are defined. + if (viewOptions.attributesProcessors != null) { + this.attributesProcessor = (0, AttributesProcessor_1.createMultiAttributesProcessor)(viewOptions.attributesProcessors); + } + else { + this.attributesProcessor = (0, AttributesProcessor_1.createNoopAttributesProcessor)(); + } + this.name = viewOptions.name; + this.description = viewOptions.description; + this.aggregation = (0, AggregationOption_1.toAggregation)(viewOptions.aggregation ?? { type: AggregationOption_1.AggregationType.DEFAULT }); + this.instrumentSelector = new InstrumentSelector_1.InstrumentSelector({ + name: viewOptions.instrumentName, + type: viewOptions.instrumentType, + unit: viewOptions.instrumentUnit, + }); + this.meterSelector = new MeterSelector_1.MeterSelector({ + name: viewOptions.meterName, + version: viewOptions.meterVersion, + schemaUrl: viewOptions.meterSchemaUrl, + }); + this.aggregationCardinalityLimit = viewOptions.aggregationCardinalityLimit; + } +} +exports.View = View; +//# sourceMappingURL=View.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/ViewRegistry.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/ViewRegistry.js new file mode 100644 index 00000000..58c5c632 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/ViewRegistry.js @@ -0,0 +1,46 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ViewRegistry = void 0; +class ViewRegistry { + _registeredViews = []; + addView(view) { + this._registeredViews.push(view); + } + findViews(instrument, meter) { + const views = this._registeredViews.filter(registeredView => { + return (this._matchInstrument(registeredView.instrumentSelector, instrument) && + this._matchMeter(registeredView.meterSelector, meter)); + }); + return views; + } + _matchInstrument(selector, instrument) { + return ((selector.getType() === undefined || + instrument.type === selector.getType()) && + selector.getNameFilter().match(instrument.name) && + selector.getUnitFilter().match(instrument.unit)); + } + _matchMeter(selector, meter) { + return (selector.getNameFilter().match(meter.name) && + (meter.version === undefined || + selector.getVersionFilter().match(meter.version)) && + (meter.schemaUrl === undefined || + selector.getSchemaUrlFilter().match(meter.schemaUrl))); + } +} +exports.ViewRegistry = ViewRegistry; +//# sourceMappingURL=ViewRegistry.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/BasicTracerProvider.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/BasicTracerProvider.js new file mode 100644 index 00000000..baa41902 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/BasicTracerProvider.js @@ -0,0 +1,104 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BasicTracerProvider = exports.ForceFlushState = void 0; +const core_1 = require("@opentelemetry/core"); +const resources_1 = require("@opentelemetry/resources"); +const Tracer_1 = require("./Tracer"); +const config_1 = require("./config"); +const MultiSpanProcessor_1 = require("./MultiSpanProcessor"); +const utility_1 = require("./utility"); +var ForceFlushState; +(function (ForceFlushState) { + ForceFlushState[ForceFlushState["resolved"] = 0] = "resolved"; + ForceFlushState[ForceFlushState["timeout"] = 1] = "timeout"; + ForceFlushState[ForceFlushState["error"] = 2] = "error"; + ForceFlushState[ForceFlushState["unresolved"] = 3] = "unresolved"; +})(ForceFlushState = exports.ForceFlushState || (exports.ForceFlushState = {})); +/** + * This class represents a basic tracer provider which platform libraries can extend + */ +class BasicTracerProvider { + _config; + _tracers = new Map(); + _resource; + _activeSpanProcessor; + constructor(config = {}) { + const mergedConfig = (0, core_1.merge)({}, (0, config_1.loadDefaultConfig)(), (0, utility_1.reconfigureLimits)(config)); + this._resource = mergedConfig.resource ?? (0, resources_1.defaultResource)(); + this._config = Object.assign({}, mergedConfig, { + resource: this._resource, + }); + const spanProcessors = []; + if (config.spanProcessors?.length) { + spanProcessors.push(...config.spanProcessors); + } + this._activeSpanProcessor = new MultiSpanProcessor_1.MultiSpanProcessor(spanProcessors); + } + getTracer(name, version, options) { + const key = `${name}@${version || ''}:${options?.schemaUrl || ''}`; + if (!this._tracers.has(key)) { + this._tracers.set(key, new Tracer_1.Tracer({ name, version, schemaUrl: options?.schemaUrl }, this._config, this._resource, this._activeSpanProcessor)); + } + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + return this._tracers.get(key); + } + forceFlush() { + const timeout = this._config.forceFlushTimeoutMillis; + const promises = this._activeSpanProcessor['_spanProcessors'].map((spanProcessor) => { + return new Promise(resolve => { + let state; + const timeoutInterval = setTimeout(() => { + resolve(new Error(`Span processor did not completed within timeout period of ${timeout} ms`)); + state = ForceFlushState.timeout; + }, timeout); + spanProcessor + .forceFlush() + .then(() => { + clearTimeout(timeoutInterval); + if (state !== ForceFlushState.timeout) { + state = ForceFlushState.resolved; + resolve(state); + } + }) + .catch(error => { + clearTimeout(timeoutInterval); + state = ForceFlushState.error; + resolve(error); + }); + }); + }); + return new Promise((resolve, reject) => { + Promise.all(promises) + .then(results => { + const errors = results.filter(result => result !== ForceFlushState.resolved); + if (errors.length > 0) { + reject(errors); + } + else { + resolve(); + } + }) + .catch(error => reject([error])); + }); + } + shutdown() { + return this._activeSpanProcessor.shutdown(); + } +} +exports.BasicTracerProvider = BasicTracerProvider; +//# sourceMappingURL=BasicTracerProvider.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/MultiSpanProcessor.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/MultiSpanProcessor.js new file mode 100644 index 00000000..de577b79 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/MultiSpanProcessor.js @@ -0,0 +1,68 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MultiSpanProcessor = void 0; +const core_1 = require("@opentelemetry/core"); +/** + * Implementation of the {@link SpanProcessor} that simply forwards all + * received events to a list of {@link SpanProcessor}s. + */ +class MultiSpanProcessor { + _spanProcessors; + constructor(_spanProcessors) { + this._spanProcessors = _spanProcessors; + } + forceFlush() { + const promises = []; + for (const spanProcessor of this._spanProcessors) { + promises.push(spanProcessor.forceFlush()); + } + return new Promise(resolve => { + Promise.all(promises) + .then(() => { + resolve(); + }) + .catch(error => { + (0, core_1.globalErrorHandler)(error || new Error('MultiSpanProcessor: forceFlush failed')); + resolve(); + }); + }); + } + onStart(span, context) { + for (const spanProcessor of this._spanProcessors) { + spanProcessor.onStart(span, context); + } + } + onEnd(span) { + for (const spanProcessor of this._spanProcessors) { + spanProcessor.onEnd(span); + } + } + shutdown() { + const promises = []; + for (const spanProcessor of this._spanProcessors) { + promises.push(spanProcessor.shutdown()); + } + return new Promise((resolve, reject) => { + Promise.all(promises).then(() => { + resolve(); + }, reject); + }); + } +} +exports.MultiSpanProcessor = MultiSpanProcessor; +//# sourceMappingURL=MultiSpanProcessor.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/Sampler.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/Sampler.js new file mode 100644 index 00000000..ddb4b599 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/Sampler.js @@ -0,0 +1,41 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SamplingDecision = void 0; +/** + * A sampling decision that determines how a {@link Span} will be recorded + * and collected. + */ +var SamplingDecision; +(function (SamplingDecision) { + /** + * `Span.isRecording() === false`, span will not be recorded and all events + * and attributes will be dropped. + */ + SamplingDecision[SamplingDecision["NOT_RECORD"] = 0] = "NOT_RECORD"; + /** + * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags} + * MUST NOT be set. + */ + SamplingDecision[SamplingDecision["RECORD"] = 1] = "RECORD"; + /** + * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags} + * MUST be set. + */ + SamplingDecision[SamplingDecision["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED"; +})(SamplingDecision = exports.SamplingDecision || (exports.SamplingDecision = {})); +//# sourceMappingURL=Sampler.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/Span.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/Span.js new file mode 100644 index 00000000..5a807fe2 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/Span.js @@ -0,0 +1,312 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SpanImpl = void 0; +const api_1 = require("@opentelemetry/api"); +const core_1 = require("@opentelemetry/core"); +const semantic_conventions_1 = require("@opentelemetry/semantic-conventions"); +const enums_1 = require("./enums"); +/** + * This class represents a span. + */ +class SpanImpl { + // Below properties are included to implement ReadableSpan for export + // purposes but are not intended to be written-to directly. + _spanContext; + kind; + parentSpanContext; + attributes = {}; + links = []; + events = []; + startTime; + resource; + instrumentationScope; + _droppedAttributesCount = 0; + _droppedEventsCount = 0; + _droppedLinksCount = 0; + name; + status = { + code: api_1.SpanStatusCode.UNSET, + }; + endTime = [0, 0]; + _ended = false; + _duration = [-1, -1]; + _spanProcessor; + _spanLimits; + _attributeValueLengthLimit; + _performanceStartTime; + _performanceOffset; + _startTimeProvided; + /** + * Constructs a new SpanImpl instance. + */ + constructor(opts) { + const now = Date.now(); + this._spanContext = opts.spanContext; + this._performanceStartTime = core_1.otperformance.now(); + this._performanceOffset = + now - (this._performanceStartTime + (0, core_1.getTimeOrigin)()); + this._startTimeProvided = opts.startTime != null; + this._spanLimits = opts.spanLimits; + this._attributeValueLengthLimit = + this._spanLimits.attributeValueLengthLimit || 0; + this._spanProcessor = opts.spanProcessor; + this.name = opts.name; + this.parentSpanContext = opts.parentSpanContext; + this.kind = opts.kind; + this.links = opts.links || []; + this.startTime = this._getTime(opts.startTime ?? now); + this.resource = opts.resource; + this.instrumentationScope = opts.scope; + if (opts.attributes != null) { + this.setAttributes(opts.attributes); + } + this._spanProcessor.onStart(this, opts.context); + } + spanContext() { + return this._spanContext; + } + setAttribute(key, value) { + if (value == null || this._isSpanEnded()) + return this; + if (key.length === 0) { + api_1.diag.warn(`Invalid attribute key: ${key}`); + return this; + } + if (!(0, core_1.isAttributeValue)(value)) { + api_1.diag.warn(`Invalid attribute value set for key: ${key}`); + return this; + } + const { attributeCountLimit } = this._spanLimits; + if (attributeCountLimit !== undefined && + Object.keys(this.attributes).length >= attributeCountLimit && + !Object.prototype.hasOwnProperty.call(this.attributes, key)) { + this._droppedAttributesCount++; + return this; + } + this.attributes[key] = this._truncateToSize(value); + return this; + } + setAttributes(attributes) { + for (const [k, v] of Object.entries(attributes)) { + this.setAttribute(k, v); + } + return this; + } + /** + * + * @param name Span Name + * @param [attributesOrStartTime] Span attributes or start time + * if type is {@type TimeInput} and 3rd param is undefined + * @param [timeStamp] Specified time stamp for the event + */ + addEvent(name, attributesOrStartTime, timeStamp) { + if (this._isSpanEnded()) + return this; + const { eventCountLimit } = this._spanLimits; + if (eventCountLimit === 0) { + api_1.diag.warn('No events allowed.'); + this._droppedEventsCount++; + return this; + } + if (eventCountLimit !== undefined && + this.events.length >= eventCountLimit) { + if (this._droppedEventsCount === 0) { + api_1.diag.debug('Dropping extra events.'); + } + this.events.shift(); + this._droppedEventsCount++; + } + if ((0, core_1.isTimeInput)(attributesOrStartTime)) { + if (!(0, core_1.isTimeInput)(timeStamp)) { + timeStamp = attributesOrStartTime; + } + attributesOrStartTime = undefined; + } + const attributes = (0, core_1.sanitizeAttributes)(attributesOrStartTime); + this.events.push({ + name, + attributes, + time: this._getTime(timeStamp), + droppedAttributesCount: 0, + }); + return this; + } + addLink(link) { + this.links.push(link); + return this; + } + addLinks(links) { + this.links.push(...links); + return this; + } + setStatus(status) { + if (this._isSpanEnded()) + return this; + this.status = { ...status }; + // When using try-catch, the caught "error" is of type `any`. When then assigning `any` to `status.message`, + // TypeScript will not error. While this can happen during use of any API, it is more common on Span#setStatus() + // as it's likely used in a catch-block. Therefore, we validate if `status.message` is actually a string, null, or + // undefined to avoid an incorrect type causing issues downstream. + if (this.status.message != null && typeof status.message !== 'string') { + api_1.diag.warn(`Dropping invalid status.message of type '${typeof status.message}', expected 'string'`); + delete this.status.message; + } + return this; + } + updateName(name) { + if (this._isSpanEnded()) + return this; + this.name = name; + return this; + } + end(endTime) { + if (this._isSpanEnded()) { + api_1.diag.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`); + return; + } + this._ended = true; + this.endTime = this._getTime(endTime); + this._duration = (0, core_1.hrTimeDuration)(this.startTime, this.endTime); + if (this._duration[0] < 0) { + api_1.diag.warn('Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.', this.startTime, this.endTime); + this.endTime = this.startTime.slice(); + this._duration = [0, 0]; + } + if (this._droppedEventsCount > 0) { + api_1.diag.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`); + } + this._spanProcessor.onEnd(this); + } + _getTime(inp) { + if (typeof inp === 'number' && inp <= core_1.otperformance.now()) { + // must be a performance timestamp + // apply correction and convert to hrtime + return (0, core_1.hrTime)(inp + this._performanceOffset); + } + if (typeof inp === 'number') { + return (0, core_1.millisToHrTime)(inp); + } + if (inp instanceof Date) { + return (0, core_1.millisToHrTime)(inp.getTime()); + } + if ((0, core_1.isTimeInputHrTime)(inp)) { + return inp; + } + if (this._startTimeProvided) { + // if user provided a time for the start manually + // we can't use duration to calculate event/end times + return (0, core_1.millisToHrTime)(Date.now()); + } + const msDuration = core_1.otperformance.now() - this._performanceStartTime; + return (0, core_1.addHrTimes)(this.startTime, (0, core_1.millisToHrTime)(msDuration)); + } + isRecording() { + return this._ended === false; + } + recordException(exception, time) { + const attributes = {}; + if (typeof exception === 'string') { + attributes[semantic_conventions_1.ATTR_EXCEPTION_MESSAGE] = exception; + } + else if (exception) { + if (exception.code) { + attributes[semantic_conventions_1.ATTR_EXCEPTION_TYPE] = exception.code.toString(); + } + else if (exception.name) { + attributes[semantic_conventions_1.ATTR_EXCEPTION_TYPE] = exception.name; + } + if (exception.message) { + attributes[semantic_conventions_1.ATTR_EXCEPTION_MESSAGE] = exception.message; + } + if (exception.stack) { + attributes[semantic_conventions_1.ATTR_EXCEPTION_STACKTRACE] = exception.stack; + } + } + // these are minimum requirements from spec + if (attributes[semantic_conventions_1.ATTR_EXCEPTION_TYPE] || attributes[semantic_conventions_1.ATTR_EXCEPTION_MESSAGE]) { + this.addEvent(enums_1.ExceptionEventName, attributes, time); + } + else { + api_1.diag.warn(`Failed to record an exception ${exception}`); + } + } + get duration() { + return this._duration; + } + get ended() { + return this._ended; + } + get droppedAttributesCount() { + return this._droppedAttributesCount; + } + get droppedEventsCount() { + return this._droppedEventsCount; + } + get droppedLinksCount() { + return this._droppedLinksCount; + } + _isSpanEnded() { + if (this._ended) { + const error = new Error(`Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`); + api_1.diag.warn(`Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`, error); + } + return this._ended; + } + // Utility function to truncate given value within size + // for value type of string, will truncate to given limit + // for type of non-string, will return same value + _truncateToLimitUtil(value, limit) { + if (value.length <= limit) { + return value; + } + return value.substring(0, limit); + } + /** + * If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then + * return string with truncated to {@code attributeValueLengthLimit} characters + * + * If the given attribute value is array of strings then + * return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters + * + * Otherwise return same Attribute {@code value} + * + * @param value Attribute value + * @returns truncated attribute value if required, otherwise same value + */ + _truncateToSize(value) { + const limit = this._attributeValueLengthLimit; + // Check limit + if (limit <= 0) { + // Negative values are invalid, so do not truncate + api_1.diag.warn(`Attribute value limit must be positive, got ${limit}`); + return value; + } + // String + if (typeof value === 'string') { + return this._truncateToLimitUtil(value, limit); + } + // Array of strings + if (Array.isArray(value)) { + return value.map(val => typeof val === 'string' ? this._truncateToLimitUtil(val, limit) : val); + } + // Other types, no need to apply value length limit + return value; + } +} +exports.SpanImpl = SpanImpl; +//# sourceMappingURL=Span.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/Tracer.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/Tracer.js new file mode 100644 index 00000000..ec08e4a6 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/Tracer.js @@ -0,0 +1,152 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Tracer = void 0; +const api = require("@opentelemetry/api"); +const core_1 = require("@opentelemetry/core"); +const Span_1 = require("./Span"); +const utility_1 = require("./utility"); +const platform_1 = require("./platform"); +/** + * This class represents a basic tracer. + */ +class Tracer { + _sampler; + _generalLimits; + _spanLimits; + _idGenerator; + instrumentationScope; + _resource; + _spanProcessor; + /** + * Constructs a new Tracer instance. + */ + constructor(instrumentationScope, config, resource, spanProcessor) { + const localConfig = (0, utility_1.mergeConfig)(config); + this._sampler = localConfig.sampler; + this._generalLimits = localConfig.generalLimits; + this._spanLimits = localConfig.spanLimits; + this._idGenerator = config.idGenerator || new platform_1.RandomIdGenerator(); + this._resource = resource; + this._spanProcessor = spanProcessor; + this.instrumentationScope = instrumentationScope; + } + /** + * Starts a new Span or returns the default NoopSpan based on the sampling + * decision. + */ + startSpan(name, options = {}, context = api.context.active()) { + // remove span from context in case a root span is requested via options + if (options.root) { + context = api.trace.deleteSpan(context); + } + const parentSpan = api.trace.getSpan(context); + if ((0, core_1.isTracingSuppressed)(context)) { + api.diag.debug('Instrumentation suppressed, returning Noop Span'); + const nonRecordingSpan = api.trace.wrapSpanContext(api.INVALID_SPAN_CONTEXT); + return nonRecordingSpan; + } + const parentSpanContext = parentSpan?.spanContext(); + const spanId = this._idGenerator.generateSpanId(); + let validParentSpanContext; + let traceId; + let traceState; + if (!parentSpanContext || + !api.trace.isSpanContextValid(parentSpanContext)) { + // New root span. + traceId = this._idGenerator.generateTraceId(); + } + else { + // New child span. + traceId = parentSpanContext.traceId; + traceState = parentSpanContext.traceState; + validParentSpanContext = parentSpanContext; + } + const spanKind = options.kind ?? api.SpanKind.INTERNAL; + const links = (options.links ?? []).map(link => { + return { + context: link.context, + attributes: (0, core_1.sanitizeAttributes)(link.attributes), + }; + }); + const attributes = (0, core_1.sanitizeAttributes)(options.attributes); + // make sampling decision + const samplingResult = this._sampler.shouldSample(context, traceId, name, spanKind, attributes, links); + traceState = samplingResult.traceState ?? traceState; + const traceFlags = samplingResult.decision === api.SamplingDecision.RECORD_AND_SAMPLED + ? api.TraceFlags.SAMPLED + : api.TraceFlags.NONE; + const spanContext = { traceId, spanId, traceFlags, traceState }; + if (samplingResult.decision === api.SamplingDecision.NOT_RECORD) { + api.diag.debug('Recording is off, propagating context in a non-recording span'); + const nonRecordingSpan = api.trace.wrapSpanContext(spanContext); + return nonRecordingSpan; + } + // Set initial span attributes. The attributes object may have been mutated + // by the sampler, so we sanitize the merged attributes before setting them. + const initAttributes = (0, core_1.sanitizeAttributes)(Object.assign(attributes, samplingResult.attributes)); + const span = new Span_1.SpanImpl({ + resource: this._resource, + scope: this.instrumentationScope, + context, + spanContext, + name, + kind: spanKind, + links, + parentSpanContext: validParentSpanContext, + attributes: initAttributes, + startTime: options.startTime, + spanProcessor: this._spanProcessor, + spanLimits: this._spanLimits, + }); + return span; + } + startActiveSpan(name, arg2, arg3, arg4) { + let opts; + let ctx; + let fn; + if (arguments.length < 2) { + return; + } + else if (arguments.length === 2) { + fn = arg2; + } + else if (arguments.length === 3) { + opts = arg2; + fn = arg3; + } + else { + opts = arg2; + ctx = arg3; + fn = arg4; + } + const parentContext = ctx ?? api.context.active(); + const span = this.startSpan(name, opts, parentContext); + const contextWithSpanSet = api.trace.setSpan(parentContext, span); + return api.context.with(contextWithSpanSet, fn, undefined, span); + } + /** Returns the active {@link GeneralLimits}. */ + getGeneralLimits() { + return this._generalLimits; + } + /** Returns the active {@link SpanLimits}. */ + getSpanLimits() { + return this._spanLimits; + } +} +exports.Tracer = Tracer; +//# sourceMappingURL=Tracer.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/config.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/config.js new file mode 100644 index 00000000..118b84af --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/config.js @@ -0,0 +1,107 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.buildSamplerFromEnv = exports.loadDefaultConfig = void 0; +const api_1 = require("@opentelemetry/api"); +const core_1 = require("@opentelemetry/core"); +const AlwaysOffSampler_1 = require("./sampler/AlwaysOffSampler"); +const AlwaysOnSampler_1 = require("./sampler/AlwaysOnSampler"); +const ParentBasedSampler_1 = require("./sampler/ParentBasedSampler"); +const TraceIdRatioBasedSampler_1 = require("./sampler/TraceIdRatioBasedSampler"); +var TracesSamplerValues; +(function (TracesSamplerValues) { + TracesSamplerValues["AlwaysOff"] = "always_off"; + TracesSamplerValues["AlwaysOn"] = "always_on"; + TracesSamplerValues["ParentBasedAlwaysOff"] = "parentbased_always_off"; + TracesSamplerValues["ParentBasedAlwaysOn"] = "parentbased_always_on"; + TracesSamplerValues["ParentBasedTraceIdRatio"] = "parentbased_traceidratio"; + TracesSamplerValues["TraceIdRatio"] = "traceidratio"; +})(TracesSamplerValues || (TracesSamplerValues = {})); +const DEFAULT_RATIO = 1; +/** + * Load default configuration. For fields with primitive values, any user-provided + * value will override the corresponding default value. For fields with + * non-primitive values (like `spanLimits`), the user-provided value will be + * used to extend the default value. + */ +// object needs to be wrapped in this function and called when needed otherwise +// envs are parsed before tests are ran - causes tests using these envs to fail +function loadDefaultConfig() { + return { + sampler: buildSamplerFromEnv(), + forceFlushTimeoutMillis: 30000, + generalLimits: { + attributeValueLengthLimit: (0, core_1.getNumberFromEnv)('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? Infinity, + attributeCountLimit: (0, core_1.getNumberFromEnv)('OTEL_ATTRIBUTE_COUNT_LIMIT') ?? 128, + }, + spanLimits: { + attributeValueLengthLimit: (0, core_1.getNumberFromEnv)('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? Infinity, + attributeCountLimit: (0, core_1.getNumberFromEnv)('OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT') ?? 128, + linkCountLimit: (0, core_1.getNumberFromEnv)('OTEL_SPAN_LINK_COUNT_LIMIT') ?? 128, + eventCountLimit: (0, core_1.getNumberFromEnv)('OTEL_SPAN_EVENT_COUNT_LIMIT') ?? 128, + attributePerEventCountLimit: (0, core_1.getNumberFromEnv)('OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT') ?? 128, + attributePerLinkCountLimit: (0, core_1.getNumberFromEnv)('OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT') ?? 128, + }, + }; +} +exports.loadDefaultConfig = loadDefaultConfig; +/** + * Based on environment, builds a sampler, complies with specification. + */ +function buildSamplerFromEnv() { + const sampler = (0, core_1.getStringFromEnv)('OTEL_TRACES_SAMPLER') ?? + TracesSamplerValues.ParentBasedAlwaysOn; + switch (sampler) { + case TracesSamplerValues.AlwaysOn: + return new AlwaysOnSampler_1.AlwaysOnSampler(); + case TracesSamplerValues.AlwaysOff: + return new AlwaysOffSampler_1.AlwaysOffSampler(); + case TracesSamplerValues.ParentBasedAlwaysOn: + return new ParentBasedSampler_1.ParentBasedSampler({ + root: new AlwaysOnSampler_1.AlwaysOnSampler(), + }); + case TracesSamplerValues.ParentBasedAlwaysOff: + return new ParentBasedSampler_1.ParentBasedSampler({ + root: new AlwaysOffSampler_1.AlwaysOffSampler(), + }); + case TracesSamplerValues.TraceIdRatio: + return new TraceIdRatioBasedSampler_1.TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv()); + case TracesSamplerValues.ParentBasedTraceIdRatio: + return new ParentBasedSampler_1.ParentBasedSampler({ + root: new TraceIdRatioBasedSampler_1.TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv()), + }); + default: + api_1.diag.error(`OTEL_TRACES_SAMPLER value "${sampler}" invalid, defaulting to "${TracesSamplerValues.ParentBasedAlwaysOn}".`); + return new ParentBasedSampler_1.ParentBasedSampler({ + root: new AlwaysOnSampler_1.AlwaysOnSampler(), + }); + } +} +exports.buildSamplerFromEnv = buildSamplerFromEnv; +function getSamplerProbabilityFromEnv() { + const probability = (0, core_1.getNumberFromEnv)('OTEL_TRACES_SAMPLER_ARG'); + if (probability == null) { + api_1.diag.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${DEFAULT_RATIO}.`); + return DEFAULT_RATIO; + } + if (probability < 0 || probability > 1) { + api_1.diag.error(`OTEL_TRACES_SAMPLER_ARG=${probability} was given, but it is out of range ([0..1]), defaulting to ${DEFAULT_RATIO}.`); + return DEFAULT_RATIO; + } + return probability; +} +//# sourceMappingURL=config.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/enums.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/enums.js new file mode 100644 index 00000000..aecbce0b --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/enums.js @@ -0,0 +1,21 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ExceptionEventName = void 0; +// Event name definitions +exports.ExceptionEventName = 'exception'; +//# sourceMappingURL=enums.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/BatchSpanProcessorBase.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/BatchSpanProcessorBase.js new file mode 100644 index 00000000..255baeec --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/BatchSpanProcessorBase.js @@ -0,0 +1,223 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BatchSpanProcessorBase = void 0; +const api_1 = require("@opentelemetry/api"); +const core_1 = require("@opentelemetry/core"); +/** + * Implementation of the {@link SpanProcessor} that batches spans exported by + * the SDK then pushes them to the exporter pipeline. + */ +class BatchSpanProcessorBase { + _exporter; + _maxExportBatchSize; + _maxQueueSize; + _scheduledDelayMillis; + _exportTimeoutMillis; + _isExporting = false; + _finishedSpans = []; + _timer; + _shutdownOnce; + _droppedSpansCount = 0; + constructor(_exporter, config) { + this._exporter = _exporter; + this._maxExportBatchSize = + typeof config?.maxExportBatchSize === 'number' + ? config.maxExportBatchSize + : ((0, core_1.getNumberFromEnv)('OTEL_BSP_MAX_EXPORT_BATCH_SIZE') ?? 512); + this._maxQueueSize = + typeof config?.maxQueueSize === 'number' + ? config.maxQueueSize + : ((0, core_1.getNumberFromEnv)('OTEL_BSP_MAX_QUEUE_SIZE') ?? 2048); + this._scheduledDelayMillis = + typeof config?.scheduledDelayMillis === 'number' + ? config.scheduledDelayMillis + : ((0, core_1.getNumberFromEnv)('OTEL_BSP_SCHEDULE_DELAY') ?? 5000); + this._exportTimeoutMillis = + typeof config?.exportTimeoutMillis === 'number' + ? config.exportTimeoutMillis + : ((0, core_1.getNumberFromEnv)('OTEL_BSP_EXPORT_TIMEOUT') ?? 30000); + this._shutdownOnce = new core_1.BindOnceFuture(this._shutdown, this); + if (this._maxExportBatchSize > this._maxQueueSize) { + api_1.diag.warn('BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize'); + this._maxExportBatchSize = this._maxQueueSize; + } + } + forceFlush() { + if (this._shutdownOnce.isCalled) { + return this._shutdownOnce.promise; + } + return this._flushAll(); + } + // does nothing. + onStart(_span, _parentContext) { } + onEnd(span) { + if (this._shutdownOnce.isCalled) { + return; + } + if ((span.spanContext().traceFlags & api_1.TraceFlags.SAMPLED) === 0) { + return; + } + this._addToBuffer(span); + } + shutdown() { + return this._shutdownOnce.call(); + } + _shutdown() { + return Promise.resolve() + .then(() => { + return this.onShutdown(); + }) + .then(() => { + return this._flushAll(); + }) + .then(() => { + return this._exporter.shutdown(); + }); + } + /** Add a span in the buffer. */ + _addToBuffer(span) { + if (this._finishedSpans.length >= this._maxQueueSize) { + // limit reached, drop span + if (this._droppedSpansCount === 0) { + api_1.diag.debug('maxQueueSize reached, dropping spans'); + } + this._droppedSpansCount++; + return; + } + if (this._droppedSpansCount > 0) { + // some spans were dropped, log once with count of spans dropped + api_1.diag.warn(`Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`); + this._droppedSpansCount = 0; + } + this._finishedSpans.push(span); + this._maybeStartTimer(); + } + /** + * Send all spans to the exporter respecting the batch size limit + * This function is used only on forceFlush or shutdown, + * for all other cases _flush should be used + * */ + _flushAll() { + return new Promise((resolve, reject) => { + const promises = []; + // calculate number of batches + const count = Math.ceil(this._finishedSpans.length / this._maxExportBatchSize); + for (let i = 0, j = count; i < j; i++) { + promises.push(this._flushOneBatch()); + } + Promise.all(promises) + .then(() => { + resolve(); + }) + .catch(reject); + }); + } + _flushOneBatch() { + this._clearTimer(); + if (this._finishedSpans.length === 0) { + return Promise.resolve(); + } + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + // don't wait anymore for export, this way the next batch can start + reject(new Error('Timeout')); + }, this._exportTimeoutMillis); + // prevent downstream exporter calls from generating spans + api_1.context.with((0, core_1.suppressTracing)(api_1.context.active()), () => { + // Reset the finished spans buffer here because the next invocations of the _flush method + // could pass the same finished spans to the exporter if the buffer is cleared + // outside the execution of this callback. + let spans; + if (this._finishedSpans.length <= this._maxExportBatchSize) { + spans = this._finishedSpans; + this._finishedSpans = []; + } + else { + spans = this._finishedSpans.splice(0, this._maxExportBatchSize); + } + const doExport = () => this._exporter.export(spans, result => { + clearTimeout(timer); + if (result.code === core_1.ExportResultCode.SUCCESS) { + resolve(); + } + else { + reject(result.error ?? + new Error('BatchSpanProcessor: span export failed')); + } + }); + let pendingResources = null; + for (let i = 0, len = spans.length; i < len; i++) { + const span = spans[i]; + if (span.resource.asyncAttributesPending && + span.resource.waitForAsyncAttributes) { + pendingResources ??= []; + pendingResources.push(span.resource.waitForAsyncAttributes()); + } + } + // Avoid scheduling a promise to make the behavior more predictable and easier to test + if (pendingResources === null) { + doExport(); + } + else { + Promise.all(pendingResources).then(doExport, err => { + (0, core_1.globalErrorHandler)(err); + reject(err); + }); + } + }); + }); + } + _maybeStartTimer() { + if (this._isExporting) + return; + const flush = () => { + this._isExporting = true; + this._flushOneBatch() + .finally(() => { + this._isExporting = false; + if (this._finishedSpans.length > 0) { + this._clearTimer(); + this._maybeStartTimer(); + } + }) + .catch(e => { + this._isExporting = false; + (0, core_1.globalErrorHandler)(e); + }); + }; + // we only wait if the queue doesn't have enough elements yet + if (this._finishedSpans.length >= this._maxExportBatchSize) { + return flush(); + } + if (this._timer !== undefined) + return; + this._timer = setTimeout(() => flush(), this._scheduledDelayMillis); + // depending on runtime, this may be a 'number' or NodeJS.Timeout + if (typeof this._timer !== 'number') { + this._timer.unref(); + } + } + _clearTimer() { + if (this._timer !== undefined) { + clearTimeout(this._timer); + this._timer = undefined; + } + } +} +exports.BatchSpanProcessorBase = BatchSpanProcessorBase; +//# sourceMappingURL=BatchSpanProcessorBase.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/ConsoleSpanExporter.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/ConsoleSpanExporter.js new file mode 100644 index 00000000..7f22fd96 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/ConsoleSpanExporter.js @@ -0,0 +1,88 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ConsoleSpanExporter = void 0; +const core_1 = require("@opentelemetry/core"); +/** + * This is implementation of {@link SpanExporter} that prints spans to the + * console. This class can be used for diagnostic purposes. + * + * NOTE: This {@link SpanExporter} is intended for diagnostics use only, output rendered to the console may change at any time. + */ +/* eslint-disable no-console */ +class ConsoleSpanExporter { + /** + * Export spans. + * @param spans + * @param resultCallback + */ + export(spans, resultCallback) { + return this._sendSpans(spans, resultCallback); + } + /** + * Shutdown the exporter. + */ + shutdown() { + this._sendSpans([]); + return this.forceFlush(); + } + /** + * Exports any pending spans in exporter + */ + forceFlush() { + return Promise.resolve(); + } + /** + * converts span info into more readable format + * @param span + */ + _exportInfo(span) { + return { + resource: { + attributes: span.resource.attributes, + }, + instrumentationScope: span.instrumentationScope, + traceId: span.spanContext().traceId, + parentSpanContext: span.parentSpanContext, + traceState: span.spanContext().traceState?.serialize(), + name: span.name, + id: span.spanContext().spanId, + kind: span.kind, + timestamp: (0, core_1.hrTimeToMicroseconds)(span.startTime), + duration: (0, core_1.hrTimeToMicroseconds)(span.duration), + attributes: span.attributes, + status: span.status, + events: span.events, + links: span.links, + }; + } + /** + * Showing spans in console + * @param spans + * @param done + */ + _sendSpans(spans, done) { + for (const span of spans) { + console.dir(this._exportInfo(span), { depth: 3 }); + } + if (done) { + return done({ code: core_1.ExportResultCode.SUCCESS }); + } + } +} +exports.ConsoleSpanExporter = ConsoleSpanExporter; +//# sourceMappingURL=ConsoleSpanExporter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/InMemorySpanExporter.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/InMemorySpanExporter.js new file mode 100644 index 00000000..f8344647 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/InMemorySpanExporter.js @@ -0,0 +1,60 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InMemorySpanExporter = void 0; +const core_1 = require("@opentelemetry/core"); +/** + * This class can be used for testing purposes. It stores the exported spans + * in a list in memory that can be retrieved using the `getFinishedSpans()` + * method. + */ +class InMemorySpanExporter { + _finishedSpans = []; + /** + * Indicates if the exporter has been "shutdown." + * When false, exported spans will not be stored in-memory. + */ + _stopped = false; + export(spans, resultCallback) { + if (this._stopped) + return resultCallback({ + code: core_1.ExportResultCode.FAILED, + error: new Error('Exporter has been stopped'), + }); + this._finishedSpans.push(...spans); + setTimeout(() => resultCallback({ code: core_1.ExportResultCode.SUCCESS }), 0); + } + shutdown() { + this._stopped = true; + this._finishedSpans = []; + return this.forceFlush(); + } + /** + * Exports any pending spans in the exporter + */ + forceFlush() { + return Promise.resolve(); + } + reset() { + this._finishedSpans = []; + } + getFinishedSpans() { + return this._finishedSpans; + } +} +exports.InMemorySpanExporter = InMemorySpanExporter; +//# sourceMappingURL=InMemorySpanExporter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/NoopSpanProcessor.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/NoopSpanProcessor.js new file mode 100644 index 00000000..d0778657 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/NoopSpanProcessor.js @@ -0,0 +1,31 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NoopSpanProcessor = void 0; +/** No-op implementation of SpanProcessor */ +class NoopSpanProcessor { + onStart(_span, _context) { } + onEnd(_span) { } + shutdown() { + return Promise.resolve(); + } + forceFlush() { + return Promise.resolve(); + } +} +exports.NoopSpanProcessor = NoopSpanProcessor; +//# sourceMappingURL=NoopSpanProcessor.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/SimpleSpanProcessor.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/SimpleSpanProcessor.js new file mode 100644 index 00000000..312a3be4 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/SimpleSpanProcessor.js @@ -0,0 +1,76 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SimpleSpanProcessor = void 0; +const api_1 = require("@opentelemetry/api"); +const core_1 = require("@opentelemetry/core"); +/** + * An implementation of the {@link SpanProcessor} that converts the {@link Span} + * to {@link ReadableSpan} and passes it to the configured exporter. + * + * Only spans that are sampled are converted. + * + * NOTE: This {@link SpanProcessor} exports every ended span individually instead of batching spans together, which causes significant performance overhead with most exporters. For production use, please consider using the {@link BatchSpanProcessor} instead. + */ +class SimpleSpanProcessor { + _exporter; + _shutdownOnce; + _pendingExports; + constructor(_exporter) { + this._exporter = _exporter; + this._shutdownOnce = new core_1.BindOnceFuture(this._shutdown, this); + this._pendingExports = new Set(); + } + async forceFlush() { + await Promise.all(Array.from(this._pendingExports)); + if (this._exporter.forceFlush) { + await this._exporter.forceFlush(); + } + } + onStart(_span, _parentContext) { } + onEnd(span) { + if (this._shutdownOnce.isCalled) { + return; + } + if ((span.spanContext().traceFlags & api_1.TraceFlags.SAMPLED) === 0) { + return; + } + const pendingExport = this._doExport(span).catch(err => (0, core_1.globalErrorHandler)(err)); + // Enqueue this export to the pending list so it can be flushed by the user. + this._pendingExports.add(pendingExport); + void pendingExport.finally(() => this._pendingExports.delete(pendingExport)); + } + async _doExport(span) { + if (span.resource.asyncAttributesPending) { + // Ensure resource is fully resolved before exporting. + await span.resource.waitForAsyncAttributes?.(); + } + const result = await core_1.internal._export(this._exporter, [span]); + if (result.code !== core_1.ExportResultCode.SUCCESS) { + throw (result.error ?? + new Error(`SimpleSpanProcessor: span export failed (status ${result})`)); + } + } + shutdown() { + return this._shutdownOnce.call(); + } + _shutdown() { + return this._exporter.shutdown(); + } +} +exports.SimpleSpanProcessor = SimpleSpanProcessor; +//# sourceMappingURL=SimpleSpanProcessor.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/index.js new file mode 100644 index 00000000..632f563f --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/index.js @@ -0,0 +1,42 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SamplingDecision = exports.TraceIdRatioBasedSampler = exports.ParentBasedSampler = exports.AlwaysOnSampler = exports.AlwaysOffSampler = exports.NoopSpanProcessor = exports.SimpleSpanProcessor = exports.InMemorySpanExporter = exports.ConsoleSpanExporter = exports.RandomIdGenerator = exports.BatchSpanProcessor = exports.BasicTracerProvider = void 0; +var BasicTracerProvider_1 = require("./BasicTracerProvider"); +Object.defineProperty(exports, "BasicTracerProvider", { enumerable: true, get: function () { return BasicTracerProvider_1.BasicTracerProvider; } }); +var platform_1 = require("./platform"); +Object.defineProperty(exports, "BatchSpanProcessor", { enumerable: true, get: function () { return platform_1.BatchSpanProcessor; } }); +Object.defineProperty(exports, "RandomIdGenerator", { enumerable: true, get: function () { return platform_1.RandomIdGenerator; } }); +var ConsoleSpanExporter_1 = require("./export/ConsoleSpanExporter"); +Object.defineProperty(exports, "ConsoleSpanExporter", { enumerable: true, get: function () { return ConsoleSpanExporter_1.ConsoleSpanExporter; } }); +var InMemorySpanExporter_1 = require("./export/InMemorySpanExporter"); +Object.defineProperty(exports, "InMemorySpanExporter", { enumerable: true, get: function () { return InMemorySpanExporter_1.InMemorySpanExporter; } }); +var SimpleSpanProcessor_1 = require("./export/SimpleSpanProcessor"); +Object.defineProperty(exports, "SimpleSpanProcessor", { enumerable: true, get: function () { return SimpleSpanProcessor_1.SimpleSpanProcessor; } }); +var NoopSpanProcessor_1 = require("./export/NoopSpanProcessor"); +Object.defineProperty(exports, "NoopSpanProcessor", { enumerable: true, get: function () { return NoopSpanProcessor_1.NoopSpanProcessor; } }); +var AlwaysOffSampler_1 = require("./sampler/AlwaysOffSampler"); +Object.defineProperty(exports, "AlwaysOffSampler", { enumerable: true, get: function () { return AlwaysOffSampler_1.AlwaysOffSampler; } }); +var AlwaysOnSampler_1 = require("./sampler/AlwaysOnSampler"); +Object.defineProperty(exports, "AlwaysOnSampler", { enumerable: true, get: function () { return AlwaysOnSampler_1.AlwaysOnSampler; } }); +var ParentBasedSampler_1 = require("./sampler/ParentBasedSampler"); +Object.defineProperty(exports, "ParentBasedSampler", { enumerable: true, get: function () { return ParentBasedSampler_1.ParentBasedSampler; } }); +var TraceIdRatioBasedSampler_1 = require("./sampler/TraceIdRatioBasedSampler"); +Object.defineProperty(exports, "TraceIdRatioBasedSampler", { enumerable: true, get: function () { return TraceIdRatioBasedSampler_1.TraceIdRatioBasedSampler; } }); +var Sampler_1 = require("./Sampler"); +Object.defineProperty(exports, "SamplingDecision", { enumerable: true, get: function () { return Sampler_1.SamplingDecision; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/platform/index.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/platform/index.js new file mode 100644 index 00000000..7357cec3 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/platform/index.js @@ -0,0 +1,22 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RandomIdGenerator = exports.BatchSpanProcessor = void 0; +var node_1 = require("./node"); +Object.defineProperty(exports, "BatchSpanProcessor", { enumerable: true, get: function () { return node_1.BatchSpanProcessor; } }); +Object.defineProperty(exports, "RandomIdGenerator", { enumerable: true, get: function () { return node_1.RandomIdGenerator; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/RandomIdGenerator.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/RandomIdGenerator.js new file mode 100644 index 00000000..47621738 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/RandomIdGenerator.js @@ -0,0 +1,54 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RandomIdGenerator = void 0; +const SPAN_ID_BYTES = 8; +const TRACE_ID_BYTES = 16; +class RandomIdGenerator { + /** + * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex + * characters corresponding to 128 bits. + */ + generateTraceId = getIdGenerator(TRACE_ID_BYTES); + /** + * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex + * characters corresponding to 64 bits. + */ + generateSpanId = getIdGenerator(SPAN_ID_BYTES); +} +exports.RandomIdGenerator = RandomIdGenerator; +const SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES); +function getIdGenerator(bytes) { + return function generateId() { + for (let i = 0; i < bytes / 4; i++) { + // unsigned right shift drops decimal part of the number + // it is required because if a number between 2**32 and 2**32 - 1 is generated, an out of range error is thrown by writeUInt32BE + SHARED_BUFFER.writeUInt32BE((Math.random() * 2 ** 32) >>> 0, i * 4); + } + // If buffer is all 0, set the last byte to 1 to guarantee a valid w3c id is generated + for (let i = 0; i < bytes; i++) { + if (SHARED_BUFFER[i] > 0) { + break; + } + else if (i === bytes - 1) { + SHARED_BUFFER[bytes - 1] = 1; + } + } + return SHARED_BUFFER.toString('hex', 0, bytes); + }; +} +//# sourceMappingURL=RandomIdGenerator.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/export/BatchSpanProcessor.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/export/BatchSpanProcessor.js new file mode 100644 index 00000000..91e47b28 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/export/BatchSpanProcessor.js @@ -0,0 +1,24 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BatchSpanProcessor = void 0; +const BatchSpanProcessorBase_1 = require("../../../export/BatchSpanProcessorBase"); +class BatchSpanProcessor extends BatchSpanProcessorBase_1.BatchSpanProcessorBase { + onShutdown() { } +} +exports.BatchSpanProcessor = BatchSpanProcessor; +//# sourceMappingURL=BatchSpanProcessor.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/index.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/index.js new file mode 100644 index 00000000..ca80efd6 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/index.js @@ -0,0 +1,23 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RandomIdGenerator = exports.BatchSpanProcessor = void 0; +var BatchSpanProcessor_1 = require("./export/BatchSpanProcessor"); +Object.defineProperty(exports, "BatchSpanProcessor", { enumerable: true, get: function () { return BatchSpanProcessor_1.BatchSpanProcessor; } }); +var RandomIdGenerator_1 = require("./RandomIdGenerator"); +Object.defineProperty(exports, "RandomIdGenerator", { enumerable: true, get: function () { return RandomIdGenerator_1.RandomIdGenerator; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/AlwaysOffSampler.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/AlwaysOffSampler.js new file mode 100644 index 00000000..7341f108 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/AlwaysOffSampler.js @@ -0,0 +1,32 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AlwaysOffSampler = void 0; +const Sampler_1 = require("../Sampler"); +/** Sampler that samples no traces. */ +class AlwaysOffSampler { + shouldSample() { + return { + decision: Sampler_1.SamplingDecision.NOT_RECORD, + }; + } + toString() { + return 'AlwaysOffSampler'; + } +} +exports.AlwaysOffSampler = AlwaysOffSampler; +//# sourceMappingURL=AlwaysOffSampler.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/AlwaysOnSampler.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/AlwaysOnSampler.js new file mode 100644 index 00000000..223b7707 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/AlwaysOnSampler.js @@ -0,0 +1,32 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AlwaysOnSampler = void 0; +const Sampler_1 = require("../Sampler"); +/** Sampler that samples all traces. */ +class AlwaysOnSampler { + shouldSample() { + return { + decision: Sampler_1.SamplingDecision.RECORD_AND_SAMPLED, + }; + } + toString() { + return 'AlwaysOnSampler'; + } +} +exports.AlwaysOnSampler = AlwaysOnSampler; +//# sourceMappingURL=AlwaysOnSampler.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/ParentBasedSampler.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/ParentBasedSampler.js new file mode 100644 index 00000000..c77b4386 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/ParentBasedSampler.js @@ -0,0 +1,69 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ParentBasedSampler = void 0; +const api_1 = require("@opentelemetry/api"); +const core_1 = require("@opentelemetry/core"); +const AlwaysOffSampler_1 = require("./AlwaysOffSampler"); +const AlwaysOnSampler_1 = require("./AlwaysOnSampler"); +/** + * A composite sampler that either respects the parent span's sampling decision + * or delegates to `delegateSampler` for root spans. + */ +class ParentBasedSampler { + _root; + _remoteParentSampled; + _remoteParentNotSampled; + _localParentSampled; + _localParentNotSampled; + constructor(config) { + this._root = config.root; + if (!this._root) { + (0, core_1.globalErrorHandler)(new Error('ParentBasedSampler must have a root sampler configured')); + this._root = new AlwaysOnSampler_1.AlwaysOnSampler(); + } + this._remoteParentSampled = + config.remoteParentSampled ?? new AlwaysOnSampler_1.AlwaysOnSampler(); + this._remoteParentNotSampled = + config.remoteParentNotSampled ?? new AlwaysOffSampler_1.AlwaysOffSampler(); + this._localParentSampled = + config.localParentSampled ?? new AlwaysOnSampler_1.AlwaysOnSampler(); + this._localParentNotSampled = + config.localParentNotSampled ?? new AlwaysOffSampler_1.AlwaysOffSampler(); + } + shouldSample(context, traceId, spanName, spanKind, attributes, links) { + const parentContext = api_1.trace.getSpanContext(context); + if (!parentContext || !(0, api_1.isSpanContextValid)(parentContext)) { + return this._root.shouldSample(context, traceId, spanName, spanKind, attributes, links); + } + if (parentContext.isRemote) { + if (parentContext.traceFlags & api_1.TraceFlags.SAMPLED) { + return this._remoteParentSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links); + } + return this._remoteParentNotSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links); + } + if (parentContext.traceFlags & api_1.TraceFlags.SAMPLED) { + return this._localParentSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links); + } + return this._localParentNotSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links); + } + toString() { + return `ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`; + } +} +exports.ParentBasedSampler = ParentBasedSampler; +//# sourceMappingURL=ParentBasedSampler.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/TraceIdRatioBasedSampler.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/TraceIdRatioBasedSampler.js new file mode 100644 index 00000000..38a5b14e --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/TraceIdRatioBasedSampler.js @@ -0,0 +1,56 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TraceIdRatioBasedSampler = void 0; +const api_1 = require("@opentelemetry/api"); +const Sampler_1 = require("../Sampler"); +/** Sampler that samples a given fraction of traces based of trace id deterministically. */ +class TraceIdRatioBasedSampler { + _ratio; + _upperBound; + constructor(_ratio = 0) { + this._ratio = _ratio; + this._ratio = this._normalize(_ratio); + this._upperBound = Math.floor(this._ratio * 0xffffffff); + } + shouldSample(context, traceId) { + return { + decision: (0, api_1.isValidTraceId)(traceId) && this._accumulate(traceId) < this._upperBound + ? Sampler_1.SamplingDecision.RECORD_AND_SAMPLED + : Sampler_1.SamplingDecision.NOT_RECORD, + }; + } + toString() { + return `TraceIdRatioBased{${this._ratio}}`; + } + _normalize(ratio) { + if (typeof ratio !== 'number' || isNaN(ratio)) + return 0; + return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio; + } + _accumulate(traceId) { + let accumulation = 0; + for (let i = 0; i < traceId.length / 8; i++) { + const pos = i * 8; + const part = parseInt(traceId.slice(pos, pos + 8), 16); + accumulation = (accumulation ^ part) >>> 0; + } + return accumulation; + } +} +exports.TraceIdRatioBasedSampler = TraceIdRatioBasedSampler; +//# sourceMappingURL=TraceIdRatioBasedSampler.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/utility.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/utility.js new file mode 100644 index 00000000..bd49cca6 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/utility.js @@ -0,0 +1,66 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.reconfigureLimits = exports.mergeConfig = exports.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = exports.DEFAULT_ATTRIBUTE_COUNT_LIMIT = void 0; +const config_1 = require("./config"); +const core_1 = require("@opentelemetry/core"); +exports.DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128; +exports.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity; +/** + * Function to merge Default configuration (as specified in './config') with + * user provided configurations. + */ +function mergeConfig(userConfig) { + const perInstanceDefaults = { + sampler: (0, config_1.buildSamplerFromEnv)(), + }; + const DEFAULT_CONFIG = (0, config_1.loadDefaultConfig)(); + const target = Object.assign({}, DEFAULT_CONFIG, perInstanceDefaults, userConfig); + target.generalLimits = Object.assign({}, DEFAULT_CONFIG.generalLimits, userConfig.generalLimits || {}); + target.spanLimits = Object.assign({}, DEFAULT_CONFIG.spanLimits, userConfig.spanLimits || {}); + return target; +} +exports.mergeConfig = mergeConfig; +/** + * When general limits are provided and model specific limits are not, + * configures the model specific limits by using the values from the general ones. + * @param userConfig User provided tracer configuration + */ +function reconfigureLimits(userConfig) { + const spanLimits = Object.assign({}, userConfig.spanLimits); + /** + * Reassign span attribute count limit to use first non null value defined by user or use default value + */ + spanLimits.attributeCountLimit = + userConfig.spanLimits?.attributeCountLimit ?? + userConfig.generalLimits?.attributeCountLimit ?? + (0, core_1.getNumberFromEnv)('OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT') ?? + (0, core_1.getNumberFromEnv)('OTEL_ATTRIBUTE_COUNT_LIMIT') ?? + exports.DEFAULT_ATTRIBUTE_COUNT_LIMIT; + /** + * Reassign span attribute value length limit to use first non null value defined by user or use default value + */ + spanLimits.attributeValueLengthLimit = + userConfig.spanLimits?.attributeValueLengthLimit ?? + userConfig.generalLimits?.attributeValueLengthLimit ?? + (0, core_1.getNumberFromEnv)('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? + (0, core_1.getNumberFromEnv)('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? + exports.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT; + return Object.assign({}, userConfig, { spanLimits }); +} +exports.reconfigureLimits = reconfigureLimits; +//# sourceMappingURL=utility.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/index.js new file mode 100644 index 00000000..abfca434 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/index.js @@ -0,0 +1,43 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +/* eslint-disable no-restricted-syntax -- + * These re-exports are only of constants, only two-levels deep, and + * should not cause problems for tree-shakers. + */ +// Deprecated. These are kept around for compatibility purposes +__exportStar(require("./trace"), exports); +__exportStar(require("./resource"), exports); +// Use these instead +__exportStar(require("./stable_attributes"), exports); +__exportStar(require("./stable_metrics"), exports); +__exportStar(require("./stable_events"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/internal/utils.js b/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/internal/utils.js new file mode 100644 index 00000000..c5cc1c5f --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/internal/utils.js @@ -0,0 +1,38 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createConstMap = void 0; +/** + * Creates a const map from the given values + * @param values - An array of values to be used as keys and values in the map. + * @returns A populated version of the map with the values and keys derived from the values. + */ +/*#__NO_SIDE_EFFECTS__*/ +function createConstMap(values) { + // eslint-disable-next-line prefer-const, @typescript-eslint/no-explicit-any + let res = {}; + const len = values.length; + for (let lp = 0; lp < len; lp++) { + const val = values[lp]; + if (val) { + res[String(val).toUpperCase().replace(/[-.]/g, '_')] = val; + } + } + return res; +} +exports.createConstMap = createConstMap; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/resource/SemanticResourceAttributes.js b/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/resource/SemanticResourceAttributes.js new file mode 100644 index 00000000..dc0c8af2 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/resource/SemanticResourceAttributes.js @@ -0,0 +1,1266 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SEMRESATTRS_K8S_STATEFULSET_NAME = exports.SEMRESATTRS_K8S_STATEFULSET_UID = exports.SEMRESATTRS_K8S_DEPLOYMENT_NAME = exports.SEMRESATTRS_K8S_DEPLOYMENT_UID = exports.SEMRESATTRS_K8S_REPLICASET_NAME = exports.SEMRESATTRS_K8S_REPLICASET_UID = exports.SEMRESATTRS_K8S_CONTAINER_NAME = exports.SEMRESATTRS_K8S_POD_NAME = exports.SEMRESATTRS_K8S_POD_UID = exports.SEMRESATTRS_K8S_NAMESPACE_NAME = exports.SEMRESATTRS_K8S_NODE_UID = exports.SEMRESATTRS_K8S_NODE_NAME = exports.SEMRESATTRS_K8S_CLUSTER_NAME = exports.SEMRESATTRS_HOST_IMAGE_VERSION = exports.SEMRESATTRS_HOST_IMAGE_ID = exports.SEMRESATTRS_HOST_IMAGE_NAME = exports.SEMRESATTRS_HOST_ARCH = exports.SEMRESATTRS_HOST_TYPE = exports.SEMRESATTRS_HOST_NAME = exports.SEMRESATTRS_HOST_ID = exports.SEMRESATTRS_FAAS_MAX_MEMORY = exports.SEMRESATTRS_FAAS_INSTANCE = exports.SEMRESATTRS_FAAS_VERSION = exports.SEMRESATTRS_FAAS_ID = exports.SEMRESATTRS_FAAS_NAME = exports.SEMRESATTRS_DEVICE_MODEL_NAME = exports.SEMRESATTRS_DEVICE_MODEL_IDENTIFIER = exports.SEMRESATTRS_DEVICE_ID = exports.SEMRESATTRS_DEPLOYMENT_ENVIRONMENT = exports.SEMRESATTRS_CONTAINER_IMAGE_TAG = exports.SEMRESATTRS_CONTAINER_IMAGE_NAME = exports.SEMRESATTRS_CONTAINER_RUNTIME = exports.SEMRESATTRS_CONTAINER_ID = exports.SEMRESATTRS_CONTAINER_NAME = exports.SEMRESATTRS_AWS_LOG_STREAM_ARNS = exports.SEMRESATTRS_AWS_LOG_STREAM_NAMES = exports.SEMRESATTRS_AWS_LOG_GROUP_ARNS = exports.SEMRESATTRS_AWS_LOG_GROUP_NAMES = exports.SEMRESATTRS_AWS_EKS_CLUSTER_ARN = exports.SEMRESATTRS_AWS_ECS_TASK_REVISION = exports.SEMRESATTRS_AWS_ECS_TASK_FAMILY = exports.SEMRESATTRS_AWS_ECS_TASK_ARN = exports.SEMRESATTRS_AWS_ECS_LAUNCHTYPE = exports.SEMRESATTRS_AWS_ECS_CLUSTER_ARN = exports.SEMRESATTRS_AWS_ECS_CONTAINER_ARN = exports.SEMRESATTRS_CLOUD_PLATFORM = exports.SEMRESATTRS_CLOUD_AVAILABILITY_ZONE = exports.SEMRESATTRS_CLOUD_REGION = exports.SEMRESATTRS_CLOUD_ACCOUNT_ID = exports.SEMRESATTRS_CLOUD_PROVIDER = void 0; +exports.CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = exports.CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = exports.CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = exports.CLOUDPLATFORMVALUES_AZURE_AKS = exports.CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES = exports.CLOUDPLATFORMVALUES_AZURE_VM = exports.CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = exports.CLOUDPLATFORMVALUES_AWS_LAMBDA = exports.CLOUDPLATFORMVALUES_AWS_EKS = exports.CLOUDPLATFORMVALUES_AWS_ECS = exports.CLOUDPLATFORMVALUES_AWS_EC2 = exports.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = exports.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = exports.CloudProviderValues = exports.CLOUDPROVIDERVALUES_GCP = exports.CLOUDPROVIDERVALUES_AZURE = exports.CLOUDPROVIDERVALUES_AWS = exports.CLOUDPROVIDERVALUES_ALIBABA_CLOUD = exports.SemanticResourceAttributes = exports.SEMRESATTRS_WEBENGINE_DESCRIPTION = exports.SEMRESATTRS_WEBENGINE_VERSION = exports.SEMRESATTRS_WEBENGINE_NAME = exports.SEMRESATTRS_TELEMETRY_AUTO_VERSION = exports.SEMRESATTRS_TELEMETRY_SDK_VERSION = exports.SEMRESATTRS_TELEMETRY_SDK_LANGUAGE = exports.SEMRESATTRS_TELEMETRY_SDK_NAME = exports.SEMRESATTRS_SERVICE_VERSION = exports.SEMRESATTRS_SERVICE_INSTANCE_ID = exports.SEMRESATTRS_SERVICE_NAMESPACE = exports.SEMRESATTRS_SERVICE_NAME = exports.SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION = exports.SEMRESATTRS_PROCESS_RUNTIME_VERSION = exports.SEMRESATTRS_PROCESS_RUNTIME_NAME = exports.SEMRESATTRS_PROCESS_OWNER = exports.SEMRESATTRS_PROCESS_COMMAND_ARGS = exports.SEMRESATTRS_PROCESS_COMMAND_LINE = exports.SEMRESATTRS_PROCESS_COMMAND = exports.SEMRESATTRS_PROCESS_EXECUTABLE_PATH = exports.SEMRESATTRS_PROCESS_EXECUTABLE_NAME = exports.SEMRESATTRS_PROCESS_PID = exports.SEMRESATTRS_OS_VERSION = exports.SEMRESATTRS_OS_NAME = exports.SEMRESATTRS_OS_DESCRIPTION = exports.SEMRESATTRS_OS_TYPE = exports.SEMRESATTRS_K8S_CRONJOB_NAME = exports.SEMRESATTRS_K8S_CRONJOB_UID = exports.SEMRESATTRS_K8S_JOB_NAME = exports.SEMRESATTRS_K8S_JOB_UID = exports.SEMRESATTRS_K8S_DAEMONSET_NAME = exports.SEMRESATTRS_K8S_DAEMONSET_UID = void 0; +exports.TelemetrySdkLanguageValues = exports.TELEMETRYSDKLANGUAGEVALUES_WEBJS = exports.TELEMETRYSDKLANGUAGEVALUES_RUBY = exports.TELEMETRYSDKLANGUAGEVALUES_PYTHON = exports.TELEMETRYSDKLANGUAGEVALUES_PHP = exports.TELEMETRYSDKLANGUAGEVALUES_NODEJS = exports.TELEMETRYSDKLANGUAGEVALUES_JAVA = exports.TELEMETRYSDKLANGUAGEVALUES_GO = exports.TELEMETRYSDKLANGUAGEVALUES_ERLANG = exports.TELEMETRYSDKLANGUAGEVALUES_DOTNET = exports.TELEMETRYSDKLANGUAGEVALUES_CPP = exports.OsTypeValues = exports.OSTYPEVALUES_Z_OS = exports.OSTYPEVALUES_SOLARIS = exports.OSTYPEVALUES_AIX = exports.OSTYPEVALUES_HPUX = exports.OSTYPEVALUES_DRAGONFLYBSD = exports.OSTYPEVALUES_OPENBSD = exports.OSTYPEVALUES_NETBSD = exports.OSTYPEVALUES_FREEBSD = exports.OSTYPEVALUES_DARWIN = exports.OSTYPEVALUES_LINUX = exports.OSTYPEVALUES_WINDOWS = exports.HostArchValues = exports.HOSTARCHVALUES_X86 = exports.HOSTARCHVALUES_PPC64 = exports.HOSTARCHVALUES_PPC32 = exports.HOSTARCHVALUES_IA64 = exports.HOSTARCHVALUES_ARM64 = exports.HOSTARCHVALUES_ARM32 = exports.HOSTARCHVALUES_AMD64 = exports.AwsEcsLaunchtypeValues = exports.AWSECSLAUNCHTYPEVALUES_FARGATE = exports.AWSECSLAUNCHTYPEVALUES_EC2 = exports.CloudPlatformValues = exports.CLOUDPLATFORMVALUES_GCP_APP_ENGINE = exports.CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = exports.CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = exports.CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = void 0; +const utils_1 = require("../internal/utils"); +//---------------------------------------------------------------------------------------------------------- +// DO NOT EDIT, this is an Auto-generated file from scripts/semconv/templates//templates/SemanticAttributes.ts.j2 +//---------------------------------------------------------------------------------------------------------- +//---------------------------------------------------------------------------------------------------------- +// Constant values for SemanticResourceAttributes +//---------------------------------------------------------------------------------------------------------- +// Temporary local constants to assign to the individual exports and the namespaced version +// Required to avoid the namespace exports using the unminifiable export names for some package types +const TMP_CLOUD_PROVIDER = 'cloud.provider'; +const TMP_CLOUD_ACCOUNT_ID = 'cloud.account.id'; +const TMP_CLOUD_REGION = 'cloud.region'; +const TMP_CLOUD_AVAILABILITY_ZONE = 'cloud.availability_zone'; +const TMP_CLOUD_PLATFORM = 'cloud.platform'; +const TMP_AWS_ECS_CONTAINER_ARN = 'aws.ecs.container.arn'; +const TMP_AWS_ECS_CLUSTER_ARN = 'aws.ecs.cluster.arn'; +const TMP_AWS_ECS_LAUNCHTYPE = 'aws.ecs.launchtype'; +const TMP_AWS_ECS_TASK_ARN = 'aws.ecs.task.arn'; +const TMP_AWS_ECS_TASK_FAMILY = 'aws.ecs.task.family'; +const TMP_AWS_ECS_TASK_REVISION = 'aws.ecs.task.revision'; +const TMP_AWS_EKS_CLUSTER_ARN = 'aws.eks.cluster.arn'; +const TMP_AWS_LOG_GROUP_NAMES = 'aws.log.group.names'; +const TMP_AWS_LOG_GROUP_ARNS = 'aws.log.group.arns'; +const TMP_AWS_LOG_STREAM_NAMES = 'aws.log.stream.names'; +const TMP_AWS_LOG_STREAM_ARNS = 'aws.log.stream.arns'; +const TMP_CONTAINER_NAME = 'container.name'; +const TMP_CONTAINER_ID = 'container.id'; +const TMP_CONTAINER_RUNTIME = 'container.runtime'; +const TMP_CONTAINER_IMAGE_NAME = 'container.image.name'; +const TMP_CONTAINER_IMAGE_TAG = 'container.image.tag'; +const TMP_DEPLOYMENT_ENVIRONMENT = 'deployment.environment'; +const TMP_DEVICE_ID = 'device.id'; +const TMP_DEVICE_MODEL_IDENTIFIER = 'device.model.identifier'; +const TMP_DEVICE_MODEL_NAME = 'device.model.name'; +const TMP_FAAS_NAME = 'faas.name'; +const TMP_FAAS_ID = 'faas.id'; +const TMP_FAAS_VERSION = 'faas.version'; +const TMP_FAAS_INSTANCE = 'faas.instance'; +const TMP_FAAS_MAX_MEMORY = 'faas.max_memory'; +const TMP_HOST_ID = 'host.id'; +const TMP_HOST_NAME = 'host.name'; +const TMP_HOST_TYPE = 'host.type'; +const TMP_HOST_ARCH = 'host.arch'; +const TMP_HOST_IMAGE_NAME = 'host.image.name'; +const TMP_HOST_IMAGE_ID = 'host.image.id'; +const TMP_HOST_IMAGE_VERSION = 'host.image.version'; +const TMP_K8S_CLUSTER_NAME = 'k8s.cluster.name'; +const TMP_K8S_NODE_NAME = 'k8s.node.name'; +const TMP_K8S_NODE_UID = 'k8s.node.uid'; +const TMP_K8S_NAMESPACE_NAME = 'k8s.namespace.name'; +const TMP_K8S_POD_UID = 'k8s.pod.uid'; +const TMP_K8S_POD_NAME = 'k8s.pod.name'; +const TMP_K8S_CONTAINER_NAME = 'k8s.container.name'; +const TMP_K8S_REPLICASET_UID = 'k8s.replicaset.uid'; +const TMP_K8S_REPLICASET_NAME = 'k8s.replicaset.name'; +const TMP_K8S_DEPLOYMENT_UID = 'k8s.deployment.uid'; +const TMP_K8S_DEPLOYMENT_NAME = 'k8s.deployment.name'; +const TMP_K8S_STATEFULSET_UID = 'k8s.statefulset.uid'; +const TMP_K8S_STATEFULSET_NAME = 'k8s.statefulset.name'; +const TMP_K8S_DAEMONSET_UID = 'k8s.daemonset.uid'; +const TMP_K8S_DAEMONSET_NAME = 'k8s.daemonset.name'; +const TMP_K8S_JOB_UID = 'k8s.job.uid'; +const TMP_K8S_JOB_NAME = 'k8s.job.name'; +const TMP_K8S_CRONJOB_UID = 'k8s.cronjob.uid'; +const TMP_K8S_CRONJOB_NAME = 'k8s.cronjob.name'; +const TMP_OS_TYPE = 'os.type'; +const TMP_OS_DESCRIPTION = 'os.description'; +const TMP_OS_NAME = 'os.name'; +const TMP_OS_VERSION = 'os.version'; +const TMP_PROCESS_PID = 'process.pid'; +const TMP_PROCESS_EXECUTABLE_NAME = 'process.executable.name'; +const TMP_PROCESS_EXECUTABLE_PATH = 'process.executable.path'; +const TMP_PROCESS_COMMAND = 'process.command'; +const TMP_PROCESS_COMMAND_LINE = 'process.command_line'; +const TMP_PROCESS_COMMAND_ARGS = 'process.command_args'; +const TMP_PROCESS_OWNER = 'process.owner'; +const TMP_PROCESS_RUNTIME_NAME = 'process.runtime.name'; +const TMP_PROCESS_RUNTIME_VERSION = 'process.runtime.version'; +const TMP_PROCESS_RUNTIME_DESCRIPTION = 'process.runtime.description'; +const TMP_SERVICE_NAME = 'service.name'; +const TMP_SERVICE_NAMESPACE = 'service.namespace'; +const TMP_SERVICE_INSTANCE_ID = 'service.instance.id'; +const TMP_SERVICE_VERSION = 'service.version'; +const TMP_TELEMETRY_SDK_NAME = 'telemetry.sdk.name'; +const TMP_TELEMETRY_SDK_LANGUAGE = 'telemetry.sdk.language'; +const TMP_TELEMETRY_SDK_VERSION = 'telemetry.sdk.version'; +const TMP_TELEMETRY_AUTO_VERSION = 'telemetry.auto.version'; +const TMP_WEBENGINE_NAME = 'webengine.name'; +const TMP_WEBENGINE_VERSION = 'webengine.version'; +const TMP_WEBENGINE_DESCRIPTION = 'webengine.description'; +/** + * Name of the cloud provider. + * + * @deprecated Use ATTR_CLOUD_PROVIDER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_CLOUD_PROVIDER = TMP_CLOUD_PROVIDER; +/** + * The cloud account ID the resource is assigned to. + * + * @deprecated Use ATTR_CLOUD_ACCOUNT_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_CLOUD_ACCOUNT_ID = TMP_CLOUD_ACCOUNT_ID; +/** + * The geographical region the resource is running. Refer to your provider's docs to see the available regions, for example [Alibaba Cloud regions](https://www.alibabacloud.com/help/doc-detail/40654.htm), [AWS regions](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/), [Azure regions](https://azure.microsoft.com/en-us/global-infrastructure/geographies/), or [Google Cloud regions](https://cloud.google.com/about/locations). + * + * @deprecated Use ATTR_CLOUD_REGION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_CLOUD_REGION = TMP_CLOUD_REGION; +/** + * Cloud regions often have multiple, isolated locations known as zones to increase availability. Availability zone represents the zone where the resource is running. + * + * Note: Availability zones are called "zones" on Alibaba Cloud and Google Cloud. + * + * @deprecated Use ATTR_CLOUD_AVAILABILITY_ZONE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_CLOUD_AVAILABILITY_ZONE = TMP_CLOUD_AVAILABILITY_ZONE; +/** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use ATTR_CLOUD_PLATFORM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_CLOUD_PLATFORM = TMP_CLOUD_PLATFORM; +/** + * The Amazon Resource Name (ARN) of an [ECS container instance](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_instances.html). + * + * @deprecated Use ATTR_AWS_ECS_CONTAINER_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_AWS_ECS_CONTAINER_ARN = TMP_AWS_ECS_CONTAINER_ARN; +/** + * The ARN of an [ECS cluster](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/clusters.html). + * + * @deprecated Use ATTR_AWS_ECS_CLUSTER_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_AWS_ECS_CLUSTER_ARN = TMP_AWS_ECS_CLUSTER_ARN; +/** + * The [launch type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) for an ECS task. + * + * @deprecated Use ATTR_AWS_ECS_LAUNCHTYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_AWS_ECS_LAUNCHTYPE = TMP_AWS_ECS_LAUNCHTYPE; +/** + * The ARN of an [ECS task definition](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html). + * + * @deprecated Use ATTR_AWS_ECS_TASK_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_AWS_ECS_TASK_ARN = TMP_AWS_ECS_TASK_ARN; +/** + * The task definition family this task definition is a member of. + * + * @deprecated Use ATTR_AWS_ECS_TASK_FAMILY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_AWS_ECS_TASK_FAMILY = TMP_AWS_ECS_TASK_FAMILY; +/** + * The revision for this task definition. + * + * @deprecated Use ATTR_AWS_ECS_TASK_REVISION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_AWS_ECS_TASK_REVISION = TMP_AWS_ECS_TASK_REVISION; +/** + * The ARN of an EKS cluster. + * + * @deprecated Use ATTR_AWS_EKS_CLUSTER_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_AWS_EKS_CLUSTER_ARN = TMP_AWS_EKS_CLUSTER_ARN; +/** + * The name(s) of the AWS log group(s) an application is writing to. + * + * Note: Multiple log groups must be supported for cases like multi-container applications, where a single application has sidecar containers, and each write to their own log group. + * + * @deprecated Use ATTR_AWS_LOG_GROUP_NAMES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_AWS_LOG_GROUP_NAMES = TMP_AWS_LOG_GROUP_NAMES; +/** + * The Amazon Resource Name(s) (ARN) of the AWS log group(s). + * + * Note: See the [log group ARN format documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-access-control-overview-cwl.html#CWL_ARN_Format). + * + * @deprecated Use ATTR_AWS_LOG_GROUP_ARNS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_AWS_LOG_GROUP_ARNS = TMP_AWS_LOG_GROUP_ARNS; +/** + * The name(s) of the AWS log stream(s) an application is writing to. + * + * @deprecated Use ATTR_AWS_LOG_STREAM_NAMES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_AWS_LOG_STREAM_NAMES = TMP_AWS_LOG_STREAM_NAMES; +/** + * The ARN(s) of the AWS log stream(s). + * + * Note: See the [log stream ARN format documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-access-control-overview-cwl.html#CWL_ARN_Format). One log group can contain several log streams, so these ARNs necessarily identify both a log group and a log stream. + * + * @deprecated Use ATTR_AWS_LOG_STREAM_ARNS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_AWS_LOG_STREAM_ARNS = TMP_AWS_LOG_STREAM_ARNS; +/** + * Container name. + * + * @deprecated Use ATTR_CONTAINER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_CONTAINER_NAME = TMP_CONTAINER_NAME; +/** + * Container ID. Usually a UUID, as for example used to [identify Docker containers](https://docs.docker.com/engine/reference/run/#container-identification). The UUID might be abbreviated. + * + * @deprecated Use ATTR_CONTAINER_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_CONTAINER_ID = TMP_CONTAINER_ID; +/** + * The container runtime managing this container. + * + * @deprecated Use ATTR_CONTAINER_RUNTIME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_CONTAINER_RUNTIME = TMP_CONTAINER_RUNTIME; +/** + * Name of the image the container was built on. + * + * @deprecated Use ATTR_CONTAINER_IMAGE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_CONTAINER_IMAGE_NAME = TMP_CONTAINER_IMAGE_NAME; +/** + * Container image tag. + * + * @deprecated Use ATTR_CONTAINER_IMAGE_TAGS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_CONTAINER_IMAGE_TAG = TMP_CONTAINER_IMAGE_TAG; +/** + * Name of the [deployment environment](https://en.wikipedia.org/wiki/Deployment_environment) (aka deployment tier). + * + * @deprecated Use ATTR_DEPLOYMENT_ENVIRONMENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_DEPLOYMENT_ENVIRONMENT = TMP_DEPLOYMENT_ENVIRONMENT; +/** + * A unique identifier representing the device. + * + * Note: The device identifier MUST only be defined using the values outlined below. This value is not an advertising identifier and MUST NOT be used as such. On iOS (Swift or Objective-C), this value MUST be equal to the [vendor identifier](https://developer.apple.com/documentation/uikit/uidevice/1620059-identifierforvendor). On Android (Java or Kotlin), this value MUST be equal to the Firebase Installation ID or a globally unique UUID which is persisted across sessions in your application. More information can be found [here](https://developer.android.com/training/articles/user-data-ids) on best practices and exact implementation details. Caution should be taken when storing personal data or anything which can identify a user. GDPR and data protection laws may apply, ensure you do your own due diligence. + * + * @deprecated Use ATTR_DEVICE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_DEVICE_ID = TMP_DEVICE_ID; +/** + * The model identifier for the device. + * + * Note: It's recommended this value represents a machine readable version of the model identifier rather than the market or consumer-friendly name of the device. + * + * @deprecated Use ATTR_DEVICE_MODEL_IDENTIFIER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_DEVICE_MODEL_IDENTIFIER = TMP_DEVICE_MODEL_IDENTIFIER; +/** + * The marketing name for the device model. + * + * Note: It's recommended this value represents a human readable version of the device model rather than a machine readable alternative. + * + * @deprecated Use ATTR_DEVICE_MODEL_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_DEVICE_MODEL_NAME = TMP_DEVICE_MODEL_NAME; +/** + * The name of the single function that this runtime instance executes. + * + * Note: This is the name of the function as configured/deployed on the FaaS platform and is usually different from the name of the callback function (which may be stored in the [`code.namespace`/`code.function`](../../trace/semantic_conventions/span-general.md#source-code-attributes) span attributes). + * + * @deprecated Use ATTR_FAAS_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_FAAS_NAME = TMP_FAAS_NAME; +/** +* The unique ID of the single function that this runtime instance executes. +* +* Note: Depending on the cloud provider, use: + +* **AWS Lambda:** The function [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html). +Take care not to use the "invoked ARN" directly but replace any +[alias suffix](https://docs.aws.amazon.com/lambda/latest/dg/configuration-aliases.html) with the resolved function version, as the same runtime instance may be invokable with multiple +different aliases. +* **GCP:** The [URI of the resource](https://cloud.google.com/iam/docs/full-resource-names) +* **Azure:** The [Fully Qualified Resource ID](https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id). + +On some providers, it may not be possible to determine the full ID at startup, +which is why this field cannot be made required. For example, on AWS the account ID +part of the ARN is not available without calling another AWS API +which may be deemed too slow for a short-running lambda function. +As an alternative, consider setting `faas.id` as a span attribute instead. +* +* @deprecated Use ATTR_CLOUD_RESOURCE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). +*/ +exports.SEMRESATTRS_FAAS_ID = TMP_FAAS_ID; +/** +* The immutable version of the function being executed. +* +* Note: Depending on the cloud provider and platform, use: + +* **AWS Lambda:** The [function version](https://docs.aws.amazon.com/lambda/latest/dg/configuration-versions.html) + (an integer represented as a decimal string). +* **Google Cloud Run:** The [revision](https://cloud.google.com/run/docs/managing/revisions) + (i.e., the function name plus the revision suffix). +* **Google Cloud Functions:** The value of the + [`K_REVISION` environment variable](https://cloud.google.com/functions/docs/env-var#runtime_environment_variables_set_automatically). +* **Azure Functions:** Not applicable. Do not set this attribute. +* +* @deprecated Use ATTR_FAAS_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). +*/ +exports.SEMRESATTRS_FAAS_VERSION = TMP_FAAS_VERSION; +/** + * The execution environment ID as a string, that will be potentially reused for other invocations to the same function/function version. + * + * Note: * **AWS Lambda:** Use the (full) log stream name. + * + * @deprecated Use ATTR_FAAS_INSTANCE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_FAAS_INSTANCE = TMP_FAAS_INSTANCE; +/** + * The amount of memory available to the serverless function in MiB. + * + * Note: It's recommended to set this attribute since e.g. too little memory can easily stop a Java AWS Lambda function from working correctly. On AWS Lambda, the environment variable `AWS_LAMBDA_FUNCTION_MEMORY_SIZE` provides this information. + * + * @deprecated Use ATTR_FAAS_MAX_MEMORY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_FAAS_MAX_MEMORY = TMP_FAAS_MAX_MEMORY; +/** + * Unique host ID. For Cloud, this must be the instance_id assigned by the cloud provider. + * + * @deprecated Use ATTR_HOST_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_HOST_ID = TMP_HOST_ID; +/** + * Name of the host. On Unix systems, it may contain what the hostname command returns, or the fully qualified hostname, or another name specified by the user. + * + * @deprecated Use ATTR_HOST_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_HOST_NAME = TMP_HOST_NAME; +/** + * Type of host. For Cloud, this must be the machine type. + * + * @deprecated Use ATTR_HOST_TYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_HOST_TYPE = TMP_HOST_TYPE; +/** + * The CPU architecture the host system is running on. + * + * @deprecated Use ATTR_HOST_ARCH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_HOST_ARCH = TMP_HOST_ARCH; +/** + * Name of the VM image or OS install the host was instantiated from. + * + * @deprecated Use ATTR_HOST_IMAGE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_HOST_IMAGE_NAME = TMP_HOST_IMAGE_NAME; +/** + * VM image ID. For Cloud, this value is from the provider. + * + * @deprecated Use ATTR_HOST_IMAGE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_HOST_IMAGE_ID = TMP_HOST_IMAGE_ID; +/** + * The version string of the VM image as defined in [Version Attributes](README.md#version-attributes). + * + * @deprecated Use ATTR_HOST_IMAGE_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_HOST_IMAGE_VERSION = TMP_HOST_IMAGE_VERSION; +/** + * The name of the cluster. + * + * @deprecated Use ATTR_K8S_CLUSTER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_K8S_CLUSTER_NAME = TMP_K8S_CLUSTER_NAME; +/** + * The name of the Node. + * + * @deprecated Use ATTR_K8S_NODE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_K8S_NODE_NAME = TMP_K8S_NODE_NAME; +/** + * The UID of the Node. + * + * @deprecated Use ATTR_K8S_NODE_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_K8S_NODE_UID = TMP_K8S_NODE_UID; +/** + * The name of the namespace that the pod is running in. + * + * @deprecated Use ATTR_K8S_NAMESPACE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_K8S_NAMESPACE_NAME = TMP_K8S_NAMESPACE_NAME; +/** + * The UID of the Pod. + * + * @deprecated Use ATTR_K8S_POD_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_K8S_POD_UID = TMP_K8S_POD_UID; +/** + * The name of the Pod. + * + * @deprecated Use ATTR_K8S_POD_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_K8S_POD_NAME = TMP_K8S_POD_NAME; +/** + * The name of the Container in a Pod template. + * + * @deprecated Use ATTR_K8S_CONTAINER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_K8S_CONTAINER_NAME = TMP_K8S_CONTAINER_NAME; +/** + * The UID of the ReplicaSet. + * + * @deprecated Use ATTR_K8S_REPLICASET_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_K8S_REPLICASET_UID = TMP_K8S_REPLICASET_UID; +/** + * The name of the ReplicaSet. + * + * @deprecated Use ATTR_K8S_REPLICASET_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_K8S_REPLICASET_NAME = TMP_K8S_REPLICASET_NAME; +/** + * The UID of the Deployment. + * + * @deprecated Use ATTR_K8S_DEPLOYMENT_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_K8S_DEPLOYMENT_UID = TMP_K8S_DEPLOYMENT_UID; +/** + * The name of the Deployment. + * + * @deprecated Use ATTR_K8S_DEPLOYMENT_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_K8S_DEPLOYMENT_NAME = TMP_K8S_DEPLOYMENT_NAME; +/** + * The UID of the StatefulSet. + * + * @deprecated Use ATTR_K8S_STATEFULSET_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_K8S_STATEFULSET_UID = TMP_K8S_STATEFULSET_UID; +/** + * The name of the StatefulSet. + * + * @deprecated Use ATTR_K8S_STATEFULSET_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_K8S_STATEFULSET_NAME = TMP_K8S_STATEFULSET_NAME; +/** + * The UID of the DaemonSet. + * + * @deprecated Use ATTR_K8S_DAEMONSET_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_K8S_DAEMONSET_UID = TMP_K8S_DAEMONSET_UID; +/** + * The name of the DaemonSet. + * + * @deprecated Use ATTR_K8S_DAEMONSET_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_K8S_DAEMONSET_NAME = TMP_K8S_DAEMONSET_NAME; +/** + * The UID of the Job. + * + * @deprecated Use ATTR_K8S_JOB_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_K8S_JOB_UID = TMP_K8S_JOB_UID; +/** + * The name of the Job. + * + * @deprecated Use ATTR_K8S_JOB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_K8S_JOB_NAME = TMP_K8S_JOB_NAME; +/** + * The UID of the CronJob. + * + * @deprecated Use ATTR_K8S_CRONJOB_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_K8S_CRONJOB_UID = TMP_K8S_CRONJOB_UID; +/** + * The name of the CronJob. + * + * @deprecated Use ATTR_K8S_CRONJOB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_K8S_CRONJOB_NAME = TMP_K8S_CRONJOB_NAME; +/** + * The operating system type. + * + * @deprecated Use ATTR_OS_TYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_OS_TYPE = TMP_OS_TYPE; +/** + * Human readable (not intended to be parsed) OS version information, like e.g. reported by `ver` or `lsb_release -a` commands. + * + * @deprecated Use ATTR_OS_DESCRIPTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_OS_DESCRIPTION = TMP_OS_DESCRIPTION; +/** + * Human readable operating system name. + * + * @deprecated Use ATTR_OS_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_OS_NAME = TMP_OS_NAME; +/** + * The version string of the operating system as defined in [Version Attributes](../../resource/semantic_conventions/README.md#version-attributes). + * + * @deprecated Use ATTR_OS_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_OS_VERSION = TMP_OS_VERSION; +/** + * Process identifier (PID). + * + * @deprecated Use ATTR_PROCESS_PID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_PROCESS_PID = TMP_PROCESS_PID; +/** + * The name of the process executable. On Linux based systems, can be set to the `Name` in `proc/[pid]/status`. On Windows, can be set to the base name of `GetProcessImageFileNameW`. + * + * @deprecated Use ATTR_PROCESS_EXECUTABLE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_PROCESS_EXECUTABLE_NAME = TMP_PROCESS_EXECUTABLE_NAME; +/** + * The full path to the process executable. On Linux based systems, can be set to the target of `proc/[pid]/exe`. On Windows, can be set to the result of `GetProcessImageFileNameW`. + * + * @deprecated Use ATTR_PROCESS_EXECUTABLE_PATH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_PROCESS_EXECUTABLE_PATH = TMP_PROCESS_EXECUTABLE_PATH; +/** + * The command used to launch the process (i.e. the command name). On Linux based systems, can be set to the zeroth string in `proc/[pid]/cmdline`. On Windows, can be set to the first parameter extracted from `GetCommandLineW`. + * + * @deprecated Use ATTR_PROCESS_COMMAND in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_PROCESS_COMMAND = TMP_PROCESS_COMMAND; +/** + * The full command used to launch the process as a single string representing the full command. On Windows, can be set to the result of `GetCommandLineW`. Do not set this if you have to assemble it just for monitoring; use `process.command_args` instead. + * + * @deprecated Use ATTR_PROCESS_COMMAND_LINE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_PROCESS_COMMAND_LINE = TMP_PROCESS_COMMAND_LINE; +/** + * All the command arguments (including the command/executable itself) as received by the process. On Linux-based systems (and some other Unixoid systems supporting procfs), can be set according to the list of null-delimited strings extracted from `proc/[pid]/cmdline`. For libc-based executables, this would be the full argv vector passed to `main`. + * + * @deprecated Use ATTR_PROCESS_COMMAND_ARGS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_PROCESS_COMMAND_ARGS = TMP_PROCESS_COMMAND_ARGS; +/** + * The username of the user that owns the process. + * + * @deprecated Use ATTR_PROCESS_OWNER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_PROCESS_OWNER = TMP_PROCESS_OWNER; +/** + * The name of the runtime of this process. For compiled native binaries, this SHOULD be the name of the compiler. + * + * @deprecated Use ATTR_PROCESS_RUNTIME_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_PROCESS_RUNTIME_NAME = TMP_PROCESS_RUNTIME_NAME; +/** + * The version of the runtime of this process, as returned by the runtime without modification. + * + * @deprecated Use ATTR_PROCESS_RUNTIME_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_PROCESS_RUNTIME_VERSION = TMP_PROCESS_RUNTIME_VERSION; +/** + * An additional description about the runtime of the process, for example a specific vendor customization of the runtime environment. + * + * @deprecated Use ATTR_PROCESS_RUNTIME_DESCRIPTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION = TMP_PROCESS_RUNTIME_DESCRIPTION; +/** + * Logical name of the service. + * + * Note: MUST be the same for all instances of horizontally scaled services. If the value was not specified, SDKs MUST fallback to `unknown_service:` concatenated with [`process.executable.name`](process.md#process), e.g. `unknown_service:bash`. If `process.executable.name` is not available, the value MUST be set to `unknown_service`. + * + * @deprecated Use ATTR_SERVICE_NAME. + */ +exports.SEMRESATTRS_SERVICE_NAME = TMP_SERVICE_NAME; +/** + * A namespace for `service.name`. + * + * Note: A string value having a meaning that helps to distinguish a group of services, for example the team name that owns a group of services. `service.name` is expected to be unique within the same namespace. If `service.namespace` is not specified in the Resource then `service.name` is expected to be unique for all services that have no explicit namespace defined (so the empty/unspecified namespace is simply one more valid namespace). Zero-length namespace string is assumed equal to unspecified namespace. + * + * @deprecated Use ATTR_SERVICE_NAMESPACE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_SERVICE_NAMESPACE = TMP_SERVICE_NAMESPACE; +/** + * The string ID of the service instance. + * + * Note: MUST be unique for each instance of the same `service.namespace,service.name` pair (in other words `service.namespace,service.name,service.instance.id` triplet MUST be globally unique). The ID helps to distinguish instances of the same service that exist at the same time (e.g. instances of a horizontally scaled service). It is preferable for the ID to be persistent and stay the same for the lifetime of the service instance, however it is acceptable that the ID is ephemeral and changes during important lifetime events for the service (e.g. service restarts). If the service has no inherent unique ID that can be used as the value of this attribute it is recommended to generate a random Version 1 or Version 4 RFC 4122 UUID (services aiming for reproducible UUIDs may also use Version 5, see RFC 4122 for more recommendations). + * + * @deprecated Use ATTR_SERVICE_INSTANCE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_SERVICE_INSTANCE_ID = TMP_SERVICE_INSTANCE_ID; +/** + * The version string of the service API or implementation. + * + * @deprecated Use ATTR_SERVICE_VERSION. + */ +exports.SEMRESATTRS_SERVICE_VERSION = TMP_SERVICE_VERSION; +/** + * The name of the telemetry SDK as defined above. + * + * @deprecated Use ATTR_TELEMETRY_SDK_NAME. + */ +exports.SEMRESATTRS_TELEMETRY_SDK_NAME = TMP_TELEMETRY_SDK_NAME; +/** + * The language of the telemetry SDK. + * + * @deprecated Use ATTR_TELEMETRY_SDK_LANGUAGE. + */ +exports.SEMRESATTRS_TELEMETRY_SDK_LANGUAGE = TMP_TELEMETRY_SDK_LANGUAGE; +/** + * The version string of the telemetry SDK. + * + * @deprecated Use ATTR_TELEMETRY_SDK_VERSION. + */ +exports.SEMRESATTRS_TELEMETRY_SDK_VERSION = TMP_TELEMETRY_SDK_VERSION; +/** + * The version string of the auto instrumentation agent, if used. + * + * @deprecated Use ATTR_TELEMETRY_DISTRO_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_TELEMETRY_AUTO_VERSION = TMP_TELEMETRY_AUTO_VERSION; +/** + * The name of the web engine. + * + * @deprecated Use ATTR_WEBENGINE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_WEBENGINE_NAME = TMP_WEBENGINE_NAME; +/** + * The version of the web engine. + * + * @deprecated Use ATTR_WEBENGINE_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_WEBENGINE_VERSION = TMP_WEBENGINE_VERSION; +/** + * Additional description of the web engine (e.g. detailed version and edition information). + * + * @deprecated Use ATTR_WEBENGINE_DESCRIPTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMRESATTRS_WEBENGINE_DESCRIPTION = TMP_WEBENGINE_DESCRIPTION; +/** + * Create exported Value Map for SemanticResourceAttributes values + * @deprecated Use the SEMRESATTRS_XXXXX constants rather than the SemanticResourceAttributes.XXXXX for bundle minification + */ +exports.SemanticResourceAttributes = +/*#__PURE__*/ (0, utils_1.createConstMap)([ + TMP_CLOUD_PROVIDER, + TMP_CLOUD_ACCOUNT_ID, + TMP_CLOUD_REGION, + TMP_CLOUD_AVAILABILITY_ZONE, + TMP_CLOUD_PLATFORM, + TMP_AWS_ECS_CONTAINER_ARN, + TMP_AWS_ECS_CLUSTER_ARN, + TMP_AWS_ECS_LAUNCHTYPE, + TMP_AWS_ECS_TASK_ARN, + TMP_AWS_ECS_TASK_FAMILY, + TMP_AWS_ECS_TASK_REVISION, + TMP_AWS_EKS_CLUSTER_ARN, + TMP_AWS_LOG_GROUP_NAMES, + TMP_AWS_LOG_GROUP_ARNS, + TMP_AWS_LOG_STREAM_NAMES, + TMP_AWS_LOG_STREAM_ARNS, + TMP_CONTAINER_NAME, + TMP_CONTAINER_ID, + TMP_CONTAINER_RUNTIME, + TMP_CONTAINER_IMAGE_NAME, + TMP_CONTAINER_IMAGE_TAG, + TMP_DEPLOYMENT_ENVIRONMENT, + TMP_DEVICE_ID, + TMP_DEVICE_MODEL_IDENTIFIER, + TMP_DEVICE_MODEL_NAME, + TMP_FAAS_NAME, + TMP_FAAS_ID, + TMP_FAAS_VERSION, + TMP_FAAS_INSTANCE, + TMP_FAAS_MAX_MEMORY, + TMP_HOST_ID, + TMP_HOST_NAME, + TMP_HOST_TYPE, + TMP_HOST_ARCH, + TMP_HOST_IMAGE_NAME, + TMP_HOST_IMAGE_ID, + TMP_HOST_IMAGE_VERSION, + TMP_K8S_CLUSTER_NAME, + TMP_K8S_NODE_NAME, + TMP_K8S_NODE_UID, + TMP_K8S_NAMESPACE_NAME, + TMP_K8S_POD_UID, + TMP_K8S_POD_NAME, + TMP_K8S_CONTAINER_NAME, + TMP_K8S_REPLICASET_UID, + TMP_K8S_REPLICASET_NAME, + TMP_K8S_DEPLOYMENT_UID, + TMP_K8S_DEPLOYMENT_NAME, + TMP_K8S_STATEFULSET_UID, + TMP_K8S_STATEFULSET_NAME, + TMP_K8S_DAEMONSET_UID, + TMP_K8S_DAEMONSET_NAME, + TMP_K8S_JOB_UID, + TMP_K8S_JOB_NAME, + TMP_K8S_CRONJOB_UID, + TMP_K8S_CRONJOB_NAME, + TMP_OS_TYPE, + TMP_OS_DESCRIPTION, + TMP_OS_NAME, + TMP_OS_VERSION, + TMP_PROCESS_PID, + TMP_PROCESS_EXECUTABLE_NAME, + TMP_PROCESS_EXECUTABLE_PATH, + TMP_PROCESS_COMMAND, + TMP_PROCESS_COMMAND_LINE, + TMP_PROCESS_COMMAND_ARGS, + TMP_PROCESS_OWNER, + TMP_PROCESS_RUNTIME_NAME, + TMP_PROCESS_RUNTIME_VERSION, + TMP_PROCESS_RUNTIME_DESCRIPTION, + TMP_SERVICE_NAME, + TMP_SERVICE_NAMESPACE, + TMP_SERVICE_INSTANCE_ID, + TMP_SERVICE_VERSION, + TMP_TELEMETRY_SDK_NAME, + TMP_TELEMETRY_SDK_LANGUAGE, + TMP_TELEMETRY_SDK_VERSION, + TMP_TELEMETRY_AUTO_VERSION, + TMP_WEBENGINE_NAME, + TMP_WEBENGINE_VERSION, + TMP_WEBENGINE_DESCRIPTION, +]); +/* ---------------------------------------------------------------------------------------------------------- + * Constant values for CloudProviderValues enum definition + * + * Name of the cloud provider. + * ---------------------------------------------------------------------------------------------------------- */ +// Temporary local constants to assign to the individual exports and the namespaced version +// Required to avoid the namespace exports using the unminifiable export names for some package types +const TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD = 'alibaba_cloud'; +const TMP_CLOUDPROVIDERVALUES_AWS = 'aws'; +const TMP_CLOUDPROVIDERVALUES_AZURE = 'azure'; +const TMP_CLOUDPROVIDERVALUES_GCP = 'gcp'; +/** + * Name of the cloud provider. + * + * @deprecated Use CLOUD_PROVIDER_VALUE_ALIBABA_CLOUD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.CLOUDPROVIDERVALUES_ALIBABA_CLOUD = TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD; +/** + * Name of the cloud provider. + * + * @deprecated Use CLOUD_PROVIDER_VALUE_AWS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.CLOUDPROVIDERVALUES_AWS = TMP_CLOUDPROVIDERVALUES_AWS; +/** + * Name of the cloud provider. + * + * @deprecated Use CLOUD_PROVIDER_VALUE_AZURE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.CLOUDPROVIDERVALUES_AZURE = TMP_CLOUDPROVIDERVALUES_AZURE; +/** + * Name of the cloud provider. + * + * @deprecated Use CLOUD_PROVIDER_VALUE_GCP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.CLOUDPROVIDERVALUES_GCP = TMP_CLOUDPROVIDERVALUES_GCP; +/** + * The constant map of values for CloudProviderValues. + * @deprecated Use the CLOUDPROVIDERVALUES_XXXXX constants rather than the CloudProviderValues.XXXXX for bundle minification. + */ +exports.CloudProviderValues = +/*#__PURE__*/ (0, utils_1.createConstMap)([ + TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD, + TMP_CLOUDPROVIDERVALUES_AWS, + TMP_CLOUDPROVIDERVALUES_AZURE, + TMP_CLOUDPROVIDERVALUES_GCP, +]); +/* ---------------------------------------------------------------------------------------------------------- + * Constant values for CloudPlatformValues enum definition + * + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * ---------------------------------------------------------------------------------------------------------- */ +// Temporary local constants to assign to the individual exports and the namespaced version +// Required to avoid the namespace exports using the unminifiable export names for some package types +const TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = 'alibaba_cloud_ecs'; +const TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = 'alibaba_cloud_fc'; +const TMP_CLOUDPLATFORMVALUES_AWS_EC2 = 'aws_ec2'; +const TMP_CLOUDPLATFORMVALUES_AWS_ECS = 'aws_ecs'; +const TMP_CLOUDPLATFORMVALUES_AWS_EKS = 'aws_eks'; +const TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA = 'aws_lambda'; +const TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = 'aws_elastic_beanstalk'; +const TMP_CLOUDPLATFORMVALUES_AZURE_VM = 'azure_vm'; +const TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES = 'azure_container_instances'; +const TMP_CLOUDPLATFORMVALUES_AZURE_AKS = 'azure_aks'; +const TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = 'azure_functions'; +const TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = 'azure_app_service'; +const TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = 'gcp_compute_engine'; +const TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = 'gcp_cloud_run'; +const TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = 'gcp_kubernetes_engine'; +const TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = 'gcp_cloud_functions'; +const TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE = 'gcp_app_engine'; +/** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use CLOUD_PLATFORM_VALUE_ALIBABA_CLOUD_ECS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS; +/** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use CLOUD_PLATFORM_VALUE_ALIBABA_CLOUD_FC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC; +/** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_EC2 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.CLOUDPLATFORMVALUES_AWS_EC2 = TMP_CLOUDPLATFORMVALUES_AWS_EC2; +/** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_ECS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.CLOUDPLATFORMVALUES_AWS_ECS = TMP_CLOUDPLATFORMVALUES_AWS_ECS; +/** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_EKS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.CLOUDPLATFORMVALUES_AWS_EKS = TMP_CLOUDPLATFORMVALUES_AWS_EKS; +/** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_LAMBDA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.CLOUDPLATFORMVALUES_AWS_LAMBDA = TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA; +/** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_ELASTIC_BEANSTALK in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK; +/** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_VM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.CLOUDPLATFORMVALUES_AZURE_VM = TMP_CLOUDPLATFORMVALUES_AZURE_VM; +/** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_CONTAINER_INSTANCES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES = TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES; +/** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_AKS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.CLOUDPLATFORMVALUES_AZURE_AKS = TMP_CLOUDPLATFORMVALUES_AZURE_AKS; +/** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_FUNCTIONS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS; +/** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_APP_SERVICE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE; +/** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_COMPUTE_ENGINE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE; +/** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_CLOUD_RUN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN; +/** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_KUBERNETES_ENGINE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE; +/** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_CLOUD_FUNCTIONS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS; +/** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_APP_ENGINE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.CLOUDPLATFORMVALUES_GCP_APP_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE; +/** + * The constant map of values for CloudPlatformValues. + * @deprecated Use the CLOUDPLATFORMVALUES_XXXXX constants rather than the CloudPlatformValues.XXXXX for bundle minification. + */ +exports.CloudPlatformValues = +/*#__PURE__*/ (0, utils_1.createConstMap)([ + TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS, + TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC, + TMP_CLOUDPLATFORMVALUES_AWS_EC2, + TMP_CLOUDPLATFORMVALUES_AWS_ECS, + TMP_CLOUDPLATFORMVALUES_AWS_EKS, + TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA, + TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK, + TMP_CLOUDPLATFORMVALUES_AZURE_VM, + TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES, + TMP_CLOUDPLATFORMVALUES_AZURE_AKS, + TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS, + TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE, + TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE, + TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN, + TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE, + TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS, + TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE, +]); +/* ---------------------------------------------------------------------------------------------------------- + * Constant values for AwsEcsLaunchtypeValues enum definition + * + * The [launch type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) for an ECS task. + * ---------------------------------------------------------------------------------------------------------- */ +// Temporary local constants to assign to the individual exports and the namespaced version +// Required to avoid the namespace exports using the unminifiable export names for some package types +const TMP_AWSECSLAUNCHTYPEVALUES_EC2 = 'ec2'; +const TMP_AWSECSLAUNCHTYPEVALUES_FARGATE = 'fargate'; +/** + * The [launch type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) for an ECS task. + * + * @deprecated Use AWS_ECS_LAUNCHTYPE_VALUE_EC2 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.AWSECSLAUNCHTYPEVALUES_EC2 = TMP_AWSECSLAUNCHTYPEVALUES_EC2; +/** + * The [launch type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) for an ECS task. + * + * @deprecated Use AWS_ECS_LAUNCHTYPE_VALUE_FARGATE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.AWSECSLAUNCHTYPEVALUES_FARGATE = TMP_AWSECSLAUNCHTYPEVALUES_FARGATE; +/** + * The constant map of values for AwsEcsLaunchtypeValues. + * @deprecated Use the AWSECSLAUNCHTYPEVALUES_XXXXX constants rather than the AwsEcsLaunchtypeValues.XXXXX for bundle minification. + */ +exports.AwsEcsLaunchtypeValues = +/*#__PURE__*/ (0, utils_1.createConstMap)([ + TMP_AWSECSLAUNCHTYPEVALUES_EC2, + TMP_AWSECSLAUNCHTYPEVALUES_FARGATE, +]); +/* ---------------------------------------------------------------------------------------------------------- + * Constant values for HostArchValues enum definition + * + * The CPU architecture the host system is running on. + * ---------------------------------------------------------------------------------------------------------- */ +// Temporary local constants to assign to the individual exports and the namespaced version +// Required to avoid the namespace exports using the unminifiable export names for some package types +const TMP_HOSTARCHVALUES_AMD64 = 'amd64'; +const TMP_HOSTARCHVALUES_ARM32 = 'arm32'; +const TMP_HOSTARCHVALUES_ARM64 = 'arm64'; +const TMP_HOSTARCHVALUES_IA64 = 'ia64'; +const TMP_HOSTARCHVALUES_PPC32 = 'ppc32'; +const TMP_HOSTARCHVALUES_PPC64 = 'ppc64'; +const TMP_HOSTARCHVALUES_X86 = 'x86'; +/** + * The CPU architecture the host system is running on. + * + * @deprecated Use HOST_ARCH_VALUE_AMD64 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.HOSTARCHVALUES_AMD64 = TMP_HOSTARCHVALUES_AMD64; +/** + * The CPU architecture the host system is running on. + * + * @deprecated Use HOST_ARCH_VALUE_ARM32 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.HOSTARCHVALUES_ARM32 = TMP_HOSTARCHVALUES_ARM32; +/** + * The CPU architecture the host system is running on. + * + * @deprecated Use HOST_ARCH_VALUE_ARM64 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.HOSTARCHVALUES_ARM64 = TMP_HOSTARCHVALUES_ARM64; +/** + * The CPU architecture the host system is running on. + * + * @deprecated Use HOST_ARCH_VALUE_IA64 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.HOSTARCHVALUES_IA64 = TMP_HOSTARCHVALUES_IA64; +/** + * The CPU architecture the host system is running on. + * + * @deprecated Use HOST_ARCH_VALUE_PPC32 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.HOSTARCHVALUES_PPC32 = TMP_HOSTARCHVALUES_PPC32; +/** + * The CPU architecture the host system is running on. + * + * @deprecated Use HOST_ARCH_VALUE_PPC64 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.HOSTARCHVALUES_PPC64 = TMP_HOSTARCHVALUES_PPC64; +/** + * The CPU architecture the host system is running on. + * + * @deprecated Use HOST_ARCH_VALUE_X86 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.HOSTARCHVALUES_X86 = TMP_HOSTARCHVALUES_X86; +/** + * The constant map of values for HostArchValues. + * @deprecated Use the HOSTARCHVALUES_XXXXX constants rather than the HostArchValues.XXXXX for bundle minification. + */ +exports.HostArchValues = +/*#__PURE__*/ (0, utils_1.createConstMap)([ + TMP_HOSTARCHVALUES_AMD64, + TMP_HOSTARCHVALUES_ARM32, + TMP_HOSTARCHVALUES_ARM64, + TMP_HOSTARCHVALUES_IA64, + TMP_HOSTARCHVALUES_PPC32, + TMP_HOSTARCHVALUES_PPC64, + TMP_HOSTARCHVALUES_X86, +]); +/* ---------------------------------------------------------------------------------------------------------- + * Constant values for OsTypeValues enum definition + * + * The operating system type. + * ---------------------------------------------------------------------------------------------------------- */ +// Temporary local constants to assign to the individual exports and the namespaced version +// Required to avoid the namespace exports using the unminifiable export names for some package types +const TMP_OSTYPEVALUES_WINDOWS = 'windows'; +const TMP_OSTYPEVALUES_LINUX = 'linux'; +const TMP_OSTYPEVALUES_DARWIN = 'darwin'; +const TMP_OSTYPEVALUES_FREEBSD = 'freebsd'; +const TMP_OSTYPEVALUES_NETBSD = 'netbsd'; +const TMP_OSTYPEVALUES_OPENBSD = 'openbsd'; +const TMP_OSTYPEVALUES_DRAGONFLYBSD = 'dragonflybsd'; +const TMP_OSTYPEVALUES_HPUX = 'hpux'; +const TMP_OSTYPEVALUES_AIX = 'aix'; +const TMP_OSTYPEVALUES_SOLARIS = 'solaris'; +const TMP_OSTYPEVALUES_Z_OS = 'z_os'; +/** + * The operating system type. + * + * @deprecated Use OS_TYPE_VALUE_WINDOWS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.OSTYPEVALUES_WINDOWS = TMP_OSTYPEVALUES_WINDOWS; +/** + * The operating system type. + * + * @deprecated Use OS_TYPE_VALUE_LINUX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.OSTYPEVALUES_LINUX = TMP_OSTYPEVALUES_LINUX; +/** + * The operating system type. + * + * @deprecated Use OS_TYPE_VALUE_DARWIN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.OSTYPEVALUES_DARWIN = TMP_OSTYPEVALUES_DARWIN; +/** + * The operating system type. + * + * @deprecated Use OS_TYPE_VALUE_FREEBSD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.OSTYPEVALUES_FREEBSD = TMP_OSTYPEVALUES_FREEBSD; +/** + * The operating system type. + * + * @deprecated Use OS_TYPE_VALUE_NETBSD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.OSTYPEVALUES_NETBSD = TMP_OSTYPEVALUES_NETBSD; +/** + * The operating system type. + * + * @deprecated Use OS_TYPE_VALUE_OPENBSD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.OSTYPEVALUES_OPENBSD = TMP_OSTYPEVALUES_OPENBSD; +/** + * The operating system type. + * + * @deprecated Use OS_TYPE_VALUE_DRAGONFLYBSD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.OSTYPEVALUES_DRAGONFLYBSD = TMP_OSTYPEVALUES_DRAGONFLYBSD; +/** + * The operating system type. + * + * @deprecated Use OS_TYPE_VALUE_HPUX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.OSTYPEVALUES_HPUX = TMP_OSTYPEVALUES_HPUX; +/** + * The operating system type. + * + * @deprecated Use OS_TYPE_VALUE_AIX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.OSTYPEVALUES_AIX = TMP_OSTYPEVALUES_AIX; +/** + * The operating system type. + * + * @deprecated Use OS_TYPE_VALUE_SOLARIS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.OSTYPEVALUES_SOLARIS = TMP_OSTYPEVALUES_SOLARIS; +/** + * The operating system type. + * + * @deprecated Use OS_TYPE_VALUE_Z_OS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.OSTYPEVALUES_Z_OS = TMP_OSTYPEVALUES_Z_OS; +/** + * The constant map of values for OsTypeValues. + * @deprecated Use the OSTYPEVALUES_XXXXX constants rather than the OsTypeValues.XXXXX for bundle minification. + */ +exports.OsTypeValues = +/*#__PURE__*/ (0, utils_1.createConstMap)([ + TMP_OSTYPEVALUES_WINDOWS, + TMP_OSTYPEVALUES_LINUX, + TMP_OSTYPEVALUES_DARWIN, + TMP_OSTYPEVALUES_FREEBSD, + TMP_OSTYPEVALUES_NETBSD, + TMP_OSTYPEVALUES_OPENBSD, + TMP_OSTYPEVALUES_DRAGONFLYBSD, + TMP_OSTYPEVALUES_HPUX, + TMP_OSTYPEVALUES_AIX, + TMP_OSTYPEVALUES_SOLARIS, + TMP_OSTYPEVALUES_Z_OS, +]); +/* ---------------------------------------------------------------------------------------------------------- + * Constant values for TelemetrySdkLanguageValues enum definition + * + * The language of the telemetry SDK. + * ---------------------------------------------------------------------------------------------------------- */ +// Temporary local constants to assign to the individual exports and the namespaced version +// Required to avoid the namespace exports using the unminifiable export names for some package types +const TMP_TELEMETRYSDKLANGUAGEVALUES_CPP = 'cpp'; +const TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET = 'dotnet'; +const TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG = 'erlang'; +const TMP_TELEMETRYSDKLANGUAGEVALUES_GO = 'go'; +const TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA = 'java'; +const TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS = 'nodejs'; +const TMP_TELEMETRYSDKLANGUAGEVALUES_PHP = 'php'; +const TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON = 'python'; +const TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY = 'ruby'; +const TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS = 'webjs'; +/** + * The language of the telemetry SDK. + * + * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_CPP. + */ +exports.TELEMETRYSDKLANGUAGEVALUES_CPP = TMP_TELEMETRYSDKLANGUAGEVALUES_CPP; +/** + * The language of the telemetry SDK. + * + * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET. + */ +exports.TELEMETRYSDKLANGUAGEVALUES_DOTNET = TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET; +/** + * The language of the telemetry SDK. + * + * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG. + */ +exports.TELEMETRYSDKLANGUAGEVALUES_ERLANG = TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG; +/** + * The language of the telemetry SDK. + * + * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_GO. + */ +exports.TELEMETRYSDKLANGUAGEVALUES_GO = TMP_TELEMETRYSDKLANGUAGEVALUES_GO; +/** + * The language of the telemetry SDK. + * + * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_JAVA. + */ +exports.TELEMETRYSDKLANGUAGEVALUES_JAVA = TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA; +/** + * The language of the telemetry SDK. + * + * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS. + */ +exports.TELEMETRYSDKLANGUAGEVALUES_NODEJS = TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS; +/** + * The language of the telemetry SDK. + * + * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_PHP. + */ +exports.TELEMETRYSDKLANGUAGEVALUES_PHP = TMP_TELEMETRYSDKLANGUAGEVALUES_PHP; +/** + * The language of the telemetry SDK. + * + * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON. + */ +exports.TELEMETRYSDKLANGUAGEVALUES_PYTHON = TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON; +/** + * The language of the telemetry SDK. + * + * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_RUBY. + */ +exports.TELEMETRYSDKLANGUAGEVALUES_RUBY = TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY; +/** + * The language of the telemetry SDK. + * + * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS. + */ +exports.TELEMETRYSDKLANGUAGEVALUES_WEBJS = TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS; +/** + * The constant map of values for TelemetrySdkLanguageValues. + * @deprecated Use the TELEMETRYSDKLANGUAGEVALUES_XXXXX constants rather than the TelemetrySdkLanguageValues.XXXXX for bundle minification. + */ +exports.TelemetrySdkLanguageValues = +/*#__PURE__*/ (0, utils_1.createConstMap)([ + TMP_TELEMETRYSDKLANGUAGEVALUES_CPP, + TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET, + TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG, + TMP_TELEMETRYSDKLANGUAGEVALUES_GO, + TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA, + TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS, + TMP_TELEMETRYSDKLANGUAGEVALUES_PHP, + TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON, + TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY, + TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS, +]); +//# sourceMappingURL=SemanticResourceAttributes.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/resource/index.js b/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/resource/index.js new file mode 100644 index 00000000..aa8ee5bd --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/resource/index.js @@ -0,0 +1,37 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +/* eslint-disable no-restricted-syntax -- + * These re-exports are only of constants, only one-level deep at this point, + * and should not cause problems for tree-shakers. + */ +__exportStar(require("./SemanticResourceAttributes"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/stable_attributes.js b/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/stable_attributes.js new file mode 100644 index 00000000..df1cc9a1 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/stable_attributes.js @@ -0,0 +1,1085 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ATTR_EXCEPTION_TYPE = exports.ATTR_EXCEPTION_STACKTRACE = exports.ATTR_EXCEPTION_MESSAGE = exports.ATTR_EXCEPTION_ESCAPED = exports.ERROR_TYPE_VALUE_OTHER = exports.ATTR_ERROR_TYPE = exports.DOTNET_GC_HEAP_GENERATION_VALUE_POH = exports.DOTNET_GC_HEAP_GENERATION_VALUE_LOH = exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN2 = exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN1 = exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN0 = exports.ATTR_DOTNET_GC_HEAP_GENERATION = exports.DB_SYSTEM_NAME_VALUE_POSTGRESQL = exports.DB_SYSTEM_NAME_VALUE_MYSQL = exports.DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER = exports.DB_SYSTEM_NAME_VALUE_MARIADB = exports.ATTR_DB_SYSTEM_NAME = exports.ATTR_DB_STORED_PROCEDURE_NAME = exports.ATTR_DB_RESPONSE_STATUS_CODE = exports.ATTR_DB_QUERY_TEXT = exports.ATTR_DB_QUERY_SUMMARY = exports.ATTR_DB_OPERATION_NAME = exports.ATTR_DB_OPERATION_BATCH_SIZE = exports.ATTR_DB_NAMESPACE = exports.ATTR_DB_COLLECTION_NAME = exports.ATTR_CODE_STACKTRACE = exports.ATTR_CODE_LINE_NUMBER = exports.ATTR_CODE_FUNCTION_NAME = exports.ATTR_CODE_FILE_PATH = exports.ATTR_CODE_COLUMN_NUMBER = exports.ATTR_CLIENT_PORT = exports.ATTR_CLIENT_ADDRESS = exports.ATTR_ASPNETCORE_USER_IS_AUTHENTICATED = exports.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS = exports.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE = exports.ATTR_ASPNETCORE_ROUTING_MATCH_STATUS = exports.ATTR_ASPNETCORE_ROUTING_IS_FALLBACK = exports.ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED = exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED = exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER = exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER = exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED = exports.ATTR_ASPNETCORE_RATE_LIMITING_RESULT = exports.ATTR_ASPNETCORE_RATE_LIMITING_POLICY = exports.ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE = exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED = exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED = exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED = exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED = exports.ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT = void 0; +exports.OTEL_STATUS_CODE_VALUE_ERROR = exports.ATTR_OTEL_STATUS_CODE = exports.ATTR_OTEL_SCOPE_VERSION = exports.ATTR_OTEL_SCOPE_NAME = exports.NETWORK_TYPE_VALUE_IPV6 = exports.NETWORK_TYPE_VALUE_IPV4 = exports.ATTR_NETWORK_TYPE = exports.NETWORK_TRANSPORT_VALUE_UNIX = exports.NETWORK_TRANSPORT_VALUE_UDP = exports.NETWORK_TRANSPORT_VALUE_TCP = exports.NETWORK_TRANSPORT_VALUE_QUIC = exports.NETWORK_TRANSPORT_VALUE_PIPE = exports.ATTR_NETWORK_TRANSPORT = exports.ATTR_NETWORK_PROTOCOL_VERSION = exports.ATTR_NETWORK_PROTOCOL_NAME = exports.ATTR_NETWORK_PEER_PORT = exports.ATTR_NETWORK_PEER_ADDRESS = exports.ATTR_NETWORK_LOCAL_PORT = exports.ATTR_NETWORK_LOCAL_ADDRESS = exports.JVM_THREAD_STATE_VALUE_WAITING = exports.JVM_THREAD_STATE_VALUE_TIMED_WAITING = exports.JVM_THREAD_STATE_VALUE_TERMINATED = exports.JVM_THREAD_STATE_VALUE_RUNNABLE = exports.JVM_THREAD_STATE_VALUE_NEW = exports.JVM_THREAD_STATE_VALUE_BLOCKED = exports.ATTR_JVM_THREAD_STATE = exports.ATTR_JVM_THREAD_DAEMON = exports.JVM_MEMORY_TYPE_VALUE_NON_HEAP = exports.JVM_MEMORY_TYPE_VALUE_HEAP = exports.ATTR_JVM_MEMORY_TYPE = exports.ATTR_JVM_MEMORY_POOL_NAME = exports.ATTR_JVM_GC_NAME = exports.ATTR_JVM_GC_ACTION = exports.ATTR_HTTP_ROUTE = exports.ATTR_HTTP_RESPONSE_STATUS_CODE = exports.ATTR_HTTP_RESPONSE_HEADER = exports.ATTR_HTTP_REQUEST_RESEND_COUNT = exports.ATTR_HTTP_REQUEST_METHOD_ORIGINAL = exports.HTTP_REQUEST_METHOD_VALUE_TRACE = exports.HTTP_REQUEST_METHOD_VALUE_PUT = exports.HTTP_REQUEST_METHOD_VALUE_POST = exports.HTTP_REQUEST_METHOD_VALUE_PATCH = exports.HTTP_REQUEST_METHOD_VALUE_OPTIONS = exports.HTTP_REQUEST_METHOD_VALUE_HEAD = exports.HTTP_REQUEST_METHOD_VALUE_GET = exports.HTTP_REQUEST_METHOD_VALUE_DELETE = exports.HTTP_REQUEST_METHOD_VALUE_CONNECT = exports.HTTP_REQUEST_METHOD_VALUE_OTHER = exports.ATTR_HTTP_REQUEST_METHOD = exports.ATTR_HTTP_REQUEST_HEADER = void 0; +exports.ATTR_USER_AGENT_ORIGINAL = exports.ATTR_URL_SCHEME = exports.ATTR_URL_QUERY = exports.ATTR_URL_PATH = exports.ATTR_URL_FULL = exports.ATTR_URL_FRAGMENT = exports.ATTR_TELEMETRY_SDK_VERSION = exports.ATTR_TELEMETRY_SDK_NAME = exports.TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS = exports.TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT = exports.TELEMETRY_SDK_LANGUAGE_VALUE_RUST = exports.TELEMETRY_SDK_LANGUAGE_VALUE_RUBY = exports.TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON = exports.TELEMETRY_SDK_LANGUAGE_VALUE_PHP = exports.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS = exports.TELEMETRY_SDK_LANGUAGE_VALUE_JAVA = exports.TELEMETRY_SDK_LANGUAGE_VALUE_GO = exports.TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG = exports.TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET = exports.TELEMETRY_SDK_LANGUAGE_VALUE_CPP = exports.ATTR_TELEMETRY_SDK_LANGUAGE = exports.SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS = exports.SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS = exports.SIGNALR_TRANSPORT_VALUE_LONG_POLLING = exports.ATTR_SIGNALR_TRANSPORT = exports.SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT = exports.SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE = exports.SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN = exports.ATTR_SIGNALR_CONNECTION_STATUS = exports.ATTR_SERVICE_VERSION = exports.ATTR_SERVICE_NAME = exports.ATTR_SERVER_PORT = exports.ATTR_SERVER_ADDRESS = exports.ATTR_OTEL_STATUS_DESCRIPTION = exports.OTEL_STATUS_CODE_VALUE_OK = void 0; +//---------------------------------------------------------------------------------------------------------- +// DO NOT EDIT, this is an Auto-generated file from scripts/semconv/templates/registry/stable/attributes.ts.j2 +//---------------------------------------------------------------------------------------------------------- +/** + * ASP.NET Core exception middleware handling result. + * + * @example handled + * @example unhandled + */ +exports.ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT = 'aspnetcore.diagnostics.exception.result'; +/** + * Enum value "aborted" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}. + * + * Exception handling didn't run because the request was aborted. + */ +exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED = "aborted"; +/** + * Enum value "handled" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}. + * + * Exception was handled by the exception handling middleware. + */ +exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED = "handled"; +/** + * Enum value "skipped" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}. + * + * Exception handling was skipped because the response had started. + */ +exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED = "skipped"; +/** + * Enum value "unhandled" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}. + * + * Exception was not handled by the exception handling middleware. + */ +exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED = "unhandled"; +/** + * Full type name of the [`IExceptionHandler`](https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.diagnostics.iexceptionhandler) implementation that handled the exception. + * + * @example Contoso.MyHandler + */ +exports.ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE = 'aspnetcore.diagnostics.handler.type'; +/** + * Rate limiting policy name. + * + * @example fixed + * @example sliding + * @example token + */ +exports.ATTR_ASPNETCORE_RATE_LIMITING_POLICY = 'aspnetcore.rate_limiting.policy'; +/** + * Rate-limiting result, shows whether the lease was acquired or contains a rejection reason + * + * @example acquired + * @example request_canceled + */ +exports.ATTR_ASPNETCORE_RATE_LIMITING_RESULT = 'aspnetcore.rate_limiting.result'; +/** + * Enum value "acquired" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}. + * + * Lease was acquired + */ +exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED = "acquired"; +/** + * Enum value "endpoint_limiter" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}. + * + * Lease request was rejected by the endpoint limiter + */ +exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER = "endpoint_limiter"; +/** + * Enum value "global_limiter" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}. + * + * Lease request was rejected by the global limiter + */ +exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER = "global_limiter"; +/** + * Enum value "request_canceled" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}. + * + * Lease request was canceled + */ +exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED = "request_canceled"; +/** + * Flag indicating if request was handled by the application pipeline. + * + * @example true + */ +exports.ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED = 'aspnetcore.request.is_unhandled'; +/** + * A value that indicates whether the matched route is a fallback route. + * + * @example true + */ +exports.ATTR_ASPNETCORE_ROUTING_IS_FALLBACK = 'aspnetcore.routing.is_fallback'; +/** + * Match result - success or failure + * + * @example success + * @example failure + */ +exports.ATTR_ASPNETCORE_ROUTING_MATCH_STATUS = 'aspnetcore.routing.match_status'; +/** + * Enum value "failure" for attribute {@link ATTR_ASPNETCORE_ROUTING_MATCH_STATUS}. + * + * Match failed + */ +exports.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE = "failure"; +/** + * Enum value "success" for attribute {@link ATTR_ASPNETCORE_ROUTING_MATCH_STATUS}. + * + * Match succeeded + */ +exports.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS = "success"; +/** + * A value that indicates whether the user is authenticated. + * + * @example true + */ +exports.ATTR_ASPNETCORE_USER_IS_AUTHENTICATED = 'aspnetcore.user.is_authenticated'; +/** + * Client address - domain name if available without reverse DNS lookup; otherwise, IP address or Unix domain socket name. + * + * @example client.example.com + * @example 10.1.2.80 + * @example /tmp/my.sock + * + * @note When observed from the server side, and when communicating through an intermediary, `client.address` **SHOULD** represent the client address behind any intermediaries, for example proxies, if it's available. + */ +exports.ATTR_CLIENT_ADDRESS = 'client.address'; +/** + * Client port number. + * + * @example 65123 + * + * @note When observed from the server side, and when communicating through an intermediary, `client.port` **SHOULD** represent the client port behind any intermediaries, for example proxies, if it's available. + */ +exports.ATTR_CLIENT_PORT = 'client.port'; +/** + * The column number in `code.file.path` best representing the operation. It **SHOULD** point within the code unit named in `code.function.name`. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Line'. This constraint is imposed to prevent redundancy and maintain data integrity. + * + * @example 16 + */ +exports.ATTR_CODE_COLUMN_NUMBER = 'code.column.number'; +/** + * The source code file name that identifies the code unit as uniquely as possible (preferably an absolute file path). This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Function'. This constraint is imposed to prevent redundancy and maintain data integrity. + * + * @example "/usr/local/MyApplication/content_root/app/index.php" + */ +exports.ATTR_CODE_FILE_PATH = 'code.file.path'; +/** + * The method or function fully-qualified name without arguments. The value should fit the natural representation of the language runtime, which is also likely the same used within `code.stacktrace` attribute value. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Function'. This constraint is imposed to prevent redundancy and maintain data integrity. + * + * @example com.example.MyHttpService.serveRequest + * @example GuzzleHttp\\Client::transfer + * @example fopen + * + * @note Values and format depends on each language runtime, thus it is impossible to provide an exhaustive list of examples. + * The values are usually the same (or prefixes of) the ones found in native stack trace representation stored in + * `code.stacktrace` without information on arguments. + * + * Examples: + * + * - Java method: `com.example.MyHttpService.serveRequest` + * - Java anonymous class method: `com.mycompany.Main$1.myMethod` + * - Java lambda method: `com.mycompany.Main$$Lambda/0x0000748ae4149c00.myMethod` + * - PHP function: `GuzzleHttp\Client::transfer` + * - Go function: `github.com/my/repo/pkg.foo.func5` + * - Elixir: `OpenTelemetry.Ctx.new` + * - Erlang: `opentelemetry_ctx:new` + * - Rust: `playground::my_module::my_cool_func` + * - C function: `fopen` + */ +exports.ATTR_CODE_FUNCTION_NAME = 'code.function.name'; +/** + * The line number in `code.file.path` best representing the operation. It **SHOULD** point within the code unit named in `code.function.name`. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Line'. This constraint is imposed to prevent redundancy and maintain data integrity. + * + * @example 42 + */ +exports.ATTR_CODE_LINE_NUMBER = 'code.line.number'; +/** + * A stacktrace as a string in the natural representation for the language runtime. The representation is identical to [`exception.stacktrace`](/docs/exceptions/exceptions-spans.md#stacktrace-representation). This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Location'. This constraint is imposed to prevent redundancy and maintain data integrity. + * + * @example "at com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\n at com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\n at com.example.GenerateTrace.main(GenerateTrace.java:5)\\n" + */ +exports.ATTR_CODE_STACKTRACE = 'code.stacktrace'; +/** + * The name of a collection (table, container) within the database. + * + * @example public.users + * @example customers + * + * @note It is **RECOMMENDED** to capture the value as provided by the application + * without attempting to do any case normalization. + * + * The collection name **SHOULD NOT** be extracted from `db.query.text`, + * when the database system supports query text with multiple collections + * in non-batch operations. + * + * For batch operations, if the individual operations are known to have the same + * collection name then that collection name **SHOULD** be used. + */ +exports.ATTR_DB_COLLECTION_NAME = 'db.collection.name'; +/** + * The name of the database, fully qualified within the server address and port. + * + * @example customers + * @example test.users + * + * @note If a database system has multiple namespace components, they **SHOULD** be concatenated from the most general to the most specific namespace component, using `|` as a separator between the components. Any missing components (and their associated separators) **SHOULD** be omitted. + * Semantic conventions for individual database systems **SHOULD** document what `db.namespace` means in the context of that system. + * It is **RECOMMENDED** to capture the value as provided by the application without attempting to do any case normalization. + */ +exports.ATTR_DB_NAMESPACE = 'db.namespace'; +/** + * The number of queries included in a batch operation. + * + * @example 2 + * @example 3 + * @example 4 + * + * @note Operations are only considered batches when they contain two or more operations, and so `db.operation.batch.size` **SHOULD** never be `1`. + */ +exports.ATTR_DB_OPERATION_BATCH_SIZE = 'db.operation.batch.size'; +/** + * The name of the operation or command being executed. + * + * @example findAndModify + * @example HMSET + * @example SELECT + * + * @note It is **RECOMMENDED** to capture the value as provided by the application + * without attempting to do any case normalization. + * + * The operation name **SHOULD NOT** be extracted from `db.query.text`, + * when the database system supports query text with multiple operations + * in non-batch operations. + * + * If spaces can occur in the operation name, multiple consecutive spaces + * **SHOULD** be normalized to a single space. + * + * For batch operations, if the individual operations are known to have the same operation name + * then that operation name **SHOULD** be used prepended by `BATCH `, + * otherwise `db.operation.name` **SHOULD** be `BATCH` or some other database + * system specific term if more applicable. + */ +exports.ATTR_DB_OPERATION_NAME = 'db.operation.name'; +/** + * Low cardinality summary of a database query. + * + * @example SELECT wuser_table + * @example INSERT shipping_details SELECT orders + * @example get user by id + * + * @note The query summary describes a class of database queries and is useful + * as a grouping key, especially when analyzing telemetry for database + * calls involving complex queries. + * + * Summary may be available to the instrumentation through + * instrumentation hooks or other means. If it is not available, instrumentations + * that support query parsing **SHOULD** generate a summary following + * [Generating query summary](/docs/database/database-spans.md#generating-a-summary-of-the-query) + * section. + */ +exports.ATTR_DB_QUERY_SUMMARY = 'db.query.summary'; +/** + * The database query being executed. + * + * @example SELECT * FROM wuser_table where username = ? + * @example SET mykey ? + * + * @note For sanitization see [Sanitization of `db.query.text`](/docs/database/database-spans.md#sanitization-of-dbquerytext). + * For batch operations, if the individual operations are known to have the same query text then that query text **SHOULD** be used, otherwise all of the individual query texts **SHOULD** be concatenated with separator `; ` or some other database system specific separator if more applicable. + * Parameterized query text **SHOULD NOT** be sanitized. Even though parameterized query text can potentially have sensitive data, by using a parameterized query the user is giving a strong signal that any sensitive data will be passed as parameter values, and the benefit to observability of capturing the static part of the query text by default outweighs the risk. + */ +exports.ATTR_DB_QUERY_TEXT = 'db.query.text'; +/** + * Database response status code. + * + * @example 102 + * @example ORA-17002 + * @example 08P01 + * @example 404 + * + * @note The status code returned by the database. Usually it represents an error code, but may also represent partial success, warning, or differentiate between various types of successful outcomes. + * Semantic conventions for individual database systems **SHOULD** document what `db.response.status_code` means in the context of that system. + */ +exports.ATTR_DB_RESPONSE_STATUS_CODE = 'db.response.status_code'; +/** + * The name of a stored procedure within the database. + * + * @example GetCustomer + * + * @note It is **RECOMMENDED** to capture the value as provided by the application + * without attempting to do any case normalization. + * + * For batch operations, if the individual operations are known to have the same + * stored procedure name then that stored procedure name **SHOULD** be used. + */ +exports.ATTR_DB_STORED_PROCEDURE_NAME = 'db.stored_procedure.name'; +/** + * The database management system (DBMS) product as identified by the client instrumentation. + * + * @note The actual DBMS may differ from the one identified by the client. For example, when using PostgreSQL client libraries to connect to a CockroachDB, the `db.system.name` is set to `postgresql` based on the instrumentation's best knowledge. + */ +exports.ATTR_DB_SYSTEM_NAME = 'db.system.name'; +/** + * Enum value "mariadb" for attribute {@link ATTR_DB_SYSTEM_NAME}. + * + * [MariaDB](https://mariadb.org/) + */ +exports.DB_SYSTEM_NAME_VALUE_MARIADB = "mariadb"; +/** + * Enum value "microsoft.sql_server" for attribute {@link ATTR_DB_SYSTEM_NAME}. + * + * [Microsoft SQL Server](https://www.microsoft.com/sql-server) + */ +exports.DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER = "microsoft.sql_server"; +/** + * Enum value "mysql" for attribute {@link ATTR_DB_SYSTEM_NAME}. + * + * [MySQL](https://www.mysql.com/) + */ +exports.DB_SYSTEM_NAME_VALUE_MYSQL = "mysql"; +/** + * Enum value "postgresql" for attribute {@link ATTR_DB_SYSTEM_NAME}. + * + * [PostgreSQL](https://www.postgresql.org/) + */ +exports.DB_SYSTEM_NAME_VALUE_POSTGRESQL = "postgresql"; +/** + * Name of the garbage collector managed heap generation. + * + * @example gen0 + * @example gen1 + * @example gen2 + */ +exports.ATTR_DOTNET_GC_HEAP_GENERATION = 'dotnet.gc.heap.generation'; +/** + * Enum value "gen0" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}. + * + * Generation 0 + */ +exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN0 = "gen0"; +/** + * Enum value "gen1" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}. + * + * Generation 1 + */ +exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN1 = "gen1"; +/** + * Enum value "gen2" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}. + * + * Generation 2 + */ +exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN2 = "gen2"; +/** + * Enum value "loh" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}. + * + * Large Object Heap + */ +exports.DOTNET_GC_HEAP_GENERATION_VALUE_LOH = "loh"; +/** + * Enum value "poh" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}. + * + * Pinned Object Heap + */ +exports.DOTNET_GC_HEAP_GENERATION_VALUE_POH = "poh"; +/** + * Describes a class of error the operation ended with. + * + * @example timeout + * @example java.net.UnknownHostException + * @example server_certificate_invalid + * @example 500 + * + * @note The `error.type` **SHOULD** be predictable, and **SHOULD** have low cardinality. + * + * When `error.type` is set to a type (e.g., an exception type), its + * canonical class name identifying the type within the artifact **SHOULD** be used. + * + * Instrumentations **SHOULD** document the list of errors they report. + * + * The cardinality of `error.type` within one instrumentation library **SHOULD** be low. + * Telemetry consumers that aggregate data from multiple instrumentation libraries and applications + * should be prepared for `error.type` to have high cardinality at query time when no + * additional filters are applied. + * + * If the operation has completed successfully, instrumentations **SHOULD NOT** set `error.type`. + * + * If a specific domain defines its own set of error identifiers (such as HTTP or gRPC status codes), + * it's **RECOMMENDED** to: + * + * - Use a domain-specific attribute + * - Set `error.type` to capture all errors, regardless of whether they are defined within the domain-specific set or not. + */ +exports.ATTR_ERROR_TYPE = 'error.type'; +/** + * Enum value "_OTHER" for attribute {@link ATTR_ERROR_TYPE}. + * + * A fallback error value to be used when the instrumentation doesn't define a custom value. + */ +exports.ERROR_TYPE_VALUE_OTHER = "_OTHER"; +/** + * Indicates that the exception is escaping the scope of the span. + * + * @deprecated It's no longer recommended to record exceptions that are handled and do not escape the scope of a span. + */ +exports.ATTR_EXCEPTION_ESCAPED = 'exception.escaped'; +/** + * The exception message. + * + * @example Division by zero + * @example Can't convert 'int' object to str implicitly + */ +exports.ATTR_EXCEPTION_MESSAGE = 'exception.message'; +/** + * A stacktrace as a string in the natural representation for the language runtime. The representation is to be determined and documented by each language SIG. + * + * @example "Exception in thread "main" java.lang.RuntimeException: Test exception\\n at com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\n at com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\n at com.example.GenerateTrace.main(GenerateTrace.java:5)\\n" + */ +exports.ATTR_EXCEPTION_STACKTRACE = 'exception.stacktrace'; +/** + * The type of the exception (its fully-qualified class name, if applicable). The dynamic type of the exception should be preferred over the static type in languages that support it. + * + * @example java.net.ConnectException + * @example OSError + */ +exports.ATTR_EXCEPTION_TYPE = 'exception.type'; +/** + * HTTP request headers, `` being the normalized HTTP Header name (lowercase), the value being the header values. + * + * @example ["application/json"] + * @example ["1.2.3.4", "1.2.3.5"] + * + * @note Instrumentations **SHOULD** require an explicit configuration of which headers are to be captured. + * Including all request headers can be a security risk - explicit configuration helps avoid leaking sensitive information. + * + * The `User-Agent` header is already captured in the `user_agent.original` attribute. + * Users **MAY** explicitly configure instrumentations to capture them even though it is not recommended. + * + * The attribute value **MUST** consist of either multiple header values as an array of strings + * or a single-item array containing a possibly comma-concatenated string, depending on the way + * the HTTP library provides access to headers. + * + * Examples: + * + * - A header `Content-Type: application/json` **SHOULD** be recorded as the `http.request.header.content-type` + * attribute with value `["application/json"]`. + * - A header `X-Forwarded-For: 1.2.3.4, 1.2.3.5` **SHOULD** be recorded as the `http.request.header.x-forwarded-for` + * attribute with value `["1.2.3.4", "1.2.3.5"]` or `["1.2.3.4, 1.2.3.5"]` depending on the HTTP library. + */ +const ATTR_HTTP_REQUEST_HEADER = (key) => `http.request.header.${key}`; +exports.ATTR_HTTP_REQUEST_HEADER = ATTR_HTTP_REQUEST_HEADER; +/** + * HTTP request method. + * + * @example GET + * @example POST + * @example HEAD + * + * @note HTTP request method value **SHOULD** be "known" to the instrumentation. + * By default, this convention defines "known" methods as the ones listed in [RFC9110](https://www.rfc-editor.org/rfc/rfc9110.html#name-methods) + * and the PATCH method defined in [RFC5789](https://www.rfc-editor.org/rfc/rfc5789.html). + * + * If the HTTP request method is not known to instrumentation, it **MUST** set the `http.request.method` attribute to `_OTHER`. + * + * If the HTTP instrumentation could end up converting valid HTTP request methods to `_OTHER`, then it **MUST** provide a way to override + * the list of known HTTP methods. If this override is done via environment variable, then the environment variable **MUST** be named + * OTEL_INSTRUMENTATION_HTTP_KNOWN_METHODS and support a comma-separated list of case-sensitive known HTTP methods + * (this list **MUST** be a full override of the default known method, it is not a list of known methods in addition to the defaults). + * + * HTTP method names are case-sensitive and `http.request.method` attribute value **MUST** match a known HTTP method name exactly. + * Instrumentations for specific web frameworks that consider HTTP methods to be case insensitive, **SHOULD** populate a canonical equivalent. + * Tracing instrumentations that do so, **MUST** also set `http.request.method_original` to the original value. + */ +exports.ATTR_HTTP_REQUEST_METHOD = 'http.request.method'; +/** + * Enum value "_OTHER" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. + * + * Any HTTP method that the instrumentation has no prior knowledge of. + */ +exports.HTTP_REQUEST_METHOD_VALUE_OTHER = "_OTHER"; +/** + * Enum value "CONNECT" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. + * + * CONNECT method. + */ +exports.HTTP_REQUEST_METHOD_VALUE_CONNECT = "CONNECT"; +/** + * Enum value "DELETE" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. + * + * DELETE method. + */ +exports.HTTP_REQUEST_METHOD_VALUE_DELETE = "DELETE"; +/** + * Enum value "GET" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. + * + * GET method. + */ +exports.HTTP_REQUEST_METHOD_VALUE_GET = "GET"; +/** + * Enum value "HEAD" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. + * + * HEAD method. + */ +exports.HTTP_REQUEST_METHOD_VALUE_HEAD = "HEAD"; +/** + * Enum value "OPTIONS" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. + * + * OPTIONS method. + */ +exports.HTTP_REQUEST_METHOD_VALUE_OPTIONS = "OPTIONS"; +/** + * Enum value "PATCH" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. + * + * PATCH method. + */ +exports.HTTP_REQUEST_METHOD_VALUE_PATCH = "PATCH"; +/** + * Enum value "POST" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. + * + * POST method. + */ +exports.HTTP_REQUEST_METHOD_VALUE_POST = "POST"; +/** + * Enum value "PUT" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. + * + * PUT method. + */ +exports.HTTP_REQUEST_METHOD_VALUE_PUT = "PUT"; +/** + * Enum value "TRACE" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. + * + * TRACE method. + */ +exports.HTTP_REQUEST_METHOD_VALUE_TRACE = "TRACE"; +/** + * Original HTTP method sent by the client in the request line. + * + * @example GeT + * @example ACL + * @example foo + */ +exports.ATTR_HTTP_REQUEST_METHOD_ORIGINAL = 'http.request.method_original'; +/** + * The ordinal number of request resending attempt (for any reason, including redirects). + * + * @example 3 + * + * @note The resend count **SHOULD** be updated each time an HTTP request gets resent by the client, regardless of what was the cause of the resending (e.g. redirection, authorization failure, 503 Server Unavailable, network issues, or any other). + */ +exports.ATTR_HTTP_REQUEST_RESEND_COUNT = 'http.request.resend_count'; +/** + * HTTP response headers, `` being the normalized HTTP Header name (lowercase), the value being the header values. + * + * @example ["application/json"] + * @example ["abc", "def"] + * + * @note Instrumentations **SHOULD** require an explicit configuration of which headers are to be captured. + * Including all response headers can be a security risk - explicit configuration helps avoid leaking sensitive information. + * + * Users **MAY** explicitly configure instrumentations to capture them even though it is not recommended. + * + * The attribute value **MUST** consist of either multiple header values as an array of strings + * or a single-item array containing a possibly comma-concatenated string, depending on the way + * the HTTP library provides access to headers. + * + * Examples: + * + * - A header `Content-Type: application/json` header **SHOULD** be recorded as the `http.request.response.content-type` + * attribute with value `["application/json"]`. + * - A header `My-custom-header: abc, def` header **SHOULD** be recorded as the `http.response.header.my-custom-header` + * attribute with value `["abc", "def"]` or `["abc, def"]` depending on the HTTP library. + */ +const ATTR_HTTP_RESPONSE_HEADER = (key) => `http.response.header.${key}`; +exports.ATTR_HTTP_RESPONSE_HEADER = ATTR_HTTP_RESPONSE_HEADER; +/** + * [HTTP response status code](https://tools.ietf.org/html/rfc7231#section-6). + * + * @example 200 + */ +exports.ATTR_HTTP_RESPONSE_STATUS_CODE = 'http.response.status_code'; +/** + * The matched route, that is, the path template in the format used by the respective server framework. + * + * @example /users/:userID? + * @example {controller}/{action}/{id?} + * + * @note **MUST NOT** be populated when this is not supported by the HTTP server framework as the route attribute should have low-cardinality and the URI path can NOT substitute it. + * **SHOULD** include the [application root](/docs/http/http-spans.md#http-server-definitions) if there is one. + */ +exports.ATTR_HTTP_ROUTE = 'http.route'; +/** + * Name of the garbage collector action. + * + * @example end of minor GC + * @example end of major GC + * + * @note Garbage collector action is generally obtained via [GarbageCollectionNotificationInfo#getGcAction()](https://docs.oracle.com/en/java/javase/11/docs/api/jdk.management/com/sun/management/GarbageCollectionNotificationInfo.html#getGcAction()). + */ +exports.ATTR_JVM_GC_ACTION = 'jvm.gc.action'; +/** + * Name of the garbage collector. + * + * @example G1 Young Generation + * @example G1 Old Generation + * + * @note Garbage collector name is generally obtained via [GarbageCollectionNotificationInfo#getGcName()](https://docs.oracle.com/en/java/javase/11/docs/api/jdk.management/com/sun/management/GarbageCollectionNotificationInfo.html#getGcName()). + */ +exports.ATTR_JVM_GC_NAME = 'jvm.gc.name'; +/** + * Name of the memory pool. + * + * @example G1 Old Gen + * @example G1 Eden space + * @example G1 Survivor Space + * + * @note Pool names are generally obtained via [MemoryPoolMXBean#getName()](https://docs.oracle.com/en/java/javase/11/docs/api/java.management/java/lang/management/MemoryPoolMXBean.html#getName()). + */ +exports.ATTR_JVM_MEMORY_POOL_NAME = 'jvm.memory.pool.name'; +/** + * The type of memory. + * + * @example heap + * @example non_heap + */ +exports.ATTR_JVM_MEMORY_TYPE = 'jvm.memory.type'; +/** + * Enum value "heap" for attribute {@link ATTR_JVM_MEMORY_TYPE}. + * + * Heap memory. + */ +exports.JVM_MEMORY_TYPE_VALUE_HEAP = "heap"; +/** + * Enum value "non_heap" for attribute {@link ATTR_JVM_MEMORY_TYPE}. + * + * Non-heap memory + */ +exports.JVM_MEMORY_TYPE_VALUE_NON_HEAP = "non_heap"; +/** + * Whether the thread is daemon or not. + */ +exports.ATTR_JVM_THREAD_DAEMON = 'jvm.thread.daemon'; +/** + * State of the thread. + * + * @example runnable + * @example blocked + */ +exports.ATTR_JVM_THREAD_STATE = 'jvm.thread.state'; +/** + * Enum value "blocked" for attribute {@link ATTR_JVM_THREAD_STATE}. + * + * A thread that is blocked waiting for a monitor lock is in this state. + */ +exports.JVM_THREAD_STATE_VALUE_BLOCKED = "blocked"; +/** + * Enum value "new" for attribute {@link ATTR_JVM_THREAD_STATE}. + * + * A thread that has not yet started is in this state. + */ +exports.JVM_THREAD_STATE_VALUE_NEW = "new"; +/** + * Enum value "runnable" for attribute {@link ATTR_JVM_THREAD_STATE}. + * + * A thread executing in the Java virtual machine is in this state. + */ +exports.JVM_THREAD_STATE_VALUE_RUNNABLE = "runnable"; +/** + * Enum value "terminated" for attribute {@link ATTR_JVM_THREAD_STATE}. + * + * A thread that has exited is in this state. + */ +exports.JVM_THREAD_STATE_VALUE_TERMINATED = "terminated"; +/** + * Enum value "timed_waiting" for attribute {@link ATTR_JVM_THREAD_STATE}. + * + * A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state. + */ +exports.JVM_THREAD_STATE_VALUE_TIMED_WAITING = "timed_waiting"; +/** + * Enum value "waiting" for attribute {@link ATTR_JVM_THREAD_STATE}. + * + * A thread that is waiting indefinitely for another thread to perform a particular action is in this state. + */ +exports.JVM_THREAD_STATE_VALUE_WAITING = "waiting"; +/** + * Local address of the network connection - IP address or Unix domain socket name. + * + * @example 10.1.2.80 + * @example /tmp/my.sock + */ +exports.ATTR_NETWORK_LOCAL_ADDRESS = 'network.local.address'; +/** + * Local port number of the network connection. + * + * @example 65123 + */ +exports.ATTR_NETWORK_LOCAL_PORT = 'network.local.port'; +/** + * Peer address of the network connection - IP address or Unix domain socket name. + * + * @example 10.1.2.80 + * @example /tmp/my.sock + */ +exports.ATTR_NETWORK_PEER_ADDRESS = 'network.peer.address'; +/** + * Peer port number of the network connection. + * + * @example 65123 + */ +exports.ATTR_NETWORK_PEER_PORT = 'network.peer.port'; +/** + * [OSI application layer](https://wikipedia.org/wiki/Application_layer) or non-OSI equivalent. + * + * @example amqp + * @example http + * @example mqtt + * + * @note The value **SHOULD** be normalized to lowercase. + */ +exports.ATTR_NETWORK_PROTOCOL_NAME = 'network.protocol.name'; +/** + * The actual version of the protocol used for network communication. + * + * @example 1.1 + * @example 2 + * + * @note If protocol version is subject to negotiation (for example using [ALPN](https://www.rfc-editor.org/rfc/rfc7301.html)), this attribute **SHOULD** be set to the negotiated version. If the actual protocol version is not known, this attribute **SHOULD NOT** be set. + */ +exports.ATTR_NETWORK_PROTOCOL_VERSION = 'network.protocol.version'; +/** + * [OSI transport layer](https://wikipedia.org/wiki/Transport_layer) or [inter-process communication method](https://wikipedia.org/wiki/Inter-process_communication). + * + * @example tcp + * @example udp + * + * @note The value **SHOULD** be normalized to lowercase. + * + * Consider always setting the transport when setting a port number, since + * a port number is ambiguous without knowing the transport. For example + * different processes could be listening on TCP port 12345 and UDP port 12345. + */ +exports.ATTR_NETWORK_TRANSPORT = 'network.transport'; +/** + * Enum value "pipe" for attribute {@link ATTR_NETWORK_TRANSPORT}. + * + * Named or anonymous pipe. + */ +exports.NETWORK_TRANSPORT_VALUE_PIPE = "pipe"; +/** + * Enum value "quic" for attribute {@link ATTR_NETWORK_TRANSPORT}. + * + * QUIC + */ +exports.NETWORK_TRANSPORT_VALUE_QUIC = "quic"; +/** + * Enum value "tcp" for attribute {@link ATTR_NETWORK_TRANSPORT}. + * + * TCP + */ +exports.NETWORK_TRANSPORT_VALUE_TCP = "tcp"; +/** + * Enum value "udp" for attribute {@link ATTR_NETWORK_TRANSPORT}. + * + * UDP + */ +exports.NETWORK_TRANSPORT_VALUE_UDP = "udp"; +/** + * Enum value "unix" for attribute {@link ATTR_NETWORK_TRANSPORT}. + * + * Unix domain socket + */ +exports.NETWORK_TRANSPORT_VALUE_UNIX = "unix"; +/** + * [OSI network layer](https://wikipedia.org/wiki/Network_layer) or non-OSI equivalent. + * + * @example ipv4 + * @example ipv6 + * + * @note The value **SHOULD** be normalized to lowercase. + */ +exports.ATTR_NETWORK_TYPE = 'network.type'; +/** + * Enum value "ipv4" for attribute {@link ATTR_NETWORK_TYPE}. + * + * IPv4 + */ +exports.NETWORK_TYPE_VALUE_IPV4 = "ipv4"; +/** + * Enum value "ipv6" for attribute {@link ATTR_NETWORK_TYPE}. + * + * IPv6 + */ +exports.NETWORK_TYPE_VALUE_IPV6 = "ipv6"; +/** + * The name of the instrumentation scope - (`InstrumentationScope.Name` in OTLP). + * + * @example io.opentelemetry.contrib.mongodb + */ +exports.ATTR_OTEL_SCOPE_NAME = 'otel.scope.name'; +/** + * The version of the instrumentation scope - (`InstrumentationScope.Version` in OTLP). + * + * @example 1.0.0 + */ +exports.ATTR_OTEL_SCOPE_VERSION = 'otel.scope.version'; +/** + * Name of the code, either "OK" or "ERROR". **MUST NOT** be set if the status code is UNSET. + */ +exports.ATTR_OTEL_STATUS_CODE = 'otel.status_code'; +/** + * Enum value "ERROR" for attribute {@link ATTR_OTEL_STATUS_CODE}. + * + * The operation contains an error. + */ +exports.OTEL_STATUS_CODE_VALUE_ERROR = "ERROR"; +/** + * Enum value "OK" for attribute {@link ATTR_OTEL_STATUS_CODE}. + * + * The operation has been validated by an Application developer or Operator to have completed successfully. + */ +exports.OTEL_STATUS_CODE_VALUE_OK = "OK"; +/** + * Description of the Status if it has a value, otherwise not set. + * + * @example resource not found + */ +exports.ATTR_OTEL_STATUS_DESCRIPTION = 'otel.status_description'; +/** + * Server domain name if available without reverse DNS lookup; otherwise, IP address or Unix domain socket name. + * + * @example example.com + * @example 10.1.2.80 + * @example /tmp/my.sock + * + * @note When observed from the client side, and when communicating through an intermediary, `server.address` **SHOULD** represent the server address behind any intermediaries, for example proxies, if it's available. + */ +exports.ATTR_SERVER_ADDRESS = 'server.address'; +/** + * Server port number. + * + * @example 80 + * @example 8080 + * @example 443 + * + * @note When observed from the client side, and when communicating through an intermediary, `server.port` **SHOULD** represent the server port behind any intermediaries, for example proxies, if it's available. + */ +exports.ATTR_SERVER_PORT = 'server.port'; +/** + * Logical name of the service. + * + * @example shoppingcart + * + * @note **MUST** be the same for all instances of horizontally scaled services. If the value was not specified, SDKs **MUST** fallback to `unknown_service:` concatenated with [`process.executable.name`](process.md), e.g. `unknown_service:bash`. If `process.executable.name` is not available, the value **MUST** be set to `unknown_service`. + */ +exports.ATTR_SERVICE_NAME = 'service.name'; +/** + * The version string of the service API or implementation. The format is not defined by these conventions. + * + * @example 2.0.0 + * @example a01dbef8a + */ +exports.ATTR_SERVICE_VERSION = 'service.version'; +/** + * SignalR HTTP connection closure status. + * + * @example app_shutdown + * @example timeout + */ +exports.ATTR_SIGNALR_CONNECTION_STATUS = 'signalr.connection.status'; +/** + * Enum value "app_shutdown" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}. + * + * The connection was closed because the app is shutting down. + */ +exports.SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN = "app_shutdown"; +/** + * Enum value "normal_closure" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}. + * + * The connection was closed normally. + */ +exports.SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE = "normal_closure"; +/** + * Enum value "timeout" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}. + * + * The connection was closed due to a timeout. + */ +exports.SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT = "timeout"; +/** + * [SignalR transport type](https://github.com/dotnet/aspnetcore/blob/main/src/SignalR/docs/specs/TransportProtocols.md) + * + * @example web_sockets + * @example long_polling + */ +exports.ATTR_SIGNALR_TRANSPORT = 'signalr.transport'; +/** + * Enum value "long_polling" for attribute {@link ATTR_SIGNALR_TRANSPORT}. + * + * LongPolling protocol + */ +exports.SIGNALR_TRANSPORT_VALUE_LONG_POLLING = "long_polling"; +/** + * Enum value "server_sent_events" for attribute {@link ATTR_SIGNALR_TRANSPORT}. + * + * ServerSentEvents protocol + */ +exports.SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS = "server_sent_events"; +/** + * Enum value "web_sockets" for attribute {@link ATTR_SIGNALR_TRANSPORT}. + * + * WebSockets protocol + */ +exports.SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS = "web_sockets"; +/** + * The language of the telemetry SDK. + */ +exports.ATTR_TELEMETRY_SDK_LANGUAGE = 'telemetry.sdk.language'; +/** + * Enum value "cpp" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. + */ +exports.TELEMETRY_SDK_LANGUAGE_VALUE_CPP = "cpp"; +/** + * Enum value "dotnet" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. + */ +exports.TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET = "dotnet"; +/** + * Enum value "erlang" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. + */ +exports.TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG = "erlang"; +/** + * Enum value "go" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. + */ +exports.TELEMETRY_SDK_LANGUAGE_VALUE_GO = "go"; +/** + * Enum value "java" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. + */ +exports.TELEMETRY_SDK_LANGUAGE_VALUE_JAVA = "java"; +/** + * Enum value "nodejs" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. + */ +exports.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS = "nodejs"; +/** + * Enum value "php" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. + */ +exports.TELEMETRY_SDK_LANGUAGE_VALUE_PHP = "php"; +/** + * Enum value "python" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. + */ +exports.TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON = "python"; +/** + * Enum value "ruby" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. + */ +exports.TELEMETRY_SDK_LANGUAGE_VALUE_RUBY = "ruby"; +/** + * Enum value "rust" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. + */ +exports.TELEMETRY_SDK_LANGUAGE_VALUE_RUST = "rust"; +/** + * Enum value "swift" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. + */ +exports.TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT = "swift"; +/** + * Enum value "webjs" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. + */ +exports.TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS = "webjs"; +/** + * The name of the telemetry SDK as defined above. + * + * @example opentelemetry + * + * @note The OpenTelemetry SDK **MUST** set the `telemetry.sdk.name` attribute to `opentelemetry`. + * If another SDK, like a fork or a vendor-provided implementation, is used, this SDK **MUST** set the + * `telemetry.sdk.name` attribute to the fully-qualified class or module name of this SDK's main entry point + * or another suitable identifier depending on the language. + * The identifier `opentelemetry` is reserved and **MUST NOT** be used in this case. + * All custom identifiers **SHOULD** be stable across different versions of an implementation. + */ +exports.ATTR_TELEMETRY_SDK_NAME = 'telemetry.sdk.name'; +/** + * The version string of the telemetry SDK. + * + * @example 1.2.3 + */ +exports.ATTR_TELEMETRY_SDK_VERSION = 'telemetry.sdk.version'; +/** + * The [URI fragment](https://www.rfc-editor.org/rfc/rfc3986#section-3.5) component + * + * @example SemConv + */ +exports.ATTR_URL_FRAGMENT = 'url.fragment'; +/** + * Absolute URL describing a network resource according to [RFC3986](https://www.rfc-editor.org/rfc/rfc3986) + * + * @example https://www.foo.bar/search?q=OpenTelemetry#SemConv + * @example //localhost + * + * @note For network calls, URL usually has `scheme://host[:port][path][?query][#fragment]` format, where the fragment + * is not transmitted over HTTP, but if it is known, it **SHOULD** be included nevertheless. + * + * `url.full` **MUST NOT** contain credentials passed via URL in form of `https://username:password@www.example.com/`. + * In such case username and password **SHOULD** be redacted and attribute's value **SHOULD** be `https://REDACTED:REDACTED@www.example.com/`. + * + * `url.full` **SHOULD** capture the absolute URL when it is available (or can be reconstructed). + * + * Sensitive content provided in `url.full` **SHOULD** be scrubbed when instrumentations can identify it. + * + * + * Query string values for the following keys **SHOULD** be redacted by default and replaced by the + * value `REDACTED`: + * + * - [`AWSAccessKeyId`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth) + * - [`Signature`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth) + * - [`sig`](https://learn.microsoft.com/azure/storage/common/storage-sas-overview#sas-token) + * - [`X-Goog-Signature`](https://cloud.google.com/storage/docs/access-control/signed-urls) + * + * This list is subject to change over time. + * + * When a query string value is redacted, the query string key **SHOULD** still be preserved, e.g. + * `https://www.example.com/path?color=blue&sig=REDACTED`. + */ +exports.ATTR_URL_FULL = 'url.full'; +/** + * The [URI path](https://www.rfc-editor.org/rfc/rfc3986#section-3.3) component + * + * @example /search + * + * @note Sensitive content provided in `url.path` **SHOULD** be scrubbed when instrumentations can identify it. + */ +exports.ATTR_URL_PATH = 'url.path'; +/** + * The [URI query](https://www.rfc-editor.org/rfc/rfc3986#section-3.4) component + * + * @example q=OpenTelemetry + * + * @note Sensitive content provided in `url.query` **SHOULD** be scrubbed when instrumentations can identify it. + * + * + * Query string values for the following keys **SHOULD** be redacted by default and replaced by the value `REDACTED`: + * + * - [`AWSAccessKeyId`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth) + * - [`Signature`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth) + * - [`sig`](https://learn.microsoft.com/azure/storage/common/storage-sas-overview#sas-token) + * - [`X-Goog-Signature`](https://cloud.google.com/storage/docs/access-control/signed-urls) + * + * This list is subject to change over time. + * + * When a query string value is redacted, the query string key **SHOULD** still be preserved, e.g. + * `q=OpenTelemetry&sig=REDACTED`. + */ +exports.ATTR_URL_QUERY = 'url.query'; +/** + * The [URI scheme](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) component identifying the used protocol. + * + * @example https + * @example ftp + * @example telnet + */ +exports.ATTR_URL_SCHEME = 'url.scheme'; +/** + * Value of the [HTTP User-Agent](https://www.rfc-editor.org/rfc/rfc9110.html#field.user-agent) header sent by the client. + * + * @example CERN-LineMode/2.15 libwww/2.17b3 + * @example Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Mobile/15E148 Safari/604.1 + * @example YourApp/1.0.0 grpc-java-okhttp/1.27.2 + */ +exports.ATTR_USER_AGENT_ORIGINAL = 'user_agent.original'; +//# sourceMappingURL=stable_attributes.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/stable_events.js b/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/stable_events.js new file mode 100644 index 00000000..23ddfd7a --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/stable_events.js @@ -0,0 +1,26 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EVENT_EXCEPTION = void 0; +//----------------------------------------------------------------------------------------------------------- +// DO NOT EDIT, this is an Auto-generated file from scripts/semconv/templates/registry/ts-stable/events.ts.j2 +//----------------------------------------------------------------------------------------------------------- +/** + * This event describes a single exception. + */ +exports.EVENT_EXCEPTION = 'exception'; +//# sourceMappingURL=stable_events.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/stable_metrics.js b/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/stable_metrics.js new file mode 100644 index 00000000..371fe857 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/stable_metrics.js @@ -0,0 +1,330 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS = exports.METRIC_KESTREL_UPGRADED_CONNECTIONS = exports.METRIC_KESTREL_TLS_HANDSHAKE_DURATION = exports.METRIC_KESTREL_REJECTED_CONNECTIONS = exports.METRIC_KESTREL_QUEUED_REQUESTS = exports.METRIC_KESTREL_QUEUED_CONNECTIONS = exports.METRIC_KESTREL_CONNECTION_DURATION = exports.METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES = exports.METRIC_KESTREL_ACTIVE_CONNECTIONS = exports.METRIC_JVM_THREAD_COUNT = exports.METRIC_JVM_MEMORY_USED_AFTER_LAST_GC = exports.METRIC_JVM_MEMORY_USED = exports.METRIC_JVM_MEMORY_LIMIT = exports.METRIC_JVM_MEMORY_COMMITTED = exports.METRIC_JVM_GC_DURATION = exports.METRIC_JVM_CPU_TIME = exports.METRIC_JVM_CPU_RECENT_UTILIZATION = exports.METRIC_JVM_CPU_COUNT = exports.METRIC_JVM_CLASS_UNLOADED = exports.METRIC_JVM_CLASS_LOADED = exports.METRIC_JVM_CLASS_COUNT = exports.METRIC_HTTP_SERVER_REQUEST_DURATION = exports.METRIC_HTTP_CLIENT_REQUEST_DURATION = exports.METRIC_DOTNET_TIMER_COUNT = exports.METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT = exports.METRIC_DOTNET_THREAD_POOL_THREAD_COUNT = exports.METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH = exports.METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET = exports.METRIC_DOTNET_PROCESS_CPU_TIME = exports.METRIC_DOTNET_PROCESS_CPU_COUNT = exports.METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS = exports.METRIC_DOTNET_JIT_COMPILED_METHODS = exports.METRIC_DOTNET_JIT_COMPILED_IL_SIZE = exports.METRIC_DOTNET_JIT_COMPILATION_TIME = exports.METRIC_DOTNET_GC_PAUSE_TIME = exports.METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE = exports.METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE = exports.METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE = exports.METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED = exports.METRIC_DOTNET_GC_COLLECTIONS = exports.METRIC_DOTNET_EXCEPTIONS = exports.METRIC_DOTNET_ASSEMBLY_COUNT = exports.METRIC_DB_CLIENT_OPERATION_DURATION = exports.METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS = exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS = exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION = exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE = exports.METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS = exports.METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES = exports.METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS = void 0; +exports.METRIC_SIGNALR_SERVER_CONNECTION_DURATION = void 0; +//---------------------------------------------------------------------------------------------------------- +// DO NOT EDIT, this is an Auto-generated file from scripts/semconv/templates/register/stable/metrics.ts.j2 +//---------------------------------------------------------------------------------------------------------- +/** + * Number of exceptions caught by exception handling middleware. + * + * @note Meter name: `Microsoft.AspNetCore.Diagnostics`; Added in: ASP.NET Core 8.0 + */ +exports.METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS = 'aspnetcore.diagnostics.exceptions'; +/** + * Number of requests that are currently active on the server that hold a rate limiting lease. + * + * @note Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0 + */ +exports.METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES = 'aspnetcore.rate_limiting.active_request_leases'; +/** + * Number of requests that are currently queued, waiting to acquire a rate limiting lease. + * + * @note Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0 + */ +exports.METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS = 'aspnetcore.rate_limiting.queued_requests'; +/** + * The time the request spent in a queue waiting to acquire a rate limiting lease. + * + * @note Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0 + */ +exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE = 'aspnetcore.rate_limiting.request.time_in_queue'; +/** + * The duration of rate limiting lease held by requests on the server. + * + * @note Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0 + */ +exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION = 'aspnetcore.rate_limiting.request_lease.duration'; +/** + * Number of requests that tried to acquire a rate limiting lease. + * + * @note Requests could be: + * + * - Rejected by global or endpoint rate limiting policies + * - Canceled while waiting for the lease. + * + * Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0 + */ +exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS = 'aspnetcore.rate_limiting.requests'; +/** + * Number of requests that were attempted to be matched to an endpoint. + * + * @note Meter name: `Microsoft.AspNetCore.Routing`; Added in: ASP.NET Core 8.0 + */ +exports.METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS = 'aspnetcore.routing.match_attempts'; +/** + * Duration of database client operations. + * + * @note Batch operations **SHOULD** be recorded as a single operation. + */ +exports.METRIC_DB_CLIENT_OPERATION_DURATION = 'db.client.operation.duration'; +/** + * The number of .NET assemblies that are currently loaded. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as calling [`AppDomain.CurrentDomain.GetAssemblies().Length`](https://learn.microsoft.com/dotnet/api/system.appdomain.getassemblies). + */ +exports.METRIC_DOTNET_ASSEMBLY_COUNT = 'dotnet.assembly.count'; +/** + * The number of exceptions that have been thrown in managed code. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as counting calls to [`AppDomain.CurrentDomain.FirstChanceException`](https://learn.microsoft.com/dotnet/api/system.appdomain.firstchanceexception). + */ +exports.METRIC_DOTNET_EXCEPTIONS = 'dotnet.exceptions'; +/** + * The number of garbage collections that have occurred since the process has started. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric uses the [`GC.CollectionCount(int generation)`](https://learn.microsoft.com/dotnet/api/system.gc.collectioncount) API to calculate exclusive collections per generation. + */ +exports.METRIC_DOTNET_GC_COLLECTIONS = 'dotnet.gc.collections'; +/** + * The *approximate* number of bytes allocated on the managed GC heap since the process has started. The returned value does not include any native allocations. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as calling [`GC.GetTotalAllocatedBytes()`](https://learn.microsoft.com/dotnet/api/system.gc.gettotalallocatedbytes). + */ +exports.METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED = 'dotnet.gc.heap.total_allocated'; +/** + * The heap fragmentation, as observed during the latest garbage collection. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as calling [`GC.GetGCMemoryInfo().GenerationInfo.FragmentationAfterBytes`](https://learn.microsoft.com/dotnet/api/system.gcgenerationinfo.fragmentationafterbytes). + */ +exports.METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE = 'dotnet.gc.last_collection.heap.fragmentation.size'; +/** + * The managed GC heap size (including fragmentation), as observed during the latest garbage collection. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as calling [`GC.GetGCMemoryInfo().GenerationInfo.SizeAfterBytes`](https://learn.microsoft.com/dotnet/api/system.gcgenerationinfo.sizeafterbytes). + */ +exports.METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE = 'dotnet.gc.last_collection.heap.size'; +/** + * The amount of committed virtual memory in use by the .NET GC, as observed during the latest garbage collection. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as calling [`GC.GetGCMemoryInfo().TotalCommittedBytes`](https://learn.microsoft.com/dotnet/api/system.gcmemoryinfo.totalcommittedbytes). Committed virtual memory may be larger than the heap size because it includes both memory for storing existing objects (the heap size) and some extra memory that is ready to handle newly allocated objects in the future. + */ +exports.METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE = 'dotnet.gc.last_collection.memory.committed_size'; +/** + * The total amount of time paused in GC since the process has started. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as calling [`GC.GetTotalPauseDuration()`](https://learn.microsoft.com/dotnet/api/system.gc.gettotalpauseduration). + */ +exports.METRIC_DOTNET_GC_PAUSE_TIME = 'dotnet.gc.pause.time'; +/** + * The amount of time the JIT compiler has spent compiling methods since the process has started. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as calling [`JitInfo.GetCompilationTime()`](https://learn.microsoft.com/dotnet/api/system.runtime.jitinfo.getcompilationtime). + */ +exports.METRIC_DOTNET_JIT_COMPILATION_TIME = 'dotnet.jit.compilation.time'; +/** + * Count of bytes of intermediate language that have been compiled since the process has started. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as calling [`JitInfo.GetCompiledILBytes()`](https://learn.microsoft.com/dotnet/api/system.runtime.jitinfo.getcompiledilbytes). + */ +exports.METRIC_DOTNET_JIT_COMPILED_IL_SIZE = 'dotnet.jit.compiled_il.size'; +/** + * The number of times the JIT compiler (re)compiled methods since the process has started. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as calling [`JitInfo.GetCompiledMethodCount()`](https://learn.microsoft.com/dotnet/api/system.runtime.jitinfo.getcompiledmethodcount). + */ +exports.METRIC_DOTNET_JIT_COMPILED_METHODS = 'dotnet.jit.compiled_methods'; +/** + * The number of times there was contention when trying to acquire a monitor lock since the process has started. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as calling [`Monitor.LockContentionCount`](https://learn.microsoft.com/dotnet/api/system.threading.monitor.lockcontentioncount). + */ +exports.METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS = 'dotnet.monitor.lock_contentions'; +/** + * The number of processors available to the process. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as accessing [`Environment.ProcessorCount`](https://learn.microsoft.com/dotnet/api/system.environment.processorcount). + */ +exports.METRIC_DOTNET_PROCESS_CPU_COUNT = 'dotnet.process.cpu.count'; +/** + * CPU time used by the process. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as accessing the corresponding processor time properties on [`System.Diagnostics.Process`](https://learn.microsoft.com/dotnet/api/system.diagnostics.process). + */ +exports.METRIC_DOTNET_PROCESS_CPU_TIME = 'dotnet.process.cpu.time'; +/** + * The number of bytes of physical memory mapped to the process context. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as calling [`Environment.WorkingSet`](https://learn.microsoft.com/dotnet/api/system.environment.workingset). + */ +exports.METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET = 'dotnet.process.memory.working_set'; +/** + * The number of work items that are currently queued to be processed by the thread pool. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as calling [`ThreadPool.PendingWorkItemCount`](https://learn.microsoft.com/dotnet/api/system.threading.threadpool.pendingworkitemcount). + */ +exports.METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH = 'dotnet.thread_pool.queue.length'; +/** + * The number of thread pool threads that currently exist. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as calling [`ThreadPool.ThreadCount`](https://learn.microsoft.com/dotnet/api/system.threading.threadpool.threadcount). + */ +exports.METRIC_DOTNET_THREAD_POOL_THREAD_COUNT = 'dotnet.thread_pool.thread.count'; +/** + * The number of work items that the thread pool has completed since the process has started. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as calling [`ThreadPool.CompletedWorkItemCount`](https://learn.microsoft.com/dotnet/api/system.threading.threadpool.completedworkitemcount). + */ +exports.METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT = 'dotnet.thread_pool.work_item.count'; +/** + * The number of timer instances that are currently active. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as calling [`Timer.ActiveCount`](https://learn.microsoft.com/dotnet/api/system.threading.timer.activecount). + */ +exports.METRIC_DOTNET_TIMER_COUNT = 'dotnet.timer.count'; +/** + * Duration of HTTP client requests. + */ +exports.METRIC_HTTP_CLIENT_REQUEST_DURATION = 'http.client.request.duration'; +/** + * Duration of HTTP server requests. + */ +exports.METRIC_HTTP_SERVER_REQUEST_DURATION = 'http.server.request.duration'; +/** + * Number of classes currently loaded. + */ +exports.METRIC_JVM_CLASS_COUNT = 'jvm.class.count'; +/** + * Number of classes loaded since JVM start. + */ +exports.METRIC_JVM_CLASS_LOADED = 'jvm.class.loaded'; +/** + * Number of classes unloaded since JVM start. + */ +exports.METRIC_JVM_CLASS_UNLOADED = 'jvm.class.unloaded'; +/** + * Number of processors available to the Java virtual machine. + */ +exports.METRIC_JVM_CPU_COUNT = 'jvm.cpu.count'; +/** + * Recent CPU utilization for the process as reported by the JVM. + * + * @note The value range is [0.0,1.0]. This utilization is not defined as being for the specific interval since last measurement (unlike `system.cpu.utilization`). [Reference](https://docs.oracle.com/en/java/javase/17/docs/api/jdk.management/com/sun/management/OperatingSystemMXBean.html#getProcessCpuLoad()). + */ +exports.METRIC_JVM_CPU_RECENT_UTILIZATION = 'jvm.cpu.recent_utilization'; +/** + * CPU time used by the process as reported by the JVM. + */ +exports.METRIC_JVM_CPU_TIME = 'jvm.cpu.time'; +/** + * Duration of JVM garbage collection actions. + */ +exports.METRIC_JVM_GC_DURATION = 'jvm.gc.duration'; +/** + * Measure of memory committed. + */ +exports.METRIC_JVM_MEMORY_COMMITTED = 'jvm.memory.committed'; +/** + * Measure of max obtainable memory. + */ +exports.METRIC_JVM_MEMORY_LIMIT = 'jvm.memory.limit'; +/** + * Measure of memory used. + */ +exports.METRIC_JVM_MEMORY_USED = 'jvm.memory.used'; +/** + * Measure of memory used, as measured after the most recent garbage collection event on this pool. + */ +exports.METRIC_JVM_MEMORY_USED_AFTER_LAST_GC = 'jvm.memory.used_after_last_gc'; +/** + * Number of executing platform threads. + */ +exports.METRIC_JVM_THREAD_COUNT = 'jvm.thread.count'; +/** + * Number of connections that are currently active on the server. + * + * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 + */ +exports.METRIC_KESTREL_ACTIVE_CONNECTIONS = 'kestrel.active_connections'; +/** + * Number of TLS handshakes that are currently in progress on the server. + * + * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 + */ +exports.METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES = 'kestrel.active_tls_handshakes'; +/** + * The duration of connections on the server. + * + * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 + */ +exports.METRIC_KESTREL_CONNECTION_DURATION = 'kestrel.connection.duration'; +/** + * Number of connections that are currently queued and are waiting to start. + * + * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 + */ +exports.METRIC_KESTREL_QUEUED_CONNECTIONS = 'kestrel.queued_connections'; +/** + * Number of HTTP requests on multiplexed connections (HTTP/2 and HTTP/3) that are currently queued and are waiting to start. + * + * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 + */ +exports.METRIC_KESTREL_QUEUED_REQUESTS = 'kestrel.queued_requests'; +/** + * Number of connections rejected by the server. + * + * @note Connections are rejected when the currently active count exceeds the value configured with `MaxConcurrentConnections`. + * Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 + */ +exports.METRIC_KESTREL_REJECTED_CONNECTIONS = 'kestrel.rejected_connections'; +/** + * The duration of TLS handshakes on the server. + * + * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 + */ +exports.METRIC_KESTREL_TLS_HANDSHAKE_DURATION = 'kestrel.tls_handshake.duration'; +/** + * Number of connections that are currently upgraded (WebSockets). . + * + * @note The counter only tracks HTTP/1.1 connections. + * + * Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 + */ +exports.METRIC_KESTREL_UPGRADED_CONNECTIONS = 'kestrel.upgraded_connections'; +/** + * Number of connections that are currently active on the server. + * + * @note Meter name: `Microsoft.AspNetCore.Http.Connections`; Added in: ASP.NET Core 8.0 + */ +exports.METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS = 'signalr.server.active_connections'; +/** + * The duration of connections on the server. + * + * @note Meter name: `Microsoft.AspNetCore.Http.Connections`; Added in: ASP.NET Core 8.0 + */ +exports.METRIC_SIGNALR_SERVER_CONNECTION_DURATION = 'signalr.server.connection.duration'; +//# sourceMappingURL=stable_metrics.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/trace/SemanticAttributes.js b/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/trace/SemanticAttributes.js new file mode 100644 index 00000000..d7337171 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/trace/SemanticAttributes.js @@ -0,0 +1,2379 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SEMATTRS_NET_HOST_CARRIER_ICC = exports.SEMATTRS_NET_HOST_CARRIER_MNC = exports.SEMATTRS_NET_HOST_CARRIER_MCC = exports.SEMATTRS_NET_HOST_CARRIER_NAME = exports.SEMATTRS_NET_HOST_CONNECTION_SUBTYPE = exports.SEMATTRS_NET_HOST_CONNECTION_TYPE = exports.SEMATTRS_NET_HOST_NAME = exports.SEMATTRS_NET_HOST_PORT = exports.SEMATTRS_NET_HOST_IP = exports.SEMATTRS_NET_PEER_NAME = exports.SEMATTRS_NET_PEER_PORT = exports.SEMATTRS_NET_PEER_IP = exports.SEMATTRS_NET_TRANSPORT = exports.SEMATTRS_FAAS_INVOKED_REGION = exports.SEMATTRS_FAAS_INVOKED_PROVIDER = exports.SEMATTRS_FAAS_INVOKED_NAME = exports.SEMATTRS_FAAS_COLDSTART = exports.SEMATTRS_FAAS_CRON = exports.SEMATTRS_FAAS_TIME = exports.SEMATTRS_FAAS_DOCUMENT_NAME = exports.SEMATTRS_FAAS_DOCUMENT_TIME = exports.SEMATTRS_FAAS_DOCUMENT_OPERATION = exports.SEMATTRS_FAAS_DOCUMENT_COLLECTION = exports.SEMATTRS_FAAS_EXECUTION = exports.SEMATTRS_FAAS_TRIGGER = exports.SEMATTRS_EXCEPTION_ESCAPED = exports.SEMATTRS_EXCEPTION_STACKTRACE = exports.SEMATTRS_EXCEPTION_MESSAGE = exports.SEMATTRS_EXCEPTION_TYPE = exports.SEMATTRS_DB_SQL_TABLE = exports.SEMATTRS_DB_MONGODB_COLLECTION = exports.SEMATTRS_DB_REDIS_DATABASE_INDEX = exports.SEMATTRS_DB_HBASE_NAMESPACE = exports.SEMATTRS_DB_CASSANDRA_COORDINATOR_DC = exports.SEMATTRS_DB_CASSANDRA_COORDINATOR_ID = exports.SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = exports.SEMATTRS_DB_CASSANDRA_IDEMPOTENCE = exports.SEMATTRS_DB_CASSANDRA_TABLE = exports.SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL = exports.SEMATTRS_DB_CASSANDRA_PAGE_SIZE = exports.SEMATTRS_DB_CASSANDRA_KEYSPACE = exports.SEMATTRS_DB_MSSQL_INSTANCE_NAME = exports.SEMATTRS_DB_OPERATION = exports.SEMATTRS_DB_STATEMENT = exports.SEMATTRS_DB_NAME = exports.SEMATTRS_DB_JDBC_DRIVER_CLASSNAME = exports.SEMATTRS_DB_USER = exports.SEMATTRS_DB_CONNECTION_STRING = exports.SEMATTRS_DB_SYSTEM = exports.SEMATTRS_AWS_LAMBDA_INVOKED_ARN = void 0; +exports.SEMATTRS_MESSAGING_DESTINATION_KIND = exports.SEMATTRS_MESSAGING_DESTINATION = exports.SEMATTRS_MESSAGING_SYSTEM = exports.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = exports.SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = exports.SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT = exports.SEMATTRS_AWS_DYNAMODB_COUNT = exports.SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS = exports.SEMATTRS_AWS_DYNAMODB_SEGMENT = exports.SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD = exports.SEMATTRS_AWS_DYNAMODB_TABLE_COUNT = exports.SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE = exports.SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = exports.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = exports.SEMATTRS_AWS_DYNAMODB_SELECT = exports.SEMATTRS_AWS_DYNAMODB_INDEX_NAME = exports.SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET = exports.SEMATTRS_AWS_DYNAMODB_LIMIT = exports.SEMATTRS_AWS_DYNAMODB_PROJECTION = exports.SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ = exports.SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = exports.SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = exports.SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS = exports.SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY = exports.SEMATTRS_AWS_DYNAMODB_TABLE_NAMES = exports.SEMATTRS_HTTP_CLIENT_IP = exports.SEMATTRS_HTTP_ROUTE = exports.SEMATTRS_HTTP_SERVER_NAME = exports.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = exports.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH = exports.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = exports.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH = exports.SEMATTRS_HTTP_USER_AGENT = exports.SEMATTRS_HTTP_FLAVOR = exports.SEMATTRS_HTTP_STATUS_CODE = exports.SEMATTRS_HTTP_SCHEME = exports.SEMATTRS_HTTP_HOST = exports.SEMATTRS_HTTP_TARGET = exports.SEMATTRS_HTTP_URL = exports.SEMATTRS_HTTP_METHOD = exports.SEMATTRS_CODE_LINENO = exports.SEMATTRS_CODE_FILEPATH = exports.SEMATTRS_CODE_NAMESPACE = exports.SEMATTRS_CODE_FUNCTION = exports.SEMATTRS_THREAD_NAME = exports.SEMATTRS_THREAD_ID = exports.SEMATTRS_ENDUSER_SCOPE = exports.SEMATTRS_ENDUSER_ROLE = exports.SEMATTRS_ENDUSER_ID = exports.SEMATTRS_PEER_SERVICE = void 0; +exports.DBSYSTEMVALUES_FILEMAKER = exports.DBSYSTEMVALUES_DERBY = exports.DBSYSTEMVALUES_FIREBIRD = exports.DBSYSTEMVALUES_ADABAS = exports.DBSYSTEMVALUES_CACHE = exports.DBSYSTEMVALUES_EDB = exports.DBSYSTEMVALUES_FIRSTSQL = exports.DBSYSTEMVALUES_INGRES = exports.DBSYSTEMVALUES_HANADB = exports.DBSYSTEMVALUES_MAXDB = exports.DBSYSTEMVALUES_PROGRESS = exports.DBSYSTEMVALUES_HSQLDB = exports.DBSYSTEMVALUES_CLOUDSCAPE = exports.DBSYSTEMVALUES_HIVE = exports.DBSYSTEMVALUES_REDSHIFT = exports.DBSYSTEMVALUES_POSTGRESQL = exports.DBSYSTEMVALUES_DB2 = exports.DBSYSTEMVALUES_ORACLE = exports.DBSYSTEMVALUES_MYSQL = exports.DBSYSTEMVALUES_MSSQL = exports.DBSYSTEMVALUES_OTHER_SQL = exports.SemanticAttributes = exports.SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE = exports.SEMATTRS_MESSAGE_COMPRESSED_SIZE = exports.SEMATTRS_MESSAGE_ID = exports.SEMATTRS_MESSAGE_TYPE = exports.SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE = exports.SEMATTRS_RPC_JSONRPC_ERROR_CODE = exports.SEMATTRS_RPC_JSONRPC_REQUEST_ID = exports.SEMATTRS_RPC_JSONRPC_VERSION = exports.SEMATTRS_RPC_GRPC_STATUS_CODE = exports.SEMATTRS_RPC_METHOD = exports.SEMATTRS_RPC_SERVICE = exports.SEMATTRS_RPC_SYSTEM = exports.SEMATTRS_MESSAGING_KAFKA_TOMBSTONE = exports.SEMATTRS_MESSAGING_KAFKA_PARTITION = exports.SEMATTRS_MESSAGING_KAFKA_CLIENT_ID = exports.SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP = exports.SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY = exports.SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY = exports.SEMATTRS_MESSAGING_CONSUMER_ID = exports.SEMATTRS_MESSAGING_OPERATION = exports.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = exports.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = exports.SEMATTRS_MESSAGING_CONVERSATION_ID = exports.SEMATTRS_MESSAGING_MESSAGE_ID = exports.SEMATTRS_MESSAGING_URL = exports.SEMATTRS_MESSAGING_PROTOCOL_VERSION = exports.SEMATTRS_MESSAGING_PROTOCOL = exports.SEMATTRS_MESSAGING_TEMP_DESTINATION = void 0; +exports.FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = exports.FaasDocumentOperationValues = exports.FAASDOCUMENTOPERATIONVALUES_DELETE = exports.FAASDOCUMENTOPERATIONVALUES_EDIT = exports.FAASDOCUMENTOPERATIONVALUES_INSERT = exports.FaasTriggerValues = exports.FAASTRIGGERVALUES_OTHER = exports.FAASTRIGGERVALUES_TIMER = exports.FAASTRIGGERVALUES_PUBSUB = exports.FAASTRIGGERVALUES_HTTP = exports.FAASTRIGGERVALUES_DATASOURCE = exports.DbCassandraConsistencyLevelValues = exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = exports.DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = exports.DBCASSANDRACONSISTENCYLEVELVALUES_ANY = exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = exports.DBCASSANDRACONSISTENCYLEVELVALUES_THREE = exports.DBCASSANDRACONSISTENCYLEVELVALUES_TWO = exports.DBCASSANDRACONSISTENCYLEVELVALUES_ONE = exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = exports.DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = exports.DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = exports.DBCASSANDRACONSISTENCYLEVELVALUES_ALL = exports.DbSystemValues = exports.DBSYSTEMVALUES_COCKROACHDB = exports.DBSYSTEMVALUES_MEMCACHED = exports.DBSYSTEMVALUES_ELASTICSEARCH = exports.DBSYSTEMVALUES_GEODE = exports.DBSYSTEMVALUES_NEO4J = exports.DBSYSTEMVALUES_DYNAMODB = exports.DBSYSTEMVALUES_COSMOSDB = exports.DBSYSTEMVALUES_COUCHDB = exports.DBSYSTEMVALUES_COUCHBASE = exports.DBSYSTEMVALUES_REDIS = exports.DBSYSTEMVALUES_MONGODB = exports.DBSYSTEMVALUES_HBASE = exports.DBSYSTEMVALUES_CASSANDRA = exports.DBSYSTEMVALUES_COLDFUSION = exports.DBSYSTEMVALUES_H2 = exports.DBSYSTEMVALUES_VERTICA = exports.DBSYSTEMVALUES_TERADATA = exports.DBSYSTEMVALUES_SYBASE = exports.DBSYSTEMVALUES_SQLITE = exports.DBSYSTEMVALUES_POINTBASE = exports.DBSYSTEMVALUES_PERVASIVE = exports.DBSYSTEMVALUES_NETEZZA = exports.DBSYSTEMVALUES_MARIADB = exports.DBSYSTEMVALUES_INTERBASE = exports.DBSYSTEMVALUES_INSTANTDB = exports.DBSYSTEMVALUES_INFORMIX = void 0; +exports.MESSAGINGOPERATIONVALUES_RECEIVE = exports.MessagingDestinationKindValues = exports.MESSAGINGDESTINATIONKINDVALUES_TOPIC = exports.MESSAGINGDESTINATIONKINDVALUES_QUEUE = exports.HttpFlavorValues = exports.HTTPFLAVORVALUES_QUIC = exports.HTTPFLAVORVALUES_SPDY = exports.HTTPFLAVORVALUES_HTTP_2_0 = exports.HTTPFLAVORVALUES_HTTP_1_1 = exports.HTTPFLAVORVALUES_HTTP_1_0 = exports.NetHostConnectionSubtypeValues = exports.NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_NR = exports.NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = exports.NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_GSM = exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = exports.NETHOSTCONNECTIONSUBTYPEVALUES_LTE = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = exports.NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = exports.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = exports.NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = exports.NetHostConnectionTypeValues = exports.NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = exports.NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = exports.NETHOSTCONNECTIONTYPEVALUES_CELL = exports.NETHOSTCONNECTIONTYPEVALUES_WIRED = exports.NETHOSTCONNECTIONTYPEVALUES_WIFI = exports.NetTransportValues = exports.NETTRANSPORTVALUES_OTHER = exports.NETTRANSPORTVALUES_INPROC = exports.NETTRANSPORTVALUES_PIPE = exports.NETTRANSPORTVALUES_UNIX = exports.NETTRANSPORTVALUES_IP = exports.NETTRANSPORTVALUES_IP_UDP = exports.NETTRANSPORTVALUES_IP_TCP = exports.FaasInvokedProviderValues = exports.FAASINVOKEDPROVIDERVALUES_GCP = exports.FAASINVOKEDPROVIDERVALUES_AZURE = exports.FAASINVOKEDPROVIDERVALUES_AWS = void 0; +exports.MessageTypeValues = exports.MESSAGETYPEVALUES_RECEIVED = exports.MESSAGETYPEVALUES_SENT = exports.RpcGrpcStatusCodeValues = exports.RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = exports.RPCGRPCSTATUSCODEVALUES_DATA_LOSS = exports.RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = exports.RPCGRPCSTATUSCODEVALUES_INTERNAL = exports.RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = exports.RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = exports.RPCGRPCSTATUSCODEVALUES_ABORTED = exports.RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = exports.RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = exports.RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = exports.RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = exports.RPCGRPCSTATUSCODEVALUES_NOT_FOUND = exports.RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = exports.RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = exports.RPCGRPCSTATUSCODEVALUES_UNKNOWN = exports.RPCGRPCSTATUSCODEVALUES_CANCELLED = exports.RPCGRPCSTATUSCODEVALUES_OK = exports.MessagingOperationValues = exports.MESSAGINGOPERATIONVALUES_PROCESS = void 0; +const utils_1 = require("../internal/utils"); +//---------------------------------------------------------------------------------------------------------- +// DO NOT EDIT, this is an Auto-generated file from scripts/semconv/templates//templates/SemanticAttributes.ts.j2 +//---------------------------------------------------------------------------------------------------------- +//---------------------------------------------------------------------------------------------------------- +// Constant values for SemanticAttributes +//---------------------------------------------------------------------------------------------------------- +// Temporary local constants to assign to the individual exports and the namespaced version +// Required to avoid the namespace exports using the unminifiable export names for some package types +const TMP_AWS_LAMBDA_INVOKED_ARN = 'aws.lambda.invoked_arn'; +const TMP_DB_SYSTEM = 'db.system'; +const TMP_DB_CONNECTION_STRING = 'db.connection_string'; +const TMP_DB_USER = 'db.user'; +const TMP_DB_JDBC_DRIVER_CLASSNAME = 'db.jdbc.driver_classname'; +const TMP_DB_NAME = 'db.name'; +const TMP_DB_STATEMENT = 'db.statement'; +const TMP_DB_OPERATION = 'db.operation'; +const TMP_DB_MSSQL_INSTANCE_NAME = 'db.mssql.instance_name'; +const TMP_DB_CASSANDRA_KEYSPACE = 'db.cassandra.keyspace'; +const TMP_DB_CASSANDRA_PAGE_SIZE = 'db.cassandra.page_size'; +const TMP_DB_CASSANDRA_CONSISTENCY_LEVEL = 'db.cassandra.consistency_level'; +const TMP_DB_CASSANDRA_TABLE = 'db.cassandra.table'; +const TMP_DB_CASSANDRA_IDEMPOTENCE = 'db.cassandra.idempotence'; +const TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = 'db.cassandra.speculative_execution_count'; +const TMP_DB_CASSANDRA_COORDINATOR_ID = 'db.cassandra.coordinator.id'; +const TMP_DB_CASSANDRA_COORDINATOR_DC = 'db.cassandra.coordinator.dc'; +const TMP_DB_HBASE_NAMESPACE = 'db.hbase.namespace'; +const TMP_DB_REDIS_DATABASE_INDEX = 'db.redis.database_index'; +const TMP_DB_MONGODB_COLLECTION = 'db.mongodb.collection'; +const TMP_DB_SQL_TABLE = 'db.sql.table'; +const TMP_EXCEPTION_TYPE = 'exception.type'; +const TMP_EXCEPTION_MESSAGE = 'exception.message'; +const TMP_EXCEPTION_STACKTRACE = 'exception.stacktrace'; +const TMP_EXCEPTION_ESCAPED = 'exception.escaped'; +const TMP_FAAS_TRIGGER = 'faas.trigger'; +const TMP_FAAS_EXECUTION = 'faas.execution'; +const TMP_FAAS_DOCUMENT_COLLECTION = 'faas.document.collection'; +const TMP_FAAS_DOCUMENT_OPERATION = 'faas.document.operation'; +const TMP_FAAS_DOCUMENT_TIME = 'faas.document.time'; +const TMP_FAAS_DOCUMENT_NAME = 'faas.document.name'; +const TMP_FAAS_TIME = 'faas.time'; +const TMP_FAAS_CRON = 'faas.cron'; +const TMP_FAAS_COLDSTART = 'faas.coldstart'; +const TMP_FAAS_INVOKED_NAME = 'faas.invoked_name'; +const TMP_FAAS_INVOKED_PROVIDER = 'faas.invoked_provider'; +const TMP_FAAS_INVOKED_REGION = 'faas.invoked_region'; +const TMP_NET_TRANSPORT = 'net.transport'; +const TMP_NET_PEER_IP = 'net.peer.ip'; +const TMP_NET_PEER_PORT = 'net.peer.port'; +const TMP_NET_PEER_NAME = 'net.peer.name'; +const TMP_NET_HOST_IP = 'net.host.ip'; +const TMP_NET_HOST_PORT = 'net.host.port'; +const TMP_NET_HOST_NAME = 'net.host.name'; +const TMP_NET_HOST_CONNECTION_TYPE = 'net.host.connection.type'; +const TMP_NET_HOST_CONNECTION_SUBTYPE = 'net.host.connection.subtype'; +const TMP_NET_HOST_CARRIER_NAME = 'net.host.carrier.name'; +const TMP_NET_HOST_CARRIER_MCC = 'net.host.carrier.mcc'; +const TMP_NET_HOST_CARRIER_MNC = 'net.host.carrier.mnc'; +const TMP_NET_HOST_CARRIER_ICC = 'net.host.carrier.icc'; +const TMP_PEER_SERVICE = 'peer.service'; +const TMP_ENDUSER_ID = 'enduser.id'; +const TMP_ENDUSER_ROLE = 'enduser.role'; +const TMP_ENDUSER_SCOPE = 'enduser.scope'; +const TMP_THREAD_ID = 'thread.id'; +const TMP_THREAD_NAME = 'thread.name'; +const TMP_CODE_FUNCTION = 'code.function'; +const TMP_CODE_NAMESPACE = 'code.namespace'; +const TMP_CODE_FILEPATH = 'code.filepath'; +const TMP_CODE_LINENO = 'code.lineno'; +const TMP_HTTP_METHOD = 'http.method'; +const TMP_HTTP_URL = 'http.url'; +const TMP_HTTP_TARGET = 'http.target'; +const TMP_HTTP_HOST = 'http.host'; +const TMP_HTTP_SCHEME = 'http.scheme'; +const TMP_HTTP_STATUS_CODE = 'http.status_code'; +const TMP_HTTP_FLAVOR = 'http.flavor'; +const TMP_HTTP_USER_AGENT = 'http.user_agent'; +const TMP_HTTP_REQUEST_CONTENT_LENGTH = 'http.request_content_length'; +const TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = 'http.request_content_length_uncompressed'; +const TMP_HTTP_RESPONSE_CONTENT_LENGTH = 'http.response_content_length'; +const TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = 'http.response_content_length_uncompressed'; +const TMP_HTTP_SERVER_NAME = 'http.server_name'; +const TMP_HTTP_ROUTE = 'http.route'; +const TMP_HTTP_CLIENT_IP = 'http.client_ip'; +const TMP_AWS_DYNAMODB_TABLE_NAMES = 'aws.dynamodb.table_names'; +const TMP_AWS_DYNAMODB_CONSUMED_CAPACITY = 'aws.dynamodb.consumed_capacity'; +const TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS = 'aws.dynamodb.item_collection_metrics'; +const TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = 'aws.dynamodb.provisioned_read_capacity'; +const TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = 'aws.dynamodb.provisioned_write_capacity'; +const TMP_AWS_DYNAMODB_CONSISTENT_READ = 'aws.dynamodb.consistent_read'; +const TMP_AWS_DYNAMODB_PROJECTION = 'aws.dynamodb.projection'; +const TMP_AWS_DYNAMODB_LIMIT = 'aws.dynamodb.limit'; +const TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET = 'aws.dynamodb.attributes_to_get'; +const TMP_AWS_DYNAMODB_INDEX_NAME = 'aws.dynamodb.index_name'; +const TMP_AWS_DYNAMODB_SELECT = 'aws.dynamodb.select'; +const TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = 'aws.dynamodb.global_secondary_indexes'; +const TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = 'aws.dynamodb.local_secondary_indexes'; +const TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE = 'aws.dynamodb.exclusive_start_table'; +const TMP_AWS_DYNAMODB_TABLE_COUNT = 'aws.dynamodb.table_count'; +const TMP_AWS_DYNAMODB_SCAN_FORWARD = 'aws.dynamodb.scan_forward'; +const TMP_AWS_DYNAMODB_SEGMENT = 'aws.dynamodb.segment'; +const TMP_AWS_DYNAMODB_TOTAL_SEGMENTS = 'aws.dynamodb.total_segments'; +const TMP_AWS_DYNAMODB_COUNT = 'aws.dynamodb.count'; +const TMP_AWS_DYNAMODB_SCANNED_COUNT = 'aws.dynamodb.scanned_count'; +const TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = 'aws.dynamodb.attribute_definitions'; +const TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = 'aws.dynamodb.global_secondary_index_updates'; +const TMP_MESSAGING_SYSTEM = 'messaging.system'; +const TMP_MESSAGING_DESTINATION = 'messaging.destination'; +const TMP_MESSAGING_DESTINATION_KIND = 'messaging.destination_kind'; +const TMP_MESSAGING_TEMP_DESTINATION = 'messaging.temp_destination'; +const TMP_MESSAGING_PROTOCOL = 'messaging.protocol'; +const TMP_MESSAGING_PROTOCOL_VERSION = 'messaging.protocol_version'; +const TMP_MESSAGING_URL = 'messaging.url'; +const TMP_MESSAGING_MESSAGE_ID = 'messaging.message_id'; +const TMP_MESSAGING_CONVERSATION_ID = 'messaging.conversation_id'; +const TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = 'messaging.message_payload_size_bytes'; +const TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = 'messaging.message_payload_compressed_size_bytes'; +const TMP_MESSAGING_OPERATION = 'messaging.operation'; +const TMP_MESSAGING_CONSUMER_ID = 'messaging.consumer_id'; +const TMP_MESSAGING_RABBITMQ_ROUTING_KEY = 'messaging.rabbitmq.routing_key'; +const TMP_MESSAGING_KAFKA_MESSAGE_KEY = 'messaging.kafka.message_key'; +const TMP_MESSAGING_KAFKA_CONSUMER_GROUP = 'messaging.kafka.consumer_group'; +const TMP_MESSAGING_KAFKA_CLIENT_ID = 'messaging.kafka.client_id'; +const TMP_MESSAGING_KAFKA_PARTITION = 'messaging.kafka.partition'; +const TMP_MESSAGING_KAFKA_TOMBSTONE = 'messaging.kafka.tombstone'; +const TMP_RPC_SYSTEM = 'rpc.system'; +const TMP_RPC_SERVICE = 'rpc.service'; +const TMP_RPC_METHOD = 'rpc.method'; +const TMP_RPC_GRPC_STATUS_CODE = 'rpc.grpc.status_code'; +const TMP_RPC_JSONRPC_VERSION = 'rpc.jsonrpc.version'; +const TMP_RPC_JSONRPC_REQUEST_ID = 'rpc.jsonrpc.request_id'; +const TMP_RPC_JSONRPC_ERROR_CODE = 'rpc.jsonrpc.error_code'; +const TMP_RPC_JSONRPC_ERROR_MESSAGE = 'rpc.jsonrpc.error_message'; +const TMP_MESSAGE_TYPE = 'message.type'; +const TMP_MESSAGE_ID = 'message.id'; +const TMP_MESSAGE_COMPRESSED_SIZE = 'message.compressed_size'; +const TMP_MESSAGE_UNCOMPRESSED_SIZE = 'message.uncompressed_size'; +/** + * The full invoked ARN as provided on the `Context` passed to the function (`Lambda-Runtime-Invoked-Function-Arn` header on the `/runtime/invocation/next` applicable). + * + * Note: This may be different from `faas.id` if an alias is involved. + * + * @deprecated Use ATTR_AWS_LAMBDA_INVOKED_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_AWS_LAMBDA_INVOKED_ARN = TMP_AWS_LAMBDA_INVOKED_ARN; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use ATTR_DB_SYSTEM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_DB_SYSTEM = TMP_DB_SYSTEM; +/** + * The connection string used to connect to the database. It is recommended to remove embedded credentials. + * + * @deprecated Use ATTR_DB_CONNECTION_STRING in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_DB_CONNECTION_STRING = TMP_DB_CONNECTION_STRING; +/** + * Username for accessing the database. + * + * @deprecated Use ATTR_DB_USER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_DB_USER = TMP_DB_USER; +/** + * The fully-qualified class name of the [Java Database Connectivity (JDBC)](https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/) driver used to connect. + * + * @deprecated Use ATTR_DB_JDBC_DRIVER_CLASSNAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_DB_JDBC_DRIVER_CLASSNAME = TMP_DB_JDBC_DRIVER_CLASSNAME; +/** + * If no [tech-specific attribute](#call-level-attributes-for-specific-technologies) is defined, this attribute is used to report the name of the database being accessed. For commands that switch the database, this should be set to the target database (even if the command fails). + * + * Note: In some SQL databases, the database name to be used is called "schema name". + * + * @deprecated Use ATTR_DB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_DB_NAME = TMP_DB_NAME; +/** + * The database statement being executed. + * + * Note: The value may be sanitized to exclude sensitive information. + * + * @deprecated Use ATTR_DB_STATEMENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_DB_STATEMENT = TMP_DB_STATEMENT; +/** + * The name of the operation being executed, e.g. the [MongoDB command name](https://docs.mongodb.com/manual/reference/command/#database-operations) such as `findAndModify`, or the SQL keyword. + * + * Note: When setting this to an SQL keyword, it is not recommended to attempt any client-side parsing of `db.statement` just to get this property, but it should be set if the operation name is provided by the library being instrumented. If the SQL statement has an ambiguous operation, or performs more than one operation, this value may be omitted. + * + * @deprecated Use ATTR_DB_OPERATION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_DB_OPERATION = TMP_DB_OPERATION; +/** + * The Microsoft SQL Server [instance name](https://docs.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url?view=sql-server-ver15) connecting to. This name is used to determine the port of a named instance. + * + * Note: If setting a `db.mssql.instance_name`, `net.peer.port` is no longer required (but still recommended if non-standard). + * + * @deprecated Use ATTR_DB_MSSQL_INSTANCE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_DB_MSSQL_INSTANCE_NAME = TMP_DB_MSSQL_INSTANCE_NAME; +/** + * The name of the keyspace being accessed. To be used instead of the generic `db.name` attribute. + * + * @deprecated Use ATTR_DB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_DB_CASSANDRA_KEYSPACE = TMP_DB_CASSANDRA_KEYSPACE; +/** + * The fetch size used for paging, i.e. how many rows will be returned at once. + * + * @deprecated Use ATTR_DB_CASSANDRA_PAGE_SIZE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_DB_CASSANDRA_PAGE_SIZE = TMP_DB_CASSANDRA_PAGE_SIZE; +/** + * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). + * + * @deprecated Use ATTR_DB_CASSANDRA_CONSISTENCY_LEVEL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL = TMP_DB_CASSANDRA_CONSISTENCY_LEVEL; +/** + * The name of the primary table that the operation is acting upon, including the schema name (if applicable). + * + * Note: This mirrors the db.sql.table attribute but references cassandra rather than sql. It is not recommended to attempt any client-side parsing of `db.statement` just to get this property, but it should be set if it is provided by the library being instrumented. If the operation is acting upon an anonymous table, or more than one table, this value MUST NOT be set. + * + * @deprecated Use ATTR_DB_CASSANDRA_TABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_DB_CASSANDRA_TABLE = TMP_DB_CASSANDRA_TABLE; +/** + * Whether or not the query is idempotent. + * + * @deprecated Use ATTR_DB_CASSANDRA_IDEMPOTENCE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_DB_CASSANDRA_IDEMPOTENCE = TMP_DB_CASSANDRA_IDEMPOTENCE; +/** + * The number of times a query was speculatively executed. Not set or `0` if the query was not executed speculatively. + * + * @deprecated Use ATTR_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT; +/** + * The ID of the coordinating node for a query. + * + * @deprecated Use ATTR_DB_CASSANDRA_COORDINATOR_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_DB_CASSANDRA_COORDINATOR_ID = TMP_DB_CASSANDRA_COORDINATOR_ID; +/** + * The data center of the coordinating node for a query. + * + * @deprecated Use ATTR_DB_CASSANDRA_COORDINATOR_DC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_DB_CASSANDRA_COORDINATOR_DC = TMP_DB_CASSANDRA_COORDINATOR_DC; +/** + * The [HBase namespace](https://hbase.apache.org/book.html#_namespace) being accessed. To be used instead of the generic `db.name` attribute. + * + * @deprecated Use ATTR_DB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_DB_HBASE_NAMESPACE = TMP_DB_HBASE_NAMESPACE; +/** + * The index of the database being accessed as used in the [`SELECT` command](https://redis.io/commands/select), provided as an integer. To be used instead of the generic `db.name` attribute. + * + * @deprecated Use ATTR_DB_REDIS_DATABASE_INDEX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_DB_REDIS_DATABASE_INDEX = TMP_DB_REDIS_DATABASE_INDEX; +/** + * The collection being accessed within the database stated in `db.name`. + * + * @deprecated Use ATTR_DB_MONGODB_COLLECTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_DB_MONGODB_COLLECTION = TMP_DB_MONGODB_COLLECTION; +/** + * The name of the primary table that the operation is acting upon, including the schema name (if applicable). + * + * Note: It is not recommended to attempt any client-side parsing of `db.statement` just to get this property, but it should be set if it is provided by the library being instrumented. If the operation is acting upon an anonymous table, or more than one table, this value MUST NOT be set. + * + * @deprecated Use ATTR_DB_SQL_TABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_DB_SQL_TABLE = TMP_DB_SQL_TABLE; +/** + * The type of the exception (its fully-qualified class name, if applicable). The dynamic type of the exception should be preferred over the static type in languages that support it. + * + * @deprecated Use ATTR_EXCEPTION_TYPE. + */ +exports.SEMATTRS_EXCEPTION_TYPE = TMP_EXCEPTION_TYPE; +/** + * The exception message. + * + * @deprecated Use ATTR_EXCEPTION_MESSAGE. + */ +exports.SEMATTRS_EXCEPTION_MESSAGE = TMP_EXCEPTION_MESSAGE; +/** + * A stacktrace as a string in the natural representation for the language runtime. The representation is to be determined and documented by each language SIG. + * + * @deprecated Use ATTR_EXCEPTION_STACKTRACE. + */ +exports.SEMATTRS_EXCEPTION_STACKTRACE = TMP_EXCEPTION_STACKTRACE; +/** +* SHOULD be set to true if the exception event is recorded at a point where it is known that the exception is escaping the scope of the span. +* +* Note: An exception is considered to have escaped (or left) the scope of a span, +if that span is ended while the exception is still logically "in flight". +This may be actually "in flight" in some languages (e.g. if the exception +is passed to a Context manager's `__exit__` method in Python) but will +usually be caught at the point of recording the exception in most languages. + +It is usually not possible to determine at the point where an exception is thrown +whether it will escape the scope of a span. +However, it is trivial to know that an exception +will escape, if one checks for an active exception just before ending the span, +as done in the [example above](#exception-end-example). + +It follows that an exception may still escape the scope of the span +even if the `exception.escaped` attribute was not set or set to false, +since the event might have been recorded at a time where it was not +clear whether the exception will escape. +* +* @deprecated Use ATTR_EXCEPTION_ESCAPED. +*/ +exports.SEMATTRS_EXCEPTION_ESCAPED = TMP_EXCEPTION_ESCAPED; +/** + * Type of the trigger on which the function is executed. + * + * @deprecated Use ATTR_FAAS_TRIGGER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_FAAS_TRIGGER = TMP_FAAS_TRIGGER; +/** + * The execution ID of the current function execution. + * + * @deprecated Use ATTR_FAAS_INVOCATION_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_FAAS_EXECUTION = TMP_FAAS_EXECUTION; +/** + * The name of the source on which the triggering operation was performed. For example, in Cloud Storage or S3 corresponds to the bucket name, and in Cosmos DB to the database name. + * + * @deprecated Use ATTR_FAAS_DOCUMENT_COLLECTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_FAAS_DOCUMENT_COLLECTION = TMP_FAAS_DOCUMENT_COLLECTION; +/** + * Describes the type of the operation that was performed on the data. + * + * @deprecated Use ATTR_FAAS_DOCUMENT_OPERATION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_FAAS_DOCUMENT_OPERATION = TMP_FAAS_DOCUMENT_OPERATION; +/** + * A string containing the time when the data was accessed in the [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format expressed in [UTC](https://www.w3.org/TR/NOTE-datetime). + * + * @deprecated Use ATTR_FAAS_DOCUMENT_TIME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_FAAS_DOCUMENT_TIME = TMP_FAAS_DOCUMENT_TIME; +/** + * The document name/table subjected to the operation. For example, in Cloud Storage or S3 is the name of the file, and in Cosmos DB the table name. + * + * @deprecated Use ATTR_FAAS_DOCUMENT_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_FAAS_DOCUMENT_NAME = TMP_FAAS_DOCUMENT_NAME; +/** + * A string containing the function invocation time in the [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format expressed in [UTC](https://www.w3.org/TR/NOTE-datetime). + * + * @deprecated Use ATTR_FAAS_TIME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_FAAS_TIME = TMP_FAAS_TIME; +/** + * A string containing the schedule period as [Cron Expression](https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm). + * + * @deprecated Use ATTR_FAAS_CRON in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_FAAS_CRON = TMP_FAAS_CRON; +/** + * A boolean that is true if the serverless function is executed for the first time (aka cold-start). + * + * @deprecated Use ATTR_FAAS_COLDSTART in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_FAAS_COLDSTART = TMP_FAAS_COLDSTART; +/** + * The name of the invoked function. + * + * Note: SHOULD be equal to the `faas.name` resource attribute of the invoked function. + * + * @deprecated Use ATTR_FAAS_INVOKED_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_FAAS_INVOKED_NAME = TMP_FAAS_INVOKED_NAME; +/** + * The cloud provider of the invoked function. + * + * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function. + * + * @deprecated Use ATTR_FAAS_INVOKED_PROVIDER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_FAAS_INVOKED_PROVIDER = TMP_FAAS_INVOKED_PROVIDER; +/** + * The cloud region of the invoked function. + * + * Note: SHOULD be equal to the `cloud.region` resource attribute of the invoked function. + * + * @deprecated Use ATTR_FAAS_INVOKED_REGION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_FAAS_INVOKED_REGION = TMP_FAAS_INVOKED_REGION; +/** + * Transport protocol used. See note below. + * + * @deprecated Use ATTR_NET_TRANSPORT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_NET_TRANSPORT = TMP_NET_TRANSPORT; +/** + * Remote address of the peer (dotted decimal for IPv4 or [RFC5952](https://tools.ietf.org/html/rfc5952) for IPv6). + * + * @deprecated Use ATTR_NET_PEER_IP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_NET_PEER_IP = TMP_NET_PEER_IP; +/** + * Remote port number. + * + * @deprecated Use ATTR_NET_PEER_PORT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_NET_PEER_PORT = TMP_NET_PEER_PORT; +/** + * Remote hostname or similar, see note below. + * + * @deprecated Use ATTR_NET_PEER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_NET_PEER_NAME = TMP_NET_PEER_NAME; +/** + * Like `net.peer.ip` but for the host IP. Useful in case of a multi-IP host. + * + * @deprecated Use ATTR_NET_HOST_IP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_NET_HOST_IP = TMP_NET_HOST_IP; +/** + * Like `net.peer.port` but for the host port. + * + * @deprecated Use ATTR_NET_HOST_PORT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_NET_HOST_PORT = TMP_NET_HOST_PORT; +/** + * Local hostname or similar, see note below. + * + * @deprecated Use ATTR_NET_HOST_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_NET_HOST_NAME = TMP_NET_HOST_NAME; +/** + * The internet connection type currently being used by the host. + * + * @deprecated Use ATTR_NETWORK_CONNECTION_TYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_NET_HOST_CONNECTION_TYPE = TMP_NET_HOST_CONNECTION_TYPE; +/** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use ATTR_NETWORK_CONNECTION_SUBTYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_NET_HOST_CONNECTION_SUBTYPE = TMP_NET_HOST_CONNECTION_SUBTYPE; +/** + * The name of the mobile carrier. + * + * @deprecated Use ATTR_NETWORK_CARRIER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_NET_HOST_CARRIER_NAME = TMP_NET_HOST_CARRIER_NAME; +/** + * The mobile carrier country code. + * + * @deprecated Use ATTR_NETWORK_CARRIER_MCC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_NET_HOST_CARRIER_MCC = TMP_NET_HOST_CARRIER_MCC; +/** + * The mobile carrier network code. + * + * @deprecated Use ATTR_NETWORK_CARRIER_MNC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_NET_HOST_CARRIER_MNC = TMP_NET_HOST_CARRIER_MNC; +/** + * The ISO 3166-1 alpha-2 2-character country code associated with the mobile carrier network. + * + * @deprecated Use ATTR_NETWORK_CARRIER_ICC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_NET_HOST_CARRIER_ICC = TMP_NET_HOST_CARRIER_ICC; +/** + * The [`service.name`](../../resource/semantic_conventions/README.md#service) of the remote service. SHOULD be equal to the actual `service.name` resource attribute of the remote service if any. + * + * @deprecated Use ATTR_PEER_SERVICE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_PEER_SERVICE = TMP_PEER_SERVICE; +/** + * Username or client_id extracted from the access token or [Authorization](https://tools.ietf.org/html/rfc7235#section-4.2) header in the inbound request from outside the system. + * + * @deprecated Use ATTR_ENDUSER_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_ENDUSER_ID = TMP_ENDUSER_ID; +/** + * Actual/assumed role the client is making the request under extracted from token or application security context. + * + * @deprecated Use ATTR_ENDUSER_ROLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_ENDUSER_ROLE = TMP_ENDUSER_ROLE; +/** + * Scopes or granted authorities the client currently possesses extracted from token or application security context. The value would come from the scope associated with an [OAuth 2.0 Access Token](https://tools.ietf.org/html/rfc6749#section-3.3) or an attribute value in a [SAML 2.0 Assertion](http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html). + * + * @deprecated Use ATTR_ENDUSER_SCOPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_ENDUSER_SCOPE = TMP_ENDUSER_SCOPE; +/** + * Current "managed" thread ID (as opposed to OS thread ID). + * + * @deprecated Use ATTR_THREAD_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_THREAD_ID = TMP_THREAD_ID; +/** + * Current thread name. + * + * @deprecated Use ATTR_THREAD_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_THREAD_NAME = TMP_THREAD_NAME; +/** + * The method or function name, or equivalent (usually rightmost part of the code unit's name). + * + * @deprecated Use ATTR_CODE_FUNCTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_CODE_FUNCTION = TMP_CODE_FUNCTION; +/** + * The "namespace" within which `code.function` is defined. Usually the qualified class or module name, such that `code.namespace` + some separator + `code.function` form a unique identifier for the code unit. + * + * @deprecated Use ATTR_CODE_NAMESPACE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_CODE_NAMESPACE = TMP_CODE_NAMESPACE; +/** + * The source code file name that identifies the code unit as uniquely as possible (preferably an absolute file path). + * + * @deprecated Use ATTR_CODE_FILEPATH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_CODE_FILEPATH = TMP_CODE_FILEPATH; +/** + * The line number in `code.filepath` best representing the operation. It SHOULD point within the code unit named in `code.function`. + * + * @deprecated Use ATTR_CODE_LINENO in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_CODE_LINENO = TMP_CODE_LINENO; +/** + * HTTP request method. + * + * @deprecated Use ATTR_HTTP_METHOD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_HTTP_METHOD = TMP_HTTP_METHOD; +/** + * Full HTTP request URL in the form `scheme://host[:port]/path?query[#fragment]`. Usually the fragment is not transmitted over HTTP, but if it is known, it should be included nevertheless. + * + * Note: `http.url` MUST NOT contain credentials passed via URL in form of `https://username:password@www.example.com/`. In such case the attribute's value should be `https://www.example.com/`. + * + * @deprecated Use ATTR_HTTP_URL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_HTTP_URL = TMP_HTTP_URL; +/** + * The full request target as passed in a HTTP request line or equivalent. + * + * @deprecated Use ATTR_HTTP_TARGET in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_HTTP_TARGET = TMP_HTTP_TARGET; +/** + * The value of the [HTTP host header](https://tools.ietf.org/html/rfc7230#section-5.4). An empty Host header should also be reported, see note. + * + * Note: When the header is present but empty the attribute SHOULD be set to the empty string. Note that this is a valid situation that is expected in certain cases, according the aforementioned [section of RFC 7230](https://tools.ietf.org/html/rfc7230#section-5.4). When the header is not set the attribute MUST NOT be set. + * + * @deprecated Use ATTR_HTTP_HOST in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_HTTP_HOST = TMP_HTTP_HOST; +/** + * The URI scheme identifying the used protocol. + * + * @deprecated Use ATTR_HTTP_SCHEME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_HTTP_SCHEME = TMP_HTTP_SCHEME; +/** + * [HTTP response status code](https://tools.ietf.org/html/rfc7231#section-6). + * + * @deprecated Use ATTR_HTTP_STATUS_CODE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_HTTP_STATUS_CODE = TMP_HTTP_STATUS_CODE; +/** + * Kind of HTTP protocol used. + * + * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. + * + * @deprecated Use ATTR_HTTP_FLAVOR in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_HTTP_FLAVOR = TMP_HTTP_FLAVOR; +/** + * Value of the [HTTP User-Agent](https://tools.ietf.org/html/rfc7231#section-5.5.3) header sent by the client. + * + * @deprecated Use ATTR_HTTP_USER_AGENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_HTTP_USER_AGENT = TMP_HTTP_USER_AGENT; +/** + * The size of the request payload body in bytes. This is the number of bytes transferred excluding headers and is often, but not always, present as the [Content-Length](https://tools.ietf.org/html/rfc7230#section-3.3.2) header. For requests using transport encoding, this should be the compressed size. + * + * @deprecated Use ATTR_HTTP_REQUEST_CONTENT_LENGTH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH = TMP_HTTP_REQUEST_CONTENT_LENGTH; +/** + * The size of the uncompressed request payload body after transport decoding. Not set if transport encoding not used. + * + * @deprecated Use ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED; +/** + * The size of the response payload body in bytes. This is the number of bytes transferred excluding headers and is often, but not always, present as the [Content-Length](https://tools.ietf.org/html/rfc7230#section-3.3.2) header. For requests using transport encoding, this should be the compressed size. + * + * @deprecated Use ATTR_HTTP_RESPONSE_CONTENT_LENGTH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH = TMP_HTTP_RESPONSE_CONTENT_LENGTH; +/** + * The size of the uncompressed response payload body after transport decoding. Not set if transport encoding not used. + * + * @deprecated Use ATTR_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED; +/** + * The primary server name of the matched virtual host. This should be obtained via configuration. If no such configuration can be obtained, this attribute MUST NOT be set ( `net.host.name` should be used instead). + * + * Note: `http.url` is usually not readily available on the server side but would have to be assembled in a cumbersome and sometimes lossy process from other information (see e.g. open-telemetry/opentelemetry-python/pull/148). It is thus preferred to supply the raw data that is available. + * + * @deprecated Use ATTR_HTTP_SERVER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_HTTP_SERVER_NAME = TMP_HTTP_SERVER_NAME; +/** + * The matched route (path template). + * + * @deprecated Use ATTR_HTTP_ROUTE. + */ +exports.SEMATTRS_HTTP_ROUTE = TMP_HTTP_ROUTE; +/** +* The IP address of the original client behind all proxies, if known (e.g. from [X-Forwarded-For](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For)). +* +* Note: This is not necessarily the same as `net.peer.ip`, which would +identify the network-level peer, which may be a proxy. + +This attribute should be set when a source of information different +from the one used for `net.peer.ip`, is available even if that other +source just confirms the same value as `net.peer.ip`. +Rationale: For `net.peer.ip`, one typically does not know if it +comes from a proxy, reverse proxy, or the actual client. Setting +`http.client_ip` when it's the same as `net.peer.ip` means that +one is at least somewhat confident that the address is not that of +the closest proxy. +* +* @deprecated Use ATTR_HTTP_CLIENT_IP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). +*/ +exports.SEMATTRS_HTTP_CLIENT_IP = TMP_HTTP_CLIENT_IP; +/** + * The keys in the `RequestItems` object field. + * + * @deprecated Use ATTR_AWS_DYNAMODB_TABLE_NAMES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_AWS_DYNAMODB_TABLE_NAMES = TMP_AWS_DYNAMODB_TABLE_NAMES; +/** + * The JSON-serialized value of each item in the `ConsumedCapacity` response field. + * + * @deprecated Use ATTR_AWS_DYNAMODB_CONSUMED_CAPACITY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY = TMP_AWS_DYNAMODB_CONSUMED_CAPACITY; +/** + * The JSON-serialized value of the `ItemCollectionMetrics` response field. + * + * @deprecated Use ATTR_AWS_DYNAMODB_ITEM_COLLECTION_METRICS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS = TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS; +/** + * The value of the `ProvisionedThroughput.ReadCapacityUnits` request parameter. + * + * @deprecated Use ATTR_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY; +/** + * The value of the `ProvisionedThroughput.WriteCapacityUnits` request parameter. + * + * @deprecated Use ATTR_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY; +/** + * The value of the `ConsistentRead` request parameter. + * + * @deprecated Use ATTR_AWS_DYNAMODB_CONSISTENT_READ in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ = TMP_AWS_DYNAMODB_CONSISTENT_READ; +/** + * The value of the `ProjectionExpression` request parameter. + * + * @deprecated Use ATTR_AWS_DYNAMODB_PROJECTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_AWS_DYNAMODB_PROJECTION = TMP_AWS_DYNAMODB_PROJECTION; +/** + * The value of the `Limit` request parameter. + * + * @deprecated Use ATTR_AWS_DYNAMODB_LIMIT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_AWS_DYNAMODB_LIMIT = TMP_AWS_DYNAMODB_LIMIT; +/** + * The value of the `AttributesToGet` request parameter. + * + * @deprecated Use ATTR_AWS_DYNAMODB_ATTRIBUTES_TO_GET in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET = TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET; +/** + * The value of the `IndexName` request parameter. + * + * @deprecated Use ATTR_AWS_DYNAMODB_INDEX_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_AWS_DYNAMODB_INDEX_NAME = TMP_AWS_DYNAMODB_INDEX_NAME; +/** + * The value of the `Select` request parameter. + * + * @deprecated Use ATTR_AWS_DYNAMODB_SELECT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_AWS_DYNAMODB_SELECT = TMP_AWS_DYNAMODB_SELECT; +/** + * The JSON-serialized value of each item of the `GlobalSecondaryIndexes` request field. + * + * @deprecated Use ATTR_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES; +/** + * The JSON-serialized value of each item of the `LocalSecondaryIndexes` request field. + * + * @deprecated Use ATTR_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES; +/** + * The value of the `ExclusiveStartTableName` request parameter. + * + * @deprecated Use ATTR_AWS_DYNAMODB_EXCLUSIVE_START_TABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE = TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE; +/** + * The the number of items in the `TableNames` response parameter. + * + * @deprecated Use ATTR_AWS_DYNAMODB_TABLE_COUNT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_AWS_DYNAMODB_TABLE_COUNT = TMP_AWS_DYNAMODB_TABLE_COUNT; +/** + * The value of the `ScanIndexForward` request parameter. + * + * @deprecated Use ATTR_AWS_DYNAMODB_SCAN_FORWARD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD = TMP_AWS_DYNAMODB_SCAN_FORWARD; +/** + * The value of the `Segment` request parameter. + * + * @deprecated Use ATTR_AWS_DYNAMODB_SEGMENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_AWS_DYNAMODB_SEGMENT = TMP_AWS_DYNAMODB_SEGMENT; +/** + * The value of the `TotalSegments` request parameter. + * + * @deprecated Use ATTR_AWS_DYNAMODB_TOTAL_SEGMENTS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS = TMP_AWS_DYNAMODB_TOTAL_SEGMENTS; +/** + * The value of the `Count` response parameter. + * + * @deprecated Use ATTR_AWS_DYNAMODB_COUNT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_AWS_DYNAMODB_COUNT = TMP_AWS_DYNAMODB_COUNT; +/** + * The value of the `ScannedCount` response parameter. + * + * @deprecated Use ATTR_AWS_DYNAMODB_SCANNED_COUNT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT = TMP_AWS_DYNAMODB_SCANNED_COUNT; +/** + * The JSON-serialized value of each item in the `AttributeDefinitions` request field. + * + * @deprecated Use ATTR_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS; +/** + * The JSON-serialized value of each item in the the `GlobalSecondaryIndexUpdates` request field. + * + * @deprecated Use ATTR_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES; +/** + * A string identifying the messaging system. + * + * @deprecated Use ATTR_MESSAGING_SYSTEM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_MESSAGING_SYSTEM = TMP_MESSAGING_SYSTEM; +/** + * The message destination name. This might be equal to the span name but is required nevertheless. + * + * @deprecated Use ATTR_MESSAGING_DESTINATION_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_MESSAGING_DESTINATION = TMP_MESSAGING_DESTINATION; +/** + * The kind of message destination. + * + * @deprecated Removed in semconv v1.20.0. + */ +exports.SEMATTRS_MESSAGING_DESTINATION_KIND = TMP_MESSAGING_DESTINATION_KIND; +/** + * A boolean that is true if the message destination is temporary. + * + * @deprecated Use ATTR_MESSAGING_DESTINATION_TEMPORARY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_MESSAGING_TEMP_DESTINATION = TMP_MESSAGING_TEMP_DESTINATION; +/** + * The name of the transport protocol. + * + * @deprecated Use ATTR_NETWORK_PROTOCOL_NAME. + */ +exports.SEMATTRS_MESSAGING_PROTOCOL = TMP_MESSAGING_PROTOCOL; +/** + * The version of the transport protocol. + * + * @deprecated Use ATTR_NETWORK_PROTOCOL_VERSION. + */ +exports.SEMATTRS_MESSAGING_PROTOCOL_VERSION = TMP_MESSAGING_PROTOCOL_VERSION; +/** + * Connection string. + * + * @deprecated Removed in semconv v1.17.0. + */ +exports.SEMATTRS_MESSAGING_URL = TMP_MESSAGING_URL; +/** + * A value used by the messaging system as an identifier for the message, represented as a string. + * + * @deprecated Use ATTR_MESSAGING_MESSAGE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_MESSAGING_MESSAGE_ID = TMP_MESSAGING_MESSAGE_ID; +/** + * The [conversation ID](#conversations) identifying the conversation to which the message belongs, represented as a string. Sometimes called "Correlation ID". + * + * @deprecated Use ATTR_MESSAGING_MESSAGE_CONVERSATION_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_MESSAGING_CONVERSATION_ID = TMP_MESSAGING_CONVERSATION_ID; +/** + * The (uncompressed) size of the message payload in bytes. Also use this attribute if it is unknown whether the compressed or uncompressed payload size is reported. + * + * @deprecated Use ATTR_MESSAGING_MESSAGE_BODY_SIZE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES; +/** + * The compressed size of the message payload in bytes. + * + * @deprecated Removed in semconv v1.22.0. + */ +exports.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES; +/** + * A string identifying the kind of message consumption as defined in the [Operation names](#operation-names) section above. If the operation is "send", this attribute MUST NOT be set, since the operation can be inferred from the span kind in that case. + * + * @deprecated Use ATTR_MESSAGING_OPERATION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_MESSAGING_OPERATION = TMP_MESSAGING_OPERATION; +/** + * The identifier for the consumer receiving a message. For Kafka, set it to `{messaging.kafka.consumer_group} - {messaging.kafka.client_id}`, if both are present, or only `messaging.kafka.consumer_group`. For brokers, such as RabbitMQ and Artemis, set it to the `client_id` of the client consuming the message. + * + * @deprecated Removed in semconv v1.21.0. + */ +exports.SEMATTRS_MESSAGING_CONSUMER_ID = TMP_MESSAGING_CONSUMER_ID; +/** + * RabbitMQ message routing key. + * + * @deprecated Use ATTR_MESSAGING_RABBITMQ_DESTINATION_ROUTING_KEY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY = TMP_MESSAGING_RABBITMQ_ROUTING_KEY; +/** + * Message keys in Kafka are used for grouping alike messages to ensure they're processed on the same partition. They differ from `messaging.message_id` in that they're not unique. If the key is `null`, the attribute MUST NOT be set. + * + * Note: If the key type is not string, it's string representation has to be supplied for the attribute. If the key has no unambiguous, canonical string form, don't include its value. + * + * @deprecated Use ATTR_MESSAGING_KAFKA_MESSAGE_KEY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY = TMP_MESSAGING_KAFKA_MESSAGE_KEY; +/** + * Name of the Kafka Consumer Group that is handling the message. Only applies to consumers, not producers. + * + * @deprecated Use ATTR_MESSAGING_KAFKA_CONSUMER_GROUP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP = TMP_MESSAGING_KAFKA_CONSUMER_GROUP; +/** + * Client Id for the Consumer or Producer that is handling the message. + * + * @deprecated Use ATTR_MESSAGING_CLIENT_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_MESSAGING_KAFKA_CLIENT_ID = TMP_MESSAGING_KAFKA_CLIENT_ID; +/** + * Partition the message is sent to. + * + * @deprecated Use ATTR_MESSAGING_KAFKA_DESTINATION_PARTITION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_MESSAGING_KAFKA_PARTITION = TMP_MESSAGING_KAFKA_PARTITION; +/** + * A boolean that is true if the message is a tombstone. + * + * @deprecated Use ATTR_MESSAGING_KAFKA_MESSAGE_TOMBSTONE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_MESSAGING_KAFKA_TOMBSTONE = TMP_MESSAGING_KAFKA_TOMBSTONE; +/** + * A string identifying the remoting system. + * + * @deprecated Use ATTR_RPC_SYSTEM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_RPC_SYSTEM = TMP_RPC_SYSTEM; +/** + * The full (logical) name of the service being called, including its package name, if applicable. + * + * Note: This is the logical name of the service from the RPC interface perspective, which can be different from the name of any implementing class. The `code.namespace` attribute may be used to store the latter (despite the attribute name, it may include a class name; e.g., class with method actually executing the call on the server side, RPC client stub class on the client side). + * + * @deprecated Use ATTR_RPC_SERVICE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_RPC_SERVICE = TMP_RPC_SERVICE; +/** + * The name of the (logical) method being called, must be equal to the $method part in the span name. + * + * Note: This is the logical name of the method from the RPC interface perspective, which can be different from the name of any implementing method/function. The `code.function` attribute may be used to store the latter (e.g., method actually executing the call on the server side, RPC client stub method on the client side). + * + * @deprecated Use ATTR_RPC_METHOD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_RPC_METHOD = TMP_RPC_METHOD; +/** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use ATTR_RPC_GRPC_STATUS_CODE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_RPC_GRPC_STATUS_CODE = TMP_RPC_GRPC_STATUS_CODE; +/** + * Protocol version as in `jsonrpc` property of request/response. Since JSON-RPC 1.0 does not specify this, the value can be omitted. + * + * @deprecated Use ATTR_RPC_JSONRPC_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_RPC_JSONRPC_VERSION = TMP_RPC_JSONRPC_VERSION; +/** + * `id` property of request or response. Since protocol allows id to be int, string, `null` or missing (for notifications), value is expected to be cast to string for simplicity. Use empty string in case of `null` value. Omit entirely if this is a notification. + * + * @deprecated Use ATTR_RPC_JSONRPC_REQUEST_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_RPC_JSONRPC_REQUEST_ID = TMP_RPC_JSONRPC_REQUEST_ID; +/** + * `error.code` property of response if it is an error response. + * + * @deprecated Use ATTR_RPC_JSONRPC_ERROR_CODE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_RPC_JSONRPC_ERROR_CODE = TMP_RPC_JSONRPC_ERROR_CODE; +/** + * `error.message` property of response if it is an error response. + * + * @deprecated Use ATTR_RPC_JSONRPC_ERROR_MESSAGE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE = TMP_RPC_JSONRPC_ERROR_MESSAGE; +/** + * Whether this is a received or sent message. + * + * @deprecated Use ATTR_MESSAGE_TYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_MESSAGE_TYPE = TMP_MESSAGE_TYPE; +/** + * MUST be calculated as two different counters starting from `1` one for sent messages and one for received message. + * + * Note: This way we guarantee that the values will be consistent between different implementations. + * + * @deprecated Use ATTR_MESSAGE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_MESSAGE_ID = TMP_MESSAGE_ID; +/** + * Compressed size of the message in bytes. + * + * @deprecated Use ATTR_MESSAGE_COMPRESSED_SIZE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_MESSAGE_COMPRESSED_SIZE = TMP_MESSAGE_COMPRESSED_SIZE; +/** + * Uncompressed size of the message in bytes. + * + * @deprecated Use ATTR_MESSAGE_UNCOMPRESSED_SIZE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE = TMP_MESSAGE_UNCOMPRESSED_SIZE; +/** + * Create exported Value Map for SemanticAttributes values + * @deprecated Use the SEMATTRS_XXXXX constants rather than the SemanticAttributes.XXXXX for bundle minification + */ +exports.SemanticAttributes = +/*#__PURE__*/ (0, utils_1.createConstMap)([ + TMP_AWS_LAMBDA_INVOKED_ARN, + TMP_DB_SYSTEM, + TMP_DB_CONNECTION_STRING, + TMP_DB_USER, + TMP_DB_JDBC_DRIVER_CLASSNAME, + TMP_DB_NAME, + TMP_DB_STATEMENT, + TMP_DB_OPERATION, + TMP_DB_MSSQL_INSTANCE_NAME, + TMP_DB_CASSANDRA_KEYSPACE, + TMP_DB_CASSANDRA_PAGE_SIZE, + TMP_DB_CASSANDRA_CONSISTENCY_LEVEL, + TMP_DB_CASSANDRA_TABLE, + TMP_DB_CASSANDRA_IDEMPOTENCE, + TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT, + TMP_DB_CASSANDRA_COORDINATOR_ID, + TMP_DB_CASSANDRA_COORDINATOR_DC, + TMP_DB_HBASE_NAMESPACE, + TMP_DB_REDIS_DATABASE_INDEX, + TMP_DB_MONGODB_COLLECTION, + TMP_DB_SQL_TABLE, + TMP_EXCEPTION_TYPE, + TMP_EXCEPTION_MESSAGE, + TMP_EXCEPTION_STACKTRACE, + TMP_EXCEPTION_ESCAPED, + TMP_FAAS_TRIGGER, + TMP_FAAS_EXECUTION, + TMP_FAAS_DOCUMENT_COLLECTION, + TMP_FAAS_DOCUMENT_OPERATION, + TMP_FAAS_DOCUMENT_TIME, + TMP_FAAS_DOCUMENT_NAME, + TMP_FAAS_TIME, + TMP_FAAS_CRON, + TMP_FAAS_COLDSTART, + TMP_FAAS_INVOKED_NAME, + TMP_FAAS_INVOKED_PROVIDER, + TMP_FAAS_INVOKED_REGION, + TMP_NET_TRANSPORT, + TMP_NET_PEER_IP, + TMP_NET_PEER_PORT, + TMP_NET_PEER_NAME, + TMP_NET_HOST_IP, + TMP_NET_HOST_PORT, + TMP_NET_HOST_NAME, + TMP_NET_HOST_CONNECTION_TYPE, + TMP_NET_HOST_CONNECTION_SUBTYPE, + TMP_NET_HOST_CARRIER_NAME, + TMP_NET_HOST_CARRIER_MCC, + TMP_NET_HOST_CARRIER_MNC, + TMP_NET_HOST_CARRIER_ICC, + TMP_PEER_SERVICE, + TMP_ENDUSER_ID, + TMP_ENDUSER_ROLE, + TMP_ENDUSER_SCOPE, + TMP_THREAD_ID, + TMP_THREAD_NAME, + TMP_CODE_FUNCTION, + TMP_CODE_NAMESPACE, + TMP_CODE_FILEPATH, + TMP_CODE_LINENO, + TMP_HTTP_METHOD, + TMP_HTTP_URL, + TMP_HTTP_TARGET, + TMP_HTTP_HOST, + TMP_HTTP_SCHEME, + TMP_HTTP_STATUS_CODE, + TMP_HTTP_FLAVOR, + TMP_HTTP_USER_AGENT, + TMP_HTTP_REQUEST_CONTENT_LENGTH, + TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED, + TMP_HTTP_RESPONSE_CONTENT_LENGTH, + TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED, + TMP_HTTP_SERVER_NAME, + TMP_HTTP_ROUTE, + TMP_HTTP_CLIENT_IP, + TMP_AWS_DYNAMODB_TABLE_NAMES, + TMP_AWS_DYNAMODB_CONSUMED_CAPACITY, + TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS, + TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY, + TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY, + TMP_AWS_DYNAMODB_CONSISTENT_READ, + TMP_AWS_DYNAMODB_PROJECTION, + TMP_AWS_DYNAMODB_LIMIT, + TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET, + TMP_AWS_DYNAMODB_INDEX_NAME, + TMP_AWS_DYNAMODB_SELECT, + TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES, + TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES, + TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE, + TMP_AWS_DYNAMODB_TABLE_COUNT, + TMP_AWS_DYNAMODB_SCAN_FORWARD, + TMP_AWS_DYNAMODB_SEGMENT, + TMP_AWS_DYNAMODB_TOTAL_SEGMENTS, + TMP_AWS_DYNAMODB_COUNT, + TMP_AWS_DYNAMODB_SCANNED_COUNT, + TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS, + TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES, + TMP_MESSAGING_SYSTEM, + TMP_MESSAGING_DESTINATION, + TMP_MESSAGING_DESTINATION_KIND, + TMP_MESSAGING_TEMP_DESTINATION, + TMP_MESSAGING_PROTOCOL, + TMP_MESSAGING_PROTOCOL_VERSION, + TMP_MESSAGING_URL, + TMP_MESSAGING_MESSAGE_ID, + TMP_MESSAGING_CONVERSATION_ID, + TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES, + TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES, + TMP_MESSAGING_OPERATION, + TMP_MESSAGING_CONSUMER_ID, + TMP_MESSAGING_RABBITMQ_ROUTING_KEY, + TMP_MESSAGING_KAFKA_MESSAGE_KEY, + TMP_MESSAGING_KAFKA_CONSUMER_GROUP, + TMP_MESSAGING_KAFKA_CLIENT_ID, + TMP_MESSAGING_KAFKA_PARTITION, + TMP_MESSAGING_KAFKA_TOMBSTONE, + TMP_RPC_SYSTEM, + TMP_RPC_SERVICE, + TMP_RPC_METHOD, + TMP_RPC_GRPC_STATUS_CODE, + TMP_RPC_JSONRPC_VERSION, + TMP_RPC_JSONRPC_REQUEST_ID, + TMP_RPC_JSONRPC_ERROR_CODE, + TMP_RPC_JSONRPC_ERROR_MESSAGE, + TMP_MESSAGE_TYPE, + TMP_MESSAGE_ID, + TMP_MESSAGE_COMPRESSED_SIZE, + TMP_MESSAGE_UNCOMPRESSED_SIZE, +]); +/* ---------------------------------------------------------------------------------------------------------- + * Constant values for DbSystemValues enum definition + * + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * ---------------------------------------------------------------------------------------------------------- */ +// Temporary local constants to assign to the individual exports and the namespaced version +// Required to avoid the namespace exports using the unminifiable export names for some package types +const TMP_DBSYSTEMVALUES_OTHER_SQL = 'other_sql'; +const TMP_DBSYSTEMVALUES_MSSQL = 'mssql'; +const TMP_DBSYSTEMVALUES_MYSQL = 'mysql'; +const TMP_DBSYSTEMVALUES_ORACLE = 'oracle'; +const TMP_DBSYSTEMVALUES_DB2 = 'db2'; +const TMP_DBSYSTEMVALUES_POSTGRESQL = 'postgresql'; +const TMP_DBSYSTEMVALUES_REDSHIFT = 'redshift'; +const TMP_DBSYSTEMVALUES_HIVE = 'hive'; +const TMP_DBSYSTEMVALUES_CLOUDSCAPE = 'cloudscape'; +const TMP_DBSYSTEMVALUES_HSQLDB = 'hsqldb'; +const TMP_DBSYSTEMVALUES_PROGRESS = 'progress'; +const TMP_DBSYSTEMVALUES_MAXDB = 'maxdb'; +const TMP_DBSYSTEMVALUES_HANADB = 'hanadb'; +const TMP_DBSYSTEMVALUES_INGRES = 'ingres'; +const TMP_DBSYSTEMVALUES_FIRSTSQL = 'firstsql'; +const TMP_DBSYSTEMVALUES_EDB = 'edb'; +const TMP_DBSYSTEMVALUES_CACHE = 'cache'; +const TMP_DBSYSTEMVALUES_ADABAS = 'adabas'; +const TMP_DBSYSTEMVALUES_FIREBIRD = 'firebird'; +const TMP_DBSYSTEMVALUES_DERBY = 'derby'; +const TMP_DBSYSTEMVALUES_FILEMAKER = 'filemaker'; +const TMP_DBSYSTEMVALUES_INFORMIX = 'informix'; +const TMP_DBSYSTEMVALUES_INSTANTDB = 'instantdb'; +const TMP_DBSYSTEMVALUES_INTERBASE = 'interbase'; +const TMP_DBSYSTEMVALUES_MARIADB = 'mariadb'; +const TMP_DBSYSTEMVALUES_NETEZZA = 'netezza'; +const TMP_DBSYSTEMVALUES_PERVASIVE = 'pervasive'; +const TMP_DBSYSTEMVALUES_POINTBASE = 'pointbase'; +const TMP_DBSYSTEMVALUES_SQLITE = 'sqlite'; +const TMP_DBSYSTEMVALUES_SYBASE = 'sybase'; +const TMP_DBSYSTEMVALUES_TERADATA = 'teradata'; +const TMP_DBSYSTEMVALUES_VERTICA = 'vertica'; +const TMP_DBSYSTEMVALUES_H2 = 'h2'; +const TMP_DBSYSTEMVALUES_COLDFUSION = 'coldfusion'; +const TMP_DBSYSTEMVALUES_CASSANDRA = 'cassandra'; +const TMP_DBSYSTEMVALUES_HBASE = 'hbase'; +const TMP_DBSYSTEMVALUES_MONGODB = 'mongodb'; +const TMP_DBSYSTEMVALUES_REDIS = 'redis'; +const TMP_DBSYSTEMVALUES_COUCHBASE = 'couchbase'; +const TMP_DBSYSTEMVALUES_COUCHDB = 'couchdb'; +const TMP_DBSYSTEMVALUES_COSMOSDB = 'cosmosdb'; +const TMP_DBSYSTEMVALUES_DYNAMODB = 'dynamodb'; +const TMP_DBSYSTEMVALUES_NEO4J = 'neo4j'; +const TMP_DBSYSTEMVALUES_GEODE = 'geode'; +const TMP_DBSYSTEMVALUES_ELASTICSEARCH = 'elasticsearch'; +const TMP_DBSYSTEMVALUES_MEMCACHED = 'memcached'; +const TMP_DBSYSTEMVALUES_COCKROACHDB = 'cockroachdb'; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_OTHER_SQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_OTHER_SQL = TMP_DBSYSTEMVALUES_OTHER_SQL; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_MSSQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_MSSQL = TMP_DBSYSTEMVALUES_MSSQL; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_MYSQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_MYSQL = TMP_DBSYSTEMVALUES_MYSQL; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_ORACLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_ORACLE = TMP_DBSYSTEMVALUES_ORACLE; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_DB2 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_DB2 = TMP_DBSYSTEMVALUES_DB2; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_POSTGRESQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_POSTGRESQL = TMP_DBSYSTEMVALUES_POSTGRESQL; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_REDSHIFT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_REDSHIFT = TMP_DBSYSTEMVALUES_REDSHIFT; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_HIVE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_HIVE = TMP_DBSYSTEMVALUES_HIVE; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_CLOUDSCAPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_CLOUDSCAPE = TMP_DBSYSTEMVALUES_CLOUDSCAPE; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_HSQLDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_HSQLDB = TMP_DBSYSTEMVALUES_HSQLDB; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_PROGRESS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_PROGRESS = TMP_DBSYSTEMVALUES_PROGRESS; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_MAXDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_MAXDB = TMP_DBSYSTEMVALUES_MAXDB; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_HANADB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_HANADB = TMP_DBSYSTEMVALUES_HANADB; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_INGRES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_INGRES = TMP_DBSYSTEMVALUES_INGRES; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_FIRSTSQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_FIRSTSQL = TMP_DBSYSTEMVALUES_FIRSTSQL; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_EDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_EDB = TMP_DBSYSTEMVALUES_EDB; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_CACHE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_CACHE = TMP_DBSYSTEMVALUES_CACHE; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_ADABAS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_ADABAS = TMP_DBSYSTEMVALUES_ADABAS; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_FIREBIRD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_FIREBIRD = TMP_DBSYSTEMVALUES_FIREBIRD; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_DERBY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_DERBY = TMP_DBSYSTEMVALUES_DERBY; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_FILEMAKER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_FILEMAKER = TMP_DBSYSTEMVALUES_FILEMAKER; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_INFORMIX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_INFORMIX = TMP_DBSYSTEMVALUES_INFORMIX; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_INSTANTDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_INSTANTDB = TMP_DBSYSTEMVALUES_INSTANTDB; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_INTERBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_INTERBASE = TMP_DBSYSTEMVALUES_INTERBASE; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_MARIADB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_MARIADB = TMP_DBSYSTEMVALUES_MARIADB; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_NETEZZA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_NETEZZA = TMP_DBSYSTEMVALUES_NETEZZA; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_PERVASIVE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_PERVASIVE = TMP_DBSYSTEMVALUES_PERVASIVE; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_POINTBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_POINTBASE = TMP_DBSYSTEMVALUES_POINTBASE; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_SQLITE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_SQLITE = TMP_DBSYSTEMVALUES_SQLITE; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_SYBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_SYBASE = TMP_DBSYSTEMVALUES_SYBASE; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_TERADATA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_TERADATA = TMP_DBSYSTEMVALUES_TERADATA; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_VERTICA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_VERTICA = TMP_DBSYSTEMVALUES_VERTICA; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_H2 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_H2 = TMP_DBSYSTEMVALUES_H2; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_COLDFUSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_COLDFUSION = TMP_DBSYSTEMVALUES_COLDFUSION; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_CASSANDRA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_CASSANDRA = TMP_DBSYSTEMVALUES_CASSANDRA; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_HBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_HBASE = TMP_DBSYSTEMVALUES_HBASE; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_MONGODB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_MONGODB = TMP_DBSYSTEMVALUES_MONGODB; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_REDIS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_REDIS = TMP_DBSYSTEMVALUES_REDIS; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_COUCHBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_COUCHBASE = TMP_DBSYSTEMVALUES_COUCHBASE; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_COUCHDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_COUCHDB = TMP_DBSYSTEMVALUES_COUCHDB; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_COSMOSDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_COSMOSDB = TMP_DBSYSTEMVALUES_COSMOSDB; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_DYNAMODB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_DYNAMODB = TMP_DBSYSTEMVALUES_DYNAMODB; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_NEO4J in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_NEO4J = TMP_DBSYSTEMVALUES_NEO4J; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_GEODE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_GEODE = TMP_DBSYSTEMVALUES_GEODE; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_ELASTICSEARCH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_ELASTICSEARCH = TMP_DBSYSTEMVALUES_ELASTICSEARCH; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_MEMCACHED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_MEMCACHED = TMP_DBSYSTEMVALUES_MEMCACHED; +/** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_COCKROACHDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBSYSTEMVALUES_COCKROACHDB = TMP_DBSYSTEMVALUES_COCKROACHDB; +/** + * The constant map of values for DbSystemValues. + * @deprecated Use the DBSYSTEMVALUES_XXXXX constants rather than the DbSystemValues.XXXXX for bundle minification. + */ +exports.DbSystemValues = +/*#__PURE__*/ (0, utils_1.createConstMap)([ + TMP_DBSYSTEMVALUES_OTHER_SQL, + TMP_DBSYSTEMVALUES_MSSQL, + TMP_DBSYSTEMVALUES_MYSQL, + TMP_DBSYSTEMVALUES_ORACLE, + TMP_DBSYSTEMVALUES_DB2, + TMP_DBSYSTEMVALUES_POSTGRESQL, + TMP_DBSYSTEMVALUES_REDSHIFT, + TMP_DBSYSTEMVALUES_HIVE, + TMP_DBSYSTEMVALUES_CLOUDSCAPE, + TMP_DBSYSTEMVALUES_HSQLDB, + TMP_DBSYSTEMVALUES_PROGRESS, + TMP_DBSYSTEMVALUES_MAXDB, + TMP_DBSYSTEMVALUES_HANADB, + TMP_DBSYSTEMVALUES_INGRES, + TMP_DBSYSTEMVALUES_FIRSTSQL, + TMP_DBSYSTEMVALUES_EDB, + TMP_DBSYSTEMVALUES_CACHE, + TMP_DBSYSTEMVALUES_ADABAS, + TMP_DBSYSTEMVALUES_FIREBIRD, + TMP_DBSYSTEMVALUES_DERBY, + TMP_DBSYSTEMVALUES_FILEMAKER, + TMP_DBSYSTEMVALUES_INFORMIX, + TMP_DBSYSTEMVALUES_INSTANTDB, + TMP_DBSYSTEMVALUES_INTERBASE, + TMP_DBSYSTEMVALUES_MARIADB, + TMP_DBSYSTEMVALUES_NETEZZA, + TMP_DBSYSTEMVALUES_PERVASIVE, + TMP_DBSYSTEMVALUES_POINTBASE, + TMP_DBSYSTEMVALUES_SQLITE, + TMP_DBSYSTEMVALUES_SYBASE, + TMP_DBSYSTEMVALUES_TERADATA, + TMP_DBSYSTEMVALUES_VERTICA, + TMP_DBSYSTEMVALUES_H2, + TMP_DBSYSTEMVALUES_COLDFUSION, + TMP_DBSYSTEMVALUES_CASSANDRA, + TMP_DBSYSTEMVALUES_HBASE, + TMP_DBSYSTEMVALUES_MONGODB, + TMP_DBSYSTEMVALUES_REDIS, + TMP_DBSYSTEMVALUES_COUCHBASE, + TMP_DBSYSTEMVALUES_COUCHDB, + TMP_DBSYSTEMVALUES_COSMOSDB, + TMP_DBSYSTEMVALUES_DYNAMODB, + TMP_DBSYSTEMVALUES_NEO4J, + TMP_DBSYSTEMVALUES_GEODE, + TMP_DBSYSTEMVALUES_ELASTICSEARCH, + TMP_DBSYSTEMVALUES_MEMCACHED, + TMP_DBSYSTEMVALUES_COCKROACHDB, +]); +/* ---------------------------------------------------------------------------------------------------------- + * Constant values for DbCassandraConsistencyLevelValues enum definition + * + * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). + * ---------------------------------------------------------------------------------------------------------- */ +// Temporary local constants to assign to the individual exports and the namespaced version +// Required to avoid the namespace exports using the unminifiable export names for some package types +const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL = 'all'; +const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = 'each_quorum'; +const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = 'quorum'; +const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = 'local_quorum'; +const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE = 'one'; +const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO = 'two'; +const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE = 'three'; +const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = 'local_one'; +const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY = 'any'; +const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = 'serial'; +const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = 'local_serial'; +/** + * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). + * + * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_ALL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBCASSANDRACONSISTENCYLEVELVALUES_ALL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL; +/** + * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). + * + * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_EACH_QUORUM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM; +/** + * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). + * + * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_QUORUM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM; +/** + * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). + * + * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_LOCAL_QUORUM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM; +/** + * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). + * + * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_ONE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBCASSANDRACONSISTENCYLEVELVALUES_ONE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE; +/** + * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). + * + * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_TWO in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBCASSANDRACONSISTENCYLEVELVALUES_TWO = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO; +/** + * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). + * + * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_THREE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBCASSANDRACONSISTENCYLEVELVALUES_THREE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE; +/** + * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). + * + * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_LOCAL_ONE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE; +/** + * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). + * + * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_ANY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBCASSANDRACONSISTENCYLEVELVALUES_ANY = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY; +/** + * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). + * + * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_SERIAL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL; +/** + * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). + * + * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_LOCAL_SERIAL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL; +/** + * The constant map of values for DbCassandraConsistencyLevelValues. + * @deprecated Use the DBCASSANDRACONSISTENCYLEVELVALUES_XXXXX constants rather than the DbCassandraConsistencyLevelValues.XXXXX for bundle minification. + */ +exports.DbCassandraConsistencyLevelValues = +/*#__PURE__*/ (0, utils_1.createConstMap)([ + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL, +]); +/* ---------------------------------------------------------------------------------------------------------- + * Constant values for FaasTriggerValues enum definition + * + * Type of the trigger on which the function is executed. + * ---------------------------------------------------------------------------------------------------------- */ +// Temporary local constants to assign to the individual exports and the namespaced version +// Required to avoid the namespace exports using the unminifiable export names for some package types +const TMP_FAASTRIGGERVALUES_DATASOURCE = 'datasource'; +const TMP_FAASTRIGGERVALUES_HTTP = 'http'; +const TMP_FAASTRIGGERVALUES_PUBSUB = 'pubsub'; +const TMP_FAASTRIGGERVALUES_TIMER = 'timer'; +const TMP_FAASTRIGGERVALUES_OTHER = 'other'; +/** + * Type of the trigger on which the function is executed. + * + * @deprecated Use FAAS_TRIGGER_VALUE_DATASOURCE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.FAASTRIGGERVALUES_DATASOURCE = TMP_FAASTRIGGERVALUES_DATASOURCE; +/** + * Type of the trigger on which the function is executed. + * + * @deprecated Use FAAS_TRIGGER_VALUE_HTTP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.FAASTRIGGERVALUES_HTTP = TMP_FAASTRIGGERVALUES_HTTP; +/** + * Type of the trigger on which the function is executed. + * + * @deprecated Use FAAS_TRIGGER_VALUE_PUBSUB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.FAASTRIGGERVALUES_PUBSUB = TMP_FAASTRIGGERVALUES_PUBSUB; +/** + * Type of the trigger on which the function is executed. + * + * @deprecated Use FAAS_TRIGGER_VALUE_TIMER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.FAASTRIGGERVALUES_TIMER = TMP_FAASTRIGGERVALUES_TIMER; +/** + * Type of the trigger on which the function is executed. + * + * @deprecated Use FAAS_TRIGGER_VALUE_OTHER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.FAASTRIGGERVALUES_OTHER = TMP_FAASTRIGGERVALUES_OTHER; +/** + * The constant map of values for FaasTriggerValues. + * @deprecated Use the FAASTRIGGERVALUES_XXXXX constants rather than the FaasTriggerValues.XXXXX for bundle minification. + */ +exports.FaasTriggerValues = +/*#__PURE__*/ (0, utils_1.createConstMap)([ + TMP_FAASTRIGGERVALUES_DATASOURCE, + TMP_FAASTRIGGERVALUES_HTTP, + TMP_FAASTRIGGERVALUES_PUBSUB, + TMP_FAASTRIGGERVALUES_TIMER, + TMP_FAASTRIGGERVALUES_OTHER, +]); +/* ---------------------------------------------------------------------------------------------------------- + * Constant values for FaasDocumentOperationValues enum definition + * + * Describes the type of the operation that was performed on the data. + * ---------------------------------------------------------------------------------------------------------- */ +// Temporary local constants to assign to the individual exports and the namespaced version +// Required to avoid the namespace exports using the unminifiable export names for some package types +const TMP_FAASDOCUMENTOPERATIONVALUES_INSERT = 'insert'; +const TMP_FAASDOCUMENTOPERATIONVALUES_EDIT = 'edit'; +const TMP_FAASDOCUMENTOPERATIONVALUES_DELETE = 'delete'; +/** + * Describes the type of the operation that was performed on the data. + * + * @deprecated Use FAAS_DOCUMENT_OPERATION_VALUE_INSERT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.FAASDOCUMENTOPERATIONVALUES_INSERT = TMP_FAASDOCUMENTOPERATIONVALUES_INSERT; +/** + * Describes the type of the operation that was performed on the data. + * + * @deprecated Use FAAS_DOCUMENT_OPERATION_VALUE_EDIT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.FAASDOCUMENTOPERATIONVALUES_EDIT = TMP_FAASDOCUMENTOPERATIONVALUES_EDIT; +/** + * Describes the type of the operation that was performed on the data. + * + * @deprecated Use FAAS_DOCUMENT_OPERATION_VALUE_DELETE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.FAASDOCUMENTOPERATIONVALUES_DELETE = TMP_FAASDOCUMENTOPERATIONVALUES_DELETE; +/** + * The constant map of values for FaasDocumentOperationValues. + * @deprecated Use the FAASDOCUMENTOPERATIONVALUES_XXXXX constants rather than the FaasDocumentOperationValues.XXXXX for bundle minification. + */ +exports.FaasDocumentOperationValues = +/*#__PURE__*/ (0, utils_1.createConstMap)([ + TMP_FAASDOCUMENTOPERATIONVALUES_INSERT, + TMP_FAASDOCUMENTOPERATIONVALUES_EDIT, + TMP_FAASDOCUMENTOPERATIONVALUES_DELETE, +]); +/* ---------------------------------------------------------------------------------------------------------- + * Constant values for FaasInvokedProviderValues enum definition + * + * The cloud provider of the invoked function. + * + * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function. + * ---------------------------------------------------------------------------------------------------------- */ +// Temporary local constants to assign to the individual exports and the namespaced version +// Required to avoid the namespace exports using the unminifiable export names for some package types +const TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = 'alibaba_cloud'; +const TMP_FAASINVOKEDPROVIDERVALUES_AWS = 'aws'; +const TMP_FAASINVOKEDPROVIDERVALUES_AZURE = 'azure'; +const TMP_FAASINVOKEDPROVIDERVALUES_GCP = 'gcp'; +/** + * The cloud provider of the invoked function. + * + * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function. + * + * @deprecated Use FAAS_INVOKED_PROVIDER_VALUE_ALIBABA_CLOUD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD; +/** + * The cloud provider of the invoked function. + * + * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function. + * + * @deprecated Use FAAS_INVOKED_PROVIDER_VALUE_AWS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.FAASINVOKEDPROVIDERVALUES_AWS = TMP_FAASINVOKEDPROVIDERVALUES_AWS; +/** + * The cloud provider of the invoked function. + * + * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function. + * + * @deprecated Use FAAS_INVOKED_PROVIDER_VALUE_AZURE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.FAASINVOKEDPROVIDERVALUES_AZURE = TMP_FAASINVOKEDPROVIDERVALUES_AZURE; +/** + * The cloud provider of the invoked function. + * + * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function. + * + * @deprecated Use FAAS_INVOKED_PROVIDER_VALUE_GCP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.FAASINVOKEDPROVIDERVALUES_GCP = TMP_FAASINVOKEDPROVIDERVALUES_GCP; +/** + * The constant map of values for FaasInvokedProviderValues. + * @deprecated Use the FAASINVOKEDPROVIDERVALUES_XXXXX constants rather than the FaasInvokedProviderValues.XXXXX for bundle minification. + */ +exports.FaasInvokedProviderValues = +/*#__PURE__*/ (0, utils_1.createConstMap)([ + TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD, + TMP_FAASINVOKEDPROVIDERVALUES_AWS, + TMP_FAASINVOKEDPROVIDERVALUES_AZURE, + TMP_FAASINVOKEDPROVIDERVALUES_GCP, +]); +/* ---------------------------------------------------------------------------------------------------------- + * Constant values for NetTransportValues enum definition + * + * Transport protocol used. See note below. + * ---------------------------------------------------------------------------------------------------------- */ +// Temporary local constants to assign to the individual exports and the namespaced version +// Required to avoid the namespace exports using the unminifiable export names for some package types +const TMP_NETTRANSPORTVALUES_IP_TCP = 'ip_tcp'; +const TMP_NETTRANSPORTVALUES_IP_UDP = 'ip_udp'; +const TMP_NETTRANSPORTVALUES_IP = 'ip'; +const TMP_NETTRANSPORTVALUES_UNIX = 'unix'; +const TMP_NETTRANSPORTVALUES_PIPE = 'pipe'; +const TMP_NETTRANSPORTVALUES_INPROC = 'inproc'; +const TMP_NETTRANSPORTVALUES_OTHER = 'other'; +/** + * Transport protocol used. See note below. + * + * @deprecated Use NET_TRANSPORT_VALUE_IP_TCP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.NETTRANSPORTVALUES_IP_TCP = TMP_NETTRANSPORTVALUES_IP_TCP; +/** + * Transport protocol used. See note below. + * + * @deprecated Use NET_TRANSPORT_VALUE_IP_UDP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.NETTRANSPORTVALUES_IP_UDP = TMP_NETTRANSPORTVALUES_IP_UDP; +/** + * Transport protocol used. See note below. + * + * @deprecated Removed in v1.21.0. + */ +exports.NETTRANSPORTVALUES_IP = TMP_NETTRANSPORTVALUES_IP; +/** + * Transport protocol used. See note below. + * + * @deprecated Removed in v1.21.0. + */ +exports.NETTRANSPORTVALUES_UNIX = TMP_NETTRANSPORTVALUES_UNIX; +/** + * Transport protocol used. See note below. + * + * @deprecated Use NET_TRANSPORT_VALUE_PIPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.NETTRANSPORTVALUES_PIPE = TMP_NETTRANSPORTVALUES_PIPE; +/** + * Transport protocol used. See note below. + * + * @deprecated Use NET_TRANSPORT_VALUE_INPROC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.NETTRANSPORTVALUES_INPROC = TMP_NETTRANSPORTVALUES_INPROC; +/** + * Transport protocol used. See note below. + * + * @deprecated Use NET_TRANSPORT_VALUE_OTHER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.NETTRANSPORTVALUES_OTHER = TMP_NETTRANSPORTVALUES_OTHER; +/** + * The constant map of values for NetTransportValues. + * @deprecated Use the NETTRANSPORTVALUES_XXXXX constants rather than the NetTransportValues.XXXXX for bundle minification. + */ +exports.NetTransportValues = +/*#__PURE__*/ (0, utils_1.createConstMap)([ + TMP_NETTRANSPORTVALUES_IP_TCP, + TMP_NETTRANSPORTVALUES_IP_UDP, + TMP_NETTRANSPORTVALUES_IP, + TMP_NETTRANSPORTVALUES_UNIX, + TMP_NETTRANSPORTVALUES_PIPE, + TMP_NETTRANSPORTVALUES_INPROC, + TMP_NETTRANSPORTVALUES_OTHER, +]); +/* ---------------------------------------------------------------------------------------------------------- + * Constant values for NetHostConnectionTypeValues enum definition + * + * The internet connection type currently being used by the host. + * ---------------------------------------------------------------------------------------------------------- */ +// Temporary local constants to assign to the individual exports and the namespaced version +// Required to avoid the namespace exports using the unminifiable export names for some package types +const TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI = 'wifi'; +const TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED = 'wired'; +const TMP_NETHOSTCONNECTIONTYPEVALUES_CELL = 'cell'; +const TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = 'unavailable'; +const TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = 'unknown'; +/** + * The internet connection type currently being used by the host. + * + * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_WIFI in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.NETHOSTCONNECTIONTYPEVALUES_WIFI = TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI; +/** + * The internet connection type currently being used by the host. + * + * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_WIRED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.NETHOSTCONNECTIONTYPEVALUES_WIRED = TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED; +/** + * The internet connection type currently being used by the host. + * + * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_CELL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.NETHOSTCONNECTIONTYPEVALUES_CELL = TMP_NETHOSTCONNECTIONTYPEVALUES_CELL; +/** + * The internet connection type currently being used by the host. + * + * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_UNAVAILABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE; +/** + * The internet connection type currently being used by the host. + * + * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_UNKNOWN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN; +/** + * The constant map of values for NetHostConnectionTypeValues. + * @deprecated Use the NETHOSTCONNECTIONTYPEVALUES_XXXXX constants rather than the NetHostConnectionTypeValues.XXXXX for bundle minification. + */ +exports.NetHostConnectionTypeValues = +/*#__PURE__*/ (0, utils_1.createConstMap)([ + TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI, + TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED, + TMP_NETHOSTCONNECTIONTYPEVALUES_CELL, + TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE, + TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN, +]); +/* ---------------------------------------------------------------------------------------------------------- + * Constant values for NetHostConnectionSubtypeValues enum definition + * + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * ---------------------------------------------------------------------------------------------------------- */ +// Temporary local constants to assign to the individual exports and the namespaced version +// Required to avoid the namespace exports using the unminifiable export names for some package types +const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = 'gprs'; +const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = 'edge'; +const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = 'umts'; +const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = 'cdma'; +const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = 'evdo_0'; +const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = 'evdo_a'; +const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = 'cdma2000_1xrtt'; +const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = 'hsdpa'; +const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = 'hsupa'; +const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = 'hspa'; +const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = 'iden'; +const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = 'evdo_b'; +const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE = 'lte'; +const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = 'ehrpd'; +const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = 'hspap'; +const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM = 'gsm'; +const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = 'td_scdma'; +const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = 'iwlan'; +const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR = 'nr'; +const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = 'nrnsa'; +const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = 'lte_ca'; +/** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_GPRS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS; +/** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EDGE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE; +/** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_UMTS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS; +/** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_CDMA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA; +/** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EVDO_0 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0; +/** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EVDO_A in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A; +/** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_CDMA2000_1XRTT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT; +/** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_HSDPA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA; +/** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_HSUPA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA; +/** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_HSPA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA; +/** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_IDEN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN; +/** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EVDO_B in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B; +/** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_LTE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.NETHOSTCONNECTIONSUBTYPEVALUES_LTE = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE; +/** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EHRPD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD; +/** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_HSPAP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP; +/** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_GSM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.NETHOSTCONNECTIONSUBTYPEVALUES_GSM = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM; +/** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_TD_SCDMA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA; +/** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_IWLAN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN; +/** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_NR in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.NETHOSTCONNECTIONSUBTYPEVALUES_NR = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR; +/** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_NRNSA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA; +/** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_LTE_CA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA; +/** + * The constant map of values for NetHostConnectionSubtypeValues. + * @deprecated Use the NETHOSTCONNECTIONSUBTYPEVALUES_XXXXX constants rather than the NetHostConnectionSubtypeValues.XXXXX for bundle minification. + */ +exports.NetHostConnectionSubtypeValues = +/*#__PURE__*/ (0, utils_1.createConstMap)([ + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA, +]); +/* ---------------------------------------------------------------------------------------------------------- + * Constant values for HttpFlavorValues enum definition + * + * Kind of HTTP protocol used. + * + * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. + * ---------------------------------------------------------------------------------------------------------- */ +// Temporary local constants to assign to the individual exports and the namespaced version +// Required to avoid the namespace exports using the unminifiable export names for some package types +const TMP_HTTPFLAVORVALUES_HTTP_1_0 = '1.0'; +const TMP_HTTPFLAVORVALUES_HTTP_1_1 = '1.1'; +const TMP_HTTPFLAVORVALUES_HTTP_2_0 = '2.0'; +const TMP_HTTPFLAVORVALUES_SPDY = 'SPDY'; +const TMP_HTTPFLAVORVALUES_QUIC = 'QUIC'; +/** + * Kind of HTTP protocol used. + * + * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. + * + * @deprecated Use HTTP_FLAVOR_VALUE_HTTP_1_0 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.HTTPFLAVORVALUES_HTTP_1_0 = TMP_HTTPFLAVORVALUES_HTTP_1_0; +/** + * Kind of HTTP protocol used. + * + * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. + * + * @deprecated Use HTTP_FLAVOR_VALUE_HTTP_1_1 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.HTTPFLAVORVALUES_HTTP_1_1 = TMP_HTTPFLAVORVALUES_HTTP_1_1; +/** + * Kind of HTTP protocol used. + * + * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. + * + * @deprecated Use HTTP_FLAVOR_VALUE_HTTP_2_0 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.HTTPFLAVORVALUES_HTTP_2_0 = TMP_HTTPFLAVORVALUES_HTTP_2_0; +/** + * Kind of HTTP protocol used. + * + * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. + * + * @deprecated Use HTTP_FLAVOR_VALUE_SPDY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.HTTPFLAVORVALUES_SPDY = TMP_HTTPFLAVORVALUES_SPDY; +/** + * Kind of HTTP protocol used. + * + * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. + * + * @deprecated Use HTTP_FLAVOR_VALUE_QUIC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.HTTPFLAVORVALUES_QUIC = TMP_HTTPFLAVORVALUES_QUIC; +/** + * The constant map of values for HttpFlavorValues. + * @deprecated Use the HTTPFLAVORVALUES_XXXXX constants rather than the HttpFlavorValues.XXXXX for bundle minification. + */ +exports.HttpFlavorValues = { + HTTP_1_0: TMP_HTTPFLAVORVALUES_HTTP_1_0, + HTTP_1_1: TMP_HTTPFLAVORVALUES_HTTP_1_1, + HTTP_2_0: TMP_HTTPFLAVORVALUES_HTTP_2_0, + SPDY: TMP_HTTPFLAVORVALUES_SPDY, + QUIC: TMP_HTTPFLAVORVALUES_QUIC, +}; +/* ---------------------------------------------------------------------------------------------------------- + * Constant values for MessagingDestinationKindValues enum definition + * + * The kind of message destination. + * ---------------------------------------------------------------------------------------------------------- */ +// Temporary local constants to assign to the individual exports and the namespaced version +// Required to avoid the namespace exports using the unminifiable export names for some package types +const TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE = 'queue'; +const TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC = 'topic'; +/** + * The kind of message destination. + * + * @deprecated Removed in semconv v1.20.0. + */ +exports.MESSAGINGDESTINATIONKINDVALUES_QUEUE = TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE; +/** + * The kind of message destination. + * + * @deprecated Removed in semconv v1.20.0. + */ +exports.MESSAGINGDESTINATIONKINDVALUES_TOPIC = TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC; +/** + * The constant map of values for MessagingDestinationKindValues. + * @deprecated Use the MESSAGINGDESTINATIONKINDVALUES_XXXXX constants rather than the MessagingDestinationKindValues.XXXXX for bundle minification. + */ +exports.MessagingDestinationKindValues = +/*#__PURE__*/ (0, utils_1.createConstMap)([ + TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE, + TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC, +]); +/* ---------------------------------------------------------------------------------------------------------- + * Constant values for MessagingOperationValues enum definition + * + * A string identifying the kind of message consumption as defined in the [Operation names](#operation-names) section above. If the operation is "send", this attribute MUST NOT be set, since the operation can be inferred from the span kind in that case. + * ---------------------------------------------------------------------------------------------------------- */ +// Temporary local constants to assign to the individual exports and the namespaced version +// Required to avoid the namespace exports using the unminifiable export names for some package types +const TMP_MESSAGINGOPERATIONVALUES_RECEIVE = 'receive'; +const TMP_MESSAGINGOPERATIONVALUES_PROCESS = 'process'; +/** + * A string identifying the kind of message consumption as defined in the [Operation names](#operation-names) section above. If the operation is "send", this attribute MUST NOT be set, since the operation can be inferred from the span kind in that case. + * + * @deprecated Use MESSAGING_OPERATION_TYPE_VALUE_RECEIVE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.MESSAGINGOPERATIONVALUES_RECEIVE = TMP_MESSAGINGOPERATIONVALUES_RECEIVE; +/** + * A string identifying the kind of message consumption as defined in the [Operation names](#operation-names) section above. If the operation is "send", this attribute MUST NOT be set, since the operation can be inferred from the span kind in that case. + * + * @deprecated Use MESSAGING_OPERATION_TYPE_VALUE_PROCESS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.MESSAGINGOPERATIONVALUES_PROCESS = TMP_MESSAGINGOPERATIONVALUES_PROCESS; +/** + * The constant map of values for MessagingOperationValues. + * @deprecated Use the MESSAGINGOPERATIONVALUES_XXXXX constants rather than the MessagingOperationValues.XXXXX for bundle minification. + */ +exports.MessagingOperationValues = +/*#__PURE__*/ (0, utils_1.createConstMap)([ + TMP_MESSAGINGOPERATIONVALUES_RECEIVE, + TMP_MESSAGINGOPERATIONVALUES_PROCESS, +]); +/* ---------------------------------------------------------------------------------------------------------- + * Constant values for RpcGrpcStatusCodeValues enum definition + * + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * ---------------------------------------------------------------------------------------------------------- */ +// Temporary local constants to assign to the individual exports and the namespaced version +// Required to avoid the namespace exports using the unminifiable export names for some package types +const TMP_RPCGRPCSTATUSCODEVALUES_OK = 0; +const TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED = 1; +const TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN = 2; +const TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = 3; +const TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = 4; +const TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND = 5; +const TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = 6; +const TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = 7; +const TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = 8; +const TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = 9; +const TMP_RPCGRPCSTATUSCODEVALUES_ABORTED = 10; +const TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = 11; +const TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = 12; +const TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL = 13; +const TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = 14; +const TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS = 15; +const TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = 16; +/** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_OK in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.RPCGRPCSTATUSCODEVALUES_OK = TMP_RPCGRPCSTATUSCODEVALUES_OK; +/** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_CANCELLED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.RPCGRPCSTATUSCODEVALUES_CANCELLED = TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED; +/** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_UNKNOWN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.RPCGRPCSTATUSCODEVALUES_UNKNOWN = TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN; +/** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_INVALID_ARGUMENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT; +/** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_DEADLINE_EXCEEDED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED; +/** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_NOT_FOUND in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.RPCGRPCSTATUSCODEVALUES_NOT_FOUND = TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND; +/** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_ALREADY_EXISTS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS; +/** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_PERMISSION_DENIED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED; +/** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_RESOURCE_EXHAUSTED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED; +/** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_FAILED_PRECONDITION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION; +/** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_ABORTED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.RPCGRPCSTATUSCODEVALUES_ABORTED = TMP_RPCGRPCSTATUSCODEVALUES_ABORTED; +/** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_OUT_OF_RANGE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE; +/** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_UNIMPLEMENTED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED; +/** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_INTERNAL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.RPCGRPCSTATUSCODEVALUES_INTERNAL = TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL; +/** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_UNAVAILABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE; +/** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_DATA_LOSS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.RPCGRPCSTATUSCODEVALUES_DATA_LOSS = TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS; +/** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_UNAUTHENTICATED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED; +/** + * The constant map of values for RpcGrpcStatusCodeValues. + * @deprecated Use the RPCGRPCSTATUSCODEVALUES_XXXXX constants rather than the RpcGrpcStatusCodeValues.XXXXX for bundle minification. + */ +exports.RpcGrpcStatusCodeValues = { + OK: TMP_RPCGRPCSTATUSCODEVALUES_OK, + CANCELLED: TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED, + UNKNOWN: TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN, + INVALID_ARGUMENT: TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT, + DEADLINE_EXCEEDED: TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED, + NOT_FOUND: TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND, + ALREADY_EXISTS: TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS, + PERMISSION_DENIED: TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED, + RESOURCE_EXHAUSTED: TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED, + FAILED_PRECONDITION: TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION, + ABORTED: TMP_RPCGRPCSTATUSCODEVALUES_ABORTED, + OUT_OF_RANGE: TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE, + UNIMPLEMENTED: TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED, + INTERNAL: TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL, + UNAVAILABLE: TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE, + DATA_LOSS: TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS, + UNAUTHENTICATED: TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED, +}; +/* ---------------------------------------------------------------------------------------------------------- + * Constant values for MessageTypeValues enum definition + * + * Whether this is a received or sent message. + * ---------------------------------------------------------------------------------------------------------- */ +// Temporary local constants to assign to the individual exports and the namespaced version +// Required to avoid the namespace exports using the unminifiable export names for some package types +const TMP_MESSAGETYPEVALUES_SENT = 'SENT'; +const TMP_MESSAGETYPEVALUES_RECEIVED = 'RECEIVED'; +/** + * Whether this is a received or sent message. + * + * @deprecated Use MESSAGE_TYPE_VALUE_SENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.MESSAGETYPEVALUES_SENT = TMP_MESSAGETYPEVALUES_SENT; +/** + * Whether this is a received or sent message. + * + * @deprecated Use MESSAGE_TYPE_VALUE_RECEIVED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ +exports.MESSAGETYPEVALUES_RECEIVED = TMP_MESSAGETYPEVALUES_RECEIVED; +/** + * The constant map of values for MessageTypeValues. + * @deprecated Use the MESSAGETYPEVALUES_XXXXX constants rather than the MessageTypeValues.XXXXX for bundle minification. + */ +exports.MessageTypeValues = +/*#__PURE__*/ (0, utils_1.createConstMap)([ + TMP_MESSAGETYPEVALUES_SENT, + TMP_MESSAGETYPEVALUES_RECEIVED, +]); +//# sourceMappingURL=SemanticAttributes.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/trace/index.js b/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/trace/index.js new file mode 100644 index 00000000..19370d56 --- /dev/null +++ b/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/trace/index.js @@ -0,0 +1,37 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +/* eslint-disable no-restricted-syntax -- + * These re-exports are only of constants, only one-level deep at this point, + * and should not cause problems for tree-shakers. + */ +__exportStar(require("./SemanticAttributes"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@pondwader/socks5-server/dist/index.js b/claude-code-source/node_modules/@pondwader/socks5-server/dist/index.js new file mode 100644 index 00000000..51696e58 --- /dev/null +++ b/claude-code-source/node_modules/@pondwader/socks5-server/dist/index.js @@ -0,0 +1,346 @@ +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + Socks5Server: () => Socks5Server, + createServer: () => createServer, + defaultConnectionHandler: () => connectionHandler_default +}); +module.exports = __toCommonJS(src_exports); + +// src/Server.ts +var import_net2 = __toESM(require("net")); + +// src/types.ts +var Socks5ConnectionCommand = /* @__PURE__ */ ((Socks5ConnectionCommand2) => { + Socks5ConnectionCommand2[Socks5ConnectionCommand2["connect"] = 1] = "connect"; + Socks5ConnectionCommand2[Socks5ConnectionCommand2["bind"] = 2] = "bind"; + Socks5ConnectionCommand2[Socks5ConnectionCommand2["udp"] = 3] = "udp"; + return Socks5ConnectionCommand2; +})(Socks5ConnectionCommand || {}); +var Socks5ConnectionStatus = /* @__PURE__ */ ((Socks5ConnectionStatus2) => { + Socks5ConnectionStatus2[Socks5ConnectionStatus2["REQUEST_GRANTED"] = 0] = "REQUEST_GRANTED"; + Socks5ConnectionStatus2[Socks5ConnectionStatus2["GENERAL_FAILURE"] = 1] = "GENERAL_FAILURE"; + Socks5ConnectionStatus2[Socks5ConnectionStatus2["CONNECTION_NOT_ALLOWED"] = 2] = "CONNECTION_NOT_ALLOWED"; + Socks5ConnectionStatus2[Socks5ConnectionStatus2["NETWORK_UNREACHABLE"] = 3] = "NETWORK_UNREACHABLE"; + Socks5ConnectionStatus2[Socks5ConnectionStatus2["HOST_UNREACHABLE"] = 4] = "HOST_UNREACHABLE"; + Socks5ConnectionStatus2[Socks5ConnectionStatus2["CONNECTION_REFUSED"] = 5] = "CONNECTION_REFUSED"; + Socks5ConnectionStatus2[Socks5ConnectionStatus2["TTL_EXPIRED"] = 6] = "TTL_EXPIRED"; + Socks5ConnectionStatus2[Socks5ConnectionStatus2["COMMAND_NOT_SUPPORTED"] = 7] = "COMMAND_NOT_SUPPORTED"; + Socks5ConnectionStatus2[Socks5ConnectionStatus2["ADDRESS_TYPE_NOT_SUPPORTED"] = 8] = "ADDRESS_TYPE_NOT_SUPPORTED"; + return Socks5ConnectionStatus2; +})(Socks5ConnectionStatus || {}); + +// src/Connection.ts +var Socks5Connection = class { + constructor(server, socket) { + this.errorHandler = () => { + }; + this.metadata = {}; + this.socket = socket; + this.server = server; + socket.on("error", this.errorHandler); + socket.pause(); + this.handleGreeting(); + } + readBytes(len) { + return new Promise((resolve) => { + let buf = Buffer.allocUnsafe(len); + let offset = 0; + const dataListener = (chunk) => { + const readAmount = Math.min(chunk.length, len - offset); + chunk.copy(buf, offset, 0, readAmount); + offset += readAmount; + if (offset < len) return; + this.socket.removeListener("data", dataListener); + this.socket.push(chunk.subarray(readAmount)); + resolve(buf); + this.socket.pause(); + }; + this.socket.on("data", dataListener); + this.socket.resume(); + }); + } + async handleGreeting() { + const ver = (await this.readBytes(1)).readUInt8(); + if (ver !== 5) return this.socket.destroy(); + const authMethodsAmount = (await this.readBytes(1)).readUInt8(); + if (authMethodsAmount > 128 || authMethodsAmount === 0) return this.socket.destroy(); + const authMethods = await this.readBytes(authMethodsAmount); + const authMethodByteCode = this.server.authHandler ? 2 : 0; + if (!authMethods.includes(authMethodByteCode)) { + this.socket.write(Buffer.from([ + 5, + // Version 5 - Socks5 + 255 + // no acceptable auth modes were offered + ])); + return this.socket.destroy(); + } + this.socket.write(Buffer.from([ + 5, + // Version 5 - Socks5 + authMethodByteCode + // The chosen auth method, 0x00 for no auth, 0x02 for user-pass + ])); + if (this.server.authHandler) this.handleUserPassword(); + else this.handleConnectionRequest(); + } + async handleUserPassword() { + await this.readBytes(1); + const usernameLength = (await this.readBytes(1)).readUint8(); + const username = (await this.readBytes(usernameLength)).toString(); + const passwordLength = (await this.readBytes(1)).readUint8(); + const password = (await this.readBytes(passwordLength)).toString(); + this.username = username; + this.password = password; + let calledBack = false; + const acceptCallback = () => { + if (calledBack) return; + calledBack = true; + this.socket.write(Buffer.from([ + 1, + // User pass auth version + 0 + // Success + ])); + this.handleConnectionRequest(); + }; + const denyCallback = () => { + if (calledBack) return; + calledBack = true; + this.socket.write(Buffer.from([ + 1, + // User pass auth version + 1 + // Failure + ])); + this.socket.destroy(); + }; + const resp = await this.server.authHandler(this, acceptCallback, denyCallback); + if (resp === true) acceptCallback(); + else if (resp === false) denyCallback(); + } + async handleConnectionRequest() { + await this.readBytes(1); + const commandByte = (await this.readBytes(1))[0]; + const command = Socks5ConnectionCommand[commandByte]; + if (!command) return this.socket.destroy(); + this.command = command; + await this.readBytes(1); + const addrType = (await this.readBytes(1)).readUInt8(); + let address = ""; + switch (addrType) { + case 1: + address = (await this.readBytes(4)).join("."); + break; + case 3: + const hostLength = (await this.readBytes(1)).readUInt8(); + address = (await this.readBytes(hostLength)).toString(); + break; + case 4: + const bytes = await this.readBytes(16); + for (let i = 0; i < 16; i++) { + if (i % 2 === 0 && i > 0) address += ":"; + address += `${bytes[i] < 16 ? "0" : ""}${bytes[i].toString(16)}`; + } + break; + default: + this.socket.destroy(); + return; + } + const port = (await this.readBytes(2)).readUInt16BE(); + if (!this.server.supportedCommands.has(command)) { + this.socket.write(Buffer.from([5, 7 /* COMMAND_NOT_SUPPORTED */])); + return this.socket.destroy(); + } + this.destAddress = address; + this.destPort = port; + let calledBack = false; + const acceptCallback = () => { + if (calledBack) return; + calledBack = true; + this.connect(); + }; + if (!this.server.rulesetValidator) return acceptCallback(); + const denyCallback = () => { + if (calledBack) return; + calledBack = true; + this.socket.write(Buffer.from([ + 5, + 2, + // connection not allowed by ruleset + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0 + ])); + this.socket.destroy(); + }; + const resp = await this.server.rulesetValidator(this, acceptCallback, denyCallback); + if (resp === true) acceptCallback(); + else if (resp === false) denyCallback(); + } + connect() { + this.socket.removeListener("error", this.errorHandler); + this.server.connectionHandler(this, (status) => { + if (Socks5ConnectionStatus[status] === void 0) throw new Error(`"${status}" is not a valid status.`); + this.socket.write(Buffer.from([ + 5, + Socks5ConnectionStatus[status], + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0 + ])); + if (status !== "REQUEST_GRANTED") { + this.socket.destroy(); + } + }); + this.socket.resume(); + } +}; + +// src/connectionHandler.ts +var import_net = __toESM(require("net")); +function connectionHandler_default(connection, sendStatus) { + if (connection.command !== "connect") return sendStatus("COMMAND_NOT_SUPPORTED"); + connection.socket.on("error", () => { + }); + const stream = import_net.default.createConnection({ + host: connection.destAddress, + port: connection.destPort + }); + stream.setNoDelay(); + let streamOpened = false; + stream.on("error", (err) => { + if (!streamOpened) { + switch (err.code) { + case "EINVAL": + case "ENOENT": + case "ENOTFOUND": + case "ETIMEDOUT": + case "EADDRNOTAVAIL": + case "EHOSTUNREACH": + sendStatus("HOST_UNREACHABLE"); + break; + case "ENETUNREACH": + sendStatus("NETWORK_UNREACHABLE"); + break; + case "ECONNREFUSED": + sendStatus("CONNECTION_REFUSED"); + break; + default: + sendStatus("GENERAL_FAILURE"); + } + } + }); + stream.on("ready", () => { + streamOpened = true; + sendStatus("REQUEST_GRANTED"); + connection.socket.pipe(stream).pipe(connection.socket); + }); + connection.socket.on("close", () => stream.destroy()); + return stream; +} + +// src/Server.ts +var Socks5Server = class { + constructor() { + this.supportedCommands = /* @__PURE__ */ new Set(["connect"]); + this.connectionHandler = connectionHandler_default; + this.server = import_net2.default.createServer((socket) => { + socket.setNoDelay(); + this._handleConnection(socket); + }); + } + listen(...args) { + this.server.listen(...args); + return this; + } + close(callback) { + this.server.close(callback); + return this; + } + setAuthHandler(handler) { + this.authHandler = handler; + return this; + } + disableAuthHandler() { + this.authHandler = void 0; + return this; + } + setRulesetValidator(handler) { + this.rulesetValidator = handler; + return this; + } + disableRulesetValidator() { + this.rulesetValidator = void 0; + return this; + } + setConnectionHandler(handler) { + this.connectionHandler = handler; + return this; + } + useDefaultConnectionHandler() { + this.connectionHandler = connectionHandler_default; + return this; + } + // Not private because someone may want to inject a duplex stream to be handled as a connection + _handleConnection(socket) { + new Socks5Connection(this, socket); + return this; + } +}; + +// src/index.ts +function createServer(opts) { + const server = new Socks5Server(); + if (opts?.auth) server.setAuthHandler((conn) => { + return conn.username === opts.auth.username && conn.password === opts.auth.password; + }); + if (opts?.port) server.listen(opts.port, opts.hostname); + return server; +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + Socks5Server, + createServer, + defaultConnectionHandler +}); diff --git a/claude-code-source/node_modules/@smithy/config-resolver/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/config-resolver/dist-cjs/index.js new file mode 100644 index 00000000..4703cff7 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/config-resolver/dist-cjs/index.js @@ -0,0 +1,186 @@ +'use strict'; + +var utilConfigProvider = require('@smithy/util-config-provider'); +var utilMiddleware = require('@smithy/util-middleware'); +var utilEndpoints = require('@smithy/util-endpoints'); + +const ENV_USE_DUALSTACK_ENDPOINT = "AWS_USE_DUALSTACK_ENDPOINT"; +const CONFIG_USE_DUALSTACK_ENDPOINT = "use_dualstack_endpoint"; +const DEFAULT_USE_DUALSTACK_ENDPOINT = false; +const NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => utilConfigProvider.booleanSelector(env, ENV_USE_DUALSTACK_ENDPOINT, utilConfigProvider.SelectorType.ENV), + configFileSelector: (profile) => utilConfigProvider.booleanSelector(profile, CONFIG_USE_DUALSTACK_ENDPOINT, utilConfigProvider.SelectorType.CONFIG), + default: false, +}; + +const ENV_USE_FIPS_ENDPOINT = "AWS_USE_FIPS_ENDPOINT"; +const CONFIG_USE_FIPS_ENDPOINT = "use_fips_endpoint"; +const DEFAULT_USE_FIPS_ENDPOINT = false; +const NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => utilConfigProvider.booleanSelector(env, ENV_USE_FIPS_ENDPOINT, utilConfigProvider.SelectorType.ENV), + configFileSelector: (profile) => utilConfigProvider.booleanSelector(profile, CONFIG_USE_FIPS_ENDPOINT, utilConfigProvider.SelectorType.CONFIG), + default: false, +}; + +const resolveCustomEndpointsConfig = (input) => { + const { tls, endpoint, urlParser, useDualstackEndpoint } = input; + return Object.assign(input, { + tls: tls ?? true, + endpoint: utilMiddleware.normalizeProvider(typeof endpoint === "string" ? urlParser(endpoint) : endpoint), + isCustomEndpoint: true, + useDualstackEndpoint: utilMiddleware.normalizeProvider(useDualstackEndpoint ?? false), + }); +}; + +const getEndpointFromRegion = async (input) => { + const { tls = true } = input; + const region = await input.region(); + const dnsHostRegex = new RegExp(/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])$/); + if (!dnsHostRegex.test(region)) { + throw new Error("Invalid region in client config"); + } + const useDualstackEndpoint = await input.useDualstackEndpoint(); + const useFipsEndpoint = await input.useFipsEndpoint(); + const { hostname } = (await input.regionInfoProvider(region, { useDualstackEndpoint, useFipsEndpoint })) ?? {}; + if (!hostname) { + throw new Error("Cannot resolve hostname from client config"); + } + return input.urlParser(`${tls ? "https:" : "http:"}//${hostname}`); +}; + +const resolveEndpointsConfig = (input) => { + const useDualstackEndpoint = utilMiddleware.normalizeProvider(input.useDualstackEndpoint ?? false); + const { endpoint, useFipsEndpoint, urlParser, tls } = input; + return Object.assign(input, { + tls: tls ?? true, + endpoint: endpoint + ? utilMiddleware.normalizeProvider(typeof endpoint === "string" ? urlParser(endpoint) : endpoint) + : () => getEndpointFromRegion({ ...input, useDualstackEndpoint, useFipsEndpoint }), + isCustomEndpoint: !!endpoint, + useDualstackEndpoint, + }); +}; + +const REGION_ENV_NAME = "AWS_REGION"; +const REGION_INI_NAME = "region"; +const NODE_REGION_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => env[REGION_ENV_NAME], + configFileSelector: (profile) => profile[REGION_INI_NAME], + default: () => { + throw new Error("Region is missing"); + }, +}; +const NODE_REGION_CONFIG_FILE_OPTIONS = { + preferredFile: "credentials", +}; + +const validRegions = new Set(); +const checkRegion = (region, check = utilEndpoints.isValidHostLabel) => { + if (!validRegions.has(region) && !check(region)) { + if (region === "*") { + console.warn(`@smithy/config-resolver WARN - Please use the caller region instead of "*". See "sigv4a" in https://github.com/aws/aws-sdk-js-v3/blob/main/supplemental-docs/CLIENTS.md.`); + } + else { + throw new Error(`Region not accepted: region="${region}" is not a valid hostname component.`); + } + } + else { + validRegions.add(region); + } +}; + +const isFipsRegion = (region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips")); + +const getRealRegion = (region) => isFipsRegion(region) + ? ["fips-aws-global", "aws-fips"].includes(region) + ? "us-east-1" + : region.replace(/fips-(dkr-|prod-)?|-fips/, "") + : region; + +const resolveRegionConfig = (input) => { + const { region, useFipsEndpoint } = input; + if (!region) { + throw new Error("Region is missing"); + } + return Object.assign(input, { + region: async () => { + const providedRegion = typeof region === "function" ? await region() : region; + const realRegion = getRealRegion(providedRegion); + checkRegion(realRegion); + return realRegion; + }, + useFipsEndpoint: async () => { + const providedRegion = typeof region === "string" ? region : await region(); + if (isFipsRegion(providedRegion)) { + return true; + } + return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint(); + }, + }); +}; + +const getHostnameFromVariants = (variants = [], { useFipsEndpoint, useDualstackEndpoint }) => variants.find(({ tags }) => useFipsEndpoint === tags.includes("fips") && useDualstackEndpoint === tags.includes("dualstack"))?.hostname; + +const getResolvedHostname = (resolvedRegion, { regionHostname, partitionHostname }) => regionHostname + ? regionHostname + : partitionHostname + ? partitionHostname.replace("{region}", resolvedRegion) + : undefined; + +const getResolvedPartition = (region, { partitionHash }) => Object.keys(partitionHash || {}).find((key) => partitionHash[key].regions.includes(region)) ?? "aws"; + +const getResolvedSigningRegion = (hostname, { signingRegion, regionRegex, useFipsEndpoint }) => { + if (signingRegion) { + return signingRegion; + } + else if (useFipsEndpoint) { + const regionRegexJs = regionRegex.replace("\\\\", "\\").replace(/^\^/g, "\\.").replace(/\$$/g, "\\."); + const regionRegexmatchArray = hostname.match(regionRegexJs); + if (regionRegexmatchArray) { + return regionRegexmatchArray[0].slice(1, -1); + } + } +}; + +const getRegionInfo = (region, { useFipsEndpoint = false, useDualstackEndpoint = false, signingService, regionHash, partitionHash, }) => { + const partition = getResolvedPartition(region, { partitionHash }); + const resolvedRegion = region in regionHash ? region : partitionHash[partition]?.endpoint ?? region; + const hostnameOptions = { useFipsEndpoint, useDualstackEndpoint }; + const regionHostname = getHostnameFromVariants(regionHash[resolvedRegion]?.variants, hostnameOptions); + const partitionHostname = getHostnameFromVariants(partitionHash[partition]?.variants, hostnameOptions); + const hostname = getResolvedHostname(resolvedRegion, { regionHostname, partitionHostname }); + if (hostname === undefined) { + throw new Error(`Endpoint resolution failed for: ${{ resolvedRegion, useFipsEndpoint, useDualstackEndpoint }}`); + } + const signingRegion = getResolvedSigningRegion(hostname, { + signingRegion: regionHash[resolvedRegion]?.signingRegion, + regionRegex: partitionHash[partition].regionRegex, + useFipsEndpoint, + }); + return { + partition, + signingService, + hostname, + ...(signingRegion && { signingRegion }), + ...(regionHash[resolvedRegion]?.signingService && { + signingService: regionHash[resolvedRegion].signingService, + }), + }; +}; + +exports.CONFIG_USE_DUALSTACK_ENDPOINT = CONFIG_USE_DUALSTACK_ENDPOINT; +exports.CONFIG_USE_FIPS_ENDPOINT = CONFIG_USE_FIPS_ENDPOINT; +exports.DEFAULT_USE_DUALSTACK_ENDPOINT = DEFAULT_USE_DUALSTACK_ENDPOINT; +exports.DEFAULT_USE_FIPS_ENDPOINT = DEFAULT_USE_FIPS_ENDPOINT; +exports.ENV_USE_DUALSTACK_ENDPOINT = ENV_USE_DUALSTACK_ENDPOINT; +exports.ENV_USE_FIPS_ENDPOINT = ENV_USE_FIPS_ENDPOINT; +exports.NODE_REGION_CONFIG_FILE_OPTIONS = NODE_REGION_CONFIG_FILE_OPTIONS; +exports.NODE_REGION_CONFIG_OPTIONS = NODE_REGION_CONFIG_OPTIONS; +exports.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS = NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS; +exports.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS = NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS; +exports.REGION_ENV_NAME = REGION_ENV_NAME; +exports.REGION_INI_NAME = REGION_INI_NAME; +exports.getRegionInfo = getRegionInfo; +exports.resolveCustomEndpointsConfig = resolveCustomEndpointsConfig; +exports.resolveEndpointsConfig = resolveEndpointsConfig; +exports.resolveRegionConfig = resolveRegionConfig; diff --git a/claude-code-source/node_modules/@smithy/core/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/core/dist-cjs/index.js new file mode 100644 index 00000000..86a61447 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/core/dist-cjs/index.js @@ -0,0 +1,349 @@ +'use strict'; + +var types = require('@smithy/types'); +var utilMiddleware = require('@smithy/util-middleware'); +var middlewareSerde = require('@smithy/middleware-serde'); +var protocolHttp = require('@smithy/protocol-http'); +var protocols = require('@smithy/core/protocols'); + +const getSmithyContext = (context) => context[types.SMITHY_CONTEXT_KEY] || (context[types.SMITHY_CONTEXT_KEY] = {}); + +const resolveAuthOptions = (candidateAuthOptions, authSchemePreference) => { + if (!authSchemePreference || authSchemePreference.length === 0) { + return candidateAuthOptions; + } + const preferredAuthOptions = []; + for (const preferredSchemeName of authSchemePreference) { + for (const candidateAuthOption of candidateAuthOptions) { + const candidateAuthSchemeName = candidateAuthOption.schemeId.split("#")[1]; + if (candidateAuthSchemeName === preferredSchemeName) { + preferredAuthOptions.push(candidateAuthOption); + } + } + } + for (const candidateAuthOption of candidateAuthOptions) { + if (!preferredAuthOptions.find(({ schemeId }) => schemeId === candidateAuthOption.schemeId)) { + preferredAuthOptions.push(candidateAuthOption); + } + } + return preferredAuthOptions; +}; + +function convertHttpAuthSchemesToMap(httpAuthSchemes) { + const map = new Map(); + for (const scheme of httpAuthSchemes) { + map.set(scheme.schemeId, scheme); + } + return map; +} +const httpAuthSchemeMiddleware = (config, mwOptions) => (next, context) => async (args) => { + const options = config.httpAuthSchemeProvider(await mwOptions.httpAuthSchemeParametersProvider(config, context, args.input)); + const authSchemePreference = config.authSchemePreference ? await config.authSchemePreference() : []; + const resolvedOptions = resolveAuthOptions(options, authSchemePreference); + const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes); + const smithyContext = utilMiddleware.getSmithyContext(context); + const failureReasons = []; + for (const option of resolvedOptions) { + const scheme = authSchemes.get(option.schemeId); + if (!scheme) { + failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`); + continue; + } + const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config)); + if (!identityProvider) { + failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`); + continue; + } + const { identityProperties = {}, signingProperties = {} } = option.propertiesExtractor?.(config, context) || {}; + option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties); + option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties); + smithyContext.selectedHttpAuthScheme = { + httpAuthOption: option, + identity: await identityProvider(option.identityProperties), + signer: scheme.signer, + }; + break; + } + if (!smithyContext.selectedHttpAuthScheme) { + throw new Error(failureReasons.join("\n")); + } + return next(args); +}; + +const httpAuthSchemeEndpointRuleSetMiddlewareOptions = { + step: "serialize", + tags: ["HTTP_AUTH_SCHEME"], + name: "httpAuthSchemeMiddleware", + override: true, + relation: "before", + toMiddleware: "endpointV2Middleware", +}; +const getHttpAuthSchemeEndpointRuleSetPlugin = (config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider, }) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(httpAuthSchemeMiddleware(config, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider, + }), httpAuthSchemeEndpointRuleSetMiddlewareOptions); + }, +}); + +const httpAuthSchemeMiddlewareOptions = { + step: "serialize", + tags: ["HTTP_AUTH_SCHEME"], + name: "httpAuthSchemeMiddleware", + override: true, + relation: "before", + toMiddleware: middlewareSerde.serializerMiddlewareOption.name, +}; +const getHttpAuthSchemePlugin = (config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider, }) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(httpAuthSchemeMiddleware(config, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider, + }), httpAuthSchemeMiddlewareOptions); + }, +}); + +const defaultErrorHandler = (signingProperties) => (error) => { + throw error; +}; +const defaultSuccessHandler = (httpResponse, signingProperties) => { }; +const httpSigningMiddleware = (config) => (next, context) => async (args) => { + if (!protocolHttp.HttpRequest.isInstance(args.request)) { + return next(args); + } + const smithyContext = utilMiddleware.getSmithyContext(context); + const scheme = smithyContext.selectedHttpAuthScheme; + if (!scheme) { + throw new Error(`No HttpAuthScheme was selected: unable to sign request`); + } + const { httpAuthOption: { signingProperties = {} }, identity, signer, } = scheme; + const output = await next({ + ...args, + request: await signer.sign(args.request, identity, signingProperties), + }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties)); + (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties); + return output; +}; + +const httpSigningMiddlewareOptions = { + step: "finalizeRequest", + tags: ["HTTP_SIGNING"], + name: "httpSigningMiddleware", + aliases: ["apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware"], + override: true, + relation: "after", + toMiddleware: "retryMiddleware", +}; +const getHttpSigningPlugin = (config) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(httpSigningMiddleware(), httpSigningMiddlewareOptions); + }, +}); + +const normalizeProvider = (input) => { + if (typeof input === "function") + return input; + const promisified = Promise.resolve(input); + return () => promisified; +}; + +const makePagedClientRequest = async (CommandCtor, client, input, withCommand = (_) => _, ...args) => { + let command = new CommandCtor(input); + command = withCommand(command) ?? command; + return await client.send(command, ...args); +}; +function createPaginator(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) { + return async function* paginateOperation(config, input, ...additionalArguments) { + const _input = input; + let token = config.startingToken ?? _input[inputTokenName]; + let hasNext = true; + let page; + while (hasNext) { + _input[inputTokenName] = token; + if (pageSizeTokenName) { + _input[pageSizeTokenName] = _input[pageSizeTokenName] ?? config.pageSize; + } + if (config.client instanceof ClientCtor) { + page = await makePagedClientRequest(CommandCtor, config.client, input, config.withCommand, ...additionalArguments); + } + else { + throw new Error(`Invalid client, expected instance of ${ClientCtor.name}`); + } + yield page; + const prevToken = token; + token = get(page, outputTokenName); + hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken)); + } + return undefined; + }; +} +const get = (fromObject, path) => { + let cursor = fromObject; + const pathComponents = path.split("."); + for (const step of pathComponents) { + if (!cursor || typeof cursor !== "object") { + return undefined; + } + cursor = cursor[step]; + } + return cursor; +}; + +function setFeature(context, feature, value) { + if (!context.__smithy_context) { + context.__smithy_context = { + features: {}, + }; + } + else if (!context.__smithy_context.features) { + context.__smithy_context.features = {}; + } + context.__smithy_context.features[feature] = value; +} + +class DefaultIdentityProviderConfig { + authSchemes = new Map(); + constructor(config) { + for (const [key, value] of Object.entries(config)) { + if (value !== undefined) { + this.authSchemes.set(key, value); + } + } + } + getIdentityProvider(schemeId) { + return this.authSchemes.get(schemeId); + } +} + +class HttpApiKeyAuthSigner { + async sign(httpRequest, identity, signingProperties) { + if (!signingProperties) { + throw new Error("request could not be signed with `apiKey` since the `name` and `in` signer properties are missing"); + } + if (!signingProperties.name) { + throw new Error("request could not be signed with `apiKey` since the `name` signer property is missing"); + } + if (!signingProperties.in) { + throw new Error("request could not be signed with `apiKey` since the `in` signer property is missing"); + } + if (!identity.apiKey) { + throw new Error("request could not be signed with `apiKey` since the `apiKey` is not defined"); + } + const clonedRequest = protocolHttp.HttpRequest.clone(httpRequest); + if (signingProperties.in === types.HttpApiKeyAuthLocation.QUERY) { + clonedRequest.query[signingProperties.name] = identity.apiKey; + } + else if (signingProperties.in === types.HttpApiKeyAuthLocation.HEADER) { + clonedRequest.headers[signingProperties.name] = signingProperties.scheme + ? `${signingProperties.scheme} ${identity.apiKey}` + : identity.apiKey; + } + else { + throw new Error("request can only be signed with `apiKey` locations `query` or `header`, " + + "but found: `" + + signingProperties.in + + "`"); + } + return clonedRequest; + } +} + +class HttpBearerAuthSigner { + async sign(httpRequest, identity, signingProperties) { + const clonedRequest = protocolHttp.HttpRequest.clone(httpRequest); + if (!identity.token) { + throw new Error("request could not be signed with `token` since the `token` is not defined"); + } + clonedRequest.headers["Authorization"] = `Bearer ${identity.token}`; + return clonedRequest; + } +} + +class NoAuthSigner { + async sign(httpRequest, identity, signingProperties) { + return httpRequest; + } +} + +const createIsIdentityExpiredFunction = (expirationMs) => function isIdentityExpired(identity) { + return doesIdentityRequireRefresh(identity) && identity.expiration.getTime() - Date.now() < expirationMs; +}; +const EXPIRATION_MS = 300_000; +const isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS); +const doesIdentityRequireRefresh = (identity) => identity.expiration !== undefined; +const memoizeIdentityProvider = (provider, isExpired, requiresRefresh) => { + if (provider === undefined) { + return undefined; + } + const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider; + let resolved; + let pending; + let hasResult; + let isConstant = false; + const coalesceProvider = async (options) => { + if (!pending) { + pending = normalizedProvider(options); + } + try { + resolved = await pending; + hasResult = true; + isConstant = false; + } + finally { + pending = undefined; + } + return resolved; + }; + if (isExpired === undefined) { + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(options); + } + return resolved; + }; + } + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(options); + } + if (isConstant) { + return resolved; + } + if (!requiresRefresh(resolved)) { + isConstant = true; + return resolved; + } + if (isExpired(resolved)) { + await coalesceProvider(options); + return resolved; + } + return resolved; + }; +}; + +Object.defineProperty(exports, "requestBuilder", { + enumerable: true, + get: function () { return protocols.requestBuilder; } +}); +exports.DefaultIdentityProviderConfig = DefaultIdentityProviderConfig; +exports.EXPIRATION_MS = EXPIRATION_MS; +exports.HttpApiKeyAuthSigner = HttpApiKeyAuthSigner; +exports.HttpBearerAuthSigner = HttpBearerAuthSigner; +exports.NoAuthSigner = NoAuthSigner; +exports.createIsIdentityExpiredFunction = createIsIdentityExpiredFunction; +exports.createPaginator = createPaginator; +exports.doesIdentityRequireRefresh = doesIdentityRequireRefresh; +exports.getHttpAuthSchemeEndpointRuleSetPlugin = getHttpAuthSchemeEndpointRuleSetPlugin; +exports.getHttpAuthSchemePlugin = getHttpAuthSchemePlugin; +exports.getHttpSigningPlugin = getHttpSigningPlugin; +exports.getSmithyContext = getSmithyContext; +exports.httpAuthSchemeEndpointRuleSetMiddlewareOptions = httpAuthSchemeEndpointRuleSetMiddlewareOptions; +exports.httpAuthSchemeMiddleware = httpAuthSchemeMiddleware; +exports.httpAuthSchemeMiddlewareOptions = httpAuthSchemeMiddlewareOptions; +exports.httpSigningMiddleware = httpSigningMiddleware; +exports.httpSigningMiddlewareOptions = httpSigningMiddlewareOptions; +exports.isIdentityExpired = isIdentityExpired; +exports.memoizeIdentityProvider = memoizeIdentityProvider; +exports.normalizeProvider = normalizeProvider; +exports.setFeature = setFeature; diff --git a/claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/cbor/index.js b/claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/cbor/index.js new file mode 100644 index 00000000..9fc40e38 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/cbor/index.js @@ -0,0 +1,1050 @@ +'use strict'; + +var serde = require('@smithy/core/serde'); +var utilUtf8 = require('@smithy/util-utf8'); +var protocols = require('@smithy/core/protocols'); +var protocolHttp = require('@smithy/protocol-http'); +var utilBodyLengthBrowser = require('@smithy/util-body-length-browser'); +var schema = require('@smithy/core/schema'); +var utilMiddleware = require('@smithy/util-middleware'); +var utilBase64 = require('@smithy/util-base64'); + +const majorUint64 = 0; +const majorNegativeInt64 = 1; +const majorUnstructuredByteString = 2; +const majorUtf8String = 3; +const majorList = 4; +const majorMap = 5; +const majorTag = 6; +const majorSpecial = 7; +const specialFalse = 20; +const specialTrue = 21; +const specialNull = 22; +const specialUndefined = 23; +const extendedOneByte = 24; +const extendedFloat16 = 25; +const extendedFloat32 = 26; +const extendedFloat64 = 27; +const minorIndefinite = 31; +function alloc(size) { + return typeof Buffer !== "undefined" ? Buffer.alloc(size) : new Uint8Array(size); +} +const tagSymbol = Symbol("@smithy/core/cbor::tagSymbol"); +function tag(data) { + data[tagSymbol] = true; + return data; +} + +const USE_TEXT_DECODER = typeof TextDecoder !== "undefined"; +const USE_BUFFER$1 = typeof Buffer !== "undefined"; +let payload = alloc(0); +let dataView$1 = new DataView(payload.buffer, payload.byteOffset, payload.byteLength); +const textDecoder = USE_TEXT_DECODER ? new TextDecoder() : null; +let _offset = 0; +function setPayload(bytes) { + payload = bytes; + dataView$1 = new DataView(payload.buffer, payload.byteOffset, payload.byteLength); +} +function decode(at, to) { + if (at >= to) { + throw new Error("unexpected end of (decode) payload."); + } + const major = (payload[at] & 0b1110_0000) >> 5; + const minor = payload[at] & 0b0001_1111; + switch (major) { + case majorUint64: + case majorNegativeInt64: + case majorTag: + let unsignedInt; + let offset; + if (minor < 24) { + unsignedInt = minor; + offset = 1; + } + else { + switch (minor) { + case extendedOneByte: + case extendedFloat16: + case extendedFloat32: + case extendedFloat64: + const countLength = minorValueToArgumentLength[minor]; + const countOffset = (countLength + 1); + offset = countOffset; + if (to - at < countOffset) { + throw new Error(`countLength ${countLength} greater than remaining buf len.`); + } + const countIndex = at + 1; + if (countLength === 1) { + unsignedInt = payload[countIndex]; + } + else if (countLength === 2) { + unsignedInt = dataView$1.getUint16(countIndex); + } + else if (countLength === 4) { + unsignedInt = dataView$1.getUint32(countIndex); + } + else { + unsignedInt = dataView$1.getBigUint64(countIndex); + } + break; + default: + throw new Error(`unexpected minor value ${minor}.`); + } + } + if (major === majorUint64) { + _offset = offset; + return castBigInt(unsignedInt); + } + else if (major === majorNegativeInt64) { + let negativeInt; + if (typeof unsignedInt === "bigint") { + negativeInt = BigInt(-1) - unsignedInt; + } + else { + negativeInt = -1 - unsignedInt; + } + _offset = offset; + return castBigInt(negativeInt); + } + else { + if (minor === 2 || minor === 3) { + const length = decodeCount(at + offset, to); + let b = BigInt(0); + const start = at + offset + _offset; + for (let i = start; i < start + length; ++i) { + b = (b << BigInt(8)) | BigInt(payload[i]); + } + _offset = offset + _offset + length; + return minor === 3 ? -b - BigInt(1) : b; + } + else if (minor === 4) { + const decimalFraction = decode(at + offset, to); + const [exponent, mantissa] = decimalFraction; + const normalizer = mantissa < 0 ? -1 : 1; + const mantissaStr = "0".repeat(Math.abs(exponent) + 1) + String(BigInt(normalizer) * BigInt(mantissa)); + let numericString; + const sign = mantissa < 0 ? "-" : ""; + numericString = + exponent === 0 + ? mantissaStr + : mantissaStr.slice(0, mantissaStr.length + exponent) + "." + mantissaStr.slice(exponent); + numericString = numericString.replace(/^0+/g, ""); + if (numericString === "") { + numericString = "0"; + } + if (numericString[0] === ".") { + numericString = "0" + numericString; + } + numericString = sign + numericString; + _offset = offset + _offset; + return serde.nv(numericString); + } + else { + const value = decode(at + offset, to); + const valueOffset = _offset; + _offset = offset + valueOffset; + return tag({ tag: castBigInt(unsignedInt), value }); + } + } + case majorUtf8String: + case majorMap: + case majorList: + case majorUnstructuredByteString: + if (minor === minorIndefinite) { + switch (major) { + case majorUtf8String: + return decodeUtf8StringIndefinite(at, to); + case majorMap: + return decodeMapIndefinite(at, to); + case majorList: + return decodeListIndefinite(at, to); + case majorUnstructuredByteString: + return decodeUnstructuredByteStringIndefinite(at, to); + } + } + else { + switch (major) { + case majorUtf8String: + return decodeUtf8String(at, to); + case majorMap: + return decodeMap(at, to); + case majorList: + return decodeList(at, to); + case majorUnstructuredByteString: + return decodeUnstructuredByteString(at, to); + } + } + default: + return decodeSpecial(at, to); + } +} +function bytesToUtf8(bytes, at, to) { + if (USE_BUFFER$1 && bytes.constructor?.name === "Buffer") { + return bytes.toString("utf-8", at, to); + } + if (textDecoder) { + return textDecoder.decode(bytes.subarray(at, to)); + } + return utilUtf8.toUtf8(bytes.subarray(at, to)); +} +function demote(bigInteger) { + const num = Number(bigInteger); + if (num < Number.MIN_SAFE_INTEGER || Number.MAX_SAFE_INTEGER < num) { + console.warn(new Error(`@smithy/core/cbor - truncating BigInt(${bigInteger}) to ${num} with loss of precision.`)); + } + return num; +} +const minorValueToArgumentLength = { + [extendedOneByte]: 1, + [extendedFloat16]: 2, + [extendedFloat32]: 4, + [extendedFloat64]: 8, +}; +function bytesToFloat16(a, b) { + const sign = a >> 7; + const exponent = (a & 0b0111_1100) >> 2; + const fraction = ((a & 0b0000_0011) << 8) | b; + const scalar = sign === 0 ? 1 : -1; + let exponentComponent; + let summation; + if (exponent === 0b00000) { + if (fraction === 0b00000_00000) { + return 0; + } + else { + exponentComponent = Math.pow(2, 1 - 15); + summation = 0; + } + } + else if (exponent === 0b11111) { + if (fraction === 0b00000_00000) { + return scalar * Infinity; + } + else { + return NaN; + } + } + else { + exponentComponent = Math.pow(2, exponent - 15); + summation = 1; + } + summation += fraction / 1024; + return scalar * (exponentComponent * summation); +} +function decodeCount(at, to) { + const minor = payload[at] & 0b0001_1111; + if (minor < 24) { + _offset = 1; + return minor; + } + if (minor === extendedOneByte || + minor === extendedFloat16 || + minor === extendedFloat32 || + minor === extendedFloat64) { + const countLength = minorValueToArgumentLength[minor]; + _offset = (countLength + 1); + if (to - at < _offset) { + throw new Error(`countLength ${countLength} greater than remaining buf len.`); + } + const countIndex = at + 1; + if (countLength === 1) { + return payload[countIndex]; + } + else if (countLength === 2) { + return dataView$1.getUint16(countIndex); + } + else if (countLength === 4) { + return dataView$1.getUint32(countIndex); + } + return demote(dataView$1.getBigUint64(countIndex)); + } + throw new Error(`unexpected minor value ${minor}.`); +} +function decodeUtf8String(at, to) { + const length = decodeCount(at, to); + const offset = _offset; + at += offset; + if (to - at < length) { + throw new Error(`string len ${length} greater than remaining buf len.`); + } + const value = bytesToUtf8(payload, at, at + length); + _offset = offset + length; + return value; +} +function decodeUtf8StringIndefinite(at, to) { + at += 1; + const vector = []; + for (const base = at; at < to;) { + if (payload[at] === 0b1111_1111) { + const data = alloc(vector.length); + data.set(vector, 0); + _offset = at - base + 2; + return bytesToUtf8(data, 0, data.length); + } + const major = (payload[at] & 0b1110_0000) >> 5; + const minor = payload[at] & 0b0001_1111; + if (major !== majorUtf8String) { + throw new Error(`unexpected major type ${major} in indefinite string.`); + } + if (minor === minorIndefinite) { + throw new Error("nested indefinite string."); + } + const bytes = decodeUnstructuredByteString(at, to); + const length = _offset; + at += length; + for (let i = 0; i < bytes.length; ++i) { + vector.push(bytes[i]); + } + } + throw new Error("expected break marker."); +} +function decodeUnstructuredByteString(at, to) { + const length = decodeCount(at, to); + const offset = _offset; + at += offset; + if (to - at < length) { + throw new Error(`unstructured byte string len ${length} greater than remaining buf len.`); + } + const value = payload.subarray(at, at + length); + _offset = offset + length; + return value; +} +function decodeUnstructuredByteStringIndefinite(at, to) { + at += 1; + const vector = []; + for (const base = at; at < to;) { + if (payload[at] === 0b1111_1111) { + const data = alloc(vector.length); + data.set(vector, 0); + _offset = at - base + 2; + return data; + } + const major = (payload[at] & 0b1110_0000) >> 5; + const minor = payload[at] & 0b0001_1111; + if (major !== majorUnstructuredByteString) { + throw new Error(`unexpected major type ${major} in indefinite string.`); + } + if (minor === minorIndefinite) { + throw new Error("nested indefinite string."); + } + const bytes = decodeUnstructuredByteString(at, to); + const length = _offset; + at += length; + for (let i = 0; i < bytes.length; ++i) { + vector.push(bytes[i]); + } + } + throw new Error("expected break marker."); +} +function decodeList(at, to) { + const listDataLength = decodeCount(at, to); + const offset = _offset; + at += offset; + const base = at; + const list = Array(listDataLength); + for (let i = 0; i < listDataLength; ++i) { + const item = decode(at, to); + const itemOffset = _offset; + list[i] = item; + at += itemOffset; + } + _offset = offset + (at - base); + return list; +} +function decodeListIndefinite(at, to) { + at += 1; + const list = []; + for (const base = at; at < to;) { + if (payload[at] === 0b1111_1111) { + _offset = at - base + 2; + return list; + } + const item = decode(at, to); + const n = _offset; + at += n; + list.push(item); + } + throw new Error("expected break marker."); +} +function decodeMap(at, to) { + const mapDataLength = decodeCount(at, to); + const offset = _offset; + at += offset; + const base = at; + const map = {}; + for (let i = 0; i < mapDataLength; ++i) { + if (at >= to) { + throw new Error("unexpected end of map payload."); + } + const major = (payload[at] & 0b1110_0000) >> 5; + if (major !== majorUtf8String) { + throw new Error(`unexpected major type ${major} for map key at index ${at}.`); + } + const key = decode(at, to); + at += _offset; + const value = decode(at, to); + at += _offset; + map[key] = value; + } + _offset = offset + (at - base); + return map; +} +function decodeMapIndefinite(at, to) { + at += 1; + const base = at; + const map = {}; + for (; at < to;) { + if (at >= to) { + throw new Error("unexpected end of map payload."); + } + if (payload[at] === 0b1111_1111) { + _offset = at - base + 2; + return map; + } + const major = (payload[at] & 0b1110_0000) >> 5; + if (major !== majorUtf8String) { + throw new Error(`unexpected major type ${major} for map key.`); + } + const key = decode(at, to); + at += _offset; + const value = decode(at, to); + at += _offset; + map[key] = value; + } + throw new Error("expected break marker."); +} +function decodeSpecial(at, to) { + const minor = payload[at] & 0b0001_1111; + switch (minor) { + case specialTrue: + case specialFalse: + _offset = 1; + return minor === specialTrue; + case specialNull: + _offset = 1; + return null; + case specialUndefined: + _offset = 1; + return null; + case extendedFloat16: + if (to - at < 3) { + throw new Error("incomplete float16 at end of buf."); + } + _offset = 3; + return bytesToFloat16(payload[at + 1], payload[at + 2]); + case extendedFloat32: + if (to - at < 5) { + throw new Error("incomplete float32 at end of buf."); + } + _offset = 5; + return dataView$1.getFloat32(at + 1); + case extendedFloat64: + if (to - at < 9) { + throw new Error("incomplete float64 at end of buf."); + } + _offset = 9; + return dataView$1.getFloat64(at + 1); + default: + throw new Error(`unexpected minor value ${minor}.`); + } +} +function castBigInt(bigInt) { + if (typeof bigInt === "number") { + return bigInt; + } + const num = Number(bigInt); + if (Number.MIN_SAFE_INTEGER <= num && num <= Number.MAX_SAFE_INTEGER) { + return num; + } + return bigInt; +} + +const USE_BUFFER = typeof Buffer !== "undefined"; +const initialSize = 2048; +let data = alloc(initialSize); +let dataView = new DataView(data.buffer, data.byteOffset, data.byteLength); +let cursor = 0; +function ensureSpace(bytes) { + const remaining = data.byteLength - cursor; + if (remaining < bytes) { + if (cursor < 16_000_000) { + resize(Math.max(data.byteLength * 4, data.byteLength + bytes)); + } + else { + resize(data.byteLength + bytes + 16_000_000); + } + } +} +function toUint8Array() { + const out = alloc(cursor); + out.set(data.subarray(0, cursor), 0); + cursor = 0; + return out; +} +function resize(size) { + const old = data; + data = alloc(size); + if (old) { + if (old.copy) { + old.copy(data, 0, 0, old.byteLength); + } + else { + data.set(old, 0); + } + } + dataView = new DataView(data.buffer, data.byteOffset, data.byteLength); +} +function encodeHeader(major, value) { + if (value < 24) { + data[cursor++] = (major << 5) | value; + } + else if (value < 1 << 8) { + data[cursor++] = (major << 5) | 24; + data[cursor++] = value; + } + else if (value < 1 << 16) { + data[cursor++] = (major << 5) | extendedFloat16; + dataView.setUint16(cursor, value); + cursor += 2; + } + else if (value < 2 ** 32) { + data[cursor++] = (major << 5) | extendedFloat32; + dataView.setUint32(cursor, value); + cursor += 4; + } + else { + data[cursor++] = (major << 5) | extendedFloat64; + dataView.setBigUint64(cursor, typeof value === "bigint" ? value : BigInt(value)); + cursor += 8; + } +} +function encode(_input) { + const encodeStack = [_input]; + while (encodeStack.length) { + const input = encodeStack.pop(); + ensureSpace(typeof input === "string" ? input.length * 4 : 64); + if (typeof input === "string") { + if (USE_BUFFER) { + encodeHeader(majorUtf8String, Buffer.byteLength(input)); + cursor += data.write(input, cursor); + } + else { + const bytes = utilUtf8.fromUtf8(input); + encodeHeader(majorUtf8String, bytes.byteLength); + data.set(bytes, cursor); + cursor += bytes.byteLength; + } + continue; + } + else if (typeof input === "number") { + if (Number.isInteger(input)) { + const nonNegative = input >= 0; + const major = nonNegative ? majorUint64 : majorNegativeInt64; + const value = nonNegative ? input : -input - 1; + if (value < 24) { + data[cursor++] = (major << 5) | value; + } + else if (value < 256) { + data[cursor++] = (major << 5) | 24; + data[cursor++] = value; + } + else if (value < 65536) { + data[cursor++] = (major << 5) | extendedFloat16; + data[cursor++] = value >> 8; + data[cursor++] = value; + } + else if (value < 4294967296) { + data[cursor++] = (major << 5) | extendedFloat32; + dataView.setUint32(cursor, value); + cursor += 4; + } + else { + data[cursor++] = (major << 5) | extendedFloat64; + dataView.setBigUint64(cursor, BigInt(value)); + cursor += 8; + } + continue; + } + data[cursor++] = (majorSpecial << 5) | extendedFloat64; + dataView.setFloat64(cursor, input); + cursor += 8; + continue; + } + else if (typeof input === "bigint") { + const nonNegative = input >= 0; + const major = nonNegative ? majorUint64 : majorNegativeInt64; + const value = nonNegative ? input : -input - BigInt(1); + const n = Number(value); + if (n < 24) { + data[cursor++] = (major << 5) | n; + } + else if (n < 256) { + data[cursor++] = (major << 5) | 24; + data[cursor++] = n; + } + else if (n < 65536) { + data[cursor++] = (major << 5) | extendedFloat16; + data[cursor++] = n >> 8; + data[cursor++] = n & 0b1111_1111; + } + else if (n < 4294967296) { + data[cursor++] = (major << 5) | extendedFloat32; + dataView.setUint32(cursor, n); + cursor += 4; + } + else if (value < BigInt("18446744073709551616")) { + data[cursor++] = (major << 5) | extendedFloat64; + dataView.setBigUint64(cursor, value); + cursor += 8; + } + else { + const binaryBigInt = value.toString(2); + const bigIntBytes = new Uint8Array(Math.ceil(binaryBigInt.length / 8)); + let b = value; + let i = 0; + while (bigIntBytes.byteLength - ++i >= 0) { + bigIntBytes[bigIntBytes.byteLength - i] = Number(b & BigInt(255)); + b >>= BigInt(8); + } + ensureSpace(bigIntBytes.byteLength * 2); + data[cursor++] = nonNegative ? 0b110_00010 : 0b110_00011; + if (USE_BUFFER) { + encodeHeader(majorUnstructuredByteString, Buffer.byteLength(bigIntBytes)); + } + else { + encodeHeader(majorUnstructuredByteString, bigIntBytes.byteLength); + } + data.set(bigIntBytes, cursor); + cursor += bigIntBytes.byteLength; + } + continue; + } + else if (input === null) { + data[cursor++] = (majorSpecial << 5) | specialNull; + continue; + } + else if (typeof input === "boolean") { + data[cursor++] = (majorSpecial << 5) | (input ? specialTrue : specialFalse); + continue; + } + else if (typeof input === "undefined") { + throw new Error("@smithy/core/cbor: client may not serialize undefined value."); + } + else if (Array.isArray(input)) { + for (let i = input.length - 1; i >= 0; --i) { + encodeStack.push(input[i]); + } + encodeHeader(majorList, input.length); + continue; + } + else if (typeof input.byteLength === "number") { + ensureSpace(input.length * 2); + encodeHeader(majorUnstructuredByteString, input.length); + data.set(input, cursor); + cursor += input.byteLength; + continue; + } + else if (typeof input === "object") { + if (input instanceof serde.NumericValue) { + const decimalIndex = input.string.indexOf("."); + const exponent = decimalIndex === -1 ? 0 : decimalIndex - input.string.length + 1; + const mantissa = BigInt(input.string.replace(".", "")); + data[cursor++] = 0b110_00100; + encodeStack.push(mantissa); + encodeStack.push(exponent); + encodeHeader(majorList, 2); + continue; + } + if (input[tagSymbol]) { + if ("tag" in input && "value" in input) { + encodeStack.push(input.value); + encodeHeader(majorTag, input.tag); + continue; + } + else { + throw new Error("tag encountered with missing fields, need 'tag' and 'value', found: " + JSON.stringify(input)); + } + } + const keys = Object.keys(input); + for (let i = keys.length - 1; i >= 0; --i) { + const key = keys[i]; + encodeStack.push(input[key]); + encodeStack.push(key); + } + encodeHeader(majorMap, keys.length); + continue; + } + throw new Error(`data type ${input?.constructor?.name ?? typeof input} not compatible for encoding.`); + } +} + +const cbor = { + deserialize(payload) { + setPayload(payload); + return decode(0, payload.length); + }, + serialize(input) { + try { + encode(input); + return toUint8Array(); + } + catch (e) { + toUint8Array(); + throw e; + } + }, + resizeEncodingBuffer(size) { + resize(size); + }, +}; + +const parseCborBody = (streamBody, context) => { + return protocols.collectBody(streamBody, context).then(async (bytes) => { + if (bytes.length) { + try { + return cbor.deserialize(bytes); + } + catch (e) { + Object.defineProperty(e, "$responseBodyText", { + value: context.utf8Encoder(bytes), + }); + throw e; + } + } + return {}; + }); +}; +const dateToTag = (date) => { + return tag({ + tag: 1, + value: date.getTime() / 1000, + }); +}; +const parseCborErrorBody = async (errorBody, context) => { + const value = await parseCborBody(errorBody, context); + value.message = value.message ?? value.Message; + return value; +}; +const loadSmithyRpcV2CborErrorCode = (output, data) => { + const sanitizeErrorCode = (rawValue) => { + let cleanValue = rawValue; + if (typeof cleanValue === "number") { + cleanValue = cleanValue.toString(); + } + if (cleanValue.indexOf(",") >= 0) { + cleanValue = cleanValue.split(",")[0]; + } + if (cleanValue.indexOf(":") >= 0) { + cleanValue = cleanValue.split(":")[0]; + } + if (cleanValue.indexOf("#") >= 0) { + cleanValue = cleanValue.split("#")[1]; + } + return cleanValue; + }; + if (data["__type"] !== undefined) { + return sanitizeErrorCode(data["__type"]); + } + const codeKey = Object.keys(data).find((key) => key.toLowerCase() === "code"); + if (codeKey && data[codeKey] !== undefined) { + return sanitizeErrorCode(data[codeKey]); + } +}; +const checkCborResponse = (response) => { + if (String(response.headers["smithy-protocol"]).toLowerCase() !== "rpc-v2-cbor") { + throw new Error("Malformed RPCv2 CBOR response, status: " + response.statusCode); + } +}; +const buildHttpRpcRequest = async (context, headers, path, resolvedHostname, body) => { + const { hostname, protocol = "https", port, path: basePath } = await context.endpoint(); + const contents = { + protocol, + hostname, + port, + method: "POST", + path: basePath.endsWith("/") ? basePath.slice(0, -1) + path : basePath + path, + headers: { + ...headers, + }, + }; + if (resolvedHostname !== undefined) { + contents.hostname = resolvedHostname; + } + if (body !== undefined) { + contents.body = body; + try { + contents.headers["content-length"] = String(utilBodyLengthBrowser.calculateBodyLength(body)); + } + catch (e) { } + } + return new protocolHttp.HttpRequest(contents); +}; + +class CborCodec extends protocols.SerdeContext { + createSerializer() { + const serializer = new CborShapeSerializer(); + serializer.setSerdeContext(this.serdeContext); + return serializer; + } + createDeserializer() { + const deserializer = new CborShapeDeserializer(); + deserializer.setSerdeContext(this.serdeContext); + return deserializer; + } +} +class CborShapeSerializer extends protocols.SerdeContext { + value; + write(schema, value) { + this.value = this.serialize(schema, value); + } + serialize(schema$1, source) { + const ns = schema.NormalizedSchema.of(schema$1); + if (source == null) { + if (ns.isIdempotencyToken()) { + return serde.generateIdempotencyToken(); + } + return source; + } + if (ns.isBlobSchema()) { + if (typeof source === "string") { + return (this.serdeContext?.base64Decoder ?? utilBase64.fromBase64)(source); + } + return source; + } + if (ns.isTimestampSchema()) { + if (typeof source === "number" || typeof source === "bigint") { + return dateToTag(new Date((Number(source) / 1000) | 0)); + } + return dateToTag(source); + } + if (typeof source === "function" || typeof source === "object") { + const sourceObject = source; + if (ns.isListSchema() && Array.isArray(sourceObject)) { + const sparse = !!ns.getMergedTraits().sparse; + const newArray = []; + let i = 0; + for (const item of sourceObject) { + const value = this.serialize(ns.getValueSchema(), item); + if (value != null || sparse) { + newArray[i++] = value; + } + } + return newArray; + } + if (sourceObject instanceof Date) { + return dateToTag(sourceObject); + } + const newObject = {}; + if (ns.isMapSchema()) { + const sparse = !!ns.getMergedTraits().sparse; + for (const key of Object.keys(sourceObject)) { + const value = this.serialize(ns.getValueSchema(), sourceObject[key]); + if (value != null || sparse) { + newObject[key] = value; + } + } + } + else if (ns.isStructSchema()) { + for (const [key, memberSchema] of ns.structIterator()) { + const value = this.serialize(memberSchema, sourceObject[key]); + if (value != null) { + newObject[key] = value; + } + } + } + else if (ns.isDocumentSchema()) { + for (const key of Object.keys(sourceObject)) { + newObject[key] = this.serialize(ns.getValueSchema(), sourceObject[key]); + } + } + return newObject; + } + return source; + } + flush() { + const buffer = cbor.serialize(this.value); + this.value = undefined; + return buffer; + } +} +class CborShapeDeserializer extends protocols.SerdeContext { + read(schema, bytes) { + const data = cbor.deserialize(bytes); + return this.readValue(schema, data); + } + readValue(_schema, value) { + const ns = schema.NormalizedSchema.of(_schema); + if (ns.isTimestampSchema() && typeof value === "number") { + return serde._parseEpochTimestamp(value); + } + if (ns.isBlobSchema()) { + if (typeof value === "string") { + return (this.serdeContext?.base64Decoder ?? utilBase64.fromBase64)(value); + } + return value; + } + if (typeof value === "undefined" || + typeof value === "boolean" || + typeof value === "number" || + typeof value === "string" || + typeof value === "bigint" || + typeof value === "symbol") { + return value; + } + else if (typeof value === "function" || typeof value === "object") { + if (value === null) { + return null; + } + if ("byteLength" in value) { + return value; + } + if (value instanceof Date) { + return value; + } + if (ns.isDocumentSchema()) { + return value; + } + if (ns.isListSchema()) { + const newArray = []; + const memberSchema = ns.getValueSchema(); + const sparse = !!ns.getMergedTraits().sparse; + for (const item of value) { + const itemValue = this.readValue(memberSchema, item); + if (itemValue != null || sparse) { + newArray.push(itemValue); + } + } + return newArray; + } + const newObject = {}; + if (ns.isMapSchema()) { + const sparse = !!ns.getMergedTraits().sparse; + const targetSchema = ns.getValueSchema(); + for (const key of Object.keys(value)) { + const itemValue = this.readValue(targetSchema, value[key]); + if (itemValue != null || sparse) { + newObject[key] = itemValue; + } + } + } + else if (ns.isStructSchema()) { + for (const [key, memberSchema] of ns.structIterator()) { + const v = this.readValue(memberSchema, value[key]); + if (v != null) { + newObject[key] = v; + } + } + } + return newObject; + } + else { + return value; + } + } +} + +class SmithyRpcV2CborProtocol extends protocols.RpcProtocol { + codec = new CborCodec(); + serializer = this.codec.createSerializer(); + deserializer = this.codec.createDeserializer(); + constructor({ defaultNamespace }) { + super({ defaultNamespace }); + } + getShapeId() { + return "smithy.protocols#rpcv2Cbor"; + } + getPayloadCodec() { + return this.codec; + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + Object.assign(request.headers, { + "content-type": this.getDefaultContentType(), + "smithy-protocol": "rpc-v2-cbor", + accept: this.getDefaultContentType(), + }); + if (schema.deref(operationSchema.input) === "unit") { + delete request.body; + delete request.headers["content-type"]; + } + else { + if (!request.body) { + this.serializer.write(15, {}); + request.body = this.serializer.flush(); + } + try { + request.headers["content-length"] = String(request.body.byteLength); + } + catch (e) { } + } + const { service, operation } = utilMiddleware.getSmithyContext(context); + const path = `/service/${service}/operation/${operation}`; + if (request.path.endsWith("/")) { + request.path += path.slice(1); + } + else { + request.path += path; + } + return request; + } + async deserializeResponse(operationSchema, context, response) { + return super.deserializeResponse(operationSchema, context, response); + } + async handleError(operationSchema, context, response, dataObject, metadata) { + const errorName = loadSmithyRpcV2CborErrorCode(response, dataObject) ?? "Unknown"; + let namespace = this.options.defaultNamespace; + if (errorName.includes("#")) { + [namespace] = errorName.split("#"); + } + const errorMetadata = { + $metadata: metadata, + $fault: response.statusCode <= 500 ? "client" : "server", + }; + const registry = schema.TypeRegistry.for(namespace); + let errorSchema; + try { + errorSchema = registry.getSchema(errorName); + } + catch (e) { + if (dataObject.Message) { + dataObject.message = dataObject.Message; + } + const synthetic = schema.TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace); + const baseExceptionSchema = synthetic.getBaseException(); + if (baseExceptionSchema) { + const ErrorCtor = synthetic.getErrorCtor(baseExceptionSchema); + throw Object.assign(new ErrorCtor({ name: errorName }), errorMetadata, dataObject); + } + throw Object.assign(new Error(errorName), errorMetadata, dataObject); + } + const ns = schema.NormalizedSchema.of(errorSchema); + const ErrorCtor = registry.getErrorCtor(errorSchema); + const message = dataObject.message ?? dataObject.Message ?? "Unknown"; + const exception = new ErrorCtor(message); + const output = {}; + for (const [name, member] of ns.structIterator()) { + output[name] = this.deserializer.readValue(member, dataObject[name]); + } + throw Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message, + }, output); + } + getDefaultContentType() { + return "application/cbor"; + } +} + +exports.CborCodec = CborCodec; +exports.CborShapeDeserializer = CborShapeDeserializer; +exports.CborShapeSerializer = CborShapeSerializer; +exports.SmithyRpcV2CborProtocol = SmithyRpcV2CborProtocol; +exports.buildHttpRpcRequest = buildHttpRpcRequest; +exports.cbor = cbor; +exports.checkCborResponse = checkCborResponse; +exports.dateToTag = dateToTag; +exports.loadSmithyRpcV2CborErrorCode = loadSmithyRpcV2CborErrorCode; +exports.parseCborBody = parseCborBody; +exports.parseCborErrorBody = parseCborErrorBody; +exports.tag = tag; +exports.tagSymbol = tagSymbol; diff --git a/claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/event-streams/index.js b/claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/event-streams/index.js new file mode 100644 index 00000000..163917b9 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/event-streams/index.js @@ -0,0 +1,252 @@ +'use strict'; + +var utilUtf8 = require('@smithy/util-utf8'); + +class EventStreamSerde { + marshaller; + serializer; + deserializer; + serdeContext; + defaultContentType; + constructor({ marshaller, serializer, deserializer, serdeContext, defaultContentType, }) { + this.marshaller = marshaller; + this.serializer = serializer; + this.deserializer = deserializer; + this.serdeContext = serdeContext; + this.defaultContentType = defaultContentType; + } + async serializeEventStream({ eventStream, requestSchema, initialRequest, }) { + const marshaller = this.marshaller; + const eventStreamMember = requestSchema.getEventStreamMember(); + const unionSchema = requestSchema.getMemberSchema(eventStreamMember); + const serializer = this.serializer; + const defaultContentType = this.defaultContentType; + const initialRequestMarker = Symbol("initialRequestMarker"); + const eventStreamIterable = { + async *[Symbol.asyncIterator]() { + if (initialRequest) { + const headers = { + ":event-type": { type: "string", value: "initial-request" }, + ":message-type": { type: "string", value: "event" }, + ":content-type": { type: "string", value: defaultContentType }, + }; + serializer.write(requestSchema, initialRequest); + const body = serializer.flush(); + yield { + [initialRequestMarker]: true, + headers, + body, + }; + } + for await (const page of eventStream) { + yield page; + } + }, + }; + return marshaller.serialize(eventStreamIterable, (event) => { + if (event[initialRequestMarker]) { + return { + headers: event.headers, + body: event.body, + }; + } + const unionMember = Object.keys(event).find((key) => { + return key !== "__type"; + }) ?? ""; + const { additionalHeaders, body, eventType, explicitPayloadContentType } = this.writeEventBody(unionMember, unionSchema, event); + const headers = { + ":event-type": { type: "string", value: eventType }, + ":message-type": { type: "string", value: "event" }, + ":content-type": { type: "string", value: explicitPayloadContentType ?? defaultContentType }, + ...additionalHeaders, + }; + return { + headers, + body, + }; + }); + } + async deserializeEventStream({ response, responseSchema, initialResponseContainer, }) { + const marshaller = this.marshaller; + const eventStreamMember = responseSchema.getEventStreamMember(); + const unionSchema = responseSchema.getMemberSchema(eventStreamMember); + const memberSchemas = unionSchema.getMemberSchemas(); + const initialResponseMarker = Symbol("initialResponseMarker"); + const asyncIterable = marshaller.deserialize(response.body, async (event) => { + const unionMember = Object.keys(event).find((key) => { + return key !== "__type"; + }) ?? ""; + const body = event[unionMember].body; + if (unionMember === "initial-response") { + const dataObject = await this.deserializer.read(responseSchema, body); + delete dataObject[eventStreamMember]; + return { + [initialResponseMarker]: true, + ...dataObject, + }; + } + else if (unionMember in memberSchemas) { + const eventStreamSchema = memberSchemas[unionMember]; + if (eventStreamSchema.isStructSchema()) { + const out = {}; + let hasBindings = false; + for (const [name, member] of eventStreamSchema.structIterator()) { + const { eventHeader, eventPayload } = member.getMergedTraits(); + hasBindings = hasBindings || Boolean(eventHeader || eventPayload); + if (eventPayload) { + if (member.isBlobSchema()) { + out[name] = body; + } + else if (member.isStringSchema()) { + out[name] = (this.serdeContext?.utf8Encoder ?? utilUtf8.toUtf8)(body); + } + else if (member.isStructSchema()) { + out[name] = await this.deserializer.read(member, body); + } + } + else if (eventHeader) { + const value = event[unionMember].headers[name]?.value; + if (value != null) { + if (member.isNumericSchema()) { + if (value && typeof value === "object" && "bytes" in value) { + out[name] = BigInt(value.toString()); + } + else { + out[name] = Number(value); + } + } + else { + out[name] = value; + } + } + } + } + if (hasBindings) { + return { + [unionMember]: out, + }; + } + } + return { + [unionMember]: await this.deserializer.read(eventStreamSchema, body), + }; + } + else { + return { + $unknown: event, + }; + } + }); + const asyncIterator = asyncIterable[Symbol.asyncIterator](); + const firstEvent = await asyncIterator.next(); + if (firstEvent.done) { + return asyncIterable; + } + if (firstEvent.value?.[initialResponseMarker]) { + if (!responseSchema) { + throw new Error("@smithy::core/protocols - initial-response event encountered in event stream but no response schema given."); + } + for (const [key, value] of Object.entries(firstEvent.value)) { + initialResponseContainer[key] = value; + } + } + return { + async *[Symbol.asyncIterator]() { + if (!firstEvent?.value?.[initialResponseMarker]) { + yield firstEvent.value; + } + while (true) { + const { done, value } = await asyncIterator.next(); + if (done) { + break; + } + yield value; + } + }, + }; + } + writeEventBody(unionMember, unionSchema, event) { + const serializer = this.serializer; + let eventType = unionMember; + let explicitPayloadMember = null; + let explicitPayloadContentType; + const isKnownSchema = (() => { + const struct = unionSchema.getSchema(); + return struct[4].includes(unionMember); + })(); + const additionalHeaders = {}; + if (!isKnownSchema) { + const [type, value] = event[unionMember]; + eventType = type; + serializer.write(15, value); + } + else { + const eventSchema = unionSchema.getMemberSchema(unionMember); + if (eventSchema.isStructSchema()) { + for (const [memberName, memberSchema] of eventSchema.structIterator()) { + const { eventHeader, eventPayload } = memberSchema.getMergedTraits(); + if (eventPayload) { + explicitPayloadMember = memberName; + break; + } + else if (eventHeader) { + const value = event[unionMember][memberName]; + let type = "binary"; + if (memberSchema.isNumericSchema()) { + if ((-2) ** 31 <= value && value <= 2 ** 31 - 1) { + type = "integer"; + } + else { + type = "long"; + } + } + else if (memberSchema.isTimestampSchema()) { + type = "timestamp"; + } + else if (memberSchema.isStringSchema()) { + type = "string"; + } + else if (memberSchema.isBooleanSchema()) { + type = "boolean"; + } + if (value != null) { + additionalHeaders[memberName] = { + type, + value, + }; + delete event[unionMember][memberName]; + } + } + } + if (explicitPayloadMember !== null) { + const payloadSchema = eventSchema.getMemberSchema(explicitPayloadMember); + if (payloadSchema.isBlobSchema()) { + explicitPayloadContentType = "application/octet-stream"; + } + else if (payloadSchema.isStringSchema()) { + explicitPayloadContentType = "text/plain"; + } + serializer.write(payloadSchema, event[unionMember][explicitPayloadMember]); + } + else { + serializer.write(eventSchema, event[unionMember]); + } + } + else { + throw new Error("@smithy/core/event-streams - non-struct member not supported in event stream union."); + } + } + const messageSerialization = serializer.flush(); + const body = typeof messageSerialization === "string" + ? (this.serdeContext?.utf8Decoder ?? utilUtf8.fromUtf8)(messageSerialization) + : messageSerialization; + return { + body, + eventType, + explicitPayloadContentType, + additionalHeaders, + }; + } +} + +exports.EventStreamSerde = EventStreamSerde; diff --git a/claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/protocols/index.js b/claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/protocols/index.js new file mode 100644 index 00000000..cb367dd7 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/protocols/index.js @@ -0,0 +1,839 @@ +'use strict'; + +var utilStream = require('@smithy/util-stream'); +var schema = require('@smithy/core/schema'); +var serde = require('@smithy/core/serde'); +var protocolHttp = require('@smithy/protocol-http'); +var utilBase64 = require('@smithy/util-base64'); +var utilUtf8 = require('@smithy/util-utf8'); + +const collectBody = async (streamBody = new Uint8Array(), context) => { + if (streamBody instanceof Uint8Array) { + return utilStream.Uint8ArrayBlobAdapter.mutate(streamBody); + } + if (!streamBody) { + return utilStream.Uint8ArrayBlobAdapter.mutate(new Uint8Array()); + } + const fromContext = context.streamCollector(streamBody); + return utilStream.Uint8ArrayBlobAdapter.mutate(await fromContext); +}; + +function extendedEncodeURIComponent(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function (c) { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); + }); +} + +class SerdeContext { + serdeContext; + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + } +} + +class HttpProtocol extends SerdeContext { + options; + constructor(options) { + super(); + this.options = options; + } + getRequestType() { + return protocolHttp.HttpRequest; + } + getResponseType() { + return protocolHttp.HttpResponse; + } + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + this.serializer.setSerdeContext(serdeContext); + this.deserializer.setSerdeContext(serdeContext); + if (this.getPayloadCodec()) { + this.getPayloadCodec().setSerdeContext(serdeContext); + } + } + updateServiceEndpoint(request, endpoint) { + if ("url" in endpoint) { + request.protocol = endpoint.url.protocol; + request.hostname = endpoint.url.hostname; + request.port = endpoint.url.port ? Number(endpoint.url.port) : undefined; + request.path = endpoint.url.pathname; + request.fragment = endpoint.url.hash || void 0; + request.username = endpoint.url.username || void 0; + request.password = endpoint.url.password || void 0; + if (!request.query) { + request.query = {}; + } + for (const [k, v] of endpoint.url.searchParams.entries()) { + request.query[k] = v; + } + return request; + } + else { + request.protocol = endpoint.protocol; + request.hostname = endpoint.hostname; + request.port = endpoint.port ? Number(endpoint.port) : undefined; + request.path = endpoint.path; + request.query = { + ...endpoint.query, + }; + return request; + } + } + setHostPrefix(request, operationSchema, input) { + const inputNs = schema.NormalizedSchema.of(operationSchema.input); + const opTraits = schema.translateTraits(operationSchema.traits ?? {}); + if (opTraits.endpoint) { + let hostPrefix = opTraits.endpoint?.[0]; + if (typeof hostPrefix === "string") { + const hostLabelInputs = [...inputNs.structIterator()].filter(([, member]) => member.getMergedTraits().hostLabel); + for (const [name] of hostLabelInputs) { + const replacement = input[name]; + if (typeof replacement !== "string") { + throw new Error(`@smithy/core/schema - ${name} in input must be a string as hostLabel.`); + } + hostPrefix = hostPrefix.replace(`{${name}}`, replacement); + } + request.hostname = hostPrefix + request.hostname; + } + } + } + deserializeMetadata(output) { + return { + httpStatusCode: output.statusCode, + requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], + extendedRequestId: output.headers["x-amz-id-2"], + cfId: output.headers["x-amz-cf-id"], + }; + } + async serializeEventStream({ eventStream, requestSchema, initialRequest, }) { + const eventStreamSerde = await this.loadEventStreamCapability(); + return eventStreamSerde.serializeEventStream({ + eventStream, + requestSchema, + initialRequest, + }); + } + async deserializeEventStream({ response, responseSchema, initialResponseContainer, }) { + const eventStreamSerde = await this.loadEventStreamCapability(); + return eventStreamSerde.deserializeEventStream({ + response, + responseSchema, + initialResponseContainer, + }); + } + async loadEventStreamCapability() { + const { EventStreamSerde } = await import('@smithy/core/event-streams'); + return new EventStreamSerde({ + marshaller: this.getEventStreamMarshaller(), + serializer: this.serializer, + deserializer: this.deserializer, + serdeContext: this.serdeContext, + defaultContentType: this.getDefaultContentType(), + }); + } + getDefaultContentType() { + throw new Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`); + } + async deserializeHttpMessage(schema, context, response, arg4, arg5) { + return []; + } + getEventStreamMarshaller() { + const context = this.serdeContext; + if (!context.eventStreamMarshaller) { + throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext."); + } + return context.eventStreamMarshaller; + } +} + +class HttpBindingProtocol extends HttpProtocol { + async serializeRequest(operationSchema, _input, context) { + const input = { + ...(_input ?? {}), + }; + const serializer = this.serializer; + const query = {}; + const headers = {}; + const endpoint = await context.endpoint(); + const ns = schema.NormalizedSchema.of(operationSchema?.input); + const schema$1 = ns.getSchema(); + let hasNonHttpBindingMember = false; + let payload; + const request = new protocolHttp.HttpRequest({ + protocol: "", + hostname: "", + port: undefined, + path: "", + fragment: undefined, + query: query, + headers: headers, + body: undefined, + }); + if (endpoint) { + this.updateServiceEndpoint(request, endpoint); + this.setHostPrefix(request, operationSchema, input); + const opTraits = schema.translateTraits(operationSchema.traits); + if (opTraits.http) { + request.method = opTraits.http[0]; + const [path, search] = opTraits.http[1].split("?"); + if (request.path == "/") { + request.path = path; + } + else { + request.path += path; + } + const traitSearchParams = new URLSearchParams(search ?? ""); + Object.assign(query, Object.fromEntries(traitSearchParams)); + } + } + for (const [memberName, memberNs] of ns.structIterator()) { + const memberTraits = memberNs.getMergedTraits() ?? {}; + const inputMemberValue = input[memberName]; + if (inputMemberValue == null && !memberNs.isIdempotencyToken()) { + continue; + } + if (memberTraits.httpPayload) { + const isStreaming = memberNs.isStreaming(); + if (isStreaming) { + const isEventStream = memberNs.isStructSchema(); + if (isEventStream) { + if (input[memberName]) { + payload = await this.serializeEventStream({ + eventStream: input[memberName], + requestSchema: ns, + }); + } + } + else { + payload = inputMemberValue; + } + } + else { + serializer.write(memberNs, inputMemberValue); + payload = serializer.flush(); + } + delete input[memberName]; + } + else if (memberTraits.httpLabel) { + serializer.write(memberNs, inputMemberValue); + const replacement = serializer.flush(); + if (request.path.includes(`{${memberName}+}`)) { + request.path = request.path.replace(`{${memberName}+}`, replacement.split("/").map(extendedEncodeURIComponent).join("/")); + } + else if (request.path.includes(`{${memberName}}`)) { + request.path = request.path.replace(`{${memberName}}`, extendedEncodeURIComponent(replacement)); + } + delete input[memberName]; + } + else if (memberTraits.httpHeader) { + serializer.write(memberNs, inputMemberValue); + headers[memberTraits.httpHeader.toLowerCase()] = String(serializer.flush()); + delete input[memberName]; + } + else if (typeof memberTraits.httpPrefixHeaders === "string") { + for (const [key, val] of Object.entries(inputMemberValue)) { + const amalgam = memberTraits.httpPrefixHeaders + key; + serializer.write([memberNs.getValueSchema(), { httpHeader: amalgam }], val); + headers[amalgam.toLowerCase()] = serializer.flush(); + } + delete input[memberName]; + } + else if (memberTraits.httpQuery || memberTraits.httpQueryParams) { + this.serializeQuery(memberNs, inputMemberValue, query); + delete input[memberName]; + } + else { + hasNonHttpBindingMember = true; + } + } + if (hasNonHttpBindingMember && input) { + serializer.write(schema$1, input); + payload = serializer.flush(); + } + request.headers = headers; + request.query = query; + request.body = payload; + return request; + } + serializeQuery(ns, data, query) { + const serializer = this.serializer; + const traits = ns.getMergedTraits(); + if (traits.httpQueryParams) { + for (const [key, val] of Object.entries(data)) { + if (!(key in query)) { + const valueSchema = ns.getValueSchema(); + Object.assign(valueSchema.getMergedTraits(), { + ...traits, + httpQuery: key, + httpQueryParams: undefined, + }); + this.serializeQuery(valueSchema, val, query); + } + } + return; + } + if (ns.isListSchema()) { + const sparse = !!ns.getMergedTraits().sparse; + const buffer = []; + for (const item of data) { + serializer.write([ns.getValueSchema(), traits], item); + const serializable = serializer.flush(); + if (sparse || serializable !== undefined) { + buffer.push(serializable); + } + } + query[traits.httpQuery] = buffer; + } + else { + serializer.write([ns, traits], data); + query[traits.httpQuery] = serializer.flush(); + } + } + async deserializeResponse(operationSchema, context, response) { + const deserializer = this.deserializer; + const ns = schema.NormalizedSchema.of(operationSchema.output); + const dataObject = {}; + if (response.statusCode >= 300) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(15, bytes)); + } + await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); + throw new Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw."); + } + for (const header in response.headers) { + const value = response.headers[header]; + delete response.headers[header]; + response.headers[header.toLowerCase()] = value; + } + const nonHttpBindingMembers = await this.deserializeHttpMessage(ns, context, response, dataObject); + if (nonHttpBindingMembers.length) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + const dataFromBody = await deserializer.read(ns, bytes); + for (const member of nonHttpBindingMembers) { + dataObject[member] = dataFromBody[member]; + } + } + } + else if (nonHttpBindingMembers.discardResponseBody) { + await collectBody(response.body, context); + } + dataObject.$metadata = this.deserializeMetadata(response); + return dataObject; + } + async deserializeHttpMessage(schema$1, context, response, arg4, arg5) { + let dataObject; + if (arg4 instanceof Set) { + dataObject = arg5; + } + else { + dataObject = arg4; + } + let discardResponseBody = true; + const deserializer = this.deserializer; + const ns = schema.NormalizedSchema.of(schema$1); + const nonHttpBindingMembers = []; + for (const [memberName, memberSchema] of ns.structIterator()) { + const memberTraits = memberSchema.getMemberTraits(); + if (memberTraits.httpPayload) { + discardResponseBody = false; + const isStreaming = memberSchema.isStreaming(); + if (isStreaming) { + const isEventStream = memberSchema.isStructSchema(); + if (isEventStream) { + dataObject[memberName] = await this.deserializeEventStream({ + response, + responseSchema: ns, + }); + } + else { + dataObject[memberName] = utilStream.sdkStreamMixin(response.body); + } + } + else if (response.body) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + dataObject[memberName] = await deserializer.read(memberSchema, bytes); + } + } + } + else if (memberTraits.httpHeader) { + const key = String(memberTraits.httpHeader).toLowerCase(); + const value = response.headers[key]; + if (null != value) { + if (memberSchema.isListSchema()) { + const headerListValueSchema = memberSchema.getValueSchema(); + headerListValueSchema.getMergedTraits().httpHeader = key; + let sections; + if (headerListValueSchema.isTimestampSchema() && + headerListValueSchema.getSchema() === 4) { + sections = serde.splitEvery(value, ",", 2); + } + else { + sections = serde.splitHeader(value); + } + const list = []; + for (const section of sections) { + list.push(await deserializer.read(headerListValueSchema, section.trim())); + } + dataObject[memberName] = list; + } + else { + dataObject[memberName] = await deserializer.read(memberSchema, value); + } + } + } + else if (memberTraits.httpPrefixHeaders !== undefined) { + dataObject[memberName] = {}; + for (const [header, value] of Object.entries(response.headers)) { + if (header.startsWith(memberTraits.httpPrefixHeaders)) { + const valueSchema = memberSchema.getValueSchema(); + valueSchema.getMergedTraits().httpHeader = header; + dataObject[memberName][header.slice(memberTraits.httpPrefixHeaders.length)] = await deserializer.read(valueSchema, value); + } + } + } + else if (memberTraits.httpResponseCode) { + dataObject[memberName] = response.statusCode; + } + else { + nonHttpBindingMembers.push(memberName); + } + } + nonHttpBindingMembers.discardResponseBody = discardResponseBody; + return nonHttpBindingMembers; + } +} + +class RpcProtocol extends HttpProtocol { + async serializeRequest(operationSchema, input, context) { + const serializer = this.serializer; + const query = {}; + const headers = {}; + const endpoint = await context.endpoint(); + const ns = schema.NormalizedSchema.of(operationSchema?.input); + const schema$1 = ns.getSchema(); + let payload; + const request = new protocolHttp.HttpRequest({ + protocol: "", + hostname: "", + port: undefined, + path: "/", + fragment: undefined, + query: query, + headers: headers, + body: undefined, + }); + if (endpoint) { + this.updateServiceEndpoint(request, endpoint); + this.setHostPrefix(request, operationSchema, input); + } + const _input = { + ...input, + }; + if (input) { + const eventStreamMember = ns.getEventStreamMember(); + if (eventStreamMember) { + if (_input[eventStreamMember]) { + const initialRequest = {}; + for (const [memberName, memberSchema] of ns.structIterator()) { + if (memberName !== eventStreamMember && _input[memberName]) { + serializer.write(memberSchema, _input[memberName]); + initialRequest[memberName] = serializer.flush(); + } + } + payload = await this.serializeEventStream({ + eventStream: _input[eventStreamMember], + requestSchema: ns, + initialRequest, + }); + } + } + else { + serializer.write(schema$1, _input); + payload = serializer.flush(); + } + } + request.headers = headers; + request.query = query; + request.body = payload; + request.method = "POST"; + return request; + } + async deserializeResponse(operationSchema, context, response) { + const deserializer = this.deserializer; + const ns = schema.NormalizedSchema.of(operationSchema.output); + const dataObject = {}; + if (response.statusCode >= 300) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(15, bytes)); + } + await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); + throw new Error("@smithy/core/protocols - RPC Protocol error handler failed to throw."); + } + for (const header in response.headers) { + const value = response.headers[header]; + delete response.headers[header]; + response.headers[header.toLowerCase()] = value; + } + const eventStreamMember = ns.getEventStreamMember(); + if (eventStreamMember) { + dataObject[eventStreamMember] = await this.deserializeEventStream({ + response, + responseSchema: ns, + initialResponseContainer: dataObject, + }); + } + else { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(ns, bytes)); + } + } + dataObject.$metadata = this.deserializeMetadata(response); + return dataObject; + } +} + +const resolvedPath = (resolvedPath, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => { + if (input != null && input[memberName] !== undefined) { + const labelValue = labelValueProvider(); + if (labelValue.length <= 0) { + throw new Error("Empty value provided for input HTTP label: " + memberName + "."); + } + resolvedPath = resolvedPath.replace(uriLabel, isGreedyLabel + ? labelValue + .split("/") + .map((segment) => extendedEncodeURIComponent(segment)) + .join("/") + : extendedEncodeURIComponent(labelValue)); + } + else { + throw new Error("No value provided for input HTTP label: " + memberName + "."); + } + return resolvedPath; +}; + +function requestBuilder(input, context) { + return new RequestBuilder(input, context); +} +class RequestBuilder { + input; + context; + query = {}; + method = ""; + headers = {}; + path = ""; + body = null; + hostname = ""; + resolvePathStack = []; + constructor(input, context) { + this.input = input; + this.context = context; + } + async build() { + const { hostname, protocol = "https", port, path: basePath } = await this.context.endpoint(); + this.path = basePath; + for (const resolvePath of this.resolvePathStack) { + resolvePath(this.path); + } + return new protocolHttp.HttpRequest({ + protocol, + hostname: this.hostname || hostname, + port, + method: this.method, + path: this.path, + query: this.query, + body: this.body, + headers: this.headers, + }); + } + hn(hostname) { + this.hostname = hostname; + return this; + } + bp(uriLabel) { + this.resolvePathStack.push((basePath) => { + this.path = `${basePath?.endsWith("/") ? basePath.slice(0, -1) : basePath || ""}` + uriLabel; + }); + return this; + } + p(memberName, labelValueProvider, uriLabel, isGreedyLabel) { + this.resolvePathStack.push((path) => { + this.path = resolvedPath(path, this.input, memberName, labelValueProvider, uriLabel, isGreedyLabel); + }); + return this; + } + h(headers) { + this.headers = headers; + return this; + } + q(query) { + this.query = query; + return this; + } + b(body) { + this.body = body; + return this; + } + m(method) { + this.method = method; + return this; + } +} + +function determineTimestampFormat(ns, settings) { + if (settings.timestampFormat.useTrait) { + if (ns.isTimestampSchema() && + (ns.getSchema() === 5 || + ns.getSchema() === 6 || + ns.getSchema() === 7)) { + return ns.getSchema(); + } + } + const { httpLabel, httpPrefixHeaders, httpHeader, httpQuery } = ns.getMergedTraits(); + const bindingFormat = settings.httpBindings + ? typeof httpPrefixHeaders === "string" || Boolean(httpHeader) + ? 6 + : Boolean(httpQuery) || Boolean(httpLabel) + ? 5 + : undefined + : undefined; + return bindingFormat ?? settings.timestampFormat.default; +} + +class FromStringShapeDeserializer extends SerdeContext { + settings; + constructor(settings) { + super(); + this.settings = settings; + } + read(_schema, data) { + const ns = schema.NormalizedSchema.of(_schema); + if (ns.isListSchema()) { + return serde.splitHeader(data).map((item) => this.read(ns.getValueSchema(), item)); + } + if (ns.isBlobSchema()) { + return (this.serdeContext?.base64Decoder ?? utilBase64.fromBase64)(data); + } + if (ns.isTimestampSchema()) { + const format = determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: + return serde._parseRfc3339DateTimeWithOffset(data); + case 6: + return serde._parseRfc7231DateTime(data); + case 7: + return serde._parseEpochTimestamp(data); + default: + console.warn("Missing timestamp format, parsing value with Date constructor:", data); + return new Date(data); + } + } + if (ns.isStringSchema()) { + const mediaType = ns.getMergedTraits().mediaType; + let intermediateValue = data; + if (mediaType) { + if (ns.getMergedTraits().httpHeader) { + intermediateValue = this.base64ToUtf8(intermediateValue); + } + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + intermediateValue = serde.LazyJsonString.from(intermediateValue); + } + return intermediateValue; + } + } + if (ns.isNumericSchema()) { + return Number(data); + } + if (ns.isBigIntegerSchema()) { + return BigInt(data); + } + if (ns.isBigDecimalSchema()) { + return new serde.NumericValue(data, "bigDecimal"); + } + if (ns.isBooleanSchema()) { + return String(data).toLowerCase() === "true"; + } + return data; + } + base64ToUtf8(base64String) { + return (this.serdeContext?.utf8Encoder ?? utilUtf8.toUtf8)((this.serdeContext?.base64Decoder ?? utilBase64.fromBase64)(base64String)); + } +} + +class HttpInterceptingShapeDeserializer extends SerdeContext { + codecDeserializer; + stringDeserializer; + constructor(codecDeserializer, codecSettings) { + super(); + this.codecDeserializer = codecDeserializer; + this.stringDeserializer = new FromStringShapeDeserializer(codecSettings); + } + setSerdeContext(serdeContext) { + this.stringDeserializer.setSerdeContext(serdeContext); + this.codecDeserializer.setSerdeContext(serdeContext); + this.serdeContext = serdeContext; + } + read(schema$1, data) { + const ns = schema.NormalizedSchema.of(schema$1); + const traits = ns.getMergedTraits(); + const toString = this.serdeContext?.utf8Encoder ?? utilUtf8.toUtf8; + if (traits.httpHeader || traits.httpResponseCode) { + return this.stringDeserializer.read(ns, toString(data)); + } + if (traits.httpPayload) { + if (ns.isBlobSchema()) { + const toBytes = this.serdeContext?.utf8Decoder ?? utilUtf8.fromUtf8; + if (typeof data === "string") { + return toBytes(data); + } + return data; + } + else if (ns.isStringSchema()) { + if ("byteLength" in data) { + return toString(data); + } + return data; + } + } + return this.codecDeserializer.read(ns, data); + } +} + +class ToStringShapeSerializer extends SerdeContext { + settings; + stringBuffer = ""; + constructor(settings) { + super(); + this.settings = settings; + } + write(schema$1, value) { + const ns = schema.NormalizedSchema.of(schema$1); + switch (typeof value) { + case "object": + if (value === null) { + this.stringBuffer = "null"; + return; + } + if (ns.isTimestampSchema()) { + if (!(value instanceof Date)) { + throw new Error(`@smithy/core/protocols - received non-Date value ${value} when schema expected Date in ${ns.getName(true)}`); + } + const format = determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: + this.stringBuffer = value.toISOString().replace(".000Z", "Z"); + break; + case 6: + this.stringBuffer = serde.dateToUtcString(value); + break; + case 7: + this.stringBuffer = String(value.getTime() / 1000); + break; + default: + console.warn("Missing timestamp format, using epoch seconds", value); + this.stringBuffer = String(value.getTime() / 1000); + } + return; + } + if (ns.isBlobSchema() && "byteLength" in value) { + this.stringBuffer = (this.serdeContext?.base64Encoder ?? utilBase64.toBase64)(value); + return; + } + if (ns.isListSchema() && Array.isArray(value)) { + let buffer = ""; + for (const item of value) { + this.write([ns.getValueSchema(), ns.getMergedTraits()], item); + const headerItem = this.flush(); + const serialized = ns.getValueSchema().isTimestampSchema() ? headerItem : serde.quoteHeader(headerItem); + if (buffer !== "") { + buffer += ", "; + } + buffer += serialized; + } + this.stringBuffer = buffer; + return; + } + this.stringBuffer = JSON.stringify(value, null, 2); + break; + case "string": + const mediaType = ns.getMergedTraits().mediaType; + let intermediateValue = value; + if (mediaType) { + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + intermediateValue = serde.LazyJsonString.from(intermediateValue); + } + if (ns.getMergedTraits().httpHeader) { + this.stringBuffer = (this.serdeContext?.base64Encoder ?? utilBase64.toBase64)(intermediateValue.toString()); + return; + } + } + this.stringBuffer = value; + break; + default: + if (ns.isIdempotencyToken()) { + this.stringBuffer = serde.generateIdempotencyToken(); + } + else { + this.stringBuffer = String(value); + } + } + } + flush() { + const buffer = this.stringBuffer; + this.stringBuffer = ""; + return buffer; + } +} + +class HttpInterceptingShapeSerializer { + codecSerializer; + stringSerializer; + buffer; + constructor(codecSerializer, codecSettings, stringSerializer = new ToStringShapeSerializer(codecSettings)) { + this.codecSerializer = codecSerializer; + this.stringSerializer = stringSerializer; + } + setSerdeContext(serdeContext) { + this.codecSerializer.setSerdeContext(serdeContext); + this.stringSerializer.setSerdeContext(serdeContext); + } + write(schema$1, value) { + const ns = schema.NormalizedSchema.of(schema$1); + const traits = ns.getMergedTraits(); + if (traits.httpHeader || traits.httpLabel || traits.httpQuery) { + this.stringSerializer.write(ns, value); + this.buffer = this.stringSerializer.flush(); + return; + } + return this.codecSerializer.write(ns, value); + } + flush() { + if (this.buffer !== undefined) { + const buffer = this.buffer; + this.buffer = undefined; + return buffer; + } + return this.codecSerializer.flush(); + } +} + +exports.FromStringShapeDeserializer = FromStringShapeDeserializer; +exports.HttpBindingProtocol = HttpBindingProtocol; +exports.HttpInterceptingShapeDeserializer = HttpInterceptingShapeDeserializer; +exports.HttpInterceptingShapeSerializer = HttpInterceptingShapeSerializer; +exports.HttpProtocol = HttpProtocol; +exports.RequestBuilder = RequestBuilder; +exports.RpcProtocol = RpcProtocol; +exports.SerdeContext = SerdeContext; +exports.ToStringShapeSerializer = ToStringShapeSerializer; +exports.collectBody = collectBody; +exports.determineTimestampFormat = determineTimestampFormat; +exports.extendedEncodeURIComponent = extendedEncodeURIComponent; +exports.requestBuilder = requestBuilder; +exports.resolvedPath = resolvedPath; diff --git a/claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/schema/index.js b/claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/schema/index.js new file mode 100644 index 00000000..a5173e01 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/schema/index.js @@ -0,0 +1,620 @@ +'use strict'; + +var protocolHttp = require('@smithy/protocol-http'); +var utilMiddleware = require('@smithy/util-middleware'); + +const deref = (schemaRef) => { + if (typeof schemaRef === "function") { + return schemaRef(); + } + return schemaRef; +}; + +const operation = (namespace, name, traits, input, output) => ({ + name, + namespace, + traits, + input, + output, +}); + +const schemaDeserializationMiddleware = (config) => (next, context) => async (args) => { + const { response } = await next(args); + const { operationSchema } = utilMiddleware.getSmithyContext(context); + const [, ns, n, t, i, o] = operationSchema ?? []; + try { + const parsed = await config.protocol.deserializeResponse(operation(ns, n, t, i, o), { + ...config, + ...context, + }, response); + return { + response, + output: parsed, + }; + } + catch (error) { + Object.defineProperty(error, "$response", { + value: response, + enumerable: false, + writable: false, + configurable: false, + }); + if (!("$metadata" in error)) { + const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; + try { + error.message += "\n " + hint; + } + catch (e) { + if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { + console.warn(hint); + } + else { + context.logger?.warn?.(hint); + } + } + if (typeof error.$responseBodyText !== "undefined") { + if (error.$response) { + error.$response.body = error.$responseBodyText; + } + } + try { + if (protocolHttp.HttpResponse.isInstance(response)) { + const { headers = {} } = response; + const headerEntries = Object.entries(headers); + error.$metadata = { + httpStatusCode: response.statusCode, + requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), + extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), + cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries), + }; + } + } + catch (e) { + } + } + throw error; + } +}; +const findHeader = (pattern, headers) => { + return (headers.find(([k]) => { + return k.match(pattern); + }) || [void 0, void 0])[1]; +}; + +const schemaSerializationMiddleware = (config) => (next, context) => async (args) => { + const { operationSchema } = utilMiddleware.getSmithyContext(context); + const [, ns, n, t, i, o] = operationSchema ?? []; + const endpoint = context.endpointV2?.url && config.urlParser + ? async () => config.urlParser(context.endpointV2.url) + : config.endpoint; + const request = await config.protocol.serializeRequest(operation(ns, n, t, i, o), args.input, { + ...config, + ...context, + endpoint, + }); + return next({ + ...args, + request, + }); +}; + +const deserializerMiddlewareOption = { + name: "deserializerMiddleware", + step: "deserialize", + tags: ["DESERIALIZER"], + override: true, +}; +const serializerMiddlewareOption = { + name: "serializerMiddleware", + step: "serialize", + tags: ["SERIALIZER"], + override: true, +}; +function getSchemaSerdePlugin(config) { + return { + applyToStack: (commandStack) => { + commandStack.add(schemaSerializationMiddleware(config), serializerMiddlewareOption); + commandStack.add(schemaDeserializationMiddleware(config), deserializerMiddlewareOption); + config.protocol.setSerdeContext(config); + }, + }; +} + +class Schema { + name; + namespace; + traits; + static assign(instance, values) { + const schema = Object.assign(instance, values); + return schema; + } + static [Symbol.hasInstance](lhs) { + const isPrototype = this.prototype.isPrototypeOf(lhs); + if (!isPrototype && typeof lhs === "object" && lhs !== null) { + const list = lhs; + return list.symbol === this.symbol; + } + return isPrototype; + } + getName() { + return this.namespace + "#" + this.name; + } +} + +class ListSchema extends Schema { + static symbol = Symbol.for("@smithy/lis"); + name; + traits; + valueSchema; + symbol = ListSchema.symbol; +} +const list = (namespace, name, traits, valueSchema) => Schema.assign(new ListSchema(), { + name, + namespace, + traits, + valueSchema, +}); + +class MapSchema extends Schema { + static symbol = Symbol.for("@smithy/map"); + name; + traits; + keySchema; + valueSchema; + symbol = MapSchema.symbol; +} +const map = (namespace, name, traits, keySchema, valueSchema) => Schema.assign(new MapSchema(), { + name, + namespace, + traits, + keySchema, + valueSchema, +}); + +class OperationSchema extends Schema { + static symbol = Symbol.for("@smithy/ope"); + name; + traits; + input; + output; + symbol = OperationSchema.symbol; +} +const op = (namespace, name, traits, input, output) => Schema.assign(new OperationSchema(), { + name, + namespace, + traits, + input, + output, +}); + +class StructureSchema extends Schema { + static symbol = Symbol.for("@smithy/str"); + name; + traits; + memberNames; + memberList; + symbol = StructureSchema.symbol; +} +const struct = (namespace, name, traits, memberNames, memberList) => Schema.assign(new StructureSchema(), { + name, + namespace, + traits, + memberNames, + memberList, +}); + +class ErrorSchema extends StructureSchema { + static symbol = Symbol.for("@smithy/err"); + ctor; + symbol = ErrorSchema.symbol; +} +const error = (namespace, name, traits, memberNames, memberList, ctor) => Schema.assign(new ErrorSchema(), { + name, + namespace, + traits, + memberNames, + memberList, + ctor: null, +}); + +function translateTraits(indicator) { + if (typeof indicator === "object") { + return indicator; + } + indicator = indicator | 0; + const traits = {}; + let i = 0; + for (const trait of [ + "httpLabel", + "idempotent", + "idempotencyToken", + "sensitive", + "httpPayload", + "httpResponseCode", + "httpQueryParams", + ]) { + if (((indicator >> i++) & 1) === 1) { + traits[trait] = 1; + } + } + return traits; +} + +class NormalizedSchema { + ref; + memberName; + static symbol = Symbol.for("@smithy/nor"); + symbol = NormalizedSchema.symbol; + name; + schema; + _isMemberSchema; + traits; + memberTraits; + normalizedTraits; + constructor(ref, memberName) { + this.ref = ref; + this.memberName = memberName; + const traitStack = []; + let _ref = ref; + let schema = ref; + this._isMemberSchema = false; + while (isMemberSchema(_ref)) { + traitStack.push(_ref[1]); + _ref = _ref[0]; + schema = deref(_ref); + this._isMemberSchema = true; + } + if (traitStack.length > 0) { + this.memberTraits = {}; + for (let i = traitStack.length - 1; i >= 0; --i) { + const traitSet = traitStack[i]; + Object.assign(this.memberTraits, translateTraits(traitSet)); + } + } + else { + this.memberTraits = 0; + } + if (schema instanceof NormalizedSchema) { + const computedMemberTraits = this.memberTraits; + Object.assign(this, schema); + this.memberTraits = Object.assign({}, computedMemberTraits, schema.getMemberTraits(), this.getMemberTraits()); + this.normalizedTraits = void 0; + this.memberName = memberName ?? schema.memberName; + return; + } + this.schema = deref(schema); + if (isStaticSchema(this.schema)) { + this.name = `${this.schema[1]}#${this.schema[2]}`; + this.traits = this.schema[3]; + } + else { + this.name = this.memberName ?? String(schema); + this.traits = 0; + } + if (this._isMemberSchema && !memberName) { + throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(true)} missing member name.`); + } + } + static [Symbol.hasInstance](lhs) { + const isPrototype = this.prototype.isPrototypeOf(lhs); + if (!isPrototype && typeof lhs === "object" && lhs !== null) { + const ns = lhs; + return ns.symbol === this.symbol; + } + return isPrototype; + } + static of(ref) { + const sc = deref(ref); + if (sc instanceof NormalizedSchema) { + return sc; + } + if (isMemberSchema(sc)) { + const [ns, traits] = sc; + if (ns instanceof NormalizedSchema) { + Object.assign(ns.getMergedTraits(), translateTraits(traits)); + return ns; + } + throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(ref, null, 2)}.`); + } + return new NormalizedSchema(sc); + } + getSchema() { + const sc = this.schema; + if (sc[0] === 0) { + return sc[4]; + } + return sc; + } + getName(withNamespace = false) { + const { name } = this; + const short = !withNamespace && name && name.includes("#"); + return short ? name.split("#")[1] : name || undefined; + } + getMemberName() { + return this.memberName; + } + isMemberSchema() { + return this._isMemberSchema; + } + isListSchema() { + const sc = this.getSchema(); + return typeof sc === "number" + ? sc >= 64 && sc < 128 + : sc[0] === 1; + } + isMapSchema() { + const sc = this.getSchema(); + return typeof sc === "number" + ? sc >= 128 && sc <= 0b1111_1111 + : sc[0] === 2; + } + isStructSchema() { + const sc = this.getSchema(); + return (sc[0] === 3 || + sc[0] === -3); + } + isBlobSchema() { + const sc = this.getSchema(); + return sc === 21 || sc === 42; + } + isTimestampSchema() { + const sc = this.getSchema(); + return (typeof sc === "number" && + sc >= 4 && + sc <= 7); + } + isUnitSchema() { + return this.getSchema() === "unit"; + } + isDocumentSchema() { + return this.getSchema() === 15; + } + isStringSchema() { + return this.getSchema() === 0; + } + isBooleanSchema() { + return this.getSchema() === 2; + } + isNumericSchema() { + return this.getSchema() === 1; + } + isBigIntegerSchema() { + return this.getSchema() === 17; + } + isBigDecimalSchema() { + return this.getSchema() === 19; + } + isStreaming() { + const { streaming } = this.getMergedTraits(); + return !!streaming || this.getSchema() === 42; + } + isIdempotencyToken() { + const match = (traits) => (traits & 0b0100) === 0b0100 || + !!traits?.idempotencyToken; + const { normalizedTraits, traits, memberTraits } = this; + return match(normalizedTraits) || match(traits) || match(memberTraits); + } + getMergedTraits() { + return (this.normalizedTraits ?? + (this.normalizedTraits = { + ...this.getOwnTraits(), + ...this.getMemberTraits(), + })); + } + getMemberTraits() { + return translateTraits(this.memberTraits); + } + getOwnTraits() { + return translateTraits(this.traits); + } + getKeySchema() { + const [isDoc, isMap] = [this.isDocumentSchema(), this.isMapSchema()]; + if (!isDoc && !isMap) { + throw new Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(true)}`); + } + const schema = this.getSchema(); + const memberSchema = isDoc + ? 15 + : schema[4] ?? 0; + return member([memberSchema, 0], "key"); + } + getValueSchema() { + const sc = this.getSchema(); + const [isDoc, isMap, isList] = [this.isDocumentSchema(), this.isMapSchema(), this.isListSchema()]; + const memberSchema = typeof sc === "number" + ? 0b0011_1111 & sc + : sc && typeof sc === "object" && (isMap || isList) + ? sc[3 + sc[0]] + : isDoc + ? 15 + : void 0; + if (memberSchema != null) { + return member([memberSchema, 0], isMap ? "value" : "member"); + } + throw new Error(`@smithy/core/schema - ${this.getName(true)} has no value member.`); + } + getMemberSchema(memberName) { + const struct = this.getSchema(); + if (this.isStructSchema() && struct[4].includes(memberName)) { + const i = struct[4].indexOf(memberName); + const memberSchema = struct[5][i]; + return member(isMemberSchema(memberSchema) ? memberSchema : [memberSchema, 0], memberName); + } + if (this.isDocumentSchema()) { + return member([15, 0], memberName); + } + throw new Error(`@smithy/core/schema - ${this.getName(true)} has no no member=${memberName}.`); + } + getMemberSchemas() { + const buffer = {}; + try { + for (const [k, v] of this.structIterator()) { + buffer[k] = v; + } + } + catch (ignored) { } + return buffer; + } + getEventStreamMember() { + if (this.isStructSchema()) { + for (const [memberName, memberSchema] of this.structIterator()) { + if (memberSchema.isStreaming() && memberSchema.isStructSchema()) { + return memberName; + } + } + } + return ""; + } + *structIterator() { + if (this.isUnitSchema()) { + return; + } + if (!this.isStructSchema()) { + throw new Error("@smithy/core/schema - cannot iterate non-struct schema."); + } + const struct = this.getSchema(); + for (let i = 0; i < struct[4].length; ++i) { + yield [struct[4][i], member([struct[5][i], 0], struct[4][i])]; + } + } +} +function member(memberSchema, memberName) { + if (memberSchema instanceof NormalizedSchema) { + return Object.assign(memberSchema, { + memberName, + _isMemberSchema: true, + }); + } + const internalCtorAccess = NormalizedSchema; + return new internalCtorAccess(memberSchema, memberName); +} +const isMemberSchema = (sc) => Array.isArray(sc) && sc.length === 2; +const isStaticSchema = (sc) => Array.isArray(sc) && sc.length >= 5; + +class SimpleSchema extends Schema { + static symbol = Symbol.for("@smithy/sim"); + name; + schemaRef; + traits; + symbol = SimpleSchema.symbol; +} +const sim = (namespace, name, schemaRef, traits) => Schema.assign(new SimpleSchema(), { + name, + namespace, + traits, + schemaRef, +}); +const simAdapter = (namespace, name, traits, schemaRef) => Schema.assign(new SimpleSchema(), { + name, + namespace, + traits, + schemaRef, +}); + +const SCHEMA = { + BLOB: 0b0001_0101, + STREAMING_BLOB: 0b0010_1010, + BOOLEAN: 0b0000_0010, + STRING: 0b0000_0000, + NUMERIC: 0b0000_0001, + BIG_INTEGER: 0b0001_0001, + BIG_DECIMAL: 0b0001_0011, + DOCUMENT: 0b0000_1111, + TIMESTAMP_DEFAULT: 0b0000_0100, + TIMESTAMP_DATE_TIME: 0b0000_0101, + TIMESTAMP_HTTP_DATE: 0b0000_0110, + TIMESTAMP_EPOCH_SECONDS: 0b0000_0111, + LIST_MODIFIER: 0b0100_0000, + MAP_MODIFIER: 0b1000_0000, +}; + +class TypeRegistry { + namespace; + schemas; + exceptions; + static registries = new Map(); + constructor(namespace, schemas = new Map(), exceptions = new Map()) { + this.namespace = namespace; + this.schemas = schemas; + this.exceptions = exceptions; + } + static for(namespace) { + if (!TypeRegistry.registries.has(namespace)) { + TypeRegistry.registries.set(namespace, new TypeRegistry(namespace)); + } + return TypeRegistry.registries.get(namespace); + } + register(shapeId, schema) { + const qualifiedName = this.normalizeShapeId(shapeId); + const registry = TypeRegistry.for(qualifiedName.split("#")[0]); + registry.schemas.set(qualifiedName, schema); + } + getSchema(shapeId) { + const id = this.normalizeShapeId(shapeId); + if (!this.schemas.has(id)) { + throw new Error(`@smithy/core/schema - schema not found for ${id}`); + } + return this.schemas.get(id); + } + registerError(es, ctor) { + const $error = es; + const registry = TypeRegistry.for($error[1]); + registry.schemas.set($error[1] + "#" + $error[2], $error); + registry.exceptions.set($error, ctor); + } + getErrorCtor(es) { + const $error = es; + const registry = TypeRegistry.for($error[1]); + return registry.exceptions.get($error); + } + getBaseException() { + for (const exceptionKey of this.exceptions.keys()) { + if (Array.isArray(exceptionKey)) { + const [, ns, name] = exceptionKey; + const id = ns + "#" + name; + if (id.startsWith("smithy.ts.sdk.synthetic.") && id.endsWith("ServiceException")) { + return exceptionKey; + } + } + } + return undefined; + } + find(predicate) { + return [...this.schemas.values()].find(predicate); + } + clear() { + this.schemas.clear(); + this.exceptions.clear(); + } + normalizeShapeId(shapeId) { + if (shapeId.includes("#")) { + return shapeId; + } + return this.namespace + "#" + shapeId; + } +} + +exports.ErrorSchema = ErrorSchema; +exports.ListSchema = ListSchema; +exports.MapSchema = MapSchema; +exports.NormalizedSchema = NormalizedSchema; +exports.OperationSchema = OperationSchema; +exports.SCHEMA = SCHEMA; +exports.Schema = Schema; +exports.SimpleSchema = SimpleSchema; +exports.StructureSchema = StructureSchema; +exports.TypeRegistry = TypeRegistry; +exports.deref = deref; +exports.deserializerMiddlewareOption = deserializerMiddlewareOption; +exports.error = error; +exports.getSchemaSerdePlugin = getSchemaSerdePlugin; +exports.isStaticSchema = isStaticSchema; +exports.list = list; +exports.map = map; +exports.op = op; +exports.operation = operation; +exports.serializerMiddlewareOption = serializerMiddlewareOption; +exports.sim = sim; +exports.simAdapter = simAdapter; +exports.struct = struct; +exports.translateTraits = translateTraits; diff --git a/claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/serde/index.js b/claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/serde/index.js new file mode 100644 index 00000000..7c4740cf --- /dev/null +++ b/claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/serde/index.js @@ -0,0 +1,697 @@ +'use strict'; + +var uuid = require('@smithy/uuid'); + +const copyDocumentWithTransform = (source, schemaRef, transform = (_) => _) => source; + +const parseBoolean = (value) => { + switch (value) { + case "true": + return true; + case "false": + return false; + default: + throw new Error(`Unable to parse boolean value "${value}"`); + } +}; +const expectBoolean = (value) => { + if (value === null || value === undefined) { + return undefined; + } + if (typeof value === "number") { + if (value === 0 || value === 1) { + logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); + } + if (value === 0) { + return false; + } + if (value === 1) { + return true; + } + } + if (typeof value === "string") { + const lower = value.toLowerCase(); + if (lower === "false" || lower === "true") { + logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); + } + if (lower === "false") { + return false; + } + if (lower === "true") { + return true; + } + } + if (typeof value === "boolean") { + return value; + } + throw new TypeError(`Expected boolean, got ${typeof value}: ${value}`); +}; +const expectNumber = (value) => { + if (value === null || value === undefined) { + return undefined; + } + if (typeof value === "string") { + const parsed = parseFloat(value); + if (!Number.isNaN(parsed)) { + if (String(parsed) !== String(value)) { + logger.warn(stackTraceWarning(`Expected number but observed string: ${value}`)); + } + return parsed; + } + } + if (typeof value === "number") { + return value; + } + throw new TypeError(`Expected number, got ${typeof value}: ${value}`); +}; +const MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23)); +const expectFloat32 = (value) => { + const expected = expectNumber(value); + if (expected !== undefined && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) { + if (Math.abs(expected) > MAX_FLOAT) { + throw new TypeError(`Expected 32-bit float, got ${value}`); + } + } + return expected; +}; +const expectLong = (value) => { + if (value === null || value === undefined) { + return undefined; + } + if (Number.isInteger(value) && !Number.isNaN(value)) { + return value; + } + throw new TypeError(`Expected integer, got ${typeof value}: ${value}`); +}; +const expectInt = expectLong; +const expectInt32 = (value) => expectSizedInt(value, 32); +const expectShort = (value) => expectSizedInt(value, 16); +const expectByte = (value) => expectSizedInt(value, 8); +const expectSizedInt = (value, size) => { + const expected = expectLong(value); + if (expected !== undefined && castInt(expected, size) !== expected) { + throw new TypeError(`Expected ${size}-bit integer, got ${value}`); + } + return expected; +}; +const castInt = (value, size) => { + switch (size) { + case 32: + return Int32Array.of(value)[0]; + case 16: + return Int16Array.of(value)[0]; + case 8: + return Int8Array.of(value)[0]; + } +}; +const expectNonNull = (value, location) => { + if (value === null || value === undefined) { + if (location) { + throw new TypeError(`Expected a non-null value for ${location}`); + } + throw new TypeError("Expected a non-null value"); + } + return value; +}; +const expectObject = (value) => { + if (value === null || value === undefined) { + return undefined; + } + if (typeof value === "object" && !Array.isArray(value)) { + return value; + } + const receivedType = Array.isArray(value) ? "array" : typeof value; + throw new TypeError(`Expected object, got ${receivedType}: ${value}`); +}; +const expectString = (value) => { + if (value === null || value === undefined) { + return undefined; + } + if (typeof value === "string") { + return value; + } + if (["boolean", "number", "bigint"].includes(typeof value)) { + logger.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`)); + return String(value); + } + throw new TypeError(`Expected string, got ${typeof value}: ${value}`); +}; +const expectUnion = (value) => { + if (value === null || value === undefined) { + return undefined; + } + const asObject = expectObject(value); + const setKeys = Object.entries(asObject) + .filter(([, v]) => v != null) + .map(([k]) => k); + if (setKeys.length === 0) { + throw new TypeError(`Unions must have exactly one non-null member. None were found.`); + } + if (setKeys.length > 1) { + throw new TypeError(`Unions must have exactly one non-null member. Keys ${setKeys} were not null.`); + } + return asObject; +}; +const strictParseDouble = (value) => { + if (typeof value == "string") { + return expectNumber(parseNumber(value)); + } + return expectNumber(value); +}; +const strictParseFloat = strictParseDouble; +const strictParseFloat32 = (value) => { + if (typeof value == "string") { + return expectFloat32(parseNumber(value)); + } + return expectFloat32(value); +}; +const NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g; +const parseNumber = (value) => { + const matches = value.match(NUMBER_REGEX); + if (matches === null || matches[0].length !== value.length) { + throw new TypeError(`Expected real number, got implicit NaN`); + } + return parseFloat(value); +}; +const limitedParseDouble = (value) => { + if (typeof value == "string") { + return parseFloatString(value); + } + return expectNumber(value); +}; +const handleFloat = limitedParseDouble; +const limitedParseFloat = limitedParseDouble; +const limitedParseFloat32 = (value) => { + if (typeof value == "string") { + return parseFloatString(value); + } + return expectFloat32(value); +}; +const parseFloatString = (value) => { + switch (value) { + case "NaN": + return NaN; + case "Infinity": + return Infinity; + case "-Infinity": + return -Infinity; + default: + throw new Error(`Unable to parse float value: ${value}`); + } +}; +const strictParseLong = (value) => { + if (typeof value === "string") { + return expectLong(parseNumber(value)); + } + return expectLong(value); +}; +const strictParseInt = strictParseLong; +const strictParseInt32 = (value) => { + if (typeof value === "string") { + return expectInt32(parseNumber(value)); + } + return expectInt32(value); +}; +const strictParseShort = (value) => { + if (typeof value === "string") { + return expectShort(parseNumber(value)); + } + return expectShort(value); +}; +const strictParseByte = (value) => { + if (typeof value === "string") { + return expectByte(parseNumber(value)); + } + return expectByte(value); +}; +const stackTraceWarning = (message) => { + return String(new TypeError(message).stack || message) + .split("\n") + .slice(0, 5) + .filter((s) => !s.includes("stackTraceWarning")) + .join("\n"); +}; +const logger = { + warn: console.warn, +}; + +const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; +const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; +function dateToUtcString(date) { + const year = date.getUTCFullYear(); + const month = date.getUTCMonth(); + const dayOfWeek = date.getUTCDay(); + const dayOfMonthInt = date.getUTCDate(); + const hoursInt = date.getUTCHours(); + const minutesInt = date.getUTCMinutes(); + const secondsInt = date.getUTCSeconds(); + const dayOfMonthString = dayOfMonthInt < 10 ? `0${dayOfMonthInt}` : `${dayOfMonthInt}`; + const hoursString = hoursInt < 10 ? `0${hoursInt}` : `${hoursInt}`; + const minutesString = minutesInt < 10 ? `0${minutesInt}` : `${minutesInt}`; + const secondsString = secondsInt < 10 ? `0${secondsInt}` : `${secondsInt}`; + return `${DAYS[dayOfWeek]}, ${dayOfMonthString} ${MONTHS[month]} ${year} ${hoursString}:${minutesString}:${secondsString} GMT`; +} +const RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/); +const parseRfc3339DateTime = (value) => { + if (value === null || value === undefined) { + return undefined; + } + if (typeof value !== "string") { + throw new TypeError("RFC-3339 date-times must be expressed as strings"); + } + const match = RFC3339.exec(value); + if (!match) { + throw new TypeError("Invalid RFC-3339 date-time value"); + } + const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match; + const year = strictParseShort(stripLeadingZeroes(yearStr)); + const month = parseDateValue(monthStr, "month", 1, 12); + const day = parseDateValue(dayStr, "day", 1, 31); + return buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); +}; +const RFC3339_WITH_OFFSET$1 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/); +const parseRfc3339DateTimeWithOffset = (value) => { + if (value === null || value === undefined) { + return undefined; + } + if (typeof value !== "string") { + throw new TypeError("RFC-3339 date-times must be expressed as strings"); + } + const match = RFC3339_WITH_OFFSET$1.exec(value); + if (!match) { + throw new TypeError("Invalid RFC-3339 date-time value"); + } + const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match; + const year = strictParseShort(stripLeadingZeroes(yearStr)); + const month = parseDateValue(monthStr, "month", 1, 12); + const day = parseDateValue(dayStr, "day", 1, 31); + const date = buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); + if (offsetStr.toUpperCase() != "Z") { + date.setTime(date.getTime() - parseOffsetToMilliseconds(offsetStr)); + } + return date; +}; +const IMF_FIXDATE$1 = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/); +const RFC_850_DATE$1 = new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/); +const ASC_TIME$1 = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/); +const parseRfc7231DateTime = (value) => { + if (value === null || value === undefined) { + return undefined; + } + if (typeof value !== "string") { + throw new TypeError("RFC-7231 date-times must be expressed as strings"); + } + let match = IMF_FIXDATE$1.exec(value); + if (match) { + const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; + return buildDate(strictParseShort(stripLeadingZeroes(yearStr)), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds }); + } + match = RFC_850_DATE$1.exec(value); + if (match) { + const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; + return adjustRfc850Year(buildDate(parseTwoDigitYear(yearStr), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { + hours, + minutes, + seconds, + fractionalMilliseconds, + })); + } + match = ASC_TIME$1.exec(value); + if (match) { + const [_, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, yearStr] = match; + return buildDate(strictParseShort(stripLeadingZeroes(yearStr)), parseMonthByShortName(monthStr), parseDateValue(dayStr.trimLeft(), "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds }); + } + throw new TypeError("Invalid RFC-7231 date-time value"); +}; +const parseEpochTimestamp = (value) => { + if (value === null || value === undefined) { + return undefined; + } + let valueAsDouble; + if (typeof value === "number") { + valueAsDouble = value; + } + else if (typeof value === "string") { + valueAsDouble = strictParseDouble(value); + } + else if (typeof value === "object" && value.tag === 1) { + valueAsDouble = value.value; + } + else { + throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation"); + } + if (Number.isNaN(valueAsDouble) || valueAsDouble === Infinity || valueAsDouble === -Infinity) { + throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics"); + } + return new Date(Math.round(valueAsDouble * 1000)); +}; +const buildDate = (year, month, day, time) => { + const adjustedMonth = month - 1; + validateDayOfMonth(year, adjustedMonth, day); + return new Date(Date.UTC(year, adjustedMonth, day, parseDateValue(time.hours, "hour", 0, 23), parseDateValue(time.minutes, "minute", 0, 59), parseDateValue(time.seconds, "seconds", 0, 60), parseMilliseconds(time.fractionalMilliseconds))); +}; +const parseTwoDigitYear = (value) => { + const thisYear = new Date().getUTCFullYear(); + const valueInThisCentury = Math.floor(thisYear / 100) * 100 + strictParseShort(stripLeadingZeroes(value)); + if (valueInThisCentury < thisYear) { + return valueInThisCentury + 100; + } + return valueInThisCentury; +}; +const FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1000; +const adjustRfc850Year = (input) => { + if (input.getTime() - new Date().getTime() > FIFTY_YEARS_IN_MILLIS) { + return new Date(Date.UTC(input.getUTCFullYear() - 100, input.getUTCMonth(), input.getUTCDate(), input.getUTCHours(), input.getUTCMinutes(), input.getUTCSeconds(), input.getUTCMilliseconds())); + } + return input; +}; +const parseMonthByShortName = (value) => { + const monthIdx = MONTHS.indexOf(value); + if (monthIdx < 0) { + throw new TypeError(`Invalid month: ${value}`); + } + return monthIdx + 1; +}; +const DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; +const validateDayOfMonth = (year, month, day) => { + let maxDays = DAYS_IN_MONTH[month]; + if (month === 1 && isLeapYear(year)) { + maxDays = 29; + } + if (day > maxDays) { + throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`); + } +}; +const isLeapYear = (year) => { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); +}; +const parseDateValue = (value, type, lower, upper) => { + const dateVal = strictParseByte(stripLeadingZeroes(value)); + if (dateVal < lower || dateVal > upper) { + throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`); + } + return dateVal; +}; +const parseMilliseconds = (value) => { + if (value === null || value === undefined) { + return 0; + } + return strictParseFloat32("0." + value) * 1000; +}; +const parseOffsetToMilliseconds = (value) => { + const directionStr = value[0]; + let direction = 1; + if (directionStr == "+") { + direction = 1; + } + else if (directionStr == "-") { + direction = -1; + } + else { + throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`); + } + const hour = Number(value.substring(1, 3)); + const minute = Number(value.substring(4, 6)); + return direction * (hour * 60 + minute) * 60 * 1000; +}; +const stripLeadingZeroes = (value) => { + let idx = 0; + while (idx < value.length - 1 && value.charAt(idx) === "0") { + idx++; + } + if (idx === 0) { + return value; + } + return value.slice(idx); +}; + +const LazyJsonString = function LazyJsonString(val) { + const str = Object.assign(new String(val), { + deserializeJSON() { + return JSON.parse(String(val)); + }, + toString() { + return String(val); + }, + toJSON() { + return String(val); + }, + }); + return str; +}; +LazyJsonString.from = (object) => { + if (object && typeof object === "object" && (object instanceof LazyJsonString || "deserializeJSON" in object)) { + return object; + } + else if (typeof object === "string" || Object.getPrototypeOf(object) === String.prototype) { + return LazyJsonString(String(object)); + } + return LazyJsonString(JSON.stringify(object)); +}; +LazyJsonString.fromObject = LazyJsonString.from; + +function quoteHeader(part) { + if (part.includes(",") || part.includes('"')) { + part = `"${part.replace(/"/g, '\\"')}"`; + } + return part; +} + +const ddd = `(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:[ne|u?r]?s?day)?`; +const mmm = `(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)`; +const time = `(\\d?\\d):(\\d{2}):(\\d{2})(?:\\.(\\d+))?`; +const date = `(\\d?\\d)`; +const year = `(\\d{4})`; +const RFC3339_WITH_OFFSET = new RegExp(/^(\d{4})-(\d\d)-(\d\d)[tT](\d\d):(\d\d):(\d\d)(\.(\d+))?(([-+]\d\d:\d\d)|[zZ])$/); +const IMF_FIXDATE = new RegExp(`^${ddd}, ${date} ${mmm} ${year} ${time} GMT$`); +const RFC_850_DATE = new RegExp(`^${ddd}, ${date}-${mmm}-(\\d\\d) ${time} GMT$`); +const ASC_TIME = new RegExp(`^${ddd} ${mmm} ( [1-9]|\\d\\d) ${time} ${year}$`); +const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; +const _parseEpochTimestamp = (value) => { + if (value == null) { + return void 0; + } + let num = NaN; + if (typeof value === "number") { + num = value; + } + else if (typeof value === "string") { + if (!/^-?\d*\.?\d+$/.test(value)) { + throw new TypeError(`parseEpochTimestamp - numeric string invalid.`); + } + num = Number.parseFloat(value); + } + else if (typeof value === "object" && value.tag === 1) { + num = value.value; + } + if (isNaN(num) || Math.abs(num) === Infinity) { + throw new TypeError("Epoch timestamps must be valid finite numbers."); + } + return new Date(Math.round(num * 1000)); +}; +const _parseRfc3339DateTimeWithOffset = (value) => { + if (value == null) { + return void 0; + } + if (typeof value !== "string") { + throw new TypeError("RFC3339 timestamps must be strings"); + } + const matches = RFC3339_WITH_OFFSET.exec(value); + if (!matches) { + throw new TypeError(`Invalid RFC3339 timestamp format ${value}`); + } + const [, yearStr, monthStr, dayStr, hours, minutes, seconds, , ms, offsetStr] = matches; + range(monthStr, 1, 12); + range(dayStr, 1, 31); + range(hours, 0, 23); + range(minutes, 0, 59); + range(seconds, 0, 60); + const date = new Date(Date.UTC(Number(yearStr), Number(monthStr) - 1, Number(dayStr), Number(hours), Number(minutes), Number(seconds), Number(ms) ? Math.round(parseFloat(`0.${ms}`) * 1000) : 0)); + date.setUTCFullYear(Number(yearStr)); + if (offsetStr.toUpperCase() != "Z") { + const [, sign, offsetH, offsetM] = /([+-])(\d\d):(\d\d)/.exec(offsetStr) || [void 0, "+", 0, 0]; + const scalar = sign === "-" ? 1 : -1; + date.setTime(date.getTime() + scalar * (Number(offsetH) * 60 * 60 * 1000 + Number(offsetM) * 60 * 1000)); + } + return date; +}; +const _parseRfc7231DateTime = (value) => { + if (value == null) { + return void 0; + } + if (typeof value !== "string") { + throw new TypeError("RFC7231 timestamps must be strings."); + } + let day; + let month; + let year; + let hour; + let minute; + let second; + let fraction; + let matches; + if ((matches = IMF_FIXDATE.exec(value))) { + [, day, month, year, hour, minute, second, fraction] = matches; + } + else if ((matches = RFC_850_DATE.exec(value))) { + [, day, month, year, hour, minute, second, fraction] = matches; + year = (Number(year) + 1900).toString(); + } + else if ((matches = ASC_TIME.exec(value))) { + [, month, day, hour, minute, second, fraction, year] = matches; + } + if (year && second) { + const timestamp = Date.UTC(Number(year), months.indexOf(month), Number(day), Number(hour), Number(minute), Number(second), fraction ? Math.round(parseFloat(`0.${fraction}`) * 1000) : 0); + range(day, 1, 31); + range(hour, 0, 23); + range(minute, 0, 59); + range(second, 0, 60); + const date = new Date(timestamp); + date.setUTCFullYear(Number(year)); + return date; + } + throw new TypeError(`Invalid RFC7231 date-time value ${value}.`); +}; +function range(v, min, max) { + const _v = Number(v); + if (_v < min || _v > max) { + throw new Error(`Value ${_v} out of range [${min}, ${max}]`); + } +} + +function splitEvery(value, delimiter, numDelimiters) { + if (numDelimiters <= 0 || !Number.isInteger(numDelimiters)) { + throw new Error("Invalid number of delimiters (" + numDelimiters + ") for splitEvery."); + } + const segments = value.split(delimiter); + if (numDelimiters === 1) { + return segments; + } + const compoundSegments = []; + let currentSegment = ""; + for (let i = 0; i < segments.length; i++) { + if (currentSegment === "") { + currentSegment = segments[i]; + } + else { + currentSegment += delimiter + segments[i]; + } + if ((i + 1) % numDelimiters === 0) { + compoundSegments.push(currentSegment); + currentSegment = ""; + } + } + if (currentSegment !== "") { + compoundSegments.push(currentSegment); + } + return compoundSegments; +} + +const splitHeader = (value) => { + const z = value.length; + const values = []; + let withinQuotes = false; + let prevChar = undefined; + let anchor = 0; + for (let i = 0; i < z; ++i) { + const char = value[i]; + switch (char) { + case `"`: + if (prevChar !== "\\") { + withinQuotes = !withinQuotes; + } + break; + case ",": + if (!withinQuotes) { + values.push(value.slice(anchor, i)); + anchor = i + 1; + } + break; + } + prevChar = char; + } + values.push(value.slice(anchor)); + return values.map((v) => { + v = v.trim(); + const z = v.length; + if (z < 2) { + return v; + } + if (v[0] === `"` && v[z - 1] === `"`) { + v = v.slice(1, z - 1); + } + return v.replace(/\\"/g, '"'); + }); +}; + +const format = /^-?\d*(\.\d+)?$/; +class NumericValue { + string; + type; + constructor(string, type) { + this.string = string; + this.type = type; + if (!format.test(string)) { + throw new Error(`@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".`); + } + } + toString() { + return this.string; + } + static [Symbol.hasInstance](object) { + if (!object || typeof object !== "object") { + return false; + } + const _nv = object; + return NumericValue.prototype.isPrototypeOf(object) || (_nv.type === "bigDecimal" && format.test(_nv.string)); + } +} +function nv(input) { + return new NumericValue(String(input), "bigDecimal"); +} + +Object.defineProperty(exports, "generateIdempotencyToken", { + enumerable: true, + get: function () { return uuid.v4; } +}); +exports.LazyJsonString = LazyJsonString; +exports.NumericValue = NumericValue; +exports._parseEpochTimestamp = _parseEpochTimestamp; +exports._parseRfc3339DateTimeWithOffset = _parseRfc3339DateTimeWithOffset; +exports._parseRfc7231DateTime = _parseRfc7231DateTime; +exports.copyDocumentWithTransform = copyDocumentWithTransform; +exports.dateToUtcString = dateToUtcString; +exports.expectBoolean = expectBoolean; +exports.expectByte = expectByte; +exports.expectFloat32 = expectFloat32; +exports.expectInt = expectInt; +exports.expectInt32 = expectInt32; +exports.expectLong = expectLong; +exports.expectNonNull = expectNonNull; +exports.expectNumber = expectNumber; +exports.expectObject = expectObject; +exports.expectShort = expectShort; +exports.expectString = expectString; +exports.expectUnion = expectUnion; +exports.handleFloat = handleFloat; +exports.limitedParseDouble = limitedParseDouble; +exports.limitedParseFloat = limitedParseFloat; +exports.limitedParseFloat32 = limitedParseFloat32; +exports.logger = logger; +exports.nv = nv; +exports.parseBoolean = parseBoolean; +exports.parseEpochTimestamp = parseEpochTimestamp; +exports.parseRfc3339DateTime = parseRfc3339DateTime; +exports.parseRfc3339DateTimeWithOffset = parseRfc3339DateTimeWithOffset; +exports.parseRfc7231DateTime = parseRfc7231DateTime; +exports.quoteHeader = quoteHeader; +exports.splitEvery = splitEvery; +exports.splitHeader = splitHeader; +exports.strictParseByte = strictParseByte; +exports.strictParseDouble = strictParseDouble; +exports.strictParseFloat = strictParseFloat; +exports.strictParseFloat32 = strictParseFloat32; +exports.strictParseInt = strictParseInt; +exports.strictParseInt32 = strictParseInt32; +exports.strictParseLong = strictParseLong; +exports.strictParseShort = strictParseShort; diff --git a/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/protocol-http/dist-cjs/index.js new file mode 100644 index 00000000..52303c3b --- /dev/null +++ b/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/protocol-http/dist-cjs/index.js @@ -0,0 +1,169 @@ +'use strict'; + +var types = require('@smithy/types'); + +const getHttpHandlerExtensionConfiguration = (runtimeConfig) => { + return { + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); + }, + }; +}; +const resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler(), + }; +}; + +class Field { + name; + kind; + values; + constructor({ name, kind = types.FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; + } + add(value) { + this.values.push(value); + } + set(values) { + this.values = values; + } + remove(value) { + this.values = this.values.filter((v) => v !== value); + } + toString() { + return this.values.map((v) => (v.includes(",") || v.includes(" ") ? `"${v}"` : v)).join(", "); + } + get() { + return this.values; + } +} + +class Fields { + entries = {}; + encoding; + constructor({ fields = [], encoding = "utf-8" }) { + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + setField(field) { + this.entries[field.name.toLowerCase()] = field; + } + getField(name) { + return this.entries[name.toLowerCase()]; + } + removeField(name) { + delete this.entries[name.toLowerCase()]; + } + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } +} + +class HttpRequest { + method; + protocol; + hostname; + port; + path; + query; + headers; + username; + password; + fragment; + body; + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol + ? options.protocol.slice(-1) !== ":" + ? `${options.protocol}:` + : options.protocol + : "https:"; + this.path = options.path ? (options.path.charAt(0) !== "/" ? `/${options.path}` : options.path) : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + static clone(request) { + const cloned = new HttpRequest({ + ...request, + headers: { ...request.headers }, + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); + } + return cloned; + } + static isInstance(request) { + if (!request) { + return false; + } + const req = request; + return ("method" in req && + "protocol" in req && + "hostname" in req && + "path" in req && + typeof req["query"] === "object" && + typeof req["headers"] === "object"); + } + clone() { + return HttpRequest.clone(this); + } +} +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param, + }; + }, {}); +} + +class HttpResponse { + statusCode; + reason; + headers; + body; + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) + return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + } +} + +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} + +exports.Field = Field; +exports.Fields = Fields; +exports.HttpRequest = HttpRequest; +exports.HttpResponse = HttpResponse; +exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration; +exports.isValidHostname = isValidHostname; +exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig; diff --git a/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/types/dist-cjs/index.js new file mode 100644 index 00000000..be6d0e1a --- /dev/null +++ b/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/types/dist-cjs/index.js @@ -0,0 +1,91 @@ +'use strict'; + +exports.HttpAuthLocation = void 0; +(function (HttpAuthLocation) { + HttpAuthLocation["HEADER"] = "header"; + HttpAuthLocation["QUERY"] = "query"; +})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); + +exports.HttpApiKeyAuthLocation = void 0; +(function (HttpApiKeyAuthLocation) { + HttpApiKeyAuthLocation["HEADER"] = "header"; + HttpApiKeyAuthLocation["QUERY"] = "query"; +})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); + +exports.EndpointURLScheme = void 0; +(function (EndpointURLScheme) { + EndpointURLScheme["HTTP"] = "http"; + EndpointURLScheme["HTTPS"] = "https"; +})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); + +exports.AlgorithmId = void 0; +(function (AlgorithmId) { + AlgorithmId["MD5"] = "md5"; + AlgorithmId["CRC32"] = "crc32"; + AlgorithmId["CRC32C"] = "crc32c"; + AlgorithmId["SHA1"] = "sha1"; + AlgorithmId["SHA256"] = "sha256"; +})(exports.AlgorithmId || (exports.AlgorithmId = {})); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.SHA256, + checksumConstructor: () => runtimeConfig.sha256, + }); + } + if (runtimeConfig.md5 != undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.MD5, + checksumConstructor: () => runtimeConfig.md5, + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getDefaultClientConfiguration = (runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}; +const resolveDefaultRuntimeConfig = (config) => { + return resolveChecksumRuntimeConfig(config); +}; + +exports.FieldPosition = void 0; +(function (FieldPosition) { + FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; + FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; +})(exports.FieldPosition || (exports.FieldPosition = {})); + +const SMITHY_CONTEXT_KEY = "__smithy_context"; + +exports.IniSectionType = void 0; +(function (IniSectionType) { + IniSectionType["PROFILE"] = "profile"; + IniSectionType["SSO_SESSION"] = "sso-session"; + IniSectionType["SERVICES"] = "services"; +})(exports.IniSectionType || (exports.IniSectionType = {})); + +exports.RequestHandlerProtocol = void 0; +(function (RequestHandlerProtocol) { + RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; +})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); + +exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; diff --git a/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js b/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js new file mode 100644 index 00000000..b06a7b87 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromBase64 = void 0; +const util_buffer_from_1 = require("@smithy/util-buffer-from"); +const BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; +const fromBase64 = (input) => { + if ((input.length * 3) % 4 !== 0) { + throw new TypeError(`Incorrect padding on base64 string.`); + } + if (!BASE64_REGEX.exec(input)) { + throw new TypeError(`Invalid base64 string.`); + } + const buffer = (0, util_buffer_from_1.fromString)(input, "base64"); + return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); +}; +exports.fromBase64 = fromBase64; diff --git a/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/dist-cjs/index.js new file mode 100644 index 00000000..c095e288 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/dist-cjs/index.js @@ -0,0 +1,19 @@ +'use strict'; + +var fromBase64 = require('./fromBase64'); +var toBase64 = require('./toBase64'); + + + +Object.keys(fromBase64).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return fromBase64[k]; } + }); +}); +Object.keys(toBase64).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return toBase64[k]; } + }); +}); diff --git a/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/dist-cjs/toBase64.js b/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/dist-cjs/toBase64.js new file mode 100644 index 00000000..0590ce3f --- /dev/null +++ b/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/dist-cjs/toBase64.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.toBase64 = void 0; +const util_buffer_from_1 = require("@smithy/util-buffer-from"); +const util_utf8_1 = require("@smithy/util-utf8"); +const toBase64 = (_input) => { + let input; + if (typeof _input === "string") { + input = (0, util_utf8_1.fromUtf8)(_input); + } + else { + input = _input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); + } + return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64"); +}; +exports.toBase64 = toBase64; diff --git a/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js new file mode 100644 index 00000000..b577c9ca --- /dev/null +++ b/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js @@ -0,0 +1,20 @@ +'use strict'; + +var isArrayBuffer = require('@smithy/is-array-buffer'); +var buffer = require('buffer'); + +const fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => { + if (!isArrayBuffer.isArrayBuffer(input)) { + throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); + } + return buffer.Buffer.from(input, offset, length); +}; +const fromString = (input, encoding) => { + if (typeof input !== "string") { + throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); + } + return encoding ? buffer.Buffer.from(input, encoding) : buffer.Buffer.from(input); +}; + +exports.fromArrayBuffer = fromArrayBuffer; +exports.fromString = fromString; diff --git a/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js new file mode 100644 index 00000000..3238bb77 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js @@ -0,0 +1,6 @@ +'use strict'; + +const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) || + Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; + +exports.isArrayBuffer = isArrayBuffer; diff --git a/claude-code-source/node_modules/@smithy/credential-provider-imds/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/credential-provider-imds/dist-cjs/index.js new file mode 100644 index 00000000..8de0d3f1 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/credential-provider-imds/dist-cjs/index.js @@ -0,0 +1,372 @@ +'use strict'; + +var propertyProvider = require('@smithy/property-provider'); +var url = require('url'); +var buffer = require('buffer'); +var http = require('http'); +var nodeConfigProvider = require('@smithy/node-config-provider'); +var urlParser = require('@smithy/url-parser'); + +function httpRequest(options) { + return new Promise((resolve, reject) => { + const req = http.request({ + method: "GET", + ...options, + hostname: options.hostname?.replace(/^\[(.+)\]$/, "$1"), + }); + req.on("error", (err) => { + reject(Object.assign(new propertyProvider.ProviderError("Unable to connect to instance metadata service"), err)); + req.destroy(); + }); + req.on("timeout", () => { + reject(new propertyProvider.ProviderError("TimeoutError from instance metadata service")); + req.destroy(); + }); + req.on("response", (res) => { + const { statusCode = 400 } = res; + if (statusCode < 200 || 300 <= statusCode) { + reject(Object.assign(new propertyProvider.ProviderError("Error response received from instance metadata service"), { statusCode })); + req.destroy(); + } + const chunks = []; + res.on("data", (chunk) => { + chunks.push(chunk); + }); + res.on("end", () => { + resolve(buffer.Buffer.concat(chunks)); + req.destroy(); + }); + }); + req.end(); + }); +} + +const isImdsCredentials = (arg) => Boolean(arg) && + typeof arg === "object" && + typeof arg.AccessKeyId === "string" && + typeof arg.SecretAccessKey === "string" && + typeof arg.Token === "string" && + typeof arg.Expiration === "string"; +const fromImdsCredentials = (creds) => ({ + accessKeyId: creds.AccessKeyId, + secretAccessKey: creds.SecretAccessKey, + sessionToken: creds.Token, + expiration: new Date(creds.Expiration), + ...(creds.AccountId && { accountId: creds.AccountId }), +}); + +const DEFAULT_TIMEOUT = 1000; +const DEFAULT_MAX_RETRIES = 0; +const providerConfigFromInit = ({ maxRetries = DEFAULT_MAX_RETRIES, timeout = DEFAULT_TIMEOUT, }) => ({ maxRetries, timeout }); + +const retry = (toRetry, maxRetries) => { + let promise = toRetry(); + for (let i = 0; i < maxRetries; i++) { + promise = promise.catch(toRetry); + } + return promise; +}; + +const ENV_CMDS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI"; +const ENV_CMDS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"; +const ENV_CMDS_AUTH_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN"; +const fromContainerMetadata = (init = {}) => { + const { timeout, maxRetries } = providerConfigFromInit(init); + return () => retry(async () => { + const requestOptions = await getCmdsUri({ logger: init.logger }); + const credsResponse = JSON.parse(await requestFromEcsImds(timeout, requestOptions)); + if (!isImdsCredentials(credsResponse)) { + throw new propertyProvider.CredentialsProviderError("Invalid response received from instance metadata service.", { + logger: init.logger, + }); + } + return fromImdsCredentials(credsResponse); + }, maxRetries); +}; +const requestFromEcsImds = async (timeout, options) => { + if (process.env[ENV_CMDS_AUTH_TOKEN]) { + options.headers = { + ...options.headers, + Authorization: process.env[ENV_CMDS_AUTH_TOKEN], + }; + } + const buffer = await httpRequest({ + ...options, + timeout, + }); + return buffer.toString(); +}; +const CMDS_IP = "169.254.170.2"; +const GREENGRASS_HOSTS = { + localhost: true, + "127.0.0.1": true, +}; +const GREENGRASS_PROTOCOLS = { + "http:": true, + "https:": true, +}; +const getCmdsUri = async ({ logger }) => { + if (process.env[ENV_CMDS_RELATIVE_URI]) { + return { + hostname: CMDS_IP, + path: process.env[ENV_CMDS_RELATIVE_URI], + }; + } + if (process.env[ENV_CMDS_FULL_URI]) { + const parsed = url.parse(process.env[ENV_CMDS_FULL_URI]); + if (!parsed.hostname || !(parsed.hostname in GREENGRASS_HOSTS)) { + throw new propertyProvider.CredentialsProviderError(`${parsed.hostname} is not a valid container metadata service hostname`, { + tryNextLink: false, + logger, + }); + } + if (!parsed.protocol || !(parsed.protocol in GREENGRASS_PROTOCOLS)) { + throw new propertyProvider.CredentialsProviderError(`${parsed.protocol} is not a valid container metadata service protocol`, { + tryNextLink: false, + logger, + }); + } + return { + ...parsed, + port: parsed.port ? parseInt(parsed.port, 10) : undefined, + }; + } + throw new propertyProvider.CredentialsProviderError("The container metadata credential provider cannot be used unless" + + ` the ${ENV_CMDS_RELATIVE_URI} or ${ENV_CMDS_FULL_URI} environment` + + " variable is set", { + tryNextLink: false, + logger, + }); +}; + +class InstanceMetadataV1FallbackError extends propertyProvider.CredentialsProviderError { + tryNextLink; + name = "InstanceMetadataV1FallbackError"; + constructor(message, tryNextLink = true) { + super(message, tryNextLink); + this.tryNextLink = tryNextLink; + Object.setPrototypeOf(this, InstanceMetadataV1FallbackError.prototype); + } +} + +exports.Endpoint = void 0; +(function (Endpoint) { + Endpoint["IPv4"] = "http://169.254.169.254"; + Endpoint["IPv6"] = "http://[fd00:ec2::254]"; +})(exports.Endpoint || (exports.Endpoint = {})); + +const ENV_ENDPOINT_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT"; +const CONFIG_ENDPOINT_NAME = "ec2_metadata_service_endpoint"; +const ENDPOINT_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => env[ENV_ENDPOINT_NAME], + configFileSelector: (profile) => profile[CONFIG_ENDPOINT_NAME], + default: undefined, +}; + +var EndpointMode; +(function (EndpointMode) { + EndpointMode["IPv4"] = "IPv4"; + EndpointMode["IPv6"] = "IPv6"; +})(EndpointMode || (EndpointMode = {})); + +const ENV_ENDPOINT_MODE_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE"; +const CONFIG_ENDPOINT_MODE_NAME = "ec2_metadata_service_endpoint_mode"; +const ENDPOINT_MODE_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => env[ENV_ENDPOINT_MODE_NAME], + configFileSelector: (profile) => profile[CONFIG_ENDPOINT_MODE_NAME], + default: EndpointMode.IPv4, +}; + +const getInstanceMetadataEndpoint = async () => urlParser.parseUrl((await getFromEndpointConfig()) || (await getFromEndpointModeConfig())); +const getFromEndpointConfig = async () => nodeConfigProvider.loadConfig(ENDPOINT_CONFIG_OPTIONS)(); +const getFromEndpointModeConfig = async () => { + const endpointMode = await nodeConfigProvider.loadConfig(ENDPOINT_MODE_CONFIG_OPTIONS)(); + switch (endpointMode) { + case EndpointMode.IPv4: + return exports.Endpoint.IPv4; + case EndpointMode.IPv6: + return exports.Endpoint.IPv6; + default: + throw new Error(`Unsupported endpoint mode: ${endpointMode}.` + ` Select from ${Object.values(EndpointMode)}`); + } +}; + +const STATIC_STABILITY_REFRESH_INTERVAL_SECONDS = 5 * 60; +const STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS = 5 * 60; +const STATIC_STABILITY_DOC_URL = "https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html"; +const getExtendedInstanceMetadataCredentials = (credentials, logger) => { + const refreshInterval = STATIC_STABILITY_REFRESH_INTERVAL_SECONDS + + Math.floor(Math.random() * STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS); + const newExpiration = new Date(Date.now() + refreshInterval * 1000); + logger.warn("Attempting credential expiration extension due to a credential service availability issue. A refresh of these " + + `credentials will be attempted after ${new Date(newExpiration)}.\nFor more information, please visit: ` + + STATIC_STABILITY_DOC_URL); + const originalExpiration = credentials.originalExpiration ?? credentials.expiration; + return { + ...credentials, + ...(originalExpiration ? { originalExpiration } : {}), + expiration: newExpiration, + }; +}; + +const staticStabilityProvider = (provider, options = {}) => { + const logger = options?.logger || console; + let pastCredentials; + return async () => { + let credentials; + try { + credentials = await provider(); + if (credentials.expiration && credentials.expiration.getTime() < Date.now()) { + credentials = getExtendedInstanceMetadataCredentials(credentials, logger); + } + } + catch (e) { + if (pastCredentials) { + logger.warn("Credential renew failed: ", e); + credentials = getExtendedInstanceMetadataCredentials(pastCredentials, logger); + } + else { + throw e; + } + } + pastCredentials = credentials; + return credentials; + }; +}; + +const IMDS_PATH = "/latest/meta-data/iam/security-credentials/"; +const IMDS_TOKEN_PATH = "/latest/api/token"; +const AWS_EC2_METADATA_V1_DISABLED = "AWS_EC2_METADATA_V1_DISABLED"; +const PROFILE_AWS_EC2_METADATA_V1_DISABLED = "ec2_metadata_v1_disabled"; +const X_AWS_EC2_METADATA_TOKEN = "x-aws-ec2-metadata-token"; +const fromInstanceMetadata = (init = {}) => staticStabilityProvider(getInstanceMetadataProvider(init), { logger: init.logger }); +const getInstanceMetadataProvider = (init = {}) => { + let disableFetchToken = false; + const { logger, profile } = init; + const { timeout, maxRetries } = providerConfigFromInit(init); + const getCredentials = async (maxRetries, options) => { + const isImdsV1Fallback = disableFetchToken || options.headers?.[X_AWS_EC2_METADATA_TOKEN] == null; + if (isImdsV1Fallback) { + let fallbackBlockedFromProfile = false; + let fallbackBlockedFromProcessEnv = false; + const configValue = await nodeConfigProvider.loadConfig({ + environmentVariableSelector: (env) => { + const envValue = env[AWS_EC2_METADATA_V1_DISABLED]; + fallbackBlockedFromProcessEnv = !!envValue && envValue !== "false"; + if (envValue === undefined) { + throw new propertyProvider.CredentialsProviderError(`${AWS_EC2_METADATA_V1_DISABLED} not set in env, checking config file next.`, { logger: init.logger }); + } + return fallbackBlockedFromProcessEnv; + }, + configFileSelector: (profile) => { + const profileValue = profile[PROFILE_AWS_EC2_METADATA_V1_DISABLED]; + fallbackBlockedFromProfile = !!profileValue && profileValue !== "false"; + return fallbackBlockedFromProfile; + }, + default: false, + }, { + profile, + })(); + if (init.ec2MetadataV1Disabled || configValue) { + const causes = []; + if (init.ec2MetadataV1Disabled) + causes.push("credential provider initialization (runtime option ec2MetadataV1Disabled)"); + if (fallbackBlockedFromProfile) + causes.push(`config file profile (${PROFILE_AWS_EC2_METADATA_V1_DISABLED})`); + if (fallbackBlockedFromProcessEnv) + causes.push(`process environment variable (${AWS_EC2_METADATA_V1_DISABLED})`); + throw new InstanceMetadataV1FallbackError(`AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${causes.join(", ")}].`); + } + } + const imdsProfile = (await retry(async () => { + let profile; + try { + profile = await getProfile(options); + } + catch (err) { + if (err.statusCode === 401) { + disableFetchToken = false; + } + throw err; + } + return profile; + }, maxRetries)).trim(); + return retry(async () => { + let creds; + try { + creds = await getCredentialsFromProfile(imdsProfile, options, init); + } + catch (err) { + if (err.statusCode === 401) { + disableFetchToken = false; + } + throw err; + } + return creds; + }, maxRetries); + }; + return async () => { + const endpoint = await getInstanceMetadataEndpoint(); + if (disableFetchToken) { + logger?.debug("AWS SDK Instance Metadata", "using v1 fallback (no token fetch)"); + return getCredentials(maxRetries, { ...endpoint, timeout }); + } + else { + let token; + try { + token = (await getMetadataToken({ ...endpoint, timeout })).toString(); + } + catch (error) { + if (error?.statusCode === 400) { + throw Object.assign(error, { + message: "EC2 Metadata token request returned error", + }); + } + else if (error.message === "TimeoutError" || [403, 404, 405].includes(error.statusCode)) { + disableFetchToken = true; + } + logger?.debug("AWS SDK Instance Metadata", "using v1 fallback (initial)"); + return getCredentials(maxRetries, { ...endpoint, timeout }); + } + return getCredentials(maxRetries, { + ...endpoint, + headers: { + [X_AWS_EC2_METADATA_TOKEN]: token, + }, + timeout, + }); + } + }; +}; +const getMetadataToken = async (options) => httpRequest({ + ...options, + path: IMDS_TOKEN_PATH, + method: "PUT", + headers: { + "x-aws-ec2-metadata-token-ttl-seconds": "21600", + }, +}); +const getProfile = async (options) => (await httpRequest({ ...options, path: IMDS_PATH })).toString(); +const getCredentialsFromProfile = async (profile, options, init) => { + const credentialsResponse = JSON.parse((await httpRequest({ + ...options, + path: IMDS_PATH + profile, + })).toString()); + if (!isImdsCredentials(credentialsResponse)) { + throw new propertyProvider.CredentialsProviderError("Invalid response received from instance metadata service.", { + logger: init.logger, + }); + } + return fromImdsCredentials(credentialsResponse); +}; + +exports.DEFAULT_MAX_RETRIES = DEFAULT_MAX_RETRIES; +exports.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT; +exports.ENV_CMDS_AUTH_TOKEN = ENV_CMDS_AUTH_TOKEN; +exports.ENV_CMDS_FULL_URI = ENV_CMDS_FULL_URI; +exports.ENV_CMDS_RELATIVE_URI = ENV_CMDS_RELATIVE_URI; +exports.fromContainerMetadata = fromContainerMetadata; +exports.fromInstanceMetadata = fromInstanceMetadata; +exports.getInstanceMetadataEndpoint = getInstanceMetadataEndpoint; +exports.httpRequest = httpRequest; +exports.providerConfigFromInit = providerConfigFromInit; diff --git a/claude-code-source/node_modules/@smithy/eventstream-codec/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/eventstream-codec/dist-cjs/index.js new file mode 100644 index 00000000..a17fea8d --- /dev/null +++ b/claude-code-source/node_modules/@smithy/eventstream-codec/dist-cjs/index.js @@ -0,0 +1,388 @@ +'use strict'; + +var crc32 = require('@aws-crypto/crc32'); +var utilHexEncoding = require('@smithy/util-hex-encoding'); + +class Int64 { + bytes; + constructor(bytes) { + this.bytes = bytes; + if (bytes.byteLength !== 8) { + throw new Error("Int64 buffers must be exactly 8 bytes"); + } + } + static fromNumber(number) { + if (number > 9_223_372_036_854_775_807 || number < -9223372036854776e3) { + throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`); + } + const bytes = new Uint8Array(8); + for (let i = 7, remaining = Math.abs(Math.round(number)); i > -1 && remaining > 0; i--, remaining /= 256) { + bytes[i] = remaining; + } + if (number < 0) { + negate(bytes); + } + return new Int64(bytes); + } + valueOf() { + const bytes = this.bytes.slice(0); + const negative = bytes[0] & 0b10000000; + if (negative) { + negate(bytes); + } + return parseInt(utilHexEncoding.toHex(bytes), 16) * (negative ? -1 : 1); + } + toString() { + return String(this.valueOf()); + } +} +function negate(bytes) { + for (let i = 0; i < 8; i++) { + bytes[i] ^= 0xff; + } + for (let i = 7; i > -1; i--) { + bytes[i]++; + if (bytes[i] !== 0) + break; + } +} + +class HeaderMarshaller { + toUtf8; + fromUtf8; + constructor(toUtf8, fromUtf8) { + this.toUtf8 = toUtf8; + this.fromUtf8 = fromUtf8; + } + format(headers) { + const chunks = []; + for (const headerName of Object.keys(headers)) { + const bytes = this.fromUtf8(headerName); + chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName])); + } + const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0)); + let position = 0; + for (const chunk of chunks) { + out.set(chunk, position); + position += chunk.byteLength; + } + return out; + } + formatHeaderValue(header) { + switch (header.type) { + case "boolean": + return Uint8Array.from([header.value ? 0 : 1]); + case "byte": + return Uint8Array.from([2, header.value]); + case "short": + const shortView = new DataView(new ArrayBuffer(3)); + shortView.setUint8(0, 3); + shortView.setInt16(1, header.value, false); + return new Uint8Array(shortView.buffer); + case "integer": + const intView = new DataView(new ArrayBuffer(5)); + intView.setUint8(0, 4); + intView.setInt32(1, header.value, false); + return new Uint8Array(intView.buffer); + case "long": + const longBytes = new Uint8Array(9); + longBytes[0] = 5; + longBytes.set(header.value.bytes, 1); + return longBytes; + case "binary": + const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength)); + binView.setUint8(0, 6); + binView.setUint16(1, header.value.byteLength, false); + const binBytes = new Uint8Array(binView.buffer); + binBytes.set(header.value, 3); + return binBytes; + case "string": + const utf8Bytes = this.fromUtf8(header.value); + const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength)); + strView.setUint8(0, 7); + strView.setUint16(1, utf8Bytes.byteLength, false); + const strBytes = new Uint8Array(strView.buffer); + strBytes.set(utf8Bytes, 3); + return strBytes; + case "timestamp": + const tsBytes = new Uint8Array(9); + tsBytes[0] = 8; + tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1); + return tsBytes; + case "uuid": + if (!UUID_PATTERN.test(header.value)) { + throw new Error(`Invalid UUID received: ${header.value}`); + } + const uuidBytes = new Uint8Array(17); + uuidBytes[0] = 9; + uuidBytes.set(utilHexEncoding.fromHex(header.value.replace(/\-/g, "")), 1); + return uuidBytes; + } + } + parse(headers) { + const out = {}; + let position = 0; + while (position < headers.byteLength) { + const nameLength = headers.getUint8(position++); + const name = this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, nameLength)); + position += nameLength; + switch (headers.getUint8(position++)) { + case 0: + out[name] = { + type: BOOLEAN_TAG, + value: true, + }; + break; + case 1: + out[name] = { + type: BOOLEAN_TAG, + value: false, + }; + break; + case 2: + out[name] = { + type: BYTE_TAG, + value: headers.getInt8(position++), + }; + break; + case 3: + out[name] = { + type: SHORT_TAG, + value: headers.getInt16(position, false), + }; + position += 2; + break; + case 4: + out[name] = { + type: INT_TAG, + value: headers.getInt32(position, false), + }; + position += 4; + break; + case 5: + out[name] = { + type: LONG_TAG, + value: new Int64(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)), + }; + position += 8; + break; + case 6: + const binaryLength = headers.getUint16(position, false); + position += 2; + out[name] = { + type: BINARY_TAG, + value: new Uint8Array(headers.buffer, headers.byteOffset + position, binaryLength), + }; + position += binaryLength; + break; + case 7: + const stringLength = headers.getUint16(position, false); + position += 2; + out[name] = { + type: STRING_TAG, + value: this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, stringLength)), + }; + position += stringLength; + break; + case 8: + out[name] = { + type: TIMESTAMP_TAG, + value: new Date(new Int64(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)).valueOf()), + }; + position += 8; + break; + case 9: + const uuidBytes = new Uint8Array(headers.buffer, headers.byteOffset + position, 16); + position += 16; + out[name] = { + type: UUID_TAG, + value: `${utilHexEncoding.toHex(uuidBytes.subarray(0, 4))}-${utilHexEncoding.toHex(uuidBytes.subarray(4, 6))}-${utilHexEncoding.toHex(uuidBytes.subarray(6, 8))}-${utilHexEncoding.toHex(uuidBytes.subarray(8, 10))}-${utilHexEncoding.toHex(uuidBytes.subarray(10))}`, + }; + break; + default: + throw new Error(`Unrecognized header type tag`); + } + } + return out; + } +} +const BOOLEAN_TAG = "boolean"; +const BYTE_TAG = "byte"; +const SHORT_TAG = "short"; +const INT_TAG = "integer"; +const LONG_TAG = "long"; +const BINARY_TAG = "binary"; +const STRING_TAG = "string"; +const TIMESTAMP_TAG = "timestamp"; +const UUID_TAG = "uuid"; +const UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; + +const PRELUDE_MEMBER_LENGTH = 4; +const PRELUDE_LENGTH = PRELUDE_MEMBER_LENGTH * 2; +const CHECKSUM_LENGTH = 4; +const MINIMUM_MESSAGE_LENGTH = PRELUDE_LENGTH + CHECKSUM_LENGTH * 2; +function splitMessage({ byteLength, byteOffset, buffer }) { + if (byteLength < MINIMUM_MESSAGE_LENGTH) { + throw new Error("Provided message too short to accommodate event stream message overhead"); + } + const view = new DataView(buffer, byteOffset, byteLength); + const messageLength = view.getUint32(0, false); + if (byteLength !== messageLength) { + throw new Error("Reported message length does not match received message length"); + } + const headerLength = view.getUint32(PRELUDE_MEMBER_LENGTH, false); + const expectedPreludeChecksum = view.getUint32(PRELUDE_LENGTH, false); + const expectedMessageChecksum = view.getUint32(byteLength - CHECKSUM_LENGTH, false); + const checksummer = new crc32.Crc32().update(new Uint8Array(buffer, byteOffset, PRELUDE_LENGTH)); + if (expectedPreludeChecksum !== checksummer.digest()) { + throw new Error(`The prelude checksum specified in the message (${expectedPreludeChecksum}) does not match the calculated CRC32 checksum (${checksummer.digest()})`); + } + checksummer.update(new Uint8Array(buffer, byteOffset + PRELUDE_LENGTH, byteLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH))); + if (expectedMessageChecksum !== checksummer.digest()) { + throw new Error(`The message checksum (${checksummer.digest()}) did not match the expected value of ${expectedMessageChecksum}`); + } + return { + headers: new DataView(buffer, byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH, headerLength), + body: new Uint8Array(buffer, byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH + headerLength, messageLength - headerLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH + CHECKSUM_LENGTH)), + }; +} + +class EventStreamCodec { + headerMarshaller; + messageBuffer; + isEndOfStream; + constructor(toUtf8, fromUtf8) { + this.headerMarshaller = new HeaderMarshaller(toUtf8, fromUtf8); + this.messageBuffer = []; + this.isEndOfStream = false; + } + feed(message) { + this.messageBuffer.push(this.decode(message)); + } + endOfStream() { + this.isEndOfStream = true; + } + getMessage() { + const message = this.messageBuffer.pop(); + const isEndOfStream = this.isEndOfStream; + return { + getMessage() { + return message; + }, + isEndOfStream() { + return isEndOfStream; + }, + }; + } + getAvailableMessages() { + const messages = this.messageBuffer; + this.messageBuffer = []; + const isEndOfStream = this.isEndOfStream; + return { + getMessages() { + return messages; + }, + isEndOfStream() { + return isEndOfStream; + }, + }; + } + encode({ headers: rawHeaders, body }) { + const headers = this.headerMarshaller.format(rawHeaders); + const length = headers.byteLength + body.byteLength + 16; + const out = new Uint8Array(length); + const view = new DataView(out.buffer, out.byteOffset, out.byteLength); + const checksum = new crc32.Crc32(); + view.setUint32(0, length, false); + view.setUint32(4, headers.byteLength, false); + view.setUint32(8, checksum.update(out.subarray(0, 8)).digest(), false); + out.set(headers, 12); + out.set(body, headers.byteLength + 12); + view.setUint32(length - 4, checksum.update(out.subarray(8, length - 4)).digest(), false); + return out; + } + decode(message) { + const { headers, body } = splitMessage(message); + return { headers: this.headerMarshaller.parse(headers), body }; + } + formatHeaders(rawHeaders) { + return this.headerMarshaller.format(rawHeaders); + } +} + +class MessageDecoderStream { + options; + constructor(options) { + this.options = options; + } + [Symbol.asyncIterator]() { + return this.asyncIterator(); + } + async *asyncIterator() { + for await (const bytes of this.options.inputStream) { + const decoded = this.options.decoder.decode(bytes); + yield decoded; + } + } +} + +class MessageEncoderStream { + options; + constructor(options) { + this.options = options; + } + [Symbol.asyncIterator]() { + return this.asyncIterator(); + } + async *asyncIterator() { + for await (const msg of this.options.messageStream) { + const encoded = this.options.encoder.encode(msg); + yield encoded; + } + if (this.options.includeEndFrame) { + yield new Uint8Array(0); + } + } +} + +class SmithyMessageDecoderStream { + options; + constructor(options) { + this.options = options; + } + [Symbol.asyncIterator]() { + return this.asyncIterator(); + } + async *asyncIterator() { + for await (const message of this.options.messageStream) { + const deserialized = await this.options.deserializer(message); + if (deserialized === undefined) + continue; + yield deserialized; + } + } +} + +class SmithyMessageEncoderStream { + options; + constructor(options) { + this.options = options; + } + [Symbol.asyncIterator]() { + return this.asyncIterator(); + } + async *asyncIterator() { + for await (const chunk of this.options.inputStream) { + const payloadBuf = this.options.serializer(chunk); + yield payloadBuf; + } + } +} + +exports.EventStreamCodec = EventStreamCodec; +exports.HeaderMarshaller = HeaderMarshaller; +exports.Int64 = Int64; +exports.MessageDecoderStream = MessageDecoderStream; +exports.MessageEncoderStream = MessageEncoderStream; +exports.SmithyMessageDecoderStream = SmithyMessageDecoderStream; +exports.SmithyMessageEncoderStream = SmithyMessageEncoderStream; diff --git a/claude-code-source/node_modules/@smithy/eventstream-codec/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/eventstream-codec/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js new file mode 100644 index 00000000..6d1eb2d1 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/eventstream-codec/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js @@ -0,0 +1,38 @@ +'use strict'; + +const SHORT_TO_HEX = {}; +const HEX_TO_SHORT = {}; +for (let i = 0; i < 256; i++) { + let encodedByte = i.toString(16).toLowerCase(); + if (encodedByte.length === 1) { + encodedByte = `0${encodedByte}`; + } + SHORT_TO_HEX[i] = encodedByte; + HEX_TO_SHORT[encodedByte] = i; +} +function fromHex(encoded) { + if (encoded.length % 2 !== 0) { + throw new Error("Hex encoded strings must have an even number length"); + } + const out = new Uint8Array(encoded.length / 2); + for (let i = 0; i < encoded.length; i += 2) { + const encodedByte = encoded.slice(i, i + 2).toLowerCase(); + if (encodedByte in HEX_TO_SHORT) { + out[i / 2] = HEX_TO_SHORT[encodedByte]; + } + else { + throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); + } + } + return out; +} +function toHex(bytes) { + let out = ""; + for (let i = 0; i < bytes.byteLength; i++) { + out += SHORT_TO_HEX[bytes[i]]; + } + return out; +} + +exports.fromHex = fromHex; +exports.toHex = toHex; diff --git a/claude-code-source/node_modules/@smithy/eventstream-serde-browser/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/eventstream-serde-browser/dist-cjs/index.js new file mode 100644 index 00000000..b3f5190d --- /dev/null +++ b/claude-code-source/node_modules/@smithy/eventstream-serde-browser/dist-cjs/index.js @@ -0,0 +1,58 @@ +'use strict'; + +var eventstreamSerdeUniversal = require('@smithy/eventstream-serde-universal'); + +const readableStreamtoIterable = (readableStream) => ({ + [Symbol.asyncIterator]: async function* () { + const reader = readableStream.getReader(); + try { + while (true) { + const { done, value } = await reader.read(); + if (done) + return; + yield value; + } + } + finally { + reader.releaseLock(); + } + }, +}); +const iterableToReadableStream = (asyncIterable) => { + const iterator = asyncIterable[Symbol.asyncIterator](); + return new ReadableStream({ + async pull(controller) { + const { done, value } = await iterator.next(); + if (done) { + return controller.close(); + } + controller.enqueue(value); + }, + }); +}; + +class EventStreamMarshaller { + universalMarshaller; + constructor({ utf8Encoder, utf8Decoder }) { + this.universalMarshaller = new eventstreamSerdeUniversal.EventStreamMarshaller({ + utf8Decoder, + utf8Encoder, + }); + } + deserialize(body, deserializer) { + const bodyIterable = isReadableStream(body) ? readableStreamtoIterable(body) : body; + return this.universalMarshaller.deserialize(bodyIterable, deserializer); + } + serialize(input, serializer) { + const serialziedIterable = this.universalMarshaller.serialize(input, serializer); + return typeof ReadableStream === "function" ? iterableToReadableStream(serialziedIterable) : serialziedIterable; + } +} +const isReadableStream = (body) => typeof ReadableStream === "function" && body instanceof ReadableStream; + +const eventStreamSerdeProvider = (options) => new EventStreamMarshaller(options); + +exports.EventStreamMarshaller = EventStreamMarshaller; +exports.eventStreamSerdeProvider = eventStreamSerdeProvider; +exports.iterableToReadableStream = iterableToReadableStream; +exports.readableStreamtoIterable = readableStreamtoIterable; diff --git a/claude-code-source/node_modules/@smithy/eventstream-serde-browser/node_modules/@smithy/eventstream-serde-universal/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/eventstream-serde-browser/node_modules/@smithy/eventstream-serde-universal/dist-cjs/index.js new file mode 100644 index 00000000..cd84e7bd --- /dev/null +++ b/claude-code-source/node_modules/@smithy/eventstream-serde-browser/node_modules/@smithy/eventstream-serde-universal/dist-cjs/index.js @@ -0,0 +1,132 @@ +'use strict'; + +var eventstreamCodec = require('@smithy/eventstream-codec'); + +function getChunkedStream(source) { + let currentMessageTotalLength = 0; + let currentMessagePendingLength = 0; + let currentMessage = null; + let messageLengthBuffer = null; + const allocateMessage = (size) => { + if (typeof size !== "number") { + throw new Error("Attempted to allocate an event message where size was not a number: " + size); + } + currentMessageTotalLength = size; + currentMessagePendingLength = 4; + currentMessage = new Uint8Array(size); + const currentMessageView = new DataView(currentMessage.buffer); + currentMessageView.setUint32(0, size, false); + }; + const iterator = async function* () { + const sourceIterator = source[Symbol.asyncIterator](); + while (true) { + const { value, done } = await sourceIterator.next(); + if (done) { + if (!currentMessageTotalLength) { + return; + } + else if (currentMessageTotalLength === currentMessagePendingLength) { + yield currentMessage; + } + else { + throw new Error("Truncated event message received."); + } + return; + } + const chunkLength = value.length; + let currentOffset = 0; + while (currentOffset < chunkLength) { + if (!currentMessage) { + const bytesRemaining = chunkLength - currentOffset; + if (!messageLengthBuffer) { + messageLengthBuffer = new Uint8Array(4); + } + const numBytesForTotal = Math.min(4 - currentMessagePendingLength, bytesRemaining); + messageLengthBuffer.set(value.slice(currentOffset, currentOffset + numBytesForTotal), currentMessagePendingLength); + currentMessagePendingLength += numBytesForTotal; + currentOffset += numBytesForTotal; + if (currentMessagePendingLength < 4) { + break; + } + allocateMessage(new DataView(messageLengthBuffer.buffer).getUint32(0, false)); + messageLengthBuffer = null; + } + const numBytesToWrite = Math.min(currentMessageTotalLength - currentMessagePendingLength, chunkLength - currentOffset); + currentMessage.set(value.slice(currentOffset, currentOffset + numBytesToWrite), currentMessagePendingLength); + currentMessagePendingLength += numBytesToWrite; + currentOffset += numBytesToWrite; + if (currentMessageTotalLength && currentMessageTotalLength === currentMessagePendingLength) { + yield currentMessage; + currentMessage = null; + currentMessageTotalLength = 0; + currentMessagePendingLength = 0; + } + } + } + }; + return { + [Symbol.asyncIterator]: iterator, + }; +} + +function getMessageUnmarshaller(deserializer, toUtf8) { + return async function (message) { + const { value: messageType } = message.headers[":message-type"]; + if (messageType === "error") { + const unmodeledError = new Error(message.headers[":error-message"].value || "UnknownError"); + unmodeledError.name = message.headers[":error-code"].value; + throw unmodeledError; + } + else if (messageType === "exception") { + const code = message.headers[":exception-type"].value; + const exception = { [code]: message }; + const deserializedException = await deserializer(exception); + if (deserializedException.$unknown) { + const error = new Error(toUtf8(message.body)); + error.name = code; + throw error; + } + throw deserializedException[code]; + } + else if (messageType === "event") { + const event = { + [message.headers[":event-type"].value]: message, + }; + const deserialized = await deserializer(event); + if (deserialized.$unknown) + return; + return deserialized; + } + else { + throw Error(`Unrecognizable event type: ${message.headers[":event-type"].value}`); + } + }; +} + +class EventStreamMarshaller { + eventStreamCodec; + utfEncoder; + constructor({ utf8Encoder, utf8Decoder }) { + this.eventStreamCodec = new eventstreamCodec.EventStreamCodec(utf8Encoder, utf8Decoder); + this.utfEncoder = utf8Encoder; + } + deserialize(body, deserializer) { + const inputStream = getChunkedStream(body); + return new eventstreamCodec.SmithyMessageDecoderStream({ + messageStream: new eventstreamCodec.MessageDecoderStream({ inputStream, decoder: this.eventStreamCodec }), + deserializer: getMessageUnmarshaller(deserializer, this.utfEncoder), + }); + } + serialize(inputStream, serializer) { + return new eventstreamCodec.MessageEncoderStream({ + messageStream: new eventstreamCodec.SmithyMessageEncoderStream({ inputStream, serializer }), + encoder: this.eventStreamCodec, + includeEndFrame: true, + }); + } +} + +const eventStreamSerdeProvider = (options) => new EventStreamMarshaller(options); + +exports.EventStreamMarshaller = EventStreamMarshaller; +exports.eventStreamSerdeProvider = eventStreamSerdeProvider; diff --git a/claude-code-source/node_modules/@smithy/eventstream-serde-config-resolver/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/eventstream-serde-config-resolver/dist-cjs/index.js new file mode 100644 index 00000000..ea364463 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/eventstream-serde-config-resolver/dist-cjs/index.js @@ -0,0 +1,7 @@ +'use strict'; + +const resolveEventStreamSerdeConfig = (input) => Object.assign(input, { + eventStreamMarshaller: input.eventStreamSerdeProvider(input), +}); + +exports.resolveEventStreamSerdeConfig = resolveEventStreamSerdeConfig; diff --git a/claude-code-source/node_modules/@smithy/eventstream-serde-node/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/eventstream-serde-node/dist-cjs/index.js new file mode 100644 index 00000000..63ca94de --- /dev/null +++ b/claude-code-source/node_modules/@smithy/eventstream-serde-node/dist-cjs/index.js @@ -0,0 +1,88 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + EventStreamMarshaller: () => EventStreamMarshaller, + eventStreamSerdeProvider: () => eventStreamSerdeProvider +}); +module.exports = __toCommonJS(src_exports); + +// src/EventStreamMarshaller.ts +var import_eventstream_serde_universal = require("@smithy/eventstream-serde-universal"); +var import_stream = require("stream"); + +// src/utils.ts +async function* readabletoIterable(readStream) { + let streamEnded = false; + let generationEnded = false; + const records = new Array(); + readStream.on("error", (err) => { + if (!streamEnded) { + streamEnded = true; + } + if (err) { + throw err; + } + }); + readStream.on("data", (data) => { + records.push(data); + }); + readStream.on("end", () => { + streamEnded = true; + }); + while (!generationEnded) { + const value = await new Promise((resolve) => setTimeout(() => resolve(records.shift()), 0)); + if (value) { + yield value; + } + generationEnded = streamEnded && records.length === 0; + } +} +__name(readabletoIterable, "readabletoIterable"); + +// src/EventStreamMarshaller.ts +var _EventStreamMarshaller = class _EventStreamMarshaller { + constructor({ utf8Encoder, utf8Decoder }) { + this.universalMarshaller = new import_eventstream_serde_universal.EventStreamMarshaller({ + utf8Decoder, + utf8Encoder + }); + } + deserialize(body, deserializer) { + const bodyIterable = typeof body[Symbol.asyncIterator] === "function" ? body : readabletoIterable(body); + return this.universalMarshaller.deserialize(bodyIterable, deserializer); + } + serialize(input, serializer) { + return import_stream.Readable.from(this.universalMarshaller.serialize(input, serializer)); + } +}; +__name(_EventStreamMarshaller, "EventStreamMarshaller"); +var EventStreamMarshaller = _EventStreamMarshaller; + +// src/provider.ts +var eventStreamSerdeProvider = /* @__PURE__ */ __name((options) => new EventStreamMarshaller(options), "eventStreamSerdeProvider"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (module.exports = { + EventStreamMarshaller, + eventStreamSerdeProvider +}); + diff --git a/claude-code-source/node_modules/@smithy/eventstream-serde-universal/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/eventstream-serde-universal/dist-cjs/index.js new file mode 100644 index 00000000..00eda6f2 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/eventstream-serde-universal/dist-cjs/index.js @@ -0,0 +1,182 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + EventStreamMarshaller: () => EventStreamMarshaller, + eventStreamSerdeProvider: () => eventStreamSerdeProvider +}); +module.exports = __toCommonJS(src_exports); + +// src/EventStreamMarshaller.ts +var import_eventstream_codec = require("@smithy/eventstream-codec"); + +// src/getChunkedStream.ts +function getChunkedStream(source) { + let currentMessageTotalLength = 0; + let currentMessagePendingLength = 0; + let currentMessage = null; + let messageLengthBuffer = null; + const allocateMessage = /* @__PURE__ */ __name((size) => { + if (typeof size !== "number") { + throw new Error("Attempted to allocate an event message where size was not a number: " + size); + } + currentMessageTotalLength = size; + currentMessagePendingLength = 4; + currentMessage = new Uint8Array(size); + const currentMessageView = new DataView(currentMessage.buffer); + currentMessageView.setUint32(0, size, false); + }, "allocateMessage"); + const iterator = /* @__PURE__ */ __name(async function* () { + const sourceIterator = source[Symbol.asyncIterator](); + while (true) { + const { value, done } = await sourceIterator.next(); + if (done) { + if (!currentMessageTotalLength) { + return; + } else if (currentMessageTotalLength === currentMessagePendingLength) { + yield currentMessage; + } else { + throw new Error("Truncated event message received."); + } + return; + } + const chunkLength = value.length; + let currentOffset = 0; + while (currentOffset < chunkLength) { + if (!currentMessage) { + const bytesRemaining = chunkLength - currentOffset; + if (!messageLengthBuffer) { + messageLengthBuffer = new Uint8Array(4); + } + const numBytesForTotal = Math.min( + 4 - currentMessagePendingLength, + // remaining bytes to fill the messageLengthBuffer + bytesRemaining + // bytes left in chunk + ); + messageLengthBuffer.set( + // @ts-ignore error TS2532: Object is possibly 'undefined' for value + value.slice(currentOffset, currentOffset + numBytesForTotal), + currentMessagePendingLength + ); + currentMessagePendingLength += numBytesForTotal; + currentOffset += numBytesForTotal; + if (currentMessagePendingLength < 4) { + break; + } + allocateMessage(new DataView(messageLengthBuffer.buffer).getUint32(0, false)); + messageLengthBuffer = null; + } + const numBytesToWrite = Math.min( + currentMessageTotalLength - currentMessagePendingLength, + // number of bytes left to complete message + chunkLength - currentOffset + // number of bytes left in the original chunk + ); + currentMessage.set( + // @ts-ignore error TS2532: Object is possibly 'undefined' for value + value.slice(currentOffset, currentOffset + numBytesToWrite), + currentMessagePendingLength + ); + currentMessagePendingLength += numBytesToWrite; + currentOffset += numBytesToWrite; + if (currentMessageTotalLength && currentMessageTotalLength === currentMessagePendingLength) { + yield currentMessage; + currentMessage = null; + currentMessageTotalLength = 0; + currentMessagePendingLength = 0; + } + } + } + }, "iterator"); + return { + [Symbol.asyncIterator]: iterator + }; +} +__name(getChunkedStream, "getChunkedStream"); + +// src/getUnmarshalledStream.ts +function getMessageUnmarshaller(deserializer, toUtf8) { + return async function(message) { + const { value: messageType } = message.headers[":message-type"]; + if (messageType === "error") { + const unmodeledError = new Error(message.headers[":error-message"].value || "UnknownError"); + unmodeledError.name = message.headers[":error-code"].value; + throw unmodeledError; + } else if (messageType === "exception") { + const code = message.headers[":exception-type"].value; + const exception = { [code]: message }; + const deserializedException = await deserializer(exception); + if (deserializedException.$unknown) { + const error = new Error(toUtf8(message.body)); + error.name = code; + throw error; + } + throw deserializedException[code]; + } else if (messageType === "event") { + const event = { + [message.headers[":event-type"].value]: message + }; + const deserialized = await deserializer(event); + if (deserialized.$unknown) + return; + return deserialized; + } else { + throw Error(`Unrecognizable event type: ${message.headers[":event-type"].value}`); + } + }; +} +__name(getMessageUnmarshaller, "getMessageUnmarshaller"); + +// src/EventStreamMarshaller.ts +var _EventStreamMarshaller = class _EventStreamMarshaller { + constructor({ utf8Encoder, utf8Decoder }) { + this.eventStreamCodec = new import_eventstream_codec.EventStreamCodec(utf8Encoder, utf8Decoder); + this.utfEncoder = utf8Encoder; + } + deserialize(body, deserializer) { + const inputStream = getChunkedStream(body); + return new import_eventstream_codec.SmithyMessageDecoderStream({ + messageStream: new import_eventstream_codec.MessageDecoderStream({ inputStream, decoder: this.eventStreamCodec }), + // @ts-expect-error Type 'T' is not assignable to type 'Record' + deserializer: getMessageUnmarshaller(deserializer, this.utfEncoder) + }); + } + serialize(inputStream, serializer) { + return new import_eventstream_codec.MessageEncoderStream({ + messageStream: new import_eventstream_codec.SmithyMessageEncoderStream({ inputStream, serializer }), + encoder: this.eventStreamCodec, + includeEndFrame: true + }); + } +}; +__name(_EventStreamMarshaller, "EventStreamMarshaller"); +var EventStreamMarshaller = _EventStreamMarshaller; + +// src/provider.ts +var eventStreamSerdeProvider = /* @__PURE__ */ __name((options) => new EventStreamMarshaller(options), "eventStreamSerdeProvider"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (module.exports = { + EventStreamMarshaller, + eventStreamSerdeProvider +}); + diff --git a/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/dist-cjs/index.js new file mode 100644 index 00000000..fac5c933 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/dist-cjs/index.js @@ -0,0 +1,468 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + EventStreamCodec: () => EventStreamCodec, + HeaderMarshaller: () => HeaderMarshaller, + Int64: () => Int64, + MessageDecoderStream: () => MessageDecoderStream, + MessageEncoderStream: () => MessageEncoderStream, + SmithyMessageDecoderStream: () => SmithyMessageDecoderStream, + SmithyMessageEncoderStream: () => SmithyMessageEncoderStream +}); +module.exports = __toCommonJS(src_exports); + +// src/EventStreamCodec.ts +var import_crc322 = require("@aws-crypto/crc32"); + +// src/HeaderMarshaller.ts + + +// src/Int64.ts +var import_util_hex_encoding = require("@smithy/util-hex-encoding"); +var _Int64 = class _Int64 { + constructor(bytes) { + this.bytes = bytes; + if (bytes.byteLength !== 8) { + throw new Error("Int64 buffers must be exactly 8 bytes"); + } + } + static fromNumber(number) { + if (number > 9223372036854776e3 || number < -9223372036854776e3) { + throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`); + } + const bytes = new Uint8Array(8); + for (let i = 7, remaining = Math.abs(Math.round(number)); i > -1 && remaining > 0; i--, remaining /= 256) { + bytes[i] = remaining; + } + if (number < 0) { + negate(bytes); + } + return new _Int64(bytes); + } + /** + * Called implicitly by infix arithmetic operators. + */ + valueOf() { + const bytes = this.bytes.slice(0); + const negative = bytes[0] & 128; + if (negative) { + negate(bytes); + } + return parseInt((0, import_util_hex_encoding.toHex)(bytes), 16) * (negative ? -1 : 1); + } + toString() { + return String(this.valueOf()); + } +}; +__name(_Int64, "Int64"); +var Int64 = _Int64; +function negate(bytes) { + for (let i = 0; i < 8; i++) { + bytes[i] ^= 255; + } + for (let i = 7; i > -1; i--) { + bytes[i]++; + if (bytes[i] !== 0) + break; + } +} +__name(negate, "negate"); + +// src/HeaderMarshaller.ts +var _HeaderMarshaller = class _HeaderMarshaller { + constructor(toUtf8, fromUtf8) { + this.toUtf8 = toUtf8; + this.fromUtf8 = fromUtf8; + } + format(headers) { + const chunks = []; + for (const headerName of Object.keys(headers)) { + const bytes = this.fromUtf8(headerName); + chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName])); + } + const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0)); + let position = 0; + for (const chunk of chunks) { + out.set(chunk, position); + position += chunk.byteLength; + } + return out; + } + formatHeaderValue(header) { + switch (header.type) { + case "boolean": + return Uint8Array.from([header.value ? 0 /* boolTrue */ : 1 /* boolFalse */]); + case "byte": + return Uint8Array.from([2 /* byte */, header.value]); + case "short": + const shortView = new DataView(new ArrayBuffer(3)); + shortView.setUint8(0, 3 /* short */); + shortView.setInt16(1, header.value, false); + return new Uint8Array(shortView.buffer); + case "integer": + const intView = new DataView(new ArrayBuffer(5)); + intView.setUint8(0, 4 /* integer */); + intView.setInt32(1, header.value, false); + return new Uint8Array(intView.buffer); + case "long": + const longBytes = new Uint8Array(9); + longBytes[0] = 5 /* long */; + longBytes.set(header.value.bytes, 1); + return longBytes; + case "binary": + const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength)); + binView.setUint8(0, 6 /* byteArray */); + binView.setUint16(1, header.value.byteLength, false); + const binBytes = new Uint8Array(binView.buffer); + binBytes.set(header.value, 3); + return binBytes; + case "string": + const utf8Bytes = this.fromUtf8(header.value); + const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength)); + strView.setUint8(0, 7 /* string */); + strView.setUint16(1, utf8Bytes.byteLength, false); + const strBytes = new Uint8Array(strView.buffer); + strBytes.set(utf8Bytes, 3); + return strBytes; + case "timestamp": + const tsBytes = new Uint8Array(9); + tsBytes[0] = 8 /* timestamp */; + tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1); + return tsBytes; + case "uuid": + if (!UUID_PATTERN.test(header.value)) { + throw new Error(`Invalid UUID received: ${header.value}`); + } + const uuidBytes = new Uint8Array(17); + uuidBytes[0] = 9 /* uuid */; + uuidBytes.set((0, import_util_hex_encoding.fromHex)(header.value.replace(/\-/g, "")), 1); + return uuidBytes; + } + } + parse(headers) { + const out = {}; + let position = 0; + while (position < headers.byteLength) { + const nameLength = headers.getUint8(position++); + const name = this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, nameLength)); + position += nameLength; + switch (headers.getUint8(position++)) { + case 0 /* boolTrue */: + out[name] = { + type: BOOLEAN_TAG, + value: true + }; + break; + case 1 /* boolFalse */: + out[name] = { + type: BOOLEAN_TAG, + value: false + }; + break; + case 2 /* byte */: + out[name] = { + type: BYTE_TAG, + value: headers.getInt8(position++) + }; + break; + case 3 /* short */: + out[name] = { + type: SHORT_TAG, + value: headers.getInt16(position, false) + }; + position += 2; + break; + case 4 /* integer */: + out[name] = { + type: INT_TAG, + value: headers.getInt32(position, false) + }; + position += 4; + break; + case 5 /* long */: + out[name] = { + type: LONG_TAG, + value: new Int64(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)) + }; + position += 8; + break; + case 6 /* byteArray */: + const binaryLength = headers.getUint16(position, false); + position += 2; + out[name] = { + type: BINARY_TAG, + value: new Uint8Array(headers.buffer, headers.byteOffset + position, binaryLength) + }; + position += binaryLength; + break; + case 7 /* string */: + const stringLength = headers.getUint16(position, false); + position += 2; + out[name] = { + type: STRING_TAG, + value: this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, stringLength)) + }; + position += stringLength; + break; + case 8 /* timestamp */: + out[name] = { + type: TIMESTAMP_TAG, + value: new Date(new Int64(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)).valueOf()) + }; + position += 8; + break; + case 9 /* uuid */: + const uuidBytes = new Uint8Array(headers.buffer, headers.byteOffset + position, 16); + position += 16; + out[name] = { + type: UUID_TAG, + value: `${(0, import_util_hex_encoding.toHex)(uuidBytes.subarray(0, 4))}-${(0, import_util_hex_encoding.toHex)(uuidBytes.subarray(4, 6))}-${(0, import_util_hex_encoding.toHex)( + uuidBytes.subarray(6, 8) + )}-${(0, import_util_hex_encoding.toHex)(uuidBytes.subarray(8, 10))}-${(0, import_util_hex_encoding.toHex)(uuidBytes.subarray(10))}` + }; + break; + default: + throw new Error(`Unrecognized header type tag`); + } + } + return out; + } +}; +__name(_HeaderMarshaller, "HeaderMarshaller"); +var HeaderMarshaller = _HeaderMarshaller; +var BOOLEAN_TAG = "boolean"; +var BYTE_TAG = "byte"; +var SHORT_TAG = "short"; +var INT_TAG = "integer"; +var LONG_TAG = "long"; +var BINARY_TAG = "binary"; +var STRING_TAG = "string"; +var TIMESTAMP_TAG = "timestamp"; +var UUID_TAG = "uuid"; +var UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; + +// src/splitMessage.ts +var import_crc32 = require("@aws-crypto/crc32"); +var PRELUDE_MEMBER_LENGTH = 4; +var PRELUDE_LENGTH = PRELUDE_MEMBER_LENGTH * 2; +var CHECKSUM_LENGTH = 4; +var MINIMUM_MESSAGE_LENGTH = PRELUDE_LENGTH + CHECKSUM_LENGTH * 2; +function splitMessage({ byteLength, byteOffset, buffer }) { + if (byteLength < MINIMUM_MESSAGE_LENGTH) { + throw new Error("Provided message too short to accommodate event stream message overhead"); + } + const view = new DataView(buffer, byteOffset, byteLength); + const messageLength = view.getUint32(0, false); + if (byteLength !== messageLength) { + throw new Error("Reported message length does not match received message length"); + } + const headerLength = view.getUint32(PRELUDE_MEMBER_LENGTH, false); + const expectedPreludeChecksum = view.getUint32(PRELUDE_LENGTH, false); + const expectedMessageChecksum = view.getUint32(byteLength - CHECKSUM_LENGTH, false); + const checksummer = new import_crc32.Crc32().update(new Uint8Array(buffer, byteOffset, PRELUDE_LENGTH)); + if (expectedPreludeChecksum !== checksummer.digest()) { + throw new Error( + `The prelude checksum specified in the message (${expectedPreludeChecksum}) does not match the calculated CRC32 checksum (${checksummer.digest()})` + ); + } + checksummer.update( + new Uint8Array(buffer, byteOffset + PRELUDE_LENGTH, byteLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH)) + ); + if (expectedMessageChecksum !== checksummer.digest()) { + throw new Error( + `The message checksum (${checksummer.digest()}) did not match the expected value of ${expectedMessageChecksum}` + ); + } + return { + headers: new DataView(buffer, byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH, headerLength), + body: new Uint8Array( + buffer, + byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH + headerLength, + messageLength - headerLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH + CHECKSUM_LENGTH) + ) + }; +} +__name(splitMessage, "splitMessage"); + +// src/EventStreamCodec.ts +var _EventStreamCodec = class _EventStreamCodec { + constructor(toUtf8, fromUtf8) { + this.headerMarshaller = new HeaderMarshaller(toUtf8, fromUtf8); + this.messageBuffer = []; + this.isEndOfStream = false; + } + feed(message) { + this.messageBuffer.push(this.decode(message)); + } + endOfStream() { + this.isEndOfStream = true; + } + getMessage() { + const message = this.messageBuffer.pop(); + const isEndOfStream = this.isEndOfStream; + return { + getMessage() { + return message; + }, + isEndOfStream() { + return isEndOfStream; + } + }; + } + getAvailableMessages() { + const messages = this.messageBuffer; + this.messageBuffer = []; + const isEndOfStream = this.isEndOfStream; + return { + getMessages() { + return messages; + }, + isEndOfStream() { + return isEndOfStream; + } + }; + } + /** + * Convert a structured JavaScript object with tagged headers into a binary + * event stream message. + */ + encode({ headers: rawHeaders, body }) { + const headers = this.headerMarshaller.format(rawHeaders); + const length = headers.byteLength + body.byteLength + 16; + const out = new Uint8Array(length); + const view = new DataView(out.buffer, out.byteOffset, out.byteLength); + const checksum = new import_crc322.Crc32(); + view.setUint32(0, length, false); + view.setUint32(4, headers.byteLength, false); + view.setUint32(8, checksum.update(out.subarray(0, 8)).digest(), false); + out.set(headers, 12); + out.set(body, headers.byteLength + 12); + view.setUint32(length - 4, checksum.update(out.subarray(8, length - 4)).digest(), false); + return out; + } + /** + * Convert a binary event stream message into a JavaScript object with an + * opaque, binary body and tagged, parsed headers. + */ + decode(message) { + const { headers, body } = splitMessage(message); + return { headers: this.headerMarshaller.parse(headers), body }; + } + /** + * Convert a structured JavaScript object with tagged headers into a binary + * event stream message header. + */ + formatHeaders(rawHeaders) { + return this.headerMarshaller.format(rawHeaders); + } +}; +__name(_EventStreamCodec, "EventStreamCodec"); +var EventStreamCodec = _EventStreamCodec; + +// src/MessageDecoderStream.ts +var _MessageDecoderStream = class _MessageDecoderStream { + constructor(options) { + this.options = options; + } + [Symbol.asyncIterator]() { + return this.asyncIterator(); + } + async *asyncIterator() { + for await (const bytes of this.options.inputStream) { + const decoded = this.options.decoder.decode(bytes); + yield decoded; + } + } +}; +__name(_MessageDecoderStream, "MessageDecoderStream"); +var MessageDecoderStream = _MessageDecoderStream; + +// src/MessageEncoderStream.ts +var _MessageEncoderStream = class _MessageEncoderStream { + constructor(options) { + this.options = options; + } + [Symbol.asyncIterator]() { + return this.asyncIterator(); + } + async *asyncIterator() { + for await (const msg of this.options.messageStream) { + const encoded = this.options.encoder.encode(msg); + yield encoded; + } + if (this.options.includeEndFrame) { + yield new Uint8Array(0); + } + } +}; +__name(_MessageEncoderStream, "MessageEncoderStream"); +var MessageEncoderStream = _MessageEncoderStream; + +// src/SmithyMessageDecoderStream.ts +var _SmithyMessageDecoderStream = class _SmithyMessageDecoderStream { + constructor(options) { + this.options = options; + } + [Symbol.asyncIterator]() { + return this.asyncIterator(); + } + async *asyncIterator() { + for await (const message of this.options.messageStream) { + const deserialized = await this.options.deserializer(message); + if (deserialized === void 0) + continue; + yield deserialized; + } + } +}; +__name(_SmithyMessageDecoderStream, "SmithyMessageDecoderStream"); +var SmithyMessageDecoderStream = _SmithyMessageDecoderStream; + +// src/SmithyMessageEncoderStream.ts +var _SmithyMessageEncoderStream = class _SmithyMessageEncoderStream { + constructor(options) { + this.options = options; + } + [Symbol.asyncIterator]() { + return this.asyncIterator(); + } + async *asyncIterator() { + for await (const chunk of this.options.inputStream) { + const payloadBuf = this.options.serializer(chunk); + yield payloadBuf; + } + } +}; +__name(_SmithyMessageEncoderStream, "SmithyMessageEncoderStream"); +var SmithyMessageEncoderStream = _SmithyMessageEncoderStream; +// Annotate the CommonJS export names for ESM import in node: + +0 && (module.exports = { + EventStreamCodec, + HeaderMarshaller, + Int64, + MessageDecoderStream, + MessageEncoderStream, + SmithyMessageDecoderStream, + SmithyMessageEncoderStream +}); + diff --git a/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/build/aws_crc32.js b/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/build/aws_crc32.js new file mode 100644 index 00000000..09c304cd --- /dev/null +++ b/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/build/aws_crc32.js @@ -0,0 +1,31 @@ +"use strict"; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AwsCrc32 = void 0; +var tslib_1 = require("tslib"); +var util_1 = require("@aws-crypto/util"); +var index_1 = require("./index"); +var AwsCrc32 = /** @class */ (function () { + function AwsCrc32() { + this.crc32 = new index_1.Crc32(); + } + AwsCrc32.prototype.update = function (toHash) { + if ((0, util_1.isEmptyData)(toHash)) + return; + this.crc32.update((0, util_1.convertToBuffer)(toHash)); + }; + AwsCrc32.prototype.digest = function () { + return tslib_1.__awaiter(this, void 0, void 0, function () { + return tslib_1.__generator(this, function (_a) { + return [2 /*return*/, (0, util_1.numToUint8)(this.crc32.digest())]; + }); + }); + }; + AwsCrc32.prototype.reset = function () { + this.crc32 = new index_1.Crc32(); + }; + return AwsCrc32; +}()); +exports.AwsCrc32 = AwsCrc32; +//# sourceMappingURL=aws_crc32.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/build/index.js b/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/build/index.js new file mode 100644 index 00000000..fa789688 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/build/index.js @@ -0,0 +1,108 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AwsCrc32 = exports.Crc32 = exports.crc32 = void 0; +var tslib_1 = require("tslib"); +var util_1 = require("@aws-crypto/util"); +function crc32(data) { + return new Crc32().update(data).digest(); +} +exports.crc32 = crc32; +var Crc32 = /** @class */ (function () { + function Crc32() { + this.checksum = 0xffffffff; + } + Crc32.prototype.update = function (data) { + var e_1, _a; + try { + for (var data_1 = tslib_1.__values(data), data_1_1 = data_1.next(); !data_1_1.done; data_1_1 = data_1.next()) { + var byte = data_1_1.value; + this.checksum = + (this.checksum >>> 8) ^ lookupTable[(this.checksum ^ byte) & 0xff]; + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (data_1_1 && !data_1_1.done && (_a = data_1.return)) _a.call(data_1); + } + finally { if (e_1) throw e_1.error; } + } + return this; + }; + Crc32.prototype.digest = function () { + return (this.checksum ^ 0xffffffff) >>> 0; + }; + return Crc32; +}()); +exports.Crc32 = Crc32; +// prettier-ignore +var a_lookUpTable = [ + 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, + 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, + 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, + 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, + 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, + 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, + 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, + 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, + 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, + 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, + 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, + 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, + 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, + 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, + 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, + 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, + 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, + 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, + 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, + 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, + 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, + 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, + 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, + 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, + 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, + 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, + 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, + 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, + 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, + 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, + 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, + 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, + 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, + 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, + 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, + 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, + 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, + 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, + 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, + 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, + 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, + 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, + 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, + 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, + 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, + 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, + 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, + 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, + 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, + 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, + 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, + 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, + 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, + 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, + 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, + 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, + 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, + 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, + 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, + 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, + 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, + 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, + 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, + 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D, +]; +var lookupTable = (0, util_1.uint32ArrayFrom)(a_lookUpTable); +var aws_crc32_1 = require("./aws_crc32"); +Object.defineProperty(exports, "AwsCrc32", { enumerable: true, get: function () { return aws_crc32_1.AwsCrc32; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/convertToBuffer.js b/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/convertToBuffer.js new file mode 100644 index 00000000..6cc8bcfe --- /dev/null +++ b/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/convertToBuffer.js @@ -0,0 +1,24 @@ +"use strict"; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +Object.defineProperty(exports, "__esModule", { value: true }); +exports.convertToBuffer = void 0; +var util_utf8_browser_1 = require("@aws-sdk/util-utf8-browser"); +// Quick polyfill +var fromUtf8 = typeof Buffer !== "undefined" && Buffer.from + ? function (input) { return Buffer.from(input, "utf8"); } + : util_utf8_browser_1.fromUtf8; +function convertToBuffer(data) { + // Already a Uint8, do nothing + if (data instanceof Uint8Array) + return data; + if (typeof data === "string") { + return fromUtf8(data); + } + if (ArrayBuffer.isView(data)) { + return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); + } + return new Uint8Array(data); +} +exports.convertToBuffer = convertToBuffer; +//# sourceMappingURL=convertToBuffer.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/index.js b/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/index.js new file mode 100644 index 00000000..94e1ca90 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/index.js @@ -0,0 +1,14 @@ +"use strict"; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +Object.defineProperty(exports, "__esModule", { value: true }); +exports.uint32ArrayFrom = exports.numToUint8 = exports.isEmptyData = exports.convertToBuffer = void 0; +var convertToBuffer_1 = require("./convertToBuffer"); +Object.defineProperty(exports, "convertToBuffer", { enumerable: true, get: function () { return convertToBuffer_1.convertToBuffer; } }); +var isEmptyData_1 = require("./isEmptyData"); +Object.defineProperty(exports, "isEmptyData", { enumerable: true, get: function () { return isEmptyData_1.isEmptyData; } }); +var numToUint8_1 = require("./numToUint8"); +Object.defineProperty(exports, "numToUint8", { enumerable: true, get: function () { return numToUint8_1.numToUint8; } }); +var uint32ArrayFrom_1 = require("./uint32ArrayFrom"); +Object.defineProperty(exports, "uint32ArrayFrom", { enumerable: true, get: function () { return uint32ArrayFrom_1.uint32ArrayFrom; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/isEmptyData.js b/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/isEmptyData.js new file mode 100644 index 00000000..6af1e89e --- /dev/null +++ b/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/isEmptyData.js @@ -0,0 +1,13 @@ +"use strict"; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isEmptyData = void 0; +function isEmptyData(data) { + if (typeof data === "string") { + return data.length === 0; + } + return data.byteLength === 0; +} +exports.isEmptyData = isEmptyData; +//# sourceMappingURL=isEmptyData.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/numToUint8.js b/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/numToUint8.js new file mode 100644 index 00000000..2f070e10 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/numToUint8.js @@ -0,0 +1,15 @@ +"use strict"; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +Object.defineProperty(exports, "__esModule", { value: true }); +exports.numToUint8 = void 0; +function numToUint8(num) { + return new Uint8Array([ + (num & 0xff000000) >> 24, + (num & 0x00ff0000) >> 16, + (num & 0x0000ff00) >> 8, + num & 0x000000ff, + ]); +} +exports.numToUint8 = numToUint8; +//# sourceMappingURL=numToUint8.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/uint32ArrayFrom.js b/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/uint32ArrayFrom.js new file mode 100644 index 00000000..226cdc3d --- /dev/null +++ b/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/uint32ArrayFrom.js @@ -0,0 +1,20 @@ +"use strict"; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +Object.defineProperty(exports, "__esModule", { value: true }); +exports.uint32ArrayFrom = void 0; +// IE 11 does not support Array.from, so we do it manually +function uint32ArrayFrom(a_lookUpTable) { + if (!Uint32Array.from) { + var return_array = new Uint32Array(a_lookUpTable.length); + var a_index = 0; + while (a_index < a_lookUpTable.length) { + return_array[a_index] = a_lookUpTable[a_index]; + a_index += 1; + } + return return_array; + } + return Uint32Array.from(a_lookUpTable); +} +exports.uint32ArrayFrom = uint32ArrayFrom; +//# sourceMappingURL=uint32ArrayFrom.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/tslib/tslib.js b/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/tslib/tslib.js new file mode 100644 index 00000000..e5b7c9b8 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/tslib/tslib.js @@ -0,0 +1,284 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ + +/* global global, define, System, Reflect, Promise */ +var __extends; +var __assign; +var __rest; +var __decorate; +var __param; +var __metadata; +var __awaiter; +var __generator; +var __exportStar; +var __values; +var __read; +var __spread; +var __spreadArrays; +var __await; +var __asyncGenerator; +var __asyncDelegator; +var __asyncValues; +var __makeTemplateObject; +var __importStar; +var __importDefault; +var __classPrivateFieldGet; +var __classPrivateFieldSet; +var __createBinding; +(function (factory) { + var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; + if (typeof define === "function" && define.amd) { + define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); + } + else if (typeof module === "object" && typeof module.exports === "object") { + factory(createExporter(root, createExporter(module.exports))); + } + else { + factory(createExporter(root)); + } + function createExporter(exports, previous) { + if (exports !== root) { + if (typeof Object.create === "function") { + Object.defineProperty(exports, "__esModule", { value: true }); + } + else { + exports.__esModule = true; + } + } + return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; + } +}) +(function (exporter) { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + + __extends = function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + + __assign = Object.assign || function (t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + + __rest = function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; + }; + + __decorate = function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + + __param = function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + + __metadata = function (metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); + }; + + __awaiter = function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + + __generator = function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + + __createBinding = function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }; + + __exportStar = function (m, exports) { + for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) exports[p] = m[p]; + }; + + __values = function (o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + + __read = function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + + __spread = function () { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; + }; + + __spreadArrays = function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; + }; + + __await = function (v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + }; + + __asyncGenerator = function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + }; + + __asyncDelegator = function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } + }; + + __asyncValues = function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } + }; + + __makeTemplateObject = function (cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; + }; + + __importStar = function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; + }; + + __importDefault = function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + + __classPrivateFieldGet = function (receiver, privateMap) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to get private field on non-instance"); + } + return privateMap.get(receiver); + }; + + __classPrivateFieldSet = function (receiver, privateMap, value) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to set private field on non-instance"); + } + privateMap.set(receiver, value); + return value; + }; + + exporter("__extends", __extends); + exporter("__assign", __assign); + exporter("__rest", __rest); + exporter("__decorate", __decorate); + exporter("__param", __param); + exporter("__metadata", __metadata); + exporter("__awaiter", __awaiter); + exporter("__generator", __generator); + exporter("__exportStar", __exportStar); + exporter("__createBinding", __createBinding); + exporter("__values", __values); + exporter("__read", __read); + exporter("__spread", __spread); + exporter("__spreadArrays", __spreadArrays); + exporter("__await", __await); + exporter("__asyncGenerator", __asyncGenerator); + exporter("__asyncDelegator", __asyncDelegator); + exporter("__asyncValues", __asyncValues); + exporter("__makeTemplateObject", __makeTemplateObject); + exporter("__importStar", __importStar); + exporter("__importDefault", __importDefault); + exporter("__classPrivateFieldGet", __classPrivateFieldGet); + exporter("__classPrivateFieldSet", __classPrivateFieldSet); +}); diff --git a/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js new file mode 100644 index 00000000..78a59ea8 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js @@ -0,0 +1,67 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + fromHex: () => fromHex, + toHex: () => toHex +}); +module.exports = __toCommonJS(src_exports); +var SHORT_TO_HEX = {}; +var HEX_TO_SHORT = {}; +for (let i = 0; i < 256; i++) { + let encodedByte = i.toString(16).toLowerCase(); + if (encodedByte.length === 1) { + encodedByte = `0${encodedByte}`; + } + SHORT_TO_HEX[i] = encodedByte; + HEX_TO_SHORT[encodedByte] = i; +} +function fromHex(encoded) { + if (encoded.length % 2 !== 0) { + throw new Error("Hex encoded strings must have an even number length"); + } + const out = new Uint8Array(encoded.length / 2); + for (let i = 0; i < encoded.length; i += 2) { + const encodedByte = encoded.slice(i, i + 2).toLowerCase(); + if (encodedByte in HEX_TO_SHORT) { + out[i / 2] = HEX_TO_SHORT[encodedByte]; + } else { + throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); + } + } + return out; +} +__name(fromHex, "fromHex"); +function toHex(bytes) { + let out = ""; + for (let i = 0; i < bytes.byteLength; i++) { + out += SHORT_TO_HEX[bytes[i]]; + } + return out; +} +__name(toHex, "toHex"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (module.exports = { + fromHex, + toHex +}); + diff --git a/claude-code-source/node_modules/@smithy/fetch-http-handler/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/fetch-http-handler/dist-cjs/index.js new file mode 100644 index 00000000..9c9c44b9 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/fetch-http-handler/dist-cjs/index.js @@ -0,0 +1,264 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + FetchHttpHandler: () => FetchHttpHandler, + keepAliveSupport: () => keepAliveSupport, + streamCollector: () => streamCollector +}); +module.exports = __toCommonJS(src_exports); + +// src/fetch-http-handler.ts +var import_protocol_http = require("@smithy/protocol-http"); +var import_querystring_builder = require("@smithy/querystring-builder"); + +// src/create-request.ts +function createRequest(url, requestOptions) { + return new Request(url, requestOptions); +} +__name(createRequest, "createRequest"); + +// src/request-timeout.ts +function requestTimeout(timeoutInMs = 0) { + return new Promise((resolve, reject) => { + if (timeoutInMs) { + setTimeout(() => { + const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`); + timeoutError.name = "TimeoutError"; + reject(timeoutError); + }, timeoutInMs); + } + }); +} +__name(requestTimeout, "requestTimeout"); + +// src/fetch-http-handler.ts +var keepAliveSupport = { + supported: void 0 +}; +var FetchHttpHandler = class _FetchHttpHandler { + static { + __name(this, "FetchHttpHandler"); + } + /** + * @returns the input if it is an HttpHandler of any class, + * or instantiates a new instance of this handler. + */ + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; + } + return new _FetchHttpHandler(instanceOrOptions); + } + constructor(options) { + if (typeof options === "function") { + this.configProvider = options().then((opts) => opts || {}); + } else { + this.config = options ?? {}; + this.configProvider = Promise.resolve(this.config); + } + if (keepAliveSupport.supported === void 0) { + keepAliveSupport.supported = Boolean( + typeof Request !== "undefined" && "keepalive" in createRequest("https://[::1]") + ); + } + } + destroy() { + } + async handle(request, { abortSignal } = {}) { + if (!this.config) { + this.config = await this.configProvider; + } + const requestTimeoutInMs = this.config.requestTimeout; + const keepAlive = this.config.keepAlive === true; + const credentials = this.config.credentials; + if (abortSignal?.aborted) { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + return Promise.reject(abortError); + } + let path = request.path; + const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); + if (queryString) { + path += `?${queryString}`; + } + if (request.fragment) { + path += `#${request.fragment}`; + } + let auth = ""; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}@`; + } + const { port, method } = request; + const url = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : ""}${path}`; + const body = method === "GET" || method === "HEAD" ? void 0 : request.body; + const requestOptions = { + body, + headers: new Headers(request.headers), + method, + credentials + }; + if (this.config?.cache) { + requestOptions.cache = this.config.cache; + } + if (body) { + requestOptions.duplex = "half"; + } + if (typeof AbortController !== "undefined") { + requestOptions.signal = abortSignal; + } + if (keepAliveSupport.supported) { + requestOptions.keepalive = keepAlive; + } + if (typeof this.config.requestInit === "function") { + Object.assign(requestOptions, this.config.requestInit(request)); + } + let removeSignalEventListener = /* @__PURE__ */ __name(() => { + }, "removeSignalEventListener"); + const fetchRequest = createRequest(url, requestOptions); + const raceOfPromises = [ + fetch(fetchRequest).then((response) => { + const fetchHeaders = response.headers; + const transformedHeaders = {}; + for (const pair of fetchHeaders.entries()) { + transformedHeaders[pair[0]] = pair[1]; + } + const hasReadableStream = response.body != void 0; + if (!hasReadableStream) { + return response.blob().then((body2) => ({ + response: new import_protocol_http.HttpResponse({ + headers: transformedHeaders, + reason: response.statusText, + statusCode: response.status, + body: body2 + }) + })); + } + return { + response: new import_protocol_http.HttpResponse({ + headers: transformedHeaders, + reason: response.statusText, + statusCode: response.status, + body: response.body + }) + }; + }), + requestTimeout(requestTimeoutInMs) + ]; + if (abortSignal) { + raceOfPromises.push( + new Promise((resolve, reject) => { + const onAbort = /* @__PURE__ */ __name(() => { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + }, "onAbort"); + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + removeSignalEventListener = /* @__PURE__ */ __name(() => signal.removeEventListener("abort", onAbort), "removeSignalEventListener"); + } else { + abortSignal.onabort = onAbort; + } + }) + ); + } + return Promise.race(raceOfPromises).finally(removeSignalEventListener); + } + updateHttpClientConfig(key, value) { + this.config = void 0; + this.configProvider = this.configProvider.then((config) => { + config[key] = value; + return config; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; + } +}; + +// src/stream-collector.ts +var import_util_base64 = require("@smithy/util-base64"); +var streamCollector = /* @__PURE__ */ __name(async (stream) => { + if (typeof Blob === "function" && stream instanceof Blob || stream.constructor?.name === "Blob") { + if (Blob.prototype.arrayBuffer !== void 0) { + return new Uint8Array(await stream.arrayBuffer()); + } + return collectBlob(stream); + } + return collectStream(stream); +}, "streamCollector"); +async function collectBlob(blob) { + const base64 = await readToBase64(blob); + const arrayBuffer = (0, import_util_base64.fromBase64)(base64); + return new Uint8Array(arrayBuffer); +} +__name(collectBlob, "collectBlob"); +async function collectStream(stream) { + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + let length = 0; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + length += value.length; + } + isDone = done; + } + const collected = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + collected.set(chunk, offset); + offset += chunk.length; + } + return collected; +} +__name(collectStream, "collectStream"); +function readToBase64(blob) { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onloadend = () => { + if (reader.readyState !== 2) { + return reject(new Error("Reader aborted too early")); + } + const result = reader.result ?? ""; + const commaIndex = result.indexOf(","); + const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length; + resolve(result.substring(dataOffset)); + }; + reader.onabort = () => reject(new Error("Read aborted")); + reader.onerror = () => reject(reader.error); + reader.readAsDataURL(blob); + }); +} +__name(readToBase64, "readToBase64"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (module.exports = { + keepAliveSupport, + FetchHttpHandler, + streamCollector +}); + diff --git a/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-cjs/index.js new file mode 100644 index 00000000..df371090 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-cjs/index.js @@ -0,0 +1,262 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + Field: () => Field, + Fields: () => Fields, + HttpRequest: () => HttpRequest, + HttpResponse: () => HttpResponse, + IHttpRequest: () => import_types.HttpRequest, + getHttpHandlerExtensionConfiguration: () => getHttpHandlerExtensionConfiguration, + isValidHostname: () => isValidHostname, + resolveHttpHandlerRuntimeConfig: () => resolveHttpHandlerRuntimeConfig +}); +module.exports = __toCommonJS(src_exports); + +// src/extensions/httpExtensionConfiguration.ts +var getHttpHandlerExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + return { + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); + } + }; +}, "getHttpHandlerExtensionConfiguration"); +var resolveHttpHandlerRuntimeConfig = /* @__PURE__ */ __name((httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler() + }; +}, "resolveHttpHandlerRuntimeConfig"); + +// src/Field.ts +var import_types = require("@smithy/types"); +var Field = class { + static { + __name(this, "Field"); + } + constructor({ name, kind = import_types.FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; + } + /** + * Appends a value to the field. + * + * @param value The value to append. + */ + add(value) { + this.values.push(value); + } + /** + * Overwrite existing field values. + * + * @param values The new field values. + */ + set(values) { + this.values = values; + } + /** + * Remove all matching entries from list. + * + * @param value Value to remove. + */ + remove(value) { + this.values = this.values.filter((v) => v !== value); + } + /** + * Get comma-delimited string. + * + * @returns String representation of {@link Field}. + */ + toString() { + return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", "); + } + /** + * Get string values as a list + * + * @returns Values in {@link Field} as a list. + */ + get() { + return this.values; + } +}; + +// src/Fields.ts +var Fields = class { + constructor({ fields = [], encoding = "utf-8" }) { + this.entries = {}; + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + static { + __name(this, "Fields"); + } + /** + * Set entry for a {@link Field} name. The `name` + * attribute will be used to key the collection. + * + * @param field The {@link Field} to set. + */ + setField(field) { + this.entries[field.name.toLowerCase()] = field; + } + /** + * Retrieve {@link Field} entry by name. + * + * @param name The name of the {@link Field} entry + * to retrieve + * @returns The {@link Field} if it exists. + */ + getField(name) { + return this.entries[name.toLowerCase()]; + } + /** + * Delete entry from collection. + * + * @param name Name of the entry to delete. + */ + removeField(name) { + delete this.entries[name.toLowerCase()]; + } + /** + * Helper function for retrieving specific types of fields. + * Used to grab all headers or all trailers. + * + * @param kind {@link FieldPosition} of entries to retrieve. + * @returns The {@link Field} entries with the specified + * {@link FieldPosition}. + */ + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } +}; + +// src/httpRequest.ts + +var HttpRequest = class _HttpRequest { + static { + __name(this, "HttpRequest"); + } + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:"; + this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + /** + * Note: this does not deep-clone the body. + */ + static clone(request) { + const cloned = new _HttpRequest({ + ...request, + headers: { ...request.headers } + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); + } + return cloned; + } + /** + * This method only actually asserts that request is the interface {@link IHttpRequest}, + * and not necessarily this concrete class. Left in place for API stability. + * + * Do not call instance methods on the input of this function, and + * do not assume it has the HttpRequest prototype. + */ + static isInstance(request) { + if (!request) { + return false; + } + const req = request; + return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object"; + } + /** + * @deprecated use static HttpRequest.clone(request) instead. It's not safe to call + * this method because {@link HttpRequest.isInstance} incorrectly + * asserts that IHttpRequest (interface) objects are of type HttpRequest (class). + */ + clone() { + return _HttpRequest.clone(this); + } +}; +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param + }; + }, {}); +} +__name(cloneQuery, "cloneQuery"); + +// src/httpResponse.ts +var HttpResponse = class { + static { + __name(this, "HttpResponse"); + } + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) + return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + } +}; + +// src/isValidHostname.ts +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} +__name(isValidHostname, "isValidHostname"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (module.exports = { + getHttpHandlerExtensionConfiguration, + resolveHttpHandlerRuntimeConfig, + Field, + Fields, + HttpRequest, + HttpResponse, + isValidHostname +}); + diff --git a/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/types/dist-cjs/index.js new file mode 100644 index 00000000..0849f2b4 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/types/dist-cjs/index.js @@ -0,0 +1,144 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + AlgorithmId: () => AlgorithmId, + EndpointURLScheme: () => EndpointURLScheme, + FieldPosition: () => FieldPosition, + HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, + HttpAuthLocation: () => HttpAuthLocation, + IniSectionType: () => IniSectionType, + RequestHandlerProtocol: () => RequestHandlerProtocol, + SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, + getDefaultClientConfiguration: () => getDefaultClientConfiguration, + resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig +}); +module.exports = __toCommonJS(src_exports); + +// src/auth/auth.ts +var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { + HttpAuthLocation2["HEADER"] = "header"; + HttpAuthLocation2["QUERY"] = "query"; + return HttpAuthLocation2; +})(HttpAuthLocation || {}); + +// src/auth/HttpApiKeyAuth.ts +var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { + HttpApiKeyAuthLocation2["HEADER"] = "header"; + HttpApiKeyAuthLocation2["QUERY"] = "query"; + return HttpApiKeyAuthLocation2; +})(HttpApiKeyAuthLocation || {}); + +// src/endpoint.ts +var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { + EndpointURLScheme2["HTTP"] = "http"; + EndpointURLScheme2["HTTPS"] = "https"; + return EndpointURLScheme2; +})(EndpointURLScheme || {}); + +// src/extensions/checksum.ts +var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { + AlgorithmId2["MD5"] = "md5"; + AlgorithmId2["CRC32"] = "crc32"; + AlgorithmId2["CRC32C"] = "crc32c"; + AlgorithmId2["SHA1"] = "sha1"; + AlgorithmId2["SHA256"] = "sha256"; + return AlgorithmId2; +})(AlgorithmId || {}); +var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== void 0) { + checksumAlgorithms.push({ + algorithmId: () => "sha256" /* SHA256 */, + checksumConstructor: () => runtimeConfig.sha256 + }); + } + if (runtimeConfig.md5 != void 0) { + checksumAlgorithms.push({ + algorithmId: () => "md5" /* MD5 */, + checksumConstructor: () => runtimeConfig.md5 + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + } + }; +}, "getChecksumConfiguration"); +var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}, "resolveChecksumRuntimeConfig"); + +// src/extensions/defaultClientConfiguration.ts +var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}, "getDefaultClientConfiguration"); +var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { + return resolveChecksumRuntimeConfig(config); +}, "resolveDefaultRuntimeConfig"); + +// src/http.ts +var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { + FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; + FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; + return FieldPosition2; +})(FieldPosition || {}); + +// src/middleware.ts +var SMITHY_CONTEXT_KEY = "__smithy_context"; + +// src/profile.ts +var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { + IniSectionType2["PROFILE"] = "profile"; + IniSectionType2["SSO_SESSION"] = "sso-session"; + IniSectionType2["SERVICES"] = "services"; + return IniSectionType2; +})(IniSectionType || {}); + +// src/transfer.ts +var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { + RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; + return RequestHandlerProtocol2; +})(RequestHandlerProtocol || {}); +// Annotate the CommonJS export names for ESM import in node: + +0 && (module.exports = { + HttpAuthLocation, + HttpApiKeyAuthLocation, + EndpointURLScheme, + AlgorithmId, + getDefaultClientConfiguration, + resolveDefaultRuntimeConfig, + FieldPosition, + SMITHY_CONTEXT_KEY, + IniSectionType, + RequestHandlerProtocol +}); + diff --git a/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js b/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js new file mode 100644 index 00000000..b06a7b87 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromBase64 = void 0; +const util_buffer_from_1 = require("@smithy/util-buffer-from"); +const BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; +const fromBase64 = (input) => { + if ((input.length * 3) % 4 !== 0) { + throw new TypeError(`Incorrect padding on base64 string.`); + } + if (!BASE64_REGEX.exec(input)) { + throw new TypeError(`Invalid base64 string.`); + } + const buffer = (0, util_buffer_from_1.fromString)(input, "base64"); + return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); +}; +exports.fromBase64 = fromBase64; diff --git a/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/index.js new file mode 100644 index 00000000..02848d02 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/index.js @@ -0,0 +1,27 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +module.exports = __toCommonJS(src_exports); +__reExport(src_exports, require("././fromBase64"), module.exports); +__reExport(src_exports, require("././toBase64"), module.exports); +// Annotate the CommonJS export names for ESM import in node: + +0 && (module.exports = { + fromBase64, + toBase64 +}); + diff --git a/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/toBase64.js b/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/toBase64.js new file mode 100644 index 00000000..0590ce3f --- /dev/null +++ b/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/toBase64.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.toBase64 = void 0; +const util_buffer_from_1 = require("@smithy/util-buffer-from"); +const util_utf8_1 = require("@smithy/util-utf8"); +const toBase64 = (_input) => { + let input; + if (typeof _input === "string") { + input = (0, util_utf8_1.fromUtf8)(_input); + } + else { + input = _input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); + } + return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64"); +}; +exports.toBase64 = toBase64; diff --git a/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js new file mode 100644 index 00000000..b577c9ca --- /dev/null +++ b/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js @@ -0,0 +1,20 @@ +'use strict'; + +var isArrayBuffer = require('@smithy/is-array-buffer'); +var buffer = require('buffer'); + +const fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => { + if (!isArrayBuffer.isArrayBuffer(input)) { + throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); + } + return buffer.Buffer.from(input, offset, length); +}; +const fromString = (input, encoding) => { + if (typeof input !== "string") { + throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); + } + return encoding ? buffer.Buffer.from(input, encoding) : buffer.Buffer.from(input); +}; + +exports.fromArrayBuffer = fromArrayBuffer; +exports.fromString = fromString; diff --git a/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js new file mode 100644 index 00000000..3238bb77 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js @@ -0,0 +1,6 @@ +'use strict'; + +const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) || + Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; + +exports.isArrayBuffer = isArrayBuffer; diff --git a/claude-code-source/node_modules/@smithy/hash-node/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/hash-node/dist-cjs/index.js new file mode 100644 index 00000000..9038b5fe --- /dev/null +++ b/claude-code-source/node_modules/@smithy/hash-node/dist-cjs/index.js @@ -0,0 +1,42 @@ +'use strict'; + +var utilBufferFrom = require('@smithy/util-buffer-from'); +var utilUtf8 = require('@smithy/util-utf8'); +var buffer = require('buffer'); +var crypto = require('crypto'); + +class Hash { + algorithmIdentifier; + secret; + hash; + constructor(algorithmIdentifier, secret) { + this.algorithmIdentifier = algorithmIdentifier; + this.secret = secret; + this.reset(); + } + update(toHash, encoding) { + this.hash.update(utilUtf8.toUint8Array(castSourceData(toHash, encoding))); + } + digest() { + return Promise.resolve(this.hash.digest()); + } + reset() { + this.hash = this.secret + ? crypto.createHmac(this.algorithmIdentifier, castSourceData(this.secret)) + : crypto.createHash(this.algorithmIdentifier); + } +} +function castSourceData(toCast, encoding) { + if (buffer.Buffer.isBuffer(toCast)) { + return toCast; + } + if (typeof toCast === "string") { + return utilBufferFrom.fromString(toCast, encoding); + } + if (ArrayBuffer.isView(toCast)) { + return utilBufferFrom.fromArrayBuffer(toCast.buffer, toCast.byteOffset, toCast.byteLength); + } + return utilBufferFrom.fromArrayBuffer(toCast); +} + +exports.Hash = Hash; diff --git a/claude-code-source/node_modules/@smithy/hash-node/node_modules/@smithy/util-buffer-from/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/hash-node/node_modules/@smithy/util-buffer-from/dist-cjs/index.js new file mode 100644 index 00000000..b577c9ca --- /dev/null +++ b/claude-code-source/node_modules/@smithy/hash-node/node_modules/@smithy/util-buffer-from/dist-cjs/index.js @@ -0,0 +1,20 @@ +'use strict'; + +var isArrayBuffer = require('@smithy/is-array-buffer'); +var buffer = require('buffer'); + +const fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => { + if (!isArrayBuffer.isArrayBuffer(input)) { + throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); + } + return buffer.Buffer.from(input, offset, length); +}; +const fromString = (input, encoding) => { + if (typeof input !== "string") { + throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); + } + return encoding ? buffer.Buffer.from(input, encoding) : buffer.Buffer.from(input); +}; + +exports.fromArrayBuffer = fromArrayBuffer; +exports.fromString = fromString; diff --git a/claude-code-source/node_modules/@smithy/hash-node/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/hash-node/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js new file mode 100644 index 00000000..3238bb77 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/hash-node/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js @@ -0,0 +1,6 @@ +'use strict'; + +const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) || + Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; + +exports.isArrayBuffer = isArrayBuffer; diff --git a/claude-code-source/node_modules/@smithy/is-array-buffer/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/is-array-buffer/dist-cjs/index.js new file mode 100644 index 00000000..5d792e71 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/is-array-buffer/dist-cjs/index.js @@ -0,0 +1,32 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + isArrayBuffer: () => isArrayBuffer +}); +module.exports = __toCommonJS(src_exports); +var isArrayBuffer = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]", "isArrayBuffer"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (module.exports = { + isArrayBuffer +}); + diff --git a/claude-code-source/node_modules/@smithy/middleware-content-length/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/middleware-content-length/dist-cjs/index.js new file mode 100644 index 00000000..e957f196 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/middleware-content-length/dist-cjs/index.js @@ -0,0 +1,46 @@ +'use strict'; + +var protocolHttp = require('@smithy/protocol-http'); + +const CONTENT_LENGTH_HEADER = "content-length"; +function contentLengthMiddleware(bodyLengthChecker) { + return (next) => async (args) => { + const request = args.request; + if (protocolHttp.HttpRequest.isInstance(request)) { + const { body, headers } = request; + if (body && + Object.keys(headers) + .map((str) => str.toLowerCase()) + .indexOf(CONTENT_LENGTH_HEADER) === -1) { + try { + const length = bodyLengthChecker(body); + request.headers = { + ...request.headers, + [CONTENT_LENGTH_HEADER]: String(length), + }; + } + catch (error) { + } + } + } + return next({ + ...args, + request, + }); + }; +} +const contentLengthMiddlewareOptions = { + step: "build", + tags: ["SET_CONTENT_LENGTH", "CONTENT_LENGTH"], + name: "contentLengthMiddleware", + override: true, +}; +const getContentLengthPlugin = (options) => ({ + applyToStack: (clientStack) => { + clientStack.add(contentLengthMiddleware(options.bodyLengthChecker), contentLengthMiddlewareOptions); + }, +}); + +exports.contentLengthMiddleware = contentLengthMiddleware; +exports.contentLengthMiddlewareOptions = contentLengthMiddlewareOptions; +exports.getContentLengthPlugin = getContentLengthPlugin; diff --git a/claude-code-source/node_modules/@smithy/middleware-content-length/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/middleware-content-length/node_modules/@smithy/protocol-http/dist-cjs/index.js new file mode 100644 index 00000000..52303c3b --- /dev/null +++ b/claude-code-source/node_modules/@smithy/middleware-content-length/node_modules/@smithy/protocol-http/dist-cjs/index.js @@ -0,0 +1,169 @@ +'use strict'; + +var types = require('@smithy/types'); + +const getHttpHandlerExtensionConfiguration = (runtimeConfig) => { + return { + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); + }, + }; +}; +const resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler(), + }; +}; + +class Field { + name; + kind; + values; + constructor({ name, kind = types.FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; + } + add(value) { + this.values.push(value); + } + set(values) { + this.values = values; + } + remove(value) { + this.values = this.values.filter((v) => v !== value); + } + toString() { + return this.values.map((v) => (v.includes(",") || v.includes(" ") ? `"${v}"` : v)).join(", "); + } + get() { + return this.values; + } +} + +class Fields { + entries = {}; + encoding; + constructor({ fields = [], encoding = "utf-8" }) { + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + setField(field) { + this.entries[field.name.toLowerCase()] = field; + } + getField(name) { + return this.entries[name.toLowerCase()]; + } + removeField(name) { + delete this.entries[name.toLowerCase()]; + } + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } +} + +class HttpRequest { + method; + protocol; + hostname; + port; + path; + query; + headers; + username; + password; + fragment; + body; + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol + ? options.protocol.slice(-1) !== ":" + ? `${options.protocol}:` + : options.protocol + : "https:"; + this.path = options.path ? (options.path.charAt(0) !== "/" ? `/${options.path}` : options.path) : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + static clone(request) { + const cloned = new HttpRequest({ + ...request, + headers: { ...request.headers }, + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); + } + return cloned; + } + static isInstance(request) { + if (!request) { + return false; + } + const req = request; + return ("method" in req && + "protocol" in req && + "hostname" in req && + "path" in req && + typeof req["query"] === "object" && + typeof req["headers"] === "object"); + } + clone() { + return HttpRequest.clone(this); + } +} +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param, + }; + }, {}); +} + +class HttpResponse { + statusCode; + reason; + headers; + body; + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) + return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + } +} + +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} + +exports.Field = Field; +exports.Fields = Fields; +exports.HttpRequest = HttpRequest; +exports.HttpResponse = HttpResponse; +exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration; +exports.isValidHostname = isValidHostname; +exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig; diff --git a/claude-code-source/node_modules/@smithy/middleware-content-length/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/middleware-content-length/node_modules/@smithy/types/dist-cjs/index.js new file mode 100644 index 00000000..be6d0e1a --- /dev/null +++ b/claude-code-source/node_modules/@smithy/middleware-content-length/node_modules/@smithy/types/dist-cjs/index.js @@ -0,0 +1,91 @@ +'use strict'; + +exports.HttpAuthLocation = void 0; +(function (HttpAuthLocation) { + HttpAuthLocation["HEADER"] = "header"; + HttpAuthLocation["QUERY"] = "query"; +})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); + +exports.HttpApiKeyAuthLocation = void 0; +(function (HttpApiKeyAuthLocation) { + HttpApiKeyAuthLocation["HEADER"] = "header"; + HttpApiKeyAuthLocation["QUERY"] = "query"; +})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); + +exports.EndpointURLScheme = void 0; +(function (EndpointURLScheme) { + EndpointURLScheme["HTTP"] = "http"; + EndpointURLScheme["HTTPS"] = "https"; +})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); + +exports.AlgorithmId = void 0; +(function (AlgorithmId) { + AlgorithmId["MD5"] = "md5"; + AlgorithmId["CRC32"] = "crc32"; + AlgorithmId["CRC32C"] = "crc32c"; + AlgorithmId["SHA1"] = "sha1"; + AlgorithmId["SHA256"] = "sha256"; +})(exports.AlgorithmId || (exports.AlgorithmId = {})); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.SHA256, + checksumConstructor: () => runtimeConfig.sha256, + }); + } + if (runtimeConfig.md5 != undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.MD5, + checksumConstructor: () => runtimeConfig.md5, + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getDefaultClientConfiguration = (runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}; +const resolveDefaultRuntimeConfig = (config) => { + return resolveChecksumRuntimeConfig(config); +}; + +exports.FieldPosition = void 0; +(function (FieldPosition) { + FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; + FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; +})(exports.FieldPosition || (exports.FieldPosition = {})); + +const SMITHY_CONTEXT_KEY = "__smithy_context"; + +exports.IniSectionType = void 0; +(function (IniSectionType) { + IniSectionType["PROFILE"] = "profile"; + IniSectionType["SSO_SESSION"] = "sso-session"; + IniSectionType["SERVICES"] = "services"; +})(exports.IniSectionType || (exports.IniSectionType = {})); + +exports.RequestHandlerProtocol = void 0; +(function (RequestHandlerProtocol) { + RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; +})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); + +exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; diff --git a/claude-code-source/node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointFromConfig.js b/claude-code-source/node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointFromConfig.js new file mode 100644 index 00000000..262b45be --- /dev/null +++ b/claude-code-source/node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointFromConfig.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getEndpointFromConfig = void 0; +const node_config_provider_1 = require("@smithy/node-config-provider"); +const getEndpointUrlConfig_1 = require("./getEndpointUrlConfig"); +const getEndpointFromConfig = async (serviceId) => (0, node_config_provider_1.loadConfig)((0, getEndpointUrlConfig_1.getEndpointUrlConfig)(serviceId ?? ""))(); +exports.getEndpointFromConfig = getEndpointFromConfig; diff --git a/claude-code-source/node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointUrlConfig.js b/claude-code-source/node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointUrlConfig.js new file mode 100644 index 00000000..fe5c010a --- /dev/null +++ b/claude-code-source/node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointUrlConfig.js @@ -0,0 +1,35 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getEndpointUrlConfig = void 0; +const shared_ini_file_loader_1 = require("@smithy/shared-ini-file-loader"); +const ENV_ENDPOINT_URL = "AWS_ENDPOINT_URL"; +const CONFIG_ENDPOINT_URL = "endpoint_url"; +const getEndpointUrlConfig = (serviceId) => ({ + environmentVariableSelector: (env) => { + const serviceSuffixParts = serviceId.split(" ").map((w) => w.toUpperCase()); + const serviceEndpointUrl = env[[ENV_ENDPOINT_URL, ...serviceSuffixParts].join("_")]; + if (serviceEndpointUrl) + return serviceEndpointUrl; + const endpointUrl = env[ENV_ENDPOINT_URL]; + if (endpointUrl) + return endpointUrl; + return undefined; + }, + configFileSelector: (profile, config) => { + if (config && profile.services) { + const servicesSection = config[["services", profile.services].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)]; + if (servicesSection) { + const servicePrefixParts = serviceId.split(" ").map((w) => w.toLowerCase()); + const endpointUrl = servicesSection[[servicePrefixParts.join("_"), CONFIG_ENDPOINT_URL].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)]; + if (endpointUrl) + return endpointUrl; + } + } + const endpointUrl = profile[CONFIG_ENDPOINT_URL]; + if (endpointUrl) + return endpointUrl; + return undefined; + }, + default: undefined, +}); +exports.getEndpointUrlConfig = getEndpointUrlConfig; diff --git a/claude-code-source/node_modules/@smithy/middleware-endpoint/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/middleware-endpoint/dist-cjs/index.js new file mode 100644 index 00000000..82a7e58e --- /dev/null +++ b/claude-code-source/node_modules/@smithy/middleware-endpoint/dist-cjs/index.js @@ -0,0 +1,240 @@ +'use strict'; + +var getEndpointFromConfig = require('./adaptors/getEndpointFromConfig'); +var urlParser = require('@smithy/url-parser'); +var core = require('@smithy/core'); +var utilMiddleware = require('@smithy/util-middleware'); +var middlewareSerde = require('@smithy/middleware-serde'); + +const resolveParamsForS3 = async (endpointParams) => { + const bucket = endpointParams?.Bucket || ""; + if (typeof endpointParams.Bucket === "string") { + endpointParams.Bucket = bucket.replace(/#/g, encodeURIComponent("#")).replace(/\?/g, encodeURIComponent("?")); + } + if (isArnBucketName(bucket)) { + if (endpointParams.ForcePathStyle === true) { + throw new Error("Path-style addressing cannot be used with ARN buckets"); + } + } + else if (!isDnsCompatibleBucketName(bucket) || + (bucket.indexOf(".") !== -1 && !String(endpointParams.Endpoint).startsWith("http:")) || + bucket.toLowerCase() !== bucket || + bucket.length < 3) { + endpointParams.ForcePathStyle = true; + } + if (endpointParams.DisableMultiRegionAccessPoints) { + endpointParams.disableMultiRegionAccessPoints = true; + endpointParams.DisableMRAP = true; + } + return endpointParams; +}; +const DOMAIN_PATTERN = /^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/; +const IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/; +const DOTS_PATTERN = /\.\./; +const isDnsCompatibleBucketName = (bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName); +const isArnBucketName = (bucketName) => { + const [arn, partition, service, , , bucket] = bucketName.split(":"); + const isArn = arn === "arn" && bucketName.split(":").length >= 6; + const isValidArn = Boolean(isArn && partition && service && bucket); + if (isArn && !isValidArn) { + throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`); + } + return isValidArn; +}; + +const createConfigValueProvider = (configKey, canonicalEndpointParamKey, config) => { + const configProvider = async () => { + const configValue = config[configKey] ?? config[canonicalEndpointParamKey]; + if (typeof configValue === "function") { + return configValue(); + } + return configValue; + }; + if (configKey === "credentialScope" || canonicalEndpointParamKey === "CredentialScope") { + return async () => { + const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials; + const configValue = credentials?.credentialScope ?? credentials?.CredentialScope; + return configValue; + }; + } + if (configKey === "accountId" || canonicalEndpointParamKey === "AccountId") { + return async () => { + const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials; + const configValue = credentials?.accountId ?? credentials?.AccountId; + return configValue; + }; + } + if (configKey === "endpoint" || canonicalEndpointParamKey === "endpoint") { + return async () => { + if (config.isCustomEndpoint === false) { + return undefined; + } + const endpoint = await configProvider(); + if (endpoint && typeof endpoint === "object") { + if ("url" in endpoint) { + return endpoint.url.href; + } + if ("hostname" in endpoint) { + const { protocol, hostname, port, path } = endpoint; + return `${protocol}//${hostname}${port ? ":" + port : ""}${path}`; + } + } + return endpoint; + }; + } + return configProvider; +}; + +const toEndpointV1 = (endpoint) => { + if (typeof endpoint === "object") { + if ("url" in endpoint) { + return urlParser.parseUrl(endpoint.url); + } + return endpoint; + } + return urlParser.parseUrl(endpoint); +}; + +const getEndpointFromInstructions = async (commandInput, instructionsSupplier, clientConfig, context) => { + if (!clientConfig.isCustomEndpoint) { + let endpointFromConfig; + if (clientConfig.serviceConfiguredEndpoint) { + endpointFromConfig = await clientConfig.serviceConfiguredEndpoint(); + } + else { + endpointFromConfig = await getEndpointFromConfig.getEndpointFromConfig(clientConfig.serviceId); + } + if (endpointFromConfig) { + clientConfig.endpoint = () => Promise.resolve(toEndpointV1(endpointFromConfig)); + clientConfig.isCustomEndpoint = true; + } + } + const endpointParams = await resolveParams(commandInput, instructionsSupplier, clientConfig); + if (typeof clientConfig.endpointProvider !== "function") { + throw new Error("config.endpointProvider is not set."); + } + const endpoint = clientConfig.endpointProvider(endpointParams, context); + return endpoint; +}; +const resolveParams = async (commandInput, instructionsSupplier, clientConfig) => { + const endpointParams = {}; + const instructions = instructionsSupplier?.getEndpointParameterInstructions?.() || {}; + for (const [name, instruction] of Object.entries(instructions)) { + switch (instruction.type) { + case "staticContextParams": + endpointParams[name] = instruction.value; + break; + case "contextParams": + endpointParams[name] = commandInput[instruction.name]; + break; + case "clientContextParams": + case "builtInParams": + endpointParams[name] = await createConfigValueProvider(instruction.name, name, clientConfig)(); + break; + case "operationContextParams": + endpointParams[name] = instruction.get(commandInput); + break; + default: + throw new Error("Unrecognized endpoint parameter instruction: " + JSON.stringify(instruction)); + } + } + if (Object.keys(instructions).length === 0) { + Object.assign(endpointParams, clientConfig); + } + if (String(clientConfig.serviceId).toLowerCase() === "s3") { + await resolveParamsForS3(endpointParams); + } + return endpointParams; +}; + +const endpointMiddleware = ({ config, instructions, }) => { + return (next, context) => async (args) => { + if (config.isCustomEndpoint) { + core.setFeature(context, "ENDPOINT_OVERRIDE", "N"); + } + const endpoint = await getEndpointFromInstructions(args.input, { + getEndpointParameterInstructions() { + return instructions; + }, + }, { ...config }, context); + context.endpointV2 = endpoint; + context.authSchemes = endpoint.properties?.authSchemes; + const authScheme = context.authSchemes?.[0]; + if (authScheme) { + context["signing_region"] = authScheme.signingRegion; + context["signing_service"] = authScheme.signingName; + const smithyContext = utilMiddleware.getSmithyContext(context); + const httpAuthOption = smithyContext?.selectedHttpAuthScheme?.httpAuthOption; + if (httpAuthOption) { + httpAuthOption.signingProperties = Object.assign(httpAuthOption.signingProperties || {}, { + signing_region: authScheme.signingRegion, + signingRegion: authScheme.signingRegion, + signing_service: authScheme.signingName, + signingName: authScheme.signingName, + signingRegionSet: authScheme.signingRegionSet, + }, authScheme.properties); + } + } + return next({ + ...args, + }); + }; +}; + +const endpointMiddlewareOptions = { + step: "serialize", + tags: ["ENDPOINT_PARAMETERS", "ENDPOINT_V2", "ENDPOINT"], + name: "endpointV2Middleware", + override: true, + relation: "before", + toMiddleware: middlewareSerde.serializerMiddlewareOption.name, +}; +const getEndpointPlugin = (config, instructions) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(endpointMiddleware({ + config, + instructions, + }), endpointMiddlewareOptions); + }, +}); + +const resolveEndpointConfig = (input) => { + const tls = input.tls ?? true; + const { endpoint, useDualstackEndpoint, useFipsEndpoint } = input; + const customEndpointProvider = endpoint != null ? async () => toEndpointV1(await utilMiddleware.normalizeProvider(endpoint)()) : undefined; + const isCustomEndpoint = !!endpoint; + const resolvedConfig = Object.assign(input, { + endpoint: customEndpointProvider, + tls, + isCustomEndpoint, + useDualstackEndpoint: utilMiddleware.normalizeProvider(useDualstackEndpoint ?? false), + useFipsEndpoint: utilMiddleware.normalizeProvider(useFipsEndpoint ?? false), + }); + let configuredEndpointPromise = undefined; + resolvedConfig.serviceConfiguredEndpoint = async () => { + if (input.serviceId && !configuredEndpointPromise) { + configuredEndpointPromise = getEndpointFromConfig.getEndpointFromConfig(input.serviceId); + } + return configuredEndpointPromise; + }; + return resolvedConfig; +}; + +const resolveEndpointRequiredConfig = (input) => { + const { endpoint } = input; + if (endpoint === undefined) { + input.endpoint = async () => { + throw new Error("@smithy/middleware-endpoint: (default endpointRuleSet) endpoint is not set - you must configure an endpoint."); + }; + } + return input; +}; + +exports.endpointMiddleware = endpointMiddleware; +exports.endpointMiddlewareOptions = endpointMiddlewareOptions; +exports.getEndpointFromInstructions = getEndpointFromInstructions; +exports.getEndpointPlugin = getEndpointPlugin; +exports.resolveEndpointConfig = resolveEndpointConfig; +exports.resolveEndpointRequiredConfig = resolveEndpointRequiredConfig; +exports.resolveParams = resolveParams; +exports.toEndpointV1 = toEndpointV1; diff --git a/claude-code-source/node_modules/@smithy/middleware-retry/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/middleware-retry/dist-cjs/index.js new file mode 100644 index 00000000..3da6fd72 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/middleware-retry/dist-cjs/index.js @@ -0,0 +1,358 @@ +'use strict'; + +var utilRetry = require('@smithy/util-retry'); +var protocolHttp = require('@smithy/protocol-http'); +var serviceErrorClassification = require('@smithy/service-error-classification'); +var uuid = require('@smithy/uuid'); +var utilMiddleware = require('@smithy/util-middleware'); +var smithyClient = require('@smithy/smithy-client'); +var isStreamingPayload = require('./isStreamingPayload/isStreamingPayload'); + +const getDefaultRetryQuota = (initialRetryTokens, options) => { + const MAX_CAPACITY = initialRetryTokens; + const noRetryIncrement = utilRetry.NO_RETRY_INCREMENT; + const retryCost = utilRetry.RETRY_COST; + const timeoutRetryCost = utilRetry.TIMEOUT_RETRY_COST; + let availableCapacity = initialRetryTokens; + const getCapacityAmount = (error) => (error.name === "TimeoutError" ? timeoutRetryCost : retryCost); + const hasRetryTokens = (error) => getCapacityAmount(error) <= availableCapacity; + const retrieveRetryTokens = (error) => { + if (!hasRetryTokens(error)) { + throw new Error("No retry token available"); + } + const capacityAmount = getCapacityAmount(error); + availableCapacity -= capacityAmount; + return capacityAmount; + }; + const releaseRetryTokens = (capacityReleaseAmount) => { + availableCapacity += capacityReleaseAmount ?? noRetryIncrement; + availableCapacity = Math.min(availableCapacity, MAX_CAPACITY); + }; + return Object.freeze({ + hasRetryTokens, + retrieveRetryTokens, + releaseRetryTokens, + }); +}; + +const defaultDelayDecider = (delayBase, attempts) => Math.floor(Math.min(utilRetry.MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase)); + +const defaultRetryDecider = (error) => { + if (!error) { + return false; + } + return serviceErrorClassification.isRetryableByTrait(error) || serviceErrorClassification.isClockSkewError(error) || serviceErrorClassification.isThrottlingError(error) || serviceErrorClassification.isTransientError(error); +}; + +const asSdkError = (error) => { + if (error instanceof Error) + return error; + if (error instanceof Object) + return Object.assign(new Error(), error); + if (typeof error === "string") + return new Error(error); + return new Error(`AWS SDK error wrapper for ${error}`); +}; + +class StandardRetryStrategy { + maxAttemptsProvider; + retryDecider; + delayDecider; + retryQuota; + mode = utilRetry.RETRY_MODES.STANDARD; + constructor(maxAttemptsProvider, options) { + this.maxAttemptsProvider = maxAttemptsProvider; + this.retryDecider = options?.retryDecider ?? defaultRetryDecider; + this.delayDecider = options?.delayDecider ?? defaultDelayDecider; + this.retryQuota = options?.retryQuota ?? getDefaultRetryQuota(utilRetry.INITIAL_RETRY_TOKENS); + } + shouldRetry(error, attempts, maxAttempts) { + return attempts < maxAttempts && this.retryDecider(error) && this.retryQuota.hasRetryTokens(error); + } + async getMaxAttempts() { + let maxAttempts; + try { + maxAttempts = await this.maxAttemptsProvider(); + } + catch (error) { + maxAttempts = utilRetry.DEFAULT_MAX_ATTEMPTS; + } + return maxAttempts; + } + async retry(next, args, options) { + let retryTokenAmount; + let attempts = 0; + let totalDelay = 0; + const maxAttempts = await this.getMaxAttempts(); + const { request } = args; + if (protocolHttp.HttpRequest.isInstance(request)) { + request.headers[utilRetry.INVOCATION_ID_HEADER] = uuid.v4(); + } + while (true) { + try { + if (protocolHttp.HttpRequest.isInstance(request)) { + request.headers[utilRetry.REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`; + } + if (options?.beforeRequest) { + await options.beforeRequest(); + } + const { response, output } = await next(args); + if (options?.afterRequest) { + options.afterRequest(response); + } + this.retryQuota.releaseRetryTokens(retryTokenAmount); + output.$metadata.attempts = attempts + 1; + output.$metadata.totalRetryDelay = totalDelay; + return { response, output }; + } + catch (e) { + const err = asSdkError(e); + attempts++; + if (this.shouldRetry(err, attempts, maxAttempts)) { + retryTokenAmount = this.retryQuota.retrieveRetryTokens(err); + const delayFromDecider = this.delayDecider(serviceErrorClassification.isThrottlingError(err) ? utilRetry.THROTTLING_RETRY_DELAY_BASE : utilRetry.DEFAULT_RETRY_DELAY_BASE, attempts); + const delayFromResponse = getDelayFromRetryAfterHeader(err.$response); + const delay = Math.max(delayFromResponse || 0, delayFromDecider); + totalDelay += delay; + await new Promise((resolve) => setTimeout(resolve, delay)); + continue; + } + if (!err.$metadata) { + err.$metadata = {}; + } + err.$metadata.attempts = attempts; + err.$metadata.totalRetryDelay = totalDelay; + throw err; + } + } + } +} +const getDelayFromRetryAfterHeader = (response) => { + if (!protocolHttp.HttpResponse.isInstance(response)) + return; + const retryAfterHeaderName = Object.keys(response.headers).find((key) => key.toLowerCase() === "retry-after"); + if (!retryAfterHeaderName) + return; + const retryAfter = response.headers[retryAfterHeaderName]; + const retryAfterSeconds = Number(retryAfter); + if (!Number.isNaN(retryAfterSeconds)) + return retryAfterSeconds * 1000; + const retryAfterDate = new Date(retryAfter); + return retryAfterDate.getTime() - Date.now(); +}; + +class AdaptiveRetryStrategy extends StandardRetryStrategy { + rateLimiter; + constructor(maxAttemptsProvider, options) { + const { rateLimiter, ...superOptions } = options ?? {}; + super(maxAttemptsProvider, superOptions); + this.rateLimiter = rateLimiter ?? new utilRetry.DefaultRateLimiter(); + this.mode = utilRetry.RETRY_MODES.ADAPTIVE; + } + async retry(next, args) { + return super.retry(next, args, { + beforeRequest: async () => { + return this.rateLimiter.getSendToken(); + }, + afterRequest: (response) => { + this.rateLimiter.updateClientSendingRate(response); + }, + }); + } +} + +const ENV_MAX_ATTEMPTS = "AWS_MAX_ATTEMPTS"; +const CONFIG_MAX_ATTEMPTS = "max_attempts"; +const NODE_MAX_ATTEMPT_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => { + const value = env[ENV_MAX_ATTEMPTS]; + if (!value) + return undefined; + const maxAttempt = parseInt(value); + if (Number.isNaN(maxAttempt)) { + throw new Error(`Environment variable ${ENV_MAX_ATTEMPTS} mast be a number, got "${value}"`); + } + return maxAttempt; + }, + configFileSelector: (profile) => { + const value = profile[CONFIG_MAX_ATTEMPTS]; + if (!value) + return undefined; + const maxAttempt = parseInt(value); + if (Number.isNaN(maxAttempt)) { + throw new Error(`Shared config file entry ${CONFIG_MAX_ATTEMPTS} mast be a number, got "${value}"`); + } + return maxAttempt; + }, + default: utilRetry.DEFAULT_MAX_ATTEMPTS, +}; +const resolveRetryConfig = (input) => { + const { retryStrategy, retryMode: _retryMode, maxAttempts: _maxAttempts } = input; + const maxAttempts = utilMiddleware.normalizeProvider(_maxAttempts ?? utilRetry.DEFAULT_MAX_ATTEMPTS); + return Object.assign(input, { + maxAttempts, + retryStrategy: async () => { + if (retryStrategy) { + return retryStrategy; + } + const retryMode = await utilMiddleware.normalizeProvider(_retryMode)(); + if (retryMode === utilRetry.RETRY_MODES.ADAPTIVE) { + return new utilRetry.AdaptiveRetryStrategy(maxAttempts); + } + return new utilRetry.StandardRetryStrategy(maxAttempts); + }, + }); +}; +const ENV_RETRY_MODE = "AWS_RETRY_MODE"; +const CONFIG_RETRY_MODE = "retry_mode"; +const NODE_RETRY_MODE_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => env[ENV_RETRY_MODE], + configFileSelector: (profile) => profile[CONFIG_RETRY_MODE], + default: utilRetry.DEFAULT_RETRY_MODE, +}; + +const omitRetryHeadersMiddleware = () => (next) => async (args) => { + const { request } = args; + if (protocolHttp.HttpRequest.isInstance(request)) { + delete request.headers[utilRetry.INVOCATION_ID_HEADER]; + delete request.headers[utilRetry.REQUEST_HEADER]; + } + return next(args); +}; +const omitRetryHeadersMiddlewareOptions = { + name: "omitRetryHeadersMiddleware", + tags: ["RETRY", "HEADERS", "OMIT_RETRY_HEADERS"], + relation: "before", + toMiddleware: "awsAuthMiddleware", + override: true, +}; +const getOmitRetryHeadersPlugin = (options) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(omitRetryHeadersMiddleware(), omitRetryHeadersMiddlewareOptions); + }, +}); + +const retryMiddleware = (options) => (next, context) => async (args) => { + let retryStrategy = await options.retryStrategy(); + const maxAttempts = await options.maxAttempts(); + if (isRetryStrategyV2(retryStrategy)) { + retryStrategy = retryStrategy; + let retryToken = await retryStrategy.acquireInitialRetryToken(context["partition_id"]); + let lastError = new Error(); + let attempts = 0; + let totalRetryDelay = 0; + const { request } = args; + const isRequest = protocolHttp.HttpRequest.isInstance(request); + if (isRequest) { + request.headers[utilRetry.INVOCATION_ID_HEADER] = uuid.v4(); + } + while (true) { + try { + if (isRequest) { + request.headers[utilRetry.REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`; + } + const { response, output } = await next(args); + retryStrategy.recordSuccess(retryToken); + output.$metadata.attempts = attempts + 1; + output.$metadata.totalRetryDelay = totalRetryDelay; + return { response, output }; + } + catch (e) { + const retryErrorInfo = getRetryErrorInfo(e); + lastError = asSdkError(e); + if (isRequest && isStreamingPayload.isStreamingPayload(request)) { + (context.logger instanceof smithyClient.NoOpLogger ? console : context.logger)?.warn("An error was encountered in a non-retryable streaming request."); + throw lastError; + } + try { + retryToken = await retryStrategy.refreshRetryTokenForRetry(retryToken, retryErrorInfo); + } + catch (refreshError) { + if (!lastError.$metadata) { + lastError.$metadata = {}; + } + lastError.$metadata.attempts = attempts + 1; + lastError.$metadata.totalRetryDelay = totalRetryDelay; + throw lastError; + } + attempts = retryToken.getRetryCount(); + const delay = retryToken.getRetryDelay(); + totalRetryDelay += delay; + await new Promise((resolve) => setTimeout(resolve, delay)); + } + } + } + else { + retryStrategy = retryStrategy; + if (retryStrategy?.mode) + context.userAgent = [...(context.userAgent || []), ["cfg/retry-mode", retryStrategy.mode]]; + return retryStrategy.retry(next, args); + } +}; +const isRetryStrategyV2 = (retryStrategy) => typeof retryStrategy.acquireInitialRetryToken !== "undefined" && + typeof retryStrategy.refreshRetryTokenForRetry !== "undefined" && + typeof retryStrategy.recordSuccess !== "undefined"; +const getRetryErrorInfo = (error) => { + const errorInfo = { + error, + errorType: getRetryErrorType(error), + }; + const retryAfterHint = getRetryAfterHint(error.$response); + if (retryAfterHint) { + errorInfo.retryAfterHint = retryAfterHint; + } + return errorInfo; +}; +const getRetryErrorType = (error) => { + if (serviceErrorClassification.isThrottlingError(error)) + return "THROTTLING"; + if (serviceErrorClassification.isTransientError(error)) + return "TRANSIENT"; + if (serviceErrorClassification.isServerError(error)) + return "SERVER_ERROR"; + return "CLIENT_ERROR"; +}; +const retryMiddlewareOptions = { + name: "retryMiddleware", + tags: ["RETRY"], + step: "finalizeRequest", + priority: "high", + override: true, +}; +const getRetryPlugin = (options) => ({ + applyToStack: (clientStack) => { + clientStack.add(retryMiddleware(options), retryMiddlewareOptions); + }, +}); +const getRetryAfterHint = (response) => { + if (!protocolHttp.HttpResponse.isInstance(response)) + return; + const retryAfterHeaderName = Object.keys(response.headers).find((key) => key.toLowerCase() === "retry-after"); + if (!retryAfterHeaderName) + return; + const retryAfter = response.headers[retryAfterHeaderName]; + const retryAfterSeconds = Number(retryAfter); + if (!Number.isNaN(retryAfterSeconds)) + return new Date(retryAfterSeconds * 1000); + const retryAfterDate = new Date(retryAfter); + return retryAfterDate; +}; + +exports.AdaptiveRetryStrategy = AdaptiveRetryStrategy; +exports.CONFIG_MAX_ATTEMPTS = CONFIG_MAX_ATTEMPTS; +exports.CONFIG_RETRY_MODE = CONFIG_RETRY_MODE; +exports.ENV_MAX_ATTEMPTS = ENV_MAX_ATTEMPTS; +exports.ENV_RETRY_MODE = ENV_RETRY_MODE; +exports.NODE_MAX_ATTEMPT_CONFIG_OPTIONS = NODE_MAX_ATTEMPT_CONFIG_OPTIONS; +exports.NODE_RETRY_MODE_CONFIG_OPTIONS = NODE_RETRY_MODE_CONFIG_OPTIONS; +exports.StandardRetryStrategy = StandardRetryStrategy; +exports.defaultDelayDecider = defaultDelayDecider; +exports.defaultRetryDecider = defaultRetryDecider; +exports.getOmitRetryHeadersPlugin = getOmitRetryHeadersPlugin; +exports.getRetryAfterHint = getRetryAfterHint; +exports.getRetryPlugin = getRetryPlugin; +exports.omitRetryHeadersMiddleware = omitRetryHeadersMiddleware; +exports.omitRetryHeadersMiddlewareOptions = omitRetryHeadersMiddlewareOptions; +exports.resolveRetryConfig = resolveRetryConfig; +exports.retryMiddleware = retryMiddleware; +exports.retryMiddlewareOptions = retryMiddlewareOptions; diff --git a/claude-code-source/node_modules/@smithy/middleware-retry/dist-cjs/isStreamingPayload/isStreamingPayload.js b/claude-code-source/node_modules/@smithy/middleware-retry/dist-cjs/isStreamingPayload/isStreamingPayload.js new file mode 100644 index 00000000..6d66c791 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/middleware-retry/dist-cjs/isStreamingPayload/isStreamingPayload.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isStreamingPayload = void 0; +const stream_1 = require("stream"); +const isStreamingPayload = (request) => request?.body instanceof stream_1.Readable || + (typeof ReadableStream !== "undefined" && request?.body instanceof ReadableStream); +exports.isStreamingPayload = isStreamingPayload; diff --git a/claude-code-source/node_modules/@smithy/middleware-retry/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/middleware-retry/node_modules/@smithy/protocol-http/dist-cjs/index.js new file mode 100644 index 00000000..52303c3b --- /dev/null +++ b/claude-code-source/node_modules/@smithy/middleware-retry/node_modules/@smithy/protocol-http/dist-cjs/index.js @@ -0,0 +1,169 @@ +'use strict'; + +var types = require('@smithy/types'); + +const getHttpHandlerExtensionConfiguration = (runtimeConfig) => { + return { + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); + }, + }; +}; +const resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler(), + }; +}; + +class Field { + name; + kind; + values; + constructor({ name, kind = types.FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; + } + add(value) { + this.values.push(value); + } + set(values) { + this.values = values; + } + remove(value) { + this.values = this.values.filter((v) => v !== value); + } + toString() { + return this.values.map((v) => (v.includes(",") || v.includes(" ") ? `"${v}"` : v)).join(", "); + } + get() { + return this.values; + } +} + +class Fields { + entries = {}; + encoding; + constructor({ fields = [], encoding = "utf-8" }) { + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + setField(field) { + this.entries[field.name.toLowerCase()] = field; + } + getField(name) { + return this.entries[name.toLowerCase()]; + } + removeField(name) { + delete this.entries[name.toLowerCase()]; + } + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } +} + +class HttpRequest { + method; + protocol; + hostname; + port; + path; + query; + headers; + username; + password; + fragment; + body; + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol + ? options.protocol.slice(-1) !== ":" + ? `${options.protocol}:` + : options.protocol + : "https:"; + this.path = options.path ? (options.path.charAt(0) !== "/" ? `/${options.path}` : options.path) : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + static clone(request) { + const cloned = new HttpRequest({ + ...request, + headers: { ...request.headers }, + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); + } + return cloned; + } + static isInstance(request) { + if (!request) { + return false; + } + const req = request; + return ("method" in req && + "protocol" in req && + "hostname" in req && + "path" in req && + typeof req["query"] === "object" && + typeof req["headers"] === "object"); + } + clone() { + return HttpRequest.clone(this); + } +} +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param, + }; + }, {}); +} + +class HttpResponse { + statusCode; + reason; + headers; + body; + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) + return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + } +} + +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} + +exports.Field = Field; +exports.Fields = Fields; +exports.HttpRequest = HttpRequest; +exports.HttpResponse = HttpResponse; +exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration; +exports.isValidHostname = isValidHostname; +exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig; diff --git a/claude-code-source/node_modules/@smithy/middleware-retry/node_modules/@smithy/smithy-client/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/middleware-retry/node_modules/@smithy/smithy-client/dist-cjs/index.js new file mode 100644 index 00000000..9f589873 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/middleware-retry/node_modules/@smithy/smithy-client/dist-cjs/index.js @@ -0,0 +1,589 @@ +'use strict'; + +var middlewareStack = require('@smithy/middleware-stack'); +var protocols = require('@smithy/core/protocols'); +var types = require('@smithy/types'); +var schema = require('@smithy/core/schema'); +var serde = require('@smithy/core/serde'); + +class Client { + config; + middlewareStack = middlewareStack.constructStack(); + initConfig; + handlers; + constructor(config) { + this.config = config; + } + send(command, optionsOrCb, cb) { + const options = typeof optionsOrCb !== "function" ? optionsOrCb : undefined; + const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb; + const useHandlerCache = options === undefined && this.config.cacheMiddleware === true; + let handler; + if (useHandlerCache) { + if (!this.handlers) { + this.handlers = new WeakMap(); + } + const handlers = this.handlers; + if (handlers.has(command.constructor)) { + handler = handlers.get(command.constructor); + } + else { + handler = command.resolveMiddleware(this.middlewareStack, this.config, options); + handlers.set(command.constructor, handler); + } + } + else { + delete this.handlers; + handler = command.resolveMiddleware(this.middlewareStack, this.config, options); + } + if (callback) { + handler(command) + .then((result) => callback(null, result.output), (err) => callback(err)) + .catch(() => { }); + } + else { + return handler(command).then((result) => result.output); + } + } + destroy() { + this.config?.requestHandler?.destroy?.(); + delete this.handlers; + } +} + +const SENSITIVE_STRING$1 = "***SensitiveInformation***"; +function schemaLogFilter(schema$1, data) { + if (data == null) { + return data; + } + const ns = schema.NormalizedSchema.of(schema$1); + if (ns.getMergedTraits().sensitive) { + return SENSITIVE_STRING$1; + } + if (ns.isListSchema()) { + const isSensitive = !!ns.getValueSchema().getMergedTraits().sensitive; + if (isSensitive) { + return SENSITIVE_STRING$1; + } + } + else if (ns.isMapSchema()) { + const isSensitive = !!ns.getKeySchema().getMergedTraits().sensitive || !!ns.getValueSchema().getMergedTraits().sensitive; + if (isSensitive) { + return SENSITIVE_STRING$1; + } + } + else if (ns.isStructSchema() && typeof data === "object") { + const object = data; + const newObject = {}; + for (const [member, memberNs] of ns.structIterator()) { + if (object[member] != null) { + newObject[member] = schemaLogFilter(memberNs, object[member]); + } + } + return newObject; + } + return data; +} + +class Command { + middlewareStack = middlewareStack.constructStack(); + schema; + static classBuilder() { + return new ClassBuilder(); + } + resolveMiddlewareWithContext(clientStack, configuration, options, { middlewareFn, clientName, commandName, inputFilterSensitiveLog, outputFilterSensitiveLog, smithyContext, additionalContext, CommandCtor, }) { + for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options)) { + this.middlewareStack.use(mw); + } + const stack = clientStack.concat(this.middlewareStack); + const { logger } = configuration; + const handlerExecutionContext = { + logger, + clientName, + commandName, + inputFilterSensitiveLog, + outputFilterSensitiveLog, + [types.SMITHY_CONTEXT_KEY]: { + commandInstance: this, + ...smithyContext, + }, + ...additionalContext, + }; + const { requestHandler } = configuration; + return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); + } +} +class ClassBuilder { + _init = () => { }; + _ep = {}; + _middlewareFn = () => []; + _commandName = ""; + _clientName = ""; + _additionalContext = {}; + _smithyContext = {}; + _inputFilterSensitiveLog = undefined; + _outputFilterSensitiveLog = undefined; + _serializer = null; + _deserializer = null; + _operationSchema; + init(cb) { + this._init = cb; + } + ep(endpointParameterInstructions) { + this._ep = endpointParameterInstructions; + return this; + } + m(middlewareSupplier) { + this._middlewareFn = middlewareSupplier; + return this; + } + s(service, operation, smithyContext = {}) { + this._smithyContext = { + service, + operation, + ...smithyContext, + }; + return this; + } + c(additionalContext = {}) { + this._additionalContext = additionalContext; + return this; + } + n(clientName, commandName) { + this._clientName = clientName; + this._commandName = commandName; + return this; + } + f(inputFilter = (_) => _, outputFilter = (_) => _) { + this._inputFilterSensitiveLog = inputFilter; + this._outputFilterSensitiveLog = outputFilter; + return this; + } + ser(serializer) { + this._serializer = serializer; + return this; + } + de(deserializer) { + this._deserializer = deserializer; + return this; + } + sc(operation) { + this._operationSchema = operation; + this._smithyContext.operationSchema = operation; + return this; + } + build() { + const closure = this; + let CommandRef; + return (CommandRef = class extends Command { + input; + static getEndpointParameterInstructions() { + return closure._ep; + } + constructor(...[input]) { + super(); + this.input = input ?? {}; + closure._init(this); + this.schema = closure._operationSchema; + } + resolveMiddleware(stack, configuration, options) { + const op = closure._operationSchema; + const input = op?.[4] ?? op?.input; + const output = op?.[5] ?? op?.output; + return this.resolveMiddlewareWithContext(stack, configuration, options, { + CommandCtor: CommandRef, + middlewareFn: closure._middlewareFn, + clientName: closure._clientName, + commandName: closure._commandName, + inputFilterSensitiveLog: closure._inputFilterSensitiveLog ?? (op ? schemaLogFilter.bind(null, input) : (_) => _), + outputFilterSensitiveLog: closure._outputFilterSensitiveLog ?? (op ? schemaLogFilter.bind(null, output) : (_) => _), + smithyContext: closure._smithyContext, + additionalContext: closure._additionalContext, + }); + } + serialize = closure._serializer; + deserialize = closure._deserializer; + }); + } +} + +const SENSITIVE_STRING = "***SensitiveInformation***"; + +const createAggregatedClient = (commands, Client) => { + for (const command of Object.keys(commands)) { + const CommandCtor = commands[command]; + const methodImpl = async function (args, optionsOrCb, cb) { + const command = new CommandCtor(args); + if (typeof optionsOrCb === "function") { + this.send(command, optionsOrCb); + } + else if (typeof cb === "function") { + if (typeof optionsOrCb !== "object") + throw new Error(`Expected http options but got ${typeof optionsOrCb}`); + this.send(command, optionsOrCb || {}, cb); + } + else { + return this.send(command, optionsOrCb); + } + }; + const methodName = (command[0].toLowerCase() + command.slice(1)).replace(/Command$/, ""); + Client.prototype[methodName] = methodImpl; + } +}; + +class ServiceException extends Error { + $fault; + $response; + $retryable; + $metadata; + constructor(options) { + super(options.message); + Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype); + this.name = options.name; + this.$fault = options.$fault; + this.$metadata = options.$metadata; + } + static isInstance(value) { + if (!value) + return false; + const candidate = value; + return (ServiceException.prototype.isPrototypeOf(candidate) || + (Boolean(candidate.$fault) && + Boolean(candidate.$metadata) && + (candidate.$fault === "client" || candidate.$fault === "server"))); + } + static [Symbol.hasInstance](instance) { + if (!instance) + return false; + const candidate = instance; + if (this === ServiceException) { + return ServiceException.isInstance(instance); + } + if (ServiceException.isInstance(instance)) { + if (candidate.name && this.name) { + return this.prototype.isPrototypeOf(instance) || candidate.name === this.name; + } + return this.prototype.isPrototypeOf(instance); + } + return false; + } +} +const decorateServiceException = (exception, additions = {}) => { + Object.entries(additions) + .filter(([, v]) => v !== undefined) + .forEach(([k, v]) => { + if (exception[k] == undefined || exception[k] === "") { + exception[k] = v; + } + }); + const message = exception.message || exception.Message || "UnknownError"; + exception.message = message; + delete exception.Message; + return exception; +}; + +const throwDefaultError = ({ output, parsedBody, exceptionCtor, errorCode }) => { + const $metadata = deserializeMetadata(output); + const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : undefined; + const response = new exceptionCtor({ + name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || "UnknownError", + $fault: "client", + $metadata, + }); + throw decorateServiceException(response, parsedBody); +}; +const withBaseException = (ExceptionCtor) => { + return ({ output, parsedBody, errorCode }) => { + throwDefaultError({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode }); + }; +}; +const deserializeMetadata = (output) => ({ + httpStatusCode: output.statusCode, + requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], + extendedRequestId: output.headers["x-amz-id-2"], + cfId: output.headers["x-amz-cf-id"], +}); + +const loadConfigsForDefaultMode = (mode) => { + switch (mode) { + case "standard": + return { + retryMode: "standard", + connectionTimeout: 3100, + }; + case "in-region": + return { + retryMode: "standard", + connectionTimeout: 1100, + }; + case "cross-region": + return { + retryMode: "standard", + connectionTimeout: 3100, + }; + case "mobile": + return { + retryMode: "standard", + connectionTimeout: 30000, + }; + default: + return {}; + } +}; + +let warningEmitted = false; +const emitWarningIfUnsupportedVersion = (version) => { + if (version && !warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 16) { + warningEmitted = true; + } +}; + +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + for (const id in types.AlgorithmId) { + const algorithmId = types.AlgorithmId[id]; + if (runtimeConfig[algorithmId] === undefined) { + continue; + } + checksumAlgorithms.push({ + algorithmId: () => algorithmId, + checksumConstructor: () => runtimeConfig[algorithmId], + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getRetryConfiguration = (runtimeConfig) => { + return { + setRetryStrategy(retryStrategy) { + runtimeConfig.retryStrategy = retryStrategy; + }, + retryStrategy() { + return runtimeConfig.retryStrategy; + }, + }; +}; +const resolveRetryRuntimeConfig = (retryStrategyConfiguration) => { + const runtimeConfig = {}; + runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy(); + return runtimeConfig; +}; + +const getDefaultExtensionConfiguration = (runtimeConfig) => { + return Object.assign(getChecksumConfiguration(runtimeConfig), getRetryConfiguration(runtimeConfig)); +}; +const getDefaultClientConfiguration = getDefaultExtensionConfiguration; +const resolveDefaultRuntimeConfig = (config) => { + return Object.assign(resolveChecksumRuntimeConfig(config), resolveRetryRuntimeConfig(config)); +}; + +const getArrayIfSingleItem = (mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray]; + +const getValueFromTextNode = (obj) => { + const textNodeName = "#text"; + for (const key in obj) { + if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== undefined) { + obj[key] = obj[key][textNodeName]; + } + else if (typeof obj[key] === "object" && obj[key] !== null) { + obj[key] = getValueFromTextNode(obj[key]); + } + } + return obj; +}; + +const isSerializableHeaderValue = (value) => { + return value != null; +}; + +class NoOpLogger { + trace() { } + debug() { } + info() { } + warn() { } + error() { } +} + +function map(arg0, arg1, arg2) { + let target; + let filter; + let instructions; + if (typeof arg1 === "undefined" && typeof arg2 === "undefined") { + target = {}; + instructions = arg0; + } + else { + target = arg0; + if (typeof arg1 === "function") { + filter = arg1; + instructions = arg2; + return mapWithFilter(target, filter, instructions); + } + else { + instructions = arg1; + } + } + for (const key of Object.keys(instructions)) { + if (!Array.isArray(instructions[key])) { + target[key] = instructions[key]; + continue; + } + applyInstruction(target, null, instructions, key); + } + return target; +} +const convertMap = (target) => { + const output = {}; + for (const [k, v] of Object.entries(target || {})) { + output[k] = [, v]; + } + return output; +}; +const take = (source, instructions) => { + const out = {}; + for (const key in instructions) { + applyInstruction(out, source, instructions, key); + } + return out; +}; +const mapWithFilter = (target, filter, instructions) => { + return map(target, Object.entries(instructions).reduce((_instructions, [key, value]) => { + if (Array.isArray(value)) { + _instructions[key] = value; + } + else { + if (typeof value === "function") { + _instructions[key] = [filter, value()]; + } + else { + _instructions[key] = [filter, value]; + } + } + return _instructions; + }, {})); +}; +const applyInstruction = (target, source, instructions, targetKey) => { + if (source !== null) { + let instruction = instructions[targetKey]; + if (typeof instruction === "function") { + instruction = [, instruction]; + } + const [filter = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction; + if ((typeof filter === "function" && filter(source[sourceKey])) || (typeof filter !== "function" && !!filter)) { + target[targetKey] = valueFn(source[sourceKey]); + } + return; + } + let [filter, value] = instructions[targetKey]; + if (typeof value === "function") { + let _value; + const defaultFilterPassed = filter === undefined && (_value = value()) != null; + const customFilterPassed = (typeof filter === "function" && !!filter(void 0)) || (typeof filter !== "function" && !!filter); + if (defaultFilterPassed) { + target[targetKey] = _value; + } + else if (customFilterPassed) { + target[targetKey] = value(); + } + } + else { + const defaultFilterPassed = filter === undefined && value != null; + const customFilterPassed = (typeof filter === "function" && !!filter(value)) || (typeof filter !== "function" && !!filter); + if (defaultFilterPassed || customFilterPassed) { + target[targetKey] = value; + } + } +}; +const nonNullish = (_) => _ != null; +const pass = (_) => _; + +const serializeFloat = (value) => { + if (value !== value) { + return "NaN"; + } + switch (value) { + case Infinity: + return "Infinity"; + case -Infinity: + return "-Infinity"; + default: + return value; + } +}; +const serializeDateTime = (date) => date.toISOString().replace(".000Z", "Z"); + +const _json = (obj) => { + if (obj == null) { + return {}; + } + if (Array.isArray(obj)) { + return obj.filter((_) => _ != null).map(_json); + } + if (typeof obj === "object") { + const target = {}; + for (const key of Object.keys(obj)) { + if (obj[key] == null) { + continue; + } + target[key] = _json(obj[key]); + } + return target; + } + return obj; +}; + +Object.defineProperty(exports, "collectBody", { + enumerable: true, + get: function () { return protocols.collectBody; } +}); +Object.defineProperty(exports, "extendedEncodeURIComponent", { + enumerable: true, + get: function () { return protocols.extendedEncodeURIComponent; } +}); +Object.defineProperty(exports, "resolvedPath", { + enumerable: true, + get: function () { return protocols.resolvedPath; } +}); +exports.Client = Client; +exports.Command = Command; +exports.NoOpLogger = NoOpLogger; +exports.SENSITIVE_STRING = SENSITIVE_STRING; +exports.ServiceException = ServiceException; +exports._json = _json; +exports.convertMap = convertMap; +exports.createAggregatedClient = createAggregatedClient; +exports.decorateServiceException = decorateServiceException; +exports.emitWarningIfUnsupportedVersion = emitWarningIfUnsupportedVersion; +exports.getArrayIfSingleItem = getArrayIfSingleItem; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.getDefaultExtensionConfiguration = getDefaultExtensionConfiguration; +exports.getValueFromTextNode = getValueFromTextNode; +exports.isSerializableHeaderValue = isSerializableHeaderValue; +exports.loadConfigsForDefaultMode = loadConfigsForDefaultMode; +exports.map = map; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; +exports.serializeDateTime = serializeDateTime; +exports.serializeFloat = serializeFloat; +exports.take = take; +exports.throwDefaultError = throwDefaultError; +exports.withBaseException = withBaseException; +Object.keys(serde).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return serde[k]; } + }); +}); diff --git a/claude-code-source/node_modules/@smithy/middleware-retry/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/middleware-retry/node_modules/@smithy/types/dist-cjs/index.js new file mode 100644 index 00000000..be6d0e1a --- /dev/null +++ b/claude-code-source/node_modules/@smithy/middleware-retry/node_modules/@smithy/types/dist-cjs/index.js @@ -0,0 +1,91 @@ +'use strict'; + +exports.HttpAuthLocation = void 0; +(function (HttpAuthLocation) { + HttpAuthLocation["HEADER"] = "header"; + HttpAuthLocation["QUERY"] = "query"; +})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); + +exports.HttpApiKeyAuthLocation = void 0; +(function (HttpApiKeyAuthLocation) { + HttpApiKeyAuthLocation["HEADER"] = "header"; + HttpApiKeyAuthLocation["QUERY"] = "query"; +})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); + +exports.EndpointURLScheme = void 0; +(function (EndpointURLScheme) { + EndpointURLScheme["HTTP"] = "http"; + EndpointURLScheme["HTTPS"] = "https"; +})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); + +exports.AlgorithmId = void 0; +(function (AlgorithmId) { + AlgorithmId["MD5"] = "md5"; + AlgorithmId["CRC32"] = "crc32"; + AlgorithmId["CRC32C"] = "crc32c"; + AlgorithmId["SHA1"] = "sha1"; + AlgorithmId["SHA256"] = "sha256"; +})(exports.AlgorithmId || (exports.AlgorithmId = {})); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.SHA256, + checksumConstructor: () => runtimeConfig.sha256, + }); + } + if (runtimeConfig.md5 != undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.MD5, + checksumConstructor: () => runtimeConfig.md5, + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getDefaultClientConfiguration = (runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}; +const resolveDefaultRuntimeConfig = (config) => { + return resolveChecksumRuntimeConfig(config); +}; + +exports.FieldPosition = void 0; +(function (FieldPosition) { + FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; + FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; +})(exports.FieldPosition || (exports.FieldPosition = {})); + +const SMITHY_CONTEXT_KEY = "__smithy_context"; + +exports.IniSectionType = void 0; +(function (IniSectionType) { + IniSectionType["PROFILE"] = "profile"; + IniSectionType["SSO_SESSION"] = "sso-session"; + IniSectionType["SERVICES"] = "services"; +})(exports.IniSectionType || (exports.IniSectionType = {})); + +exports.RequestHandlerProtocol = void 0; +(function (RequestHandlerProtocol) { + RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; +})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); + +exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; diff --git a/claude-code-source/node_modules/@smithy/middleware-serde/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/middleware-serde/dist-cjs/index.js new file mode 100644 index 00000000..b0712b8d --- /dev/null +++ b/claude-code-source/node_modules/@smithy/middleware-serde/dist-cjs/index.js @@ -0,0 +1,103 @@ +'use strict'; + +var protocolHttp = require('@smithy/protocol-http'); + +const deserializerMiddleware = (options, deserializer) => (next, context) => async (args) => { + const { response } = await next(args); + try { + const parsed = await deserializer(response, options); + return { + response, + output: parsed, + }; + } + catch (error) { + Object.defineProperty(error, "$response", { + value: response, + enumerable: false, + writable: false, + configurable: false, + }); + if (!("$metadata" in error)) { + const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; + try { + error.message += "\n " + hint; + } + catch (e) { + if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { + console.warn(hint); + } + else { + context.logger?.warn?.(hint); + } + } + if (typeof error.$responseBodyText !== "undefined") { + if (error.$response) { + error.$response.body = error.$responseBodyText; + } + } + try { + if (protocolHttp.HttpResponse.isInstance(response)) { + const { headers = {} } = response; + const headerEntries = Object.entries(headers); + error.$metadata = { + httpStatusCode: response.statusCode, + requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), + extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), + cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries), + }; + } + } + catch (e) { + } + } + throw error; + } +}; +const findHeader = (pattern, headers) => { + return (headers.find(([k]) => { + return k.match(pattern); + }) || [void 0, void 0])[1]; +}; + +const serializerMiddleware = (options, serializer) => (next, context) => async (args) => { + const endpointConfig = options; + const endpoint = context.endpointV2?.url && endpointConfig.urlParser + ? async () => endpointConfig.urlParser(context.endpointV2.url) + : endpointConfig.endpoint; + if (!endpoint) { + throw new Error("No valid endpoint provider available."); + } + const request = await serializer(args.input, { ...options, endpoint }); + return next({ + ...args, + request, + }); +}; + +const deserializerMiddlewareOption = { + name: "deserializerMiddleware", + step: "deserialize", + tags: ["DESERIALIZER"], + override: true, +}; +const serializerMiddlewareOption = { + name: "serializerMiddleware", + step: "serialize", + tags: ["SERIALIZER"], + override: true, +}; +function getSerdePlugin(config, serializer, deserializer) { + return { + applyToStack: (commandStack) => { + commandStack.add(deserializerMiddleware(config, deserializer), deserializerMiddlewareOption); + commandStack.add(serializerMiddleware(config, serializer), serializerMiddlewareOption); + }, + }; +} + +exports.deserializerMiddleware = deserializerMiddleware; +exports.deserializerMiddlewareOption = deserializerMiddlewareOption; +exports.getSerdePlugin = getSerdePlugin; +exports.serializerMiddleware = serializerMiddleware; +exports.serializerMiddlewareOption = serializerMiddlewareOption; diff --git a/claude-code-source/node_modules/@smithy/middleware-serde/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/middleware-serde/node_modules/@smithy/protocol-http/dist-cjs/index.js new file mode 100644 index 00000000..52303c3b --- /dev/null +++ b/claude-code-source/node_modules/@smithy/middleware-serde/node_modules/@smithy/protocol-http/dist-cjs/index.js @@ -0,0 +1,169 @@ +'use strict'; + +var types = require('@smithy/types'); + +const getHttpHandlerExtensionConfiguration = (runtimeConfig) => { + return { + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); + }, + }; +}; +const resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler(), + }; +}; + +class Field { + name; + kind; + values; + constructor({ name, kind = types.FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; + } + add(value) { + this.values.push(value); + } + set(values) { + this.values = values; + } + remove(value) { + this.values = this.values.filter((v) => v !== value); + } + toString() { + return this.values.map((v) => (v.includes(",") || v.includes(" ") ? `"${v}"` : v)).join(", "); + } + get() { + return this.values; + } +} + +class Fields { + entries = {}; + encoding; + constructor({ fields = [], encoding = "utf-8" }) { + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + setField(field) { + this.entries[field.name.toLowerCase()] = field; + } + getField(name) { + return this.entries[name.toLowerCase()]; + } + removeField(name) { + delete this.entries[name.toLowerCase()]; + } + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } +} + +class HttpRequest { + method; + protocol; + hostname; + port; + path; + query; + headers; + username; + password; + fragment; + body; + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol + ? options.protocol.slice(-1) !== ":" + ? `${options.protocol}:` + : options.protocol + : "https:"; + this.path = options.path ? (options.path.charAt(0) !== "/" ? `/${options.path}` : options.path) : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + static clone(request) { + const cloned = new HttpRequest({ + ...request, + headers: { ...request.headers }, + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); + } + return cloned; + } + static isInstance(request) { + if (!request) { + return false; + } + const req = request; + return ("method" in req && + "protocol" in req && + "hostname" in req && + "path" in req && + typeof req["query"] === "object" && + typeof req["headers"] === "object"); + } + clone() { + return HttpRequest.clone(this); + } +} +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param, + }; + }, {}); +} + +class HttpResponse { + statusCode; + reason; + headers; + body; + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) + return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + } +} + +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} + +exports.Field = Field; +exports.Fields = Fields; +exports.HttpRequest = HttpRequest; +exports.HttpResponse = HttpResponse; +exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration; +exports.isValidHostname = isValidHostname; +exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig; diff --git a/claude-code-source/node_modules/@smithy/middleware-serde/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/middleware-serde/node_modules/@smithy/types/dist-cjs/index.js new file mode 100644 index 00000000..be6d0e1a --- /dev/null +++ b/claude-code-source/node_modules/@smithy/middleware-serde/node_modules/@smithy/types/dist-cjs/index.js @@ -0,0 +1,91 @@ +'use strict'; + +exports.HttpAuthLocation = void 0; +(function (HttpAuthLocation) { + HttpAuthLocation["HEADER"] = "header"; + HttpAuthLocation["QUERY"] = "query"; +})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); + +exports.HttpApiKeyAuthLocation = void 0; +(function (HttpApiKeyAuthLocation) { + HttpApiKeyAuthLocation["HEADER"] = "header"; + HttpApiKeyAuthLocation["QUERY"] = "query"; +})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); + +exports.EndpointURLScheme = void 0; +(function (EndpointURLScheme) { + EndpointURLScheme["HTTP"] = "http"; + EndpointURLScheme["HTTPS"] = "https"; +})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); + +exports.AlgorithmId = void 0; +(function (AlgorithmId) { + AlgorithmId["MD5"] = "md5"; + AlgorithmId["CRC32"] = "crc32"; + AlgorithmId["CRC32C"] = "crc32c"; + AlgorithmId["SHA1"] = "sha1"; + AlgorithmId["SHA256"] = "sha256"; +})(exports.AlgorithmId || (exports.AlgorithmId = {})); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.SHA256, + checksumConstructor: () => runtimeConfig.sha256, + }); + } + if (runtimeConfig.md5 != undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.MD5, + checksumConstructor: () => runtimeConfig.md5, + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getDefaultClientConfiguration = (runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}; +const resolveDefaultRuntimeConfig = (config) => { + return resolveChecksumRuntimeConfig(config); +}; + +exports.FieldPosition = void 0; +(function (FieldPosition) { + FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; + FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; +})(exports.FieldPosition || (exports.FieldPosition = {})); + +const SMITHY_CONTEXT_KEY = "__smithy_context"; + +exports.IniSectionType = void 0; +(function (IniSectionType) { + IniSectionType["PROFILE"] = "profile"; + IniSectionType["SSO_SESSION"] = "sso-session"; + IniSectionType["SERVICES"] = "services"; +})(exports.IniSectionType || (exports.IniSectionType = {})); + +exports.RequestHandlerProtocol = void 0; +(function (RequestHandlerProtocol) { + RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; +})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); + +exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; diff --git a/claude-code-source/node_modules/@smithy/middleware-stack/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/middleware-stack/dist-cjs/index.js new file mode 100644 index 00000000..b83cef58 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/middleware-stack/dist-cjs/index.js @@ -0,0 +1,285 @@ +'use strict'; + +const getAllAliases = (name, aliases) => { + const _aliases = []; + if (name) { + _aliases.push(name); + } + if (aliases) { + for (const alias of aliases) { + _aliases.push(alias); + } + } + return _aliases; +}; +const getMiddlewareNameWithAliases = (name, aliases) => { + return `${name || "anonymous"}${aliases && aliases.length > 0 ? ` (a.k.a. ${aliases.join(",")})` : ""}`; +}; +const constructStack = () => { + let absoluteEntries = []; + let relativeEntries = []; + let identifyOnResolve = false; + const entriesNameSet = new Set(); + const sort = (entries) => entries.sort((a, b) => stepWeights[b.step] - stepWeights[a.step] || + priorityWeights[b.priority || "normal"] - priorityWeights[a.priority || "normal"]); + const removeByName = (toRemove) => { + let isRemoved = false; + const filterCb = (entry) => { + const aliases = getAllAliases(entry.name, entry.aliases); + if (aliases.includes(toRemove)) { + isRemoved = true; + for (const alias of aliases) { + entriesNameSet.delete(alias); + } + return false; + } + return true; + }; + absoluteEntries = absoluteEntries.filter(filterCb); + relativeEntries = relativeEntries.filter(filterCb); + return isRemoved; + }; + const removeByReference = (toRemove) => { + let isRemoved = false; + const filterCb = (entry) => { + if (entry.middleware === toRemove) { + isRemoved = true; + for (const alias of getAllAliases(entry.name, entry.aliases)) { + entriesNameSet.delete(alias); + } + return false; + } + return true; + }; + absoluteEntries = absoluteEntries.filter(filterCb); + relativeEntries = relativeEntries.filter(filterCb); + return isRemoved; + }; + const cloneTo = (toStack) => { + absoluteEntries.forEach((entry) => { + toStack.add(entry.middleware, { ...entry }); + }); + relativeEntries.forEach((entry) => { + toStack.addRelativeTo(entry.middleware, { ...entry }); + }); + toStack.identifyOnResolve?.(stack.identifyOnResolve()); + return toStack; + }; + const expandRelativeMiddlewareList = (from) => { + const expandedMiddlewareList = []; + from.before.forEach((entry) => { + if (entry.before.length === 0 && entry.after.length === 0) { + expandedMiddlewareList.push(entry); + } + else { + expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry)); + } + }); + expandedMiddlewareList.push(from); + from.after.reverse().forEach((entry) => { + if (entry.before.length === 0 && entry.after.length === 0) { + expandedMiddlewareList.push(entry); + } + else { + expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry)); + } + }); + return expandedMiddlewareList; + }; + const getMiddlewareList = (debug = false) => { + const normalizedAbsoluteEntries = []; + const normalizedRelativeEntries = []; + const normalizedEntriesNameMap = {}; + absoluteEntries.forEach((entry) => { + const normalizedEntry = { + ...entry, + before: [], + after: [], + }; + for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) { + normalizedEntriesNameMap[alias] = normalizedEntry; + } + normalizedAbsoluteEntries.push(normalizedEntry); + }); + relativeEntries.forEach((entry) => { + const normalizedEntry = { + ...entry, + before: [], + after: [], + }; + for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) { + normalizedEntriesNameMap[alias] = normalizedEntry; + } + normalizedRelativeEntries.push(normalizedEntry); + }); + normalizedRelativeEntries.forEach((entry) => { + if (entry.toMiddleware) { + const toMiddleware = normalizedEntriesNameMap[entry.toMiddleware]; + if (toMiddleware === undefined) { + if (debug) { + return; + } + throw new Error(`${entry.toMiddleware} is not found when adding ` + + `${getMiddlewareNameWithAliases(entry.name, entry.aliases)} ` + + `middleware ${entry.relation} ${entry.toMiddleware}`); + } + if (entry.relation === "after") { + toMiddleware.after.push(entry); + } + if (entry.relation === "before") { + toMiddleware.before.push(entry); + } + } + }); + const mainChain = sort(normalizedAbsoluteEntries) + .map(expandRelativeMiddlewareList) + .reduce((wholeList, expandedMiddlewareList) => { + wholeList.push(...expandedMiddlewareList); + return wholeList; + }, []); + return mainChain; + }; + const stack = { + add: (middleware, options = {}) => { + const { name, override, aliases: _aliases } = options; + const entry = { + step: "initialize", + priority: "normal", + middleware, + ...options, + }; + const aliases = getAllAliases(name, _aliases); + if (aliases.length > 0) { + if (aliases.some((alias) => entriesNameSet.has(alias))) { + if (!override) + throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`); + for (const alias of aliases) { + const toOverrideIndex = absoluteEntries.findIndex((entry) => entry.name === alias || entry.aliases?.some((a) => a === alias)); + if (toOverrideIndex === -1) { + continue; + } + const toOverride = absoluteEntries[toOverrideIndex]; + if (toOverride.step !== entry.step || entry.priority !== toOverride.priority) { + throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware with ` + + `${toOverride.priority} priority in ${toOverride.step} step cannot ` + + `be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware with ` + + `${entry.priority} priority in ${entry.step} step.`); + } + absoluteEntries.splice(toOverrideIndex, 1); + } + } + for (const alias of aliases) { + entriesNameSet.add(alias); + } + } + absoluteEntries.push(entry); + }, + addRelativeTo: (middleware, options) => { + const { name, override, aliases: _aliases } = options; + const entry = { + middleware, + ...options, + }; + const aliases = getAllAliases(name, _aliases); + if (aliases.length > 0) { + if (aliases.some((alias) => entriesNameSet.has(alias))) { + if (!override) + throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`); + for (const alias of aliases) { + const toOverrideIndex = relativeEntries.findIndex((entry) => entry.name === alias || entry.aliases?.some((a) => a === alias)); + if (toOverrideIndex === -1) { + continue; + } + const toOverride = relativeEntries[toOverrideIndex]; + if (toOverride.toMiddleware !== entry.toMiddleware || toOverride.relation !== entry.relation) { + throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware ` + + `${toOverride.relation} "${toOverride.toMiddleware}" middleware cannot be overridden ` + + `by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware ${entry.relation} ` + + `"${entry.toMiddleware}" middleware.`); + } + relativeEntries.splice(toOverrideIndex, 1); + } + } + for (const alias of aliases) { + entriesNameSet.add(alias); + } + } + relativeEntries.push(entry); + }, + clone: () => cloneTo(constructStack()), + use: (plugin) => { + plugin.applyToStack(stack); + }, + remove: (toRemove) => { + if (typeof toRemove === "string") + return removeByName(toRemove); + else + return removeByReference(toRemove); + }, + removeByTag: (toRemove) => { + let isRemoved = false; + const filterCb = (entry) => { + const { tags, name, aliases: _aliases } = entry; + if (tags && tags.includes(toRemove)) { + const aliases = getAllAliases(name, _aliases); + for (const alias of aliases) { + entriesNameSet.delete(alias); + } + isRemoved = true; + return false; + } + return true; + }; + absoluteEntries = absoluteEntries.filter(filterCb); + relativeEntries = relativeEntries.filter(filterCb); + return isRemoved; + }, + concat: (from) => { + const cloned = cloneTo(constructStack()); + cloned.use(from); + cloned.identifyOnResolve(identifyOnResolve || cloned.identifyOnResolve() || (from.identifyOnResolve?.() ?? false)); + return cloned; + }, + applyToStack: cloneTo, + identify: () => { + return getMiddlewareList(true).map((mw) => { + const step = mw.step ?? + mw.relation + + " " + + mw.toMiddleware; + return getMiddlewareNameWithAliases(mw.name, mw.aliases) + " - " + step; + }); + }, + identifyOnResolve(toggle) { + if (typeof toggle === "boolean") + identifyOnResolve = toggle; + return identifyOnResolve; + }, + resolve: (handler, context) => { + for (const middleware of getMiddlewareList() + .map((entry) => entry.middleware) + .reverse()) { + handler = middleware(handler, context); + } + if (identifyOnResolve) { + console.log(stack.identify()); + } + return handler; + }, + }; + return stack; +}; +const stepWeights = { + initialize: 5, + serialize: 4, + build: 3, + finalizeRequest: 2, + deserialize: 1, +}; +const priorityWeights = { + high: 3, + normal: 2, + low: 1, +}; + +exports.constructStack = constructStack; diff --git a/claude-code-source/node_modules/@smithy/node-config-provider/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/node-config-provider/dist-cjs/index.js new file mode 100644 index 00000000..b68e5434 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/node-config-provider/dist-cjs/index.js @@ -0,0 +1,62 @@ +'use strict'; + +var propertyProvider = require('@smithy/property-provider'); +var sharedIniFileLoader = require('@smithy/shared-ini-file-loader'); + +function getSelectorName(functionString) { + try { + const constants = new Set(Array.from(functionString.match(/([A-Z_]){3,}/g) ?? [])); + constants.delete("CONFIG"); + constants.delete("CONFIG_PREFIX_SEPARATOR"); + constants.delete("ENV"); + return [...constants].join(", "); + } + catch (e) { + return functionString; + } +} + +const fromEnv = (envVarSelector, options) => async () => { + try { + const config = envVarSelector(process.env, options); + if (config === undefined) { + throw new Error(); + } + return config; + } + catch (e) { + throw new propertyProvider.CredentialsProviderError(e.message || `Not found in ENV: ${getSelectorName(envVarSelector.toString())}`, { logger: options?.logger }); + } +}; + +const fromSharedConfigFiles = (configSelector, { preferredFile = "config", ...init } = {}) => async () => { + const profile = sharedIniFileLoader.getProfileName(init); + const { configFile, credentialsFile } = await sharedIniFileLoader.loadSharedConfigFiles(init); + const profileFromCredentials = credentialsFile[profile] || {}; + const profileFromConfig = configFile[profile] || {}; + const mergedProfile = preferredFile === "config" + ? { ...profileFromCredentials, ...profileFromConfig } + : { ...profileFromConfig, ...profileFromCredentials }; + try { + const cfgFile = preferredFile === "config" ? configFile : credentialsFile; + const configValue = configSelector(mergedProfile, cfgFile); + if (configValue === undefined) { + throw new Error(); + } + return configValue; + } + catch (e) { + throw new propertyProvider.CredentialsProviderError(e.message || `Not found in config files w/ profile [${profile}]: ${getSelectorName(configSelector.toString())}`, { logger: init.logger }); + } +}; + +const isFunction = (func) => typeof func === "function"; +const fromStatic = (defaultValue) => isFunction(defaultValue) ? async () => await defaultValue() : propertyProvider.fromStatic(defaultValue); + +const loadConfig = ({ environmentVariableSelector, configFileSelector, default: defaultValue }, configuration = {}) => { + const { signingName, logger } = configuration; + const envOptions = { signingName, logger }; + return propertyProvider.memoize(propertyProvider.chain(fromEnv(environmentVariableSelector, envOptions), fromSharedConfigFiles(configFileSelector, configuration), fromStatic(defaultValue))); +}; + +exports.loadConfig = loadConfig; diff --git a/claude-code-source/node_modules/@smithy/node-http-handler/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/node-http-handler/dist-cjs/index.js new file mode 100644 index 00000000..bdc797c6 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/node-http-handler/dist-cjs/index.js @@ -0,0 +1,732 @@ +'use strict'; + +var protocolHttp = require('@smithy/protocol-http'); +var querystringBuilder = require('@smithy/querystring-builder'); +var http = require('http'); +var https = require('https'); +var stream = require('stream'); +var http2 = require('http2'); + +const NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"]; + +const getTransformedHeaders = (headers) => { + const transformedHeaders = {}; + for (const name of Object.keys(headers)) { + const headerValues = headers[name]; + transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues; + } + return transformedHeaders; +}; + +const timing = { + setTimeout: (cb, ms) => setTimeout(cb, ms), + clearTimeout: (timeoutId) => clearTimeout(timeoutId), +}; + +const DEFER_EVENT_LISTENER_TIME$2 = 1000; +const setConnectionTimeout = (request, reject, timeoutInMs = 0) => { + if (!timeoutInMs) { + return -1; + } + const registerTimeout = (offset) => { + const timeoutId = timing.setTimeout(() => { + request.destroy(); + reject(Object.assign(new Error(`@smithy/node-http-handler - the request socket did not establish a connection with the server within the configured timeout of ${timeoutInMs} ms.`), { + name: "TimeoutError", + })); + }, timeoutInMs - offset); + const doWithSocket = (socket) => { + if (socket?.connecting) { + socket.on("connect", () => { + timing.clearTimeout(timeoutId); + }); + } + else { + timing.clearTimeout(timeoutId); + } + }; + if (request.socket) { + doWithSocket(request.socket); + } + else { + request.on("socket", doWithSocket); + } + }; + if (timeoutInMs < 2000) { + registerTimeout(0); + return 0; + } + return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME$2), DEFER_EVENT_LISTENER_TIME$2); +}; + +const setRequestTimeout = (req, reject, timeoutInMs = 0, throwOnRequestTimeout, logger) => { + if (timeoutInMs) { + return timing.setTimeout(() => { + let msg = `@smithy/node-http-handler - [${throwOnRequestTimeout ? "ERROR" : "WARN"}] a request has exceeded the configured ${timeoutInMs} ms requestTimeout.`; + if (throwOnRequestTimeout) { + const error = Object.assign(new Error(msg), { + name: "TimeoutError", + code: "ETIMEDOUT", + }); + req.destroy(error); + reject(error); + } + else { + msg += ` Init client requestHandler with throwOnRequestTimeout=true to turn this into an error.`; + logger?.warn?.(msg); + } + }, timeoutInMs); + } + return -1; +}; + +const DEFER_EVENT_LISTENER_TIME$1 = 3000; +const setSocketKeepAlive = (request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME$1) => { + if (keepAlive !== true) { + return -1; + } + const registerListener = () => { + if (request.socket) { + request.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); + } + else { + request.on("socket", (socket) => { + socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); + }); + } + }; + if (deferTimeMs === 0) { + registerListener(); + return 0; + } + return timing.setTimeout(registerListener, deferTimeMs); +}; + +const DEFER_EVENT_LISTENER_TIME = 3000; +const setSocketTimeout = (request, reject, timeoutInMs = 0) => { + const registerTimeout = (offset) => { + const timeout = timeoutInMs - offset; + const onTimeout = () => { + request.destroy(); + reject(Object.assign(new Error(`@smithy/node-http-handler - the request socket timed out after ${timeoutInMs} ms of inactivity (configured by client requestHandler).`), { name: "TimeoutError" })); + }; + if (request.socket) { + request.socket.setTimeout(timeout, onTimeout); + request.on("close", () => request.socket?.removeListener("timeout", onTimeout)); + } + else { + request.setTimeout(timeout, onTimeout); + } + }; + if (0 < timeoutInMs && timeoutInMs < 6000) { + registerTimeout(0); + return 0; + } + return timing.setTimeout(registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME); +}; + +const MIN_WAIT_TIME = 6_000; +async function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME, externalAgent = false) { + const headers = request.headers ?? {}; + const expect = headers.Expect || headers.expect; + let timeoutId = -1; + let sendBody = true; + if (!externalAgent && expect === "100-continue") { + sendBody = await Promise.race([ + new Promise((resolve) => { + timeoutId = Number(timing.setTimeout(() => resolve(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs))); + }), + new Promise((resolve) => { + httpRequest.on("continue", () => { + timing.clearTimeout(timeoutId); + resolve(true); + }); + httpRequest.on("response", () => { + timing.clearTimeout(timeoutId); + resolve(false); + }); + httpRequest.on("error", () => { + timing.clearTimeout(timeoutId); + resolve(false); + }); + }), + ]); + } + if (sendBody) { + writeBody(httpRequest, request.body); + } +} +function writeBody(httpRequest, body) { + if (body instanceof stream.Readable) { + body.pipe(httpRequest); + return; + } + if (body) { + if (Buffer.isBuffer(body) || typeof body === "string") { + httpRequest.end(body); + return; + } + const uint8 = body; + if (typeof uint8 === "object" && + uint8.buffer && + typeof uint8.byteOffset === "number" && + typeof uint8.byteLength === "number") { + httpRequest.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength)); + return; + } + httpRequest.end(Buffer.from(body)); + return; + } + httpRequest.end(); +} + +const DEFAULT_REQUEST_TIMEOUT = 0; +class NodeHttpHandler { + config; + configProvider; + socketWarningTimestamp = 0; + externalAgent = false; + metadata = { handlerProtocol: "http/1.1" }; + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; + } + return new NodeHttpHandler(instanceOrOptions); + } + static checkSocketUsage(agent, socketWarningTimestamp, logger = console) { + const { sockets, requests, maxSockets } = agent; + if (typeof maxSockets !== "number" || maxSockets === Infinity) { + return socketWarningTimestamp; + } + const interval = 15_000; + if (Date.now() - interval < socketWarningTimestamp) { + return socketWarningTimestamp; + } + if (sockets && requests) { + for (const origin in sockets) { + const socketsInUse = sockets[origin]?.length ?? 0; + const requestsEnqueued = requests[origin]?.length ?? 0; + if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) { + logger?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued. +See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html +or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.`); + return Date.now(); + } + } + } + return socketWarningTimestamp; + } + constructor(options) { + this.configProvider = new Promise((resolve, reject) => { + if (typeof options === "function") { + options() + .then((_options) => { + resolve(this.resolveDefaultConfig(_options)); + }) + .catch(reject); + } + else { + resolve(this.resolveDefaultConfig(options)); + } + }); + } + resolveDefaultConfig(options) { + const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent, throwOnRequestTimeout, } = options || {}; + const keepAlive = true; + const maxSockets = 50; + return { + connectionTimeout, + requestTimeout, + socketTimeout, + socketAcquisitionWarningTimeout, + throwOnRequestTimeout, + httpAgent: (() => { + if (httpAgent instanceof http.Agent || typeof httpAgent?.destroy === "function") { + this.externalAgent = true; + return httpAgent; + } + return new http.Agent({ keepAlive, maxSockets, ...httpAgent }); + })(), + httpsAgent: (() => { + if (httpsAgent instanceof https.Agent || typeof httpsAgent?.destroy === "function") { + this.externalAgent = true; + return httpsAgent; + } + return new https.Agent({ keepAlive, maxSockets, ...httpsAgent }); + })(), + logger: console, + }; + } + destroy() { + this.config?.httpAgent?.destroy(); + this.config?.httpsAgent?.destroy(); + } + async handle(request, { abortSignal, requestTimeout } = {}) { + if (!this.config) { + this.config = await this.configProvider; + } + return new Promise((_resolve, _reject) => { + const config = this.config; + let writeRequestBodyPromise = undefined; + const timeouts = []; + const resolve = async (arg) => { + await writeRequestBodyPromise; + timeouts.forEach(timing.clearTimeout); + _resolve(arg); + }; + const reject = async (arg) => { + await writeRequestBodyPromise; + timeouts.forEach(timing.clearTimeout); + _reject(arg); + }; + if (abortSignal?.aborted) { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + return; + } + const isSSL = request.protocol === "https:"; + const headers = request.headers ?? {}; + const expectContinue = (headers.Expect ?? headers.expect) === "100-continue"; + let agent = isSSL ? config.httpsAgent : config.httpAgent; + if (expectContinue && !this.externalAgent) { + agent = new (isSSL ? https.Agent : http.Agent)({ + keepAlive: false, + maxSockets: Infinity, + }); + } + timeouts.push(timing.setTimeout(() => { + this.socketWarningTimestamp = NodeHttpHandler.checkSocketUsage(agent, this.socketWarningTimestamp, config.logger); + }, config.socketAcquisitionWarningTimeout ?? (config.requestTimeout ?? 2000) + (config.connectionTimeout ?? 1000))); + const queryString = querystringBuilder.buildQueryString(request.query || {}); + let auth = undefined; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}`; + } + let path = request.path; + if (queryString) { + path += `?${queryString}`; + } + if (request.fragment) { + path += `#${request.fragment}`; + } + let hostname = request.hostname ?? ""; + if (hostname[0] === "[" && hostname.endsWith("]")) { + hostname = request.hostname.slice(1, -1); + } + else { + hostname = request.hostname; + } + const nodeHttpsOptions = { + headers: request.headers, + host: hostname, + method: request.method, + path, + port: request.port, + agent, + auth, + }; + const requestFunc = isSSL ? https.request : http.request; + const req = requestFunc(nodeHttpsOptions, (res) => { + const httpResponse = new protocolHttp.HttpResponse({ + statusCode: res.statusCode || -1, + reason: res.statusMessage, + headers: getTransformedHeaders(res.headers), + body: res, + }); + resolve({ response: httpResponse }); + }); + req.on("error", (err) => { + if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) { + reject(Object.assign(err, { name: "TimeoutError" })); + } + else { + reject(err); + } + }); + if (abortSignal) { + const onAbort = () => { + req.destroy(); + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + }; + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + req.once("close", () => signal.removeEventListener("abort", onAbort)); + } + else { + abortSignal.onabort = onAbort; + } + } + const effectiveRequestTimeout = requestTimeout ?? config.requestTimeout; + timeouts.push(setConnectionTimeout(req, reject, config.connectionTimeout)); + timeouts.push(setRequestTimeout(req, reject, effectiveRequestTimeout, config.throwOnRequestTimeout, config.logger ?? console)); + timeouts.push(setSocketTimeout(req, reject, config.socketTimeout)); + const httpAgent = nodeHttpsOptions.agent; + if (typeof httpAgent === "object" && "keepAlive" in httpAgent) { + timeouts.push(setSocketKeepAlive(req, { + keepAlive: httpAgent.keepAlive, + keepAliveMsecs: httpAgent.keepAliveMsecs, + })); + } + writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout, this.externalAgent).catch((e) => { + timeouts.forEach(timing.clearTimeout); + return _reject(e); + }); + }); + } + updateHttpClientConfig(key, value) { + this.config = undefined; + this.configProvider = this.configProvider.then((config) => { + return { + ...config, + [key]: value, + }; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; + } +} + +class NodeHttp2ConnectionPool { + sessions = []; + constructor(sessions) { + this.sessions = sessions ?? []; + } + poll() { + if (this.sessions.length > 0) { + return this.sessions.shift(); + } + } + offerLast(session) { + this.sessions.push(session); + } + contains(session) { + return this.sessions.includes(session); + } + remove(session) { + this.sessions = this.sessions.filter((s) => s !== session); + } + [Symbol.iterator]() { + return this.sessions[Symbol.iterator](); + } + destroy(connection) { + for (const session of this.sessions) { + if (session === connection) { + if (!session.destroyed) { + session.destroy(); + } + } + } + } +} + +class NodeHttp2ConnectionManager { + constructor(config) { + this.config = config; + if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) { + throw new RangeError("maxConcurrency must be greater than zero."); + } + } + config; + sessionCache = new Map(); + lease(requestContext, connectionConfiguration) { + const url = this.getUrlString(requestContext); + const existingPool = this.sessionCache.get(url); + if (existingPool) { + const existingSession = existingPool.poll(); + if (existingSession && !this.config.disableConcurrency) { + return existingSession; + } + } + const session = http2.connect(url); + if (this.config.maxConcurrency) { + session.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err) => { + if (err) { + throw new Error("Fail to set maxConcurrentStreams to " + + this.config.maxConcurrency + + "when creating new session for " + + requestContext.destination.toString()); + } + }); + } + session.unref(); + const destroySessionCb = () => { + session.destroy(); + this.deleteSession(url, session); + }; + session.on("goaway", destroySessionCb); + session.on("error", destroySessionCb); + session.on("frameError", destroySessionCb); + session.on("close", () => this.deleteSession(url, session)); + if (connectionConfiguration.requestTimeout) { + session.setTimeout(connectionConfiguration.requestTimeout, destroySessionCb); + } + const connectionPool = this.sessionCache.get(url) || new NodeHttp2ConnectionPool(); + connectionPool.offerLast(session); + this.sessionCache.set(url, connectionPool); + return session; + } + deleteSession(authority, session) { + const existingConnectionPool = this.sessionCache.get(authority); + if (!existingConnectionPool) { + return; + } + if (!existingConnectionPool.contains(session)) { + return; + } + existingConnectionPool.remove(session); + this.sessionCache.set(authority, existingConnectionPool); + } + release(requestContext, session) { + const cacheKey = this.getUrlString(requestContext); + this.sessionCache.get(cacheKey)?.offerLast(session); + } + destroy() { + for (const [key, connectionPool] of this.sessionCache) { + for (const session of connectionPool) { + if (!session.destroyed) { + session.destroy(); + } + connectionPool.remove(session); + } + this.sessionCache.delete(key); + } + } + setMaxConcurrentStreams(maxConcurrentStreams) { + if (maxConcurrentStreams && maxConcurrentStreams <= 0) { + throw new RangeError("maxConcurrentStreams must be greater than zero."); + } + this.config.maxConcurrency = maxConcurrentStreams; + } + setDisableConcurrentStreams(disableConcurrentStreams) { + this.config.disableConcurrency = disableConcurrentStreams; + } + getUrlString(request) { + return request.destination.toString(); + } +} + +class NodeHttp2Handler { + config; + configProvider; + metadata = { handlerProtocol: "h2" }; + connectionManager = new NodeHttp2ConnectionManager({}); + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; + } + return new NodeHttp2Handler(instanceOrOptions); + } + constructor(options) { + this.configProvider = new Promise((resolve, reject) => { + if (typeof options === "function") { + options() + .then((opts) => { + resolve(opts || {}); + }) + .catch(reject); + } + else { + resolve(options || {}); + } + }); + } + destroy() { + this.connectionManager.destroy(); + } + async handle(request, { abortSignal, requestTimeout } = {}) { + if (!this.config) { + this.config = await this.configProvider; + this.connectionManager.setDisableConcurrentStreams(this.config.disableConcurrentStreams || false); + if (this.config.maxConcurrentStreams) { + this.connectionManager.setMaxConcurrentStreams(this.config.maxConcurrentStreams); + } + } + const { requestTimeout: configRequestTimeout, disableConcurrentStreams } = this.config; + const effectiveRequestTimeout = requestTimeout ?? configRequestTimeout; + return new Promise((_resolve, _reject) => { + let fulfilled = false; + let writeRequestBodyPromise = undefined; + const resolve = async (arg) => { + await writeRequestBodyPromise; + _resolve(arg); + }; + const reject = async (arg) => { + await writeRequestBodyPromise; + _reject(arg); + }; + if (abortSignal?.aborted) { + fulfilled = true; + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + return; + } + const { hostname, method, port, protocol, query } = request; + let auth = ""; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}@`; + } + const authority = `${protocol}//${auth}${hostname}${port ? `:${port}` : ""}`; + const requestContext = { destination: new URL(authority) }; + const session = this.connectionManager.lease(requestContext, { + requestTimeout: this.config?.sessionTimeout, + disableConcurrentStreams: disableConcurrentStreams || false, + }); + const rejectWithDestroy = (err) => { + if (disableConcurrentStreams) { + this.destroySession(session); + } + fulfilled = true; + reject(err); + }; + const queryString = querystringBuilder.buildQueryString(query || {}); + let path = request.path; + if (queryString) { + path += `?${queryString}`; + } + if (request.fragment) { + path += `#${request.fragment}`; + } + const req = session.request({ + ...request.headers, + [http2.constants.HTTP2_HEADER_PATH]: path, + [http2.constants.HTTP2_HEADER_METHOD]: method, + }); + session.ref(); + req.on("response", (headers) => { + const httpResponse = new protocolHttp.HttpResponse({ + statusCode: headers[":status"] || -1, + headers: getTransformedHeaders(headers), + body: req, + }); + fulfilled = true; + resolve({ response: httpResponse }); + if (disableConcurrentStreams) { + session.close(); + this.connectionManager.deleteSession(authority, session); + } + }); + if (effectiveRequestTimeout) { + req.setTimeout(effectiveRequestTimeout, () => { + req.close(); + const timeoutError = new Error(`Stream timed out because of no activity for ${effectiveRequestTimeout} ms`); + timeoutError.name = "TimeoutError"; + rejectWithDestroy(timeoutError); + }); + } + if (abortSignal) { + const onAbort = () => { + req.close(); + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + rejectWithDestroy(abortError); + }; + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + req.once("close", () => signal.removeEventListener("abort", onAbort)); + } + else { + abortSignal.onabort = onAbort; + } + } + req.on("frameError", (type, code, id) => { + rejectWithDestroy(new Error(`Frame type id ${type} in stream id ${id} has failed with code ${code}.`)); + }); + req.on("error", rejectWithDestroy); + req.on("aborted", () => { + rejectWithDestroy(new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${req.rstCode}.`)); + }); + req.on("close", () => { + session.unref(); + if (disableConcurrentStreams) { + session.destroy(); + } + if (!fulfilled) { + rejectWithDestroy(new Error("Unexpected error: http2 request did not get a response")); + } + }); + writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout); + }); + } + updateHttpClientConfig(key, value) { + this.config = undefined; + this.configProvider = this.configProvider.then((config) => { + return { + ...config, + [key]: value, + }; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; + } + destroySession(session) { + if (!session.destroyed) { + session.destroy(); + } + } +} + +class Collector extends stream.Writable { + bufferedBytes = []; + _write(chunk, encoding, callback) { + this.bufferedBytes.push(chunk); + callback(); + } +} + +const streamCollector = (stream) => { + if (isReadableStreamInstance(stream)) { + return collectReadableStream(stream); + } + return new Promise((resolve, reject) => { + const collector = new Collector(); + stream.pipe(collector); + stream.on("error", (err) => { + collector.end(); + reject(err); + }); + collector.on("error", reject); + collector.on("finish", function () { + const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes)); + resolve(bytes); + }); + }); +}; +const isReadableStreamInstance = (stream) => typeof ReadableStream === "function" && stream instanceof ReadableStream; +async function collectReadableStream(stream) { + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + let length = 0; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + length += value.length; + } + isDone = done; + } + const collected = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + collected.set(chunk, offset); + offset += chunk.length; + } + return collected; +} + +exports.DEFAULT_REQUEST_TIMEOUT = DEFAULT_REQUEST_TIMEOUT; +exports.NodeHttp2Handler = NodeHttp2Handler; +exports.NodeHttpHandler = NodeHttpHandler; +exports.streamCollector = streamCollector; diff --git a/claude-code-source/node_modules/@smithy/node-http-handler/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/node-http-handler/node_modules/@smithy/protocol-http/dist-cjs/index.js new file mode 100644 index 00000000..52303c3b --- /dev/null +++ b/claude-code-source/node_modules/@smithy/node-http-handler/node_modules/@smithy/protocol-http/dist-cjs/index.js @@ -0,0 +1,169 @@ +'use strict'; + +var types = require('@smithy/types'); + +const getHttpHandlerExtensionConfiguration = (runtimeConfig) => { + return { + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); + }, + }; +}; +const resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler(), + }; +}; + +class Field { + name; + kind; + values; + constructor({ name, kind = types.FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; + } + add(value) { + this.values.push(value); + } + set(values) { + this.values = values; + } + remove(value) { + this.values = this.values.filter((v) => v !== value); + } + toString() { + return this.values.map((v) => (v.includes(",") || v.includes(" ") ? `"${v}"` : v)).join(", "); + } + get() { + return this.values; + } +} + +class Fields { + entries = {}; + encoding; + constructor({ fields = [], encoding = "utf-8" }) { + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + setField(field) { + this.entries[field.name.toLowerCase()] = field; + } + getField(name) { + return this.entries[name.toLowerCase()]; + } + removeField(name) { + delete this.entries[name.toLowerCase()]; + } + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } +} + +class HttpRequest { + method; + protocol; + hostname; + port; + path; + query; + headers; + username; + password; + fragment; + body; + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol + ? options.protocol.slice(-1) !== ":" + ? `${options.protocol}:` + : options.protocol + : "https:"; + this.path = options.path ? (options.path.charAt(0) !== "/" ? `/${options.path}` : options.path) : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + static clone(request) { + const cloned = new HttpRequest({ + ...request, + headers: { ...request.headers }, + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); + } + return cloned; + } + static isInstance(request) { + if (!request) { + return false; + } + const req = request; + return ("method" in req && + "protocol" in req && + "hostname" in req && + "path" in req && + typeof req["query"] === "object" && + typeof req["headers"] === "object"); + } + clone() { + return HttpRequest.clone(this); + } +} +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param, + }; + }, {}); +} + +class HttpResponse { + statusCode; + reason; + headers; + body; + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) + return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + } +} + +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} + +exports.Field = Field; +exports.Fields = Fields; +exports.HttpRequest = HttpRequest; +exports.HttpResponse = HttpResponse; +exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration; +exports.isValidHostname = isValidHostname; +exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig; diff --git a/claude-code-source/node_modules/@smithy/node-http-handler/node_modules/@smithy/querystring-builder/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/node-http-handler/node_modules/@smithy/querystring-builder/dist-cjs/index.js new file mode 100644 index 00000000..f245489f --- /dev/null +++ b/claude-code-source/node_modules/@smithy/node-http-handler/node_modules/@smithy/querystring-builder/dist-cjs/index.js @@ -0,0 +1,26 @@ +'use strict'; + +var utilUriEscape = require('@smithy/util-uri-escape'); + +function buildQueryString(query) { + const parts = []; + for (let key of Object.keys(query).sort()) { + const value = query[key]; + key = utilUriEscape.escapeUri(key); + if (Array.isArray(value)) { + for (let i = 0, iLen = value.length; i < iLen; i++) { + parts.push(`${key}=${utilUriEscape.escapeUri(value[i])}`); + } + } + else { + let qsEntry = key; + if (value || typeof value === "string") { + qsEntry += `=${utilUriEscape.escapeUri(value)}`; + } + parts.push(qsEntry); + } + } + return parts.join("&"); +} + +exports.buildQueryString = buildQueryString; diff --git a/claude-code-source/node_modules/@smithy/node-http-handler/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/node-http-handler/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js new file mode 100644 index 00000000..11f942c3 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/node-http-handler/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js @@ -0,0 +1,9 @@ +'use strict'; + +const escapeUri = (uri) => encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode); +const hexEncode = (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`; + +const escapeUriPath = (uri) => uri.split("/").map(escapeUri).join("/"); + +exports.escapeUri = escapeUri; +exports.escapeUriPath = escapeUriPath; diff --git a/claude-code-source/node_modules/@smithy/node-http-handler/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/node-http-handler/node_modules/@smithy/types/dist-cjs/index.js new file mode 100644 index 00000000..be6d0e1a --- /dev/null +++ b/claude-code-source/node_modules/@smithy/node-http-handler/node_modules/@smithy/types/dist-cjs/index.js @@ -0,0 +1,91 @@ +'use strict'; + +exports.HttpAuthLocation = void 0; +(function (HttpAuthLocation) { + HttpAuthLocation["HEADER"] = "header"; + HttpAuthLocation["QUERY"] = "query"; +})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); + +exports.HttpApiKeyAuthLocation = void 0; +(function (HttpApiKeyAuthLocation) { + HttpApiKeyAuthLocation["HEADER"] = "header"; + HttpApiKeyAuthLocation["QUERY"] = "query"; +})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); + +exports.EndpointURLScheme = void 0; +(function (EndpointURLScheme) { + EndpointURLScheme["HTTP"] = "http"; + EndpointURLScheme["HTTPS"] = "https"; +})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); + +exports.AlgorithmId = void 0; +(function (AlgorithmId) { + AlgorithmId["MD5"] = "md5"; + AlgorithmId["CRC32"] = "crc32"; + AlgorithmId["CRC32C"] = "crc32c"; + AlgorithmId["SHA1"] = "sha1"; + AlgorithmId["SHA256"] = "sha256"; +})(exports.AlgorithmId || (exports.AlgorithmId = {})); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.SHA256, + checksumConstructor: () => runtimeConfig.sha256, + }); + } + if (runtimeConfig.md5 != undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.MD5, + checksumConstructor: () => runtimeConfig.md5, + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getDefaultClientConfiguration = (runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}; +const resolveDefaultRuntimeConfig = (config) => { + return resolveChecksumRuntimeConfig(config); +}; + +exports.FieldPosition = void 0; +(function (FieldPosition) { + FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; + FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; +})(exports.FieldPosition || (exports.FieldPosition = {})); + +const SMITHY_CONTEXT_KEY = "__smithy_context"; + +exports.IniSectionType = void 0; +(function (IniSectionType) { + IniSectionType["PROFILE"] = "profile"; + IniSectionType["SSO_SESSION"] = "sso-session"; + IniSectionType["SERVICES"] = "services"; +})(exports.IniSectionType || (exports.IniSectionType = {})); + +exports.RequestHandlerProtocol = void 0; +(function (RequestHandlerProtocol) { + RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; +})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); + +exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; diff --git a/claude-code-source/node_modules/@smithy/property-provider/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/property-provider/dist-cjs/index.js new file mode 100644 index 00000000..a419560c --- /dev/null +++ b/claude-code-source/node_modules/@smithy/property-provider/dist-cjs/index.js @@ -0,0 +1,117 @@ +'use strict'; + +class ProviderError extends Error { + name = "ProviderError"; + tryNextLink; + constructor(message, options = true) { + let logger; + let tryNextLink = true; + if (typeof options === "boolean") { + logger = undefined; + tryNextLink = options; + } + else if (options != null && typeof options === "object") { + logger = options.logger; + tryNextLink = options.tryNextLink ?? true; + } + super(message); + this.tryNextLink = tryNextLink; + Object.setPrototypeOf(this, ProviderError.prototype); + logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); + } + static from(error, options = true) { + return Object.assign(new this(error.message, options), error); + } +} + +class CredentialsProviderError extends ProviderError { + name = "CredentialsProviderError"; + constructor(message, options = true) { + super(message, options); + Object.setPrototypeOf(this, CredentialsProviderError.prototype); + } +} + +class TokenProviderError extends ProviderError { + name = "TokenProviderError"; + constructor(message, options = true) { + super(message, options); + Object.setPrototypeOf(this, TokenProviderError.prototype); + } +} + +const chain = (...providers) => async () => { + if (providers.length === 0) { + throw new ProviderError("No providers in chain"); + } + let lastProviderError; + for (const provider of providers) { + try { + const credentials = await provider(); + return credentials; + } + catch (err) { + lastProviderError = err; + if (err?.tryNextLink) { + continue; + } + throw err; + } + } + throw lastProviderError; +}; + +const fromStatic = (staticValue) => () => Promise.resolve(staticValue); + +const memoize = (provider, isExpired, requiresRefresh) => { + let resolved; + let pending; + let hasResult; + let isConstant = false; + const coalesceProvider = async () => { + if (!pending) { + pending = provider(); + } + try { + resolved = await pending; + hasResult = true; + isConstant = false; + } + finally { + pending = undefined; + } + return resolved; + }; + if (isExpired === undefined) { + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); + } + return resolved; + }; + } + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); + } + if (isConstant) { + return resolved; + } + if (requiresRefresh && !requiresRefresh(resolved)) { + isConstant = true; + return resolved; + } + if (isExpired(resolved)) { + await coalesceProvider(); + return resolved; + } + return resolved; + }; +}; + +exports.CredentialsProviderError = CredentialsProviderError; +exports.ProviderError = ProviderError; +exports.TokenProviderError = TokenProviderError; +exports.chain = chain; +exports.fromStatic = fromStatic; +exports.memoize = memoize; diff --git a/claude-code-source/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/protocol-http/dist-cjs/index.js new file mode 100644 index 00000000..182663fb --- /dev/null +++ b/claude-code-source/node_modules/@smithy/protocol-http/dist-cjs/index.js @@ -0,0 +1,237 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + Field: () => Field, + Fields: () => Fields, + HttpRequest: () => HttpRequest, + HttpResponse: () => HttpResponse, + getHttpHandlerExtensionConfiguration: () => getHttpHandlerExtensionConfiguration, + isValidHostname: () => isValidHostname, + resolveHttpHandlerRuntimeConfig: () => resolveHttpHandlerRuntimeConfig +}); +module.exports = __toCommonJS(src_exports); + +// src/extensions/httpExtensionConfiguration.ts +var getHttpHandlerExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + let httpHandler = runtimeConfig.httpHandler; + return { + setHttpHandler(handler) { + httpHandler = handler; + }, + httpHandler() { + return httpHandler; + }, + updateHttpClientConfig(key, value) { + httpHandler.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return httpHandler.httpHandlerConfigs(); + } + }; +}, "getHttpHandlerExtensionConfiguration"); +var resolveHttpHandlerRuntimeConfig = /* @__PURE__ */ __name((httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler() + }; +}, "resolveHttpHandlerRuntimeConfig"); + +// src/Field.ts +var import_types = require("@smithy/types"); +var _Field = class _Field { + constructor({ name, kind = import_types.FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; + } + /** + * Appends a value to the field. + * + * @param value The value to append. + */ + add(value) { + this.values.push(value); + } + /** + * Overwrite existing field values. + * + * @param values The new field values. + */ + set(values) { + this.values = values; + } + /** + * Remove all matching entries from list. + * + * @param value Value to remove. + */ + remove(value) { + this.values = this.values.filter((v) => v !== value); + } + /** + * Get comma-delimited string. + * + * @returns String representation of {@link Field}. + */ + toString() { + return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", "); + } + /** + * Get string values as a list + * + * @returns Values in {@link Field} as a list. + */ + get() { + return this.values; + } +}; +__name(_Field, "Field"); +var Field = _Field; + +// src/Fields.ts +var _Fields = class _Fields { + constructor({ fields = [], encoding = "utf-8" }) { + this.entries = {}; + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + /** + * Set entry for a {@link Field} name. The `name` + * attribute will be used to key the collection. + * + * @param field The {@link Field} to set. + */ + setField(field) { + this.entries[field.name.toLowerCase()] = field; + } + /** + * Retrieve {@link Field} entry by name. + * + * @param name The name of the {@link Field} entry + * to retrieve + * @returns The {@link Field} if it exists. + */ + getField(name) { + return this.entries[name.toLowerCase()]; + } + /** + * Delete entry from collection. + * + * @param name Name of the entry to delete. + */ + removeField(name) { + delete this.entries[name.toLowerCase()]; + } + /** + * Helper function for retrieving specific types of fields. + * Used to grab all headers or all trailers. + * + * @param kind {@link FieldPosition} of entries to retrieve. + * @returns The {@link Field} entries with the specified + * {@link FieldPosition}. + */ + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } +}; +__name(_Fields, "Fields"); +var Fields = _Fields; + +// src/httpRequest.ts +var _HttpRequest = class _HttpRequest { + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:"; + this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + static isInstance(request) { + if (!request) + return false; + const req = request; + return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object"; + } + clone() { + const cloned = new _HttpRequest({ + ...this, + headers: { ...this.headers } + }); + if (cloned.query) + cloned.query = cloneQuery(cloned.query); + return cloned; + } +}; +__name(_HttpRequest, "HttpRequest"); +var HttpRequest = _HttpRequest; +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param + }; + }, {}); +} +__name(cloneQuery, "cloneQuery"); + +// src/httpResponse.ts +var _HttpResponse = class _HttpResponse { + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) + return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + } +}; +__name(_HttpResponse, "HttpResponse"); +var HttpResponse = _HttpResponse; + +// src/isValidHostname.ts +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} +__name(isValidHostname, "isValidHostname"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (module.exports = { + getHttpHandlerExtensionConfiguration, + resolveHttpHandlerRuntimeConfig, + Field, + Fields, + HttpRequest, + HttpResponse, + isValidHostname +}); + diff --git a/claude-code-source/node_modules/@smithy/querystring-builder/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/querystring-builder/dist-cjs/index.js new file mode 100644 index 00000000..70302425 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/querystring-builder/dist-cjs/index.js @@ -0,0 +1,52 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + buildQueryString: () => buildQueryString +}); +module.exports = __toCommonJS(src_exports); +var import_util_uri_escape = require("@smithy/util-uri-escape"); +function buildQueryString(query) { + const parts = []; + for (let key of Object.keys(query).sort()) { + const value = query[key]; + key = (0, import_util_uri_escape.escapeUri)(key); + if (Array.isArray(value)) { + for (let i = 0, iLen = value.length; i < iLen; i++) { + parts.push(`${key}=${(0, import_util_uri_escape.escapeUri)(value[i])}`); + } + } else { + let qsEntry = key; + if (value || typeof value === "string") { + qsEntry += `=${(0, import_util_uri_escape.escapeUri)(value)}`; + } + parts.push(qsEntry); + } + } + return parts.join("&"); +} +__name(buildQueryString, "buildQueryString"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (module.exports = { + buildQueryString +}); + diff --git a/claude-code-source/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js new file mode 100644 index 00000000..51001efe --- /dev/null +++ b/claude-code-source/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js @@ -0,0 +1,43 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + escapeUri: () => escapeUri, + escapeUriPath: () => escapeUriPath +}); +module.exports = __toCommonJS(src_exports); + +// src/escape-uri.ts +var escapeUri = /* @__PURE__ */ __name((uri) => ( + // AWS percent-encodes some extra non-standard characters in a URI + encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode) +), "escapeUri"); +var hexEncode = /* @__PURE__ */ __name((c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`, "hexEncode"); + +// src/escape-uri-path.ts +var escapeUriPath = /* @__PURE__ */ __name((uri) => uri.split("/").map(escapeUri).join("/"), "escapeUriPath"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (module.exports = { + escapeUri, + escapeUriPath +}); + diff --git a/claude-code-source/node_modules/@smithy/querystring-parser/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/querystring-parser/dist-cjs/index.js new file mode 100644 index 00000000..d1efbf7a --- /dev/null +++ b/claude-code-source/node_modules/@smithy/querystring-parser/dist-cjs/index.js @@ -0,0 +1,27 @@ +'use strict'; + +function parseQueryString(querystring) { + const query = {}; + querystring = querystring.replace(/^\?/, ""); + if (querystring) { + for (const pair of querystring.split("&")) { + let [key, value = null] = pair.split("="); + key = decodeURIComponent(key); + if (value) { + value = decodeURIComponent(value); + } + if (!(key in query)) { + query[key] = value; + } + else if (Array.isArray(query[key])) { + query[key].push(value); + } + else { + query[key] = [query[key], value]; + } + } + } + return query; +} + +exports.parseQueryString = parseQueryString; diff --git a/claude-code-source/node_modules/@smithy/service-error-classification/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/service-error-classification/dist-cjs/index.js new file mode 100644 index 00000000..03f20230 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/service-error-classification/dist-cjs/index.js @@ -0,0 +1,77 @@ +'use strict'; + +const CLOCK_SKEW_ERROR_CODES = [ + "AuthFailure", + "InvalidSignatureException", + "RequestExpired", + "RequestInTheFuture", + "RequestTimeTooSkewed", + "SignatureDoesNotMatch", +]; +const THROTTLING_ERROR_CODES = [ + "BandwidthLimitExceeded", + "EC2ThrottledException", + "LimitExceededException", + "PriorRequestNotComplete", + "ProvisionedThroughputExceededException", + "RequestLimitExceeded", + "RequestThrottled", + "RequestThrottledException", + "SlowDown", + "ThrottledException", + "Throttling", + "ThrottlingException", + "TooManyRequestsException", + "TransactionInProgressException", +]; +const TRANSIENT_ERROR_CODES = ["TimeoutError", "RequestTimeout", "RequestTimeoutException"]; +const TRANSIENT_ERROR_STATUS_CODES = [500, 502, 503, 504]; +const NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT"]; +const NODEJS_NETWORK_ERROR_CODES = ["EHOSTUNREACH", "ENETUNREACH", "ENOTFOUND"]; + +const isRetryableByTrait = (error) => error?.$retryable !== undefined; +const isClockSkewError = (error) => CLOCK_SKEW_ERROR_CODES.includes(error.name); +const isClockSkewCorrectedError = (error) => error.$metadata?.clockSkewCorrected; +const isBrowserNetworkError = (error) => { + const errorMessages = new Set([ + "Failed to fetch", + "NetworkError when attempting to fetch resource", + "The Internet connection appears to be offline", + "Load failed", + "Network request failed", + ]); + const isValid = error && error instanceof TypeError; + if (!isValid) { + return false; + } + return errorMessages.has(error.message); +}; +const isThrottlingError = (error) => error.$metadata?.httpStatusCode === 429 || + THROTTLING_ERROR_CODES.includes(error.name) || + error.$retryable?.throttling == true; +const isTransientError = (error, depth = 0) => isRetryableByTrait(error) || + isClockSkewCorrectedError(error) || + TRANSIENT_ERROR_CODES.includes(error.name) || + NODEJS_TIMEOUT_ERROR_CODES.includes(error?.code || "") || + NODEJS_NETWORK_ERROR_CODES.includes(error?.code || "") || + TRANSIENT_ERROR_STATUS_CODES.includes(error.$metadata?.httpStatusCode || 0) || + isBrowserNetworkError(error) || + (error.cause !== undefined && depth <= 10 && isTransientError(error.cause, depth + 1)); +const isServerError = (error) => { + if (error.$metadata?.httpStatusCode !== undefined) { + const statusCode = error.$metadata.httpStatusCode; + if (500 <= statusCode && statusCode <= 599 && !isTransientError(error)) { + return true; + } + return false; + } + return false; +}; + +exports.isBrowserNetworkError = isBrowserNetworkError; +exports.isClockSkewCorrectedError = isClockSkewCorrectedError; +exports.isClockSkewError = isClockSkewError; +exports.isRetryableByTrait = isRetryableByTrait; +exports.isServerError = isServerError; +exports.isThrottlingError = isThrottlingError; +exports.isTransientError = isTransientError; diff --git a/claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getHomeDir.js b/claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getHomeDir.js new file mode 100644 index 00000000..2a4f7375 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getHomeDir.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getHomeDir = void 0; +const os_1 = require("os"); +const path_1 = require("path"); +const homeDirCache = {}; +const getHomeDirCacheKey = () => { + if (process && process.geteuid) { + return `${process.geteuid()}`; + } + return "DEFAULT"; +}; +const getHomeDir = () => { + const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${path_1.sep}` } = process.env; + if (HOME) + return HOME; + if (USERPROFILE) + return USERPROFILE; + if (HOMEPATH) + return `${HOMEDRIVE}${HOMEPATH}`; + const homeDirCacheKey = getHomeDirCacheKey(); + if (!homeDirCache[homeDirCacheKey]) + homeDirCache[homeDirCacheKey] = (0, os_1.homedir)(); + return homeDirCache[homeDirCacheKey]; +}; +exports.getHomeDir = getHomeDir; diff --git a/claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFilepath.js b/claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFilepath.js new file mode 100644 index 00000000..30d97b3d --- /dev/null +++ b/claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFilepath.js @@ -0,0 +1,12 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getSSOTokenFilepath = void 0; +const crypto_1 = require("crypto"); +const path_1 = require("path"); +const getHomeDir_1 = require("./getHomeDir"); +const getSSOTokenFilepath = (id) => { + const hasher = (0, crypto_1.createHash)("sha1"); + const cacheName = hasher.update(id).digest("hex"); + return (0, path_1.join)((0, getHomeDir_1.getHomeDir)(), ".aws", "sso", "cache", `${cacheName}.json`); +}; +exports.getSSOTokenFilepath = getSSOTokenFilepath; diff --git a/claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFromFile.js b/claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFromFile.js new file mode 100644 index 00000000..955e1121 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFromFile.js @@ -0,0 +1,15 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getSSOTokenFromFile = exports.tokenIntercept = void 0; +const promises_1 = require("fs/promises"); +const getSSOTokenFilepath_1 = require("./getSSOTokenFilepath"); +exports.tokenIntercept = {}; +const getSSOTokenFromFile = async (id) => { + if (exports.tokenIntercept[id]) { + return exports.tokenIntercept[id]; + } + const ssoTokenFilepath = (0, getSSOTokenFilepath_1.getSSOTokenFilepath)(id); + const ssoTokenText = await (0, promises_1.readFile)(ssoTokenFilepath, "utf8"); + return JSON.parse(ssoTokenText); +}; +exports.getSSOTokenFromFile = getSSOTokenFromFile; diff --git a/claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/index.js new file mode 100644 index 00000000..75693847 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/index.js @@ -0,0 +1,194 @@ +'use strict'; + +var getHomeDir = require('./getHomeDir'); +var getSSOTokenFilepath = require('./getSSOTokenFilepath'); +var getSSOTokenFromFile = require('./getSSOTokenFromFile'); +var path = require('path'); +var types = require('@smithy/types'); +var readFile = require('./readFile'); + +const ENV_PROFILE = "AWS_PROFILE"; +const DEFAULT_PROFILE = "default"; +const getProfileName = (init) => init.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE; + +const CONFIG_PREFIX_SEPARATOR = "."; + +const getConfigData = (data) => Object.entries(data) + .filter(([key]) => { + const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); + if (indexOfSeparator === -1) { + return false; + } + return Object.values(types.IniSectionType).includes(key.substring(0, indexOfSeparator)); +}) + .reduce((acc, [key, value]) => { + const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); + const updatedKey = key.substring(0, indexOfSeparator) === types.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key; + acc[updatedKey] = value; + return acc; +}, { + ...(data.default && { default: data.default }), +}); + +const ENV_CONFIG_PATH = "AWS_CONFIG_FILE"; +const getConfigFilepath = () => process.env[ENV_CONFIG_PATH] || path.join(getHomeDir.getHomeDir(), ".aws", "config"); + +const ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE"; +const getCredentialsFilepath = () => process.env[ENV_CREDENTIALS_PATH] || path.join(getHomeDir.getHomeDir(), ".aws", "credentials"); + +const prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/; +const profileNameBlockList = ["__proto__", "profile __proto__"]; +const parseIni = (iniData) => { + const map = {}; + let currentSection; + let currentSubSection; + for (const iniLine of iniData.split(/\r?\n/)) { + const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim(); + const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]"; + if (isSection) { + currentSection = undefined; + currentSubSection = undefined; + const sectionName = trimmedLine.substring(1, trimmedLine.length - 1); + const matches = prefixKeyRegex.exec(sectionName); + if (matches) { + const [, prefix, , name] = matches; + if (Object.values(types.IniSectionType).includes(prefix)) { + currentSection = [prefix, name].join(CONFIG_PREFIX_SEPARATOR); + } + } + else { + currentSection = sectionName; + } + if (profileNameBlockList.includes(sectionName)) { + throw new Error(`Found invalid profile name "${sectionName}"`); + } + } + else if (currentSection) { + const indexOfEqualsSign = trimmedLine.indexOf("="); + if (![0, -1].includes(indexOfEqualsSign)) { + const [name, value] = [ + trimmedLine.substring(0, indexOfEqualsSign).trim(), + trimmedLine.substring(indexOfEqualsSign + 1).trim(), + ]; + if (value === "") { + currentSubSection = name; + } + else { + if (currentSubSection && iniLine.trimStart() === iniLine) { + currentSubSection = undefined; + } + map[currentSection] = map[currentSection] || {}; + const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name; + map[currentSection][key] = value; + } + } + } + } + return map; +}; + +const swallowError$1 = () => ({}); +const loadSharedConfigFiles = async (init = {}) => { + const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init; + const homeDir = getHomeDir.getHomeDir(); + const relativeHomeDirPrefix = "~/"; + let resolvedFilepath = filepath; + if (filepath.startsWith(relativeHomeDirPrefix)) { + resolvedFilepath = path.join(homeDir, filepath.slice(2)); + } + let resolvedConfigFilepath = configFilepath; + if (configFilepath.startsWith(relativeHomeDirPrefix)) { + resolvedConfigFilepath = path.join(homeDir, configFilepath.slice(2)); + } + const parsedFiles = await Promise.all([ + readFile.readFile(resolvedConfigFilepath, { + ignoreCache: init.ignoreCache, + }) + .then(parseIni) + .then(getConfigData) + .catch(swallowError$1), + readFile.readFile(resolvedFilepath, { + ignoreCache: init.ignoreCache, + }) + .then(parseIni) + .catch(swallowError$1), + ]); + return { + configFile: parsedFiles[0], + credentialsFile: parsedFiles[1], + }; +}; + +const getSsoSessionData = (data) => Object.entries(data) + .filter(([key]) => key.startsWith(types.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)) + .reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}); + +const swallowError = () => ({}); +const loadSsoSessionData = async (init = {}) => readFile.readFile(init.configFilepath ?? getConfigFilepath()) + .then(parseIni) + .then(getSsoSessionData) + .catch(swallowError); + +const mergeConfigFiles = (...files) => { + const merged = {}; + for (const file of files) { + for (const [key, values] of Object.entries(file)) { + if (merged[key] !== undefined) { + Object.assign(merged[key], values); + } + else { + merged[key] = values; + } + } + } + return merged; +}; + +const parseKnownFiles = async (init) => { + const parsedFiles = await loadSharedConfigFiles(init); + return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile); +}; + +const externalDataInterceptor = { + getFileRecord() { + return readFile.fileIntercept; + }, + interceptFile(path, contents) { + readFile.fileIntercept[path] = Promise.resolve(contents); + }, + getTokenRecord() { + return getSSOTokenFromFile.tokenIntercept; + }, + interceptToken(id, contents) { + getSSOTokenFromFile.tokenIntercept[id] = contents; + }, +}; + +Object.defineProperty(exports, "getSSOTokenFromFile", { + enumerable: true, + get: function () { return getSSOTokenFromFile.getSSOTokenFromFile; } +}); +Object.defineProperty(exports, "readFile", { + enumerable: true, + get: function () { return readFile.readFile; } +}); +exports.CONFIG_PREFIX_SEPARATOR = CONFIG_PREFIX_SEPARATOR; +exports.DEFAULT_PROFILE = DEFAULT_PROFILE; +exports.ENV_PROFILE = ENV_PROFILE; +exports.externalDataInterceptor = externalDataInterceptor; +exports.getProfileName = getProfileName; +exports.loadSharedConfigFiles = loadSharedConfigFiles; +exports.loadSsoSessionData = loadSsoSessionData; +exports.parseKnownFiles = parseKnownFiles; +Object.keys(getHomeDir).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return getHomeDir[k]; } + }); +}); +Object.keys(getSSOTokenFilepath).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return getSSOTokenFilepath[k]; } + }); +}); diff --git a/claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/readFile.js b/claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/readFile.js new file mode 100644 index 00000000..e2a492fd --- /dev/null +++ b/claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/readFile.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.readFile = exports.fileIntercept = exports.filePromises = void 0; +const promises_1 = require("node:fs/promises"); +exports.filePromises = {}; +exports.fileIntercept = {}; +const readFile = (path, options) => { + if (exports.fileIntercept[path] !== undefined) { + return exports.fileIntercept[path]; + } + if (!exports.filePromises[path] || options?.ignoreCache) { + exports.filePromises[path] = (0, promises_1.readFile)(path, "utf8"); + } + return exports.filePromises[path]; +}; +exports.readFile = readFile; diff --git a/claude-code-source/node_modules/@smithy/shared-ini-file-loader/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/shared-ini-file-loader/node_modules/@smithy/types/dist-cjs/index.js new file mode 100644 index 00000000..be6d0e1a --- /dev/null +++ b/claude-code-source/node_modules/@smithy/shared-ini-file-loader/node_modules/@smithy/types/dist-cjs/index.js @@ -0,0 +1,91 @@ +'use strict'; + +exports.HttpAuthLocation = void 0; +(function (HttpAuthLocation) { + HttpAuthLocation["HEADER"] = "header"; + HttpAuthLocation["QUERY"] = "query"; +})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); + +exports.HttpApiKeyAuthLocation = void 0; +(function (HttpApiKeyAuthLocation) { + HttpApiKeyAuthLocation["HEADER"] = "header"; + HttpApiKeyAuthLocation["QUERY"] = "query"; +})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); + +exports.EndpointURLScheme = void 0; +(function (EndpointURLScheme) { + EndpointURLScheme["HTTP"] = "http"; + EndpointURLScheme["HTTPS"] = "https"; +})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); + +exports.AlgorithmId = void 0; +(function (AlgorithmId) { + AlgorithmId["MD5"] = "md5"; + AlgorithmId["CRC32"] = "crc32"; + AlgorithmId["CRC32C"] = "crc32c"; + AlgorithmId["SHA1"] = "sha1"; + AlgorithmId["SHA256"] = "sha256"; +})(exports.AlgorithmId || (exports.AlgorithmId = {})); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.SHA256, + checksumConstructor: () => runtimeConfig.sha256, + }); + } + if (runtimeConfig.md5 != undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.MD5, + checksumConstructor: () => runtimeConfig.md5, + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getDefaultClientConfiguration = (runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}; +const resolveDefaultRuntimeConfig = (config) => { + return resolveChecksumRuntimeConfig(config); +}; + +exports.FieldPosition = void 0; +(function (FieldPosition) { + FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; + FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; +})(exports.FieldPosition || (exports.FieldPosition = {})); + +const SMITHY_CONTEXT_KEY = "__smithy_context"; + +exports.IniSectionType = void 0; +(function (IniSectionType) { + IniSectionType["PROFILE"] = "profile"; + IniSectionType["SSO_SESSION"] = "sso-session"; + IniSectionType["SERVICES"] = "services"; +})(exports.IniSectionType || (exports.IniSectionType = {})); + +exports.RequestHandlerProtocol = void 0; +(function (RequestHandlerProtocol) { + RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; +})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); + +exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; diff --git a/claude-code-source/node_modules/@smithy/signature-v4/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/signature-v4/dist-cjs/index.js new file mode 100644 index 00000000..fc678618 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/signature-v4/dist-cjs/index.js @@ -0,0 +1,589 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + SignatureV4: () => SignatureV4, + clearCredentialCache: () => clearCredentialCache, + createScope: () => createScope, + getCanonicalHeaders: () => getCanonicalHeaders, + getCanonicalQuery: () => getCanonicalQuery, + getPayloadHash: () => getPayloadHash, + getSigningKey: () => getSigningKey, + moveHeadersToQuery: () => moveHeadersToQuery, + prepareRequest: () => prepareRequest +}); +module.exports = __toCommonJS(src_exports); + +// src/SignatureV4.ts + +var import_util_middleware = require("@smithy/util-middleware"); + +var import_util_utf84 = require("@smithy/util-utf8"); + +// src/constants.ts +var ALGORITHM_QUERY_PARAM = "X-Amz-Algorithm"; +var CREDENTIAL_QUERY_PARAM = "X-Amz-Credential"; +var AMZ_DATE_QUERY_PARAM = "X-Amz-Date"; +var SIGNED_HEADERS_QUERY_PARAM = "X-Amz-SignedHeaders"; +var EXPIRES_QUERY_PARAM = "X-Amz-Expires"; +var SIGNATURE_QUERY_PARAM = "X-Amz-Signature"; +var TOKEN_QUERY_PARAM = "X-Amz-Security-Token"; +var AUTH_HEADER = "authorization"; +var AMZ_DATE_HEADER = AMZ_DATE_QUERY_PARAM.toLowerCase(); +var DATE_HEADER = "date"; +var GENERATED_HEADERS = [AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER]; +var SIGNATURE_HEADER = SIGNATURE_QUERY_PARAM.toLowerCase(); +var SHA256_HEADER = "x-amz-content-sha256"; +var TOKEN_HEADER = TOKEN_QUERY_PARAM.toLowerCase(); +var ALWAYS_UNSIGNABLE_HEADERS = { + authorization: true, + "cache-control": true, + connection: true, + expect: true, + from: true, + "keep-alive": true, + "max-forwards": true, + pragma: true, + referer: true, + te: true, + trailer: true, + "transfer-encoding": true, + upgrade: true, + "user-agent": true, + "x-amzn-trace-id": true +}; +var PROXY_HEADER_PATTERN = /^proxy-/; +var SEC_HEADER_PATTERN = /^sec-/; +var ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256"; +var EVENT_ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256-PAYLOAD"; +var UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD"; +var MAX_CACHE_SIZE = 50; +var KEY_TYPE_IDENTIFIER = "aws4_request"; +var MAX_PRESIGNED_TTL = 60 * 60 * 24 * 7; + +// src/credentialDerivation.ts +var import_util_hex_encoding = require("@smithy/util-hex-encoding"); +var import_util_utf8 = require("@smithy/util-utf8"); +var signingKeyCache = {}; +var cacheQueue = []; +var createScope = /* @__PURE__ */ __name((shortDate, region, service) => `${shortDate}/${region}/${service}/${KEY_TYPE_IDENTIFIER}`, "createScope"); +var getSigningKey = /* @__PURE__ */ __name(async (sha256Constructor, credentials, shortDate, region, service) => { + const credsHash = await hmac(sha256Constructor, credentials.secretAccessKey, credentials.accessKeyId); + const cacheKey = `${shortDate}:${region}:${service}:${(0, import_util_hex_encoding.toHex)(credsHash)}:${credentials.sessionToken}`; + if (cacheKey in signingKeyCache) { + return signingKeyCache[cacheKey]; + } + cacheQueue.push(cacheKey); + while (cacheQueue.length > MAX_CACHE_SIZE) { + delete signingKeyCache[cacheQueue.shift()]; + } + let key = `AWS4${credentials.secretAccessKey}`; + for (const signable of [shortDate, region, service, KEY_TYPE_IDENTIFIER]) { + key = await hmac(sha256Constructor, key, signable); + } + return signingKeyCache[cacheKey] = key; +}, "getSigningKey"); +var clearCredentialCache = /* @__PURE__ */ __name(() => { + cacheQueue.length = 0; + Object.keys(signingKeyCache).forEach((cacheKey) => { + delete signingKeyCache[cacheKey]; + }); +}, "clearCredentialCache"); +var hmac = /* @__PURE__ */ __name((ctor, secret, data) => { + const hash = new ctor(secret); + hash.update((0, import_util_utf8.toUint8Array)(data)); + return hash.digest(); +}, "hmac"); + +// src/getCanonicalHeaders.ts +var getCanonicalHeaders = /* @__PURE__ */ __name(({ headers }, unsignableHeaders, signableHeaders) => { + const canonical = {}; + for (const headerName of Object.keys(headers).sort()) { + if (headers[headerName] == void 0) { + continue; + } + const canonicalHeaderName = headerName.toLowerCase(); + if (canonicalHeaderName in ALWAYS_UNSIGNABLE_HEADERS || (unsignableHeaders == null ? void 0 : unsignableHeaders.has(canonicalHeaderName)) || PROXY_HEADER_PATTERN.test(canonicalHeaderName) || SEC_HEADER_PATTERN.test(canonicalHeaderName)) { + if (!signableHeaders || signableHeaders && !signableHeaders.has(canonicalHeaderName)) { + continue; + } + } + canonical[canonicalHeaderName] = headers[headerName].trim().replace(/\s+/g, " "); + } + return canonical; +}, "getCanonicalHeaders"); + +// src/getCanonicalQuery.ts +var import_util_uri_escape = require("@smithy/util-uri-escape"); +var getCanonicalQuery = /* @__PURE__ */ __name(({ query = {} }) => { + const keys = []; + const serialized = {}; + for (const key of Object.keys(query).sort()) { + if (key.toLowerCase() === SIGNATURE_HEADER) { + continue; + } + keys.push(key); + const value = query[key]; + if (typeof value === "string") { + serialized[key] = `${(0, import_util_uri_escape.escapeUri)(key)}=${(0, import_util_uri_escape.escapeUri)(value)}`; + } else if (Array.isArray(value)) { + serialized[key] = value.slice(0).reduce( + (encoded, value2) => encoded.concat([`${(0, import_util_uri_escape.escapeUri)(key)}=${(0, import_util_uri_escape.escapeUri)(value2)}`]), + [] + ).sort().join("&"); + } + } + return keys.map((key) => serialized[key]).filter((serialized2) => serialized2).join("&"); +}, "getCanonicalQuery"); + +// src/getPayloadHash.ts +var import_is_array_buffer = require("@smithy/is-array-buffer"); + +var import_util_utf82 = require("@smithy/util-utf8"); +var getPayloadHash = /* @__PURE__ */ __name(async ({ headers, body }, hashConstructor) => { + for (const headerName of Object.keys(headers)) { + if (headerName.toLowerCase() === SHA256_HEADER) { + return headers[headerName]; + } + } + if (body == void 0) { + return "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; + } else if (typeof body === "string" || ArrayBuffer.isView(body) || (0, import_is_array_buffer.isArrayBuffer)(body)) { + const hashCtor = new hashConstructor(); + hashCtor.update((0, import_util_utf82.toUint8Array)(body)); + return (0, import_util_hex_encoding.toHex)(await hashCtor.digest()); + } + return UNSIGNED_PAYLOAD; +}, "getPayloadHash"); + +// src/HeaderFormatter.ts + +var import_util_utf83 = require("@smithy/util-utf8"); +var _HeaderFormatter = class _HeaderFormatter { + format(headers) { + const chunks = []; + for (const headerName of Object.keys(headers)) { + const bytes = (0, import_util_utf83.fromUtf8)(headerName); + chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName])); + } + const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0)); + let position = 0; + for (const chunk of chunks) { + out.set(chunk, position); + position += chunk.byteLength; + } + return out; + } + formatHeaderValue(header) { + switch (header.type) { + case "boolean": + return Uint8Array.from([header.value ? 0 /* boolTrue */ : 1 /* boolFalse */]); + case "byte": + return Uint8Array.from([2 /* byte */, header.value]); + case "short": + const shortView = new DataView(new ArrayBuffer(3)); + shortView.setUint8(0, 3 /* short */); + shortView.setInt16(1, header.value, false); + return new Uint8Array(shortView.buffer); + case "integer": + const intView = new DataView(new ArrayBuffer(5)); + intView.setUint8(0, 4 /* integer */); + intView.setInt32(1, header.value, false); + return new Uint8Array(intView.buffer); + case "long": + const longBytes = new Uint8Array(9); + longBytes[0] = 5 /* long */; + longBytes.set(header.value.bytes, 1); + return longBytes; + case "binary": + const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength)); + binView.setUint8(0, 6 /* byteArray */); + binView.setUint16(1, header.value.byteLength, false); + const binBytes = new Uint8Array(binView.buffer); + binBytes.set(header.value, 3); + return binBytes; + case "string": + const utf8Bytes = (0, import_util_utf83.fromUtf8)(header.value); + const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength)); + strView.setUint8(0, 7 /* string */); + strView.setUint16(1, utf8Bytes.byteLength, false); + const strBytes = new Uint8Array(strView.buffer); + strBytes.set(utf8Bytes, 3); + return strBytes; + case "timestamp": + const tsBytes = new Uint8Array(9); + tsBytes[0] = 8 /* timestamp */; + tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1); + return tsBytes; + case "uuid": + if (!UUID_PATTERN.test(header.value)) { + throw new Error(`Invalid UUID received: ${header.value}`); + } + const uuidBytes = new Uint8Array(17); + uuidBytes[0] = 9 /* uuid */; + uuidBytes.set((0, import_util_hex_encoding.fromHex)(header.value.replace(/\-/g, "")), 1); + return uuidBytes; + } + } +}; +__name(_HeaderFormatter, "HeaderFormatter"); +var HeaderFormatter = _HeaderFormatter; +var UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; +var _Int64 = class _Int64 { + constructor(bytes) { + this.bytes = bytes; + if (bytes.byteLength !== 8) { + throw new Error("Int64 buffers must be exactly 8 bytes"); + } + } + static fromNumber(number) { + if (number > 9223372036854776e3 || number < -9223372036854776e3) { + throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`); + } + const bytes = new Uint8Array(8); + for (let i = 7, remaining = Math.abs(Math.round(number)); i > -1 && remaining > 0; i--, remaining /= 256) { + bytes[i] = remaining; + } + if (number < 0) { + negate(bytes); + } + return new _Int64(bytes); + } + /** + * Called implicitly by infix arithmetic operators. + */ + valueOf() { + const bytes = this.bytes.slice(0); + const negative = bytes[0] & 128; + if (negative) { + negate(bytes); + } + return parseInt((0, import_util_hex_encoding.toHex)(bytes), 16) * (negative ? -1 : 1); + } + toString() { + return String(this.valueOf()); + } +}; +__name(_Int64, "Int64"); +var Int64 = _Int64; +function negate(bytes) { + for (let i = 0; i < 8; i++) { + bytes[i] ^= 255; + } + for (let i = 7; i > -1; i--) { + bytes[i]++; + if (bytes[i] !== 0) + break; + } +} +__name(negate, "negate"); + +// src/headerUtil.ts +var hasHeader = /* @__PURE__ */ __name((soughtHeader, headers) => { + soughtHeader = soughtHeader.toLowerCase(); + for (const headerName of Object.keys(headers)) { + if (soughtHeader === headerName.toLowerCase()) { + return true; + } + } + return false; +}, "hasHeader"); + +// src/cloneRequest.ts +var cloneRequest = /* @__PURE__ */ __name(({ headers, query, ...rest }) => ({ + ...rest, + headers: { ...headers }, + query: query ? cloneQuery(query) : void 0 +}), "cloneRequest"); +var cloneQuery = /* @__PURE__ */ __name((query) => Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param + }; +}, {}), "cloneQuery"); + +// src/moveHeadersToQuery.ts +var moveHeadersToQuery = /* @__PURE__ */ __name((request, options = {}) => { + var _a; + const { headers, query = {} } = typeof request.clone === "function" ? request.clone() : cloneRequest(request); + for (const name of Object.keys(headers)) { + const lname = name.toLowerCase(); + if (lname.slice(0, 6) === "x-amz-" && !((_a = options.unhoistableHeaders) == null ? void 0 : _a.has(lname))) { + query[name] = headers[name]; + delete headers[name]; + } + } + return { + ...request, + headers, + query + }; +}, "moveHeadersToQuery"); + +// src/prepareRequest.ts +var prepareRequest = /* @__PURE__ */ __name((request) => { + request = typeof request.clone === "function" ? request.clone() : cloneRequest(request); + for (const headerName of Object.keys(request.headers)) { + if (GENERATED_HEADERS.indexOf(headerName.toLowerCase()) > -1) { + delete request.headers[headerName]; + } + } + return request; +}, "prepareRequest"); + +// src/utilDate.ts +var iso8601 = /* @__PURE__ */ __name((time) => toDate(time).toISOString().replace(/\.\d{3}Z$/, "Z"), "iso8601"); +var toDate = /* @__PURE__ */ __name((time) => { + if (typeof time === "number") { + return new Date(time * 1e3); + } + if (typeof time === "string") { + if (Number(time)) { + return new Date(Number(time) * 1e3); + } + return new Date(time); + } + return time; +}, "toDate"); + +// src/SignatureV4.ts +var _SignatureV4 = class _SignatureV4 { + constructor({ + applyChecksum, + credentials, + region, + service, + sha256, + uriEscapePath = true + }) { + this.headerFormatter = new HeaderFormatter(); + this.service = service; + this.sha256 = sha256; + this.uriEscapePath = uriEscapePath; + this.applyChecksum = typeof applyChecksum === "boolean" ? applyChecksum : true; + this.regionProvider = (0, import_util_middleware.normalizeProvider)(region); + this.credentialProvider = (0, import_util_middleware.normalizeProvider)(credentials); + } + async presign(originalRequest, options = {}) { + const { + signingDate = /* @__PURE__ */ new Date(), + expiresIn = 3600, + unsignableHeaders, + unhoistableHeaders, + signableHeaders, + signingRegion, + signingService + } = options; + const credentials = await this.credentialProvider(); + this.validateResolvedCredentials(credentials); + const region = signingRegion ?? await this.regionProvider(); + const { longDate, shortDate } = formatDate(signingDate); + if (expiresIn > MAX_PRESIGNED_TTL) { + return Promise.reject( + "Signature version 4 presigned URLs must have an expiration date less than one week in the future" + ); + } + const scope = createScope(shortDate, region, signingService ?? this.service); + const request = moveHeadersToQuery(prepareRequest(originalRequest), { unhoistableHeaders }); + if (credentials.sessionToken) { + request.query[TOKEN_QUERY_PARAM] = credentials.sessionToken; + } + request.query[ALGORITHM_QUERY_PARAM] = ALGORITHM_IDENTIFIER; + request.query[CREDENTIAL_QUERY_PARAM] = `${credentials.accessKeyId}/${scope}`; + request.query[AMZ_DATE_QUERY_PARAM] = longDate; + request.query[EXPIRES_QUERY_PARAM] = expiresIn.toString(10); + const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders); + request.query[SIGNED_HEADERS_QUERY_PARAM] = getCanonicalHeaderList(canonicalHeaders); + request.query[SIGNATURE_QUERY_PARAM] = await this.getSignature( + longDate, + scope, + this.getSigningKey(credentials, region, shortDate, signingService), + this.createCanonicalRequest(request, canonicalHeaders, await getPayloadHash(originalRequest, this.sha256)) + ); + return request; + } + async sign(toSign, options) { + if (typeof toSign === "string") { + return this.signString(toSign, options); + } else if (toSign.headers && toSign.payload) { + return this.signEvent(toSign, options); + } else if (toSign.message) { + return this.signMessage(toSign, options); + } else { + return this.signRequest(toSign, options); + } + } + async signEvent({ headers, payload }, { signingDate = /* @__PURE__ */ new Date(), priorSignature, signingRegion, signingService }) { + const region = signingRegion ?? await this.regionProvider(); + const { shortDate, longDate } = formatDate(signingDate); + const scope = createScope(shortDate, region, signingService ?? this.service); + const hashedPayload = await getPayloadHash({ headers: {}, body: payload }, this.sha256); + const hash = new this.sha256(); + hash.update(headers); + const hashedHeaders = (0, import_util_hex_encoding.toHex)(await hash.digest()); + const stringToSign = [ + EVENT_ALGORITHM_IDENTIFIER, + longDate, + scope, + priorSignature, + hashedHeaders, + hashedPayload + ].join("\n"); + return this.signString(stringToSign, { signingDate, signingRegion: region, signingService }); + } + async signMessage(signableMessage, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService }) { + const promise = this.signEvent( + { + headers: this.headerFormatter.format(signableMessage.message.headers), + payload: signableMessage.message.body + }, + { + signingDate, + signingRegion, + signingService, + priorSignature: signableMessage.priorSignature + } + ); + return promise.then((signature) => { + return { message: signableMessage.message, signature }; + }); + } + async signString(stringToSign, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService } = {}) { + const credentials = await this.credentialProvider(); + this.validateResolvedCredentials(credentials); + const region = signingRegion ?? await this.regionProvider(); + const { shortDate } = formatDate(signingDate); + const hash = new this.sha256(await this.getSigningKey(credentials, region, shortDate, signingService)); + hash.update((0, import_util_utf84.toUint8Array)(stringToSign)); + return (0, import_util_hex_encoding.toHex)(await hash.digest()); + } + async signRequest(requestToSign, { + signingDate = /* @__PURE__ */ new Date(), + signableHeaders, + unsignableHeaders, + signingRegion, + signingService + } = {}) { + const credentials = await this.credentialProvider(); + this.validateResolvedCredentials(credentials); + const region = signingRegion ?? await this.regionProvider(); + const request = prepareRequest(requestToSign); + const { longDate, shortDate } = formatDate(signingDate); + const scope = createScope(shortDate, region, signingService ?? this.service); + request.headers[AMZ_DATE_HEADER] = longDate; + if (credentials.sessionToken) { + request.headers[TOKEN_HEADER] = credentials.sessionToken; + } + const payloadHash = await getPayloadHash(request, this.sha256); + if (!hasHeader(SHA256_HEADER, request.headers) && this.applyChecksum) { + request.headers[SHA256_HEADER] = payloadHash; + } + const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders); + const signature = await this.getSignature( + longDate, + scope, + this.getSigningKey(credentials, region, shortDate, signingService), + this.createCanonicalRequest(request, canonicalHeaders, payloadHash) + ); + request.headers[AUTH_HEADER] = `${ALGORITHM_IDENTIFIER} Credential=${credentials.accessKeyId}/${scope}, SignedHeaders=${getCanonicalHeaderList(canonicalHeaders)}, Signature=${signature}`; + return request; + } + createCanonicalRequest(request, canonicalHeaders, payloadHash) { + const sortedHeaders = Object.keys(canonicalHeaders).sort(); + return `${request.method} +${this.getCanonicalPath(request)} +${getCanonicalQuery(request)} +${sortedHeaders.map((name) => `${name}:${canonicalHeaders[name]}`).join("\n")} + +${sortedHeaders.join(";")} +${payloadHash}`; + } + async createStringToSign(longDate, credentialScope, canonicalRequest) { + const hash = new this.sha256(); + hash.update((0, import_util_utf84.toUint8Array)(canonicalRequest)); + const hashedRequest = await hash.digest(); + return `${ALGORITHM_IDENTIFIER} +${longDate} +${credentialScope} +${(0, import_util_hex_encoding.toHex)(hashedRequest)}`; + } + getCanonicalPath({ path }) { + if (this.uriEscapePath) { + const normalizedPathSegments = []; + for (const pathSegment of path.split("/")) { + if ((pathSegment == null ? void 0 : pathSegment.length) === 0) + continue; + if (pathSegment === ".") + continue; + if (pathSegment === "..") { + normalizedPathSegments.pop(); + } else { + normalizedPathSegments.push(pathSegment); + } + } + const normalizedPath = `${(path == null ? void 0 : path.startsWith("/")) ? "/" : ""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length > 0 && (path == null ? void 0 : path.endsWith("/")) ? "/" : ""}`; + const doubleEncoded = (0, import_util_uri_escape.escapeUri)(normalizedPath); + return doubleEncoded.replace(/%2F/g, "/"); + } + return path; + } + async getSignature(longDate, credentialScope, keyPromise, canonicalRequest) { + const stringToSign = await this.createStringToSign(longDate, credentialScope, canonicalRequest); + const hash = new this.sha256(await keyPromise); + hash.update((0, import_util_utf84.toUint8Array)(stringToSign)); + return (0, import_util_hex_encoding.toHex)(await hash.digest()); + } + getSigningKey(credentials, region, shortDate, service) { + return getSigningKey(this.sha256, credentials, shortDate, region, service || this.service); + } + validateResolvedCredentials(credentials) { + if (typeof credentials !== "object" || // @ts-expect-error: Property 'accessKeyId' does not exist on type 'object'.ts(2339) + typeof credentials.accessKeyId !== "string" || // @ts-expect-error: Property 'secretAccessKey' does not exist on type 'object'.ts(2339) + typeof credentials.secretAccessKey !== "string") { + throw new Error("Resolved credential object is not valid"); + } + } +}; +__name(_SignatureV4, "SignatureV4"); +var SignatureV4 = _SignatureV4; +var formatDate = /* @__PURE__ */ __name((now) => { + const longDate = iso8601(now).replace(/[\-:]/g, ""); + return { + longDate, + shortDate: longDate.slice(0, 8) + }; +}, "formatDate"); +var getCanonicalHeaderList = /* @__PURE__ */ __name((headers) => Object.keys(headers).sort().join(";"), "getCanonicalHeaderList"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (module.exports = { + getCanonicalHeaders, + getCanonicalQuery, + getPayloadHash, + moveHeadersToQuery, + prepareRequest, + SignatureV4, + createScope, + getSigningKey, + clearCredentialCache +}); + diff --git a/claude-code-source/node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-cjs/index.js new file mode 100644 index 00000000..b22a90a6 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-cjs/index.js @@ -0,0 +1,149 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + AlgorithmId: () => AlgorithmId, + EndpointURLScheme: () => EndpointURLScheme, + FieldPosition: () => FieldPosition, + HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, + HttpAuthLocation: () => HttpAuthLocation, + IniSectionType: () => IniSectionType, + RequestHandlerProtocol: () => RequestHandlerProtocol, + SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, + getDefaultClientConfiguration: () => getDefaultClientConfiguration, + resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig +}); +module.exports = __toCommonJS(src_exports); + +// src/auth/auth.ts +var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { + HttpAuthLocation2["HEADER"] = "header"; + HttpAuthLocation2["QUERY"] = "query"; + return HttpAuthLocation2; +})(HttpAuthLocation || {}); + +// src/auth/HttpApiKeyAuth.ts +var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { + HttpApiKeyAuthLocation2["HEADER"] = "header"; + HttpApiKeyAuthLocation2["QUERY"] = "query"; + return HttpApiKeyAuthLocation2; +})(HttpApiKeyAuthLocation || {}); + +// src/endpoint.ts +var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { + EndpointURLScheme2["HTTP"] = "http"; + EndpointURLScheme2["HTTPS"] = "https"; + return EndpointURLScheme2; +})(EndpointURLScheme || {}); + +// src/extensions/checksum.ts +var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { + AlgorithmId2["MD5"] = "md5"; + AlgorithmId2["CRC32"] = "crc32"; + AlgorithmId2["CRC32C"] = "crc32c"; + AlgorithmId2["SHA1"] = "sha1"; + AlgorithmId2["SHA256"] = "sha256"; + return AlgorithmId2; +})(AlgorithmId || {}); +var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== void 0) { + checksumAlgorithms.push({ + algorithmId: () => "sha256" /* SHA256 */, + checksumConstructor: () => runtimeConfig.sha256 + }); + } + if (runtimeConfig.md5 != void 0) { + checksumAlgorithms.push({ + algorithmId: () => "md5" /* MD5 */, + checksumConstructor: () => runtimeConfig.md5 + }); + } + return { + _checksumAlgorithms: checksumAlgorithms, + addChecksumAlgorithm(algo) { + this._checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return this._checksumAlgorithms; + } + }; +}, "getChecksumConfiguration"); +var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}, "resolveChecksumRuntimeConfig"); + +// src/extensions/defaultClientConfiguration.ts +var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + return { + ...getChecksumConfiguration(runtimeConfig) + }; +}, "getDefaultClientConfiguration"); +var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { + return { + ...resolveChecksumRuntimeConfig(config) + }; +}, "resolveDefaultRuntimeConfig"); + +// src/http.ts +var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { + FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; + FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; + return FieldPosition2; +})(FieldPosition || {}); + +// src/middleware.ts +var SMITHY_CONTEXT_KEY = "__smithy_context"; + +// src/profile.ts +var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { + IniSectionType2["PROFILE"] = "profile"; + IniSectionType2["SSO_SESSION"] = "sso-session"; + IniSectionType2["SERVICES"] = "services"; + return IniSectionType2; +})(IniSectionType || {}); + +// src/transfer.ts +var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { + RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; + return RequestHandlerProtocol2; +})(RequestHandlerProtocol || {}); +// Annotate the CommonJS export names for ESM import in node: + +0 && (module.exports = { + HttpAuthLocation, + HttpApiKeyAuthLocation, + EndpointURLScheme, + AlgorithmId, + getDefaultClientConfiguration, + resolveDefaultRuntimeConfig, + FieldPosition, + SMITHY_CONTEXT_KEY, + IniSectionType, + RequestHandlerProtocol +}); + diff --git a/claude-code-source/node_modules/@smithy/signature-v4/node_modules/@smithy/util-middleware/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/signature-v4/node_modules/@smithy/util-middleware/dist-cjs/index.js new file mode 100644 index 00000000..dfccf176 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/signature-v4/node_modules/@smithy/util-middleware/dist-cjs/index.js @@ -0,0 +1,45 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + getSmithyContext: () => getSmithyContext, + normalizeProvider: () => normalizeProvider +}); +module.exports = __toCommonJS(src_exports); + +// src/getSmithyContext.ts +var import_types = require("@smithy/types"); +var getSmithyContext = /* @__PURE__ */ __name((context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext"); + +// src/normalizeProvider.ts +var normalizeProvider = /* @__PURE__ */ __name((input) => { + if (typeof input === "function") + return input; + const promisified = Promise.resolve(input); + return () => promisified; +}, "normalizeProvider"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (module.exports = { + getSmithyContext, + normalizeProvider +}); + diff --git a/claude-code-source/node_modules/@smithy/signature-v4/node_modules/@smithy/util-utf8/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/signature-v4/node_modules/@smithy/util-utf8/dist-cjs/index.js new file mode 100644 index 00000000..0b22680a --- /dev/null +++ b/claude-code-source/node_modules/@smithy/signature-v4/node_modules/@smithy/util-utf8/dist-cjs/index.js @@ -0,0 +1,65 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + fromUtf8: () => fromUtf8, + toUint8Array: () => toUint8Array, + toUtf8: () => toUtf8 +}); +module.exports = __toCommonJS(src_exports); + +// src/fromUtf8.ts +var import_util_buffer_from = require("@smithy/util-buffer-from"); +var fromUtf8 = /* @__PURE__ */ __name((input) => { + const buf = (0, import_util_buffer_from.fromString)(input, "utf8"); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); +}, "fromUtf8"); + +// src/toUint8Array.ts +var toUint8Array = /* @__PURE__ */ __name((data) => { + if (typeof data === "string") { + return fromUtf8(data); + } + if (ArrayBuffer.isView(data)) { + return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); + } + return new Uint8Array(data); +}, "toUint8Array"); + +// src/toUtf8.ts + +var toUtf8 = /* @__PURE__ */ __name((input) => { + if (typeof input === "string") { + return input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); + } + return (0, import_util_buffer_from.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); +}, "toUtf8"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (module.exports = { + fromUtf8, + toUint8Array, + toUtf8 +}); + diff --git a/claude-code-source/node_modules/@smithy/signature-v4/node_modules/@smithy/util-utf8/node_modules/@smithy/util-buffer-from/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/signature-v4/node_modules/@smithy/util-utf8/node_modules/@smithy/util-buffer-from/dist-cjs/index.js new file mode 100644 index 00000000..c6738d94 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/signature-v4/node_modules/@smithy/util-utf8/node_modules/@smithy/util-buffer-from/dist-cjs/index.js @@ -0,0 +1,47 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + fromArrayBuffer: () => fromArrayBuffer, + fromString: () => fromString +}); +module.exports = __toCommonJS(src_exports); +var import_is_array_buffer = require("@smithy/is-array-buffer"); +var import_buffer = require("buffer"); +var fromArrayBuffer = /* @__PURE__ */ __name((input, offset = 0, length = input.byteLength - offset) => { + if (!(0, import_is_array_buffer.isArrayBuffer)(input)) { + throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); + } + return import_buffer.Buffer.from(input, offset, length); +}, "fromArrayBuffer"); +var fromString = /* @__PURE__ */ __name((input, encoding) => { + if (typeof input !== "string") { + throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); + } + return encoding ? import_buffer.Buffer.from(input, encoding) : import_buffer.Buffer.from(input); +}, "fromString"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (module.exports = { + fromArrayBuffer, + fromString +}); + diff --git a/claude-code-source/node_modules/@smithy/smithy-client/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/smithy-client/dist-cjs/index.js new file mode 100644 index 00000000..6d1e298c --- /dev/null +++ b/claude-code-source/node_modules/@smithy/smithy-client/dist-cjs/index.js @@ -0,0 +1,1256 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + Client: () => Client, + Command: () => Command, + LazyJsonString: () => LazyJsonString, + NoOpLogger: () => NoOpLogger, + SENSITIVE_STRING: () => SENSITIVE_STRING, + ServiceException: () => ServiceException, + StringWrapper: () => StringWrapper, + _json: () => _json, + collectBody: () => collectBody, + convertMap: () => convertMap, + createAggregatedClient: () => createAggregatedClient, + dateToUtcString: () => dateToUtcString, + decorateServiceException: () => decorateServiceException, + emitWarningIfUnsupportedVersion: () => emitWarningIfUnsupportedVersion, + expectBoolean: () => expectBoolean, + expectByte: () => expectByte, + expectFloat32: () => expectFloat32, + expectInt: () => expectInt, + expectInt32: () => expectInt32, + expectLong: () => expectLong, + expectNonNull: () => expectNonNull, + expectNumber: () => expectNumber, + expectObject: () => expectObject, + expectShort: () => expectShort, + expectString: () => expectString, + expectUnion: () => expectUnion, + extendedEncodeURIComponent: () => extendedEncodeURIComponent, + getArrayIfSingleItem: () => getArrayIfSingleItem, + getDefaultClientConfiguration: () => getDefaultClientConfiguration, + getDefaultExtensionConfiguration: () => getDefaultExtensionConfiguration, + getValueFromTextNode: () => getValueFromTextNode, + handleFloat: () => handleFloat, + limitedParseDouble: () => limitedParseDouble, + limitedParseFloat: () => limitedParseFloat, + limitedParseFloat32: () => limitedParseFloat32, + loadConfigsForDefaultMode: () => loadConfigsForDefaultMode, + logger: () => logger, + map: () => map, + parseBoolean: () => parseBoolean, + parseEpochTimestamp: () => parseEpochTimestamp, + parseRfc3339DateTime: () => parseRfc3339DateTime, + parseRfc3339DateTimeWithOffset: () => parseRfc3339DateTimeWithOffset, + parseRfc7231DateTime: () => parseRfc7231DateTime, + resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig, + resolvedPath: () => resolvedPath, + serializeFloat: () => serializeFloat, + splitEvery: () => splitEvery, + strictParseByte: () => strictParseByte, + strictParseDouble: () => strictParseDouble, + strictParseFloat: () => strictParseFloat, + strictParseFloat32: () => strictParseFloat32, + strictParseInt: () => strictParseInt, + strictParseInt32: () => strictParseInt32, + strictParseLong: () => strictParseLong, + strictParseShort: () => strictParseShort, + take: () => take, + throwDefaultError: () => throwDefaultError, + withBaseException: () => withBaseException +}); +module.exports = __toCommonJS(src_exports); + +// src/NoOpLogger.ts +var _NoOpLogger = class _NoOpLogger { + trace() { + } + debug() { + } + info() { + } + warn() { + } + error() { + } +}; +__name(_NoOpLogger, "NoOpLogger"); +var NoOpLogger = _NoOpLogger; + +// src/client.ts +var import_middleware_stack = require("@smithy/middleware-stack"); +var _Client = class _Client { + constructor(config) { + this.middlewareStack = (0, import_middleware_stack.constructStack)(); + this.config = config; + } + send(command, optionsOrCb, cb) { + const options = typeof optionsOrCb !== "function" ? optionsOrCb : void 0; + const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb; + const handler = command.resolveMiddleware(this.middlewareStack, this.config, options); + if (callback) { + handler(command).then( + (result) => callback(null, result.output), + (err) => callback(err) + ).catch( + // prevent any errors thrown in the callback from triggering an + // unhandled promise rejection + () => { + } + ); + } else { + return handler(command).then((result) => result.output); + } + } + destroy() { + if (this.config.requestHandler.destroy) + this.config.requestHandler.destroy(); + } +}; +__name(_Client, "Client"); +var Client = _Client; + +// src/collect-stream-body.ts +var import_util_stream = require("@smithy/util-stream"); +var collectBody = /* @__PURE__ */ __name(async (streamBody = new Uint8Array(), context) => { + if (streamBody instanceof Uint8Array) { + return import_util_stream.Uint8ArrayBlobAdapter.mutate(streamBody); + } + if (!streamBody) { + return import_util_stream.Uint8ArrayBlobAdapter.mutate(new Uint8Array()); + } + const fromContext = context.streamCollector(streamBody); + return import_util_stream.Uint8ArrayBlobAdapter.mutate(await fromContext); +}, "collectBody"); + +// src/command.ts + +var import_types = require("@smithy/types"); +var _Command = class _Command { + constructor() { + this.middlewareStack = (0, import_middleware_stack.constructStack)(); + } + /** + * Factory for Command ClassBuilder. + * @internal + */ + static classBuilder() { + return new ClassBuilder(); + } + /** + * @internal + */ + resolveMiddlewareWithContext(clientStack, configuration, options, { + middlewareFn, + clientName, + commandName, + inputFilterSensitiveLog, + outputFilterSensitiveLog, + smithyContext, + additionalContext, + CommandCtor + }) { + for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options)) { + this.middlewareStack.use(mw); + } + const stack = clientStack.concat(this.middlewareStack); + const { logger: logger2 } = configuration; + const handlerExecutionContext = { + logger: logger2, + clientName, + commandName, + inputFilterSensitiveLog, + outputFilterSensitiveLog, + [import_types.SMITHY_CONTEXT_KEY]: { + ...smithyContext + }, + ...additionalContext + }; + const { requestHandler } = configuration; + return stack.resolve( + (request) => requestHandler.handle(request.request, options || {}), + handlerExecutionContext + ); + } +}; +__name(_Command, "Command"); +var Command = _Command; +var _ClassBuilder = class _ClassBuilder { + constructor() { + this._init = () => { + }; + this._ep = {}; + this._middlewareFn = () => []; + this._commandName = ""; + this._clientName = ""; + this._additionalContext = {}; + this._smithyContext = {}; + this._inputFilterSensitiveLog = (_) => _; + this._outputFilterSensitiveLog = (_) => _; + this._serializer = null; + this._deserializer = null; + } + /** + * Optional init callback. + */ + init(cb) { + this._init = cb; + } + /** + * Set the endpoint parameter instructions. + */ + ep(endpointParameterInstructions) { + this._ep = endpointParameterInstructions; + return this; + } + /** + * Add any number of middleware. + */ + m(middlewareSupplier) { + this._middlewareFn = middlewareSupplier; + return this; + } + /** + * Set the initial handler execution context Smithy field. + */ + s(service, operation, smithyContext = {}) { + this._smithyContext = { + service, + operation, + ...smithyContext + }; + return this; + } + /** + * Set the initial handler execution context. + */ + c(additionalContext = {}) { + this._additionalContext = additionalContext; + return this; + } + /** + * Set constant string identifiers for the operation. + */ + n(clientName, commandName) { + this._clientName = clientName; + this._commandName = commandName; + return this; + } + /** + * Set the input and output sensistive log filters. + */ + f(inputFilter = (_) => _, outputFilter = (_) => _) { + this._inputFilterSensitiveLog = inputFilter; + this._outputFilterSensitiveLog = outputFilter; + return this; + } + /** + * Sets the serializer. + */ + ser(serializer) { + this._serializer = serializer; + return this; + } + /** + * Sets the deserializer. + */ + de(deserializer) { + this._deserializer = deserializer; + return this; + } + /** + * @returns a Command class with the classBuilder properties. + */ + build() { + var _a; + const closure = this; + let CommandRef; + return CommandRef = (_a = class extends Command { + /** + * @public + */ + constructor(...[input]) { + super(); + /** + * @internal + */ + // @ts-ignore used in middlewareFn closure. + this.serialize = closure._serializer; + /** + * @internal + */ + // @ts-ignore used in middlewareFn closure. + this.deserialize = closure._deserializer; + this.input = input ?? {}; + closure._init(this); + } + /** + * @public + */ + static getEndpointParameterInstructions() { + return closure._ep; + } + /** + * @internal + */ + resolveMiddleware(stack, configuration, options) { + return this.resolveMiddlewareWithContext(stack, configuration, options, { + CommandCtor: CommandRef, + middlewareFn: closure._middlewareFn, + clientName: closure._clientName, + commandName: closure._commandName, + inputFilterSensitiveLog: closure._inputFilterSensitiveLog, + outputFilterSensitiveLog: closure._outputFilterSensitiveLog, + smithyContext: closure._smithyContext, + additionalContext: closure._additionalContext + }); + } + }, __name(_a, "CommandRef"), _a); + } +}; +__name(_ClassBuilder, "ClassBuilder"); +var ClassBuilder = _ClassBuilder; + +// src/constants.ts +var SENSITIVE_STRING = "***SensitiveInformation***"; + +// src/create-aggregated-client.ts +var createAggregatedClient = /* @__PURE__ */ __name((commands, Client2) => { + for (const command of Object.keys(commands)) { + const CommandCtor = commands[command]; + const methodImpl = /* @__PURE__ */ __name(async function(args, optionsOrCb, cb) { + const command2 = new CommandCtor(args); + if (typeof optionsOrCb === "function") { + this.send(command2, optionsOrCb); + } else if (typeof cb === "function") { + if (typeof optionsOrCb !== "object") + throw new Error(`Expected http options but got ${typeof optionsOrCb}`); + this.send(command2, optionsOrCb || {}, cb); + } else { + return this.send(command2, optionsOrCb); + } + }, "methodImpl"); + const methodName = (command[0].toLowerCase() + command.slice(1)).replace(/Command$/, ""); + Client2.prototype[methodName] = methodImpl; + } +}, "createAggregatedClient"); + +// src/parse-utils.ts +var parseBoolean = /* @__PURE__ */ __name((value) => { + switch (value) { + case "true": + return true; + case "false": + return false; + default: + throw new Error(`Unable to parse boolean value "${value}"`); + } +}, "parseBoolean"); +var expectBoolean = /* @__PURE__ */ __name((value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value === "number") { + if (value === 0 || value === 1) { + logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); + } + if (value === 0) { + return false; + } + if (value === 1) { + return true; + } + } + if (typeof value === "string") { + const lower = value.toLowerCase(); + if (lower === "false" || lower === "true") { + logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); + } + if (lower === "false") { + return false; + } + if (lower === "true") { + return true; + } + } + if (typeof value === "boolean") { + return value; + } + throw new TypeError(`Expected boolean, got ${typeof value}: ${value}`); +}, "expectBoolean"); +var expectNumber = /* @__PURE__ */ __name((value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value === "string") { + const parsed = parseFloat(value); + if (!Number.isNaN(parsed)) { + if (String(parsed) !== String(value)) { + logger.warn(stackTraceWarning(`Expected number but observed string: ${value}`)); + } + return parsed; + } + } + if (typeof value === "number") { + return value; + } + throw new TypeError(`Expected number, got ${typeof value}: ${value}`); +}, "expectNumber"); +var MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23)); +var expectFloat32 = /* @__PURE__ */ __name((value) => { + const expected = expectNumber(value); + if (expected !== void 0 && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) { + if (Math.abs(expected) > MAX_FLOAT) { + throw new TypeError(`Expected 32-bit float, got ${value}`); + } + } + return expected; +}, "expectFloat32"); +var expectLong = /* @__PURE__ */ __name((value) => { + if (value === null || value === void 0) { + return void 0; + } + if (Number.isInteger(value) && !Number.isNaN(value)) { + return value; + } + throw new TypeError(`Expected integer, got ${typeof value}: ${value}`); +}, "expectLong"); +var expectInt = expectLong; +var expectInt32 = /* @__PURE__ */ __name((value) => expectSizedInt(value, 32), "expectInt32"); +var expectShort = /* @__PURE__ */ __name((value) => expectSizedInt(value, 16), "expectShort"); +var expectByte = /* @__PURE__ */ __name((value) => expectSizedInt(value, 8), "expectByte"); +var expectSizedInt = /* @__PURE__ */ __name((value, size) => { + const expected = expectLong(value); + if (expected !== void 0 && castInt(expected, size) !== expected) { + throw new TypeError(`Expected ${size}-bit integer, got ${value}`); + } + return expected; +}, "expectSizedInt"); +var castInt = /* @__PURE__ */ __name((value, size) => { + switch (size) { + case 32: + return Int32Array.of(value)[0]; + case 16: + return Int16Array.of(value)[0]; + case 8: + return Int8Array.of(value)[0]; + } +}, "castInt"); +var expectNonNull = /* @__PURE__ */ __name((value, location) => { + if (value === null || value === void 0) { + if (location) { + throw new TypeError(`Expected a non-null value for ${location}`); + } + throw new TypeError("Expected a non-null value"); + } + return value; +}, "expectNonNull"); +var expectObject = /* @__PURE__ */ __name((value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value === "object" && !Array.isArray(value)) { + return value; + } + const receivedType = Array.isArray(value) ? "array" : typeof value; + throw new TypeError(`Expected object, got ${receivedType}: ${value}`); +}, "expectObject"); +var expectString = /* @__PURE__ */ __name((value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value === "string") { + return value; + } + if (["boolean", "number", "bigint"].includes(typeof value)) { + logger.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`)); + return String(value); + } + throw new TypeError(`Expected string, got ${typeof value}: ${value}`); +}, "expectString"); +var expectUnion = /* @__PURE__ */ __name((value) => { + if (value === null || value === void 0) { + return void 0; + } + const asObject = expectObject(value); + const setKeys = Object.entries(asObject).filter(([, v]) => v != null).map(([k]) => k); + if (setKeys.length === 0) { + throw new TypeError(`Unions must have exactly one non-null member. None were found.`); + } + if (setKeys.length > 1) { + throw new TypeError(`Unions must have exactly one non-null member. Keys ${setKeys} were not null.`); + } + return asObject; +}, "expectUnion"); +var strictParseDouble = /* @__PURE__ */ __name((value) => { + if (typeof value == "string") { + return expectNumber(parseNumber(value)); + } + return expectNumber(value); +}, "strictParseDouble"); +var strictParseFloat = strictParseDouble; +var strictParseFloat32 = /* @__PURE__ */ __name((value) => { + if (typeof value == "string") { + return expectFloat32(parseNumber(value)); + } + return expectFloat32(value); +}, "strictParseFloat32"); +var NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g; +var parseNumber = /* @__PURE__ */ __name((value) => { + const matches = value.match(NUMBER_REGEX); + if (matches === null || matches[0].length !== value.length) { + throw new TypeError(`Expected real number, got implicit NaN`); + } + return parseFloat(value); +}, "parseNumber"); +var limitedParseDouble = /* @__PURE__ */ __name((value) => { + if (typeof value == "string") { + return parseFloatString(value); + } + return expectNumber(value); +}, "limitedParseDouble"); +var handleFloat = limitedParseDouble; +var limitedParseFloat = limitedParseDouble; +var limitedParseFloat32 = /* @__PURE__ */ __name((value) => { + if (typeof value == "string") { + return parseFloatString(value); + } + return expectFloat32(value); +}, "limitedParseFloat32"); +var parseFloatString = /* @__PURE__ */ __name((value) => { + switch (value) { + case "NaN": + return NaN; + case "Infinity": + return Infinity; + case "-Infinity": + return -Infinity; + default: + throw new Error(`Unable to parse float value: ${value}`); + } +}, "parseFloatString"); +var strictParseLong = /* @__PURE__ */ __name((value) => { + if (typeof value === "string") { + return expectLong(parseNumber(value)); + } + return expectLong(value); +}, "strictParseLong"); +var strictParseInt = strictParseLong; +var strictParseInt32 = /* @__PURE__ */ __name((value) => { + if (typeof value === "string") { + return expectInt32(parseNumber(value)); + } + return expectInt32(value); +}, "strictParseInt32"); +var strictParseShort = /* @__PURE__ */ __name((value) => { + if (typeof value === "string") { + return expectShort(parseNumber(value)); + } + return expectShort(value); +}, "strictParseShort"); +var strictParseByte = /* @__PURE__ */ __name((value) => { + if (typeof value === "string") { + return expectByte(parseNumber(value)); + } + return expectByte(value); +}, "strictParseByte"); +var stackTraceWarning = /* @__PURE__ */ __name((message) => { + return String(new TypeError(message).stack || message).split("\n").slice(0, 5).filter((s) => !s.includes("stackTraceWarning")).join("\n"); +}, "stackTraceWarning"); +var logger = { + warn: console.warn +}; + +// src/date-utils.ts +var DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; +var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; +function dateToUtcString(date) { + const year = date.getUTCFullYear(); + const month = date.getUTCMonth(); + const dayOfWeek = date.getUTCDay(); + const dayOfMonthInt = date.getUTCDate(); + const hoursInt = date.getUTCHours(); + const minutesInt = date.getUTCMinutes(); + const secondsInt = date.getUTCSeconds(); + const dayOfMonthString = dayOfMonthInt < 10 ? `0${dayOfMonthInt}` : `${dayOfMonthInt}`; + const hoursString = hoursInt < 10 ? `0${hoursInt}` : `${hoursInt}`; + const minutesString = minutesInt < 10 ? `0${minutesInt}` : `${minutesInt}`; + const secondsString = secondsInt < 10 ? `0${secondsInt}` : `${secondsInt}`; + return `${DAYS[dayOfWeek]}, ${dayOfMonthString} ${MONTHS[month]} ${year} ${hoursString}:${minutesString}:${secondsString} GMT`; +} +__name(dateToUtcString, "dateToUtcString"); +var RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/); +var parseRfc3339DateTime = /* @__PURE__ */ __name((value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value !== "string") { + throw new TypeError("RFC-3339 date-times must be expressed as strings"); + } + const match = RFC3339.exec(value); + if (!match) { + throw new TypeError("Invalid RFC-3339 date-time value"); + } + const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match; + const year = strictParseShort(stripLeadingZeroes(yearStr)); + const month = parseDateValue(monthStr, "month", 1, 12); + const day = parseDateValue(dayStr, "day", 1, 31); + return buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); +}, "parseRfc3339DateTime"); +var RFC3339_WITH_OFFSET = new RegExp( + /^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/ +); +var parseRfc3339DateTimeWithOffset = /* @__PURE__ */ __name((value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value !== "string") { + throw new TypeError("RFC-3339 date-times must be expressed as strings"); + } + const match = RFC3339_WITH_OFFSET.exec(value); + if (!match) { + throw new TypeError("Invalid RFC-3339 date-time value"); + } + const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match; + const year = strictParseShort(stripLeadingZeroes(yearStr)); + const month = parseDateValue(monthStr, "month", 1, 12); + const day = parseDateValue(dayStr, "day", 1, 31); + const date = buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); + if (offsetStr.toUpperCase() != "Z") { + date.setTime(date.getTime() - parseOffsetToMilliseconds(offsetStr)); + } + return date; +}, "parseRfc3339DateTimeWithOffset"); +var IMF_FIXDATE = new RegExp( + /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/ +); +var RFC_850_DATE = new RegExp( + /^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/ +); +var ASC_TIME = new RegExp( + /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/ +); +var parseRfc7231DateTime = /* @__PURE__ */ __name((value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value !== "string") { + throw new TypeError("RFC-7231 date-times must be expressed as strings"); + } + let match = IMF_FIXDATE.exec(value); + if (match) { + const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; + return buildDate( + strictParseShort(stripLeadingZeroes(yearStr)), + parseMonthByShortName(monthStr), + parseDateValue(dayStr, "day", 1, 31), + { hours, minutes, seconds, fractionalMilliseconds } + ); + } + match = RFC_850_DATE.exec(value); + if (match) { + const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; + return adjustRfc850Year( + buildDate(parseTwoDigitYear(yearStr), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { + hours, + minutes, + seconds, + fractionalMilliseconds + }) + ); + } + match = ASC_TIME.exec(value); + if (match) { + const [_, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, yearStr] = match; + return buildDate( + strictParseShort(stripLeadingZeroes(yearStr)), + parseMonthByShortName(monthStr), + parseDateValue(dayStr.trimLeft(), "day", 1, 31), + { hours, minutes, seconds, fractionalMilliseconds } + ); + } + throw new TypeError("Invalid RFC-7231 date-time value"); +}, "parseRfc7231DateTime"); +var parseEpochTimestamp = /* @__PURE__ */ __name((value) => { + if (value === null || value === void 0) { + return void 0; + } + let valueAsDouble; + if (typeof value === "number") { + valueAsDouble = value; + } else if (typeof value === "string") { + valueAsDouble = strictParseDouble(value); + } else { + throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation"); + } + if (Number.isNaN(valueAsDouble) || valueAsDouble === Infinity || valueAsDouble === -Infinity) { + throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics"); + } + return new Date(Math.round(valueAsDouble * 1e3)); +}, "parseEpochTimestamp"); +var buildDate = /* @__PURE__ */ __name((year, month, day, time) => { + const adjustedMonth = month - 1; + validateDayOfMonth(year, adjustedMonth, day); + return new Date( + Date.UTC( + year, + adjustedMonth, + day, + parseDateValue(time.hours, "hour", 0, 23), + parseDateValue(time.minutes, "minute", 0, 59), + // seconds can go up to 60 for leap seconds + parseDateValue(time.seconds, "seconds", 0, 60), + parseMilliseconds(time.fractionalMilliseconds) + ) + ); +}, "buildDate"); +var parseTwoDigitYear = /* @__PURE__ */ __name((value) => { + const thisYear = (/* @__PURE__ */ new Date()).getUTCFullYear(); + const valueInThisCentury = Math.floor(thisYear / 100) * 100 + strictParseShort(stripLeadingZeroes(value)); + if (valueInThisCentury < thisYear) { + return valueInThisCentury + 100; + } + return valueInThisCentury; +}, "parseTwoDigitYear"); +var FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1e3; +var adjustRfc850Year = /* @__PURE__ */ __name((input) => { + if (input.getTime() - (/* @__PURE__ */ new Date()).getTime() > FIFTY_YEARS_IN_MILLIS) { + return new Date( + Date.UTC( + input.getUTCFullYear() - 100, + input.getUTCMonth(), + input.getUTCDate(), + input.getUTCHours(), + input.getUTCMinutes(), + input.getUTCSeconds(), + input.getUTCMilliseconds() + ) + ); + } + return input; +}, "adjustRfc850Year"); +var parseMonthByShortName = /* @__PURE__ */ __name((value) => { + const monthIdx = MONTHS.indexOf(value); + if (monthIdx < 0) { + throw new TypeError(`Invalid month: ${value}`); + } + return monthIdx + 1; +}, "parseMonthByShortName"); +var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; +var validateDayOfMonth = /* @__PURE__ */ __name((year, month, day) => { + let maxDays = DAYS_IN_MONTH[month]; + if (month === 1 && isLeapYear(year)) { + maxDays = 29; + } + if (day > maxDays) { + throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`); + } +}, "validateDayOfMonth"); +var isLeapYear = /* @__PURE__ */ __name((year) => { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); +}, "isLeapYear"); +var parseDateValue = /* @__PURE__ */ __name((value, type, lower, upper) => { + const dateVal = strictParseByte(stripLeadingZeroes(value)); + if (dateVal < lower || dateVal > upper) { + throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`); + } + return dateVal; +}, "parseDateValue"); +var parseMilliseconds = /* @__PURE__ */ __name((value) => { + if (value === null || value === void 0) { + return 0; + } + return strictParseFloat32("0." + value) * 1e3; +}, "parseMilliseconds"); +var parseOffsetToMilliseconds = /* @__PURE__ */ __name((value) => { + const directionStr = value[0]; + let direction = 1; + if (directionStr == "+") { + direction = 1; + } else if (directionStr == "-") { + direction = -1; + } else { + throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`); + } + const hour = Number(value.substring(1, 3)); + const minute = Number(value.substring(4, 6)); + return direction * (hour * 60 + minute) * 60 * 1e3; +}, "parseOffsetToMilliseconds"); +var stripLeadingZeroes = /* @__PURE__ */ __name((value) => { + let idx = 0; + while (idx < value.length - 1 && value.charAt(idx) === "0") { + idx++; + } + if (idx === 0) { + return value; + } + return value.slice(idx); +}, "stripLeadingZeroes"); + +// src/exceptions.ts +var _ServiceException = class _ServiceException extends Error { + constructor(options) { + super(options.message); + Object.setPrototypeOf(this, _ServiceException.prototype); + this.name = options.name; + this.$fault = options.$fault; + this.$metadata = options.$metadata; + } +}; +__name(_ServiceException, "ServiceException"); +var ServiceException = _ServiceException; +var decorateServiceException = /* @__PURE__ */ __name((exception, additions = {}) => { + Object.entries(additions).filter(([, v]) => v !== void 0).forEach(([k, v]) => { + if (exception[k] == void 0 || exception[k] === "") { + exception[k] = v; + } + }); + const message = exception.message || exception.Message || "UnknownError"; + exception.message = message; + delete exception.Message; + return exception; +}, "decorateServiceException"); + +// src/default-error-handler.ts +var throwDefaultError = /* @__PURE__ */ __name(({ output, parsedBody, exceptionCtor, errorCode }) => { + const $metadata = deserializeMetadata(output); + const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : void 0; + const response = new exceptionCtor({ + name: (parsedBody == null ? void 0 : parsedBody.code) || (parsedBody == null ? void 0 : parsedBody.Code) || errorCode || statusCode || "UnknownError", + $fault: "client", + $metadata + }); + throw decorateServiceException(response, parsedBody); +}, "throwDefaultError"); +var withBaseException = /* @__PURE__ */ __name((ExceptionCtor) => { + return ({ output, parsedBody, errorCode }) => { + throwDefaultError({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode }); + }; +}, "withBaseException"); +var deserializeMetadata = /* @__PURE__ */ __name((output) => ({ + httpStatusCode: output.statusCode, + requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], + extendedRequestId: output.headers["x-amz-id-2"], + cfId: output.headers["x-amz-cf-id"] +}), "deserializeMetadata"); + +// src/defaults-mode.ts +var loadConfigsForDefaultMode = /* @__PURE__ */ __name((mode) => { + switch (mode) { + case "standard": + return { + retryMode: "standard", + connectionTimeout: 3100 + }; + case "in-region": + return { + retryMode: "standard", + connectionTimeout: 1100 + }; + case "cross-region": + return { + retryMode: "standard", + connectionTimeout: 3100 + }; + case "mobile": + return { + retryMode: "standard", + connectionTimeout: 3e4 + }; + default: + return {}; + } +}, "loadConfigsForDefaultMode"); + +// src/emitWarningIfUnsupportedVersion.ts +var warningEmitted = false; +var emitWarningIfUnsupportedVersion = /* @__PURE__ */ __name((version) => { + if (version && !warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 14) { + warningEmitted = true; + } +}, "emitWarningIfUnsupportedVersion"); + +// src/extensions/checksum.ts + +var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + const checksumAlgorithms = []; + for (const id in import_types.AlgorithmId) { + const algorithmId = import_types.AlgorithmId[id]; + if (runtimeConfig[algorithmId] === void 0) { + continue; + } + checksumAlgorithms.push({ + algorithmId: () => algorithmId, + checksumConstructor: () => runtimeConfig[algorithmId] + }); + } + return { + _checksumAlgorithms: checksumAlgorithms, + addChecksumAlgorithm(algo) { + this._checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return this._checksumAlgorithms; + } + }; +}, "getChecksumConfiguration"); +var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}, "resolveChecksumRuntimeConfig"); + +// src/extensions/retry.ts +var getRetryConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + let _retryStrategy = runtimeConfig.retryStrategy; + return { + setRetryStrategy(retryStrategy) { + _retryStrategy = retryStrategy; + }, + retryStrategy() { + return _retryStrategy; + } + }; +}, "getRetryConfiguration"); +var resolveRetryRuntimeConfig = /* @__PURE__ */ __name((retryStrategyConfiguration) => { + const runtimeConfig = {}; + runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy(); + return runtimeConfig; +}, "resolveRetryRuntimeConfig"); + +// src/extensions/defaultExtensionConfiguration.ts +var getDefaultExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + return { + ...getChecksumConfiguration(runtimeConfig), + ...getRetryConfiguration(runtimeConfig) + }; +}, "getDefaultExtensionConfiguration"); +var getDefaultClientConfiguration = getDefaultExtensionConfiguration; +var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { + return { + ...resolveChecksumRuntimeConfig(config), + ...resolveRetryRuntimeConfig(config) + }; +}, "resolveDefaultRuntimeConfig"); + +// src/extended-encode-uri-component.ts +function extendedEncodeURIComponent(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); + }); +} +__name(extendedEncodeURIComponent, "extendedEncodeURIComponent"); + +// src/get-array-if-single-item.ts +var getArrayIfSingleItem = /* @__PURE__ */ __name((mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray], "getArrayIfSingleItem"); + +// src/get-value-from-text-node.ts +var getValueFromTextNode = /* @__PURE__ */ __name((obj) => { + const textNodeName = "#text"; + for (const key in obj) { + if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== void 0) { + obj[key] = obj[key][textNodeName]; + } else if (typeof obj[key] === "object" && obj[key] !== null) { + obj[key] = getValueFromTextNode(obj[key]); + } + } + return obj; +}, "getValueFromTextNode"); + +// src/lazy-json.ts +var StringWrapper = /* @__PURE__ */ __name(function() { + const Class = Object.getPrototypeOf(this).constructor; + const Constructor = Function.bind.apply(String, [null, ...arguments]); + const instance = new Constructor(); + Object.setPrototypeOf(instance, Class.prototype); + return instance; +}, "StringWrapper"); +StringWrapper.prototype = Object.create(String.prototype, { + constructor: { + value: StringWrapper, + enumerable: false, + writable: true, + configurable: true + } +}); +Object.setPrototypeOf(StringWrapper, String); +var _LazyJsonString = class _LazyJsonString extends StringWrapper { + deserializeJSON() { + return JSON.parse(super.toString()); + } + toJSON() { + return super.toString(); + } + static fromObject(object) { + if (object instanceof _LazyJsonString) { + return object; + } else if (object instanceof String || typeof object === "string") { + return new _LazyJsonString(object); + } + return new _LazyJsonString(JSON.stringify(object)); + } +}; +__name(_LazyJsonString, "LazyJsonString"); +var LazyJsonString = _LazyJsonString; + +// src/object-mapping.ts +function map(arg0, arg1, arg2) { + let target; + let filter; + let instructions; + if (typeof arg1 === "undefined" && typeof arg2 === "undefined") { + target = {}; + instructions = arg0; + } else { + target = arg0; + if (typeof arg1 === "function") { + filter = arg1; + instructions = arg2; + return mapWithFilter(target, filter, instructions); + } else { + instructions = arg1; + } + } + for (const key of Object.keys(instructions)) { + if (!Array.isArray(instructions[key])) { + target[key] = instructions[key]; + continue; + } + applyInstruction(target, null, instructions, key); + } + return target; +} +__name(map, "map"); +var convertMap = /* @__PURE__ */ __name((target) => { + const output = {}; + for (const [k, v] of Object.entries(target || {})) { + output[k] = [, v]; + } + return output; +}, "convertMap"); +var take = /* @__PURE__ */ __name((source, instructions) => { + const out = {}; + for (const key in instructions) { + applyInstruction(out, source, instructions, key); + } + return out; +}, "take"); +var mapWithFilter = /* @__PURE__ */ __name((target, filter, instructions) => { + return map( + target, + Object.entries(instructions).reduce( + (_instructions, [key, value]) => { + if (Array.isArray(value)) { + _instructions[key] = value; + } else { + if (typeof value === "function") { + _instructions[key] = [filter, value()]; + } else { + _instructions[key] = [filter, value]; + } + } + return _instructions; + }, + {} + ) + ); +}, "mapWithFilter"); +var applyInstruction = /* @__PURE__ */ __name((target, source, instructions, targetKey) => { + if (source !== null) { + let instruction = instructions[targetKey]; + if (typeof instruction === "function") { + instruction = [, instruction]; + } + const [filter2 = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction; + if (typeof filter2 === "function" && filter2(source[sourceKey]) || typeof filter2 !== "function" && !!filter2) { + target[targetKey] = valueFn(source[sourceKey]); + } + return; + } + let [filter, value] = instructions[targetKey]; + if (typeof value === "function") { + let _value; + const defaultFilterPassed = filter === void 0 && (_value = value()) != null; + const customFilterPassed = typeof filter === "function" && !!filter(void 0) || typeof filter !== "function" && !!filter; + if (defaultFilterPassed) { + target[targetKey] = _value; + } else if (customFilterPassed) { + target[targetKey] = value(); + } + } else { + const defaultFilterPassed = filter === void 0 && value != null; + const customFilterPassed = typeof filter === "function" && !!filter(value) || typeof filter !== "function" && !!filter; + if (defaultFilterPassed || customFilterPassed) { + target[targetKey] = value; + } + } +}, "applyInstruction"); +var nonNullish = /* @__PURE__ */ __name((_) => _ != null, "nonNullish"); +var pass = /* @__PURE__ */ __name((_) => _, "pass"); + +// src/resolve-path.ts +var resolvedPath = /* @__PURE__ */ __name((resolvedPath2, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => { + if (input != null && input[memberName] !== void 0) { + const labelValue = labelValueProvider(); + if (labelValue.length <= 0) { + throw new Error("Empty value provided for input HTTP label: " + memberName + "."); + } + resolvedPath2 = resolvedPath2.replace( + uriLabel, + isGreedyLabel ? labelValue.split("/").map((segment) => extendedEncodeURIComponent(segment)).join("/") : extendedEncodeURIComponent(labelValue) + ); + } else { + throw new Error("No value provided for input HTTP label: " + memberName + "."); + } + return resolvedPath2; +}, "resolvedPath"); + +// src/ser-utils.ts +var serializeFloat = /* @__PURE__ */ __name((value) => { + if (value !== value) { + return "NaN"; + } + switch (value) { + case Infinity: + return "Infinity"; + case -Infinity: + return "-Infinity"; + default: + return value; + } +}, "serializeFloat"); + +// src/serde-json.ts +var _json = /* @__PURE__ */ __name((obj) => { + if (obj == null) { + return {}; + } + if (Array.isArray(obj)) { + return obj.filter((_) => _ != null).map(_json); + } + if (typeof obj === "object") { + const target = {}; + for (const key of Object.keys(obj)) { + if (obj[key] == null) { + continue; + } + target[key] = _json(obj[key]); + } + return target; + } + return obj; +}, "_json"); + +// src/split-every.ts +function splitEvery(value, delimiter, numDelimiters) { + if (numDelimiters <= 0 || !Number.isInteger(numDelimiters)) { + throw new Error("Invalid number of delimiters (" + numDelimiters + ") for splitEvery."); + } + const segments = value.split(delimiter); + if (numDelimiters === 1) { + return segments; + } + const compoundSegments = []; + let currentSegment = ""; + for (let i = 0; i < segments.length; i++) { + if (currentSegment === "") { + currentSegment = segments[i]; + } else { + currentSegment += delimiter + segments[i]; + } + if ((i + 1) % numDelimiters === 0) { + compoundSegments.push(currentSegment); + currentSegment = ""; + } + } + if (currentSegment !== "") { + compoundSegments.push(currentSegment); + } + return compoundSegments; +} +__name(splitEvery, "splitEvery"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (module.exports = { + NoOpLogger, + Client, + collectBody, + Command, + SENSITIVE_STRING, + createAggregatedClient, + dateToUtcString, + parseRfc3339DateTime, + parseRfc3339DateTimeWithOffset, + parseRfc7231DateTime, + parseEpochTimestamp, + throwDefaultError, + withBaseException, + loadConfigsForDefaultMode, + emitWarningIfUnsupportedVersion, + getDefaultExtensionConfiguration, + getDefaultClientConfiguration, + resolveDefaultRuntimeConfig, + ServiceException, + decorateServiceException, + extendedEncodeURIComponent, + getArrayIfSingleItem, + getValueFromTextNode, + StringWrapper, + LazyJsonString, + map, + convertMap, + take, + parseBoolean, + expectBoolean, + expectNumber, + expectFloat32, + expectLong, + expectInt, + expectInt32, + expectShort, + expectByte, + expectNonNull, + expectObject, + expectString, + expectUnion, + strictParseDouble, + strictParseFloat, + strictParseFloat32, + limitedParseDouble, + handleFloat, + limitedParseFloat, + limitedParseFloat32, + strictParseLong, + strictParseInt, + strictParseInt32, + strictParseShort, + strictParseByte, + logger, + resolvedPath, + serializeFloat, + _json, + splitEvery +}); + diff --git a/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/middleware-stack/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/middleware-stack/dist-cjs/index.js new file mode 100644 index 00000000..18329dd6 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/middleware-stack/dist-cjs/index.js @@ -0,0 +1,318 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + constructStack: () => constructStack +}); +module.exports = __toCommonJS(src_exports); + +// src/MiddlewareStack.ts +var getAllAliases = /* @__PURE__ */ __name((name, aliases) => { + const _aliases = []; + if (name) { + _aliases.push(name); + } + if (aliases) { + for (const alias of aliases) { + _aliases.push(alias); + } + } + return _aliases; +}, "getAllAliases"); +var getMiddlewareNameWithAliases = /* @__PURE__ */ __name((name, aliases) => { + return `${name || "anonymous"}${aliases && aliases.length > 0 ? ` (a.k.a. ${aliases.join(",")})` : ""}`; +}, "getMiddlewareNameWithAliases"); +var constructStack = /* @__PURE__ */ __name(() => { + let absoluteEntries = []; + let relativeEntries = []; + let identifyOnResolve = false; + const entriesNameSet = /* @__PURE__ */ new Set(); + const sort = /* @__PURE__ */ __name((entries) => entries.sort( + (a, b) => stepWeights[b.step] - stepWeights[a.step] || priorityWeights[b.priority || "normal"] - priorityWeights[a.priority || "normal"] + ), "sort"); + const removeByName = /* @__PURE__ */ __name((toRemove) => { + let isRemoved = false; + const filterCb = /* @__PURE__ */ __name((entry) => { + const aliases = getAllAliases(entry.name, entry.aliases); + if (aliases.includes(toRemove)) { + isRemoved = true; + for (const alias of aliases) { + entriesNameSet.delete(alias); + } + return false; + } + return true; + }, "filterCb"); + absoluteEntries = absoluteEntries.filter(filterCb); + relativeEntries = relativeEntries.filter(filterCb); + return isRemoved; + }, "removeByName"); + const removeByReference = /* @__PURE__ */ __name((toRemove) => { + let isRemoved = false; + const filterCb = /* @__PURE__ */ __name((entry) => { + if (entry.middleware === toRemove) { + isRemoved = true; + for (const alias of getAllAliases(entry.name, entry.aliases)) { + entriesNameSet.delete(alias); + } + return false; + } + return true; + }, "filterCb"); + absoluteEntries = absoluteEntries.filter(filterCb); + relativeEntries = relativeEntries.filter(filterCb); + return isRemoved; + }, "removeByReference"); + const cloneTo = /* @__PURE__ */ __name((toStack) => { + var _a; + absoluteEntries.forEach((entry) => { + toStack.add(entry.middleware, { ...entry }); + }); + relativeEntries.forEach((entry) => { + toStack.addRelativeTo(entry.middleware, { ...entry }); + }); + (_a = toStack.identifyOnResolve) == null ? void 0 : _a.call(toStack, stack.identifyOnResolve()); + return toStack; + }, "cloneTo"); + const expandRelativeMiddlewareList = /* @__PURE__ */ __name((from) => { + const expandedMiddlewareList = []; + from.before.forEach((entry) => { + if (entry.before.length === 0 && entry.after.length === 0) { + expandedMiddlewareList.push(entry); + } else { + expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry)); + } + }); + expandedMiddlewareList.push(from); + from.after.reverse().forEach((entry) => { + if (entry.before.length === 0 && entry.after.length === 0) { + expandedMiddlewareList.push(entry); + } else { + expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry)); + } + }); + return expandedMiddlewareList; + }, "expandRelativeMiddlewareList"); + const getMiddlewareList = /* @__PURE__ */ __name((debug = false) => { + const normalizedAbsoluteEntries = []; + const normalizedRelativeEntries = []; + const normalizedEntriesNameMap = {}; + absoluteEntries.forEach((entry) => { + const normalizedEntry = { + ...entry, + before: [], + after: [] + }; + for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) { + normalizedEntriesNameMap[alias] = normalizedEntry; + } + normalizedAbsoluteEntries.push(normalizedEntry); + }); + relativeEntries.forEach((entry) => { + const normalizedEntry = { + ...entry, + before: [], + after: [] + }; + for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) { + normalizedEntriesNameMap[alias] = normalizedEntry; + } + normalizedRelativeEntries.push(normalizedEntry); + }); + normalizedRelativeEntries.forEach((entry) => { + if (entry.toMiddleware) { + const toMiddleware = normalizedEntriesNameMap[entry.toMiddleware]; + if (toMiddleware === void 0) { + if (debug) { + return; + } + throw new Error( + `${entry.toMiddleware} is not found when adding ${getMiddlewareNameWithAliases(entry.name, entry.aliases)} middleware ${entry.relation} ${entry.toMiddleware}` + ); + } + if (entry.relation === "after") { + toMiddleware.after.push(entry); + } + if (entry.relation === "before") { + toMiddleware.before.push(entry); + } + } + }); + const mainChain = sort(normalizedAbsoluteEntries).map(expandRelativeMiddlewareList).reduce((wholeList, expandedMiddlewareList) => { + wholeList.push(...expandedMiddlewareList); + return wholeList; + }, []); + return mainChain; + }, "getMiddlewareList"); + const stack = { + add: (middleware, options = {}) => { + const { name, override, aliases: _aliases } = options; + const entry = { + step: "initialize", + priority: "normal", + middleware, + ...options + }; + const aliases = getAllAliases(name, _aliases); + if (aliases.length > 0) { + if (aliases.some((alias) => entriesNameSet.has(alias))) { + if (!override) + throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`); + for (const alias of aliases) { + const toOverrideIndex = absoluteEntries.findIndex( + (entry2) => { + var _a; + return entry2.name === alias || ((_a = entry2.aliases) == null ? void 0 : _a.some((a) => a === alias)); + } + ); + if (toOverrideIndex === -1) { + continue; + } + const toOverride = absoluteEntries[toOverrideIndex]; + if (toOverride.step !== entry.step || entry.priority !== toOverride.priority) { + throw new Error( + `"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware with ${toOverride.priority} priority in ${toOverride.step} step cannot be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware with ${entry.priority} priority in ${entry.step} step.` + ); + } + absoluteEntries.splice(toOverrideIndex, 1); + } + } + for (const alias of aliases) { + entriesNameSet.add(alias); + } + } + absoluteEntries.push(entry); + }, + addRelativeTo: (middleware, options) => { + const { name, override, aliases: _aliases } = options; + const entry = { + middleware, + ...options + }; + const aliases = getAllAliases(name, _aliases); + if (aliases.length > 0) { + if (aliases.some((alias) => entriesNameSet.has(alias))) { + if (!override) + throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`); + for (const alias of aliases) { + const toOverrideIndex = relativeEntries.findIndex( + (entry2) => { + var _a; + return entry2.name === alias || ((_a = entry2.aliases) == null ? void 0 : _a.some((a) => a === alias)); + } + ); + if (toOverrideIndex === -1) { + continue; + } + const toOverride = relativeEntries[toOverrideIndex]; + if (toOverride.toMiddleware !== entry.toMiddleware || toOverride.relation !== entry.relation) { + throw new Error( + `"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware ${toOverride.relation} "${toOverride.toMiddleware}" middleware cannot be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware ${entry.relation} "${entry.toMiddleware}" middleware.` + ); + } + relativeEntries.splice(toOverrideIndex, 1); + } + } + for (const alias of aliases) { + entriesNameSet.add(alias); + } + } + relativeEntries.push(entry); + }, + clone: () => cloneTo(constructStack()), + use: (plugin) => { + plugin.applyToStack(stack); + }, + remove: (toRemove) => { + if (typeof toRemove === "string") + return removeByName(toRemove); + else + return removeByReference(toRemove); + }, + removeByTag: (toRemove) => { + let isRemoved = false; + const filterCb = /* @__PURE__ */ __name((entry) => { + const { tags, name, aliases: _aliases } = entry; + if (tags && tags.includes(toRemove)) { + const aliases = getAllAliases(name, _aliases); + for (const alias of aliases) { + entriesNameSet.delete(alias); + } + isRemoved = true; + return false; + } + return true; + }, "filterCb"); + absoluteEntries = absoluteEntries.filter(filterCb); + relativeEntries = relativeEntries.filter(filterCb); + return isRemoved; + }, + concat: (from) => { + var _a; + const cloned = cloneTo(constructStack()); + cloned.use(from); + cloned.identifyOnResolve( + identifyOnResolve || cloned.identifyOnResolve() || (((_a = from.identifyOnResolve) == null ? void 0 : _a.call(from)) ?? false) + ); + return cloned; + }, + applyToStack: cloneTo, + identify: () => { + return getMiddlewareList(true).map((mw) => { + const step = mw.step ?? mw.relation + " " + mw.toMiddleware; + return getMiddlewareNameWithAliases(mw.name, mw.aliases) + " - " + step; + }); + }, + identifyOnResolve(toggle) { + if (typeof toggle === "boolean") + identifyOnResolve = toggle; + return identifyOnResolve; + }, + resolve: (handler, context) => { + for (const middleware of getMiddlewareList().map((entry) => entry.middleware).reverse()) { + handler = middleware(handler, context); + } + if (identifyOnResolve) { + console.log(stack.identify()); + } + return handler; + } + }; + return stack; +}, "constructStack"); +var stepWeights = { + initialize: 5, + serialize: 4, + build: 3, + finalizeRequest: 2, + deserialize: 1 +}; +var priorityWeights = { + high: 3, + normal: 2, + low: 1 +}; +// Annotate the CommonJS export names for ESM import in node: + +0 && (module.exports = { + constructStack +}); + diff --git a/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/dist-cjs/getAwsChunkedEncodingStream.js b/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/dist-cjs/getAwsChunkedEncodingStream.js new file mode 100644 index 00000000..4f3f9e73 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/dist-cjs/getAwsChunkedEncodingStream.js @@ -0,0 +1,30 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getAwsChunkedEncodingStream = void 0; +const stream_1 = require("stream"); +const getAwsChunkedEncodingStream = (readableStream, options) => { + const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options; + const checksumRequired = base64Encoder !== undefined && + checksumAlgorithmFn !== undefined && + checksumLocationName !== undefined && + streamHasher !== undefined; + const digest = checksumRequired ? streamHasher(checksumAlgorithmFn, readableStream) : undefined; + const awsChunkedEncodingStream = new stream_1.Readable({ read: () => { } }); + readableStream.on("data", (data) => { + const length = bodyLengthChecker(data) || 0; + awsChunkedEncodingStream.push(`${length.toString(16)}\r\n`); + awsChunkedEncodingStream.push(data); + awsChunkedEncodingStream.push("\r\n"); + }); + readableStream.on("end", async () => { + awsChunkedEncodingStream.push(`0\r\n`); + if (checksumRequired) { + const checksum = base64Encoder(await digest); + awsChunkedEncodingStream.push(`${checksumLocationName}:${checksum}\r\n`); + awsChunkedEncodingStream.push(`\r\n`); + } + awsChunkedEncodingStream.push(null); + }); + return awsChunkedEncodingStream; +}; +exports.getAwsChunkedEncodingStream = getAwsChunkedEncodingStream; diff --git a/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/dist-cjs/index.js new file mode 100644 index 00000000..4031941e --- /dev/null +++ b/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/dist-cjs/index.js @@ -0,0 +1,89 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + Uint8ArrayBlobAdapter: () => Uint8ArrayBlobAdapter +}); +module.exports = __toCommonJS(src_exports); + +// src/blob/transforms.ts +var import_util_base64 = require("@smithy/util-base64"); +var import_util_utf8 = require("@smithy/util-utf8"); +function transformToString(payload, encoding = "utf-8") { + if (encoding === "base64") { + return (0, import_util_base64.toBase64)(payload); + } + return (0, import_util_utf8.toUtf8)(payload); +} +__name(transformToString, "transformToString"); +function transformFromString(str, encoding) { + if (encoding === "base64") { + return Uint8ArrayBlobAdapter.mutate((0, import_util_base64.fromBase64)(str)); + } + return Uint8ArrayBlobAdapter.mutate((0, import_util_utf8.fromUtf8)(str)); +} +__name(transformFromString, "transformFromString"); + +// src/blob/Uint8ArrayBlobAdapter.ts +var _Uint8ArrayBlobAdapter = class _Uint8ArrayBlobAdapter extends Uint8Array { + /** + * @param source - such as a string or Stream. + * @returns a new Uint8ArrayBlobAdapter extending Uint8Array. + */ + static fromString(source, encoding = "utf-8") { + switch (typeof source) { + case "string": + return transformFromString(source, encoding); + default: + throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`); + } + } + /** + * @param source - Uint8Array to be mutated. + * @returns the same Uint8Array but with prototype switched to Uint8ArrayBlobAdapter. + */ + static mutate(source) { + Object.setPrototypeOf(source, _Uint8ArrayBlobAdapter.prototype); + return source; + } + /** + * @param encoding - default 'utf-8'. + * @returns the blob as string. + */ + transformToString(encoding = "utf-8") { + return transformToString(this, encoding); + } +}; +__name(_Uint8ArrayBlobAdapter, "Uint8ArrayBlobAdapter"); +var Uint8ArrayBlobAdapter = _Uint8ArrayBlobAdapter; + +// src/index.ts +__reExport(src_exports, require("././getAwsChunkedEncodingStream"), module.exports); +__reExport(src_exports, require("././sdk-stream-mixin"), module.exports); +// Annotate the CommonJS export names for ESM import in node: + +0 && (module.exports = { + Uint8ArrayBlobAdapter, + getAwsChunkedEncodingStream, + sdkStreamMixin +}); + diff --git a/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.js b/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.js new file mode 100644 index 00000000..c2af3441 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.js @@ -0,0 +1,50 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sdkStreamMixin = void 0; +const node_http_handler_1 = require("@smithy/node-http-handler"); +const util_buffer_from_1 = require("@smithy/util-buffer-from"); +const stream_1 = require("stream"); +const util_1 = require("util"); +const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; +const sdkStreamMixin = (stream) => { + var _a, _b; + if (!(stream instanceof stream_1.Readable)) { + const name = ((_b = (_a = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream; + throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${name}`); + } + let transformed = false; + const transformToByteArray = async () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + transformed = true; + return await (0, node_http_handler_1.streamCollector)(stream); + }; + return Object.assign(stream, { + transformToByteArray, + transformToString: async (encoding) => { + const buf = await transformToByteArray(); + if (encoding === undefined || Buffer.isEncoding(encoding)) { + return (0, util_buffer_from_1.fromArrayBuffer)(buf.buffer, buf.byteOffset, buf.byteLength).toString(encoding); + } + else { + const decoder = new util_1.TextDecoder(encoding); + return decoder.decode(buf); + } + }, + transformToWebStream: () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + if (stream.readableFlowing !== null) { + throw new Error("The stream has been consumed by other callbacks."); + } + if (typeof stream_1.Readable.toWeb !== "function") { + throw new Error("Readable.toWeb() is not supported. Please make sure you are using Node.js >= 17.0.0, or polyfill is available."); + } + transformed = true; + return stream_1.Readable.toWeb(stream); + }, + }); +}; +exports.sdkStreamMixin = sdkStreamMixin; diff --git a/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/node-http-handler/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/node-http-handler/dist-cjs/index.js new file mode 100644 index 00000000..33f84613 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/node-http-handler/dist-cjs/index.js @@ -0,0 +1,687 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + DEFAULT_REQUEST_TIMEOUT: () => DEFAULT_REQUEST_TIMEOUT, + NodeHttp2Handler: () => NodeHttp2Handler, + NodeHttpHandler: () => NodeHttpHandler, + streamCollector: () => streamCollector +}); +module.exports = __toCommonJS(src_exports); + +// src/node-http-handler.ts +var import_protocol_http = require("@smithy/protocol-http"); +var import_querystring_builder = require("@smithy/querystring-builder"); +var import_http = require("http"); +var import_https = require("https"); + +// src/constants.ts +var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"]; + +// src/get-transformed-headers.ts +var getTransformedHeaders = /* @__PURE__ */ __name((headers) => { + const transformedHeaders = {}; + for (const name of Object.keys(headers)) { + const headerValues = headers[name]; + transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues; + } + return transformedHeaders; +}, "getTransformedHeaders"); + +// src/set-connection-timeout.ts +var setConnectionTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = 0) => { + if (!timeoutInMs) { + return; + } + const timeoutId = setTimeout(() => { + request.destroy(); + reject( + Object.assign(new Error(`Socket timed out without establishing a connection within ${timeoutInMs} ms`), { + name: "TimeoutError" + }) + ); + }, timeoutInMs); + request.on("socket", (socket) => { + if (socket.connecting) { + socket.on("connect", () => { + clearTimeout(timeoutId); + }); + } else { + clearTimeout(timeoutId); + } + }); +}, "setConnectionTimeout"); + +// src/set-socket-keep-alive.ts +var setSocketKeepAlive = /* @__PURE__ */ __name((request, { keepAlive, keepAliveMsecs }) => { + if (keepAlive !== true) { + return; + } + request.on("socket", (socket) => { + socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); + }); +}, "setSocketKeepAlive"); + +// src/set-socket-timeout.ts +var setSocketTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = 0) => { + request.setTimeout(timeoutInMs, () => { + request.destroy(); + reject(Object.assign(new Error(`Connection timed out after ${timeoutInMs} ms`), { name: "TimeoutError" })); + }); +}, "setSocketTimeout"); + +// src/write-request-body.ts +var import_stream = require("stream"); +var MIN_WAIT_TIME = 1e3; +async function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME) { + const headers = request.headers ?? {}; + const expect = headers["Expect"] || headers["expect"]; + let timeoutId = -1; + let hasError = false; + if (expect === "100-continue") { + await Promise.race([ + new Promise((resolve) => { + timeoutId = Number(setTimeout(resolve, Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs))); + }), + new Promise((resolve) => { + httpRequest.on("continue", () => { + clearTimeout(timeoutId); + resolve(); + }); + httpRequest.on("error", () => { + hasError = true; + clearTimeout(timeoutId); + resolve(); + }); + }) + ]); + } + if (!hasError) { + writeBody(httpRequest, request.body); + } +} +__name(writeRequestBody, "writeRequestBody"); +function writeBody(httpRequest, body) { + if (body instanceof import_stream.Readable) { + body.pipe(httpRequest); + return; + } + if (body) { + if (Buffer.isBuffer(body) || typeof body === "string") { + httpRequest.end(body); + return; + } + const uint8 = body; + if (typeof uint8 === "object" && uint8.buffer && typeof uint8.byteOffset === "number" && typeof uint8.byteLength === "number") { + httpRequest.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength)); + return; + } + httpRequest.end(Buffer.from(body)); + return; + } + httpRequest.end(); +} +__name(writeBody, "writeBody"); + +// src/node-http-handler.ts +var DEFAULT_REQUEST_TIMEOUT = 0; +var _NodeHttpHandler = class _NodeHttpHandler { + constructor(options) { + this.socketWarningTimestamp = 0; + // Node http handler is hard-coded to http/1.1: https://github.com/nodejs/node/blob/ff5664b83b89c55e4ab5d5f60068fb457f1f5872/lib/_http_server.js#L286 + this.metadata = { handlerProtocol: "http/1.1" }; + this.configProvider = new Promise((resolve, reject) => { + if (typeof options === "function") { + options().then((_options) => { + resolve(this.resolveDefaultConfig(_options)); + }).catch(reject); + } else { + resolve(this.resolveDefaultConfig(options)); + } + }); + } + /** + * @returns the input if it is an HttpHandler of any class, + * or instantiates a new instance of this handler. + */ + static create(instanceOrOptions) { + if (typeof (instanceOrOptions == null ? void 0 : instanceOrOptions.handle) === "function") { + return instanceOrOptions; + } + return new _NodeHttpHandler(instanceOrOptions); + } + /** + * @internal + * + * @param agent - http(s) agent in use by the NodeHttpHandler instance. + * @returns timestamp of last emitted warning. + */ + static checkSocketUsage(agent, socketWarningTimestamp) { + var _a, _b; + const { sockets, requests, maxSockets } = agent; + if (typeof maxSockets !== "number" || maxSockets === Infinity) { + return socketWarningTimestamp; + } + const interval = 15e3; + if (Date.now() - interval < socketWarningTimestamp) { + return socketWarningTimestamp; + } + if (sockets && requests) { + for (const origin in sockets) { + const socketsInUse = ((_a = sockets[origin]) == null ? void 0 : _a.length) ?? 0; + const requestsEnqueued = ((_b = requests[origin]) == null ? void 0 : _b.length) ?? 0; + if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) { + console.warn( + "@smithy/node-http-handler:WARN", + `socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued.`, + "See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html", + "or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config." + ); + return Date.now(); + } + } + } + return socketWarningTimestamp; + } + resolveDefaultConfig(options) { + const { requestTimeout, connectionTimeout, socketTimeout, httpAgent, httpsAgent } = options || {}; + const keepAlive = true; + const maxSockets = 50; + return { + connectionTimeout, + requestTimeout: requestTimeout ?? socketTimeout, + httpAgent: (() => { + if (httpAgent instanceof import_http.Agent || typeof (httpAgent == null ? void 0 : httpAgent.destroy) === "function") { + return httpAgent; + } + return new import_http.Agent({ keepAlive, maxSockets, ...httpAgent }); + })(), + httpsAgent: (() => { + if (httpsAgent instanceof import_https.Agent || typeof (httpsAgent == null ? void 0 : httpsAgent.destroy) === "function") { + return httpsAgent; + } + return new import_https.Agent({ keepAlive, maxSockets, ...httpsAgent }); + })() + }; + } + destroy() { + var _a, _b, _c, _d; + (_b = (_a = this.config) == null ? void 0 : _a.httpAgent) == null ? void 0 : _b.destroy(); + (_d = (_c = this.config) == null ? void 0 : _c.httpsAgent) == null ? void 0 : _d.destroy(); + } + async handle(request, { abortSignal } = {}) { + if (!this.config) { + this.config = await this.configProvider; + } + let socketCheckTimeoutId; + return new Promise((_resolve, _reject) => { + let writeRequestBodyPromise = void 0; + const resolve = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + clearTimeout(socketCheckTimeoutId); + _resolve(arg); + }, "resolve"); + const reject = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + _reject(arg); + }, "reject"); + if (!this.config) { + throw new Error("Node HTTP request handler config is not resolved"); + } + if (abortSignal == null ? void 0 : abortSignal.aborted) { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + return; + } + const isSSL = request.protocol === "https:"; + const agent = isSSL ? this.config.httpsAgent : this.config.httpAgent; + socketCheckTimeoutId = setTimeout(() => { + this.socketWarningTimestamp = _NodeHttpHandler.checkSocketUsage(agent, this.socketWarningTimestamp); + }, this.config.socketAcquisitionWarningTimeout ?? (this.config.requestTimeout ?? 2e3) + (this.config.connectionTimeout ?? 1e3)); + const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); + let auth = void 0; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}`; + } + let path = request.path; + if (queryString) { + path += `?${queryString}`; + } + if (request.fragment) { + path += `#${request.fragment}`; + } + const nodeHttpsOptions = { + headers: request.headers, + host: request.hostname, + method: request.method, + path, + port: request.port, + agent, + auth + }; + const requestFunc = isSSL ? import_https.request : import_http.request; + const req = requestFunc(nodeHttpsOptions, (res) => { + const httpResponse = new import_protocol_http.HttpResponse({ + statusCode: res.statusCode || -1, + reason: res.statusMessage, + headers: getTransformedHeaders(res.headers), + body: res + }); + resolve({ response: httpResponse }); + }); + req.on("error", (err) => { + if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) { + reject(Object.assign(err, { name: "TimeoutError" })); + } else { + reject(err); + } + }); + setConnectionTimeout(req, reject, this.config.connectionTimeout); + setSocketTimeout(req, reject, this.config.requestTimeout); + if (abortSignal) { + abortSignal.onabort = () => { + req.abort(); + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + }; + } + const httpAgent = nodeHttpsOptions.agent; + if (typeof httpAgent === "object" && "keepAlive" in httpAgent) { + setSocketKeepAlive(req, { + // @ts-expect-error keepAlive is not public on httpAgent. + keepAlive: httpAgent.keepAlive, + // @ts-expect-error keepAliveMsecs is not public on httpAgent. + keepAliveMsecs: httpAgent.keepAliveMsecs + }); + } + writeRequestBodyPromise = writeRequestBody(req, request, this.config.requestTimeout).catch(_reject); + }); + } + updateHttpClientConfig(key, value) { + this.config = void 0; + this.configProvider = this.configProvider.then((config) => { + return { + ...config, + [key]: value + }; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; + } +}; +__name(_NodeHttpHandler, "NodeHttpHandler"); +var NodeHttpHandler = _NodeHttpHandler; + +// src/node-http2-handler.ts + + +var import_http22 = require("http2"); + +// src/node-http2-connection-manager.ts +var import_http2 = __toESM(require("http2")); + +// src/node-http2-connection-pool.ts +var _NodeHttp2ConnectionPool = class _NodeHttp2ConnectionPool { + constructor(sessions) { + this.sessions = []; + this.sessions = sessions ?? []; + } + poll() { + if (this.sessions.length > 0) { + return this.sessions.shift(); + } + } + offerLast(session) { + this.sessions.push(session); + } + contains(session) { + return this.sessions.includes(session); + } + remove(session) { + this.sessions = this.sessions.filter((s) => s !== session); + } + [Symbol.iterator]() { + return this.sessions[Symbol.iterator](); + } + destroy(connection) { + for (const session of this.sessions) { + if (session === connection) { + if (!session.destroyed) { + session.destroy(); + } + } + } + } +}; +__name(_NodeHttp2ConnectionPool, "NodeHttp2ConnectionPool"); +var NodeHttp2ConnectionPool = _NodeHttp2ConnectionPool; + +// src/node-http2-connection-manager.ts +var _NodeHttp2ConnectionManager = class _NodeHttp2ConnectionManager { + constructor(config) { + this.sessionCache = /* @__PURE__ */ new Map(); + this.config = config; + if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) { + throw new RangeError("maxConcurrency must be greater than zero."); + } + } + lease(requestContext, connectionConfiguration) { + const url = this.getUrlString(requestContext); + const existingPool = this.sessionCache.get(url); + if (existingPool) { + const existingSession = existingPool.poll(); + if (existingSession && !this.config.disableConcurrency) { + return existingSession; + } + } + const session = import_http2.default.connect(url); + if (this.config.maxConcurrency) { + session.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err) => { + if (err) { + throw new Error( + "Fail to set maxConcurrentStreams to " + this.config.maxConcurrency + "when creating new session for " + requestContext.destination.toString() + ); + } + }); + } + session.unref(); + const destroySessionCb = /* @__PURE__ */ __name(() => { + session.destroy(); + this.deleteSession(url, session); + }, "destroySessionCb"); + session.on("goaway", destroySessionCb); + session.on("error", destroySessionCb); + session.on("frameError", destroySessionCb); + session.on("close", () => this.deleteSession(url, session)); + if (connectionConfiguration.requestTimeout) { + session.setTimeout(connectionConfiguration.requestTimeout, destroySessionCb); + } + const connectionPool = this.sessionCache.get(url) || new NodeHttp2ConnectionPool(); + connectionPool.offerLast(session); + this.sessionCache.set(url, connectionPool); + return session; + } + /** + * Delete a session from the connection pool. + * @param authority The authority of the session to delete. + * @param session The session to delete. + */ + deleteSession(authority, session) { + const existingConnectionPool = this.sessionCache.get(authority); + if (!existingConnectionPool) { + return; + } + if (!existingConnectionPool.contains(session)) { + return; + } + existingConnectionPool.remove(session); + this.sessionCache.set(authority, existingConnectionPool); + } + release(requestContext, session) { + var _a; + const cacheKey = this.getUrlString(requestContext); + (_a = this.sessionCache.get(cacheKey)) == null ? void 0 : _a.offerLast(session); + } + destroy() { + for (const [key, connectionPool] of this.sessionCache) { + for (const session of connectionPool) { + if (!session.destroyed) { + session.destroy(); + } + connectionPool.remove(session); + } + this.sessionCache.delete(key); + } + } + setMaxConcurrentStreams(maxConcurrentStreams) { + if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) { + throw new RangeError("maxConcurrentStreams must be greater than zero."); + } + this.config.maxConcurrency = maxConcurrentStreams; + } + setDisableConcurrentStreams(disableConcurrentStreams) { + this.config.disableConcurrency = disableConcurrentStreams; + } + getUrlString(request) { + return request.destination.toString(); + } +}; +__name(_NodeHttp2ConnectionManager, "NodeHttp2ConnectionManager"); +var NodeHttp2ConnectionManager = _NodeHttp2ConnectionManager; + +// src/node-http2-handler.ts +var _NodeHttp2Handler = class _NodeHttp2Handler { + constructor(options) { + this.metadata = { handlerProtocol: "h2" }; + this.connectionManager = new NodeHttp2ConnectionManager({}); + this.configProvider = new Promise((resolve, reject) => { + if (typeof options === "function") { + options().then((opts) => { + resolve(opts || {}); + }).catch(reject); + } else { + resolve(options || {}); + } + }); + } + /** + * @returns the input if it is an HttpHandler of any class, + * or instantiates a new instance of this handler. + */ + static create(instanceOrOptions) { + if (typeof (instanceOrOptions == null ? void 0 : instanceOrOptions.handle) === "function") { + return instanceOrOptions; + } + return new _NodeHttp2Handler(instanceOrOptions); + } + destroy() { + this.connectionManager.destroy(); + } + async handle(request, { abortSignal } = {}) { + if (!this.config) { + this.config = await this.configProvider; + this.connectionManager.setDisableConcurrentStreams(this.config.disableConcurrentStreams || false); + if (this.config.maxConcurrentStreams) { + this.connectionManager.setMaxConcurrentStreams(this.config.maxConcurrentStreams); + } + } + const { requestTimeout, disableConcurrentStreams } = this.config; + return new Promise((_resolve, _reject) => { + var _a; + let fulfilled = false; + let writeRequestBodyPromise = void 0; + const resolve = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + _resolve(arg); + }, "resolve"); + const reject = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + _reject(arg); + }, "reject"); + if (abortSignal == null ? void 0 : abortSignal.aborted) { + fulfilled = true; + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + return; + } + const { hostname, method, port, protocol, query } = request; + let auth = ""; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}@`; + } + const authority = `${protocol}//${auth}${hostname}${port ? `:${port}` : ""}`; + const requestContext = { destination: new URL(authority) }; + const session = this.connectionManager.lease(requestContext, { + requestTimeout: (_a = this.config) == null ? void 0 : _a.sessionTimeout, + disableConcurrentStreams: disableConcurrentStreams || false + }); + const rejectWithDestroy = /* @__PURE__ */ __name((err) => { + if (disableConcurrentStreams) { + this.destroySession(session); + } + fulfilled = true; + reject(err); + }, "rejectWithDestroy"); + const queryString = (0, import_querystring_builder.buildQueryString)(query || {}); + let path = request.path; + if (queryString) { + path += `?${queryString}`; + } + if (request.fragment) { + path += `#${request.fragment}`; + } + const req = session.request({ + ...request.headers, + [import_http22.constants.HTTP2_HEADER_PATH]: path, + [import_http22.constants.HTTP2_HEADER_METHOD]: method + }); + session.ref(); + req.on("response", (headers) => { + const httpResponse = new import_protocol_http.HttpResponse({ + statusCode: headers[":status"] || -1, + headers: getTransformedHeaders(headers), + body: req + }); + fulfilled = true; + resolve({ response: httpResponse }); + if (disableConcurrentStreams) { + session.close(); + this.connectionManager.deleteSession(authority, session); + } + }); + if (requestTimeout) { + req.setTimeout(requestTimeout, () => { + req.close(); + const timeoutError = new Error(`Stream timed out because of no activity for ${requestTimeout} ms`); + timeoutError.name = "TimeoutError"; + rejectWithDestroy(timeoutError); + }); + } + if (abortSignal) { + abortSignal.onabort = () => { + req.close(); + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + rejectWithDestroy(abortError); + }; + } + req.on("frameError", (type, code, id) => { + rejectWithDestroy(new Error(`Frame type id ${type} in stream id ${id} has failed with code ${code}.`)); + }); + req.on("error", rejectWithDestroy); + req.on("aborted", () => { + rejectWithDestroy( + new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${req.rstCode}.`) + ); + }); + req.on("close", () => { + session.unref(); + if (disableConcurrentStreams) { + session.destroy(); + } + if (!fulfilled) { + rejectWithDestroy(new Error("Unexpected error: http2 request did not get a response")); + } + }); + writeRequestBodyPromise = writeRequestBody(req, request, requestTimeout); + }); + } + updateHttpClientConfig(key, value) { + this.config = void 0; + this.configProvider = this.configProvider.then((config) => { + return { + ...config, + [key]: value + }; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; + } + /** + * Destroys a session. + * @param session The session to destroy. + */ + destroySession(session) { + if (!session.destroyed) { + session.destroy(); + } + } +}; +__name(_NodeHttp2Handler, "NodeHttp2Handler"); +var NodeHttp2Handler = _NodeHttp2Handler; + +// src/stream-collector/collector.ts + +var _Collector = class _Collector extends import_stream.Writable { + constructor() { + super(...arguments); + this.bufferedBytes = []; + } + _write(chunk, encoding, callback) { + this.bufferedBytes.push(chunk); + callback(); + } +}; +__name(_Collector, "Collector"); +var Collector = _Collector; + +// src/stream-collector/index.ts +var streamCollector = /* @__PURE__ */ __name((stream) => new Promise((resolve, reject) => { + const collector = new Collector(); + stream.pipe(collector); + stream.on("error", (err) => { + collector.end(); + reject(err); + }); + collector.on("error", reject); + collector.on("finish", function() { + const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes)); + resolve(bytes); + }); +}), "streamCollector"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (module.exports = { + DEFAULT_REQUEST_TIMEOUT, + NodeHttpHandler, + NodeHttp2Handler, + streamCollector +}); + diff --git a/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/node-http-handler/node_modules/@smithy/querystring-builder/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/node-http-handler/node_modules/@smithy/querystring-builder/dist-cjs/index.js new file mode 100644 index 00000000..70302425 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/node-http-handler/node_modules/@smithy/querystring-builder/dist-cjs/index.js @@ -0,0 +1,52 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + buildQueryString: () => buildQueryString +}); +module.exports = __toCommonJS(src_exports); +var import_util_uri_escape = require("@smithy/util-uri-escape"); +function buildQueryString(query) { + const parts = []; + for (let key of Object.keys(query).sort()) { + const value = query[key]; + key = (0, import_util_uri_escape.escapeUri)(key); + if (Array.isArray(value)) { + for (let i = 0, iLen = value.length; i < iLen; i++) { + parts.push(`${key}=${(0, import_util_uri_escape.escapeUri)(value[i])}`); + } + } else { + let qsEntry = key; + if (value || typeof value === "string") { + qsEntry += `=${(0, import_util_uri_escape.escapeUri)(value)}`; + } + parts.push(qsEntry); + } + } + return parts.join("&"); +} +__name(buildQueryString, "buildQueryString"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (module.exports = { + buildQueryString +}); + diff --git a/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/node-http-handler/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/node-http-handler/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js new file mode 100644 index 00000000..51001efe --- /dev/null +++ b/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/node-http-handler/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js @@ -0,0 +1,43 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + escapeUri: () => escapeUri, + escapeUriPath: () => escapeUriPath +}); +module.exports = __toCommonJS(src_exports); + +// src/escape-uri.ts +var escapeUri = /* @__PURE__ */ __name((uri) => ( + // AWS percent-encodes some extra non-standard characters in a URI + encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode) +), "escapeUri"); +var hexEncode = /* @__PURE__ */ __name((c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`, "hexEncode"); + +// src/escape-uri-path.ts +var escapeUriPath = /* @__PURE__ */ __name((uri) => uri.split("/").map(escapeUri).join("/"), "escapeUriPath"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (module.exports = { + escapeUri, + escapeUriPath +}); + diff --git a/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/util-utf8/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/util-utf8/dist-cjs/index.js new file mode 100644 index 00000000..0b22680a --- /dev/null +++ b/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/util-utf8/dist-cjs/index.js @@ -0,0 +1,65 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + fromUtf8: () => fromUtf8, + toUint8Array: () => toUint8Array, + toUtf8: () => toUtf8 +}); +module.exports = __toCommonJS(src_exports); + +// src/fromUtf8.ts +var import_util_buffer_from = require("@smithy/util-buffer-from"); +var fromUtf8 = /* @__PURE__ */ __name((input) => { + const buf = (0, import_util_buffer_from.fromString)(input, "utf8"); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); +}, "fromUtf8"); + +// src/toUint8Array.ts +var toUint8Array = /* @__PURE__ */ __name((data) => { + if (typeof data === "string") { + return fromUtf8(data); + } + if (ArrayBuffer.isView(data)) { + return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); + } + return new Uint8Array(data); +}, "toUint8Array"); + +// src/toUtf8.ts + +var toUtf8 = /* @__PURE__ */ __name((input) => { + if (typeof input === "string") { + return input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); + } + return (0, import_util_buffer_from.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); +}, "toUtf8"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (module.exports = { + fromUtf8, + toUint8Array, + toUtf8 +}); + diff --git a/claude-code-source/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/types/dist-cjs/index.js new file mode 100644 index 00000000..b22a90a6 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/types/dist-cjs/index.js @@ -0,0 +1,149 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + AlgorithmId: () => AlgorithmId, + EndpointURLScheme: () => EndpointURLScheme, + FieldPosition: () => FieldPosition, + HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, + HttpAuthLocation: () => HttpAuthLocation, + IniSectionType: () => IniSectionType, + RequestHandlerProtocol: () => RequestHandlerProtocol, + SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, + getDefaultClientConfiguration: () => getDefaultClientConfiguration, + resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig +}); +module.exports = __toCommonJS(src_exports); + +// src/auth/auth.ts +var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { + HttpAuthLocation2["HEADER"] = "header"; + HttpAuthLocation2["QUERY"] = "query"; + return HttpAuthLocation2; +})(HttpAuthLocation || {}); + +// src/auth/HttpApiKeyAuth.ts +var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { + HttpApiKeyAuthLocation2["HEADER"] = "header"; + HttpApiKeyAuthLocation2["QUERY"] = "query"; + return HttpApiKeyAuthLocation2; +})(HttpApiKeyAuthLocation || {}); + +// src/endpoint.ts +var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { + EndpointURLScheme2["HTTP"] = "http"; + EndpointURLScheme2["HTTPS"] = "https"; + return EndpointURLScheme2; +})(EndpointURLScheme || {}); + +// src/extensions/checksum.ts +var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { + AlgorithmId2["MD5"] = "md5"; + AlgorithmId2["CRC32"] = "crc32"; + AlgorithmId2["CRC32C"] = "crc32c"; + AlgorithmId2["SHA1"] = "sha1"; + AlgorithmId2["SHA256"] = "sha256"; + return AlgorithmId2; +})(AlgorithmId || {}); +var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== void 0) { + checksumAlgorithms.push({ + algorithmId: () => "sha256" /* SHA256 */, + checksumConstructor: () => runtimeConfig.sha256 + }); + } + if (runtimeConfig.md5 != void 0) { + checksumAlgorithms.push({ + algorithmId: () => "md5" /* MD5 */, + checksumConstructor: () => runtimeConfig.md5 + }); + } + return { + _checksumAlgorithms: checksumAlgorithms, + addChecksumAlgorithm(algo) { + this._checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return this._checksumAlgorithms; + } + }; +}, "getChecksumConfiguration"); +var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}, "resolveChecksumRuntimeConfig"); + +// src/extensions/defaultClientConfiguration.ts +var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + return { + ...getChecksumConfiguration(runtimeConfig) + }; +}, "getDefaultClientConfiguration"); +var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { + return { + ...resolveChecksumRuntimeConfig(config) + }; +}, "resolveDefaultRuntimeConfig"); + +// src/http.ts +var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { + FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; + FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; + return FieldPosition2; +})(FieldPosition || {}); + +// src/middleware.ts +var SMITHY_CONTEXT_KEY = "__smithy_context"; + +// src/profile.ts +var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { + IniSectionType2["PROFILE"] = "profile"; + IniSectionType2["SSO_SESSION"] = "sso-session"; + IniSectionType2["SERVICES"] = "services"; + return IniSectionType2; +})(IniSectionType || {}); + +// src/transfer.ts +var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { + RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; + return RequestHandlerProtocol2; +})(RequestHandlerProtocol || {}); +// Annotate the CommonJS export names for ESM import in node: + +0 && (module.exports = { + HttpAuthLocation, + HttpApiKeyAuthLocation, + EndpointURLScheme, + AlgorithmId, + getDefaultClientConfiguration, + resolveDefaultRuntimeConfig, + FieldPosition, + SMITHY_CONTEXT_KEY, + IniSectionType, + RequestHandlerProtocol +}); + diff --git a/claude-code-source/node_modules/@smithy/url-parser/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/url-parser/dist-cjs/index.js new file mode 100644 index 00000000..ddc21b01 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/url-parser/dist-cjs/index.js @@ -0,0 +1,23 @@ +'use strict'; + +var querystringParser = require('@smithy/querystring-parser'); + +const parseUrl = (url) => { + if (typeof url === "string") { + return parseUrl(new URL(url)); + } + const { hostname, pathname, port, protocol, search } = url; + let query; + if (search) { + query = querystringParser.parseQueryString(search); + } + return { + hostname, + port: port ? parseInt(port) : undefined, + protocol, + path: pathname, + query, + }; +}; + +exports.parseUrl = parseUrl; diff --git a/claude-code-source/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js b/claude-code-source/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js new file mode 100644 index 00000000..b06a7b87 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromBase64 = void 0; +const util_buffer_from_1 = require("@smithy/util-buffer-from"); +const BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; +const fromBase64 = (input) => { + if ((input.length * 3) % 4 !== 0) { + throw new TypeError(`Incorrect padding on base64 string.`); + } + if (!BASE64_REGEX.exec(input)) { + throw new TypeError(`Invalid base64 string.`); + } + const buffer = (0, util_buffer_from_1.fromString)(input, "base64"); + return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); +}; +exports.fromBase64 = fromBase64; diff --git a/claude-code-source/node_modules/@smithy/util-base64/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-base64/dist-cjs/index.js new file mode 100644 index 00000000..02848d02 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-base64/dist-cjs/index.js @@ -0,0 +1,27 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +module.exports = __toCommonJS(src_exports); +__reExport(src_exports, require("././fromBase64"), module.exports); +__reExport(src_exports, require("././toBase64"), module.exports); +// Annotate the CommonJS export names for ESM import in node: + +0 && (module.exports = { + fromBase64, + toBase64 +}); + diff --git a/claude-code-source/node_modules/@smithy/util-base64/dist-cjs/toBase64.js b/claude-code-source/node_modules/@smithy/util-base64/dist-cjs/toBase64.js new file mode 100644 index 00000000..0590ce3f --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-base64/dist-cjs/toBase64.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.toBase64 = void 0; +const util_buffer_from_1 = require("@smithy/util-buffer-from"); +const util_utf8_1 = require("@smithy/util-utf8"); +const toBase64 = (_input) => { + let input; + if (typeof _input === "string") { + input = (0, util_utf8_1.fromUtf8)(_input); + } + else { + input = _input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); + } + return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64"); +}; +exports.toBase64 = toBase64; diff --git a/claude-code-source/node_modules/@smithy/util-base64/node_modules/@smithy/util-utf8/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-base64/node_modules/@smithy/util-utf8/dist-cjs/index.js new file mode 100644 index 00000000..0b22680a --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-base64/node_modules/@smithy/util-utf8/dist-cjs/index.js @@ -0,0 +1,65 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + fromUtf8: () => fromUtf8, + toUint8Array: () => toUint8Array, + toUtf8: () => toUtf8 +}); +module.exports = __toCommonJS(src_exports); + +// src/fromUtf8.ts +var import_util_buffer_from = require("@smithy/util-buffer-from"); +var fromUtf8 = /* @__PURE__ */ __name((input) => { + const buf = (0, import_util_buffer_from.fromString)(input, "utf8"); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); +}, "fromUtf8"); + +// src/toUint8Array.ts +var toUint8Array = /* @__PURE__ */ __name((data) => { + if (typeof data === "string") { + return fromUtf8(data); + } + if (ArrayBuffer.isView(data)) { + return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); + } + return new Uint8Array(data); +}, "toUint8Array"); + +// src/toUtf8.ts + +var toUtf8 = /* @__PURE__ */ __name((input) => { + if (typeof input === "string") { + return input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); + } + return (0, import_util_buffer_from.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); +}, "toUtf8"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (module.exports = { + fromUtf8, + toUint8Array, + toUtf8 +}); + diff --git a/claude-code-source/node_modules/@smithy/util-body-length-browser/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-body-length-browser/dist-cjs/index.js new file mode 100644 index 00000000..5cf421cb --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-body-length-browser/dist-cjs/index.js @@ -0,0 +1,30 @@ +'use strict'; + +const TEXT_ENCODER = typeof TextEncoder == "function" ? new TextEncoder() : null; +const calculateBodyLength = (body) => { + if (typeof body === "string") { + if (TEXT_ENCODER) { + return TEXT_ENCODER.encode(body).byteLength; + } + let len = body.length; + for (let i = len - 1; i >= 0; i--) { + const code = body.charCodeAt(i); + if (code > 0x7f && code <= 0x7ff) + len++; + else if (code > 0x7ff && code <= 0xffff) + len += 2; + if (code >= 0xdc00 && code <= 0xdfff) + i--; + } + return len; + } + else if (typeof body.byteLength === "number") { + return body.byteLength; + } + else if (typeof body.size === "number") { + return body.size; + } + throw new Error(`Body Length computation failed for ${body}`); +}; + +exports.calculateBodyLength = calculateBodyLength; diff --git a/claude-code-source/node_modules/@smithy/util-body-length-node/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-body-length-node/dist-cjs/index.js new file mode 100644 index 00000000..a388e288 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-body-length-node/dist-cjs/index.js @@ -0,0 +1,32 @@ +'use strict'; + +var node_fs = require('node:fs'); + +const calculateBodyLength = (body) => { + if (!body) { + return 0; + } + if (typeof body === "string") { + return Buffer.byteLength(body); + } + else if (typeof body.byteLength === "number") { + return body.byteLength; + } + else if (typeof body.size === "number") { + return body.size; + } + else if (typeof body.start === "number" && typeof body.end === "number") { + return body.end + 1 - body.start; + } + else if (body instanceof node_fs.ReadStream) { + if (body.path != null) { + return node_fs.lstatSync(body.path).size; + } + else if (typeof body.fd === "number") { + return node_fs.fstatSync(body.fd).size; + } + } + throw new Error(`Body Length computation failed for ${body}`); +}; + +exports.calculateBodyLength = calculateBodyLength; diff --git a/claude-code-source/node_modules/@smithy/util-buffer-from/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-buffer-from/dist-cjs/index.js new file mode 100644 index 00000000..c6738d94 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-buffer-from/dist-cjs/index.js @@ -0,0 +1,47 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + fromArrayBuffer: () => fromArrayBuffer, + fromString: () => fromString +}); +module.exports = __toCommonJS(src_exports); +var import_is_array_buffer = require("@smithy/is-array-buffer"); +var import_buffer = require("buffer"); +var fromArrayBuffer = /* @__PURE__ */ __name((input, offset = 0, length = input.byteLength - offset) => { + if (!(0, import_is_array_buffer.isArrayBuffer)(input)) { + throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); + } + return import_buffer.Buffer.from(input, offset, length); +}, "fromArrayBuffer"); +var fromString = /* @__PURE__ */ __name((input, encoding) => { + if (typeof input !== "string") { + throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); + } + return encoding ? import_buffer.Buffer.from(input, encoding) : import_buffer.Buffer.from(input); +}, "fromString"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (module.exports = { + fromArrayBuffer, + fromString +}); + diff --git a/claude-code-source/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js new file mode 100644 index 00000000..5d792e71 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js @@ -0,0 +1,32 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + isArrayBuffer: () => isArrayBuffer +}); +module.exports = __toCommonJS(src_exports); +var isArrayBuffer = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]", "isArrayBuffer"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (module.exports = { + isArrayBuffer +}); + diff --git a/claude-code-source/node_modules/@smithy/util-config-provider/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-config-provider/dist-cjs/index.js new file mode 100644 index 00000000..52d176d5 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-config-provider/dist-cjs/index.js @@ -0,0 +1,30 @@ +'use strict'; + +const booleanSelector = (obj, key, type) => { + if (!(key in obj)) + return undefined; + if (obj[key] === "true") + return true; + if (obj[key] === "false") + return false; + throw new Error(`Cannot load ${type} "${key}". Expected "true" or "false", got ${obj[key]}.`); +}; + +const numberSelector = (obj, key, type) => { + if (!(key in obj)) + return undefined; + const numberValue = parseInt(obj[key], 10); + if (Number.isNaN(numberValue)) { + throw new TypeError(`Cannot load ${type} '${key}'. Expected number, got '${obj[key]}'.`); + } + return numberValue; +}; + +exports.SelectorType = void 0; +(function (SelectorType) { + SelectorType["ENV"] = "env"; + SelectorType["CONFIG"] = "shared config entry"; +})(exports.SelectorType || (exports.SelectorType = {})); + +exports.booleanSelector = booleanSelector; +exports.numberSelector = numberSelector; diff --git a/claude-code-source/node_modules/@smithy/util-defaults-mode-node/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-defaults-mode-node/dist-cjs/index.js new file mode 100644 index 00000000..9fae1b10 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-defaults-mode-node/dist-cjs/index.js @@ -0,0 +1,74 @@ +'use strict'; + +var configResolver = require('@smithy/config-resolver'); +var nodeConfigProvider = require('@smithy/node-config-provider'); +var propertyProvider = require('@smithy/property-provider'); + +const AWS_EXECUTION_ENV = "AWS_EXECUTION_ENV"; +const AWS_REGION_ENV = "AWS_REGION"; +const AWS_DEFAULT_REGION_ENV = "AWS_DEFAULT_REGION"; +const ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED"; +const DEFAULTS_MODE_OPTIONS = ["in-region", "cross-region", "mobile", "standard", "legacy"]; +const IMDS_REGION_PATH = "/latest/meta-data/placement/region"; + +const AWS_DEFAULTS_MODE_ENV = "AWS_DEFAULTS_MODE"; +const AWS_DEFAULTS_MODE_CONFIG = "defaults_mode"; +const NODE_DEFAULTS_MODE_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => { + return env[AWS_DEFAULTS_MODE_ENV]; + }, + configFileSelector: (profile) => { + return profile[AWS_DEFAULTS_MODE_CONFIG]; + }, + default: "legacy", +}; + +const resolveDefaultsModeConfig = ({ region = nodeConfigProvider.loadConfig(configResolver.NODE_REGION_CONFIG_OPTIONS), defaultsMode = nodeConfigProvider.loadConfig(NODE_DEFAULTS_MODE_CONFIG_OPTIONS), } = {}) => propertyProvider.memoize(async () => { + const mode = typeof defaultsMode === "function" ? await defaultsMode() : defaultsMode; + switch (mode?.toLowerCase()) { + case "auto": + return resolveNodeDefaultsModeAuto(region); + case "in-region": + case "cross-region": + case "mobile": + case "standard": + case "legacy": + return Promise.resolve(mode?.toLocaleLowerCase()); + case undefined: + return Promise.resolve("legacy"); + default: + throw new Error(`Invalid parameter for "defaultsMode", expect ${DEFAULTS_MODE_OPTIONS.join(", ")}, got ${mode}`); + } +}); +const resolveNodeDefaultsModeAuto = async (clientRegion) => { + if (clientRegion) { + const resolvedRegion = typeof clientRegion === "function" ? await clientRegion() : clientRegion; + const inferredRegion = await inferPhysicalRegion(); + if (!inferredRegion) { + return "standard"; + } + if (resolvedRegion === inferredRegion) { + return "in-region"; + } + else { + return "cross-region"; + } + } + return "standard"; +}; +const inferPhysicalRegion = async () => { + if (process.env[AWS_EXECUTION_ENV] && (process.env[AWS_REGION_ENV] || process.env[AWS_DEFAULT_REGION_ENV])) { + return process.env[AWS_REGION_ENV] ?? process.env[AWS_DEFAULT_REGION_ENV]; + } + if (!process.env[ENV_IMDS_DISABLED]) { + try { + const { getInstanceMetadataEndpoint, httpRequest } = await import('@smithy/credential-provider-imds'); + const endpoint = await getInstanceMetadataEndpoint(); + return (await httpRequest({ ...endpoint, path: IMDS_REGION_PATH })).toString(); + } + catch (e) { + } + } +}; + +exports.resolveDefaultsModeConfig = resolveDefaultsModeConfig; diff --git a/claude-code-source/node_modules/@smithy/util-endpoints/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-endpoints/dist-cjs/index.js new file mode 100644 index 00000000..e3a02c6f --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-endpoints/dist-cjs/index.js @@ -0,0 +1,472 @@ +'use strict'; + +var types = require('@smithy/types'); + +class EndpointCache { + capacity; + data = new Map(); + parameters = []; + constructor({ size, params }) { + this.capacity = size ?? 50; + if (params) { + this.parameters = params; + } + } + get(endpointParams, resolver) { + const key = this.hash(endpointParams); + if (key === false) { + return resolver(); + } + if (!this.data.has(key)) { + if (this.data.size > this.capacity + 10) { + const keys = this.data.keys(); + let i = 0; + while (true) { + const { value, done } = keys.next(); + this.data.delete(value); + if (done || ++i > 10) { + break; + } + } + } + this.data.set(key, resolver()); + } + return this.data.get(key); + } + size() { + return this.data.size; + } + hash(endpointParams) { + let buffer = ""; + const { parameters } = this; + if (parameters.length === 0) { + return false; + } + for (const param of parameters) { + const val = String(endpointParams[param] ?? ""); + if (val.includes("|;")) { + return false; + } + buffer += val + "|;"; + } + return buffer; + } +} + +const IP_V4_REGEX = new RegExp(`^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$`); +const isIpAddress = (value) => IP_V4_REGEX.test(value) || (value.startsWith("[") && value.endsWith("]")); + +const VALID_HOST_LABEL_REGEX = new RegExp(`^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$`); +const isValidHostLabel = (value, allowSubDomains = false) => { + if (!allowSubDomains) { + return VALID_HOST_LABEL_REGEX.test(value); + } + const labels = value.split("."); + for (const label of labels) { + if (!isValidHostLabel(label)) { + return false; + } + } + return true; +}; + +const customEndpointFunctions = {}; + +const debugId = "endpoints"; + +function toDebugString(input) { + if (typeof input !== "object" || input == null) { + return input; + } + if ("ref" in input) { + return `$${toDebugString(input.ref)}`; + } + if ("fn" in input) { + return `${input.fn}(${(input.argv || []).map(toDebugString).join(", ")})`; + } + return JSON.stringify(input, null, 2); +} + +class EndpointError extends Error { + constructor(message) { + super(message); + this.name = "EndpointError"; + } +} + +const booleanEquals = (value1, value2) => value1 === value2; + +const getAttrPathList = (path) => { + const parts = path.split("."); + const pathList = []; + for (const part of parts) { + const squareBracketIndex = part.indexOf("["); + if (squareBracketIndex !== -1) { + if (part.indexOf("]") !== part.length - 1) { + throw new EndpointError(`Path: '${path}' does not end with ']'`); + } + const arrayIndex = part.slice(squareBracketIndex + 1, -1); + if (Number.isNaN(parseInt(arrayIndex))) { + throw new EndpointError(`Invalid array index: '${arrayIndex}' in path: '${path}'`); + } + if (squareBracketIndex !== 0) { + pathList.push(part.slice(0, squareBracketIndex)); + } + pathList.push(arrayIndex); + } + else { + pathList.push(part); + } + } + return pathList; +}; + +const getAttr = (value, path) => getAttrPathList(path).reduce((acc, index) => { + if (typeof acc !== "object") { + throw new EndpointError(`Index '${index}' in '${path}' not found in '${JSON.stringify(value)}'`); + } + else if (Array.isArray(acc)) { + return acc[parseInt(index)]; + } + return acc[index]; +}, value); + +const isSet = (value) => value != null; + +const not = (value) => !value; + +const DEFAULT_PORTS = { + [types.EndpointURLScheme.HTTP]: 80, + [types.EndpointURLScheme.HTTPS]: 443, +}; +const parseURL = (value) => { + const whatwgURL = (() => { + try { + if (value instanceof URL) { + return value; + } + if (typeof value === "object" && "hostname" in value) { + const { hostname, port, protocol = "", path = "", query = {} } = value; + const url = new URL(`${protocol}//${hostname}${port ? `:${port}` : ""}${path}`); + url.search = Object.entries(query) + .map(([k, v]) => `${k}=${v}`) + .join("&"); + return url; + } + return new URL(value); + } + catch (error) { + return null; + } + })(); + if (!whatwgURL) { + console.error(`Unable to parse ${JSON.stringify(value)} as a whatwg URL.`); + return null; + } + const urlString = whatwgURL.href; + const { host, hostname, pathname, protocol, search } = whatwgURL; + if (search) { + return null; + } + const scheme = protocol.slice(0, -1); + if (!Object.values(types.EndpointURLScheme).includes(scheme)) { + return null; + } + const isIp = isIpAddress(hostname); + const inputContainsDefaultPort = urlString.includes(`${host}:${DEFAULT_PORTS[scheme]}`) || + (typeof value === "string" && value.includes(`${host}:${DEFAULT_PORTS[scheme]}`)); + const authority = `${host}${inputContainsDefaultPort ? `:${DEFAULT_PORTS[scheme]}` : ``}`; + return { + scheme, + authority, + path: pathname, + normalizedPath: pathname.endsWith("/") ? pathname : `${pathname}/`, + isIp, + }; +}; + +const stringEquals = (value1, value2) => value1 === value2; + +const substring = (input, start, stop, reverse) => { + if (start >= stop || input.length < stop) { + return null; + } + if (!reverse) { + return input.substring(start, stop); + } + return input.substring(input.length - stop, input.length - start); +}; + +const uriEncode = (value) => encodeURIComponent(value).replace(/[!*'()]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`); + +const endpointFunctions = { + booleanEquals, + getAttr, + isSet, + isValidHostLabel, + not, + parseURL, + stringEquals, + substring, + uriEncode, +}; + +const evaluateTemplate = (template, options) => { + const evaluatedTemplateArr = []; + const templateContext = { + ...options.endpointParams, + ...options.referenceRecord, + }; + let currentIndex = 0; + while (currentIndex < template.length) { + const openingBraceIndex = template.indexOf("{", currentIndex); + if (openingBraceIndex === -1) { + evaluatedTemplateArr.push(template.slice(currentIndex)); + break; + } + evaluatedTemplateArr.push(template.slice(currentIndex, openingBraceIndex)); + const closingBraceIndex = template.indexOf("}", openingBraceIndex); + if (closingBraceIndex === -1) { + evaluatedTemplateArr.push(template.slice(openingBraceIndex)); + break; + } + if (template[openingBraceIndex + 1] === "{" && template[closingBraceIndex + 1] === "}") { + evaluatedTemplateArr.push(template.slice(openingBraceIndex + 1, closingBraceIndex)); + currentIndex = closingBraceIndex + 2; + } + const parameterName = template.substring(openingBraceIndex + 1, closingBraceIndex); + if (parameterName.includes("#")) { + const [refName, attrName] = parameterName.split("#"); + evaluatedTemplateArr.push(getAttr(templateContext[refName], attrName)); + } + else { + evaluatedTemplateArr.push(templateContext[parameterName]); + } + currentIndex = closingBraceIndex + 1; + } + return evaluatedTemplateArr.join(""); +}; + +const getReferenceValue = ({ ref }, options) => { + const referenceRecord = { + ...options.endpointParams, + ...options.referenceRecord, + }; + return referenceRecord[ref]; +}; + +const evaluateExpression = (obj, keyName, options) => { + if (typeof obj === "string") { + return evaluateTemplate(obj, options); + } + else if (obj["fn"]) { + return group$2.callFunction(obj, options); + } + else if (obj["ref"]) { + return getReferenceValue(obj, options); + } + throw new EndpointError(`'${keyName}': ${String(obj)} is not a string, function or reference.`); +}; +const callFunction = ({ fn, argv }, options) => { + const evaluatedArgs = argv.map((arg) => ["boolean", "number"].includes(typeof arg) ? arg : group$2.evaluateExpression(arg, "arg", options)); + const fnSegments = fn.split("."); + if (fnSegments[0] in customEndpointFunctions && fnSegments[1] != null) { + return customEndpointFunctions[fnSegments[0]][fnSegments[1]](...evaluatedArgs); + } + return endpointFunctions[fn](...evaluatedArgs); +}; +const group$2 = { + evaluateExpression, + callFunction, +}; + +const evaluateCondition = ({ assign, ...fnArgs }, options) => { + if (assign && assign in options.referenceRecord) { + throw new EndpointError(`'${assign}' is already defined in Reference Record.`); + } + const value = callFunction(fnArgs, options); + options.logger?.debug?.(`${debugId} evaluateCondition: ${toDebugString(fnArgs)} = ${toDebugString(value)}`); + return { + result: value === "" ? true : !!value, + ...(assign != null && { toAssign: { name: assign, value } }), + }; +}; + +const evaluateConditions = (conditions = [], options) => { + const conditionsReferenceRecord = {}; + for (const condition of conditions) { + const { result, toAssign } = evaluateCondition(condition, { + ...options, + referenceRecord: { + ...options.referenceRecord, + ...conditionsReferenceRecord, + }, + }); + if (!result) { + return { result }; + } + if (toAssign) { + conditionsReferenceRecord[toAssign.name] = toAssign.value; + options.logger?.debug?.(`${debugId} assign: ${toAssign.name} := ${toDebugString(toAssign.value)}`); + } + } + return { result: true, referenceRecord: conditionsReferenceRecord }; +}; + +const getEndpointHeaders = (headers, options) => Object.entries(headers).reduce((acc, [headerKey, headerVal]) => ({ + ...acc, + [headerKey]: headerVal.map((headerValEntry) => { + const processedExpr = evaluateExpression(headerValEntry, "Header value entry", options); + if (typeof processedExpr !== "string") { + throw new EndpointError(`Header '${headerKey}' value '${processedExpr}' is not a string`); + } + return processedExpr; + }), +}), {}); + +const getEndpointProperties = (properties, options) => Object.entries(properties).reduce((acc, [propertyKey, propertyVal]) => ({ + ...acc, + [propertyKey]: group$1.getEndpointProperty(propertyVal, options), +}), {}); +const getEndpointProperty = (property, options) => { + if (Array.isArray(property)) { + return property.map((propertyEntry) => getEndpointProperty(propertyEntry, options)); + } + switch (typeof property) { + case "string": + return evaluateTemplate(property, options); + case "object": + if (property === null) { + throw new EndpointError(`Unexpected endpoint property: ${property}`); + } + return group$1.getEndpointProperties(property, options); + case "boolean": + return property; + default: + throw new EndpointError(`Unexpected endpoint property type: ${typeof property}`); + } +}; +const group$1 = { + getEndpointProperty, + getEndpointProperties, +}; + +const getEndpointUrl = (endpointUrl, options) => { + const expression = evaluateExpression(endpointUrl, "Endpoint URL", options); + if (typeof expression === "string") { + try { + return new URL(expression); + } + catch (error) { + console.error(`Failed to construct URL with ${expression}`, error); + throw error; + } + } + throw new EndpointError(`Endpoint URL must be a string, got ${typeof expression}`); +}; + +const evaluateEndpointRule = (endpointRule, options) => { + const { conditions, endpoint } = endpointRule; + const { result, referenceRecord } = evaluateConditions(conditions, options); + if (!result) { + return; + } + const endpointRuleOptions = { + ...options, + referenceRecord: { ...options.referenceRecord, ...referenceRecord }, + }; + const { url, properties, headers } = endpoint; + options.logger?.debug?.(`${debugId} Resolving endpoint from template: ${toDebugString(endpoint)}`); + return { + ...(headers != undefined && { + headers: getEndpointHeaders(headers, endpointRuleOptions), + }), + ...(properties != undefined && { + properties: getEndpointProperties(properties, endpointRuleOptions), + }), + url: getEndpointUrl(url, endpointRuleOptions), + }; +}; + +const evaluateErrorRule = (errorRule, options) => { + const { conditions, error } = errorRule; + const { result, referenceRecord } = evaluateConditions(conditions, options); + if (!result) { + return; + } + throw new EndpointError(evaluateExpression(error, "Error", { + ...options, + referenceRecord: { ...options.referenceRecord, ...referenceRecord }, + })); +}; + +const evaluateRules = (rules, options) => { + for (const rule of rules) { + if (rule.type === "endpoint") { + const endpointOrUndefined = evaluateEndpointRule(rule, options); + if (endpointOrUndefined) { + return endpointOrUndefined; + } + } + else if (rule.type === "error") { + evaluateErrorRule(rule, options); + } + else if (rule.type === "tree") { + const endpointOrUndefined = group.evaluateTreeRule(rule, options); + if (endpointOrUndefined) { + return endpointOrUndefined; + } + } + else { + throw new EndpointError(`Unknown endpoint rule: ${rule}`); + } + } + throw new EndpointError(`Rules evaluation failed`); +}; +const evaluateTreeRule = (treeRule, options) => { + const { conditions, rules } = treeRule; + const { result, referenceRecord } = evaluateConditions(conditions, options); + if (!result) { + return; + } + return group.evaluateRules(rules, { + ...options, + referenceRecord: { ...options.referenceRecord, ...referenceRecord }, + }); +}; +const group = { + evaluateRules, + evaluateTreeRule, +}; + +const resolveEndpoint = (ruleSetObject, options) => { + const { endpointParams, logger } = options; + const { parameters, rules } = ruleSetObject; + options.logger?.debug?.(`${debugId} Initial EndpointParams: ${toDebugString(endpointParams)}`); + const paramsWithDefault = Object.entries(parameters) + .filter(([, v]) => v.default != null) + .map(([k, v]) => [k, v.default]); + if (paramsWithDefault.length > 0) { + for (const [paramKey, paramDefaultValue] of paramsWithDefault) { + endpointParams[paramKey] = endpointParams[paramKey] ?? paramDefaultValue; + } + } + const requiredParams = Object.entries(parameters) + .filter(([, v]) => v.required) + .map(([k]) => k); + for (const requiredParam of requiredParams) { + if (endpointParams[requiredParam] == null) { + throw new EndpointError(`Missing required parameter: '${requiredParam}'`); + } + } + const endpoint = evaluateRules(rules, { endpointParams, logger, referenceRecord: {} }); + options.logger?.debug?.(`${debugId} Resolved endpoint: ${toDebugString(endpoint)}`); + return endpoint; +}; + +exports.EndpointCache = EndpointCache; +exports.EndpointError = EndpointError; +exports.customEndpointFunctions = customEndpointFunctions; +exports.isIpAddress = isIpAddress; +exports.isValidHostLabel = isValidHostLabel; +exports.resolveEndpoint = resolveEndpoint; diff --git a/claude-code-source/node_modules/@smithy/util-endpoints/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-endpoints/node_modules/@smithy/types/dist-cjs/index.js new file mode 100644 index 00000000..be6d0e1a --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-endpoints/node_modules/@smithy/types/dist-cjs/index.js @@ -0,0 +1,91 @@ +'use strict'; + +exports.HttpAuthLocation = void 0; +(function (HttpAuthLocation) { + HttpAuthLocation["HEADER"] = "header"; + HttpAuthLocation["QUERY"] = "query"; +})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); + +exports.HttpApiKeyAuthLocation = void 0; +(function (HttpApiKeyAuthLocation) { + HttpApiKeyAuthLocation["HEADER"] = "header"; + HttpApiKeyAuthLocation["QUERY"] = "query"; +})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); + +exports.EndpointURLScheme = void 0; +(function (EndpointURLScheme) { + EndpointURLScheme["HTTP"] = "http"; + EndpointURLScheme["HTTPS"] = "https"; +})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); + +exports.AlgorithmId = void 0; +(function (AlgorithmId) { + AlgorithmId["MD5"] = "md5"; + AlgorithmId["CRC32"] = "crc32"; + AlgorithmId["CRC32C"] = "crc32c"; + AlgorithmId["SHA1"] = "sha1"; + AlgorithmId["SHA256"] = "sha256"; +})(exports.AlgorithmId || (exports.AlgorithmId = {})); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.SHA256, + checksumConstructor: () => runtimeConfig.sha256, + }); + } + if (runtimeConfig.md5 != undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.MD5, + checksumConstructor: () => runtimeConfig.md5, + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getDefaultClientConfiguration = (runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}; +const resolveDefaultRuntimeConfig = (config) => { + return resolveChecksumRuntimeConfig(config); +}; + +exports.FieldPosition = void 0; +(function (FieldPosition) { + FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; + FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; +})(exports.FieldPosition || (exports.FieldPosition = {})); + +const SMITHY_CONTEXT_KEY = "__smithy_context"; + +exports.IniSectionType = void 0; +(function (IniSectionType) { + IniSectionType["PROFILE"] = "profile"; + IniSectionType["SSO_SESSION"] = "sso-session"; + IniSectionType["SERVICES"] = "services"; +})(exports.IniSectionType || (exports.IniSectionType = {})); + +exports.RequestHandlerProtocol = void 0; +(function (RequestHandlerProtocol) { + RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; +})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); + +exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; diff --git a/claude-code-source/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js new file mode 100644 index 00000000..78a59ea8 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js @@ -0,0 +1,67 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + fromHex: () => fromHex, + toHex: () => toHex +}); +module.exports = __toCommonJS(src_exports); +var SHORT_TO_HEX = {}; +var HEX_TO_SHORT = {}; +for (let i = 0; i < 256; i++) { + let encodedByte = i.toString(16).toLowerCase(); + if (encodedByte.length === 1) { + encodedByte = `0${encodedByte}`; + } + SHORT_TO_HEX[i] = encodedByte; + HEX_TO_SHORT[encodedByte] = i; +} +function fromHex(encoded) { + if (encoded.length % 2 !== 0) { + throw new Error("Hex encoded strings must have an even number length"); + } + const out = new Uint8Array(encoded.length / 2); + for (let i = 0; i < encoded.length; i += 2) { + const encodedByte = encoded.slice(i, i + 2).toLowerCase(); + if (encodedByte in HEX_TO_SHORT) { + out[i / 2] = HEX_TO_SHORT[encodedByte]; + } else { + throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); + } + } + return out; +} +__name(fromHex, "fromHex"); +function toHex(bytes) { + let out = ""; + for (let i = 0; i < bytes.byteLength; i++) { + out += SHORT_TO_HEX[bytes[i]]; + } + return out; +} +__name(toHex, "toHex"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (module.exports = { + fromHex, + toHex +}); + diff --git a/claude-code-source/node_modules/@smithy/util-middleware/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-middleware/dist-cjs/index.js new file mode 100644 index 00000000..2b9af753 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-middleware/dist-cjs/index.js @@ -0,0 +1,15 @@ +'use strict'; + +var types = require('@smithy/types'); + +const getSmithyContext = (context) => context[types.SMITHY_CONTEXT_KEY] || (context[types.SMITHY_CONTEXT_KEY] = {}); + +const normalizeProvider = (input) => { + if (typeof input === "function") + return input; + const promisified = Promise.resolve(input); + return () => promisified; +}; + +exports.getSmithyContext = getSmithyContext; +exports.normalizeProvider = normalizeProvider; diff --git a/claude-code-source/node_modules/@smithy/util-middleware/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-middleware/node_modules/@smithy/types/dist-cjs/index.js new file mode 100644 index 00000000..be6d0e1a --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-middleware/node_modules/@smithy/types/dist-cjs/index.js @@ -0,0 +1,91 @@ +'use strict'; + +exports.HttpAuthLocation = void 0; +(function (HttpAuthLocation) { + HttpAuthLocation["HEADER"] = "header"; + HttpAuthLocation["QUERY"] = "query"; +})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); + +exports.HttpApiKeyAuthLocation = void 0; +(function (HttpApiKeyAuthLocation) { + HttpApiKeyAuthLocation["HEADER"] = "header"; + HttpApiKeyAuthLocation["QUERY"] = "query"; +})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); + +exports.EndpointURLScheme = void 0; +(function (EndpointURLScheme) { + EndpointURLScheme["HTTP"] = "http"; + EndpointURLScheme["HTTPS"] = "https"; +})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); + +exports.AlgorithmId = void 0; +(function (AlgorithmId) { + AlgorithmId["MD5"] = "md5"; + AlgorithmId["CRC32"] = "crc32"; + AlgorithmId["CRC32C"] = "crc32c"; + AlgorithmId["SHA1"] = "sha1"; + AlgorithmId["SHA256"] = "sha256"; +})(exports.AlgorithmId || (exports.AlgorithmId = {})); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.SHA256, + checksumConstructor: () => runtimeConfig.sha256, + }); + } + if (runtimeConfig.md5 != undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.MD5, + checksumConstructor: () => runtimeConfig.md5, + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getDefaultClientConfiguration = (runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}; +const resolveDefaultRuntimeConfig = (config) => { + return resolveChecksumRuntimeConfig(config); +}; + +exports.FieldPosition = void 0; +(function (FieldPosition) { + FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; + FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; +})(exports.FieldPosition || (exports.FieldPosition = {})); + +const SMITHY_CONTEXT_KEY = "__smithy_context"; + +exports.IniSectionType = void 0; +(function (IniSectionType) { + IniSectionType["PROFILE"] = "profile"; + IniSectionType["SSO_SESSION"] = "sso-session"; + IniSectionType["SERVICES"] = "services"; +})(exports.IniSectionType || (exports.IniSectionType = {})); + +exports.RequestHandlerProtocol = void 0; +(function (RequestHandlerProtocol) { + RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; +})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); + +exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; diff --git a/claude-code-source/node_modules/@smithy/util-retry/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-retry/dist-cjs/index.js new file mode 100644 index 00000000..a56d37c9 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-retry/dist-cjs/index.js @@ -0,0 +1,278 @@ +'use strict'; + +var serviceErrorClassification = require('@smithy/service-error-classification'); + +exports.RETRY_MODES = void 0; +(function (RETRY_MODES) { + RETRY_MODES["STANDARD"] = "standard"; + RETRY_MODES["ADAPTIVE"] = "adaptive"; +})(exports.RETRY_MODES || (exports.RETRY_MODES = {})); +const DEFAULT_MAX_ATTEMPTS = 3; +const DEFAULT_RETRY_MODE = exports.RETRY_MODES.STANDARD; + +class DefaultRateLimiter { + static setTimeoutFn = setTimeout; + beta; + minCapacity; + minFillRate; + scaleConstant; + smooth; + currentCapacity = 0; + enabled = false; + lastMaxRate = 0; + measuredTxRate = 0; + requestCount = 0; + fillRate; + lastThrottleTime; + lastTimestamp = 0; + lastTxRateBucket; + maxCapacity; + timeWindow = 0; + constructor(options) { + this.beta = options?.beta ?? 0.7; + this.minCapacity = options?.minCapacity ?? 1; + this.minFillRate = options?.minFillRate ?? 0.5; + this.scaleConstant = options?.scaleConstant ?? 0.4; + this.smooth = options?.smooth ?? 0.8; + const currentTimeInSeconds = this.getCurrentTimeInSeconds(); + this.lastThrottleTime = currentTimeInSeconds; + this.lastTxRateBucket = Math.floor(this.getCurrentTimeInSeconds()); + this.fillRate = this.minFillRate; + this.maxCapacity = this.minCapacity; + } + getCurrentTimeInSeconds() { + return Date.now() / 1000; + } + async getSendToken() { + return this.acquireTokenBucket(1); + } + async acquireTokenBucket(amount) { + if (!this.enabled) { + return; + } + this.refillTokenBucket(); + if (amount > this.currentCapacity) { + const delay = ((amount - this.currentCapacity) / this.fillRate) * 1000; + await new Promise((resolve) => DefaultRateLimiter.setTimeoutFn(resolve, delay)); + } + this.currentCapacity = this.currentCapacity - amount; + } + refillTokenBucket() { + const timestamp = this.getCurrentTimeInSeconds(); + if (!this.lastTimestamp) { + this.lastTimestamp = timestamp; + return; + } + const fillAmount = (timestamp - this.lastTimestamp) * this.fillRate; + this.currentCapacity = Math.min(this.maxCapacity, this.currentCapacity + fillAmount); + this.lastTimestamp = timestamp; + } + updateClientSendingRate(response) { + let calculatedRate; + this.updateMeasuredRate(); + if (serviceErrorClassification.isThrottlingError(response)) { + const rateToUse = !this.enabled ? this.measuredTxRate : Math.min(this.measuredTxRate, this.fillRate); + this.lastMaxRate = rateToUse; + this.calculateTimeWindow(); + this.lastThrottleTime = this.getCurrentTimeInSeconds(); + calculatedRate = this.cubicThrottle(rateToUse); + this.enableTokenBucket(); + } + else { + this.calculateTimeWindow(); + calculatedRate = this.cubicSuccess(this.getCurrentTimeInSeconds()); + } + const newRate = Math.min(calculatedRate, 2 * this.measuredTxRate); + this.updateTokenBucketRate(newRate); + } + calculateTimeWindow() { + this.timeWindow = this.getPrecise(Math.pow((this.lastMaxRate * (1 - this.beta)) / this.scaleConstant, 1 / 3)); + } + cubicThrottle(rateToUse) { + return this.getPrecise(rateToUse * this.beta); + } + cubicSuccess(timestamp) { + return this.getPrecise(this.scaleConstant * Math.pow(timestamp - this.lastThrottleTime - this.timeWindow, 3) + this.lastMaxRate); + } + enableTokenBucket() { + this.enabled = true; + } + updateTokenBucketRate(newRate) { + this.refillTokenBucket(); + this.fillRate = Math.max(newRate, this.minFillRate); + this.maxCapacity = Math.max(newRate, this.minCapacity); + this.currentCapacity = Math.min(this.currentCapacity, this.maxCapacity); + } + updateMeasuredRate() { + const t = this.getCurrentTimeInSeconds(); + const timeBucket = Math.floor(t * 2) / 2; + this.requestCount++; + if (timeBucket > this.lastTxRateBucket) { + const currentRate = this.requestCount / (timeBucket - this.lastTxRateBucket); + this.measuredTxRate = this.getPrecise(currentRate * this.smooth + this.measuredTxRate * (1 - this.smooth)); + this.requestCount = 0; + this.lastTxRateBucket = timeBucket; + } + } + getPrecise(num) { + return parseFloat(num.toFixed(8)); + } +} + +const DEFAULT_RETRY_DELAY_BASE = 100; +const MAXIMUM_RETRY_DELAY = 20 * 1000; +const THROTTLING_RETRY_DELAY_BASE = 500; +const INITIAL_RETRY_TOKENS = 500; +const RETRY_COST = 5; +const TIMEOUT_RETRY_COST = 10; +const NO_RETRY_INCREMENT = 1; +const INVOCATION_ID_HEADER = "amz-sdk-invocation-id"; +const REQUEST_HEADER = "amz-sdk-request"; + +const getDefaultRetryBackoffStrategy = () => { + let delayBase = DEFAULT_RETRY_DELAY_BASE; + const computeNextBackoffDelay = (attempts) => { + return Math.floor(Math.min(MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase)); + }; + const setDelayBase = (delay) => { + delayBase = delay; + }; + return { + computeNextBackoffDelay, + setDelayBase, + }; +}; + +const createDefaultRetryToken = ({ retryDelay, retryCount, retryCost, }) => { + const getRetryCount = () => retryCount; + const getRetryDelay = () => Math.min(MAXIMUM_RETRY_DELAY, retryDelay); + const getRetryCost = () => retryCost; + return { + getRetryCount, + getRetryDelay, + getRetryCost, + }; +}; + +class StandardRetryStrategy { + maxAttempts; + mode = exports.RETRY_MODES.STANDARD; + capacity = INITIAL_RETRY_TOKENS; + retryBackoffStrategy = getDefaultRetryBackoffStrategy(); + maxAttemptsProvider; + constructor(maxAttempts) { + this.maxAttempts = maxAttempts; + this.maxAttemptsProvider = typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts; + } + async acquireInitialRetryToken(retryTokenScope) { + return createDefaultRetryToken({ + retryDelay: DEFAULT_RETRY_DELAY_BASE, + retryCount: 0, + }); + } + async refreshRetryTokenForRetry(token, errorInfo) { + const maxAttempts = await this.getMaxAttempts(); + if (this.shouldRetry(token, errorInfo, maxAttempts)) { + const errorType = errorInfo.errorType; + this.retryBackoffStrategy.setDelayBase(errorType === "THROTTLING" ? THROTTLING_RETRY_DELAY_BASE : DEFAULT_RETRY_DELAY_BASE); + const delayFromErrorType = this.retryBackoffStrategy.computeNextBackoffDelay(token.getRetryCount()); + const retryDelay = errorInfo.retryAfterHint + ? Math.max(errorInfo.retryAfterHint.getTime() - Date.now() || 0, delayFromErrorType) + : delayFromErrorType; + const capacityCost = this.getCapacityCost(errorType); + this.capacity -= capacityCost; + return createDefaultRetryToken({ + retryDelay, + retryCount: token.getRetryCount() + 1, + retryCost: capacityCost, + }); + } + throw new Error("No retry token available"); + } + recordSuccess(token) { + this.capacity = Math.max(INITIAL_RETRY_TOKENS, this.capacity + (token.getRetryCost() ?? NO_RETRY_INCREMENT)); + } + getCapacity() { + return this.capacity; + } + async getMaxAttempts() { + try { + return await this.maxAttemptsProvider(); + } + catch (error) { + console.warn(`Max attempts provider could not resolve. Using default of ${DEFAULT_MAX_ATTEMPTS}`); + return DEFAULT_MAX_ATTEMPTS; + } + } + shouldRetry(tokenToRenew, errorInfo, maxAttempts) { + const attempts = tokenToRenew.getRetryCount() + 1; + return (attempts < maxAttempts && + this.capacity >= this.getCapacityCost(errorInfo.errorType) && + this.isRetryableError(errorInfo.errorType)); + } + getCapacityCost(errorType) { + return errorType === "TRANSIENT" ? TIMEOUT_RETRY_COST : RETRY_COST; + } + isRetryableError(errorType) { + return errorType === "THROTTLING" || errorType === "TRANSIENT"; + } +} + +class AdaptiveRetryStrategy { + maxAttemptsProvider; + rateLimiter; + standardRetryStrategy; + mode = exports.RETRY_MODES.ADAPTIVE; + constructor(maxAttemptsProvider, options) { + this.maxAttemptsProvider = maxAttemptsProvider; + const { rateLimiter } = options ?? {}; + this.rateLimiter = rateLimiter ?? new DefaultRateLimiter(); + this.standardRetryStrategy = new StandardRetryStrategy(maxAttemptsProvider); + } + async acquireInitialRetryToken(retryTokenScope) { + await this.rateLimiter.getSendToken(); + return this.standardRetryStrategy.acquireInitialRetryToken(retryTokenScope); + } + async refreshRetryTokenForRetry(tokenToRenew, errorInfo) { + this.rateLimiter.updateClientSendingRate(errorInfo); + return this.standardRetryStrategy.refreshRetryTokenForRetry(tokenToRenew, errorInfo); + } + recordSuccess(token) { + this.rateLimiter.updateClientSendingRate({}); + this.standardRetryStrategy.recordSuccess(token); + } +} + +class ConfiguredRetryStrategy extends StandardRetryStrategy { + computeNextBackoffDelay; + constructor(maxAttempts, computeNextBackoffDelay = DEFAULT_RETRY_DELAY_BASE) { + super(typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts); + if (typeof computeNextBackoffDelay === "number") { + this.computeNextBackoffDelay = () => computeNextBackoffDelay; + } + else { + this.computeNextBackoffDelay = computeNextBackoffDelay; + } + } + async refreshRetryTokenForRetry(tokenToRenew, errorInfo) { + const token = await super.refreshRetryTokenForRetry(tokenToRenew, errorInfo); + token.getRetryDelay = () => this.computeNextBackoffDelay(token.getRetryCount()); + return token; + } +} + +exports.AdaptiveRetryStrategy = AdaptiveRetryStrategy; +exports.ConfiguredRetryStrategy = ConfiguredRetryStrategy; +exports.DEFAULT_MAX_ATTEMPTS = DEFAULT_MAX_ATTEMPTS; +exports.DEFAULT_RETRY_DELAY_BASE = DEFAULT_RETRY_DELAY_BASE; +exports.DEFAULT_RETRY_MODE = DEFAULT_RETRY_MODE; +exports.DefaultRateLimiter = DefaultRateLimiter; +exports.INITIAL_RETRY_TOKENS = INITIAL_RETRY_TOKENS; +exports.INVOCATION_ID_HEADER = INVOCATION_ID_HEADER; +exports.MAXIMUM_RETRY_DELAY = MAXIMUM_RETRY_DELAY; +exports.NO_RETRY_INCREMENT = NO_RETRY_INCREMENT; +exports.REQUEST_HEADER = REQUEST_HEADER; +exports.RETRY_COST = RETRY_COST; +exports.StandardRetryStrategy = StandardRetryStrategy; +exports.THROTTLING_RETRY_DELAY_BASE = THROTTLING_RETRY_DELAY_BASE; +exports.TIMEOUT_RETRY_COST = TIMEOUT_RETRY_COST; diff --git a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/ByteArrayCollector.js b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/ByteArrayCollector.js new file mode 100644 index 00000000..f056f826 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/ByteArrayCollector.js @@ -0,0 +1,36 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ByteArrayCollector = void 0; +class ByteArrayCollector { + allocByteArray; + byteLength = 0; + byteArrays = []; + constructor(allocByteArray) { + this.allocByteArray = allocByteArray; + } + push(byteArray) { + this.byteArrays.push(byteArray); + this.byteLength += byteArray.byteLength; + } + flush() { + if (this.byteArrays.length === 1) { + const bytes = this.byteArrays[0]; + this.reset(); + return bytes; + } + const aggregation = this.allocByteArray(this.byteLength); + let cursor = 0; + for (let i = 0; i < this.byteArrays.length; ++i) { + const bytes = this.byteArrays[i]; + aggregation.set(bytes, cursor); + cursor += bytes.byteLength; + } + this.reset(); + return aggregation; + } + reset() { + this.byteArrays = []; + this.byteLength = 0; + } +} +exports.ByteArrayCollector = ByteArrayCollector; diff --git a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.browser.js b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.browser.js new file mode 100644 index 00000000..b73363a5 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.browser.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ChecksumStream = void 0; +const ReadableStreamRef = typeof ReadableStream === "function" ? ReadableStream : function () { }; +class ChecksumStream extends ReadableStreamRef { +} +exports.ChecksumStream = ChecksumStream; diff --git a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.js b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.js new file mode 100644 index 00000000..f1624ec2 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.js @@ -0,0 +1,53 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ChecksumStream = void 0; +const util_base64_1 = require("@smithy/util-base64"); +const stream_1 = require("stream"); +class ChecksumStream extends stream_1.Duplex { + expectedChecksum; + checksumSourceLocation; + checksum; + source; + base64Encoder; + constructor({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) { + super(); + if (typeof source.pipe === "function") { + this.source = source; + } + else { + throw new Error(`@smithy/util-stream: unsupported source type ${source?.constructor?.name ?? source} in ChecksumStream.`); + } + this.base64Encoder = base64Encoder ?? util_base64_1.toBase64; + this.expectedChecksum = expectedChecksum; + this.checksum = checksum; + this.checksumSourceLocation = checksumSourceLocation; + this.source.pipe(this); + } + _read(size) { } + _write(chunk, encoding, callback) { + try { + this.checksum.update(chunk); + this.push(chunk); + } + catch (e) { + return callback(e); + } + return callback(); + } + async _final(callback) { + try { + const digest = await this.checksum.digest(); + const received = this.base64Encoder(digest); + if (this.expectedChecksum !== received) { + return callback(new Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${received}"` + + ` in response header "${this.checksumSourceLocation}".`)); + } + } + catch (e) { + return callback(e); + } + this.push(null); + return callback(); + } +} +exports.ChecksumStream = ChecksumStream; diff --git a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.browser.js b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.browser.js new file mode 100644 index 00000000..2bbe76e5 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.browser.js @@ -0,0 +1,39 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createChecksumStream = void 0; +const util_base64_1 = require("@smithy/util-base64"); +const stream_type_check_1 = require("../stream-type-check"); +const ChecksumStream_browser_1 = require("./ChecksumStream.browser"); +const createChecksumStream = ({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) => { + if (!(0, stream_type_check_1.isReadableStream)(source)) { + throw new Error(`@smithy/util-stream: unsupported source type ${source?.constructor?.name ?? source} in ChecksumStream.`); + } + const encoder = base64Encoder ?? util_base64_1.toBase64; + if (typeof TransformStream !== "function") { + throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream."); + } + const transform = new TransformStream({ + start() { }, + async transform(chunk, controller) { + checksum.update(chunk); + controller.enqueue(chunk); + }, + async flush(controller) { + const digest = await checksum.digest(); + const received = encoder(digest); + if (expectedChecksum !== received) { + const error = new Error(`Checksum mismatch: expected "${expectedChecksum}" but received "${received}"` + + ` in response header "${checksumSourceLocation}".`); + controller.error(error); + } + else { + controller.terminate(); + } + }, + }); + source.pipeThrough(transform); + const readable = transform.readable; + Object.setPrototypeOf(readable, ChecksumStream_browser_1.ChecksumStream.prototype); + return readable; +}; +exports.createChecksumStream = createChecksumStream; diff --git a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.js b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.js new file mode 100644 index 00000000..9638f020 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.js @@ -0,0 +1,12 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createChecksumStream = createChecksumStream; +const stream_type_check_1 = require("../stream-type-check"); +const ChecksumStream_1 = require("./ChecksumStream"); +const createChecksumStream_browser_1 = require("./createChecksumStream.browser"); +function createChecksumStream(init) { + if (typeof ReadableStream === "function" && (0, stream_type_check_1.isReadableStream)(init.source)) { + return (0, createChecksumStream_browser_1.createChecksumStream)(init); + } + return new ChecksumStream_1.ChecksumStream(init); +} diff --git a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/createBufferedReadable.js b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/createBufferedReadable.js new file mode 100644 index 00000000..b3b47a26 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/createBufferedReadable.js @@ -0,0 +1,60 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createBufferedReadable = createBufferedReadable; +const node_stream_1 = require("node:stream"); +const ByteArrayCollector_1 = require("./ByteArrayCollector"); +const createBufferedReadableStream_1 = require("./createBufferedReadableStream"); +const stream_type_check_1 = require("./stream-type-check"); +function createBufferedReadable(upstream, size, logger) { + if ((0, stream_type_check_1.isReadableStream)(upstream)) { + return (0, createBufferedReadableStream_1.createBufferedReadableStream)(upstream, size, logger); + } + const downstream = new node_stream_1.Readable({ read() { } }); + let streamBufferingLoggedWarning = false; + let bytesSeen = 0; + const buffers = [ + "", + new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size)), + new ByteArrayCollector_1.ByteArrayCollector((size) => Buffer.from(new Uint8Array(size))), + ]; + let mode = -1; + upstream.on("data", (chunk) => { + const chunkMode = (0, createBufferedReadableStream_1.modeOf)(chunk, true); + if (mode !== chunkMode) { + if (mode >= 0) { + downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); + } + mode = chunkMode; + } + if (mode === -1) { + downstream.push(chunk); + return; + } + const chunkSize = (0, createBufferedReadableStream_1.sizeOf)(chunk); + bytesSeen += chunkSize; + const bufferSize = (0, createBufferedReadableStream_1.sizeOf)(buffers[mode]); + if (chunkSize >= size && bufferSize === 0) { + downstream.push(chunk); + } + else { + const newSize = (0, createBufferedReadableStream_1.merge)(buffers, mode, chunk); + if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { + streamBufferingLoggedWarning = true; + logger?.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); + } + if (newSize >= size) { + downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); + } + } + }); + upstream.on("end", () => { + if (mode !== -1) { + const remainder = (0, createBufferedReadableStream_1.flush)(buffers, mode); + if ((0, createBufferedReadableStream_1.sizeOf)(remainder) > 0) { + downstream.push(remainder); + } + } + downstream.push(null); + }); + return downstream; +} diff --git a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/createBufferedReadableStream.js b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/createBufferedReadableStream.js new file mode 100644 index 00000000..1b7d8c38 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/createBufferedReadableStream.js @@ -0,0 +1,103 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createBufferedReadable = void 0; +exports.createBufferedReadableStream = createBufferedReadableStream; +exports.merge = merge; +exports.flush = flush; +exports.sizeOf = sizeOf; +exports.modeOf = modeOf; +const ByteArrayCollector_1 = require("./ByteArrayCollector"); +function createBufferedReadableStream(upstream, size, logger) { + const reader = upstream.getReader(); + let streamBufferingLoggedWarning = false; + let bytesSeen = 0; + const buffers = ["", new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size))]; + let mode = -1; + const pull = async (controller) => { + const { value, done } = await reader.read(); + const chunk = value; + if (done) { + if (mode !== -1) { + const remainder = flush(buffers, mode); + if (sizeOf(remainder) > 0) { + controller.enqueue(remainder); + } + } + controller.close(); + } + else { + const chunkMode = modeOf(chunk, false); + if (mode !== chunkMode) { + if (mode >= 0) { + controller.enqueue(flush(buffers, mode)); + } + mode = chunkMode; + } + if (mode === -1) { + controller.enqueue(chunk); + return; + } + const chunkSize = sizeOf(chunk); + bytesSeen += chunkSize; + const bufferSize = sizeOf(buffers[mode]); + if (chunkSize >= size && bufferSize === 0) { + controller.enqueue(chunk); + } + else { + const newSize = merge(buffers, mode, chunk); + if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { + streamBufferingLoggedWarning = true; + logger?.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); + } + if (newSize >= size) { + controller.enqueue(flush(buffers, mode)); + } + else { + await pull(controller); + } + } + } + }; + return new ReadableStream({ + pull, + }); +} +exports.createBufferedReadable = createBufferedReadableStream; +function merge(buffers, mode, chunk) { + switch (mode) { + case 0: + buffers[0] += chunk; + return sizeOf(buffers[0]); + case 1: + case 2: + buffers[mode].push(chunk); + return sizeOf(buffers[mode]); + } +} +function flush(buffers, mode) { + switch (mode) { + case 0: + const s = buffers[0]; + buffers[0] = ""; + return s; + case 1: + case 2: + return buffers[mode].flush(); + } + throw new Error(`@smithy/util-stream - invalid index ${mode} given to flush()`); +} +function sizeOf(chunk) { + return chunk?.byteLength ?? chunk?.length ?? 0; +} +function modeOf(chunk, allowBuffer = true) { + if (allowBuffer && typeof Buffer !== "undefined" && chunk instanceof Buffer) { + return 2; + } + if (chunk instanceof Uint8Array) { + return 1; + } + if (typeof chunk === "string") { + return 0; + } + return -1; +} diff --git a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/getAwsChunkedEncodingStream.js b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/getAwsChunkedEncodingStream.js new file mode 100644 index 00000000..4f3f9e73 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/getAwsChunkedEncodingStream.js @@ -0,0 +1,30 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getAwsChunkedEncodingStream = void 0; +const stream_1 = require("stream"); +const getAwsChunkedEncodingStream = (readableStream, options) => { + const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options; + const checksumRequired = base64Encoder !== undefined && + checksumAlgorithmFn !== undefined && + checksumLocationName !== undefined && + streamHasher !== undefined; + const digest = checksumRequired ? streamHasher(checksumAlgorithmFn, readableStream) : undefined; + const awsChunkedEncodingStream = new stream_1.Readable({ read: () => { } }); + readableStream.on("data", (data) => { + const length = bodyLengthChecker(data) || 0; + awsChunkedEncodingStream.push(`${length.toString(16)}\r\n`); + awsChunkedEncodingStream.push(data); + awsChunkedEncodingStream.push("\r\n"); + }); + readableStream.on("end", async () => { + awsChunkedEncodingStream.push(`0\r\n`); + if (checksumRequired) { + const checksum = base64Encoder(await digest); + awsChunkedEncodingStream.push(`${checksumLocationName}:${checksum}\r\n`); + awsChunkedEncodingStream.push(`\r\n`); + } + awsChunkedEncodingStream.push(null); + }); + return awsChunkedEncodingStream; +}; +exports.getAwsChunkedEncodingStream = getAwsChunkedEncodingStream; diff --git a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/headStream.browser.js b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/headStream.browser.js new file mode 100644 index 00000000..e8413f2c --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/headStream.browser.js @@ -0,0 +1,34 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.headStream = headStream; +async function headStream(stream, bytes) { + let byteLengthCounter = 0; + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + byteLengthCounter += value?.byteLength ?? 0; + } + if (byteLengthCounter >= bytes) { + break; + } + isDone = done; + } + reader.releaseLock(); + const collected = new Uint8Array(Math.min(bytes, byteLengthCounter)); + let offset = 0; + for (const chunk of chunks) { + if (chunk.byteLength > collected.byteLength - offset) { + collected.set(chunk.subarray(0, collected.byteLength - offset), offset); + break; + } + else { + collected.set(chunk, offset); + } + offset += chunk.length; + } + return collected; +} diff --git a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/headStream.js b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/headStream.js new file mode 100644 index 00000000..4e766334 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/headStream.js @@ -0,0 +1,42 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.headStream = void 0; +const stream_1 = require("stream"); +const headStream_browser_1 = require("./headStream.browser"); +const stream_type_check_1 = require("./stream-type-check"); +const headStream = (stream, bytes) => { + if ((0, stream_type_check_1.isReadableStream)(stream)) { + return (0, headStream_browser_1.headStream)(stream, bytes); + } + return new Promise((resolve, reject) => { + const collector = new Collector(); + collector.limit = bytes; + stream.pipe(collector); + stream.on("error", (err) => { + collector.end(); + reject(err); + }); + collector.on("error", reject); + collector.on("finish", function () { + const bytes = new Uint8Array(Buffer.concat(this.buffers)); + resolve(bytes); + }); + }); +}; +exports.headStream = headStream; +class Collector extends stream_1.Writable { + buffers = []; + limit = Infinity; + bytesBuffered = 0; + _write(chunk, encoding, callback) { + this.buffers.push(chunk); + this.bytesBuffered += chunk.byteLength ?? 0; + if (this.bytesBuffered >= this.limit) { + const excess = this.bytesBuffered - this.limit; + const tailBuffer = this.buffers[this.buffers.length - 1]; + this.buffers[this.buffers.length - 1] = tailBuffer.subarray(0, tailBuffer.byteLength - excess); + this.emit("finish"); + } + callback(); + } +} diff --git a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/index.js new file mode 100644 index 00000000..a50b4993 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/index.js @@ -0,0 +1,84 @@ +'use strict'; + +var utilBase64 = require('@smithy/util-base64'); +var utilUtf8 = require('@smithy/util-utf8'); +var ChecksumStream = require('./checksum/ChecksumStream'); +var createChecksumStream = require('./checksum/createChecksumStream'); +var createBufferedReadable = require('./createBufferedReadable'); +var getAwsChunkedEncodingStream = require('./getAwsChunkedEncodingStream'); +var headStream = require('./headStream'); +var sdkStreamMixin = require('./sdk-stream-mixin'); +var splitStream = require('./splitStream'); +var streamTypeCheck = require('./stream-type-check'); + +class Uint8ArrayBlobAdapter extends Uint8Array { + static fromString(source, encoding = "utf-8") { + if (typeof source === "string") { + if (encoding === "base64") { + return Uint8ArrayBlobAdapter.mutate(utilBase64.fromBase64(source)); + } + return Uint8ArrayBlobAdapter.mutate(utilUtf8.fromUtf8(source)); + } + throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`); + } + static mutate(source) { + Object.setPrototypeOf(source, Uint8ArrayBlobAdapter.prototype); + return source; + } + transformToString(encoding = "utf-8") { + if (encoding === "base64") { + return utilBase64.toBase64(this); + } + return utilUtf8.toUtf8(this); + } +} + +exports.Uint8ArrayBlobAdapter = Uint8ArrayBlobAdapter; +Object.keys(ChecksumStream).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return ChecksumStream[k]; } + }); +}); +Object.keys(createChecksumStream).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return createChecksumStream[k]; } + }); +}); +Object.keys(createBufferedReadable).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return createBufferedReadable[k]; } + }); +}); +Object.keys(getAwsChunkedEncodingStream).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return getAwsChunkedEncodingStream[k]; } + }); +}); +Object.keys(headStream).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return headStream[k]; } + }); +}); +Object.keys(sdkStreamMixin).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return sdkStreamMixin[k]; } + }); +}); +Object.keys(splitStream).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return splitStream[k]; } + }); +}); +Object.keys(streamTypeCheck).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return streamTypeCheck[k]; } + }); +}); diff --git a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.browser.js b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.browser.js new file mode 100644 index 00000000..222c5f78 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.browser.js @@ -0,0 +1,68 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sdkStreamMixin = void 0; +const fetch_http_handler_1 = require("@smithy/fetch-http-handler"); +const util_base64_1 = require("@smithy/util-base64"); +const util_hex_encoding_1 = require("@smithy/util-hex-encoding"); +const util_utf8_1 = require("@smithy/util-utf8"); +const stream_type_check_1 = require("./stream-type-check"); +const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; +const sdkStreamMixin = (stream) => { + if (!isBlobInstance(stream) && !(0, stream_type_check_1.isReadableStream)(stream)) { + const name = stream?.__proto__?.constructor?.name || stream; + throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name}`); + } + let transformed = false; + const transformToByteArray = async () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + transformed = true; + return await (0, fetch_http_handler_1.streamCollector)(stream); + }; + const blobToWebStream = (blob) => { + if (typeof blob.stream !== "function") { + throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\n" + + "If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body"); + } + return blob.stream(); + }; + return Object.assign(stream, { + transformToByteArray: transformToByteArray, + transformToString: async (encoding) => { + const buf = await transformToByteArray(); + if (encoding === "base64") { + return (0, util_base64_1.toBase64)(buf); + } + else if (encoding === "hex") { + return (0, util_hex_encoding_1.toHex)(buf); + } + else if (encoding === undefined || encoding === "utf8" || encoding === "utf-8") { + return (0, util_utf8_1.toUtf8)(buf); + } + else if (typeof TextDecoder === "function") { + return new TextDecoder(encoding).decode(buf); + } + else { + throw new Error("TextDecoder is not available, please make sure polyfill is provided."); + } + }, + transformToWebStream: () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + transformed = true; + if (isBlobInstance(stream)) { + return blobToWebStream(stream); + } + else if ((0, stream_type_check_1.isReadableStream)(stream)) { + return stream; + } + else { + throw new Error(`Cannot transform payload to web stream, got ${stream}`); + } + }, + }); +}; +exports.sdkStreamMixin = sdkStreamMixin; +const isBlobInstance = (stream) => typeof Blob === "function" && stream instanceof Blob; diff --git a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.js b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.js new file mode 100644 index 00000000..31d8da1b --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.js @@ -0,0 +1,54 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sdkStreamMixin = void 0; +const node_http_handler_1 = require("@smithy/node-http-handler"); +const util_buffer_from_1 = require("@smithy/util-buffer-from"); +const stream_1 = require("stream"); +const sdk_stream_mixin_browser_1 = require("./sdk-stream-mixin.browser"); +const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; +const sdkStreamMixin = (stream) => { + if (!(stream instanceof stream_1.Readable)) { + try { + return (0, sdk_stream_mixin_browser_1.sdkStreamMixin)(stream); + } + catch (e) { + const name = stream?.__proto__?.constructor?.name || stream; + throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${name}`); + } + } + let transformed = false; + const transformToByteArray = async () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + transformed = true; + return await (0, node_http_handler_1.streamCollector)(stream); + }; + return Object.assign(stream, { + transformToByteArray, + transformToString: async (encoding) => { + const buf = await transformToByteArray(); + if (encoding === undefined || Buffer.isEncoding(encoding)) { + return (0, util_buffer_from_1.fromArrayBuffer)(buf.buffer, buf.byteOffset, buf.byteLength).toString(encoding); + } + else { + const decoder = new TextDecoder(encoding); + return decoder.decode(buf); + } + }, + transformToWebStream: () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + if (stream.readableFlowing !== null) { + throw new Error("The stream has been consumed by other callbacks."); + } + if (typeof stream_1.Readable.toWeb !== "function") { + throw new Error("Readable.toWeb() is not supported. Please ensure a polyfill is available."); + } + transformed = true; + return stream_1.Readable.toWeb(stream); + }, + }); +}; +exports.sdkStreamMixin = sdkStreamMixin; diff --git a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/splitStream.browser.js b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/splitStream.browser.js new file mode 100644 index 00000000..1a4cc07b --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/splitStream.browser.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.splitStream = splitStream; +async function splitStream(stream) { + if (typeof stream.stream === "function") { + stream = stream.stream(); + } + const readableStream = stream; + return readableStream.tee(); +} diff --git a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/splitStream.js b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/splitStream.js new file mode 100644 index 00000000..a60ffadf --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/splitStream.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.splitStream = splitStream; +const stream_1 = require("stream"); +const splitStream_browser_1 = require("./splitStream.browser"); +const stream_type_check_1 = require("./stream-type-check"); +async function splitStream(stream) { + if ((0, stream_type_check_1.isReadableStream)(stream) || (0, stream_type_check_1.isBlob)(stream)) { + return (0, splitStream_browser_1.splitStream)(stream); + } + const stream1 = new stream_1.PassThrough(); + const stream2 = new stream_1.PassThrough(); + stream.pipe(stream1); + stream.pipe(stream2); + return [stream1, stream2]; +} diff --git a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/stream-type-check.js b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/stream-type-check.js new file mode 100644 index 00000000..c4648f8d --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/stream-type-check.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isBlob = exports.isReadableStream = void 0; +const isReadableStream = (stream) => typeof ReadableStream === "function" && + (stream?.constructor?.name === ReadableStream.name || stream instanceof ReadableStream); +exports.isReadableStream = isReadableStream; +const isBlob = (blob) => { + return typeof Blob === "function" && (blob?.constructor?.name === Blob.name || blob instanceof Blob); +}; +exports.isBlob = isBlob; diff --git a/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/fetch-http-handler/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/fetch-http-handler/dist-cjs/index.js new file mode 100644 index 00000000..e6673dc8 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/fetch-http-handler/dist-cjs/index.js @@ -0,0 +1,216 @@ +'use strict'; + +var protocolHttp = require('@smithy/protocol-http'); +var querystringBuilder = require('@smithy/querystring-builder'); +var utilBase64 = require('@smithy/util-base64'); + +function createRequest(url, requestOptions) { + return new Request(url, requestOptions); +} + +function requestTimeout(timeoutInMs = 0) { + return new Promise((resolve, reject) => { + if (timeoutInMs) { + setTimeout(() => { + const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`); + timeoutError.name = "TimeoutError"; + reject(timeoutError); + }, timeoutInMs); + } + }); +} + +const keepAliveSupport = { + supported: undefined, +}; +class FetchHttpHandler { + config; + configProvider; + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; + } + return new FetchHttpHandler(instanceOrOptions); + } + constructor(options) { + if (typeof options === "function") { + this.configProvider = options().then((opts) => opts || {}); + } + else { + this.config = options ?? {}; + this.configProvider = Promise.resolve(this.config); + } + if (keepAliveSupport.supported === undefined) { + keepAliveSupport.supported = Boolean(typeof Request !== "undefined" && "keepalive" in createRequest("https://[::1]")); + } + } + destroy() { + } + async handle(request, { abortSignal, requestTimeout: requestTimeout$1 } = {}) { + if (!this.config) { + this.config = await this.configProvider; + } + const requestTimeoutInMs = requestTimeout$1 ?? this.config.requestTimeout; + const keepAlive = this.config.keepAlive === true; + const credentials = this.config.credentials; + if (abortSignal?.aborted) { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + return Promise.reject(abortError); + } + let path = request.path; + const queryString = querystringBuilder.buildQueryString(request.query || {}); + if (queryString) { + path += `?${queryString}`; + } + if (request.fragment) { + path += `#${request.fragment}`; + } + let auth = ""; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}@`; + } + const { port, method } = request; + const url = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : ""}${path}`; + const body = method === "GET" || method === "HEAD" ? undefined : request.body; + const requestOptions = { + body, + headers: new Headers(request.headers), + method: method, + credentials, + }; + if (this.config?.cache) { + requestOptions.cache = this.config.cache; + } + if (body) { + requestOptions.duplex = "half"; + } + if (typeof AbortController !== "undefined") { + requestOptions.signal = abortSignal; + } + if (keepAliveSupport.supported) { + requestOptions.keepalive = keepAlive; + } + if (typeof this.config.requestInit === "function") { + Object.assign(requestOptions, this.config.requestInit(request)); + } + let removeSignalEventListener = () => { }; + const fetchRequest = createRequest(url, requestOptions); + const raceOfPromises = [ + fetch(fetchRequest).then((response) => { + const fetchHeaders = response.headers; + const transformedHeaders = {}; + for (const pair of fetchHeaders.entries()) { + transformedHeaders[pair[0]] = pair[1]; + } + const hasReadableStream = response.body != undefined; + if (!hasReadableStream) { + return response.blob().then((body) => ({ + response: new protocolHttp.HttpResponse({ + headers: transformedHeaders, + reason: response.statusText, + statusCode: response.status, + body, + }), + })); + } + return { + response: new protocolHttp.HttpResponse({ + headers: transformedHeaders, + reason: response.statusText, + statusCode: response.status, + body: response.body, + }), + }; + }), + requestTimeout(requestTimeoutInMs), + ]; + if (abortSignal) { + raceOfPromises.push(new Promise((resolve, reject) => { + const onAbort = () => { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + }; + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + removeSignalEventListener = () => signal.removeEventListener("abort", onAbort); + } + else { + abortSignal.onabort = onAbort; + } + })); + } + return Promise.race(raceOfPromises).finally(removeSignalEventListener); + } + updateHttpClientConfig(key, value) { + this.config = undefined; + this.configProvider = this.configProvider.then((config) => { + config[key] = value; + return config; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; + } +} + +const streamCollector = async (stream) => { + if ((typeof Blob === "function" && stream instanceof Blob) || stream.constructor?.name === "Blob") { + if (Blob.prototype.arrayBuffer !== undefined) { + return new Uint8Array(await stream.arrayBuffer()); + } + return collectBlob(stream); + } + return collectStream(stream); +}; +async function collectBlob(blob) { + const base64 = await readToBase64(blob); + const arrayBuffer = utilBase64.fromBase64(base64); + return new Uint8Array(arrayBuffer); +} +async function collectStream(stream) { + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + let length = 0; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + length += value.length; + } + isDone = done; + } + const collected = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + collected.set(chunk, offset); + offset += chunk.length; + } + return collected; +} +function readToBase64(blob) { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onloadend = () => { + if (reader.readyState !== 2) { + return reject(new Error("Reader aborted too early")); + } + const result = (reader.result ?? ""); + const commaIndex = result.indexOf(","); + const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length; + resolve(result.substring(dataOffset)); + }; + reader.onabort = () => reject(new Error("Read aborted")); + reader.onerror = () => reject(reader.error); + reader.readAsDataURL(blob); + }); +} + +exports.FetchHttpHandler = FetchHttpHandler; +exports.keepAliveSupport = keepAliveSupport; +exports.streamCollector = streamCollector; diff --git a/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-cjs/index.js new file mode 100644 index 00000000..52303c3b --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-cjs/index.js @@ -0,0 +1,169 @@ +'use strict'; + +var types = require('@smithy/types'); + +const getHttpHandlerExtensionConfiguration = (runtimeConfig) => { + return { + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); + }, + }; +}; +const resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler(), + }; +}; + +class Field { + name; + kind; + values; + constructor({ name, kind = types.FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; + } + add(value) { + this.values.push(value); + } + set(values) { + this.values = values; + } + remove(value) { + this.values = this.values.filter((v) => v !== value); + } + toString() { + return this.values.map((v) => (v.includes(",") || v.includes(" ") ? `"${v}"` : v)).join(", "); + } + get() { + return this.values; + } +} + +class Fields { + entries = {}; + encoding; + constructor({ fields = [], encoding = "utf-8" }) { + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + setField(field) { + this.entries[field.name.toLowerCase()] = field; + } + getField(name) { + return this.entries[name.toLowerCase()]; + } + removeField(name) { + delete this.entries[name.toLowerCase()]; + } + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } +} + +class HttpRequest { + method; + protocol; + hostname; + port; + path; + query; + headers; + username; + password; + fragment; + body; + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol + ? options.protocol.slice(-1) !== ":" + ? `${options.protocol}:` + : options.protocol + : "https:"; + this.path = options.path ? (options.path.charAt(0) !== "/" ? `/${options.path}` : options.path) : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + static clone(request) { + const cloned = new HttpRequest({ + ...request, + headers: { ...request.headers }, + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); + } + return cloned; + } + static isInstance(request) { + if (!request) { + return false; + } + const req = request; + return ("method" in req && + "protocol" in req && + "hostname" in req && + "path" in req && + typeof req["query"] === "object" && + typeof req["headers"] === "object"); + } + clone() { + return HttpRequest.clone(this); + } +} +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param, + }; + }, {}); +} + +class HttpResponse { + statusCode; + reason; + headers; + body; + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) + return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + } +} + +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} + +exports.Field = Field; +exports.Fields = Fields; +exports.HttpRequest = HttpRequest; +exports.HttpResponse = HttpResponse; +exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration; +exports.isValidHostname = isValidHostname; +exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig; diff --git a/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/querystring-builder/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/querystring-builder/dist-cjs/index.js new file mode 100644 index 00000000..f245489f --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/querystring-builder/dist-cjs/index.js @@ -0,0 +1,26 @@ +'use strict'; + +var utilUriEscape = require('@smithy/util-uri-escape'); + +function buildQueryString(query) { + const parts = []; + for (let key of Object.keys(query).sort()) { + const value = query[key]; + key = utilUriEscape.escapeUri(key); + if (Array.isArray(value)) { + for (let i = 0, iLen = value.length; i < iLen; i++) { + parts.push(`${key}=${utilUriEscape.escapeUri(value[i])}`); + } + } + else { + let qsEntry = key; + if (value || typeof value === "string") { + qsEntry += `=${utilUriEscape.escapeUri(value)}`; + } + parts.push(qsEntry); + } + } + return parts.join("&"); +} + +exports.buildQueryString = buildQueryString; diff --git a/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js new file mode 100644 index 00000000..11f942c3 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js @@ -0,0 +1,9 @@ +'use strict'; + +const escapeUri = (uri) => encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode); +const hexEncode = (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`; + +const escapeUriPath = (uri) => uri.split("/").map(escapeUri).join("/"); + +exports.escapeUri = escapeUri; +exports.escapeUriPath = escapeUriPath; diff --git a/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/types/dist-cjs/index.js new file mode 100644 index 00000000..be6d0e1a --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/types/dist-cjs/index.js @@ -0,0 +1,91 @@ +'use strict'; + +exports.HttpAuthLocation = void 0; +(function (HttpAuthLocation) { + HttpAuthLocation["HEADER"] = "header"; + HttpAuthLocation["QUERY"] = "query"; +})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); + +exports.HttpApiKeyAuthLocation = void 0; +(function (HttpApiKeyAuthLocation) { + HttpApiKeyAuthLocation["HEADER"] = "header"; + HttpApiKeyAuthLocation["QUERY"] = "query"; +})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); + +exports.EndpointURLScheme = void 0; +(function (EndpointURLScheme) { + EndpointURLScheme["HTTP"] = "http"; + EndpointURLScheme["HTTPS"] = "https"; +})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); + +exports.AlgorithmId = void 0; +(function (AlgorithmId) { + AlgorithmId["MD5"] = "md5"; + AlgorithmId["CRC32"] = "crc32"; + AlgorithmId["CRC32C"] = "crc32c"; + AlgorithmId["SHA1"] = "sha1"; + AlgorithmId["SHA256"] = "sha256"; +})(exports.AlgorithmId || (exports.AlgorithmId = {})); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.SHA256, + checksumConstructor: () => runtimeConfig.sha256, + }); + } + if (runtimeConfig.md5 != undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.MD5, + checksumConstructor: () => runtimeConfig.md5, + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getDefaultClientConfiguration = (runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}; +const resolveDefaultRuntimeConfig = (config) => { + return resolveChecksumRuntimeConfig(config); +}; + +exports.FieldPosition = void 0; +(function (FieldPosition) { + FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; + FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; +})(exports.FieldPosition || (exports.FieldPosition = {})); + +const SMITHY_CONTEXT_KEY = "__smithy_context"; + +exports.IniSectionType = void 0; +(function (IniSectionType) { + IniSectionType["PROFILE"] = "profile"; + IniSectionType["SSO_SESSION"] = "sso-session"; + IniSectionType["SERVICES"] = "services"; +})(exports.IniSectionType || (exports.IniSectionType = {})); + +exports.RequestHandlerProtocol = void 0; +(function (RequestHandlerProtocol) { + RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; +})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); + +exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; diff --git a/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js b/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js new file mode 100644 index 00000000..b06a7b87 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromBase64 = void 0; +const util_buffer_from_1 = require("@smithy/util-buffer-from"); +const BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; +const fromBase64 = (input) => { + if ((input.length * 3) % 4 !== 0) { + throw new TypeError(`Incorrect padding on base64 string.`); + } + if (!BASE64_REGEX.exec(input)) { + throw new TypeError(`Invalid base64 string.`); + } + const buffer = (0, util_buffer_from_1.fromString)(input, "base64"); + return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); +}; +exports.fromBase64 = fromBase64; diff --git a/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-base64/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-base64/dist-cjs/index.js new file mode 100644 index 00000000..c095e288 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-base64/dist-cjs/index.js @@ -0,0 +1,19 @@ +'use strict'; + +var fromBase64 = require('./fromBase64'); +var toBase64 = require('./toBase64'); + + + +Object.keys(fromBase64).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return fromBase64[k]; } + }); +}); +Object.keys(toBase64).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return toBase64[k]; } + }); +}); diff --git a/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-base64/dist-cjs/toBase64.js b/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-base64/dist-cjs/toBase64.js new file mode 100644 index 00000000..0590ce3f --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-base64/dist-cjs/toBase64.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.toBase64 = void 0; +const util_buffer_from_1 = require("@smithy/util-buffer-from"); +const util_utf8_1 = require("@smithy/util-utf8"); +const toBase64 = (_input) => { + let input; + if (typeof _input === "string") { + input = (0, util_utf8_1.fromUtf8)(_input); + } + else { + input = _input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); + } + return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64"); +}; +exports.toBase64 = toBase64; diff --git a/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-buffer-from/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-buffer-from/dist-cjs/index.js new file mode 100644 index 00000000..b577c9ca --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-buffer-from/dist-cjs/index.js @@ -0,0 +1,20 @@ +'use strict'; + +var isArrayBuffer = require('@smithy/is-array-buffer'); +var buffer = require('buffer'); + +const fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => { + if (!isArrayBuffer.isArrayBuffer(input)) { + throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); + } + return buffer.Buffer.from(input, offset, length); +}; +const fromString = (input, encoding) => { + if (typeof input !== "string") { + throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); + } + return encoding ? buffer.Buffer.from(input, encoding) : buffer.Buffer.from(input); +}; + +exports.fromArrayBuffer = fromArrayBuffer; +exports.fromString = fromString; diff --git a/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js new file mode 100644 index 00000000..3238bb77 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js @@ -0,0 +1,6 @@ +'use strict'; + +const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) || + Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; + +exports.isArrayBuffer = isArrayBuffer; diff --git a/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js new file mode 100644 index 00000000..6d1eb2d1 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js @@ -0,0 +1,38 @@ +'use strict'; + +const SHORT_TO_HEX = {}; +const HEX_TO_SHORT = {}; +for (let i = 0; i < 256; i++) { + let encodedByte = i.toString(16).toLowerCase(); + if (encodedByte.length === 1) { + encodedByte = `0${encodedByte}`; + } + SHORT_TO_HEX[i] = encodedByte; + HEX_TO_SHORT[encodedByte] = i; +} +function fromHex(encoded) { + if (encoded.length % 2 !== 0) { + throw new Error("Hex encoded strings must have an even number length"); + } + const out = new Uint8Array(encoded.length / 2); + for (let i = 0; i < encoded.length; i += 2) { + const encodedByte = encoded.slice(i, i + 2).toLowerCase(); + if (encodedByte in HEX_TO_SHORT) { + out[i / 2] = HEX_TO_SHORT[encodedByte]; + } + else { + throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); + } + } + return out; +} +function toHex(bytes) { + let out = ""; + for (let i = 0; i < bytes.byteLength; i++) { + out += SHORT_TO_HEX[bytes[i]]; + } + return out; +} + +exports.fromHex = fromHex; +exports.toHex = toHex; diff --git a/claude-code-source/node_modules/@smithy/util-uri-escape/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-uri-escape/dist-cjs/index.js new file mode 100644 index 00000000..51001efe --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-uri-escape/dist-cjs/index.js @@ -0,0 +1,43 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + escapeUri: () => escapeUri, + escapeUriPath: () => escapeUriPath +}); +module.exports = __toCommonJS(src_exports); + +// src/escape-uri.ts +var escapeUri = /* @__PURE__ */ __name((uri) => ( + // AWS percent-encodes some extra non-standard characters in a URI + encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode) +), "escapeUri"); +var hexEncode = /* @__PURE__ */ __name((c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`, "hexEncode"); + +// src/escape-uri-path.ts +var escapeUriPath = /* @__PURE__ */ __name((uri) => uri.split("/").map(escapeUri).join("/"), "escapeUriPath"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (module.exports = { + escapeUri, + escapeUriPath +}); + diff --git a/claude-code-source/node_modules/@smithy/util-utf8/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-utf8/dist-cjs/index.js new file mode 100644 index 00000000..7f945100 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-utf8/dist-cjs/index.js @@ -0,0 +1,32 @@ +'use strict'; + +var utilBufferFrom = require('@smithy/util-buffer-from'); + +const fromUtf8 = (input) => { + const buf = utilBufferFrom.fromString(input, "utf8"); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); +}; + +const toUint8Array = (data) => { + if (typeof data === "string") { + return fromUtf8(data); + } + if (ArrayBuffer.isView(data)) { + return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); + } + return new Uint8Array(data); +}; + +const toUtf8 = (input) => { + if (typeof input === "string") { + return input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); + } + return utilBufferFrom.fromArrayBuffer(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); +}; + +exports.fromUtf8 = fromUtf8; +exports.toUint8Array = toUint8Array; +exports.toUtf8 = toUtf8; diff --git a/claude-code-source/node_modules/@smithy/util-utf8/node_modules/@smithy/util-buffer-from/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-utf8/node_modules/@smithy/util-buffer-from/dist-cjs/index.js new file mode 100644 index 00000000..b577c9ca --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-utf8/node_modules/@smithy/util-buffer-from/dist-cjs/index.js @@ -0,0 +1,20 @@ +'use strict'; + +var isArrayBuffer = require('@smithy/is-array-buffer'); +var buffer = require('buffer'); + +const fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => { + if (!isArrayBuffer.isArrayBuffer(input)) { + throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); + } + return buffer.Buffer.from(input, offset, length); +}; +const fromString = (input, encoding) => { + if (typeof input !== "string") { + throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); + } + return encoding ? buffer.Buffer.from(input, encoding) : buffer.Buffer.from(input); +}; + +exports.fromArrayBuffer = fromArrayBuffer; +exports.fromString = fromString; diff --git a/claude-code-source/node_modules/@smithy/util-utf8/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-utf8/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js new file mode 100644 index 00000000..3238bb77 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/util-utf8/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js @@ -0,0 +1,6 @@ +'use strict'; + +const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) || + Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; + +exports.isArrayBuffer = isArrayBuffer; diff --git a/claude-code-source/node_modules/@smithy/uuid/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/uuid/dist-cjs/index.js new file mode 100644 index 00000000..e9399c97 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/uuid/dist-cjs/index.js @@ -0,0 +1,36 @@ +'use strict'; + +var randomUUID = require('./randomUUID'); + +const decimalToHex = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); +const v4 = () => { + if (randomUUID.randomUUID) { + return randomUUID.randomUUID(); + } + const rnds = new Uint8Array(16); + crypto.getRandomValues(rnds); + rnds[6] = (rnds[6] & 0x0f) | 0x40; + rnds[8] = (rnds[8] & 0x3f) | 0x80; + return (decimalToHex[rnds[0]] + + decimalToHex[rnds[1]] + + decimalToHex[rnds[2]] + + decimalToHex[rnds[3]] + + "-" + + decimalToHex[rnds[4]] + + decimalToHex[rnds[5]] + + "-" + + decimalToHex[rnds[6]] + + decimalToHex[rnds[7]] + + "-" + + decimalToHex[rnds[8]] + + decimalToHex[rnds[9]] + + "-" + + decimalToHex[rnds[10]] + + decimalToHex[rnds[11]] + + decimalToHex[rnds[12]] + + decimalToHex[rnds[13]] + + decimalToHex[rnds[14]] + + decimalToHex[rnds[15]]); +}; + +exports.v4 = v4; diff --git a/claude-code-source/node_modules/@smithy/uuid/dist-cjs/randomUUID.js b/claude-code-source/node_modules/@smithy/uuid/dist-cjs/randomUUID.js new file mode 100644 index 00000000..a1a97239 --- /dev/null +++ b/claude-code-source/node_modules/@smithy/uuid/dist-cjs/randomUUID.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.randomUUID = void 0; +const tslib_1 = require("tslib"); +const crypto_1 = tslib_1.__importDefault(require("crypto")); +exports.randomUUID = crypto_1.default.randomUUID.bind(crypto_1.default); diff --git a/claude-code-source/node_modules/@types/node b/claude-code-source/node_modules/@types/node new file mode 120000 index 00000000..55649128 --- /dev/null +++ b/claude-code-source/node_modules/@types/node @@ -0,0 +1 @@ +../.pnpm/@types+node@25.5.0/node_modules/@types/node \ No newline at end of file diff --git a/claude-code-source/node_modules/@types/react b/claude-code-source/node_modules/@types/react new file mode 120000 index 00000000..a92f0bb6 --- /dev/null +++ b/claude-code-source/node_modules/@types/react @@ -0,0 +1 @@ +../.pnpm/@types+react@19.2.14/node_modules/@types/react \ No newline at end of file diff --git a/claude-code-source/node_modules/@types/ws b/claude-code-source/node_modules/@types/ws new file mode 120000 index 00000000..73e151dd --- /dev/null +++ b/claude-code-source/node_modules/@types/ws @@ -0,0 +1 @@ +../.pnpm/@types+ws@8.18.1/node_modules/@types/ws \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/abort-controller/AbortError.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/abort-controller/AbortError.js new file mode 100644 index 00000000..4b5139e8 --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/abort-controller/AbortError.js @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +/** + * This error is thrown when an asynchronous operation has been aborted. + * Check for this error by testing the `name` that the name property of the + * error matches `"AbortError"`. + * + * @example + * ```ts snippet:ReadmeSampleAbortError + * import { AbortError } from "@typespec/ts-http-runtime"; + * + * async function doAsyncWork(options: { abortSignal: AbortSignal }): Promise { + * if (options.abortSignal.aborted) { + * throw new AbortError(); + * } + * + * // do async work + * } + * + * const controller = new AbortController(); + * controller.abort(); + * + * try { + * doAsyncWork({ abortSignal: controller.signal }); + * } catch (e) { + * if (e instanceof Error && e.name === "AbortError") { + * // handle abort error here. + * } + * } + * ``` + */ +export class AbortError extends Error { + constructor(message) { + super(message); + this.name = "AbortError"; + } +} +//# sourceMappingURL=AbortError.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/constants.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/constants.js new file mode 100644 index 00000000..b7e120f4 --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/constants.js @@ -0,0 +1,5 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +export const SDK_VERSION = "0.2.3"; +export const DEFAULT_RETRY_POLICY_COUNT = 3; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/defaultHttpClient.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/defaultHttpClient.js new file mode 100644 index 00000000..f4b15a92 --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/defaultHttpClient.js @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { createNodeHttpClient } from "./nodeHttpClient.js"; +/** + * Create the correct HttpClient for the current environment. + */ +export function createDefaultHttpClient() { + return createNodeHttpClient(); +} +//# sourceMappingURL=defaultHttpClient.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/httpHeaders.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/httpHeaders.js new file mode 100644 index 00000000..ba491c7e --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/httpHeaders.js @@ -0,0 +1,89 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +function normalizeName(name) { + return name.toLowerCase(); +} +function* headerIterator(map) { + for (const entry of map.values()) { + yield [entry.name, entry.value]; + } +} +class HttpHeadersImpl { + constructor(rawHeaders) { + this._headersMap = new Map(); + if (rawHeaders) { + for (const headerName of Object.keys(rawHeaders)) { + this.set(headerName, rawHeaders[headerName]); + } + } + } + /** + * Set a header in this collection with the provided name and value. The name is + * case-insensitive. + * @param name - The name of the header to set. This value is case-insensitive. + * @param value - The value of the header to set. + */ + set(name, value) { + this._headersMap.set(normalizeName(name), { name, value: String(value).trim() }); + } + /** + * Get the header value for the provided header name, or undefined if no header exists in this + * collection with the provided name. + * @param name - The name of the header. This value is case-insensitive. + */ + get(name) { + var _a; + return (_a = this._headersMap.get(normalizeName(name))) === null || _a === void 0 ? void 0 : _a.value; + } + /** + * Get whether or not this header collection contains a header entry for the provided header name. + * @param name - The name of the header to set. This value is case-insensitive. + */ + has(name) { + return this._headersMap.has(normalizeName(name)); + } + /** + * Remove the header with the provided headerName. + * @param name - The name of the header to remove. + */ + delete(name) { + this._headersMap.delete(normalizeName(name)); + } + /** + * Get the JSON object representation of this HTTP header collection. + */ + toJSON(options = {}) { + const result = {}; + if (options.preserveCase) { + for (const entry of this._headersMap.values()) { + result[entry.name] = entry.value; + } + } + else { + for (const [normalizedName, entry] of this._headersMap) { + result[normalizedName] = entry.value; + } + } + return result; + } + /** + * Get the string representation of this HTTP header collection. + */ + toString() { + return JSON.stringify(this.toJSON({ preserveCase: true })); + } + /** + * Iterate over tuples of header [name, value] pairs. + */ + [Symbol.iterator]() { + return headerIterator(this._headersMap); + } +} +/** + * Creates an object that satisfies the `HttpHeaders` interface. + * @param rawHeaders - A simple object representing initial headers + */ +export function createHttpHeaders(rawHeaders) { + return new HttpHeadersImpl(rawHeaders); +} +//# sourceMappingURL=httpHeaders.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/index.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/index.js new file mode 100644 index 00000000..14432ff6 --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/index.js @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +export { AbortError } from "./abort-controller/AbortError.js"; +export { createClientLogger, getLogLevel, setLogLevel, TypeSpecRuntimeLogger, } from "./logger/logger.js"; +export { createHttpHeaders } from "./httpHeaders.js"; +export * from "./auth/schemes.js"; +export * from "./auth/oauth2Flows.js"; +export { createPipelineRequest } from "./pipelineRequest.js"; +export { createEmptyPipeline, } from "./pipeline.js"; +export { RestError, isRestError } from "./restError.js"; +export { stringToUint8Array, uint8ArrayToString } from "./util/bytesEncoding.js"; +export { createDefaultHttpClient } from "./defaultHttpClient.js"; +export { getClient } from "./client/getClient.js"; +export { operationOptionsToRequestParameters } from "./client/operationOptionHelpers.js"; +export { createRestError } from "./client/restError.js"; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/log.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/log.js new file mode 100644 index 00000000..5c452cf7 --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/log.js @@ -0,0 +1,5 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { createClientLogger } from "./logger/logger.js"; +export const logger = createClientLogger("ts-http-runtime"); +//# sourceMappingURL=log.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/logger/debug.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/logger/debug.js new file mode 100644 index 00000000..1ca28d6b --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/logger/debug.js @@ -0,0 +1,93 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { log } from "./log.js"; +const debugEnvVariable = (typeof process !== "undefined" && process.env && process.env.DEBUG) || undefined; +let enabledString; +let enabledNamespaces = []; +let skippedNamespaces = []; +const debuggers = []; +if (debugEnvVariable) { + enable(debugEnvVariable); +} +const debugObj = Object.assign((namespace) => { + return createDebugger(namespace); +}, { + enable, + enabled, + disable, + log, +}); +function enable(namespaces) { + enabledString = namespaces; + enabledNamespaces = []; + skippedNamespaces = []; + const wildcard = /\*/g; + const namespaceList = namespaces.split(",").map((ns) => ns.trim().replace(wildcard, ".*?")); + for (const ns of namespaceList) { + if (ns.startsWith("-")) { + skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`)); + } + else { + enabledNamespaces.push(new RegExp(`^${ns}$`)); + } + } + for (const instance of debuggers) { + instance.enabled = enabled(instance.namespace); + } +} +function enabled(namespace) { + if (namespace.endsWith("*")) { + return true; + } + for (const skipped of skippedNamespaces) { + if (skipped.test(namespace)) { + return false; + } + } + for (const enabledNamespace of enabledNamespaces) { + if (enabledNamespace.test(namespace)) { + return true; + } + } + return false; +} +function disable() { + const result = enabledString || ""; + enable(""); + return result; +} +function createDebugger(namespace) { + const newDebugger = Object.assign(debug, { + enabled: enabled(namespace), + destroy, + log: debugObj.log, + namespace, + extend, + }); + function debug(...args) { + if (!newDebugger.enabled) { + return; + } + if (args.length > 0) { + args[0] = `${namespace} ${args[0]}`; + } + newDebugger.log(...args); + } + debuggers.push(newDebugger); + return newDebugger; +} +function destroy() { + const index = debuggers.indexOf(this); + if (index >= 0) { + debuggers.splice(index, 1); + return true; + } + return false; +} +function extend(namespace) { + const newDebugger = createDebugger(`${this.namespace}:${namespace}`); + newDebugger.log = this.log; + return newDebugger; +} +export default debugObj; +//# sourceMappingURL=debug.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/logger/internal.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/logger/internal.js new file mode 100644 index 00000000..3e5b5461 --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/logger/internal.js @@ -0,0 +1,4 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +export { createLoggerContext, } from "./logger.js"; +//# sourceMappingURL=internal.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/logger/log.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/logger/log.js new file mode 100644 index 00000000..38323684 --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/logger/log.js @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { EOL } from "node:os"; +import util from "node:util"; +import * as process from "node:process"; +export function log(message, ...args) { + process.stderr.write(`${util.format(message, ...args)}${EOL}`); +} +//# sourceMappingURL=log.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/logger/logger.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/logger/logger.js new file mode 100644 index 00000000..25922d80 --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/logger/logger.js @@ -0,0 +1,125 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import debug from "./debug.js"; +const TYPESPEC_RUNTIME_LOG_LEVELS = ["verbose", "info", "warning", "error"]; +const levelMap = { + verbose: 400, + info: 300, + warning: 200, + error: 100, +}; +function patchLogMethod(parent, child) { + child.log = (...args) => { + parent.log(...args); + }; +} +function isTypeSpecRuntimeLogLevel(level) { + return TYPESPEC_RUNTIME_LOG_LEVELS.includes(level); +} +/** + * Creates a logger context base on the provided options. + * @param options - The options for creating a logger context. + * @returns The logger context. + */ +export function createLoggerContext(options) { + const registeredLoggers = new Set(); + const logLevelFromEnv = (typeof process !== "undefined" && process.env && process.env[options.logLevelEnvVarName]) || + undefined; + let logLevel; + const clientLogger = debug(options.namespace); + clientLogger.log = (...args) => { + debug.log(...args); + }; + function contextSetLogLevel(level) { + if (level && !isTypeSpecRuntimeLogLevel(level)) { + throw new Error(`Unknown log level '${level}'. Acceptable values: ${TYPESPEC_RUNTIME_LOG_LEVELS.join(",")}`); + } + logLevel = level; + const enabledNamespaces = []; + for (const logger of registeredLoggers) { + if (shouldEnable(logger)) { + enabledNamespaces.push(logger.namespace); + } + } + debug.enable(enabledNamespaces.join(",")); + } + if (logLevelFromEnv) { + // avoid calling setLogLevel because we don't want a mis-set environment variable to crash + if (isTypeSpecRuntimeLogLevel(logLevelFromEnv)) { + contextSetLogLevel(logLevelFromEnv); + } + else { + console.error(`${options.logLevelEnvVarName} set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${TYPESPEC_RUNTIME_LOG_LEVELS.join(", ")}.`); + } + } + function shouldEnable(logger) { + return Boolean(logLevel && levelMap[logger.level] <= levelMap[logLevel]); + } + function createLogger(parent, level) { + const logger = Object.assign(parent.extend(level), { + level, + }); + patchLogMethod(parent, logger); + if (shouldEnable(logger)) { + const enabledNamespaces = debug.disable(); + debug.enable(enabledNamespaces + "," + logger.namespace); + } + registeredLoggers.add(logger); + return logger; + } + function contextGetLogLevel() { + return logLevel; + } + function contextCreateClientLogger(namespace) { + const clientRootLogger = clientLogger.extend(namespace); + patchLogMethod(clientLogger, clientRootLogger); + return { + error: createLogger(clientRootLogger, "error"), + warning: createLogger(clientRootLogger, "warning"), + info: createLogger(clientRootLogger, "info"), + verbose: createLogger(clientRootLogger, "verbose"), + }; + } + return { + setLogLevel: contextSetLogLevel, + getLogLevel: contextGetLogLevel, + createClientLogger: contextCreateClientLogger, + logger: clientLogger, + }; +} +const context = createLoggerContext({ + logLevelEnvVarName: "TYPESPEC_RUNTIME_LOG_LEVEL", + namespace: "typeSpecRuntime", +}); +/** + * Immediately enables logging at the specified log level. If no level is specified, logging is disabled. + * @param level - The log level to enable for logging. + * Options from most verbose to least verbose are: + * - verbose + * - info + * - warning + * - error + */ +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const TypeSpecRuntimeLogger = context.logger; +/** + * Retrieves the currently specified log level. + */ +export function setLogLevel(logLevel) { + context.setLogLevel(logLevel); +} +/** + * Retrieves the currently specified log level. + */ +export function getLogLevel() { + return context.getLogLevel(); +} +/** + * Creates a logger for use by the SDKs that inherits from `TypeSpecRuntimeLogger`. + * @param namespace - The name of the SDK package. + * @hidden + */ +export function createClientLogger(namespace) { + return context.createClientLogger(namespace); +} +//# sourceMappingURL=logger.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/nodeHttpClient.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/nodeHttpClient.js new file mode 100644 index 00000000..41b51289 --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/nodeHttpClient.js @@ -0,0 +1,341 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import * as http from "node:http"; +import * as https from "node:https"; +import * as zlib from "node:zlib"; +import { Transform } from "node:stream"; +import { AbortError } from "./abort-controller/AbortError.js"; +import { createHttpHeaders } from "./httpHeaders.js"; +import { RestError } from "./restError.js"; +import { logger } from "./log.js"; +import { Sanitizer } from "./util/sanitizer.js"; +const DEFAULT_TLS_SETTINGS = {}; +function isReadableStream(body) { + return body && typeof body.pipe === "function"; +} +function isStreamComplete(stream) { + if (stream.readable === false) { + return Promise.resolve(); + } + return new Promise((resolve) => { + const handler = () => { + resolve(); + stream.removeListener("close", handler); + stream.removeListener("end", handler); + stream.removeListener("error", handler); + }; + stream.on("close", handler); + stream.on("end", handler); + stream.on("error", handler); + }); +} +function isArrayBuffer(body) { + return body && typeof body.byteLength === "number"; +} +class ReportTransform extends Transform { + // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type + _transform(chunk, _encoding, callback) { + this.push(chunk); + this.loadedBytes += chunk.length; + try { + this.progressCallback({ loadedBytes: this.loadedBytes }); + callback(); + } + catch (e) { + callback(e); + } + } + constructor(progressCallback) { + super(); + this.loadedBytes = 0; + this.progressCallback = progressCallback; + } +} +/** + * A HttpClient implementation that uses Node's "https" module to send HTTPS requests. + * @internal + */ +class NodeHttpClient { + constructor() { + this.cachedHttpsAgents = new WeakMap(); + } + /** + * Makes a request over an underlying transport layer and returns the response. + * @param request - The request to be made. + */ + async sendRequest(request) { + var _a, _b, _c; + const abortController = new AbortController(); + let abortListener; + if (request.abortSignal) { + if (request.abortSignal.aborted) { + throw new AbortError("The operation was aborted. Request has already been canceled."); + } + abortListener = (event) => { + if (event.type === "abort") { + abortController.abort(); + } + }; + request.abortSignal.addEventListener("abort", abortListener); + } + let timeoutId; + if (request.timeout > 0) { + timeoutId = setTimeout(() => { + const sanitizer = new Sanitizer(); + logger.info(`request to '${sanitizer.sanitizeUrl(request.url)}' timed out. canceling...`); + abortController.abort(); + }, request.timeout); + } + const acceptEncoding = request.headers.get("Accept-Encoding"); + const shouldDecompress = (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("gzip")) || (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("deflate")); + let body = typeof request.body === "function" ? request.body() : request.body; + if (body && !request.headers.has("Content-Length")) { + const bodyLength = getBodyLength(body); + if (bodyLength !== null) { + request.headers.set("Content-Length", bodyLength); + } + } + let responseStream; + try { + if (body && request.onUploadProgress) { + const onUploadProgress = request.onUploadProgress; + const uploadReportStream = new ReportTransform(onUploadProgress); + uploadReportStream.on("error", (e) => { + logger.error("Error in upload progress", e); + }); + if (isReadableStream(body)) { + body.pipe(uploadReportStream); + } + else { + uploadReportStream.end(body); + } + body = uploadReportStream; + } + const res = await this.makeRequest(request, abortController, body); + if (timeoutId !== undefined) { + clearTimeout(timeoutId); + } + const headers = getResponseHeaders(res); + const status = (_a = res.statusCode) !== null && _a !== void 0 ? _a : 0; + const response = { + status, + headers, + request, + }; + // Responses to HEAD must not have a body. + // If they do return a body, that body must be ignored. + if (request.method === "HEAD") { + // call resume() and not destroy() to avoid closing the socket + // and losing keep alive + res.resume(); + return response; + } + responseStream = shouldDecompress ? getDecodedResponseStream(res, headers) : res; + const onDownloadProgress = request.onDownloadProgress; + if (onDownloadProgress) { + const downloadReportStream = new ReportTransform(onDownloadProgress); + downloadReportStream.on("error", (e) => { + logger.error("Error in download progress", e); + }); + responseStream.pipe(downloadReportStream); + responseStream = downloadReportStream; + } + if ( + // Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code + ((_b = request.streamResponseStatusCodes) === null || _b === void 0 ? void 0 : _b.has(Number.POSITIVE_INFINITY)) || + ((_c = request.streamResponseStatusCodes) === null || _c === void 0 ? void 0 : _c.has(response.status))) { + response.readableStreamBody = responseStream; + } + else { + response.bodyAsText = await streamToText(responseStream); + } + return response; + } + finally { + // clean up event listener + if (request.abortSignal && abortListener) { + let uploadStreamDone = Promise.resolve(); + if (isReadableStream(body)) { + uploadStreamDone = isStreamComplete(body); + } + let downloadStreamDone = Promise.resolve(); + if (isReadableStream(responseStream)) { + downloadStreamDone = isStreamComplete(responseStream); + } + Promise.all([uploadStreamDone, downloadStreamDone]) + .then(() => { + var _a; + // eslint-disable-next-line promise/always-return + if (abortListener) { + (_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.removeEventListener("abort", abortListener); + } + }) + .catch((e) => { + logger.warning("Error when cleaning up abortListener on httpRequest", e); + }); + } + } + } + makeRequest(request, abortController, body) { + var _a; + const url = new URL(request.url); + const isInsecure = url.protocol !== "https:"; + if (isInsecure && !request.allowInsecureConnection) { + throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`); + } + const agent = (_a = request.agent) !== null && _a !== void 0 ? _a : this.getOrCreateAgent(request, isInsecure); + const options = Object.assign({ agent, hostname: url.hostname, path: `${url.pathname}${url.search}`, port: url.port, method: request.method, headers: request.headers.toJSON({ preserveCase: true }) }, request.requestOverrides); + return new Promise((resolve, reject) => { + const req = isInsecure ? http.request(options, resolve) : https.request(options, resolve); + req.once("error", (err) => { + var _a; + reject(new RestError(err.message, { code: (_a = err.code) !== null && _a !== void 0 ? _a : RestError.REQUEST_SEND_ERROR, request })); + }); + abortController.signal.addEventListener("abort", () => { + const abortError = new AbortError("The operation was aborted. Rejecting from abort signal callback while making request."); + req.destroy(abortError); + reject(abortError); + }); + if (body && isReadableStream(body)) { + body.pipe(req); + } + else if (body) { + if (typeof body === "string" || Buffer.isBuffer(body)) { + req.end(body); + } + else if (isArrayBuffer(body)) { + req.end(ArrayBuffer.isView(body) ? Buffer.from(body.buffer) : Buffer.from(body)); + } + else { + logger.error("Unrecognized body type", body); + reject(new RestError("Unrecognized body type")); + } + } + else { + // streams don't like "undefined" being passed as data + req.end(); + } + }); + } + getOrCreateAgent(request, isInsecure) { + var _a; + const disableKeepAlive = request.disableKeepAlive; + // Handle Insecure requests first + if (isInsecure) { + if (disableKeepAlive) { + // keepAlive:false is the default so we don't need a custom Agent + return http.globalAgent; + } + if (!this.cachedHttpAgent) { + // If there is no cached agent create a new one and cache it. + this.cachedHttpAgent = new http.Agent({ keepAlive: true }); + } + return this.cachedHttpAgent; + } + else { + if (disableKeepAlive && !request.tlsSettings) { + // When there are no tlsSettings and keepAlive is false + // we don't need a custom agent + return https.globalAgent; + } + // We use the tlsSettings to index cached clients + const tlsSettings = (_a = request.tlsSettings) !== null && _a !== void 0 ? _a : DEFAULT_TLS_SETTINGS; + // Get the cached agent or create a new one with the + // provided values for keepAlive and tlsSettings + let agent = this.cachedHttpsAgents.get(tlsSettings); + if (agent && agent.options.keepAlive === !disableKeepAlive) { + return agent; + } + logger.info("No cached TLS Agent exist, creating a new Agent"); + agent = new https.Agent(Object.assign({ + // keepAlive is true if disableKeepAlive is false. + keepAlive: !disableKeepAlive }, tlsSettings)); + this.cachedHttpsAgents.set(tlsSettings, agent); + return agent; + } + } +} +function getResponseHeaders(res) { + const headers = createHttpHeaders(); + for (const header of Object.keys(res.headers)) { + const value = res.headers[header]; + if (Array.isArray(value)) { + if (value.length > 0) { + headers.set(header, value[0]); + } + } + else if (value) { + headers.set(header, value); + } + } + return headers; +} +function getDecodedResponseStream(stream, headers) { + const contentEncoding = headers.get("Content-Encoding"); + if (contentEncoding === "gzip") { + const unzip = zlib.createGunzip(); + stream.pipe(unzip); + return unzip; + } + else if (contentEncoding === "deflate") { + const inflate = zlib.createInflate(); + stream.pipe(inflate); + return inflate; + } + return stream; +} +function streamToText(stream) { + return new Promise((resolve, reject) => { + const buffer = []; + stream.on("data", (chunk) => { + if (Buffer.isBuffer(chunk)) { + buffer.push(chunk); + } + else { + buffer.push(Buffer.from(chunk)); + } + }); + stream.on("end", () => { + resolve(Buffer.concat(buffer).toString("utf8")); + }); + stream.on("error", (e) => { + if (e && (e === null || e === void 0 ? void 0 : e.name) === "AbortError") { + reject(e); + } + else { + reject(new RestError(`Error reading response as text: ${e.message}`, { + code: RestError.PARSE_ERROR, + })); + } + }); + }); +} +/** @internal */ +export function getBodyLength(body) { + if (!body) { + return 0; + } + else if (Buffer.isBuffer(body)) { + return body.length; + } + else if (isReadableStream(body)) { + return null; + } + else if (isArrayBuffer(body)) { + return body.byteLength; + } + else if (typeof body === "string") { + return Buffer.from(body).length; + } + else { + return null; + } +} +/** + * Create a new HttpClient instance for the NodeJS environment. + * @internal + */ +export function createNodeHttpClient() { + return new NodeHttpClient(); +} +//# sourceMappingURL=nodeHttpClient.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/pipeline.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/pipeline.js new file mode 100644 index 00000000..637b8962 --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/pipeline.js @@ -0,0 +1,262 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +const ValidPhaseNames = new Set(["Deserialize", "Serialize", "Retry", "Sign"]); +/** + * A private implementation of Pipeline. + * Do not export this class from the package. + * @internal + */ +class HttpPipeline { + constructor(policies) { + var _a; + this._policies = []; + this._policies = (_a = policies === null || policies === void 0 ? void 0 : policies.slice(0)) !== null && _a !== void 0 ? _a : []; + this._orderedPolicies = undefined; + } + addPolicy(policy, options = {}) { + if (options.phase && options.afterPhase) { + throw new Error("Policies inside a phase cannot specify afterPhase."); + } + if (options.phase && !ValidPhaseNames.has(options.phase)) { + throw new Error(`Invalid phase name: ${options.phase}`); + } + if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) { + throw new Error(`Invalid afterPhase name: ${options.afterPhase}`); + } + this._policies.push({ + policy, + options, + }); + this._orderedPolicies = undefined; + } + removePolicy(options) { + const removedPolicies = []; + this._policies = this._policies.filter((policyDescriptor) => { + if ((options.name && policyDescriptor.policy.name === options.name) || + (options.phase && policyDescriptor.options.phase === options.phase)) { + removedPolicies.push(policyDescriptor.policy); + return false; + } + else { + return true; + } + }); + this._orderedPolicies = undefined; + return removedPolicies; + } + sendRequest(httpClient, request) { + const policies = this.getOrderedPolicies(); + const pipeline = policies.reduceRight((next, policy) => { + return (req) => { + return policy.sendRequest(req, next); + }; + }, (req) => httpClient.sendRequest(req)); + return pipeline(request); + } + getOrderedPolicies() { + if (!this._orderedPolicies) { + this._orderedPolicies = this.orderPolicies(); + } + return this._orderedPolicies; + } + clone() { + return new HttpPipeline(this._policies); + } + static create() { + return new HttpPipeline(); + } + orderPolicies() { + /** + * The goal of this method is to reliably order pipeline policies + * based on their declared requirements when they were added. + * + * Order is first determined by phase: + * + * 1. Serialize Phase + * 2. Policies not in a phase + * 3. Deserialize Phase + * 4. Retry Phase + * 5. Sign Phase + * + * Within each phase, policies are executed in the order + * they were added unless they were specified to execute + * before/after other policies or after a particular phase. + * + * To determine the final order, we will walk the policy list + * in phase order multiple times until all dependencies are + * satisfied. + * + * `afterPolicies` are the set of policies that must be + * executed before a given policy. This requirement is + * considered satisfied when each of the listed policies + * have been scheduled. + * + * `beforePolicies` are the set of policies that must be + * executed after a given policy. Since this dependency + * can be expressed by converting it into a equivalent + * `afterPolicies` declarations, they are normalized + * into that form for simplicity. + * + * An `afterPhase` dependency is considered satisfied when all + * policies in that phase have scheduled. + * + */ + const result = []; + // Track all policies we know about. + const policyMap = new Map(); + function createPhase(name) { + return { + name, + policies: new Set(), + hasRun: false, + hasAfterPolicies: false, + }; + } + // Track policies for each phase. + const serializePhase = createPhase("Serialize"); + const noPhase = createPhase("None"); + const deserializePhase = createPhase("Deserialize"); + const retryPhase = createPhase("Retry"); + const signPhase = createPhase("Sign"); + // a list of phases in order + const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase]; + // Small helper function to map phase name to each Phase + function getPhase(phase) { + if (phase === "Retry") { + return retryPhase; + } + else if (phase === "Serialize") { + return serializePhase; + } + else if (phase === "Deserialize") { + return deserializePhase; + } + else if (phase === "Sign") { + return signPhase; + } + else { + return noPhase; + } + } + // First walk each policy and create a node to track metadata. + for (const descriptor of this._policies) { + const policy = descriptor.policy; + const options = descriptor.options; + const policyName = policy.name; + if (policyMap.has(policyName)) { + throw new Error("Duplicate policy names not allowed in pipeline"); + } + const node = { + policy, + dependsOn: new Set(), + dependants: new Set(), + }; + if (options.afterPhase) { + node.afterPhase = getPhase(options.afterPhase); + node.afterPhase.hasAfterPolicies = true; + } + policyMap.set(policyName, node); + const phase = getPhase(options.phase); + phase.policies.add(node); + } + // Now that each policy has a node, connect dependency references. + for (const descriptor of this._policies) { + const { policy, options } = descriptor; + const policyName = policy.name; + const node = policyMap.get(policyName); + if (!node) { + throw new Error(`Missing node for policy ${policyName}`); + } + if (options.afterPolicies) { + for (const afterPolicyName of options.afterPolicies) { + const afterNode = policyMap.get(afterPolicyName); + if (afterNode) { + // Linking in both directions helps later + // when we want to notify dependants. + node.dependsOn.add(afterNode); + afterNode.dependants.add(node); + } + } + } + if (options.beforePolicies) { + for (const beforePolicyName of options.beforePolicies) { + const beforeNode = policyMap.get(beforePolicyName); + if (beforeNode) { + // To execute before another node, make it + // depend on the current node. + beforeNode.dependsOn.add(node); + node.dependants.add(beforeNode); + } + } + } + } + function walkPhase(phase) { + phase.hasRun = true; + // Sets iterate in insertion order + for (const node of phase.policies) { + if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) { + // If this node is waiting on a phase to complete, + // we need to skip it for now. + // Even if the phase is empty, we should wait for it + // to be walked to avoid re-ordering policies. + continue; + } + if (node.dependsOn.size === 0) { + // If there's nothing else we're waiting for, we can + // add this policy to the result list. + result.push(node.policy); + // Notify anything that depends on this policy that + // the policy has been scheduled. + for (const dependant of node.dependants) { + dependant.dependsOn.delete(node); + } + policyMap.delete(node.policy.name); + phase.policies.delete(node); + } + } + } + function walkPhases() { + for (const phase of orderedPhases) { + walkPhase(phase); + // if the phase isn't complete + if (phase.policies.size > 0 && phase !== noPhase) { + if (!noPhase.hasRun) { + // Try running noPhase to see if that unblocks this phase next tick. + // This can happen if a phase that happens before noPhase + // is waiting on a noPhase policy to complete. + walkPhase(noPhase); + } + // Don't proceed to the next phase until this phase finishes. + return; + } + if (phase.hasAfterPolicies) { + // Run any policies unblocked by this phase + walkPhase(noPhase); + } + } + } + // Iterate until we've put every node in the result list. + let iteration = 0; + while (policyMap.size > 0) { + iteration++; + const initialResultLength = result.length; + // Keep walking each phase in order until we can order every node. + walkPhases(); + // The result list *should* get at least one larger each time + // after the first full pass. + // Otherwise, we're going to loop forever. + if (result.length <= initialResultLength && iteration > 1) { + throw new Error("Cannot satisfy policy dependencies due to requirements cycle."); + } + } + return result; + } +} +/** + * Creates a totally empty pipeline. + * Useful for testing or creating a custom one. + */ +export function createEmptyPipeline() { + return HttpPipeline.create(); +} +//# sourceMappingURL=pipeline.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/pipelineRequest.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/pipelineRequest.js new file mode 100644 index 00000000..2a7501a3 --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/pipelineRequest.js @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { createHttpHeaders } from "./httpHeaders.js"; +import { randomUUID } from "./util/uuidUtils.js"; +class PipelineRequestImpl { + constructor(options) { + var _a, _b, _c, _d, _e, _f, _g; + this.url = options.url; + this.body = options.body; + this.headers = (_a = options.headers) !== null && _a !== void 0 ? _a : createHttpHeaders(); + this.method = (_b = options.method) !== null && _b !== void 0 ? _b : "GET"; + this.timeout = (_c = options.timeout) !== null && _c !== void 0 ? _c : 0; + this.multipartBody = options.multipartBody; + this.formData = options.formData; + this.disableKeepAlive = (_d = options.disableKeepAlive) !== null && _d !== void 0 ? _d : false; + this.proxySettings = options.proxySettings; + this.streamResponseStatusCodes = options.streamResponseStatusCodes; + this.withCredentials = (_e = options.withCredentials) !== null && _e !== void 0 ? _e : false; + this.abortSignal = options.abortSignal; + this.onUploadProgress = options.onUploadProgress; + this.onDownloadProgress = options.onDownloadProgress; + this.requestId = options.requestId || randomUUID(); + this.allowInsecureConnection = (_f = options.allowInsecureConnection) !== null && _f !== void 0 ? _f : false; + this.enableBrowserStreams = (_g = options.enableBrowserStreams) !== null && _g !== void 0 ? _g : false; + this.requestOverrides = options.requestOverrides; + this.authSchemes = options.authSchemes; + } +} +/** + * 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) { + return new PipelineRequestImpl(options); +} +//# sourceMappingURL=pipelineRequest.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/agentPolicy.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/agentPolicy.js new file mode 100644 index 00000000..3f770ed6 --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/agentPolicy.js @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +/** + * Name of the Agent Policy + */ +export const agentPolicyName = "agentPolicy"; +/** + * Gets a pipeline policy that sets http.agent + */ +export function agentPolicy(agent) { + return { + name: agentPolicyName, + sendRequest: async (req, next) => { + // Users may define an agent on the request, honor it over the client level one + if (!req.agent) { + req.agent = agent; + } + return next(req); + }, + }; +} +//# sourceMappingURL=agentPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/decompressResponsePolicy.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/decompressResponsePolicy.js new file mode 100644 index 00000000..d687748a --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/decompressResponsePolicy.js @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +/** + * The programmatic identifier of the decompressResponsePolicy. + */ +export 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 function decompressResponsePolicy() { + return { + name: decompressResponsePolicyName, + async sendRequest(request, next) { + // HEAD requests have no body + if (request.method !== "HEAD") { + request.headers.set("Accept-Encoding", "gzip,deflate"); + } + return next(request); + }, + }; +} +//# sourceMappingURL=decompressResponsePolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/defaultRetryPolicy.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/defaultRetryPolicy.js new file mode 100644 index 00000000..791c0baa --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/defaultRetryPolicy.js @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { exponentialRetryStrategy } from "../retryStrategies/exponentialRetryStrategy.js"; +import { throttlingRetryStrategy } from "../retryStrategies/throttlingRetryStrategy.js"; +import { retryPolicy } from "./retryPolicy.js"; +import { DEFAULT_RETRY_POLICY_COUNT } from "../constants.js"; +/** + * Name of the {@link defaultRetryPolicy} + */ +export const defaultRetryPolicyName = "defaultRetryPolicy"; +/** + * 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 = {}) { + var _a; + return { + name: defaultRetryPolicyName, + sendRequest: retryPolicy([throttlingRetryStrategy(), exponentialRetryStrategy(options)], { + maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : DEFAULT_RETRY_POLICY_COUNT, + }).sendRequest, + }; +} +//# sourceMappingURL=defaultRetryPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/formDataPolicy.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/formDataPolicy.js new file mode 100644 index 00000000..2c05f02f --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/formDataPolicy.js @@ -0,0 +1,97 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { stringToUint8Array } from "../util/bytesEncoding.js"; +import { isNodeLike } from "../util/checkEnvironment.js"; +import { createHttpHeaders } from "../httpHeaders.js"; +/** + * The programmatic identifier of the formDataPolicy. + */ +export const formDataPolicyName = "formDataPolicy"; +function formDataToFormDataMap(formData) { + var _a; + const formDataMap = {}; + for (const [key, value] of formData.entries()) { + (_a = formDataMap[key]) !== null && _a !== void 0 ? _a : (formDataMap[key] = []); + formDataMap[key].push(value); + } + return formDataMap; +} +/** + * A policy that encodes FormData on the request into the body. + */ +export function formDataPolicy() { + return { + name: formDataPolicyName, + async sendRequest(request, next) { + if (isNodeLike && typeof FormData !== "undefined" && request.body instanceof FormData) { + request.formData = formDataToFormDataMap(request.body); + request.body = undefined; + } + if (request.formData) { + const contentType = request.headers.get("Content-Type"); + if (contentType && contentType.indexOf("application/x-www-form-urlencoded") !== -1) { + request.body = wwwFormUrlEncode(request.formData); + } + else { + await prepareFormData(request.formData, request); + } + request.formData = undefined; + } + return next(request); + }, + }; +} +function wwwFormUrlEncode(formData) { + const urlSearchParams = new URLSearchParams(); + for (const [key, value] of Object.entries(formData)) { + if (Array.isArray(value)) { + for (const subValue of value) { + urlSearchParams.append(key, subValue.toString()); + } + } + else { + urlSearchParams.append(key, value.toString()); + } + } + return urlSearchParams.toString(); +} +async function prepareFormData(formData, request) { + // validate content type (multipart/form-data) + const contentType = request.headers.get("Content-Type"); + if (contentType && !contentType.startsWith("multipart/form-data")) { + // content type is specified and is not multipart/form-data. Exit. + return; + } + request.headers.set("Content-Type", contentType !== null && contentType !== void 0 ? contentType : "multipart/form-data"); + // set body to MultipartRequestBody using content from FormDataMap + const parts = []; + for (const [fieldName, values] of Object.entries(formData)) { + for (const value of Array.isArray(values) ? values : [values]) { + if (typeof value === "string") { + parts.push({ + headers: createHttpHeaders({ + "Content-Disposition": `form-data; name="${fieldName}"`, + }), + body: stringToUint8Array(value, "utf-8"), + }); + } + else if (value === undefined || value === null || typeof value !== "object") { + throw new Error(`Unexpected value for key ${fieldName}: ${value}. Value should be serialized to string first.`); + } + else { + // using || instead of ?? here since if value.name is empty we should create a file name + const fileName = value.name || "blob"; + const headers = createHttpHeaders(); + headers.set("Content-Disposition", `form-data; name="${fieldName}"; filename="${fileName}"`); + // again, || is used since an empty value.type means the content type is unset + headers.set("Content-Type", value.type || "application/octet-stream"); + parts.push({ + headers, + body: value, + }); + } + } + } + request.multipartBody = { parts }; +} +//# sourceMappingURL=formDataPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/internal.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/internal.js new file mode 100644 index 00000000..d2e2522e --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/internal.js @@ -0,0 +1,17 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +export { agentPolicy, agentPolicyName } from "./agentPolicy.js"; +export { decompressResponsePolicy, decompressResponsePolicyName, } from "./decompressResponsePolicy.js"; +export { defaultRetryPolicy, defaultRetryPolicyName, } from "./defaultRetryPolicy.js"; +export { exponentialRetryPolicy, exponentialRetryPolicyName, } from "./exponentialRetryPolicy.js"; +export { retryPolicy } from "./retryPolicy.js"; +export { systemErrorRetryPolicy, systemErrorRetryPolicyName } from "./systemErrorRetryPolicy.js"; +export { throttlingRetryPolicy, throttlingRetryPolicyName } from "./throttlingRetryPolicy.js"; +export { formDataPolicy, formDataPolicyName } from "./formDataPolicy.js"; +export { logPolicy, logPolicyName } from "./logPolicy.js"; +export { multipartPolicy, multipartPolicyName } from "./multipartPolicy.js"; +export { proxyPolicy, proxyPolicyName, getDefaultProxySettings } from "./proxyPolicy.js"; +export { redirectPolicy, redirectPolicyName } from "./redirectPolicy.js"; +export { tlsPolicy, tlsPolicyName } from "./tlsPolicy.js"; +export { userAgentPolicy, userAgentPolicyName } from "./userAgentPolicy.js"; +//# sourceMappingURL=internal.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/logPolicy.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/logPolicy.js new file mode 100644 index 00000000..2d8d94fd --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/logPolicy.js @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { logger as coreLogger } from "../log.js"; +import { Sanitizer } from "../util/sanitizer.js"; +/** + * The programmatic identifier of the logPolicy. + */ +export const logPolicyName = "logPolicy"; +/** + * A policy that logs all requests and responses. + * @param options - Options to configure logPolicy. + */ +export function logPolicy(options = {}) { + var _a; + const logger = (_a = options.logger) !== null && _a !== void 0 ? _a : coreLogger.info; + const sanitizer = new Sanitizer({ + additionalAllowedHeaderNames: options.additionalAllowedHeaderNames, + additionalAllowedQueryParameters: options.additionalAllowedQueryParameters, + }); + return { + name: logPolicyName, + async sendRequest(request, next) { + if (!logger.enabled) { + return next(request); + } + logger(`Request: ${sanitizer.sanitize(request)}`); + const response = await next(request); + logger(`Response status code: ${response.status}`); + logger(`Headers: ${sanitizer.sanitize(response.headers)}`); + return response; + }, + }; +} +//# sourceMappingURL=logPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/multipartPolicy.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/multipartPolicy.js new file mode 100644 index 00000000..269db9a5 --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/multipartPolicy.js @@ -0,0 +1,112 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { stringToUint8Array } from "../util/bytesEncoding.js"; +import { isBlob } from "../util/typeGuards.js"; +import { randomUUID } from "../util/uuidUtils.js"; +import { concat } from "../util/concat.js"; +function generateBoundary() { + return `----AzSDKFormBoundary${randomUUID()}`; +} +function encodeHeaders(headers) { + let result = ""; + for (const [key, value] of headers) { + result += `${key}: ${value}\r\n`; + } + return result; +} +function getLength(source) { + if (source instanceof Uint8Array) { + return source.byteLength; + } + else if (isBlob(source)) { + // if was created using createFile then -1 means we have an unknown size + return source.size === -1 ? undefined : source.size; + } + else { + return undefined; + } +} +function getTotalLength(sources) { + let total = 0; + for (const source of sources) { + const partLength = getLength(source); + if (partLength === undefined) { + return undefined; + } + else { + total += partLength; + } + } + return total; +} +async function buildRequestBody(request, parts, boundary) { + const sources = [ + stringToUint8Array(`--${boundary}`, "utf-8"), + ...parts.flatMap((part) => [ + stringToUint8Array("\r\n", "utf-8"), + stringToUint8Array(encodeHeaders(part.headers), "utf-8"), + stringToUint8Array("\r\n", "utf-8"), + part.body, + stringToUint8Array(`\r\n--${boundary}`, "utf-8"), + ]), + stringToUint8Array("--\r\n\r\n", "utf-8"), + ]; + const contentLength = getTotalLength(sources); + if (contentLength) { + request.headers.set("Content-Length", contentLength); + } + request.body = await concat(sources); +} +/** + * Name of multipart policy + */ +export const multipartPolicyName = "multipartPolicy"; +const maxBoundaryLength = 70; +const validBoundaryCharacters = new Set(`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'()+,-./:=?`); +function assertValidBoundary(boundary) { + if (boundary.length > maxBoundaryLength) { + throw new Error(`Multipart boundary "${boundary}" exceeds maximum length of 70 characters`); + } + if (Array.from(boundary).some((x) => !validBoundaryCharacters.has(x))) { + throw new Error(`Multipart boundary "${boundary}" contains invalid characters`); + } +} +/** + * Pipeline policy for multipart requests + */ +export function multipartPolicy() { + return { + name: multipartPolicyName, + async sendRequest(request, next) { + var _a; + if (!request.multipartBody) { + return next(request); + } + if (request.body) { + throw new Error("multipartBody and regular body cannot be set at the same time"); + } + let boundary = request.multipartBody.boundary; + const contentTypeHeader = (_a = request.headers.get("Content-Type")) !== null && _a !== void 0 ? _a : "multipart/mixed"; + const parsedHeader = contentTypeHeader.match(/^(multipart\/[^ ;]+)(?:; *boundary=(.+))?$/); + if (!parsedHeader) { + throw new Error(`Got multipart request body, but content-type header was not multipart: ${contentTypeHeader}`); + } + const [, contentType, parsedBoundary] = parsedHeader; + if (parsedBoundary && boundary && parsedBoundary !== boundary) { + throw new Error(`Multipart boundary was specified as ${parsedBoundary} in the header, but got ${boundary} in the request body`); + } + boundary !== null && boundary !== void 0 ? boundary : (boundary = parsedBoundary); + if (boundary) { + assertValidBoundary(boundary); + } + else { + boundary = generateBoundary(); + } + request.headers.set("Content-Type", `${contentType}; boundary=${boundary}`); + await buildRequestBody(request, request.multipartBody.parts, boundary); + request.multipartBody = undefined; + return next(request); + }, + }; +} +//# sourceMappingURL=multipartPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/proxyPolicy.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/proxyPolicy.js new file mode 100644 index 00000000..a722e3dd --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/proxyPolicy.js @@ -0,0 +1,191 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { HttpsProxyAgent } from "https-proxy-agent"; +import { HttpProxyAgent } from "http-proxy-agent"; +import { logger } from "../log.js"; +const HTTPS_PROXY = "HTTPS_PROXY"; +const HTTP_PROXY = "HTTP_PROXY"; +const ALL_PROXY = "ALL_PROXY"; +const NO_PROXY = "NO_PROXY"; +/** + * The programmatic identifier of the proxyPolicy. + */ +export const proxyPolicyName = "proxyPolicy"; +/** + * Stores the patterns specified in NO_PROXY environment variable. + * @internal + */ +export const globalNoProxyList = []; +let noProxyListLoaded = false; +/** A cache of whether a host should bypass the proxy. */ +const globalBypassedMap = new Map(); +function getEnvironmentValue(name) { + if (process.env[name]) { + return process.env[name]; + } + else if (process.env[name.toLowerCase()]) { + return process.env[name.toLowerCase()]; + } + return undefined; +} +function loadEnvironmentProxyValue() { + if (!process) { + return undefined; + } + const httpsProxy = getEnvironmentValue(HTTPS_PROXY); + const allProxy = getEnvironmentValue(ALL_PROXY); + const httpProxy = getEnvironmentValue(HTTP_PROXY); + return httpsProxy || allProxy || httpProxy; +} +/** + * Check whether the host of a given `uri` matches any pattern in the no proxy list. + * If there's a match, any request sent to the same host shouldn't have the proxy settings set. + * This implementation is a port of https://github.com/Azure/azure-sdk-for-net/blob/8cca811371159e527159c7eb65602477898683e2/sdk/core/Azure.Core/src/Pipeline/Internal/HttpEnvironmentProxy.cs#L210 + */ +function isBypassed(uri, noProxyList, bypassedMap) { + if (noProxyList.length === 0) { + return false; + } + const host = new URL(uri).hostname; + if (bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.has(host)) { + return bypassedMap.get(host); + } + let isBypassedFlag = false; + for (const pattern of noProxyList) { + if (pattern[0] === ".") { + // This should match either domain it self or any subdomain or host + // .foo.com will match foo.com it self or *.foo.com + if (host.endsWith(pattern)) { + isBypassedFlag = true; + } + else { + if (host.length === pattern.length - 1 && host === pattern.slice(1)) { + isBypassedFlag = true; + } + } + } + else { + if (host === pattern) { + isBypassedFlag = true; + } + } + } + bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.set(host, isBypassedFlag); + return isBypassedFlag; +} +export function loadNoProxy() { + const noProxy = getEnvironmentValue(NO_PROXY); + noProxyListLoaded = true; + if (noProxy) { + return noProxy + .split(",") + .map((item) => item.trim()) + .filter((item) => item.length); + } + return []; +} +/** + * 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) { + if (!proxyUrl) { + proxyUrl = loadEnvironmentProxyValue(); + if (!proxyUrl) { + return undefined; + } + } + const parsedUrl = new URL(proxyUrl); + const schema = parsedUrl.protocol ? parsedUrl.protocol + "//" : ""; + return { + host: schema + parsedUrl.hostname, + port: Number.parseInt(parsedUrl.port || "80"), + username: parsedUrl.username, + password: parsedUrl.password, + }; +} +/** + * This method attempts to parse a proxy URL from the environment + * variables `HTTPS_PROXY` or `HTTP_PROXY`. + */ +function getDefaultProxySettingsInternal() { + const envProxy = loadEnvironmentProxyValue(); + return envProxy ? new URL(envProxy) : undefined; +} +function getUrlFromProxySettings(settings) { + let parsedProxyUrl; + try { + parsedProxyUrl = new URL(settings.host); + } + catch (_a) { + throw new Error(`Expecting a valid host string in proxy settings, but found "${settings.host}".`); + } + parsedProxyUrl.port = String(settings.port); + if (settings.username) { + parsedProxyUrl.username = settings.username; + } + if (settings.password) { + parsedProxyUrl.password = settings.password; + } + return parsedProxyUrl; +} +function setProxyAgentOnRequest(request, cachedAgents, proxyUrl) { + // Custom Agent should take precedence so if one is present + // we should skip to avoid overwriting it. + if (request.agent) { + return; + } + const url = new URL(request.url); + const isInsecure = url.protocol !== "https:"; + if (request.tlsSettings) { + logger.warning("TLS settings are not supported in combination with custom Proxy, certificates provided to the client will be ignored."); + } + const headers = request.headers.toJSON(); + if (isInsecure) { + if (!cachedAgents.httpProxyAgent) { + cachedAgents.httpProxyAgent = new HttpProxyAgent(proxyUrl, { headers }); + } + request.agent = cachedAgents.httpProxyAgent; + } + else { + if (!cachedAgents.httpsProxyAgent) { + cachedAgents.httpsProxyAgent = new HttpsProxyAgent(proxyUrl, { headers }); + } + request.agent = cachedAgents.httpsProxyAgent; + } +} +/** + * 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) { + if (!noProxyListLoaded) { + globalNoProxyList.push(...loadNoProxy()); + } + const defaultProxy = proxySettings + ? getUrlFromProxySettings(proxySettings) + : getDefaultProxySettingsInternal(); + const cachedAgents = {}; + return { + name: proxyPolicyName, + async sendRequest(request, next) { + var _a; + if (!request.proxySettings && + defaultProxy && + !isBypassed(request.url, (_a = options === null || options === void 0 ? void 0 : options.customNoProxyList) !== null && _a !== void 0 ? _a : globalNoProxyList, (options === null || options === void 0 ? void 0 : options.customNoProxyList) ? undefined : globalBypassedMap)) { + setProxyAgentOnRequest(request, cachedAgents, defaultProxy); + } + else if (request.proxySettings) { + setProxyAgentOnRequest(request, cachedAgents, getUrlFromProxySettings(request.proxySettings)); + } + return next(request); + }, + }; +} +//# sourceMappingURL=proxyPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/redirectPolicy.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/redirectPolicy.js new file mode 100644 index 00000000..0a67fd8e --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/redirectPolicy.js @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +/** + * The programmatic identifier of the redirectPolicy. + */ +export const redirectPolicyName = "redirectPolicy"; +/** + * Methods that are allowed to follow redirects 301 and 302 + */ +const allowedRedirect = ["GET", "HEAD"]; +/** + * 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 = {}) { + const { maxRetries = 20 } = options; + return { + name: redirectPolicyName, + async sendRequest(request, next) { + const response = await next(request); + return handleRedirect(next, response, maxRetries); + }, + }; +} +async function handleRedirect(next, response, maxRetries, currentRetries = 0) { + const { request, status, headers } = response; + const locationHeader = headers.get("location"); + if (locationHeader && + (status === 300 || + (status === 301 && allowedRedirect.includes(request.method)) || + (status === 302 && allowedRedirect.includes(request.method)) || + (status === 303 && request.method === "POST") || + status === 307) && + currentRetries < maxRetries) { + const url = new URL(locationHeader, request.url); + request.url = url.toString(); + // POST request with Status code 303 should be converted into a + // redirected GET request if the redirect url is present in the location header + if (status === 303) { + request.method = "GET"; + request.headers.delete("Content-Length"); + delete request.body; + } + request.headers.delete("Authorization"); + const res = await next(request); + return handleRedirect(next, res, maxRetries, currentRetries + 1); + } + return response; +} +//# sourceMappingURL=redirectPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/retryPolicy.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/retryPolicy.js new file mode 100644 index 00000000..802de0d1 --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/retryPolicy.js @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { delay } from "../util/helpers.js"; +import { AbortError } from "../abort-controller/AbortError.js"; +import { createClientLogger } from "../logger/logger.js"; +import { DEFAULT_RETRY_POLICY_COUNT } from "../constants.js"; +const retryPolicyLogger = createClientLogger("ts-http-runtime retryPolicy"); +/** + * The programmatic identifier of the retryPolicy. + */ +const retryPolicyName = "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 }) { + const logger = options.logger || retryPolicyLogger; + return { + name: retryPolicyName, + async sendRequest(request, next) { + var _a, _b; + let response; + let responseError; + let retryCount = -1; + retryRequest: while (true) { + retryCount += 1; + response = undefined; + responseError = undefined; + try { + logger.info(`Retry ${retryCount}: Attempting to send request`, request.requestId); + response = await next(request); + logger.info(`Retry ${retryCount}: Received a response from request`, request.requestId); + } + catch (e) { + logger.error(`Retry ${retryCount}: Received an error from request`, request.requestId); + // RestErrors are valid targets for the retry strategies. + // If none of the retry strategies can work with them, they will be thrown later in this policy. + // If the received error is not a RestError, it is immediately thrown. + responseError = e; + if (!e || responseError.name !== "RestError") { + throw e; + } + response = responseError.response; + } + if ((_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) { + logger.error(`Retry ${retryCount}: Request aborted.`); + const abortError = new AbortError(); + throw abortError; + } + if (retryCount >= ((_b = options.maxRetries) !== null && _b !== void 0 ? _b : DEFAULT_RETRY_POLICY_COUNT)) { + logger.info(`Retry ${retryCount}: Maximum retries reached. Returning the last received response, or throwing the last received error.`); + if (responseError) { + throw responseError; + } + else if (response) { + return response; + } + else { + throw new Error("Maximum retries reached with no response or error to throw"); + } + } + logger.info(`Retry ${retryCount}: Processing ${strategies.length} retry strategies.`); + strategiesLoop: for (const strategy of strategies) { + const strategyLogger = strategy.logger || logger; + strategyLogger.info(`Retry ${retryCount}: Processing retry strategy ${strategy.name}.`); + const modifiers = strategy.retry({ + retryCount, + response, + responseError, + }); + if (modifiers.skipStrategy) { + strategyLogger.info(`Retry ${retryCount}: Skipped.`); + continue strategiesLoop; + } + const { errorToThrow, retryAfterInMs, redirectTo } = modifiers; + if (errorToThrow) { + strategyLogger.error(`Retry ${retryCount}: Retry strategy ${strategy.name} throws error:`, errorToThrow); + throw errorToThrow; + } + if (retryAfterInMs || retryAfterInMs === 0) { + strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} retries after ${retryAfterInMs}`); + await delay(retryAfterInMs, undefined, { abortSignal: request.abortSignal }); + continue retryRequest; + } + if (redirectTo) { + strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} redirects to ${redirectTo}`); + request.url = redirectTo; + continue retryRequest; + } + } + if (responseError) { + logger.info(`None of the retry strategies could work with the received error. Throwing it.`); + throw responseError; + } + if (response) { + logger.info(`None of the retry strategies could work with the received response. Returning it.`); + return response; + } + // If all the retries skip and there's no response, + // we're still in the retry loop, so a new request will be sent + // until `maxRetries` is reached. + } + }, + }; +} +//# sourceMappingURL=retryPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/tlsPolicy.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/tlsPolicy.js new file mode 100644 index 00000000..d2dd9b2f --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/tlsPolicy.js @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +/** + * Name of the TLS Policy + */ +export const tlsPolicyName = "tlsPolicy"; +/** + * Gets a pipeline policy that adds the client certificate to the HttpClient agent for authentication. + */ +export function tlsPolicy(tlsSettings) { + return { + name: tlsPolicyName, + sendRequest: async (req, next) => { + // Users may define a request tlsSettings, honor those over the client level one + if (!req.tlsSettings) { + req.tlsSettings = tlsSettings; + } + return next(req); + }, + }; +} +//# sourceMappingURL=tlsPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/restError.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/restError.js new file mode 100644 index 00000000..501644dd --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/restError.js @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { isError } from "./util/error.js"; +import { custom } from "./util/inspect.js"; +import { Sanitizer } from "./util/sanitizer.js"; +const errorSanitizer = new Sanitizer(); +/** + * A custom error type for failed pipeline requests. + */ +export class RestError extends Error { + constructor(message, options = {}) { + super(message); + this.name = "RestError"; + this.code = options.code; + this.statusCode = options.statusCode; + // The request and response may contain sensitive information in the headers or body. + // To help prevent this sensitive information being accidentally logged, the request and response + // properties are marked as non-enumerable here. This prevents them showing up in the output of + // JSON.stringify and console.log. + Object.defineProperty(this, "request", { value: options.request, enumerable: false }); + Object.defineProperty(this, "response", { value: options.response, enumerable: false }); + // Logging method for util.inspect in Node + Object.defineProperty(this, custom, { + value: () => { + // Extract non-enumerable properties and add them back. This is OK since in this output the request and + // response get sanitized. + return `RestError: ${this.message} \n ${errorSanitizer.sanitize(Object.assign(Object.assign({}, this), { request: this.request, response: this.response }))}`; + }, + enumerable: false, + }); + Object.setPrototypeOf(this, RestError.prototype); + } +} +/** + * 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. + */ +RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR"; +/** + * This means that parsing the response from the server failed. + * It may have been malformed. + */ +RestError.PARSE_ERROR = "PARSE_ERROR"; +/** + * Typeguard for RestError + * @param e - Something caught by a catch clause. + */ +export function isRestError(e) { + if (e instanceof RestError) { + return true; + } + return isError(e) && e.name === "RestError"; +} +//# sourceMappingURL=restError.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/retryStrategies/exponentialRetryStrategy.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/retryStrategies/exponentialRetryStrategy.js new file mode 100644 index 00000000..78c19d55 --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/retryStrategies/exponentialRetryStrategy.js @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { calculateRetryDelay } from "../util/delay.js"; +import { isThrottlingRetryResponse } from "./throttlingRetryStrategy.js"; +// intervals are in milliseconds +const DEFAULT_CLIENT_RETRY_INTERVAL = 1000; +const DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 64; +/** + * A retry strategy that retries with an exponentially increasing delay in these two cases: + * - When there are errors in the underlying transport layer (e.g. DNS lookup failures). + * - Or otherwise if the outgoing request fails (408, greater or equal than 500, except for 501 and 505). + */ +export function exponentialRetryStrategy(options = {}) { + var _a, _b; + const retryInterval = (_a = options.retryDelayInMs) !== null && _a !== void 0 ? _a : DEFAULT_CLIENT_RETRY_INTERVAL; + const maxRetryInterval = (_b = options.maxRetryDelayInMs) !== null && _b !== void 0 ? _b : DEFAULT_CLIENT_MAX_RETRY_INTERVAL; + return { + name: "exponentialRetryStrategy", + retry({ retryCount, response, responseError }) { + const matchedSystemError = isSystemError(responseError); + const ignoreSystemErrors = matchedSystemError && options.ignoreSystemErrors; + const isExponential = isExponentialRetryResponse(response); + const ignoreExponentialResponse = isExponential && options.ignoreHttpStatusCodes; + const unknownResponse = response && (isThrottlingRetryResponse(response) || !isExponential); + if (unknownResponse || ignoreExponentialResponse || ignoreSystemErrors) { + return { skipStrategy: true }; + } + if (responseError && !matchedSystemError && !isExponential) { + return { errorToThrow: responseError }; + } + return calculateRetryDelay(retryCount, { + retryDelayInMs: retryInterval, + maxRetryDelayInMs: maxRetryInterval, + }); + }, + }; +} +/** + * A response is a retry response if it has status codes: + * - 408, or + * - Greater or equal than 500, except for 501 and 505. + */ +export function isExponentialRetryResponse(response) { + return Boolean(response && + response.status !== undefined && + (response.status >= 500 || response.status === 408) && + response.status !== 501 && + response.status !== 505); +} +/** + * Determines whether an error from a pipeline response was triggered in the network layer. + */ +export function isSystemError(err) { + if (!err) { + return false; + } + return (err.code === "ETIMEDOUT" || + err.code === "ESOCKETTIMEDOUT" || + err.code === "ECONNREFUSED" || + err.code === "ECONNRESET" || + err.code === "ENOENT" || + err.code === "ENOTFOUND"); +} +//# sourceMappingURL=exponentialRetryStrategy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/retryStrategies/throttlingRetryStrategy.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/retryStrategies/throttlingRetryStrategy.js new file mode 100644 index 00000000..ccc2f0c6 --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/retryStrategies/throttlingRetryStrategy.js @@ -0,0 +1,74 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { parseHeaderValueAsNumber } from "../util/helpers.js"; +/** + * The header that comes back from services representing + * the amount of time (minimum) to wait to retry (in seconds or timestamp after which we can retry). + */ +const RetryAfterHeader = "Retry-After"; +/** + * The headers that come back from services representing + * the amount of time (minimum) to wait to retry. + * + * "retry-after-ms", "x-ms-retry-after-ms" : milliseconds + * "Retry-After" : seconds or timestamp + */ +const AllRetryAfterHeaders = ["retry-after-ms", "x-ms-retry-after-ms", RetryAfterHeader]; +/** + * A response is a throttling retry response if it has a throttling status code (429 or 503), + * as long as one of the [ "Retry-After" or "retry-after-ms" or "x-ms-retry-after-ms" ] headers has a valid value. + * + * Returns the `retryAfterInMs` value if the response is a throttling retry response. + * If not throttling retry response, returns `undefined`. + * + * @internal + */ +function getRetryAfterInMs(response) { + if (!(response && [429, 503].includes(response.status))) + return undefined; + try { + // Headers: "retry-after-ms", "x-ms-retry-after-ms", "Retry-After" + for (const header of AllRetryAfterHeaders) { + const retryAfterValue = parseHeaderValueAsNumber(response, header); + if (retryAfterValue === 0 || retryAfterValue) { + // "Retry-After" header ==> seconds + // "retry-after-ms", "x-ms-retry-after-ms" headers ==> milli-seconds + const multiplyingFactor = header === RetryAfterHeader ? 1000 : 1; + return retryAfterValue * multiplyingFactor; // in milli-seconds + } + } + // RetryAfterHeader ("Retry-After") has a special case where it might be formatted as a date instead of a number of seconds + const retryAfterHeader = response.headers.get(RetryAfterHeader); + if (!retryAfterHeader) + return; + const date = Date.parse(retryAfterHeader); + const diff = date - Date.now(); + // negative diff would mean a date in the past, so retry asap with 0 milliseconds + return Number.isFinite(diff) ? Math.max(0, diff) : undefined; + } + catch (_a) { + return undefined; + } +} +/** + * A response is a retry response if it has a throttling status code (429 or 503), + * as long as one of the [ "Retry-After" or "retry-after-ms" or "x-ms-retry-after-ms" ] headers has a valid value. + */ +export function isThrottlingRetryResponse(response) { + return Number.isFinite(getRetryAfterInMs(response)); +} +export function throttlingRetryStrategy() { + return { + name: "throttlingRetryStrategy", + retry({ response }) { + const retryAfterInMs = getRetryAfterInMs(response); + if (!Number.isFinite(retryAfterInMs)) { + return { skipStrategy: true }; + } + return { + retryAfterInMs, + }; + }, + }; +} +//# sourceMappingURL=throttlingRetryStrategy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/bytesEncoding.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/bytesEncoding.js new file mode 100644 index 00000000..432cc94a --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/bytesEncoding.js @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +/** + * The helper that transforms bytes with specific character encoding into string + * @param bytes - the uint8array bytes + * @param format - the format we use to encode the byte + * @returns a string of the encoded string + */ +export function uint8ArrayToString(bytes, format) { + return Buffer.from(bytes).toString(format); +} +/** + * The helper that transforms string to specific character encoded bytes array. + * @param value - the string to be converted + * @param format - the format we use to decode the value + * @returns a uint8array + */ +export function stringToUint8Array(value, format) { + return Buffer.from(value, format); +} +//# sourceMappingURL=bytesEncoding.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/checkEnvironment.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/checkEnvironment.js new file mode 100644 index 00000000..7b38b63a --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/checkEnvironment.js @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +var _a, _b, _c, _d; +/** + * A constant that indicates whether the environment the code is running is a Web Browser. + */ +// eslint-disable-next-line @azure/azure-sdk/ts-no-window +export const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined"; +/** + * A constant that indicates whether the environment the code is running is a Web Worker. + */ +export const isWebWorker = typeof self === "object" && + typeof (self === null || self === void 0 ? void 0 : self.importScripts) === "function" && + (((_a = self.constructor) === null || _a === void 0 ? void 0 : _a.name) === "DedicatedWorkerGlobalScope" || + ((_b = self.constructor) === null || _b === void 0 ? void 0 : _b.name) === "ServiceWorkerGlobalScope" || + ((_c = self.constructor) === null || _c === void 0 ? void 0 : _c.name) === "SharedWorkerGlobalScope"); +/** + * A constant that indicates whether the environment the code is running is Deno. + */ +export const isDeno = typeof Deno !== "undefined" && + typeof Deno.version !== "undefined" && + typeof Deno.version.deno !== "undefined"; +/** + * A constant that indicates whether the environment the code is running is Bun.sh. + */ +export const isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined"; +/** + * A constant that indicates whether the environment the code is running is a Node.js compatible environment. + */ +export const isNodeLike = typeof globalThis.process !== "undefined" && + Boolean(globalThis.process.version) && + Boolean((_d = globalThis.process.versions) === null || _d === void 0 ? void 0 : _d.node); +/** + * A constant that indicates whether the environment the code is running is Node.JS. + */ +export const isNodeRuntime = isNodeLike && !isBun && !isDeno; +/** + * A constant that indicates whether the environment the code is running is in React-Native. + */ +// https://github.com/facebook/react-native/blob/main/packages/react-native/Libraries/Core/setUpNavigator.js +export const isReactNative = typeof navigator !== "undefined" && (navigator === null || navigator === void 0 ? void 0 : navigator.product) === "ReactNative"; +//# sourceMappingURL=checkEnvironment.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/concat.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/concat.js new file mode 100644 index 00000000..7dc6c6ed --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/concat.js @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { __asyncGenerator, __asyncValues, __await } from "tslib"; +import { Readable } from "stream"; +import { isBlob } from "./typeGuards.js"; +function streamAsyncIterator() { + return __asyncGenerator(this, arguments, function* streamAsyncIterator_1() { + const reader = this.getReader(); + try { + while (true) { + const { done, value } = yield __await(reader.read()); + if (done) { + return yield __await(void 0); + } + yield yield __await(value); + } + } + finally { + reader.releaseLock(); + } + }); +} +function makeAsyncIterable(webStream) { + if (!webStream[Symbol.asyncIterator]) { + webStream[Symbol.asyncIterator] = streamAsyncIterator.bind(webStream); + } + if (!webStream.values) { + webStream.values = streamAsyncIterator.bind(webStream); + } +} +function ensureNodeStream(stream) { + if (stream instanceof ReadableStream) { + makeAsyncIterable(stream); + return Readable.fromWeb(stream); + } + else { + return stream; + } +} +function toStream(source) { + if (source instanceof Uint8Array) { + return Readable.from(Buffer.from(source)); + } + else if (isBlob(source)) { + return ensureNodeStream(source.stream()); + } + else { + return ensureNodeStream(source); + } +} +/** + * Utility function that concatenates a set of binary inputs into one combined output. + * + * @param sources - array of sources for the concatenation + * @returns - in Node, a (() =\> NodeJS.ReadableStream) which, when read, produces a concatenation of all the inputs. + * In browser, returns a `Blob` representing all the concatenated inputs. + * + * @internal + */ +export async function concat(sources) { + return function () { + const streams = sources.map((x) => (typeof x === "function" ? x() : x)).map(toStream); + return Readable.from((function () { + return __asyncGenerator(this, arguments, function* () { + var _a, e_1, _b, _c; + for (const stream of streams) { + try { + for (var _d = true, stream_1 = (e_1 = void 0, __asyncValues(stream)), stream_1_1; stream_1_1 = yield __await(stream_1.next()), _a = stream_1_1.done, !_a; _d = true) { + _c = stream_1_1.value; + _d = false; + const chunk = _c; + yield yield __await(chunk); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_d && !_a && (_b = stream_1.return)) yield __await(_b.call(stream_1)); + } + finally { if (e_1) throw e_1.error; } + } + } + }); + })()); + }; +} +//# sourceMappingURL=concat.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/delay.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/delay.js new file mode 100644 index 00000000..b9338b86 --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/delay.js @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { getRandomIntegerInclusive } from "./random.js"; +/** + * Calculates the delay interval for retry attempts using exponential delay with jitter. + * @param retryAttempt - The current retry attempt number. + * @param config - The exponential retry configuration. + * @returns An object containing the calculated retry delay. + */ +export function calculateRetryDelay(retryAttempt, config) { + // Exponentially increase the delay each time + const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt); + // Don't let the delay exceed the maximum + const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay); + // Allow the final value to have some "jitter" (within 50% of the delay size) so + // that retries across multiple clients don't occur simultaneously. + const retryAfterInMs = clampedDelay / 2 + getRandomIntegerInclusive(0, clampedDelay / 2); + return { retryAfterInMs }; +} +//# sourceMappingURL=delay.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/error.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/error.js new file mode 100644 index 00000000..204c75cd --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/error.js @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { isObject } from "./object.js"; +/** + * Typeguard for an error object shape (has name and message) + * @param e - Something caught by a catch clause. + */ +export function isError(e) { + if (isObject(e)) { + const hasName = typeof e.name === "string"; + const hasMessage = typeof e.message === "string"; + return hasName && hasMessage; + } + return false; +} +//# sourceMappingURL=error.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/helpers.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/helpers.js new file mode 100644 index 00000000..a5bd15be --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/helpers.js @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { AbortError } from "../abort-controller/AbortError.js"; +const StandardAbortMessage = "The operation was aborted."; +/** + * A wrapper for setTimeout that resolves a promise after delayInMs milliseconds. + * @param delayInMs - The number of milliseconds to be delayed. + * @param value - The value to be resolved with after a timeout of t milliseconds. + * @param options - The options for delay - currently abort options + * - abortSignal - The abortSignal associated with containing operation. + * - abortErrorMsg - The abort error message associated with containing operation. + * @returns Resolved promise + */ +export function delay(delayInMs, value, options) { + return new Promise((resolve, reject) => { + let timer = undefined; + let onAborted = undefined; + const rejectOnAbort = () => { + return reject(new AbortError((options === null || options === void 0 ? void 0 : options.abortErrorMsg) ? options === null || options === void 0 ? void 0 : options.abortErrorMsg : StandardAbortMessage)); + }; + const removeListeners = () => { + if ((options === null || options === void 0 ? void 0 : options.abortSignal) && onAborted) { + options.abortSignal.removeEventListener("abort", onAborted); + } + }; + onAborted = () => { + if (timer) { + clearTimeout(timer); + } + removeListeners(); + return rejectOnAbort(); + }; + if ((options === null || options === void 0 ? void 0 : options.abortSignal) && options.abortSignal.aborted) { + return rejectOnAbort(); + } + timer = setTimeout(() => { + removeListeners(); + resolve(value); + }, delayInMs); + if (options === null || options === void 0 ? void 0 : options.abortSignal) { + options.abortSignal.addEventListener("abort", onAborted); + } + }); +} +/** + * @internal + * @returns the parsed value or undefined if the parsed value is invalid. + */ +export function parseHeaderValueAsNumber(response, headerName) { + const value = response.headers.get(headerName); + if (!value) + return; + const valueAsNum = Number(value); + if (Number.isNaN(valueAsNum)) + return; + return valueAsNum; +} +//# sourceMappingURL=helpers.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/inspect.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/inspect.js new file mode 100644 index 00000000..4782720f --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/inspect.js @@ -0,0 +1,5 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { inspect } from "node:util"; +export const custom = inspect.custom; +//# sourceMappingURL=inspect.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/internal.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/internal.js new file mode 100644 index 00000000..3676840f --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/internal.js @@ -0,0 +1,12 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +export { calculateRetryDelay } from "./delay.js"; +export { getRandomIntegerInclusive } from "./random.js"; +export { isObject } from "./object.js"; +export { isError } from "./error.js"; +export { computeSha256Hash, computeSha256Hmac } from "./sha256.js"; +export { randomUUID } from "./uuidUtils.js"; +export { isBrowser, isBun, isNodeLike, isNodeRuntime, isDeno, isReactNative, isWebWorker, } from "./checkEnvironment.js"; +export { stringToUint8Array, uint8ArrayToString } from "./bytesEncoding.js"; +export { Sanitizer } from "./sanitizer.js"; +//# sourceMappingURL=internal.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/object.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/object.js new file mode 100644 index 00000000..f3e9e1d1 --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/object.js @@ -0,0 +1,14 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +/** + * Helper to determine when an input is a generic JS object. + * @returns true when input is an object type that is not null, Array, RegExp, or Date. + */ +export function isObject(input) { + return (typeof input === "object" && + input !== null && + !Array.isArray(input) && + !(input instanceof RegExp) && + !(input instanceof Date)); +} +//# sourceMappingURL=object.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/random.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/random.js new file mode 100644 index 00000000..88eee7f7 --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/random.js @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +/** + * Returns a random integer value between a lower and upper bound, + * inclusive of both bounds. + * Note that this uses Math.random and isn't secure. If you need to use + * this for any kind of security purpose, find a better source of random. + * @param min - The smallest integer value allowed. + * @param max - The largest integer value allowed. + */ +export function getRandomIntegerInclusive(min, max) { + // Make sure inputs are integers. + min = Math.ceil(min); + max = Math.floor(max); + // Pick a random offset from zero to the size of the range. + // Since Math.random() can never return 1, we have to make the range one larger + // in order to be inclusive of the maximum value after we take the floor. + const offset = Math.floor(Math.random() * (max - min + 1)); + return offset + min; +} +//# sourceMappingURL=random.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/sanitizer.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/sanitizer.js new file mode 100644 index 00000000..4add75d6 --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/sanitizer.js @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +import { isObject } from "./object.js"; +const RedactedString = "REDACTED"; +// Make sure this list is up-to-date with the one under core/logger/Readme#Keyconcepts +const defaultAllowedHeaderNames = [ + "x-ms-client-request-id", + "x-ms-return-client-request-id", + "x-ms-useragent", + "x-ms-correlation-request-id", + "x-ms-request-id", + "client-request-id", + "ms-cv", + "return-client-request-id", + "traceparent", + "Access-Control-Allow-Credentials", + "Access-Control-Allow-Headers", + "Access-Control-Allow-Methods", + "Access-Control-Allow-Origin", + "Access-Control-Expose-Headers", + "Access-Control-Max-Age", + "Access-Control-Request-Headers", + "Access-Control-Request-Method", + "Origin", + "Accept", + "Accept-Encoding", + "Cache-Control", + "Connection", + "Content-Length", + "Content-Type", + "Date", + "ETag", + "Expires", + "If-Match", + "If-Modified-Since", + "If-None-Match", + "If-Unmodified-Since", + "Last-Modified", + "Pragma", + "Request-Id", + "Retry-After", + "Server", + "Transfer-Encoding", + "User-Agent", + "WWW-Authenticate", +]; +const defaultAllowedQueryParameters = ["api-version"]; +/** + * A utility class to sanitize objects for logging. + */ +export class Sanitizer { + constructor({ additionalAllowedHeaderNames: allowedHeaderNames = [], additionalAllowedQueryParameters: allowedQueryParameters = [], } = {}) { + allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames); + allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters); + this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase())); + this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase())); + } + /** + * Sanitizes an object for logging. + * @param obj - The object to sanitize + * @returns - The sanitized object as a string + */ + sanitize(obj) { + const seen = new Set(); + return JSON.stringify(obj, (key, value) => { + // Ensure Errors include their interesting non-enumerable members + if (value instanceof Error) { + return Object.assign(Object.assign({}, value), { name: value.name, message: value.message }); + } + if (key === "headers") { + return this.sanitizeHeaders(value); + } + else if (key === "url") { + return this.sanitizeUrl(value); + } + else if (key === "query") { + return this.sanitizeQuery(value); + } + else if (key === "body") { + // Don't log the request body + return undefined; + } + else if (key === "response") { + // Don't log response again + return undefined; + } + else if (key === "operationSpec") { + // When using sendOperationRequest, the request carries a massive + // field with the autorest spec. No need to log it. + return undefined; + } + else if (Array.isArray(value) || isObject(value)) { + if (seen.has(value)) { + return "[Circular]"; + } + seen.add(value); + } + return value; + }, 2); + } + /** + * Sanitizes a URL for logging. + * @param value - The URL to sanitize + * @returns - The sanitized URL as a string + */ + sanitizeUrl(value) { + if (typeof value !== "string" || value === null || value === "") { + return value; + } + const url = new URL(value); + if (!url.search) { + return value; + } + for (const [key] of url.searchParams) { + if (!this.allowedQueryParameters.has(key.toLowerCase())) { + url.searchParams.set(key, RedactedString); + } + } + return url.toString(); + } + sanitizeHeaders(obj) { + const sanitized = {}; + for (const key of Object.keys(obj)) { + if (this.allowedHeaderNames.has(key.toLowerCase())) { + sanitized[key] = obj[key]; + } + else { + sanitized[key] = RedactedString; + } + } + return sanitized; + } + sanitizeQuery(value) { + if (typeof value !== "object" || value === null) { + return value; + } + const sanitized = {}; + for (const k of Object.keys(value)) { + if (this.allowedQueryParameters.has(k.toLowerCase())) { + sanitized[k] = value[k]; + } + else { + sanitized[k] = RedactedString; + } + } + return sanitized; + } +} +//# sourceMappingURL=sanitizer.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/typeGuards.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/typeGuards.js new file mode 100644 index 00000000..c8e3b812 --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/typeGuards.js @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +export function isNodeReadableStream(x) { + return Boolean(x && typeof x["pipe"] === "function"); +} +export function isWebReadableStream(x) { + return Boolean(x && + typeof x.getReader === "function" && + typeof x.tee === "function"); +} +export function isBinaryBody(body) { + return (body !== undefined && + (body instanceof Uint8Array || + isReadableStream(body) || + typeof body === "function" || + body instanceof Blob)); +} +export function isReadableStream(x) { + return isNodeReadableStream(x) || isWebReadableStream(x); +} +export function isBlob(x) { + return typeof x.stream === "function"; +} +//# sourceMappingURL=typeGuards.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/uuidUtils.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/uuidUtils.js new file mode 100644 index 00000000..e50afafc --- /dev/null +++ b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/uuidUtils.js @@ -0,0 +1,17 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +var _a; +import { randomUUID as v4RandomUUID } from "node:crypto"; +// NOTE: This is a workaround until we can use `globalThis.crypto.randomUUID` in Node.js 19+. +const uuidFunction = typeof ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.crypto) === null || _a === void 0 ? void 0 : _a.randomUUID) === "function" + ? globalThis.crypto.randomUUID.bind(globalThis.crypto) + : v4RandomUUID; +/** + * Generated Universally Unique Identifier + * + * @returns RFC4122 v4 UUID. + */ +export function randomUUID() { + return uuidFunction(); +} +//# sourceMappingURL=uuidUtils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@xmldom/xmldom/lib/conventions.js b/claude-code-source/node_modules/@xmldom/xmldom/lib/conventions.js new file mode 100644 index 00000000..953f0eff --- /dev/null +++ b/claude-code-source/node_modules/@xmldom/xmldom/lib/conventions.js @@ -0,0 +1,203 @@ +'use strict' + +/** + * Ponyfill for `Array.prototype.find` which is only available in ES6 runtimes. + * + * Works with anything that has a `length` property and index access properties, including NodeList. + * + * @template {unknown} T + * @param {Array | ({length:number, [number]: T})} list + * @param {function (item: T, index: number, list:Array | ({length:number, [number]: T})):boolean} predicate + * @param {Partial>?} ac `Array.prototype` by default, + * allows injecting a custom implementation in tests + * @returns {T | undefined} + * + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find + * @see https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.find + */ +function find(list, predicate, ac) { + if (ac === undefined) { + ac = Array.prototype; + } + if (list && typeof ac.find === 'function') { + return ac.find.call(list, predicate); + } + for (var i = 0; i < list.length; i++) { + if (Object.prototype.hasOwnProperty.call(list, i)) { + var item = list[i]; + if (predicate.call(undefined, item, i, list)) { + return item; + } + } + } +} + +/** + * "Shallow freezes" an object to render it immutable. + * Uses `Object.freeze` if available, + * otherwise the immutability is only in the type. + * + * Is used to create "enum like" objects. + * + * @template T + * @param {T} object the object to freeze + * @param {Pick = Object} oc `Object` by default, + * allows to inject custom object constructor for tests + * @returns {Readonly} + * + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze + */ +function freeze(object, oc) { + if (oc === undefined) { + oc = Object + } + return oc && typeof oc.freeze === 'function' ? oc.freeze(object) : object +} + +/** + * Since we can not rely on `Object.assign` we provide a simplified version + * that is sufficient for our needs. + * + * @param {Object} target + * @param {Object | null | undefined} source + * + * @returns {Object} target + * @throws TypeError if target is not an object + * + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign + * @see https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.assign + */ +function assign(target, source) { + if (target === null || typeof target !== 'object') { + throw new TypeError('target is not an object') + } + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key] + } + } + return target +} + +/** + * All mime types that are allowed as input to `DOMParser.parseFromString` + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#Argument02 MDN + * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#domparsersupportedtype WHATWG HTML Spec + * @see DOMParser.prototype.parseFromString + */ +var MIME_TYPE = freeze({ + /** + * `text/html`, the only mime type that triggers treating an XML document as HTML. + * + * @see DOMParser.SupportedType.isHTML + * @see https://www.iana.org/assignments/media-types/text/html IANA MimeType registration + * @see https://en.wikipedia.org/wiki/HTML Wikipedia + * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString MDN + * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-domparser-parsefromstring WHATWG HTML Spec + */ + HTML: 'text/html', + + /** + * Helper method to check a mime type if it indicates an HTML document + * + * @param {string} [value] + * @returns {boolean} + * + * @see https://www.iana.org/assignments/media-types/text/html IANA MimeType registration + * @see https://en.wikipedia.org/wiki/HTML Wikipedia + * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString MDN + * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-domparser-parsefromstring */ + isHTML: function (value) { + return value === MIME_TYPE.HTML + }, + + /** + * `application/xml`, the standard mime type for XML documents. + * + * @see https://www.iana.org/assignments/media-types/application/xml IANA MimeType registration + * @see https://tools.ietf.org/html/rfc7303#section-9.1 RFC 7303 + * @see https://en.wikipedia.org/wiki/XML_and_MIME Wikipedia + */ + XML_APPLICATION: 'application/xml', + + /** + * `text/html`, an alias for `application/xml`. + * + * @see https://tools.ietf.org/html/rfc7303#section-9.2 RFC 7303 + * @see https://www.iana.org/assignments/media-types/text/xml IANA MimeType registration + * @see https://en.wikipedia.org/wiki/XML_and_MIME Wikipedia + */ + XML_TEXT: 'text/xml', + + /** + * `application/xhtml+xml`, indicates an XML document that has the default HTML namespace, + * but is parsed as an XML document. + * + * @see https://www.iana.org/assignments/media-types/application/xhtml+xml IANA MimeType registration + * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument WHATWG DOM Spec + * @see https://en.wikipedia.org/wiki/XHTML Wikipedia + */ + XML_XHTML_APPLICATION: 'application/xhtml+xml', + + /** + * `image/svg+xml`, + * + * @see https://www.iana.org/assignments/media-types/image/svg+xml IANA MimeType registration + * @see https://www.w3.org/TR/SVG11/ W3C SVG 1.1 + * @see https://en.wikipedia.org/wiki/Scalable_Vector_Graphics Wikipedia + */ + XML_SVG_IMAGE: 'image/svg+xml', +}) + +/** + * Namespaces that are used in this code base. + * + * @see http://www.w3.org/TR/REC-xml-names + */ +var NAMESPACE = freeze({ + /** + * The XHTML namespace. + * + * @see http://www.w3.org/1999/xhtml + */ + HTML: 'http://www.w3.org/1999/xhtml', + + /** + * Checks if `uri` equals `NAMESPACE.HTML`. + * + * @param {string} [uri] + * + * @see NAMESPACE.HTML + */ + isHTML: function (uri) { + return uri === NAMESPACE.HTML + }, + + /** + * The SVG namespace. + * + * @see http://www.w3.org/2000/svg + */ + SVG: 'http://www.w3.org/2000/svg', + + /** + * The `xml:` namespace. + * + * @see http://www.w3.org/XML/1998/namespace + */ + XML: 'http://www.w3.org/XML/1998/namespace', + + /** + * The `xmlns:` namespace + * + * @see https://www.w3.org/2000/xmlns/ + */ + XMLNS: 'http://www.w3.org/2000/xmlns/', +}) + +exports.assign = assign; +exports.find = find; +exports.freeze = freeze; +exports.MIME_TYPE = MIME_TYPE; +exports.NAMESPACE = NAMESPACE; diff --git a/claude-code-source/node_modules/@xmldom/xmldom/lib/dom-parser.js b/claude-code-source/node_modules/@xmldom/xmldom/lib/dom-parser.js new file mode 100644 index 00000000..94769a21 --- /dev/null +++ b/claude-code-source/node_modules/@xmldom/xmldom/lib/dom-parser.js @@ -0,0 +1,322 @@ +var conventions = require("./conventions"); +var dom = require('./dom') +var entities = require('./entities'); +var sax = require('./sax'); + +var DOMImplementation = dom.DOMImplementation; + +var NAMESPACE = conventions.NAMESPACE; + +var ParseError = sax.ParseError; +var XMLReader = sax.XMLReader; + +/** + * Normalizes line ending according to https://www.w3.org/TR/xml11/#sec-line-ends: + * + * > XML parsed entities are often stored in computer files which, + * > for editing convenience, are organized into lines. + * > These lines are typically separated by some combination + * > of the characters CARRIAGE RETURN (#xD) and LINE FEED (#xA). + * > + * > To simplify the tasks of applications, the XML processor must behave + * > as if it normalized all line breaks in external parsed entities (including the document entity) + * > on input, before parsing, by translating all of the following to a single #xA character: + * > + * > 1. the two-character sequence #xD #xA + * > 2. the two-character sequence #xD #x85 + * > 3. the single character #x85 + * > 4. the single character #x2028 + * > 5. any #xD character that is not immediately followed by #xA or #x85. + * + * @param {string} input + * @returns {string} + */ +function normalizeLineEndings(input) { + return input + .replace(/\r[\n\u0085]/g, '\n') + .replace(/[\r\u0085\u2028]/g, '\n') +} + +/** + * @typedef Locator + * @property {number} [columnNumber] + * @property {number} [lineNumber] + */ + +/** + * @typedef DOMParserOptions + * @property {DOMHandler} [domBuilder] + * @property {Function} [errorHandler] + * @property {(string) => string} [normalizeLineEndings] used to replace line endings before parsing + * defaults to `normalizeLineEndings` + * @property {Locator} [locator] + * @property {Record} [xmlns] + * + * @see normalizeLineEndings + */ + +/** + * The DOMParser interface provides the ability to parse XML or HTML source code + * from a string into a DOM `Document`. + * + * _xmldom is different from the spec in that it allows an `options` parameter, + * to override the default behavior._ + * + * @param {DOMParserOptions} [options] + * @constructor + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser + * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-parsing-and-serialization + */ +function DOMParser(options){ + this.options = options ||{locator:{}}; +} + +DOMParser.prototype.parseFromString = function(source,mimeType){ + var options = this.options; + var sax = new XMLReader(); + var domBuilder = options.domBuilder || new DOMHandler();//contentHandler and LexicalHandler + var errorHandler = options.errorHandler; + var locator = options.locator; + var defaultNSMap = options.xmlns||{}; + var isHTML = /\/x?html?$/.test(mimeType);//mimeType.toLowerCase().indexOf('html') > -1; + var entityMap = isHTML ? entities.HTML_ENTITIES : entities.XML_ENTITIES; + if(locator){ + domBuilder.setDocumentLocator(locator) + } + + sax.errorHandler = buildErrorHandler(errorHandler,domBuilder,locator); + sax.domBuilder = options.domBuilder || domBuilder; + if(isHTML){ + defaultNSMap[''] = NAMESPACE.HTML; + } + defaultNSMap.xml = defaultNSMap.xml || NAMESPACE.XML; + var normalize = options.normalizeLineEndings || normalizeLineEndings; + if (source && typeof source === 'string') { + sax.parse( + normalize(source), + defaultNSMap, + entityMap + ) + } else { + sax.errorHandler.error('invalid doc source') + } + return domBuilder.doc; +} +function buildErrorHandler(errorImpl,domBuilder,locator){ + if(!errorImpl){ + if(domBuilder instanceof DOMHandler){ + return domBuilder; + } + errorImpl = domBuilder ; + } + var errorHandler = {} + var isCallback = errorImpl instanceof Function; + locator = locator||{} + function build(key){ + var fn = errorImpl[key]; + if(!fn && isCallback){ + fn = errorImpl.length == 2?function(msg){errorImpl(key,msg)}:errorImpl; + } + errorHandler[key] = fn && function(msg){ + fn('[xmldom '+key+']\t'+msg+_locator(locator)); + }||function(){}; + } + build('warning'); + build('error'); + build('fatalError'); + return errorHandler; +} + +//console.log('#\n\n\n\n\n\n\n####') +/** + * +ContentHandler+ErrorHandler + * +LexicalHandler+EntityResolver2 + * -DeclHandler-DTDHandler + * + * DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler + * DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2 + * @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html + */ +function DOMHandler() { + this.cdata = false; +} +function position(locator,node){ + node.lineNumber = locator.lineNumber; + node.columnNumber = locator.columnNumber; +} +/** + * @see org.xml.sax.ContentHandler#startDocument + * @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html + */ +DOMHandler.prototype = { + startDocument : function() { + this.doc = new DOMImplementation().createDocument(null, null, null); + if (this.locator) { + this.doc.documentURI = this.locator.systemId; + } + }, + startElement:function(namespaceURI, localName, qName, attrs) { + var doc = this.doc; + var el = doc.createElementNS(namespaceURI, qName||localName); + var len = attrs.length; + appendElement(this, el); + this.currentElement = el; + + this.locator && position(this.locator,el) + for (var i = 0 ; i < len; i++) { + var namespaceURI = attrs.getURI(i); + var value = attrs.getValue(i); + var qName = attrs.getQName(i); + var attr = doc.createAttributeNS(namespaceURI, qName); + this.locator &&position(attrs.getLocator(i),attr); + attr.value = attr.nodeValue = value; + el.setAttributeNode(attr) + } + }, + endElement:function(namespaceURI, localName, qName) { + var current = this.currentElement + var tagName = current.tagName; + this.currentElement = current.parentNode; + }, + startPrefixMapping:function(prefix, uri) { + }, + endPrefixMapping:function(prefix) { + }, + processingInstruction:function(target, data) { + var ins = this.doc.createProcessingInstruction(target, data); + this.locator && position(this.locator,ins) + appendElement(this, ins); + }, + ignorableWhitespace:function(ch, start, length) { + }, + characters:function(chars, start, length) { + chars = _toString.apply(this,arguments) + //console.log(chars) + if(chars){ + if (this.cdata) { + var charNode = this.doc.createCDATASection(chars); + } else { + var charNode = this.doc.createTextNode(chars); + } + if(this.currentElement){ + this.currentElement.appendChild(charNode); + }else if(/^\s*$/.test(chars)){ + this.doc.appendChild(charNode); + //process xml + } + this.locator && position(this.locator,charNode) + } + }, + skippedEntity:function(name) { + }, + endDocument:function() { + this.doc.normalize(); + }, + setDocumentLocator:function (locator) { + if(this.locator = locator){// && !('lineNumber' in locator)){ + locator.lineNumber = 0; + } + }, + //LexicalHandler + comment:function(chars, start, length) { + chars = _toString.apply(this,arguments) + var comm = this.doc.createComment(chars); + this.locator && position(this.locator,comm) + appendElement(this, comm); + }, + + startCDATA:function() { + //used in characters() methods + this.cdata = true; + }, + endCDATA:function() { + this.cdata = false; + }, + + startDTD:function(name, publicId, systemId) { + var impl = this.doc.implementation; + if (impl && impl.createDocumentType) { + var dt = impl.createDocumentType(name, publicId, systemId); + this.locator && position(this.locator,dt) + appendElement(this, dt); + this.doc.doctype = dt; + } + }, + /** + * @see org.xml.sax.ErrorHandler + * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html + */ + warning:function(error) { + console.warn('[xmldom warning]\t'+error,_locator(this.locator)); + }, + error:function(error) { + console.error('[xmldom error]\t'+error,_locator(this.locator)); + }, + fatalError:function(error) { + throw new ParseError(error, this.locator); + } +} +function _locator(l){ + if(l){ + return '\n@'+(l.systemId ||'')+'#[line:'+l.lineNumber+',col:'+l.columnNumber+']' + } +} +function _toString(chars,start,length){ + if(typeof chars == 'string'){ + return chars.substr(start,length) + }else{//java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)") + if(chars.length >= start+length || start){ + return new java.lang.String(chars,start,length)+''; + } + return chars; + } +} + +/* + * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html + * used method of org.xml.sax.ext.LexicalHandler: + * #comment(chars, start, length) + * #startCDATA() + * #endCDATA() + * #startDTD(name, publicId, systemId) + * + * + * IGNORED method of org.xml.sax.ext.LexicalHandler: + * #endDTD() + * #startEntity(name) + * #endEntity(name) + * + * + * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html + * IGNORED method of org.xml.sax.ext.DeclHandler + * #attributeDecl(eName, aName, type, mode, value) + * #elementDecl(name, model) + * #externalEntityDecl(name, publicId, systemId) + * #internalEntityDecl(name, value) + * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html + * IGNORED method of org.xml.sax.EntityResolver2 + * #resolveEntity(String name,String publicId,String baseURI,String systemId) + * #resolveEntity(publicId, systemId) + * #getExternalSubset(name, baseURI) + * @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html + * IGNORED method of org.xml.sax.DTDHandler + * #notationDecl(name, publicId, systemId) {}; + * #unparsedEntityDecl(name, publicId, systemId, notationName) {}; + */ +"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(key){ + DOMHandler.prototype[key] = function(){return null} +}) + +/* Private static helpers treated below as private instance methods, so don't need to add these to the public API; we might use a Relator to also get rid of non-standard public properties */ +function appendElement (hander,node) { + if (!hander.currentElement) { + hander.doc.appendChild(node); + } else { + hander.currentElement.appendChild(node); + } +}//appendChild and setAttributeNS are preformance key + +exports.__DOMHandler = DOMHandler; +exports.normalizeLineEndings = normalizeLineEndings; +exports.DOMParser = DOMParser; diff --git a/claude-code-source/node_modules/@xmldom/xmldom/lib/dom.js b/claude-code-source/node_modules/@xmldom/xmldom/lib/dom.js new file mode 100644 index 00000000..aaa745fe --- /dev/null +++ b/claude-code-source/node_modules/@xmldom/xmldom/lib/dom.js @@ -0,0 +1,1840 @@ +var conventions = require("./conventions"); + +var find = conventions.find; +var NAMESPACE = conventions.NAMESPACE; + +/** + * A prerequisite for `[].filter`, to drop elements that are empty + * @param {string} input + * @returns {boolean} + */ +function notEmptyString (input) { + return input !== '' +} +/** + * @see https://infra.spec.whatwg.org/#split-on-ascii-whitespace + * @see https://infra.spec.whatwg.org/#ascii-whitespace + * + * @param {string} input + * @returns {string[]} (can be empty) + */ +function splitOnASCIIWhitespace(input) { + // U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, U+0020 SPACE + return input ? input.split(/[\t\n\f\r ]+/).filter(notEmptyString) : [] +} + +/** + * Adds element as a key to current if it is not already present. + * + * @param {Record} current + * @param {string} element + * @returns {Record} + */ +function orderedSetReducer (current, element) { + if (!current.hasOwnProperty(element)) { + current[element] = true; + } + return current; +} + +/** + * @see https://infra.spec.whatwg.org/#ordered-set + * @param {string} input + * @returns {string[]} + */ +function toOrderedSet(input) { + if (!input) return []; + var list = splitOnASCIIWhitespace(input); + return Object.keys(list.reduce(orderedSetReducer, {})) +} + +/** + * Uses `list.indexOf` to implement something like `Array.prototype.includes`, + * which we can not rely on being available. + * + * @param {any[]} list + * @returns {function(any): boolean} + */ +function arrayIncludes (list) { + return function(element) { + return list && list.indexOf(element) !== -1; + } +} + +function copy(src,dest){ + for(var p in src){ + if (Object.prototype.hasOwnProperty.call(src, p)) { + dest[p] = src[p]; + } + } +} + +/** +^\w+\.prototype\.([_\w]+)\s*=\s*((?:.*\{\s*?[\r\n][\s\S]*?^})|\S.*?(?=[;\r\n]));? +^\w+\.prototype\.([_\w]+)\s*=\s*(\S.*?(?=[;\r\n]));? + */ +function _extends(Class,Super){ + var pt = Class.prototype; + if(!(pt instanceof Super)){ + function t(){}; + t.prototype = Super.prototype; + t = new t(); + copy(pt,t); + Class.prototype = pt = t; + } + if(pt.constructor != Class){ + if(typeof Class != 'function'){ + console.error("unknown Class:"+Class) + } + pt.constructor = Class + } +} + +// Node Types +var NodeType = {} +var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1; +var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2; +var TEXT_NODE = NodeType.TEXT_NODE = 3; +var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4; +var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5; +var ENTITY_NODE = NodeType.ENTITY_NODE = 6; +var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7; +var COMMENT_NODE = NodeType.COMMENT_NODE = 8; +var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9; +var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10; +var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11; +var NOTATION_NODE = NodeType.NOTATION_NODE = 12; + +// ExceptionCode +var ExceptionCode = {} +var ExceptionMessage = {}; +var INDEX_SIZE_ERR = ExceptionCode.INDEX_SIZE_ERR = ((ExceptionMessage[1]="Index size error"),1); +var DOMSTRING_SIZE_ERR = ExceptionCode.DOMSTRING_SIZE_ERR = ((ExceptionMessage[2]="DOMString size error"),2); +var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = ((ExceptionMessage[3]="Hierarchy request error"),3); +var WRONG_DOCUMENT_ERR = ExceptionCode.WRONG_DOCUMENT_ERR = ((ExceptionMessage[4]="Wrong document"),4); +var INVALID_CHARACTER_ERR = ExceptionCode.INVALID_CHARACTER_ERR = ((ExceptionMessage[5]="Invalid character"),5); +var NO_DATA_ALLOWED_ERR = ExceptionCode.NO_DATA_ALLOWED_ERR = ((ExceptionMessage[6]="No data allowed"),6); +var NO_MODIFICATION_ALLOWED_ERR = ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = ((ExceptionMessage[7]="No modification allowed"),7); +var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = ((ExceptionMessage[8]="Not found"),8); +var NOT_SUPPORTED_ERR = ExceptionCode.NOT_SUPPORTED_ERR = ((ExceptionMessage[9]="Not supported"),9); +var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = ((ExceptionMessage[10]="Attribute in use"),10); +//level2 +var INVALID_STATE_ERR = ExceptionCode.INVALID_STATE_ERR = ((ExceptionMessage[11]="Invalid state"),11); +var SYNTAX_ERR = ExceptionCode.SYNTAX_ERR = ((ExceptionMessage[12]="Syntax error"),12); +var INVALID_MODIFICATION_ERR = ExceptionCode.INVALID_MODIFICATION_ERR = ((ExceptionMessage[13]="Invalid modification"),13); +var NAMESPACE_ERR = ExceptionCode.NAMESPACE_ERR = ((ExceptionMessage[14]="Invalid namespace"),14); +var INVALID_ACCESS_ERR = ExceptionCode.INVALID_ACCESS_ERR = ((ExceptionMessage[15]="Invalid access"),15); + +/** + * DOM Level 2 + * Object DOMException + * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html + * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html + */ +function DOMException(code, message) { + if(message instanceof Error){ + var error = message; + }else{ + error = this; + Error.call(this, ExceptionMessage[code]); + this.message = ExceptionMessage[code]; + if(Error.captureStackTrace) Error.captureStackTrace(this, DOMException); + } + error.code = code; + if(message) this.message = this.message + ": " + message; + return error; +}; +DOMException.prototype = Error.prototype; +copy(ExceptionCode,DOMException) + +/** + * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-536297177 + * The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live. + * The items in the NodeList are accessible via an integral index, starting from 0. + */ +function NodeList() { +}; +NodeList.prototype = { + /** + * The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive. + * @standard level1 + */ + length:0, + /** + * Returns the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns null. + * @standard level1 + * @param index unsigned long + * Index into the collection. + * @return Node + * The node at the indexth position in the NodeList, or null if that is not a valid index. + */ + item: function(index) { + return index >= 0 && index < this.length ? this[index] : null; + }, + toString:function(isHTML,nodeFilter){ + for(var buf = [], i = 0;i=0){ + var lastIndex = list.length-1 + while(i0 || key == 'xmlns'){ +// return null; +// } + //console.log() + var i = this.length; + while(i--){ + var attr = this[i]; + //console.log(attr.nodeName,key) + if(attr.nodeName == key){ + return attr; + } + } + }, + setNamedItem: function(attr) { + var el = attr.ownerElement; + if(el && el!=this._ownerElement){ + throw new DOMException(INUSE_ATTRIBUTE_ERR); + } + var oldAttr = this.getNamedItem(attr.nodeName); + _addNamedNode(this._ownerElement,this,attr,oldAttr); + return oldAttr; + }, + /* returns Node */ + setNamedItemNS: function(attr) {// raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR + var el = attr.ownerElement, oldAttr; + if(el && el!=this._ownerElement){ + throw new DOMException(INUSE_ATTRIBUTE_ERR); + } + oldAttr = this.getNamedItemNS(attr.namespaceURI,attr.localName); + _addNamedNode(this._ownerElement,this,attr,oldAttr); + return oldAttr; + }, + + /* returns Node */ + removeNamedItem: function(key) { + var attr = this.getNamedItem(key); + _removeNamedNode(this._ownerElement,this,attr); + return attr; + + + },// raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR + + //for level2 + removeNamedItemNS:function(namespaceURI,localName){ + var attr = this.getNamedItemNS(namespaceURI,localName); + _removeNamedNode(this._ownerElement,this,attr); + return attr; + }, + getNamedItemNS: function(namespaceURI, localName) { + var i = this.length; + while(i--){ + var node = this[i]; + if(node.localName == localName && node.namespaceURI == namespaceURI){ + return node; + } + } + return null; + } +}; + +/** + * The DOMImplementation interface represents an object providing methods + * which are not dependent on any particular document. + * Such an object is returned by the `Document.implementation` property. + * + * __The individual methods describe the differences compared to the specs.__ + * + * @constructor + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation MDN + * @see https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-102161490 DOM Level 1 Core (Initial) + * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-102161490 DOM Level 2 Core + * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-102161490 DOM Level 3 Core + * @see https://dom.spec.whatwg.org/#domimplementation DOM Living Standard + */ +function DOMImplementation() { +} + +DOMImplementation.prototype = { + /** + * The DOMImplementation.hasFeature() method returns a Boolean flag indicating if a given feature is supported. + * The different implementations fairly diverged in what kind of features were reported. + * The latest version of the spec settled to force this method to always return true, where the functionality was accurate and in use. + * + * @deprecated It is deprecated and modern browsers return true in all cases. + * + * @param {string} feature + * @param {string} [version] + * @returns {boolean} always true + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/hasFeature MDN + * @see https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-5CED94D7 DOM Level 1 Core + * @see https://dom.spec.whatwg.org/#dom-domimplementation-hasfeature DOM Living Standard + */ + hasFeature: function(feature, version) { + return true; + }, + /** + * Creates an XML Document object of the specified type with its document element. + * + * __It behaves slightly different from the description in the living standard__: + * - There is no interface/class `XMLDocument`, it returns a `Document` instance. + * - `contentType`, `encoding`, `mode`, `origin`, `url` fields are currently not declared. + * - this implementation is not validating names or qualified names + * (when parsing XML strings, the SAX parser takes care of that) + * + * @param {string|null} namespaceURI + * @param {string} qualifiedName + * @param {DocumentType=null} doctype + * @returns {Document} + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocument MDN + * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocument DOM Level 2 Core (initial) + * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument DOM Level 2 Core + * + * @see https://dom.spec.whatwg.org/#validate-and-extract DOM: Validate and extract + * @see https://www.w3.org/TR/xml/#NT-NameStartChar XML Spec: Names + * @see https://www.w3.org/TR/xml-names/#ns-qualnames XML Namespaces: Qualified names + */ + createDocument: function(namespaceURI, qualifiedName, doctype){ + var doc = new Document(); + doc.implementation = this; + doc.childNodes = new NodeList(); + doc.doctype = doctype || null; + if (doctype){ + doc.appendChild(doctype); + } + if (qualifiedName){ + var root = doc.createElementNS(namespaceURI, qualifiedName); + doc.appendChild(root); + } + return doc; + }, + /** + * Returns a doctype, with the given `qualifiedName`, `publicId`, and `systemId`. + * + * __This behavior is slightly different from the in the specs__: + * - this implementation is not validating names or qualified names + * (when parsing XML strings, the SAX parser takes care of that) + * + * @param {string} qualifiedName + * @param {string} [publicId] + * @param {string} [systemId] + * @returns {DocumentType} which can either be used with `DOMImplementation.createDocument` upon document creation + * or can be put into the document via methods like `Node.insertBefore()` or `Node.replaceChild()` + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocumentType MDN + * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocType DOM Level 2 Core + * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocumenttype DOM Living Standard + * + * @see https://dom.spec.whatwg.org/#validate-and-extract DOM: Validate and extract + * @see https://www.w3.org/TR/xml/#NT-NameStartChar XML Spec: Names + * @see https://www.w3.org/TR/xml-names/#ns-qualnames XML Namespaces: Qualified names + */ + createDocumentType: function(qualifiedName, publicId, systemId){ + var node = new DocumentType(); + node.name = qualifiedName; + node.nodeName = qualifiedName; + node.publicId = publicId || ''; + node.systemId = systemId || ''; + + return node; + } +}; + + +/** + * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247 + */ + +function Node() { +}; + +Node.prototype = { + firstChild : null, + lastChild : null, + previousSibling : null, + nextSibling : null, + attributes : null, + parentNode : null, + childNodes : null, + ownerDocument : null, + nodeValue : null, + namespaceURI : null, + prefix : null, + localName : null, + // Modified in DOM Level 2: + insertBefore:function(newChild, refChild){//raises + return _insertBefore(this,newChild,refChild); + }, + replaceChild:function(newChild, oldChild){//raises + _insertBefore(this, newChild,oldChild, assertPreReplacementValidityInDocument); + if(oldChild){ + this.removeChild(oldChild); + } + }, + removeChild:function(oldChild){ + return _removeChild(this,oldChild); + }, + appendChild:function(newChild){ + return this.insertBefore(newChild,null); + }, + hasChildNodes:function(){ + return this.firstChild != null; + }, + cloneNode:function(deep){ + return cloneNode(this.ownerDocument||this,this,deep); + }, + // Modified in DOM Level 2: + normalize:function(){ + var child = this.firstChild; + while(child){ + var next = child.nextSibling; + if(next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE){ + this.removeChild(next); + child.appendData(next.data); + }else{ + child.normalize(); + child = next; + } + } + }, + // Introduced in DOM Level 2: + isSupported:function(feature, version){ + return this.ownerDocument.implementation.hasFeature(feature,version); + }, + // Introduced in DOM Level 2: + hasAttributes:function(){ + return this.attributes.length>0; + }, + /** + * Look up the prefix associated to the given namespace URI, starting from this node. + * **The default namespace declarations are ignored by this method.** + * See Namespace Prefix Lookup for details on the algorithm used by this method. + * + * _Note: The implementation seems to be incomplete when compared to the algorithm described in the specs._ + * + * @param {string | null} namespaceURI + * @returns {string | null} + * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-lookupNamespacePrefix + * @see https://www.w3.org/TR/DOM-Level-3-Core/namespaces-algorithms.html#lookupNamespacePrefixAlgo + * @see https://dom.spec.whatwg.org/#dom-node-lookupprefix + * @see https://github.com/xmldom/xmldom/issues/322 + */ + lookupPrefix:function(namespaceURI){ + var el = this; + while(el){ + var map = el._nsMap; + //console.dir(map) + if(map){ + for(var n in map){ + if (Object.prototype.hasOwnProperty.call(map, n) && map[n] === namespaceURI) { + return n; + } + } + } + el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode; + } + return null; + }, + // Introduced in DOM Level 3: + lookupNamespaceURI:function(prefix){ + var el = this; + while(el){ + var map = el._nsMap; + //console.dir(map) + if(map){ + if(Object.prototype.hasOwnProperty.call(map, prefix)){ + return map[prefix] ; + } + } + el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode; + } + return null; + }, + // Introduced in DOM Level 3: + isDefaultNamespace:function(namespaceURI){ + var prefix = this.lookupPrefix(namespaceURI); + return prefix == null; + } +}; + + +function _xmlEncoder(c){ + return c == '<' && '<' || + c == '>' && '>' || + c == '&' && '&' || + c == '"' && '"' || + '&#'+c.charCodeAt()+';' +} + + +copy(NodeType,Node); +copy(NodeType,Node.prototype); + +/** + * @param callback return true for continue,false for break + * @return boolean true: break visit; + */ +function _visitNode(node,callback){ + if(callback(node)){ + return true; + } + if(node = node.firstChild){ + do{ + if(_visitNode(node,callback)){return true} + }while(node=node.nextSibling) + } +} + + + +function Document(){ + this.ownerDocument = this; +} + +function _onAddAttribute(doc,el,newAttr){ + doc && doc._inc++; + var ns = newAttr.namespaceURI ; + if(ns === NAMESPACE.XMLNS){ + //update namespace + el._nsMap[newAttr.prefix?newAttr.localName:''] = newAttr.value + } +} + +function _onRemoveAttribute(doc,el,newAttr,remove){ + doc && doc._inc++; + var ns = newAttr.namespaceURI ; + if(ns === NAMESPACE.XMLNS){ + //update namespace + delete el._nsMap[newAttr.prefix?newAttr.localName:''] + } +} + +/** + * Updates `el.childNodes`, updating the indexed items and it's `length`. + * Passing `newChild` means it will be appended. + * Otherwise it's assumed that an item has been removed, + * and `el.firstNode` and it's `.nextSibling` are used + * to walk the current list of child nodes. + * + * @param {Document} doc + * @param {Node} el + * @param {Node} [newChild] + * @private + */ +function _onUpdateChild (doc, el, newChild) { + if(doc && doc._inc){ + doc._inc++; + //update childNodes + var cs = el.childNodes; + if (newChild) { + cs[cs.length++] = newChild; + } else { + var child = el.firstChild; + var i = 0; + while (child) { + cs[i++] = child; + child = child.nextSibling; + } + cs.length = i; + delete cs[cs.length]; + } + } +} + +/** + * Removes the connections between `parentNode` and `child` + * and any existing `child.previousSibling` or `child.nextSibling`. + * + * @see https://github.com/xmldom/xmldom/issues/135 + * @see https://github.com/xmldom/xmldom/issues/145 + * + * @param {Node} parentNode + * @param {Node} child + * @returns {Node} the child that was removed. + * @private + */ +function _removeChild (parentNode, child) { + var previous = child.previousSibling; + var next = child.nextSibling; + if (previous) { + previous.nextSibling = next; + } else { + parentNode.firstChild = next; + } + if (next) { + next.previousSibling = previous; + } else { + parentNode.lastChild = previous; + } + child.parentNode = null; + child.previousSibling = null; + child.nextSibling = null; + _onUpdateChild(parentNode.ownerDocument, parentNode); + return child; +} + +/** + * Returns `true` if `node` can be a parent for insertion. + * @param {Node} node + * @returns {boolean} + */ +function hasValidParentNodeType(node) { + return ( + node && + (node.nodeType === Node.DOCUMENT_NODE || node.nodeType === Node.DOCUMENT_FRAGMENT_NODE || node.nodeType === Node.ELEMENT_NODE) + ); +} + +/** + * Returns `true` if `node` can be inserted according to it's `nodeType`. + * @param {Node} node + * @returns {boolean} + */ +function hasInsertableNodeType(node) { + return ( + node && + (isElementNode(node) || + isTextNode(node) || + isDocTypeNode(node) || + node.nodeType === Node.DOCUMENT_FRAGMENT_NODE || + node.nodeType === Node.COMMENT_NODE || + node.nodeType === Node.PROCESSING_INSTRUCTION_NODE) + ); +} + +/** + * Returns true if `node` is a DOCTYPE node + * @param {Node} node + * @returns {boolean} + */ +function isDocTypeNode(node) { + return node && node.nodeType === Node.DOCUMENT_TYPE_NODE; +} + +/** + * Returns true if the node is an element + * @param {Node} node + * @returns {boolean} + */ +function isElementNode(node) { + return node && node.nodeType === Node.ELEMENT_NODE; +} +/** + * Returns true if `node` is a text node + * @param {Node} node + * @returns {boolean} + */ +function isTextNode(node) { + return node && node.nodeType === Node.TEXT_NODE; +} + +/** + * Check if en element node can be inserted before `child`, or at the end if child is falsy, + * according to the presence and position of a doctype node on the same level. + * + * @param {Document} doc The document node + * @param {Node} child the node that would become the nextSibling if the element would be inserted + * @returns {boolean} `true` if an element can be inserted before child + * @private + * https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity + */ +function isElementInsertionPossible(doc, child) { + var parentChildNodes = doc.childNodes || []; + if (find(parentChildNodes, isElementNode) || isDocTypeNode(child)) { + return false; + } + var docTypeNode = find(parentChildNodes, isDocTypeNode); + return !(child && docTypeNode && parentChildNodes.indexOf(docTypeNode) > parentChildNodes.indexOf(child)); +} + +/** + * Check if en element node can be inserted before `child`, or at the end if child is falsy, + * according to the presence and position of a doctype node on the same level. + * + * @param {Node} doc The document node + * @param {Node} child the node that would become the nextSibling if the element would be inserted + * @returns {boolean} `true` if an element can be inserted before child + * @private + * https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity + */ +function isElementReplacementPossible(doc, child) { + var parentChildNodes = doc.childNodes || []; + + function hasElementChildThatIsNotChild(node) { + return isElementNode(node) && node !== child; + } + + if (find(parentChildNodes, hasElementChildThatIsNotChild)) { + return false; + } + var docTypeNode = find(parentChildNodes, isDocTypeNode); + return !(child && docTypeNode && parentChildNodes.indexOf(docTypeNode) > parentChildNodes.indexOf(child)); +} + +/** + * @private + * Steps 1-5 of the checks before inserting and before replacing a child are the same. + * + * @param {Node} parent the parent node to insert `node` into + * @param {Node} node the node to insert + * @param {Node=} child the node that should become the `nextSibling` of `node` + * @returns {Node} + * @throws DOMException for several node combinations that would create a DOM that is not well-formed. + * @throws DOMException if `child` is provided but is not a child of `parent`. + * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity + * @see https://dom.spec.whatwg.org/#concept-node-replace + */ +function assertPreInsertionValidity1to5(parent, node, child) { + // 1. If `parent` is not a Document, DocumentFragment, or Element node, then throw a "HierarchyRequestError" DOMException. + if (!hasValidParentNodeType(parent)) { + throw new DOMException(HIERARCHY_REQUEST_ERR, 'Unexpected parent node type ' + parent.nodeType); + } + // 2. If `node` is a host-including inclusive ancestor of `parent`, then throw a "HierarchyRequestError" DOMException. + // not implemented! + // 3. If `child` is non-null and its parent is not `parent`, then throw a "NotFoundError" DOMException. + if (child && child.parentNode !== parent) { + throw new DOMException(NOT_FOUND_ERR, 'child not in parent'); + } + if ( + // 4. If `node` is not a DocumentFragment, DocumentType, Element, or CharacterData node, then throw a "HierarchyRequestError" DOMException. + !hasInsertableNodeType(node) || + // 5. If either `node` is a Text node and `parent` is a document, + // the sax parser currently adds top level text nodes, this will be fixed in 0.9.0 + // || (node.nodeType === Node.TEXT_NODE && parent.nodeType === Node.DOCUMENT_NODE) + // or `node` is a doctype and `parent` is not a document, then throw a "HierarchyRequestError" DOMException. + (isDocTypeNode(node) && parent.nodeType !== Node.DOCUMENT_NODE) + ) { + throw new DOMException( + HIERARCHY_REQUEST_ERR, + 'Unexpected node type ' + node.nodeType + ' for parent node type ' + parent.nodeType + ); + } +} + +/** + * @private + * Step 6 of the checks before inserting and before replacing a child are different. + * + * @param {Document} parent the parent node to insert `node` into + * @param {Node} node the node to insert + * @param {Node | undefined} child the node that should become the `nextSibling` of `node` + * @returns {Node} + * @throws DOMException for several node combinations that would create a DOM that is not well-formed. + * @throws DOMException if `child` is provided but is not a child of `parent`. + * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity + * @see https://dom.spec.whatwg.org/#concept-node-replace + */ +function assertPreInsertionValidityInDocument(parent, node, child) { + var parentChildNodes = parent.childNodes || []; + var nodeChildNodes = node.childNodes || []; + + // DocumentFragment + if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { + var nodeChildElements = nodeChildNodes.filter(isElementNode); + // If node has more than one element child or has a Text node child. + if (nodeChildElements.length > 1 || find(nodeChildNodes, isTextNode)) { + throw new DOMException(HIERARCHY_REQUEST_ERR, 'More than one element or text in fragment'); + } + // Otherwise, if `node` has one element child and either `parent` has an element child, + // `child` is a doctype, or `child` is non-null and a doctype is following `child`. + if (nodeChildElements.length === 1 && !isElementInsertionPossible(parent, child)) { + throw new DOMException(HIERARCHY_REQUEST_ERR, 'Element in fragment can not be inserted before doctype'); + } + } + // Element + if (isElementNode(node)) { + // `parent` has an element child, `child` is a doctype, + // or `child` is non-null and a doctype is following `child`. + if (!isElementInsertionPossible(parent, child)) { + throw new DOMException(HIERARCHY_REQUEST_ERR, 'Only one element can be added and only after doctype'); + } + } + // DocumentType + if (isDocTypeNode(node)) { + // `parent` has a doctype child, + if (find(parentChildNodes, isDocTypeNode)) { + throw new DOMException(HIERARCHY_REQUEST_ERR, 'Only one doctype is allowed'); + } + var parentElementChild = find(parentChildNodes, isElementNode); + // `child` is non-null and an element is preceding `child`, + if (child && parentChildNodes.indexOf(parentElementChild) < parentChildNodes.indexOf(child)) { + throw new DOMException(HIERARCHY_REQUEST_ERR, 'Doctype can only be inserted before an element'); + } + // or `child` is null and `parent` has an element child. + if (!child && parentElementChild) { + throw new DOMException(HIERARCHY_REQUEST_ERR, 'Doctype can not be appended since element is present'); + } + } +} + +/** + * @private + * Step 6 of the checks before inserting and before replacing a child are different. + * + * @param {Document} parent the parent node to insert `node` into + * @param {Node} node the node to insert + * @param {Node | undefined} child the node that should become the `nextSibling` of `node` + * @returns {Node} + * @throws DOMException for several node combinations that would create a DOM that is not well-formed. + * @throws DOMException if `child` is provided but is not a child of `parent`. + * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity + * @see https://dom.spec.whatwg.org/#concept-node-replace + */ +function assertPreReplacementValidityInDocument(parent, node, child) { + var parentChildNodes = parent.childNodes || []; + var nodeChildNodes = node.childNodes || []; + + // DocumentFragment + if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { + var nodeChildElements = nodeChildNodes.filter(isElementNode); + // If `node` has more than one element child or has a Text node child. + if (nodeChildElements.length > 1 || find(nodeChildNodes, isTextNode)) { + throw new DOMException(HIERARCHY_REQUEST_ERR, 'More than one element or text in fragment'); + } + // Otherwise, if `node` has one element child and either `parent` has an element child that is not `child` or a doctype is following `child`. + if (nodeChildElements.length === 1 && !isElementReplacementPossible(parent, child)) { + throw new DOMException(HIERARCHY_REQUEST_ERR, 'Element in fragment can not be inserted before doctype'); + } + } + // Element + if (isElementNode(node)) { + // `parent` has an element child that is not `child` or a doctype is following `child`. + if (!isElementReplacementPossible(parent, child)) { + throw new DOMException(HIERARCHY_REQUEST_ERR, 'Only one element can be added and only after doctype'); + } + } + // DocumentType + if (isDocTypeNode(node)) { + function hasDoctypeChildThatIsNotChild(node) { + return isDocTypeNode(node) && node !== child; + } + + // `parent` has a doctype child that is not `child`, + if (find(parentChildNodes, hasDoctypeChildThatIsNotChild)) { + throw new DOMException(HIERARCHY_REQUEST_ERR, 'Only one doctype is allowed'); + } + var parentElementChild = find(parentChildNodes, isElementNode); + // or an element is preceding `child`. + if (child && parentChildNodes.indexOf(parentElementChild) < parentChildNodes.indexOf(child)) { + throw new DOMException(HIERARCHY_REQUEST_ERR, 'Doctype can only be inserted before an element'); + } + } +} + +/** + * @private + * @param {Node} parent the parent node to insert `node` into + * @param {Node} node the node to insert + * @param {Node=} child the node that should become the `nextSibling` of `node` + * @returns {Node} + * @throws DOMException for several node combinations that would create a DOM that is not well-formed. + * @throws DOMException if `child` is provided but is not a child of `parent`. + * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity + */ +function _insertBefore(parent, node, child, _inDocumentAssertion) { + // To ensure pre-insertion validity of a node into a parent before a child, run these steps: + assertPreInsertionValidity1to5(parent, node, child); + + // If parent is a document, and any of the statements below, switched on the interface node implements, + // are true, then throw a "HierarchyRequestError" DOMException. + if (parent.nodeType === Node.DOCUMENT_NODE) { + (_inDocumentAssertion || assertPreInsertionValidityInDocument)(parent, node, child); + } + + var cp = node.parentNode; + if(cp){ + cp.removeChild(node);//remove and update + } + if(node.nodeType === DOCUMENT_FRAGMENT_NODE){ + var newFirst = node.firstChild; + if (newFirst == null) { + return node; + } + var newLast = node.lastChild; + }else{ + newFirst = newLast = node; + } + var pre = child ? child.previousSibling : parent.lastChild; + + newFirst.previousSibling = pre; + newLast.nextSibling = child; + + + if(pre){ + pre.nextSibling = newFirst; + }else{ + parent.firstChild = newFirst; + } + if(child == null){ + parent.lastChild = newLast; + }else{ + child.previousSibling = newLast; + } + do{ + newFirst.parentNode = parent; + }while(newFirst !== newLast && (newFirst= newFirst.nextSibling)) + _onUpdateChild(parent.ownerDocument||parent, parent); + //console.log(parent.lastChild.nextSibling == null) + if (node.nodeType == DOCUMENT_FRAGMENT_NODE) { + node.firstChild = node.lastChild = null; + } + return node; +} + +/** + * Appends `newChild` to `parentNode`. + * If `newChild` is already connected to a `parentNode` it is first removed from it. + * + * @see https://github.com/xmldom/xmldom/issues/135 + * @see https://github.com/xmldom/xmldom/issues/145 + * @param {Node} parentNode + * @param {Node} newChild + * @returns {Node} + * @private + */ +function _appendSingleChild (parentNode, newChild) { + if (newChild.parentNode) { + newChild.parentNode.removeChild(newChild); + } + newChild.parentNode = parentNode; + newChild.previousSibling = parentNode.lastChild; + newChild.nextSibling = null; + if (newChild.previousSibling) { + newChild.previousSibling.nextSibling = newChild; + } else { + parentNode.firstChild = newChild; + } + parentNode.lastChild = newChild; + _onUpdateChild(parentNode.ownerDocument, parentNode, newChild); + return newChild; +} + +Document.prototype = { + //implementation : null, + nodeName : '#document', + nodeType : DOCUMENT_NODE, + /** + * The DocumentType node of the document. + * + * @readonly + * @type DocumentType + */ + doctype : null, + documentElement : null, + _inc : 1, + + insertBefore : function(newChild, refChild){//raises + if(newChild.nodeType == DOCUMENT_FRAGMENT_NODE){ + var child = newChild.firstChild; + while(child){ + var next = child.nextSibling; + this.insertBefore(child,refChild); + child = next; + } + return newChild; + } + _insertBefore(this, newChild, refChild); + newChild.ownerDocument = this; + if (this.documentElement === null && newChild.nodeType === ELEMENT_NODE) { + this.documentElement = newChild; + } + + return newChild; + }, + removeChild : function(oldChild){ + if(this.documentElement == oldChild){ + this.documentElement = null; + } + return _removeChild(this,oldChild); + }, + replaceChild: function (newChild, oldChild) { + //raises + _insertBefore(this, newChild, oldChild, assertPreReplacementValidityInDocument); + newChild.ownerDocument = this; + if (oldChild) { + this.removeChild(oldChild); + } + if (isElementNode(newChild)) { + this.documentElement = newChild; + } + }, + // Introduced in DOM Level 2: + importNode : function(importedNode,deep){ + return importNode(this,importedNode,deep); + }, + // Introduced in DOM Level 2: + getElementById : function(id){ + var rtv = null; + _visitNode(this.documentElement,function(node){ + if(node.nodeType == ELEMENT_NODE){ + if(node.getAttribute('id') == id){ + rtv = node; + return true; + } + } + }) + return rtv; + }, + + /** + * The `getElementsByClassName` method of `Document` interface returns an array-like object + * of all child elements which have **all** of the given class name(s). + * + * Returns an empty list if `classeNames` is an empty string or only contains HTML white space characters. + * + * + * Warning: This is a live LiveNodeList. + * Changes in the DOM will reflect in the array as the changes occur. + * If an element selected by this array no longer qualifies for the selector, + * it will automatically be removed. Be aware of this for iteration purposes. + * + * @param {string} classNames is a string representing the class name(s) to match; multiple class names are separated by (ASCII-)whitespace + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName + * @see https://dom.spec.whatwg.org/#concept-getelementsbyclassname + */ + getElementsByClassName: function(classNames) { + var classNamesSet = toOrderedSet(classNames) + return new LiveNodeList(this, function(base) { + var ls = []; + if (classNamesSet.length > 0) { + _visitNode(base.documentElement, function(node) { + if(node !== base && node.nodeType === ELEMENT_NODE) { + var nodeClassNames = node.getAttribute('class') + // can be null if the attribute does not exist + if (nodeClassNames) { + // before splitting and iterating just compare them for the most common case + var matches = classNames === nodeClassNames; + if (!matches) { + var nodeClassNamesSet = toOrderedSet(nodeClassNames) + matches = classNamesSet.every(arrayIncludes(nodeClassNamesSet)) + } + if(matches) { + ls.push(node); + } + } + } + }); + } + return ls; + }); + }, + + //document factory method: + createElement : function(tagName){ + var node = new Element(); + node.ownerDocument = this; + node.nodeName = tagName; + node.tagName = tagName; + node.localName = tagName; + node.childNodes = new NodeList(); + var attrs = node.attributes = new NamedNodeMap(); + attrs._ownerElement = node; + return node; + }, + createDocumentFragment : function(){ + var node = new DocumentFragment(); + node.ownerDocument = this; + node.childNodes = new NodeList(); + return node; + }, + createTextNode : function(data){ + var node = new Text(); + node.ownerDocument = this; + node.appendData(data) + return node; + }, + createComment : function(data){ + var node = new Comment(); + node.ownerDocument = this; + node.appendData(data) + return node; + }, + createCDATASection : function(data){ + var node = new CDATASection(); + node.ownerDocument = this; + node.appendData(data) + return node; + }, + createProcessingInstruction : function(target,data){ + var node = new ProcessingInstruction(); + node.ownerDocument = this; + node.tagName = node.nodeName = node.target = target; + node.nodeValue = node.data = data; + return node; + }, + createAttribute : function(name){ + var node = new Attr(); + node.ownerDocument = this; + node.name = name; + node.nodeName = name; + node.localName = name; + node.specified = true; + return node; + }, + createEntityReference : function(name){ + var node = new EntityReference(); + node.ownerDocument = this; + node.nodeName = name; + return node; + }, + // Introduced in DOM Level 2: + createElementNS : function(namespaceURI,qualifiedName){ + var node = new Element(); + var pl = qualifiedName.split(':'); + var attrs = node.attributes = new NamedNodeMap(); + node.childNodes = new NodeList(); + node.ownerDocument = this; + node.nodeName = qualifiedName; + node.tagName = qualifiedName; + node.namespaceURI = namespaceURI; + if(pl.length == 2){ + node.prefix = pl[0]; + node.localName = pl[1]; + }else{ + //el.prefix = null; + node.localName = qualifiedName; + } + attrs._ownerElement = node; + return node; + }, + // Introduced in DOM Level 2: + createAttributeNS : function(namespaceURI,qualifiedName){ + var node = new Attr(); + var pl = qualifiedName.split(':'); + node.ownerDocument = this; + node.nodeName = qualifiedName; + node.name = qualifiedName; + node.namespaceURI = namespaceURI; + node.specified = true; + if(pl.length == 2){ + node.prefix = pl[0]; + node.localName = pl[1]; + }else{ + //el.prefix = null; + node.localName = qualifiedName; + } + return node; + } +}; +_extends(Document,Node); + + +function Element() { + this._nsMap = {}; +}; +Element.prototype = { + nodeType : ELEMENT_NODE, + hasAttribute : function(name){ + return this.getAttributeNode(name)!=null; + }, + getAttribute : function(name){ + var attr = this.getAttributeNode(name); + return attr && attr.value || ''; + }, + getAttributeNode : function(name){ + return this.attributes.getNamedItem(name); + }, + setAttribute : function(name, value){ + var attr = this.ownerDocument.createAttribute(name); + attr.value = attr.nodeValue = "" + value; + this.setAttributeNode(attr) + }, + removeAttribute : function(name){ + var attr = this.getAttributeNode(name) + attr && this.removeAttributeNode(attr); + }, + + //four real opeartion method + appendChild:function(newChild){ + if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){ + return this.insertBefore(newChild,null); + }else{ + return _appendSingleChild(this,newChild); + } + }, + setAttributeNode : function(newAttr){ + return this.attributes.setNamedItem(newAttr); + }, + setAttributeNodeNS : function(newAttr){ + return this.attributes.setNamedItemNS(newAttr); + }, + removeAttributeNode : function(oldAttr){ + //console.log(this == oldAttr.ownerElement) + return this.attributes.removeNamedItem(oldAttr.nodeName); + }, + //get real attribute name,and remove it by removeAttributeNode + removeAttributeNS : function(namespaceURI, localName){ + var old = this.getAttributeNodeNS(namespaceURI, localName); + old && this.removeAttributeNode(old); + }, + + hasAttributeNS : function(namespaceURI, localName){ + return this.getAttributeNodeNS(namespaceURI, localName)!=null; + }, + getAttributeNS : function(namespaceURI, localName){ + var attr = this.getAttributeNodeNS(namespaceURI, localName); + return attr && attr.value || ''; + }, + setAttributeNS : function(namespaceURI, qualifiedName, value){ + var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName); + attr.value = attr.nodeValue = "" + value; + this.setAttributeNode(attr) + }, + getAttributeNodeNS : function(namespaceURI, localName){ + return this.attributes.getNamedItemNS(namespaceURI, localName); + }, + + getElementsByTagName : function(tagName){ + return new LiveNodeList(this,function(base){ + var ls = []; + _visitNode(base,function(node){ + if(node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)){ + ls.push(node); + } + }); + return ls; + }); + }, + getElementsByTagNameNS : function(namespaceURI, localName){ + return new LiveNodeList(this,function(base){ + var ls = []; + _visitNode(base,function(node){ + if(node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)){ + ls.push(node); + } + }); + return ls; + + }); + } +}; +Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName; +Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS; + + +_extends(Element,Node); +function Attr() { +}; +Attr.prototype.nodeType = ATTRIBUTE_NODE; +_extends(Attr,Node); + + +function CharacterData() { +}; +CharacterData.prototype = { + data : '', + substringData : function(offset, count) { + return this.data.substring(offset, offset+count); + }, + appendData: function(text) { + text = this.data+text; + this.nodeValue = this.data = text; + this.length = text.length; + }, + insertData: function(offset,text) { + this.replaceData(offset,0,text); + + }, + appendChild:function(newChild){ + throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR]) + }, + deleteData: function(offset, count) { + this.replaceData(offset,count,""); + }, + replaceData: function(offset, count, text) { + var start = this.data.substring(0,offset); + var end = this.data.substring(offset+count); + text = start + text + end; + this.nodeValue = this.data = text; + this.length = text.length; + } +} +_extends(CharacterData,Node); +function Text() { +}; +Text.prototype = { + nodeName : "#text", + nodeType : TEXT_NODE, + splitText : function(offset) { + var text = this.data; + var newText = text.substring(offset); + text = text.substring(0, offset); + this.data = this.nodeValue = text; + this.length = text.length; + var newNode = this.ownerDocument.createTextNode(newText); + if(this.parentNode){ + this.parentNode.insertBefore(newNode, this.nextSibling); + } + return newNode; + } +} +_extends(Text,CharacterData); +function Comment() { +}; +Comment.prototype = { + nodeName : "#comment", + nodeType : COMMENT_NODE +} +_extends(Comment,CharacterData); + +function CDATASection() { +}; +CDATASection.prototype = { + nodeName : "#cdata-section", + nodeType : CDATA_SECTION_NODE +} +_extends(CDATASection,CharacterData); + + +function DocumentType() { +}; +DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE; +_extends(DocumentType,Node); + +function Notation() { +}; +Notation.prototype.nodeType = NOTATION_NODE; +_extends(Notation,Node); + +function Entity() { +}; +Entity.prototype.nodeType = ENTITY_NODE; +_extends(Entity,Node); + +function EntityReference() { +}; +EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE; +_extends(EntityReference,Node); + +function DocumentFragment() { +}; +DocumentFragment.prototype.nodeName = "#document-fragment"; +DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE; +_extends(DocumentFragment,Node); + + +function ProcessingInstruction() { +} +ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE; +_extends(ProcessingInstruction,Node); +function XMLSerializer(){} +XMLSerializer.prototype.serializeToString = function(node,isHtml,nodeFilter){ + return nodeSerializeToString.call(node,isHtml,nodeFilter); +} +Node.prototype.toString = nodeSerializeToString; +function nodeSerializeToString(isHtml,nodeFilter){ + var buf = []; + var refNode = this.nodeType == 9 && this.documentElement || this; + var prefix = refNode.prefix; + var uri = refNode.namespaceURI; + + if(uri && prefix == null){ + //console.log(prefix) + var prefix = refNode.lookupPrefix(uri); + if(prefix == null){ + //isHTML = true; + var visibleNamespaces=[ + {namespace:uri,prefix:null} + //{namespace:uri,prefix:''} + ] + } + } + serializeToString(this,buf,isHtml,nodeFilter,visibleNamespaces); + //console.log('###',this.nodeType,uri,prefix,buf.join('')) + return buf.join(''); +} + +function needNamespaceDefine(node, isHTML, visibleNamespaces) { + var prefix = node.prefix || ''; + var uri = node.namespaceURI; + // According to [Namespaces in XML 1.0](https://www.w3.org/TR/REC-xml-names/#ns-using) , + // and more specifically https://www.w3.org/TR/REC-xml-names/#nsc-NoPrefixUndecl : + // > In a namespace declaration for a prefix [...], the attribute value MUST NOT be empty. + // in a similar manner [Namespaces in XML 1.1](https://www.w3.org/TR/xml-names11/#ns-using) + // and more specifically https://www.w3.org/TR/xml-names11/#nsc-NSDeclared : + // > [...] Furthermore, the attribute value [...] must not be an empty string. + // so serializing empty namespace value like xmlns:ds="" would produce an invalid XML document. + if (!uri) { + return false; + } + if (prefix === "xml" && uri === NAMESPACE.XML || uri === NAMESPACE.XMLNS) { + return false; + } + + var i = visibleNamespaces.length + while (i--) { + var ns = visibleNamespaces[i]; + // get namespace prefix + if (ns.prefix === prefix) { + return ns.namespace !== uri; + } + } + return true; +} +/** + * Well-formed constraint: No < in Attribute Values + * > The replacement text of any entity referred to directly or indirectly + * > in an attribute value must not contain a <. + * @see https://www.w3.org/TR/xml11/#CleanAttrVals + * @see https://www.w3.org/TR/xml11/#NT-AttValue + * + * Literal whitespace other than space that appear in attribute values + * are serialized as their entity references, so they will be preserved. + * (In contrast to whitespace literals in the input which are normalized to spaces) + * @see https://www.w3.org/TR/xml11/#AVNormalize + * @see https://w3c.github.io/DOM-Parsing/#serializing-an-element-s-attributes + */ +function addSerializedAttribute(buf, qualifiedName, value) { + buf.push(' ', qualifiedName, '="', value.replace(/[<>&"\t\n\r]/g, _xmlEncoder), '"') +} + +function serializeToString(node,buf,isHTML,nodeFilter,visibleNamespaces){ + if (!visibleNamespaces) { + visibleNamespaces = []; + } + + if(nodeFilter){ + node = nodeFilter(node); + if(node){ + if(typeof node == 'string'){ + buf.push(node); + return; + } + }else{ + return; + } + //buf.sort.apply(attrs, attributeSorter); + } + + switch(node.nodeType){ + case ELEMENT_NODE: + var attrs = node.attributes; + var len = attrs.length; + var child = node.firstChild; + var nodeName = node.tagName; + + isHTML = NAMESPACE.isHTML(node.namespaceURI) || isHTML + + var prefixedNodeName = nodeName + if (!isHTML && !node.prefix && node.namespaceURI) { + var defaultNS + // lookup current default ns from `xmlns` attribute + for (var ai = 0; ai < attrs.length; ai++) { + if (attrs.item(ai).name === 'xmlns') { + defaultNS = attrs.item(ai).value + break + } + } + if (!defaultNS) { + // lookup current default ns in visibleNamespaces + for (var nsi = visibleNamespaces.length - 1; nsi >= 0; nsi--) { + var namespace = visibleNamespaces[nsi] + if (namespace.prefix === '' && namespace.namespace === node.namespaceURI) { + defaultNS = namespace.namespace + break + } + } + } + if (defaultNS !== node.namespaceURI) { + for (var nsi = visibleNamespaces.length - 1; nsi >= 0; nsi--) { + var namespace = visibleNamespaces[nsi] + if (namespace.namespace === node.namespaceURI) { + if (namespace.prefix) { + prefixedNodeName = namespace.prefix + ':' + nodeName + } + break + } + } + } + } + + buf.push('<', prefixedNodeName); + + for(var i=0;i'); + //if is cdata child node + if(isHTML && /^script$/i.test(nodeName)){ + while(child){ + if(child.data){ + buf.push(child.data); + }else{ + serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice()); + } + child = child.nextSibling; + } + }else + { + while(child){ + serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice()); + child = child.nextSibling; + } + } + buf.push(''); + }else{ + buf.push('/>'); + } + // remove added visible namespaces + //visibleNamespaces.length = startVisibleNamespaces; + return; + case DOCUMENT_NODE: + case DOCUMENT_FRAGMENT_NODE: + var child = node.firstChild; + while(child){ + serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice()); + child = child.nextSibling; + } + return; + case ATTRIBUTE_NODE: + return addSerializedAttribute(buf, node.name, node.value); + case TEXT_NODE: + /** + * The ampersand character (&) and the left angle bracket (<) must not appear in their literal form, + * except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section. + * If they are needed elsewhere, they must be escaped using either numeric character references or the strings + * `&` and `<` respectively. + * The right angle bracket (>) may be represented using the string " > ", and must, for compatibility, + * be escaped using either `>` or a character reference when it appears in the string `]]>` in content, + * when that string is not marking the end of a CDATA section. + * + * In the content of elements, character data is any string of characters + * which does not contain the start-delimiter of any markup + * and does not include the CDATA-section-close delimiter, `]]>`. + * + * @see https://www.w3.org/TR/xml/#NT-CharData + * @see https://w3c.github.io/DOM-Parsing/#xml-serializing-a-text-node + */ + return buf.push(node.data + .replace(/[<&>]/g,_xmlEncoder) + ); + case CDATA_SECTION_NODE: + return buf.push( ''); + case COMMENT_NODE: + return buf.push( ""); + case DOCUMENT_TYPE_NODE: + var pubid = node.publicId; + var sysid = node.systemId; + buf.push(''); + }else if(sysid && sysid!='.'){ + buf.push(' SYSTEM ', sysid, '>'); + }else{ + var sub = node.internalSubset; + if(sub){ + buf.push(" [",sub,"]"); + } + buf.push(">"); + } + return; + case PROCESSING_INSTRUCTION_NODE: + return buf.push( ""); + case ENTITY_REFERENCE_NODE: + return buf.push( '&',node.nodeName,';'); + //case ENTITY_NODE: + //case NOTATION_NODE: + default: + buf.push('??',node.nodeName); + } +} +function importNode(doc,node,deep){ + var node2; + switch (node.nodeType) { + case ELEMENT_NODE: + node2 = node.cloneNode(false); + node2.ownerDocument = doc; + //var attrs = node2.attributes; + //var len = attrs.length; + //for(var i=0;i', + lt: '<', + quot: '"', +}); + +/** + * A map of all entities that are detected in an HTML document. + * They contain all entries from `XML_ENTITIES`. + * + * @see XML_ENTITIES + * @see DOMParser.parseFromString + * @see DOMImplementation.prototype.createHTMLDocument + * @see https://html.spec.whatwg.org/#named-character-references WHATWG HTML(5) Spec + * @see https://html.spec.whatwg.org/entities.json JSON + * @see https://www.w3.org/TR/xml-entity-names/ W3C XML Entity Names + * @see https://www.w3.org/TR/html4/sgml/entities.html W3C HTML4/SGML + * @see https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Character_entity_references_in_HTML Wikipedia (HTML) + * @see https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Entities_representing_special_characters_in_XHTML Wikpedia (XHTML) + */ +exports.HTML_ENTITIES = freeze({ + Aacute: '\u00C1', + aacute: '\u00E1', + Abreve: '\u0102', + abreve: '\u0103', + ac: '\u223E', + acd: '\u223F', + acE: '\u223E\u0333', + Acirc: '\u00C2', + acirc: '\u00E2', + acute: '\u00B4', + Acy: '\u0410', + acy: '\u0430', + AElig: '\u00C6', + aelig: '\u00E6', + af: '\u2061', + Afr: '\uD835\uDD04', + afr: '\uD835\uDD1E', + Agrave: '\u00C0', + agrave: '\u00E0', + alefsym: '\u2135', + aleph: '\u2135', + Alpha: '\u0391', + alpha: '\u03B1', + Amacr: '\u0100', + amacr: '\u0101', + amalg: '\u2A3F', + AMP: '\u0026', + amp: '\u0026', + And: '\u2A53', + and: '\u2227', + andand: '\u2A55', + andd: '\u2A5C', + andslope: '\u2A58', + andv: '\u2A5A', + ang: '\u2220', + ange: '\u29A4', + angle: '\u2220', + angmsd: '\u2221', + angmsdaa: '\u29A8', + angmsdab: '\u29A9', + angmsdac: '\u29AA', + angmsdad: '\u29AB', + angmsdae: '\u29AC', + angmsdaf: '\u29AD', + angmsdag: '\u29AE', + angmsdah: '\u29AF', + angrt: '\u221F', + angrtvb: '\u22BE', + angrtvbd: '\u299D', + angsph: '\u2222', + angst: '\u00C5', + angzarr: '\u237C', + Aogon: '\u0104', + aogon: '\u0105', + Aopf: '\uD835\uDD38', + aopf: '\uD835\uDD52', + ap: '\u2248', + apacir: '\u2A6F', + apE: '\u2A70', + ape: '\u224A', + apid: '\u224B', + apos: '\u0027', + ApplyFunction: '\u2061', + approx: '\u2248', + approxeq: '\u224A', + Aring: '\u00C5', + aring: '\u00E5', + Ascr: '\uD835\uDC9C', + ascr: '\uD835\uDCB6', + Assign: '\u2254', + ast: '\u002A', + asymp: '\u2248', + asympeq: '\u224D', + Atilde: '\u00C3', + atilde: '\u00E3', + Auml: '\u00C4', + auml: '\u00E4', + awconint: '\u2233', + awint: '\u2A11', + backcong: '\u224C', + backepsilon: '\u03F6', + backprime: '\u2035', + backsim: '\u223D', + backsimeq: '\u22CD', + Backslash: '\u2216', + Barv: '\u2AE7', + barvee: '\u22BD', + Barwed: '\u2306', + barwed: '\u2305', + barwedge: '\u2305', + bbrk: '\u23B5', + bbrktbrk: '\u23B6', + bcong: '\u224C', + Bcy: '\u0411', + bcy: '\u0431', + bdquo: '\u201E', + becaus: '\u2235', + Because: '\u2235', + because: '\u2235', + bemptyv: '\u29B0', + bepsi: '\u03F6', + bernou: '\u212C', + Bernoullis: '\u212C', + Beta: '\u0392', + beta: '\u03B2', + beth: '\u2136', + between: '\u226C', + Bfr: '\uD835\uDD05', + bfr: '\uD835\uDD1F', + bigcap: '\u22C2', + bigcirc: '\u25EF', + bigcup: '\u22C3', + bigodot: '\u2A00', + bigoplus: '\u2A01', + bigotimes: '\u2A02', + bigsqcup: '\u2A06', + bigstar: '\u2605', + bigtriangledown: '\u25BD', + bigtriangleup: '\u25B3', + biguplus: '\u2A04', + bigvee: '\u22C1', + bigwedge: '\u22C0', + bkarow: '\u290D', + blacklozenge: '\u29EB', + blacksquare: '\u25AA', + blacktriangle: '\u25B4', + blacktriangledown: '\u25BE', + blacktriangleleft: '\u25C2', + blacktriangleright: '\u25B8', + blank: '\u2423', + blk12: '\u2592', + blk14: '\u2591', + blk34: '\u2593', + block: '\u2588', + bne: '\u003D\u20E5', + bnequiv: '\u2261\u20E5', + bNot: '\u2AED', + bnot: '\u2310', + Bopf: '\uD835\uDD39', + bopf: '\uD835\uDD53', + bot: '\u22A5', + bottom: '\u22A5', + bowtie: '\u22C8', + boxbox: '\u29C9', + boxDL: '\u2557', + boxDl: '\u2556', + boxdL: '\u2555', + boxdl: '\u2510', + boxDR: '\u2554', + boxDr: '\u2553', + boxdR: '\u2552', + boxdr: '\u250C', + boxH: '\u2550', + boxh: '\u2500', + boxHD: '\u2566', + boxHd: '\u2564', + boxhD: '\u2565', + boxhd: '\u252C', + boxHU: '\u2569', + boxHu: '\u2567', + boxhU: '\u2568', + boxhu: '\u2534', + boxminus: '\u229F', + boxplus: '\u229E', + boxtimes: '\u22A0', + boxUL: '\u255D', + boxUl: '\u255C', + boxuL: '\u255B', + boxul: '\u2518', + boxUR: '\u255A', + boxUr: '\u2559', + boxuR: '\u2558', + boxur: '\u2514', + boxV: '\u2551', + boxv: '\u2502', + boxVH: '\u256C', + boxVh: '\u256B', + boxvH: '\u256A', + boxvh: '\u253C', + boxVL: '\u2563', + boxVl: '\u2562', + boxvL: '\u2561', + boxvl: '\u2524', + boxVR: '\u2560', + boxVr: '\u255F', + boxvR: '\u255E', + boxvr: '\u251C', + bprime: '\u2035', + Breve: '\u02D8', + breve: '\u02D8', + brvbar: '\u00A6', + Bscr: '\u212C', + bscr: '\uD835\uDCB7', + bsemi: '\u204F', + bsim: '\u223D', + bsime: '\u22CD', + bsol: '\u005C', + bsolb: '\u29C5', + bsolhsub: '\u27C8', + bull: '\u2022', + bullet: '\u2022', + bump: '\u224E', + bumpE: '\u2AAE', + bumpe: '\u224F', + Bumpeq: '\u224E', + bumpeq: '\u224F', + Cacute: '\u0106', + cacute: '\u0107', + Cap: '\u22D2', + cap: '\u2229', + capand: '\u2A44', + capbrcup: '\u2A49', + capcap: '\u2A4B', + capcup: '\u2A47', + capdot: '\u2A40', + CapitalDifferentialD: '\u2145', + caps: '\u2229\uFE00', + caret: '\u2041', + caron: '\u02C7', + Cayleys: '\u212D', + ccaps: '\u2A4D', + Ccaron: '\u010C', + ccaron: '\u010D', + Ccedil: '\u00C7', + ccedil: '\u00E7', + Ccirc: '\u0108', + ccirc: '\u0109', + Cconint: '\u2230', + ccups: '\u2A4C', + ccupssm: '\u2A50', + Cdot: '\u010A', + cdot: '\u010B', + cedil: '\u00B8', + Cedilla: '\u00B8', + cemptyv: '\u29B2', + cent: '\u00A2', + CenterDot: '\u00B7', + centerdot: '\u00B7', + Cfr: '\u212D', + cfr: '\uD835\uDD20', + CHcy: '\u0427', + chcy: '\u0447', + check: '\u2713', + checkmark: '\u2713', + Chi: '\u03A7', + chi: '\u03C7', + cir: '\u25CB', + circ: '\u02C6', + circeq: '\u2257', + circlearrowleft: '\u21BA', + circlearrowright: '\u21BB', + circledast: '\u229B', + circledcirc: '\u229A', + circleddash: '\u229D', + CircleDot: '\u2299', + circledR: '\u00AE', + circledS: '\u24C8', + CircleMinus: '\u2296', + CirclePlus: '\u2295', + CircleTimes: '\u2297', + cirE: '\u29C3', + cire: '\u2257', + cirfnint: '\u2A10', + cirmid: '\u2AEF', + cirscir: '\u29C2', + ClockwiseContourIntegral: '\u2232', + CloseCurlyDoubleQuote: '\u201D', + CloseCurlyQuote: '\u2019', + clubs: '\u2663', + clubsuit: '\u2663', + Colon: '\u2237', + colon: '\u003A', + Colone: '\u2A74', + colone: '\u2254', + coloneq: '\u2254', + comma: '\u002C', + commat: '\u0040', + comp: '\u2201', + compfn: '\u2218', + complement: '\u2201', + complexes: '\u2102', + cong: '\u2245', + congdot: '\u2A6D', + Congruent: '\u2261', + Conint: '\u222F', + conint: '\u222E', + ContourIntegral: '\u222E', + Copf: '\u2102', + copf: '\uD835\uDD54', + coprod: '\u2210', + Coproduct: '\u2210', + COPY: '\u00A9', + copy: '\u00A9', + copysr: '\u2117', + CounterClockwiseContourIntegral: '\u2233', + crarr: '\u21B5', + Cross: '\u2A2F', + cross: '\u2717', + Cscr: '\uD835\uDC9E', + cscr: '\uD835\uDCB8', + csub: '\u2ACF', + csube: '\u2AD1', + csup: '\u2AD0', + csupe: '\u2AD2', + ctdot: '\u22EF', + cudarrl: '\u2938', + cudarrr: '\u2935', + cuepr: '\u22DE', + cuesc: '\u22DF', + cularr: '\u21B6', + cularrp: '\u293D', + Cup: '\u22D3', + cup: '\u222A', + cupbrcap: '\u2A48', + CupCap: '\u224D', + cupcap: '\u2A46', + cupcup: '\u2A4A', + cupdot: '\u228D', + cupor: '\u2A45', + cups: '\u222A\uFE00', + curarr: '\u21B7', + curarrm: '\u293C', + curlyeqprec: '\u22DE', + curlyeqsucc: '\u22DF', + curlyvee: '\u22CE', + curlywedge: '\u22CF', + curren: '\u00A4', + curvearrowleft: '\u21B6', + curvearrowright: '\u21B7', + cuvee: '\u22CE', + cuwed: '\u22CF', + cwconint: '\u2232', + cwint: '\u2231', + cylcty: '\u232D', + Dagger: '\u2021', + dagger: '\u2020', + daleth: '\u2138', + Darr: '\u21A1', + dArr: '\u21D3', + darr: '\u2193', + dash: '\u2010', + Dashv: '\u2AE4', + dashv: '\u22A3', + dbkarow: '\u290F', + dblac: '\u02DD', + Dcaron: '\u010E', + dcaron: '\u010F', + Dcy: '\u0414', + dcy: '\u0434', + DD: '\u2145', + dd: '\u2146', + ddagger: '\u2021', + ddarr: '\u21CA', + DDotrahd: '\u2911', + ddotseq: '\u2A77', + deg: '\u00B0', + Del: '\u2207', + Delta: '\u0394', + delta: '\u03B4', + demptyv: '\u29B1', + dfisht: '\u297F', + Dfr: '\uD835\uDD07', + dfr: '\uD835\uDD21', + dHar: '\u2965', + dharl: '\u21C3', + dharr: '\u21C2', + DiacriticalAcute: '\u00B4', + DiacriticalDot: '\u02D9', + DiacriticalDoubleAcute: '\u02DD', + DiacriticalGrave: '\u0060', + DiacriticalTilde: '\u02DC', + diam: '\u22C4', + Diamond: '\u22C4', + diamond: '\u22C4', + diamondsuit: '\u2666', + diams: '\u2666', + die: '\u00A8', + DifferentialD: '\u2146', + digamma: '\u03DD', + disin: '\u22F2', + div: '\u00F7', + divide: '\u00F7', + divideontimes: '\u22C7', + divonx: '\u22C7', + DJcy: '\u0402', + djcy: '\u0452', + dlcorn: '\u231E', + dlcrop: '\u230D', + dollar: '\u0024', + Dopf: '\uD835\uDD3B', + dopf: '\uD835\uDD55', + Dot: '\u00A8', + dot: '\u02D9', + DotDot: '\u20DC', + doteq: '\u2250', + doteqdot: '\u2251', + DotEqual: '\u2250', + dotminus: '\u2238', + dotplus: '\u2214', + dotsquare: '\u22A1', + doublebarwedge: '\u2306', + DoubleContourIntegral: '\u222F', + DoubleDot: '\u00A8', + DoubleDownArrow: '\u21D3', + DoubleLeftArrow: '\u21D0', + DoubleLeftRightArrow: '\u21D4', + DoubleLeftTee: '\u2AE4', + DoubleLongLeftArrow: '\u27F8', + DoubleLongLeftRightArrow: '\u27FA', + DoubleLongRightArrow: '\u27F9', + DoubleRightArrow: '\u21D2', + DoubleRightTee: '\u22A8', + DoubleUpArrow: '\u21D1', + DoubleUpDownArrow: '\u21D5', + DoubleVerticalBar: '\u2225', + DownArrow: '\u2193', + Downarrow: '\u21D3', + downarrow: '\u2193', + DownArrowBar: '\u2913', + DownArrowUpArrow: '\u21F5', + DownBreve: '\u0311', + downdownarrows: '\u21CA', + downharpoonleft: '\u21C3', + downharpoonright: '\u21C2', + DownLeftRightVector: '\u2950', + DownLeftTeeVector: '\u295E', + DownLeftVector: '\u21BD', + DownLeftVectorBar: '\u2956', + DownRightTeeVector: '\u295F', + DownRightVector: '\u21C1', + DownRightVectorBar: '\u2957', + DownTee: '\u22A4', + DownTeeArrow: '\u21A7', + drbkarow: '\u2910', + drcorn: '\u231F', + drcrop: '\u230C', + Dscr: '\uD835\uDC9F', + dscr: '\uD835\uDCB9', + DScy: '\u0405', + dscy: '\u0455', + dsol: '\u29F6', + Dstrok: '\u0110', + dstrok: '\u0111', + dtdot: '\u22F1', + dtri: '\u25BF', + dtrif: '\u25BE', + duarr: '\u21F5', + duhar: '\u296F', + dwangle: '\u29A6', + DZcy: '\u040F', + dzcy: '\u045F', + dzigrarr: '\u27FF', + Eacute: '\u00C9', + eacute: '\u00E9', + easter: '\u2A6E', + Ecaron: '\u011A', + ecaron: '\u011B', + ecir: '\u2256', + Ecirc: '\u00CA', + ecirc: '\u00EA', + ecolon: '\u2255', + Ecy: '\u042D', + ecy: '\u044D', + eDDot: '\u2A77', + Edot: '\u0116', + eDot: '\u2251', + edot: '\u0117', + ee: '\u2147', + efDot: '\u2252', + Efr: '\uD835\uDD08', + efr: '\uD835\uDD22', + eg: '\u2A9A', + Egrave: '\u00C8', + egrave: '\u00E8', + egs: '\u2A96', + egsdot: '\u2A98', + el: '\u2A99', + Element: '\u2208', + elinters: '\u23E7', + ell: '\u2113', + els: '\u2A95', + elsdot: '\u2A97', + Emacr: '\u0112', + emacr: '\u0113', + empty: '\u2205', + emptyset: '\u2205', + EmptySmallSquare: '\u25FB', + emptyv: '\u2205', + EmptyVerySmallSquare: '\u25AB', + emsp: '\u2003', + emsp13: '\u2004', + emsp14: '\u2005', + ENG: '\u014A', + eng: '\u014B', + ensp: '\u2002', + Eogon: '\u0118', + eogon: '\u0119', + Eopf: '\uD835\uDD3C', + eopf: '\uD835\uDD56', + epar: '\u22D5', + eparsl: '\u29E3', + eplus: '\u2A71', + epsi: '\u03B5', + Epsilon: '\u0395', + epsilon: '\u03B5', + epsiv: '\u03F5', + eqcirc: '\u2256', + eqcolon: '\u2255', + eqsim: '\u2242', + eqslantgtr: '\u2A96', + eqslantless: '\u2A95', + Equal: '\u2A75', + equals: '\u003D', + EqualTilde: '\u2242', + equest: '\u225F', + Equilibrium: '\u21CC', + equiv: '\u2261', + equivDD: '\u2A78', + eqvparsl: '\u29E5', + erarr: '\u2971', + erDot: '\u2253', + Escr: '\u2130', + escr: '\u212F', + esdot: '\u2250', + Esim: '\u2A73', + esim: '\u2242', + Eta: '\u0397', + eta: '\u03B7', + ETH: '\u00D0', + eth: '\u00F0', + Euml: '\u00CB', + euml: '\u00EB', + euro: '\u20AC', + excl: '\u0021', + exist: '\u2203', + Exists: '\u2203', + expectation: '\u2130', + ExponentialE: '\u2147', + exponentiale: '\u2147', + fallingdotseq: '\u2252', + Fcy: '\u0424', + fcy: '\u0444', + female: '\u2640', + ffilig: '\uFB03', + fflig: '\uFB00', + ffllig: '\uFB04', + Ffr: '\uD835\uDD09', + ffr: '\uD835\uDD23', + filig: '\uFB01', + FilledSmallSquare: '\u25FC', + FilledVerySmallSquare: '\u25AA', + fjlig: '\u0066\u006A', + flat: '\u266D', + fllig: '\uFB02', + fltns: '\u25B1', + fnof: '\u0192', + Fopf: '\uD835\uDD3D', + fopf: '\uD835\uDD57', + ForAll: '\u2200', + forall: '\u2200', + fork: '\u22D4', + forkv: '\u2AD9', + Fouriertrf: '\u2131', + fpartint: '\u2A0D', + frac12: '\u00BD', + frac13: '\u2153', + frac14: '\u00BC', + frac15: '\u2155', + frac16: '\u2159', + frac18: '\u215B', + frac23: '\u2154', + frac25: '\u2156', + frac34: '\u00BE', + frac35: '\u2157', + frac38: '\u215C', + frac45: '\u2158', + frac56: '\u215A', + frac58: '\u215D', + frac78: '\u215E', + frasl: '\u2044', + frown: '\u2322', + Fscr: '\u2131', + fscr: '\uD835\uDCBB', + gacute: '\u01F5', + Gamma: '\u0393', + gamma: '\u03B3', + Gammad: '\u03DC', + gammad: '\u03DD', + gap: '\u2A86', + Gbreve: '\u011E', + gbreve: '\u011F', + Gcedil: '\u0122', + Gcirc: '\u011C', + gcirc: '\u011D', + Gcy: '\u0413', + gcy: '\u0433', + Gdot: '\u0120', + gdot: '\u0121', + gE: '\u2267', + ge: '\u2265', + gEl: '\u2A8C', + gel: '\u22DB', + geq: '\u2265', + geqq: '\u2267', + geqslant: '\u2A7E', + ges: '\u2A7E', + gescc: '\u2AA9', + gesdot: '\u2A80', + gesdoto: '\u2A82', + gesdotol: '\u2A84', + gesl: '\u22DB\uFE00', + gesles: '\u2A94', + Gfr: '\uD835\uDD0A', + gfr: '\uD835\uDD24', + Gg: '\u22D9', + gg: '\u226B', + ggg: '\u22D9', + gimel: '\u2137', + GJcy: '\u0403', + gjcy: '\u0453', + gl: '\u2277', + gla: '\u2AA5', + glE: '\u2A92', + glj: '\u2AA4', + gnap: '\u2A8A', + gnapprox: '\u2A8A', + gnE: '\u2269', + gne: '\u2A88', + gneq: '\u2A88', + gneqq: '\u2269', + gnsim: '\u22E7', + Gopf: '\uD835\uDD3E', + gopf: '\uD835\uDD58', + grave: '\u0060', + GreaterEqual: '\u2265', + GreaterEqualLess: '\u22DB', + GreaterFullEqual: '\u2267', + GreaterGreater: '\u2AA2', + GreaterLess: '\u2277', + GreaterSlantEqual: '\u2A7E', + GreaterTilde: '\u2273', + Gscr: '\uD835\uDCA2', + gscr: '\u210A', + gsim: '\u2273', + gsime: '\u2A8E', + gsiml: '\u2A90', + Gt: '\u226B', + GT: '\u003E', + gt: '\u003E', + gtcc: '\u2AA7', + gtcir: '\u2A7A', + gtdot: '\u22D7', + gtlPar: '\u2995', + gtquest: '\u2A7C', + gtrapprox: '\u2A86', + gtrarr: '\u2978', + gtrdot: '\u22D7', + gtreqless: '\u22DB', + gtreqqless: '\u2A8C', + gtrless: '\u2277', + gtrsim: '\u2273', + gvertneqq: '\u2269\uFE00', + gvnE: '\u2269\uFE00', + Hacek: '\u02C7', + hairsp: '\u200A', + half: '\u00BD', + hamilt: '\u210B', + HARDcy: '\u042A', + hardcy: '\u044A', + hArr: '\u21D4', + harr: '\u2194', + harrcir: '\u2948', + harrw: '\u21AD', + Hat: '\u005E', + hbar: '\u210F', + Hcirc: '\u0124', + hcirc: '\u0125', + hearts: '\u2665', + heartsuit: '\u2665', + hellip: '\u2026', + hercon: '\u22B9', + Hfr: '\u210C', + hfr: '\uD835\uDD25', + HilbertSpace: '\u210B', + hksearow: '\u2925', + hkswarow: '\u2926', + hoarr: '\u21FF', + homtht: '\u223B', + hookleftarrow: '\u21A9', + hookrightarrow: '\u21AA', + Hopf: '\u210D', + hopf: '\uD835\uDD59', + horbar: '\u2015', + HorizontalLine: '\u2500', + Hscr: '\u210B', + hscr: '\uD835\uDCBD', + hslash: '\u210F', + Hstrok: '\u0126', + hstrok: '\u0127', + HumpDownHump: '\u224E', + HumpEqual: '\u224F', + hybull: '\u2043', + hyphen: '\u2010', + Iacute: '\u00CD', + iacute: '\u00ED', + ic: '\u2063', + Icirc: '\u00CE', + icirc: '\u00EE', + Icy: '\u0418', + icy: '\u0438', + Idot: '\u0130', + IEcy: '\u0415', + iecy: '\u0435', + iexcl: '\u00A1', + iff: '\u21D4', + Ifr: '\u2111', + ifr: '\uD835\uDD26', + Igrave: '\u00CC', + igrave: '\u00EC', + ii: '\u2148', + iiiint: '\u2A0C', + iiint: '\u222D', + iinfin: '\u29DC', + iiota: '\u2129', + IJlig: '\u0132', + ijlig: '\u0133', + Im: '\u2111', + Imacr: '\u012A', + imacr: '\u012B', + image: '\u2111', + ImaginaryI: '\u2148', + imagline: '\u2110', + imagpart: '\u2111', + imath: '\u0131', + imof: '\u22B7', + imped: '\u01B5', + Implies: '\u21D2', + in: '\u2208', + incare: '\u2105', + infin: '\u221E', + infintie: '\u29DD', + inodot: '\u0131', + Int: '\u222C', + int: '\u222B', + intcal: '\u22BA', + integers: '\u2124', + Integral: '\u222B', + intercal: '\u22BA', + Intersection: '\u22C2', + intlarhk: '\u2A17', + intprod: '\u2A3C', + InvisibleComma: '\u2063', + InvisibleTimes: '\u2062', + IOcy: '\u0401', + iocy: '\u0451', + Iogon: '\u012E', + iogon: '\u012F', + Iopf: '\uD835\uDD40', + iopf: '\uD835\uDD5A', + Iota: '\u0399', + iota: '\u03B9', + iprod: '\u2A3C', + iquest: '\u00BF', + Iscr: '\u2110', + iscr: '\uD835\uDCBE', + isin: '\u2208', + isindot: '\u22F5', + isinE: '\u22F9', + isins: '\u22F4', + isinsv: '\u22F3', + isinv: '\u2208', + it: '\u2062', + Itilde: '\u0128', + itilde: '\u0129', + Iukcy: '\u0406', + iukcy: '\u0456', + Iuml: '\u00CF', + iuml: '\u00EF', + Jcirc: '\u0134', + jcirc: '\u0135', + Jcy: '\u0419', + jcy: '\u0439', + Jfr: '\uD835\uDD0D', + jfr: '\uD835\uDD27', + jmath: '\u0237', + Jopf: '\uD835\uDD41', + jopf: '\uD835\uDD5B', + Jscr: '\uD835\uDCA5', + jscr: '\uD835\uDCBF', + Jsercy: '\u0408', + jsercy: '\u0458', + Jukcy: '\u0404', + jukcy: '\u0454', + Kappa: '\u039A', + kappa: '\u03BA', + kappav: '\u03F0', + Kcedil: '\u0136', + kcedil: '\u0137', + Kcy: '\u041A', + kcy: '\u043A', + Kfr: '\uD835\uDD0E', + kfr: '\uD835\uDD28', + kgreen: '\u0138', + KHcy: '\u0425', + khcy: '\u0445', + KJcy: '\u040C', + kjcy: '\u045C', + Kopf: '\uD835\uDD42', + kopf: '\uD835\uDD5C', + Kscr: '\uD835\uDCA6', + kscr: '\uD835\uDCC0', + lAarr: '\u21DA', + Lacute: '\u0139', + lacute: '\u013A', + laemptyv: '\u29B4', + lagran: '\u2112', + Lambda: '\u039B', + lambda: '\u03BB', + Lang: '\u27EA', + lang: '\u27E8', + langd: '\u2991', + langle: '\u27E8', + lap: '\u2A85', + Laplacetrf: '\u2112', + laquo: '\u00AB', + Larr: '\u219E', + lArr: '\u21D0', + larr: '\u2190', + larrb: '\u21E4', + larrbfs: '\u291F', + larrfs: '\u291D', + larrhk: '\u21A9', + larrlp: '\u21AB', + larrpl: '\u2939', + larrsim: '\u2973', + larrtl: '\u21A2', + lat: '\u2AAB', + lAtail: '\u291B', + latail: '\u2919', + late: '\u2AAD', + lates: '\u2AAD\uFE00', + lBarr: '\u290E', + lbarr: '\u290C', + lbbrk: '\u2772', + lbrace: '\u007B', + lbrack: '\u005B', + lbrke: '\u298B', + lbrksld: '\u298F', + lbrkslu: '\u298D', + Lcaron: '\u013D', + lcaron: '\u013E', + Lcedil: '\u013B', + lcedil: '\u013C', + lceil: '\u2308', + lcub: '\u007B', + Lcy: '\u041B', + lcy: '\u043B', + ldca: '\u2936', + ldquo: '\u201C', + ldquor: '\u201E', + ldrdhar: '\u2967', + ldrushar: '\u294B', + ldsh: '\u21B2', + lE: '\u2266', + le: '\u2264', + LeftAngleBracket: '\u27E8', + LeftArrow: '\u2190', + Leftarrow: '\u21D0', + leftarrow: '\u2190', + LeftArrowBar: '\u21E4', + LeftArrowRightArrow: '\u21C6', + leftarrowtail: '\u21A2', + LeftCeiling: '\u2308', + LeftDoubleBracket: '\u27E6', + LeftDownTeeVector: '\u2961', + LeftDownVector: '\u21C3', + LeftDownVectorBar: '\u2959', + LeftFloor: '\u230A', + leftharpoondown: '\u21BD', + leftharpoonup: '\u21BC', + leftleftarrows: '\u21C7', + LeftRightArrow: '\u2194', + Leftrightarrow: '\u21D4', + leftrightarrow: '\u2194', + leftrightarrows: '\u21C6', + leftrightharpoons: '\u21CB', + leftrightsquigarrow: '\u21AD', + LeftRightVector: '\u294E', + LeftTee: '\u22A3', + LeftTeeArrow: '\u21A4', + LeftTeeVector: '\u295A', + leftthreetimes: '\u22CB', + LeftTriangle: '\u22B2', + LeftTriangleBar: '\u29CF', + LeftTriangleEqual: '\u22B4', + LeftUpDownVector: '\u2951', + LeftUpTeeVector: '\u2960', + LeftUpVector: '\u21BF', + LeftUpVectorBar: '\u2958', + LeftVector: '\u21BC', + LeftVectorBar: '\u2952', + lEg: '\u2A8B', + leg: '\u22DA', + leq: '\u2264', + leqq: '\u2266', + leqslant: '\u2A7D', + les: '\u2A7D', + lescc: '\u2AA8', + lesdot: '\u2A7F', + lesdoto: '\u2A81', + lesdotor: '\u2A83', + lesg: '\u22DA\uFE00', + lesges: '\u2A93', + lessapprox: '\u2A85', + lessdot: '\u22D6', + lesseqgtr: '\u22DA', + lesseqqgtr: '\u2A8B', + LessEqualGreater: '\u22DA', + LessFullEqual: '\u2266', + LessGreater: '\u2276', + lessgtr: '\u2276', + LessLess: '\u2AA1', + lesssim: '\u2272', + LessSlantEqual: '\u2A7D', + LessTilde: '\u2272', + lfisht: '\u297C', + lfloor: '\u230A', + Lfr: '\uD835\uDD0F', + lfr: '\uD835\uDD29', + lg: '\u2276', + lgE: '\u2A91', + lHar: '\u2962', + lhard: '\u21BD', + lharu: '\u21BC', + lharul: '\u296A', + lhblk: '\u2584', + LJcy: '\u0409', + ljcy: '\u0459', + Ll: '\u22D8', + ll: '\u226A', + llarr: '\u21C7', + llcorner: '\u231E', + Lleftarrow: '\u21DA', + llhard: '\u296B', + lltri: '\u25FA', + Lmidot: '\u013F', + lmidot: '\u0140', + lmoust: '\u23B0', + lmoustache: '\u23B0', + lnap: '\u2A89', + lnapprox: '\u2A89', + lnE: '\u2268', + lne: '\u2A87', + lneq: '\u2A87', + lneqq: '\u2268', + lnsim: '\u22E6', + loang: '\u27EC', + loarr: '\u21FD', + lobrk: '\u27E6', + LongLeftArrow: '\u27F5', + Longleftarrow: '\u27F8', + longleftarrow: '\u27F5', + LongLeftRightArrow: '\u27F7', + Longleftrightarrow: '\u27FA', + longleftrightarrow: '\u27F7', + longmapsto: '\u27FC', + LongRightArrow: '\u27F6', + Longrightarrow: '\u27F9', + longrightarrow: '\u27F6', + looparrowleft: '\u21AB', + looparrowright: '\u21AC', + lopar: '\u2985', + Lopf: '\uD835\uDD43', + lopf: '\uD835\uDD5D', + loplus: '\u2A2D', + lotimes: '\u2A34', + lowast: '\u2217', + lowbar: '\u005F', + LowerLeftArrow: '\u2199', + LowerRightArrow: '\u2198', + loz: '\u25CA', + lozenge: '\u25CA', + lozf: '\u29EB', + lpar: '\u0028', + lparlt: '\u2993', + lrarr: '\u21C6', + lrcorner: '\u231F', + lrhar: '\u21CB', + lrhard: '\u296D', + lrm: '\u200E', + lrtri: '\u22BF', + lsaquo: '\u2039', + Lscr: '\u2112', + lscr: '\uD835\uDCC1', + Lsh: '\u21B0', + lsh: '\u21B0', + lsim: '\u2272', + lsime: '\u2A8D', + lsimg: '\u2A8F', + lsqb: '\u005B', + lsquo: '\u2018', + lsquor: '\u201A', + Lstrok: '\u0141', + lstrok: '\u0142', + Lt: '\u226A', + LT: '\u003C', + lt: '\u003C', + ltcc: '\u2AA6', + ltcir: '\u2A79', + ltdot: '\u22D6', + lthree: '\u22CB', + ltimes: '\u22C9', + ltlarr: '\u2976', + ltquest: '\u2A7B', + ltri: '\u25C3', + ltrie: '\u22B4', + ltrif: '\u25C2', + ltrPar: '\u2996', + lurdshar: '\u294A', + luruhar: '\u2966', + lvertneqq: '\u2268\uFE00', + lvnE: '\u2268\uFE00', + macr: '\u00AF', + male: '\u2642', + malt: '\u2720', + maltese: '\u2720', + Map: '\u2905', + map: '\u21A6', + mapsto: '\u21A6', + mapstodown: '\u21A7', + mapstoleft: '\u21A4', + mapstoup: '\u21A5', + marker: '\u25AE', + mcomma: '\u2A29', + Mcy: '\u041C', + mcy: '\u043C', + mdash: '\u2014', + mDDot: '\u223A', + measuredangle: '\u2221', + MediumSpace: '\u205F', + Mellintrf: '\u2133', + Mfr: '\uD835\uDD10', + mfr: '\uD835\uDD2A', + mho: '\u2127', + micro: '\u00B5', + mid: '\u2223', + midast: '\u002A', + midcir: '\u2AF0', + middot: '\u00B7', + minus: '\u2212', + minusb: '\u229F', + minusd: '\u2238', + minusdu: '\u2A2A', + MinusPlus: '\u2213', + mlcp: '\u2ADB', + mldr: '\u2026', + mnplus: '\u2213', + models: '\u22A7', + Mopf: '\uD835\uDD44', + mopf: '\uD835\uDD5E', + mp: '\u2213', + Mscr: '\u2133', + mscr: '\uD835\uDCC2', + mstpos: '\u223E', + Mu: '\u039C', + mu: '\u03BC', + multimap: '\u22B8', + mumap: '\u22B8', + nabla: '\u2207', + Nacute: '\u0143', + nacute: '\u0144', + nang: '\u2220\u20D2', + nap: '\u2249', + napE: '\u2A70\u0338', + napid: '\u224B\u0338', + napos: '\u0149', + napprox: '\u2249', + natur: '\u266E', + natural: '\u266E', + naturals: '\u2115', + nbsp: '\u00A0', + nbump: '\u224E\u0338', + nbumpe: '\u224F\u0338', + ncap: '\u2A43', + Ncaron: '\u0147', + ncaron: '\u0148', + Ncedil: '\u0145', + ncedil: '\u0146', + ncong: '\u2247', + ncongdot: '\u2A6D\u0338', + ncup: '\u2A42', + Ncy: '\u041D', + ncy: '\u043D', + ndash: '\u2013', + ne: '\u2260', + nearhk: '\u2924', + neArr: '\u21D7', + nearr: '\u2197', + nearrow: '\u2197', + nedot: '\u2250\u0338', + NegativeMediumSpace: '\u200B', + NegativeThickSpace: '\u200B', + NegativeThinSpace: '\u200B', + NegativeVeryThinSpace: '\u200B', + nequiv: '\u2262', + nesear: '\u2928', + nesim: '\u2242\u0338', + NestedGreaterGreater: '\u226B', + NestedLessLess: '\u226A', + NewLine: '\u000A', + nexist: '\u2204', + nexists: '\u2204', + Nfr: '\uD835\uDD11', + nfr: '\uD835\uDD2B', + ngE: '\u2267\u0338', + nge: '\u2271', + ngeq: '\u2271', + ngeqq: '\u2267\u0338', + ngeqslant: '\u2A7E\u0338', + nges: '\u2A7E\u0338', + nGg: '\u22D9\u0338', + ngsim: '\u2275', + nGt: '\u226B\u20D2', + ngt: '\u226F', + ngtr: '\u226F', + nGtv: '\u226B\u0338', + nhArr: '\u21CE', + nharr: '\u21AE', + nhpar: '\u2AF2', + ni: '\u220B', + nis: '\u22FC', + nisd: '\u22FA', + niv: '\u220B', + NJcy: '\u040A', + njcy: '\u045A', + nlArr: '\u21CD', + nlarr: '\u219A', + nldr: '\u2025', + nlE: '\u2266\u0338', + nle: '\u2270', + nLeftarrow: '\u21CD', + nleftarrow: '\u219A', + nLeftrightarrow: '\u21CE', + nleftrightarrow: '\u21AE', + nleq: '\u2270', + nleqq: '\u2266\u0338', + nleqslant: '\u2A7D\u0338', + nles: '\u2A7D\u0338', + nless: '\u226E', + nLl: '\u22D8\u0338', + nlsim: '\u2274', + nLt: '\u226A\u20D2', + nlt: '\u226E', + nltri: '\u22EA', + nltrie: '\u22EC', + nLtv: '\u226A\u0338', + nmid: '\u2224', + NoBreak: '\u2060', + NonBreakingSpace: '\u00A0', + Nopf: '\u2115', + nopf: '\uD835\uDD5F', + Not: '\u2AEC', + not: '\u00AC', + NotCongruent: '\u2262', + NotCupCap: '\u226D', + NotDoubleVerticalBar: '\u2226', + NotElement: '\u2209', + NotEqual: '\u2260', + NotEqualTilde: '\u2242\u0338', + NotExists: '\u2204', + NotGreater: '\u226F', + NotGreaterEqual: '\u2271', + NotGreaterFullEqual: '\u2267\u0338', + NotGreaterGreater: '\u226B\u0338', + NotGreaterLess: '\u2279', + NotGreaterSlantEqual: '\u2A7E\u0338', + NotGreaterTilde: '\u2275', + NotHumpDownHump: '\u224E\u0338', + NotHumpEqual: '\u224F\u0338', + notin: '\u2209', + notindot: '\u22F5\u0338', + notinE: '\u22F9\u0338', + notinva: '\u2209', + notinvb: '\u22F7', + notinvc: '\u22F6', + NotLeftTriangle: '\u22EA', + NotLeftTriangleBar: '\u29CF\u0338', + NotLeftTriangleEqual: '\u22EC', + NotLess: '\u226E', + NotLessEqual: '\u2270', + NotLessGreater: '\u2278', + NotLessLess: '\u226A\u0338', + NotLessSlantEqual: '\u2A7D\u0338', + NotLessTilde: '\u2274', + NotNestedGreaterGreater: '\u2AA2\u0338', + NotNestedLessLess: '\u2AA1\u0338', + notni: '\u220C', + notniva: '\u220C', + notnivb: '\u22FE', + notnivc: '\u22FD', + NotPrecedes: '\u2280', + NotPrecedesEqual: '\u2AAF\u0338', + NotPrecedesSlantEqual: '\u22E0', + NotReverseElement: '\u220C', + NotRightTriangle: '\u22EB', + NotRightTriangleBar: '\u29D0\u0338', + NotRightTriangleEqual: '\u22ED', + NotSquareSubset: '\u228F\u0338', + NotSquareSubsetEqual: '\u22E2', + NotSquareSuperset: '\u2290\u0338', + NotSquareSupersetEqual: '\u22E3', + NotSubset: '\u2282\u20D2', + NotSubsetEqual: '\u2288', + NotSucceeds: '\u2281', + NotSucceedsEqual: '\u2AB0\u0338', + NotSucceedsSlantEqual: '\u22E1', + NotSucceedsTilde: '\u227F\u0338', + NotSuperset: '\u2283\u20D2', + NotSupersetEqual: '\u2289', + NotTilde: '\u2241', + NotTildeEqual: '\u2244', + NotTildeFullEqual: '\u2247', + NotTildeTilde: '\u2249', + NotVerticalBar: '\u2224', + npar: '\u2226', + nparallel: '\u2226', + nparsl: '\u2AFD\u20E5', + npart: '\u2202\u0338', + npolint: '\u2A14', + npr: '\u2280', + nprcue: '\u22E0', + npre: '\u2AAF\u0338', + nprec: '\u2280', + npreceq: '\u2AAF\u0338', + nrArr: '\u21CF', + nrarr: '\u219B', + nrarrc: '\u2933\u0338', + nrarrw: '\u219D\u0338', + nRightarrow: '\u21CF', + nrightarrow: '\u219B', + nrtri: '\u22EB', + nrtrie: '\u22ED', + nsc: '\u2281', + nsccue: '\u22E1', + nsce: '\u2AB0\u0338', + Nscr: '\uD835\uDCA9', + nscr: '\uD835\uDCC3', + nshortmid: '\u2224', + nshortparallel: '\u2226', + nsim: '\u2241', + nsime: '\u2244', + nsimeq: '\u2244', + nsmid: '\u2224', + nspar: '\u2226', + nsqsube: '\u22E2', + nsqsupe: '\u22E3', + nsub: '\u2284', + nsubE: '\u2AC5\u0338', + nsube: '\u2288', + nsubset: '\u2282\u20D2', + nsubseteq: '\u2288', + nsubseteqq: '\u2AC5\u0338', + nsucc: '\u2281', + nsucceq: '\u2AB0\u0338', + nsup: '\u2285', + nsupE: '\u2AC6\u0338', + nsupe: '\u2289', + nsupset: '\u2283\u20D2', + nsupseteq: '\u2289', + nsupseteqq: '\u2AC6\u0338', + ntgl: '\u2279', + Ntilde: '\u00D1', + ntilde: '\u00F1', + ntlg: '\u2278', + ntriangleleft: '\u22EA', + ntrianglelefteq: '\u22EC', + ntriangleright: '\u22EB', + ntrianglerighteq: '\u22ED', + Nu: '\u039D', + nu: '\u03BD', + num: '\u0023', + numero: '\u2116', + numsp: '\u2007', + nvap: '\u224D\u20D2', + nVDash: '\u22AF', + nVdash: '\u22AE', + nvDash: '\u22AD', + nvdash: '\u22AC', + nvge: '\u2265\u20D2', + nvgt: '\u003E\u20D2', + nvHarr: '\u2904', + nvinfin: '\u29DE', + nvlArr: '\u2902', + nvle: '\u2264\u20D2', + nvlt: '\u003C\u20D2', + nvltrie: '\u22B4\u20D2', + nvrArr: '\u2903', + nvrtrie: '\u22B5\u20D2', + nvsim: '\u223C\u20D2', + nwarhk: '\u2923', + nwArr: '\u21D6', + nwarr: '\u2196', + nwarrow: '\u2196', + nwnear: '\u2927', + Oacute: '\u00D3', + oacute: '\u00F3', + oast: '\u229B', + ocir: '\u229A', + Ocirc: '\u00D4', + ocirc: '\u00F4', + Ocy: '\u041E', + ocy: '\u043E', + odash: '\u229D', + Odblac: '\u0150', + odblac: '\u0151', + odiv: '\u2A38', + odot: '\u2299', + odsold: '\u29BC', + OElig: '\u0152', + oelig: '\u0153', + ofcir: '\u29BF', + Ofr: '\uD835\uDD12', + ofr: '\uD835\uDD2C', + ogon: '\u02DB', + Ograve: '\u00D2', + ograve: '\u00F2', + ogt: '\u29C1', + ohbar: '\u29B5', + ohm: '\u03A9', + oint: '\u222E', + olarr: '\u21BA', + olcir: '\u29BE', + olcross: '\u29BB', + oline: '\u203E', + olt: '\u29C0', + Omacr: '\u014C', + omacr: '\u014D', + Omega: '\u03A9', + omega: '\u03C9', + Omicron: '\u039F', + omicron: '\u03BF', + omid: '\u29B6', + ominus: '\u2296', + Oopf: '\uD835\uDD46', + oopf: '\uD835\uDD60', + opar: '\u29B7', + OpenCurlyDoubleQuote: '\u201C', + OpenCurlyQuote: '\u2018', + operp: '\u29B9', + oplus: '\u2295', + Or: '\u2A54', + or: '\u2228', + orarr: '\u21BB', + ord: '\u2A5D', + order: '\u2134', + orderof: '\u2134', + ordf: '\u00AA', + ordm: '\u00BA', + origof: '\u22B6', + oror: '\u2A56', + orslope: '\u2A57', + orv: '\u2A5B', + oS: '\u24C8', + Oscr: '\uD835\uDCAA', + oscr: '\u2134', + Oslash: '\u00D8', + oslash: '\u00F8', + osol: '\u2298', + Otilde: '\u00D5', + otilde: '\u00F5', + Otimes: '\u2A37', + otimes: '\u2297', + otimesas: '\u2A36', + Ouml: '\u00D6', + ouml: '\u00F6', + ovbar: '\u233D', + OverBar: '\u203E', + OverBrace: '\u23DE', + OverBracket: '\u23B4', + OverParenthesis: '\u23DC', + par: '\u2225', + para: '\u00B6', + parallel: '\u2225', + parsim: '\u2AF3', + parsl: '\u2AFD', + part: '\u2202', + PartialD: '\u2202', + Pcy: '\u041F', + pcy: '\u043F', + percnt: '\u0025', + period: '\u002E', + permil: '\u2030', + perp: '\u22A5', + pertenk: '\u2031', + Pfr: '\uD835\uDD13', + pfr: '\uD835\uDD2D', + Phi: '\u03A6', + phi: '\u03C6', + phiv: '\u03D5', + phmmat: '\u2133', + phone: '\u260E', + Pi: '\u03A0', + pi: '\u03C0', + pitchfork: '\u22D4', + piv: '\u03D6', + planck: '\u210F', + planckh: '\u210E', + plankv: '\u210F', + plus: '\u002B', + plusacir: '\u2A23', + plusb: '\u229E', + pluscir: '\u2A22', + plusdo: '\u2214', + plusdu: '\u2A25', + pluse: '\u2A72', + PlusMinus: '\u00B1', + plusmn: '\u00B1', + plussim: '\u2A26', + plustwo: '\u2A27', + pm: '\u00B1', + Poincareplane: '\u210C', + pointint: '\u2A15', + Popf: '\u2119', + popf: '\uD835\uDD61', + pound: '\u00A3', + Pr: '\u2ABB', + pr: '\u227A', + prap: '\u2AB7', + prcue: '\u227C', + prE: '\u2AB3', + pre: '\u2AAF', + prec: '\u227A', + precapprox: '\u2AB7', + preccurlyeq: '\u227C', + Precedes: '\u227A', + PrecedesEqual: '\u2AAF', + PrecedesSlantEqual: '\u227C', + PrecedesTilde: '\u227E', + preceq: '\u2AAF', + precnapprox: '\u2AB9', + precneqq: '\u2AB5', + precnsim: '\u22E8', + precsim: '\u227E', + Prime: '\u2033', + prime: '\u2032', + primes: '\u2119', + prnap: '\u2AB9', + prnE: '\u2AB5', + prnsim: '\u22E8', + prod: '\u220F', + Product: '\u220F', + profalar: '\u232E', + profline: '\u2312', + profsurf: '\u2313', + prop: '\u221D', + Proportion: '\u2237', + Proportional: '\u221D', + propto: '\u221D', + prsim: '\u227E', + prurel: '\u22B0', + Pscr: '\uD835\uDCAB', + pscr: '\uD835\uDCC5', + Psi: '\u03A8', + psi: '\u03C8', + puncsp: '\u2008', + Qfr: '\uD835\uDD14', + qfr: '\uD835\uDD2E', + qint: '\u2A0C', + Qopf: '\u211A', + qopf: '\uD835\uDD62', + qprime: '\u2057', + Qscr: '\uD835\uDCAC', + qscr: '\uD835\uDCC6', + quaternions: '\u210D', + quatint: '\u2A16', + quest: '\u003F', + questeq: '\u225F', + QUOT: '\u0022', + quot: '\u0022', + rAarr: '\u21DB', + race: '\u223D\u0331', + Racute: '\u0154', + racute: '\u0155', + radic: '\u221A', + raemptyv: '\u29B3', + Rang: '\u27EB', + rang: '\u27E9', + rangd: '\u2992', + range: '\u29A5', + rangle: '\u27E9', + raquo: '\u00BB', + Rarr: '\u21A0', + rArr: '\u21D2', + rarr: '\u2192', + rarrap: '\u2975', + rarrb: '\u21E5', + rarrbfs: '\u2920', + rarrc: '\u2933', + rarrfs: '\u291E', + rarrhk: '\u21AA', + rarrlp: '\u21AC', + rarrpl: '\u2945', + rarrsim: '\u2974', + Rarrtl: '\u2916', + rarrtl: '\u21A3', + rarrw: '\u219D', + rAtail: '\u291C', + ratail: '\u291A', + ratio: '\u2236', + rationals: '\u211A', + RBarr: '\u2910', + rBarr: '\u290F', + rbarr: '\u290D', + rbbrk: '\u2773', + rbrace: '\u007D', + rbrack: '\u005D', + rbrke: '\u298C', + rbrksld: '\u298E', + rbrkslu: '\u2990', + Rcaron: '\u0158', + rcaron: '\u0159', + Rcedil: '\u0156', + rcedil: '\u0157', + rceil: '\u2309', + rcub: '\u007D', + Rcy: '\u0420', + rcy: '\u0440', + rdca: '\u2937', + rdldhar: '\u2969', + rdquo: '\u201D', + rdquor: '\u201D', + rdsh: '\u21B3', + Re: '\u211C', + real: '\u211C', + realine: '\u211B', + realpart: '\u211C', + reals: '\u211D', + rect: '\u25AD', + REG: '\u00AE', + reg: '\u00AE', + ReverseElement: '\u220B', + ReverseEquilibrium: '\u21CB', + ReverseUpEquilibrium: '\u296F', + rfisht: '\u297D', + rfloor: '\u230B', + Rfr: '\u211C', + rfr: '\uD835\uDD2F', + rHar: '\u2964', + rhard: '\u21C1', + rharu: '\u21C0', + rharul: '\u296C', + Rho: '\u03A1', + rho: '\u03C1', + rhov: '\u03F1', + RightAngleBracket: '\u27E9', + RightArrow: '\u2192', + Rightarrow: '\u21D2', + rightarrow: '\u2192', + RightArrowBar: '\u21E5', + RightArrowLeftArrow: '\u21C4', + rightarrowtail: '\u21A3', + RightCeiling: '\u2309', + RightDoubleBracket: '\u27E7', + RightDownTeeVector: '\u295D', + RightDownVector: '\u21C2', + RightDownVectorBar: '\u2955', + RightFloor: '\u230B', + rightharpoondown: '\u21C1', + rightharpoonup: '\u21C0', + rightleftarrows: '\u21C4', + rightleftharpoons: '\u21CC', + rightrightarrows: '\u21C9', + rightsquigarrow: '\u219D', + RightTee: '\u22A2', + RightTeeArrow: '\u21A6', + RightTeeVector: '\u295B', + rightthreetimes: '\u22CC', + RightTriangle: '\u22B3', + RightTriangleBar: '\u29D0', + RightTriangleEqual: '\u22B5', + RightUpDownVector: '\u294F', + RightUpTeeVector: '\u295C', + RightUpVector: '\u21BE', + RightUpVectorBar: '\u2954', + RightVector: '\u21C0', + RightVectorBar: '\u2953', + ring: '\u02DA', + risingdotseq: '\u2253', + rlarr: '\u21C4', + rlhar: '\u21CC', + rlm: '\u200F', + rmoust: '\u23B1', + rmoustache: '\u23B1', + rnmid: '\u2AEE', + roang: '\u27ED', + roarr: '\u21FE', + robrk: '\u27E7', + ropar: '\u2986', + Ropf: '\u211D', + ropf: '\uD835\uDD63', + roplus: '\u2A2E', + rotimes: '\u2A35', + RoundImplies: '\u2970', + rpar: '\u0029', + rpargt: '\u2994', + rppolint: '\u2A12', + rrarr: '\u21C9', + Rrightarrow: '\u21DB', + rsaquo: '\u203A', + Rscr: '\u211B', + rscr: '\uD835\uDCC7', + Rsh: '\u21B1', + rsh: '\u21B1', + rsqb: '\u005D', + rsquo: '\u2019', + rsquor: '\u2019', + rthree: '\u22CC', + rtimes: '\u22CA', + rtri: '\u25B9', + rtrie: '\u22B5', + rtrif: '\u25B8', + rtriltri: '\u29CE', + RuleDelayed: '\u29F4', + ruluhar: '\u2968', + rx: '\u211E', + Sacute: '\u015A', + sacute: '\u015B', + sbquo: '\u201A', + Sc: '\u2ABC', + sc: '\u227B', + scap: '\u2AB8', + Scaron: '\u0160', + scaron: '\u0161', + sccue: '\u227D', + scE: '\u2AB4', + sce: '\u2AB0', + Scedil: '\u015E', + scedil: '\u015F', + Scirc: '\u015C', + scirc: '\u015D', + scnap: '\u2ABA', + scnE: '\u2AB6', + scnsim: '\u22E9', + scpolint: '\u2A13', + scsim: '\u227F', + Scy: '\u0421', + scy: '\u0441', + sdot: '\u22C5', + sdotb: '\u22A1', + sdote: '\u2A66', + searhk: '\u2925', + seArr: '\u21D8', + searr: '\u2198', + searrow: '\u2198', + sect: '\u00A7', + semi: '\u003B', + seswar: '\u2929', + setminus: '\u2216', + setmn: '\u2216', + sext: '\u2736', + Sfr: '\uD835\uDD16', + sfr: '\uD835\uDD30', + sfrown: '\u2322', + sharp: '\u266F', + SHCHcy: '\u0429', + shchcy: '\u0449', + SHcy: '\u0428', + shcy: '\u0448', + ShortDownArrow: '\u2193', + ShortLeftArrow: '\u2190', + shortmid: '\u2223', + shortparallel: '\u2225', + ShortRightArrow: '\u2192', + ShortUpArrow: '\u2191', + shy: '\u00AD', + Sigma: '\u03A3', + sigma: '\u03C3', + sigmaf: '\u03C2', + sigmav: '\u03C2', + sim: '\u223C', + simdot: '\u2A6A', + sime: '\u2243', + simeq: '\u2243', + simg: '\u2A9E', + simgE: '\u2AA0', + siml: '\u2A9D', + simlE: '\u2A9F', + simne: '\u2246', + simplus: '\u2A24', + simrarr: '\u2972', + slarr: '\u2190', + SmallCircle: '\u2218', + smallsetminus: '\u2216', + smashp: '\u2A33', + smeparsl: '\u29E4', + smid: '\u2223', + smile: '\u2323', + smt: '\u2AAA', + smte: '\u2AAC', + smtes: '\u2AAC\uFE00', + SOFTcy: '\u042C', + softcy: '\u044C', + sol: '\u002F', + solb: '\u29C4', + solbar: '\u233F', + Sopf: '\uD835\uDD4A', + sopf: '\uD835\uDD64', + spades: '\u2660', + spadesuit: '\u2660', + spar: '\u2225', + sqcap: '\u2293', + sqcaps: '\u2293\uFE00', + sqcup: '\u2294', + sqcups: '\u2294\uFE00', + Sqrt: '\u221A', + sqsub: '\u228F', + sqsube: '\u2291', + sqsubset: '\u228F', + sqsubseteq: '\u2291', + sqsup: '\u2290', + sqsupe: '\u2292', + sqsupset: '\u2290', + sqsupseteq: '\u2292', + squ: '\u25A1', + Square: '\u25A1', + square: '\u25A1', + SquareIntersection: '\u2293', + SquareSubset: '\u228F', + SquareSubsetEqual: '\u2291', + SquareSuperset: '\u2290', + SquareSupersetEqual: '\u2292', + SquareUnion: '\u2294', + squarf: '\u25AA', + squf: '\u25AA', + srarr: '\u2192', + Sscr: '\uD835\uDCAE', + sscr: '\uD835\uDCC8', + ssetmn: '\u2216', + ssmile: '\u2323', + sstarf: '\u22C6', + Star: '\u22C6', + star: '\u2606', + starf: '\u2605', + straightepsilon: '\u03F5', + straightphi: '\u03D5', + strns: '\u00AF', + Sub: '\u22D0', + sub: '\u2282', + subdot: '\u2ABD', + subE: '\u2AC5', + sube: '\u2286', + subedot: '\u2AC3', + submult: '\u2AC1', + subnE: '\u2ACB', + subne: '\u228A', + subplus: '\u2ABF', + subrarr: '\u2979', + Subset: '\u22D0', + subset: '\u2282', + subseteq: '\u2286', + subseteqq: '\u2AC5', + SubsetEqual: '\u2286', + subsetneq: '\u228A', + subsetneqq: '\u2ACB', + subsim: '\u2AC7', + subsub: '\u2AD5', + subsup: '\u2AD3', + succ: '\u227B', + succapprox: '\u2AB8', + succcurlyeq: '\u227D', + Succeeds: '\u227B', + SucceedsEqual: '\u2AB0', + SucceedsSlantEqual: '\u227D', + SucceedsTilde: '\u227F', + succeq: '\u2AB0', + succnapprox: '\u2ABA', + succneqq: '\u2AB6', + succnsim: '\u22E9', + succsim: '\u227F', + SuchThat: '\u220B', + Sum: '\u2211', + sum: '\u2211', + sung: '\u266A', + Sup: '\u22D1', + sup: '\u2283', + sup1: '\u00B9', + sup2: '\u00B2', + sup3: '\u00B3', + supdot: '\u2ABE', + supdsub: '\u2AD8', + supE: '\u2AC6', + supe: '\u2287', + supedot: '\u2AC4', + Superset: '\u2283', + SupersetEqual: '\u2287', + suphsol: '\u27C9', + suphsub: '\u2AD7', + suplarr: '\u297B', + supmult: '\u2AC2', + supnE: '\u2ACC', + supne: '\u228B', + supplus: '\u2AC0', + Supset: '\u22D1', + supset: '\u2283', + supseteq: '\u2287', + supseteqq: '\u2AC6', + supsetneq: '\u228B', + supsetneqq: '\u2ACC', + supsim: '\u2AC8', + supsub: '\u2AD4', + supsup: '\u2AD6', + swarhk: '\u2926', + swArr: '\u21D9', + swarr: '\u2199', + swarrow: '\u2199', + swnwar: '\u292A', + szlig: '\u00DF', + Tab: '\u0009', + target: '\u2316', + Tau: '\u03A4', + tau: '\u03C4', + tbrk: '\u23B4', + Tcaron: '\u0164', + tcaron: '\u0165', + Tcedil: '\u0162', + tcedil: '\u0163', + Tcy: '\u0422', + tcy: '\u0442', + tdot: '\u20DB', + telrec: '\u2315', + Tfr: '\uD835\uDD17', + tfr: '\uD835\uDD31', + there4: '\u2234', + Therefore: '\u2234', + therefore: '\u2234', + Theta: '\u0398', + theta: '\u03B8', + thetasym: '\u03D1', + thetav: '\u03D1', + thickapprox: '\u2248', + thicksim: '\u223C', + ThickSpace: '\u205F\u200A', + thinsp: '\u2009', + ThinSpace: '\u2009', + thkap: '\u2248', + thksim: '\u223C', + THORN: '\u00DE', + thorn: '\u00FE', + Tilde: '\u223C', + tilde: '\u02DC', + TildeEqual: '\u2243', + TildeFullEqual: '\u2245', + TildeTilde: '\u2248', + times: '\u00D7', + timesb: '\u22A0', + timesbar: '\u2A31', + timesd: '\u2A30', + tint: '\u222D', + toea: '\u2928', + top: '\u22A4', + topbot: '\u2336', + topcir: '\u2AF1', + Topf: '\uD835\uDD4B', + topf: '\uD835\uDD65', + topfork: '\u2ADA', + tosa: '\u2929', + tprime: '\u2034', + TRADE: '\u2122', + trade: '\u2122', + triangle: '\u25B5', + triangledown: '\u25BF', + triangleleft: '\u25C3', + trianglelefteq: '\u22B4', + triangleq: '\u225C', + triangleright: '\u25B9', + trianglerighteq: '\u22B5', + tridot: '\u25EC', + trie: '\u225C', + triminus: '\u2A3A', + TripleDot: '\u20DB', + triplus: '\u2A39', + trisb: '\u29CD', + tritime: '\u2A3B', + trpezium: '\u23E2', + Tscr: '\uD835\uDCAF', + tscr: '\uD835\uDCC9', + TScy: '\u0426', + tscy: '\u0446', + TSHcy: '\u040B', + tshcy: '\u045B', + Tstrok: '\u0166', + tstrok: '\u0167', + twixt: '\u226C', + twoheadleftarrow: '\u219E', + twoheadrightarrow: '\u21A0', + Uacute: '\u00DA', + uacute: '\u00FA', + Uarr: '\u219F', + uArr: '\u21D1', + uarr: '\u2191', + Uarrocir: '\u2949', + Ubrcy: '\u040E', + ubrcy: '\u045E', + Ubreve: '\u016C', + ubreve: '\u016D', + Ucirc: '\u00DB', + ucirc: '\u00FB', + Ucy: '\u0423', + ucy: '\u0443', + udarr: '\u21C5', + Udblac: '\u0170', + udblac: '\u0171', + udhar: '\u296E', + ufisht: '\u297E', + Ufr: '\uD835\uDD18', + ufr: '\uD835\uDD32', + Ugrave: '\u00D9', + ugrave: '\u00F9', + uHar: '\u2963', + uharl: '\u21BF', + uharr: '\u21BE', + uhblk: '\u2580', + ulcorn: '\u231C', + ulcorner: '\u231C', + ulcrop: '\u230F', + ultri: '\u25F8', + Umacr: '\u016A', + umacr: '\u016B', + uml: '\u00A8', + UnderBar: '\u005F', + UnderBrace: '\u23DF', + UnderBracket: '\u23B5', + UnderParenthesis: '\u23DD', + Union: '\u22C3', + UnionPlus: '\u228E', + Uogon: '\u0172', + uogon: '\u0173', + Uopf: '\uD835\uDD4C', + uopf: '\uD835\uDD66', + UpArrow: '\u2191', + Uparrow: '\u21D1', + uparrow: '\u2191', + UpArrowBar: '\u2912', + UpArrowDownArrow: '\u21C5', + UpDownArrow: '\u2195', + Updownarrow: '\u21D5', + updownarrow: '\u2195', + UpEquilibrium: '\u296E', + upharpoonleft: '\u21BF', + upharpoonright: '\u21BE', + uplus: '\u228E', + UpperLeftArrow: '\u2196', + UpperRightArrow: '\u2197', + Upsi: '\u03D2', + upsi: '\u03C5', + upsih: '\u03D2', + Upsilon: '\u03A5', + upsilon: '\u03C5', + UpTee: '\u22A5', + UpTeeArrow: '\u21A5', + upuparrows: '\u21C8', + urcorn: '\u231D', + urcorner: '\u231D', + urcrop: '\u230E', + Uring: '\u016E', + uring: '\u016F', + urtri: '\u25F9', + Uscr: '\uD835\uDCB0', + uscr: '\uD835\uDCCA', + utdot: '\u22F0', + Utilde: '\u0168', + utilde: '\u0169', + utri: '\u25B5', + utrif: '\u25B4', + uuarr: '\u21C8', + Uuml: '\u00DC', + uuml: '\u00FC', + uwangle: '\u29A7', + vangrt: '\u299C', + varepsilon: '\u03F5', + varkappa: '\u03F0', + varnothing: '\u2205', + varphi: '\u03D5', + varpi: '\u03D6', + varpropto: '\u221D', + vArr: '\u21D5', + varr: '\u2195', + varrho: '\u03F1', + varsigma: '\u03C2', + varsubsetneq: '\u228A\uFE00', + varsubsetneqq: '\u2ACB\uFE00', + varsupsetneq: '\u228B\uFE00', + varsupsetneqq: '\u2ACC\uFE00', + vartheta: '\u03D1', + vartriangleleft: '\u22B2', + vartriangleright: '\u22B3', + Vbar: '\u2AEB', + vBar: '\u2AE8', + vBarv: '\u2AE9', + Vcy: '\u0412', + vcy: '\u0432', + VDash: '\u22AB', + Vdash: '\u22A9', + vDash: '\u22A8', + vdash: '\u22A2', + Vdashl: '\u2AE6', + Vee: '\u22C1', + vee: '\u2228', + veebar: '\u22BB', + veeeq: '\u225A', + vellip: '\u22EE', + Verbar: '\u2016', + verbar: '\u007C', + Vert: '\u2016', + vert: '\u007C', + VerticalBar: '\u2223', + VerticalLine: '\u007C', + VerticalSeparator: '\u2758', + VerticalTilde: '\u2240', + VeryThinSpace: '\u200A', + Vfr: '\uD835\uDD19', + vfr: '\uD835\uDD33', + vltri: '\u22B2', + vnsub: '\u2282\u20D2', + vnsup: '\u2283\u20D2', + Vopf: '\uD835\uDD4D', + vopf: '\uD835\uDD67', + vprop: '\u221D', + vrtri: '\u22B3', + Vscr: '\uD835\uDCB1', + vscr: '\uD835\uDCCB', + vsubnE: '\u2ACB\uFE00', + vsubne: '\u228A\uFE00', + vsupnE: '\u2ACC\uFE00', + vsupne: '\u228B\uFE00', + Vvdash: '\u22AA', + vzigzag: '\u299A', + Wcirc: '\u0174', + wcirc: '\u0175', + wedbar: '\u2A5F', + Wedge: '\u22C0', + wedge: '\u2227', + wedgeq: '\u2259', + weierp: '\u2118', + Wfr: '\uD835\uDD1A', + wfr: '\uD835\uDD34', + Wopf: '\uD835\uDD4E', + wopf: '\uD835\uDD68', + wp: '\u2118', + wr: '\u2240', + wreath: '\u2240', + Wscr: '\uD835\uDCB2', + wscr: '\uD835\uDCCC', + xcap: '\u22C2', + xcirc: '\u25EF', + xcup: '\u22C3', + xdtri: '\u25BD', + Xfr: '\uD835\uDD1B', + xfr: '\uD835\uDD35', + xhArr: '\u27FA', + xharr: '\u27F7', + Xi: '\u039E', + xi: '\u03BE', + xlArr: '\u27F8', + xlarr: '\u27F5', + xmap: '\u27FC', + xnis: '\u22FB', + xodot: '\u2A00', + Xopf: '\uD835\uDD4F', + xopf: '\uD835\uDD69', + xoplus: '\u2A01', + xotime: '\u2A02', + xrArr: '\u27F9', + xrarr: '\u27F6', + Xscr: '\uD835\uDCB3', + xscr: '\uD835\uDCCD', + xsqcup: '\u2A06', + xuplus: '\u2A04', + xutri: '\u25B3', + xvee: '\u22C1', + xwedge: '\u22C0', + Yacute: '\u00DD', + yacute: '\u00FD', + YAcy: '\u042F', + yacy: '\u044F', + Ycirc: '\u0176', + ycirc: '\u0177', + Ycy: '\u042B', + ycy: '\u044B', + yen: '\u00A5', + Yfr: '\uD835\uDD1C', + yfr: '\uD835\uDD36', + YIcy: '\u0407', + yicy: '\u0457', + Yopf: '\uD835\uDD50', + yopf: '\uD835\uDD6A', + Yscr: '\uD835\uDCB4', + yscr: '\uD835\uDCCE', + YUcy: '\u042E', + yucy: '\u044E', + Yuml: '\u0178', + yuml: '\u00FF', + Zacute: '\u0179', + zacute: '\u017A', + Zcaron: '\u017D', + zcaron: '\u017E', + Zcy: '\u0417', + zcy: '\u0437', + Zdot: '\u017B', + zdot: '\u017C', + zeetrf: '\u2128', + ZeroWidthSpace: '\u200B', + Zeta: '\u0396', + zeta: '\u03B6', + Zfr: '\u2128', + zfr: '\uD835\uDD37', + ZHcy: '\u0416', + zhcy: '\u0436', + zigrarr: '\u21DD', + Zopf: '\u2124', + zopf: '\uD835\uDD6B', + Zscr: '\uD835\uDCB5', + zscr: '\uD835\uDCCF', + zwj: '\u200D', + zwnj: '\u200C', +}); + +/** + * @deprecated use `HTML_ENTITIES` instead + * @see HTML_ENTITIES + */ +exports.entityMap = exports.HTML_ENTITIES; diff --git a/claude-code-source/node_modules/@xmldom/xmldom/lib/index.js b/claude-code-source/node_modules/@xmldom/xmldom/lib/index.js new file mode 100644 index 00000000..df827f6f --- /dev/null +++ b/claude-code-source/node_modules/@xmldom/xmldom/lib/index.js @@ -0,0 +1,4 @@ +var dom = require('./dom') +exports.DOMImplementation = dom.DOMImplementation +exports.XMLSerializer = dom.XMLSerializer +exports.DOMParser = require('./dom-parser').DOMParser diff --git a/claude-code-source/node_modules/@xmldom/xmldom/lib/sax.js b/claude-code-source/node_modules/@xmldom/xmldom/lib/sax.js new file mode 100644 index 00000000..2ec3ea1e --- /dev/null +++ b/claude-code-source/node_modules/@xmldom/xmldom/lib/sax.js @@ -0,0 +1,662 @@ +var NAMESPACE = require("./conventions").NAMESPACE; + +//[4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF] +//[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040] +//[5] Name ::= NameStartChar (NameChar)* +var nameStartChar = /[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]///\u10000-\uEFFFF +var nameChar = new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"); +var tagNamePattern = new RegExp('^'+nameStartChar.source+nameChar.source+'*(?:\:'+nameStartChar.source+nameChar.source+'*)?$'); +//var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/ +//var handlers = 'resolveEntity,getExternalSubset,characters,endDocument,endElement,endPrefixMapping,ignorableWhitespace,processingInstruction,setDocumentLocator,skippedEntity,startDocument,startElement,startPrefixMapping,notationDecl,unparsedEntityDecl,error,fatalError,warning,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,comment,endCDATA,endDTD,endEntity,startCDATA,startDTD,startEntity'.split(',') + +//S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE +//S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE +var S_TAG = 0;//tag name offerring +var S_ATTR = 1;//attr name offerring +var S_ATTR_SPACE=2;//attr name end and space offer +var S_EQ = 3;//=space? +var S_ATTR_NOQUOT_VALUE = 4;//attr value(no quot value only) +var S_ATTR_END = 5;//attr value end and no space(quot end) +var S_TAG_SPACE = 6;//(attr value end || tag end ) && (space offer) +var S_TAG_CLOSE = 7;//closed el + +/** + * Creates an error that will not be caught by XMLReader aka the SAX parser. + * + * @param {string} message + * @param {any?} locator Optional, can provide details about the location in the source + * @constructor + */ +function ParseError(message, locator) { + this.message = message + this.locator = locator + if(Error.captureStackTrace) Error.captureStackTrace(this, ParseError); +} +ParseError.prototype = new Error(); +ParseError.prototype.name = ParseError.name + +function XMLReader(){ + +} + +XMLReader.prototype = { + parse:function(source,defaultNSMap,entityMap){ + var domBuilder = this.domBuilder; + domBuilder.startDocument(); + _copy(defaultNSMap ,defaultNSMap = {}) + parse(source,defaultNSMap,entityMap, + domBuilder,this.errorHandler); + domBuilder.endDocument(); + } +} +function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){ + function fixedFromCharCode(code) { + // String.prototype.fromCharCode does not supports + // > 2 bytes unicode chars directly + if (code > 0xffff) { + code -= 0x10000; + var surrogate1 = 0xd800 + (code >> 10) + , surrogate2 = 0xdc00 + (code & 0x3ff); + + return String.fromCharCode(surrogate1, surrogate2); + } else { + return String.fromCharCode(code); + } + } + function entityReplacer(a){ + var k = a.slice(1,-1); + if (Object.hasOwnProperty.call(entityMap, k)) { + return entityMap[k]; + }else if(k.charAt(0) === '#'){ + return fixedFromCharCode(parseInt(k.substr(1).replace('x','0x'))) + }else{ + errorHandler.error('entity not found:'+a); + return a; + } + } + function appendText(end){//has some bugs + if(end>start){ + var xt = source.substring(start,end).replace(/&#?\w+;/g,entityReplacer); + locator&&position(start); + domBuilder.characters(xt,0,end-start); + start = end + } + } + function position(p,m){ + while(p>=lineEnd && (m = linePattern.exec(source))){ + lineStart = m.index; + lineEnd = lineStart + m[0].length; + locator.lineNumber++; + //console.log('line++:',locator,startPos,endPos) + } + locator.columnNumber = p-lineStart+1; + } + var lineStart = 0; + var lineEnd = 0; + var linePattern = /.*(?:\r\n?|\n)|.*$/g + var locator = domBuilder.locator; + + var parseStack = [{currentNSMap:defaultNSMapCopy}] + var closeMap = {}; + var start = 0; + while(true){ + try{ + var tagStart = source.indexOf('<',start); + if(tagStart<0){ + if(!source.substr(start).match(/^\s*$/)){ + var doc = domBuilder.doc; + var text = doc.createTextNode(source.substr(start)); + doc.appendChild(text); + domBuilder.currentElement = text; + } + return; + } + if(tagStart>start){ + appendText(tagStart); + } + switch(source.charAt(tagStart+1)){ + case '/': + var end = source.indexOf('>',tagStart+3); + var tagName = source.substring(tagStart + 2, end).replace(/[ \t\n\r]+$/g, ''); + var config = parseStack.pop(); + if(end<0){ + + tagName = source.substring(tagStart+2).replace(/[\s<].*/,''); + errorHandler.error("end tag name: "+tagName+' is not complete:'+config.tagName); + end = tagStart+1+tagName.length; + }else if(tagName.match(/\s + locator&&position(tagStart); + end = parseInstruction(source,tagStart,domBuilder); + break; + case '!':// start){ + start = end; + }else{ + //TODO: 这里有可能sax回退,有位置错误风险 + appendText(Math.max(tagStart,start)+1); + } + } +} +function copyLocator(f,t){ + t.lineNumber = f.lineNumber; + t.columnNumber = f.columnNumber; + return t; +} + +/** + * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack); + * @return end of the elementStartPart(end of elementEndPart for selfClosed el) + */ +function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,errorHandler){ + + /** + * @param {string} qname + * @param {string} value + * @param {number} startIndex + */ + function addAttribute(qname, value, startIndex) { + if (el.attributeNames.hasOwnProperty(qname)) { + errorHandler.fatalError('Attribute ' + qname + ' redefined') + } + el.addValue( + qname, + // @see https://www.w3.org/TR/xml/#AVNormalize + // since the xmldom sax parser does not "interpret" DTD the following is not implemented: + // - recursive replacement of (DTD) entity references + // - trimming and collapsing multiple spaces into a single one for attributes that are not of type CDATA + value.replace(/[\t\n\r]/g, ' ').replace(/&#?\w+;/g, entityReplacer), + startIndex + ) + } + var attrName; + var value; + var p = ++start; + var s = S_TAG;//status + while(true){ + var c = source.charAt(p); + switch(c){ + case '=': + if(s === S_ATTR){//attrName + attrName = source.slice(start,p); + s = S_EQ; + }else if(s === S_ATTR_SPACE){ + s = S_EQ; + }else{ + //fatalError: equal must after attrName or space after attrName + throw new Error('attribute equal must after attrName'); // No known test case + } + break; + case '\'': + case '"': + if(s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE + ){//equal + if(s === S_ATTR){ + errorHandler.warning('attribute value must after "="') + attrName = source.slice(start,p) + } + start = p+1; + p = source.indexOf(c,start) + if(p>0){ + value = source.slice(start, p); + addAttribute(attrName, value, start-1); + s = S_ATTR_END; + }else{ + //fatalError: no end quot match + throw new Error('attribute value no end \''+c+'\' match'); + } + }else if(s == S_ATTR_NOQUOT_VALUE){ + value = source.slice(start, p); + addAttribute(attrName, value, start); + errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+')!!'); + start = p+1; + s = S_ATTR_END + }else{ + //fatalError: no equal before + throw new Error('attribute value must after "="'); // No known test case + } + break; + case '/': + switch(s){ + case S_TAG: + el.setTagName(source.slice(start,p)); + case S_ATTR_END: + case S_TAG_SPACE: + case S_TAG_CLOSE: + s =S_TAG_CLOSE; + el.closed = true; + case S_ATTR_NOQUOT_VALUE: + case S_ATTR: + break; + case S_ATTR_SPACE: + el.closed = true; + break; + //case S_EQ: + default: + throw new Error("attribute invalid close char('/')") // No known test case + } + break; + case ''://end document + errorHandler.error('unexpected end of input'); + if(s == S_TAG){ + el.setTagName(source.slice(start,p)); + } + return p; + case '>': + switch(s){ + case S_TAG: + el.setTagName(source.slice(start,p)); + case S_ATTR_END: + case S_TAG_SPACE: + case S_TAG_CLOSE: + break;//normal + case S_ATTR_NOQUOT_VALUE://Compatible state + case S_ATTR: + value = source.slice(start,p); + if(value.slice(-1) === '/'){ + el.closed = true; + value = value.slice(0,-1) + } + case S_ATTR_SPACE: + if(s === S_ATTR_SPACE){ + value = attrName; + } + if(s == S_ATTR_NOQUOT_VALUE){ + errorHandler.warning('attribute "'+value+'" missed quot(")!'); + addAttribute(attrName, value, start) + }else{ + if(!NAMESPACE.isHTML(currentNSMap['']) || !value.match(/^(?:disabled|checked|selected)$/i)){ + errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!') + } + addAttribute(value, value, start) + } + break; + case S_EQ: + throw new Error('attribute value missed!!'); + } +// console.log(tagName,tagNamePattern,tagNamePattern.test(tagName)) + return p; + /*xml space '\x20' | #x9 | #xD | #xA; */ + case '\u0080': + c = ' '; + default: + if(c<= ' '){//space + switch(s){ + case S_TAG: + el.setTagName(source.slice(start,p));//tagName + s = S_TAG_SPACE; + break; + case S_ATTR: + attrName = source.slice(start,p) + s = S_ATTR_SPACE; + break; + case S_ATTR_NOQUOT_VALUE: + var value = source.slice(start, p); + errorHandler.warning('attribute "'+value+'" missed quot(")!!'); + addAttribute(attrName, value, start) + case S_ATTR_END: + s = S_TAG_SPACE; + break; + //case S_TAG_SPACE: + //case S_EQ: + //case S_ATTR_SPACE: + // void();break; + //case S_TAG_CLOSE: + //ignore warning + } + }else{//not space +//S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE +//S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE + switch(s){ + //case S_TAG:void();break; + //case S_ATTR:void();break; + //case S_ATTR_NOQUOT_VALUE:void();break; + case S_ATTR_SPACE: + var tagName = el.tagName; + if (!NAMESPACE.isHTML(currentNSMap['']) || !attrName.match(/^(?:disabled|checked|selected)$/i)) { + errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead2!!') + } + addAttribute(attrName, attrName, start); + start = p; + s = S_ATTR; + break; + case S_ATTR_END: + errorHandler.warning('attribute space is required"'+attrName+'"!!') + case S_TAG_SPACE: + s = S_ATTR; + start = p; + break; + case S_EQ: + s = S_ATTR_NOQUOT_VALUE; + start = p; + break; + case S_TAG_CLOSE: + throw new Error("elements closed character '/' and '>' must be connected to"); + } + } + }//end outer switch + //console.log('p++',p) + p++; + } +} +/** + * @return true if has new namespace define + */ +function appendElement(el,domBuilder,currentNSMap){ + var tagName = el.tagName; + var localNSMap = null; + //var currentNSMap = parseStack[parseStack.length-1].currentNSMap; + var i = el.length; + while(i--){ + var a = el[i]; + var qName = a.qName; + var value = a.value; + var nsp = qName.indexOf(':'); + if(nsp>0){ + var prefix = a.prefix = qName.slice(0,nsp); + var localName = qName.slice(nsp+1); + var nsPrefix = prefix === 'xmlns' && localName + }else{ + localName = qName; + prefix = null + nsPrefix = qName === 'xmlns' && '' + } + //can not set prefix,because prefix !== '' + a.localName = localName ; + //prefix == null for no ns prefix attribute + if(nsPrefix !== false){//hack!! + if(localNSMap == null){ + localNSMap = {} + //console.log(currentNSMap,0) + _copy(currentNSMap,currentNSMap={}) + //console.log(currentNSMap,1) + } + currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value; + a.uri = NAMESPACE.XMLNS + domBuilder.startPrefixMapping(nsPrefix, value) + } + } + var i = el.length; + while(i--){ + a = el[i]; + var prefix = a.prefix; + if(prefix){//no prefix attribute has no namespace + if(prefix === 'xml'){ + a.uri = NAMESPACE.XML; + }if(prefix !== 'xmlns'){ + a.uri = currentNSMap[prefix || ''] + + //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)} + } + } + } + var nsp = tagName.indexOf(':'); + if(nsp>0){ + prefix = el.prefix = tagName.slice(0,nsp); + localName = el.localName = tagName.slice(nsp+1); + }else{ + prefix = null;//important!! + localName = el.localName = tagName; + } + //no prefix element has default namespace + var ns = el.uri = currentNSMap[prefix || '']; + domBuilder.startElement(ns,localName,tagName,el); + //endPrefixMapping and startPrefixMapping have not any help for dom builder + //localNSMap = null + if(el.closed){ + domBuilder.endElement(ns,localName,tagName); + if(localNSMap){ + for (prefix in localNSMap) { + if (Object.prototype.hasOwnProperty.call(localNSMap, prefix)) { + domBuilder.endPrefixMapping(prefix); + } + } + } + }else{ + el.currentNSMap = currentNSMap; + el.localNSMap = localNSMap; + //parseStack.push(el); + return true; + } +} +function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){ + if(/^(?:script|textarea)$/i.test(tagName)){ + var elEndStart = source.indexOf('',elStartEnd); + var text = source.substring(elStartEnd+1,elEndStart); + if(/[&<]/.test(text)){ + if(/^script$/i.test(tagName)){ + //if(!/\]\]>/.test(text)){ + //lexHandler.startCDATA(); + domBuilder.characters(text,0,text.length); + //lexHandler.endCDATA(); + return elEndStart; + //} + }//}else{//text area + text = text.replace(/&#?\w+;/g,entityReplacer); + domBuilder.characters(text,0,text.length); + return elEndStart; + //} + + } + } + return elStartEnd+1; +} +function fixSelfClosed(source,elStartEnd,tagName,closeMap){ + //if(tagName in closeMap){ + var pos = closeMap[tagName]; + if(pos == null){ + //console.log(tagName) + pos = source.lastIndexOf('') + if(pos',start+4); + //append comment source.substring(4,end)//' + }, + { + begin: '' + } + ] + } + ] + } + ), + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + { + className: 'meta', + begin: '#', + end: '$', + keywords: { + 'meta-keyword': 'if else elif endif define undef warning error line region endregion pragma checksum' + } + }, + STRING, + NUMBERS, + { + beginKeywords: 'class interface', + relevance: 0, + end: /[{;=]/, + illegal: /[^\s:,]/, + contains: [ + { + beginKeywords: "where class" + }, + TITLE_MODE, + GENERIC_MODIFIER, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE + ] + }, + { + beginKeywords: 'namespace', + relevance: 0, + end: /[{;=]/, + illegal: /[^\s:]/, + contains: [ + TITLE_MODE, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE + ] + }, + { + beginKeywords: 'record', + relevance: 0, + end: /[{;=]/, + illegal: /[^\s:]/, + contains: [ + TITLE_MODE, + GENERIC_MODIFIER, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE + ] + }, + { + // [Attributes("")] + className: 'meta', + begin: '^\\s*\\[', + excludeBegin: true, + end: '\\]', + excludeEnd: true, + contains: [ + { + className: 'meta-string', + begin: /"/, + end: /"/ + } + ] + }, + { + // Expression keywords prevent 'keyword Name(...)' from being + // recognized as a function definition + beginKeywords: 'new return throw await else', + relevance: 0 + }, + { + className: 'function', + begin: '(' + TYPE_IDENT_RE + '\\s+)+' + hljs.IDENT_RE + '\\s*(<.+>\\s*)?\\(', + returnBegin: true, + end: /\s*[{;=]/, + excludeEnd: true, + keywords: KEYWORDS, + contains: [ + // prevents these from being highlighted `title` + { + beginKeywords: FUNCTION_MODIFIERS.join(" "), + relevance: 0 + }, + { + begin: hljs.IDENT_RE + '\\s*(<.+>\\s*)?\\(', + returnBegin: true, + contains: [ + hljs.TITLE_MODE, + GENERIC_MODIFIER + ], + relevance: 0 + }, + { + className: 'params', + begin: /\(/, + end: /\)/, + excludeBegin: true, + excludeEnd: true, + keywords: KEYWORDS, + relevance: 0, + contains: [ + STRING, + NUMBERS, + hljs.C_BLOCK_COMMENT_MODE + ] + }, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE + ] + }, + AT_IDENTIFIER + ] + }; +} + +module.exports = csharp; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/csp.js b/claude-code-source/node_modules/highlight.js/lib/languages/csp.js new file mode 100644 index 00000000..6539c47b --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/csp.js @@ -0,0 +1,37 @@ +/* +Language: CSP +Description: Content Security Policy definition highlighting +Author: Taras +Website: https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP + +vim: ts=2 sw=2 st=2 +*/ + +/** @type LanguageFn */ +function csp(hljs) { + return { + name: 'CSP', + case_insensitive: false, + keywords: { + $pattern: '[a-zA-Z][a-zA-Z0-9_-]*', + keyword: 'base-uri child-src connect-src default-src font-src form-action ' + + 'frame-ancestors frame-src img-src media-src object-src plugin-types ' + + 'report-uri sandbox script-src style-src' + }, + contains: [ + { + className: 'string', + begin: "'", + end: "'" + }, + { + className: 'attribute', + begin: '^Content', + end: ':', + excludeEnd: true + } + ] + }; +} + +module.exports = csp; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/css.js b/claude-code-source/node_modules/highlight.js/lib/languages/css.js new file mode 100644 index 00000000..b0e21b6a --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/css.js @@ -0,0 +1,608 @@ +const MODES = (hljs) => { + return { + IMPORTANT: { + className: 'meta', + begin: '!important' + }, + HEXCOLOR: { + className: 'number', + begin: '#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})' + }, + ATTRIBUTE_SELECTOR_MODE: { + className: 'selector-attr', + begin: /\[/, + end: /\]/, + illegal: '$', + contains: [ + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE + ] + } + }; +}; + +const TAGS = [ + 'a', + 'abbr', + 'address', + 'article', + 'aside', + 'audio', + 'b', + 'blockquote', + 'body', + 'button', + 'canvas', + 'caption', + 'cite', + 'code', + 'dd', + 'del', + 'details', + 'dfn', + 'div', + 'dl', + 'dt', + 'em', + 'fieldset', + 'figcaption', + 'figure', + 'footer', + 'form', + 'h1', + 'h2', + 'h3', + 'h4', + 'h5', + 'h6', + 'header', + 'hgroup', + 'html', + 'i', + 'iframe', + 'img', + 'input', + 'ins', + 'kbd', + 'label', + 'legend', + 'li', + 'main', + 'mark', + 'menu', + 'nav', + 'object', + 'ol', + 'p', + 'q', + 'quote', + 'samp', + 'section', + 'span', + 'strong', + 'summary', + 'sup', + 'table', + 'tbody', + 'td', + 'textarea', + 'tfoot', + 'th', + 'thead', + 'time', + 'tr', + 'ul', + 'var', + 'video' +]; + +const MEDIA_FEATURES = [ + 'any-hover', + 'any-pointer', + 'aspect-ratio', + 'color', + 'color-gamut', + 'color-index', + 'device-aspect-ratio', + 'device-height', + 'device-width', + 'display-mode', + 'forced-colors', + 'grid', + 'height', + 'hover', + 'inverted-colors', + 'monochrome', + 'orientation', + 'overflow-block', + 'overflow-inline', + 'pointer', + 'prefers-color-scheme', + 'prefers-contrast', + 'prefers-reduced-motion', + 'prefers-reduced-transparency', + 'resolution', + 'scan', + 'scripting', + 'update', + 'width', + // TODO: find a better solution? + 'min-width', + 'max-width', + 'min-height', + 'max-height' +]; + +// https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes +const PSEUDO_CLASSES = [ + 'active', + 'any-link', + 'blank', + 'checked', + 'current', + 'default', + 'defined', + 'dir', // dir() + 'disabled', + 'drop', + 'empty', + 'enabled', + 'first', + 'first-child', + 'first-of-type', + 'fullscreen', + 'future', + 'focus', + 'focus-visible', + 'focus-within', + 'has', // has() + 'host', // host or host() + 'host-context', // host-context() + 'hover', + 'indeterminate', + 'in-range', + 'invalid', + 'is', // is() + 'lang', // lang() + 'last-child', + 'last-of-type', + 'left', + 'link', + 'local-link', + 'not', // not() + 'nth-child', // nth-child() + 'nth-col', // nth-col() + 'nth-last-child', // nth-last-child() + 'nth-last-col', // nth-last-col() + 'nth-last-of-type', //nth-last-of-type() + 'nth-of-type', //nth-of-type() + 'only-child', + 'only-of-type', + 'optional', + 'out-of-range', + 'past', + 'placeholder-shown', + 'read-only', + 'read-write', + 'required', + 'right', + 'root', + 'scope', + 'target', + 'target-within', + 'user-invalid', + 'valid', + 'visited', + 'where' // where() +]; + +// https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements +const PSEUDO_ELEMENTS = [ + 'after', + 'backdrop', + 'before', + 'cue', + 'cue-region', + 'first-letter', + 'first-line', + 'grammar-error', + 'marker', + 'part', + 'placeholder', + 'selection', + 'slotted', + 'spelling-error' +]; + +const ATTRIBUTES = [ + 'align-content', + 'align-items', + 'align-self', + 'animation', + 'animation-delay', + 'animation-direction', + 'animation-duration', + 'animation-fill-mode', + 'animation-iteration-count', + 'animation-name', + 'animation-play-state', + 'animation-timing-function', + 'auto', + 'backface-visibility', + 'background', + 'background-attachment', + 'background-clip', + 'background-color', + 'background-image', + 'background-origin', + 'background-position', + 'background-repeat', + 'background-size', + 'border', + 'border-bottom', + 'border-bottom-color', + 'border-bottom-left-radius', + 'border-bottom-right-radius', + 'border-bottom-style', + 'border-bottom-width', + 'border-collapse', + 'border-color', + 'border-image', + 'border-image-outset', + 'border-image-repeat', + 'border-image-slice', + 'border-image-source', + 'border-image-width', + 'border-left', + 'border-left-color', + 'border-left-style', + 'border-left-width', + 'border-radius', + 'border-right', + 'border-right-color', + 'border-right-style', + 'border-right-width', + 'border-spacing', + 'border-style', + 'border-top', + 'border-top-color', + 'border-top-left-radius', + 'border-top-right-radius', + 'border-top-style', + 'border-top-width', + 'border-width', + 'bottom', + 'box-decoration-break', + 'box-shadow', + 'box-sizing', + 'break-after', + 'break-before', + 'break-inside', + 'caption-side', + 'clear', + 'clip', + 'clip-path', + 'color', + 'column-count', + 'column-fill', + 'column-gap', + 'column-rule', + 'column-rule-color', + 'column-rule-style', + 'column-rule-width', + 'column-span', + 'column-width', + 'columns', + 'content', + 'counter-increment', + 'counter-reset', + 'cursor', + 'direction', + 'display', + 'empty-cells', + 'filter', + 'flex', + 'flex-basis', + 'flex-direction', + 'flex-flow', + 'flex-grow', + 'flex-shrink', + 'flex-wrap', + 'float', + 'font', + 'font-display', + 'font-family', + 'font-feature-settings', + 'font-kerning', + 'font-language-override', + 'font-size', + 'font-size-adjust', + 'font-smoothing', + 'font-stretch', + 'font-style', + 'font-variant', + 'font-variant-ligatures', + 'font-variation-settings', + 'font-weight', + 'height', + 'hyphens', + 'icon', + 'image-orientation', + 'image-rendering', + 'image-resolution', + 'ime-mode', + 'inherit', + 'initial', + 'justify-content', + 'left', + 'letter-spacing', + 'line-height', + 'list-style', + 'list-style-image', + 'list-style-position', + 'list-style-type', + 'margin', + 'margin-bottom', + 'margin-left', + 'margin-right', + 'margin-top', + 'marks', + 'mask', + 'max-height', + 'max-width', + 'min-height', + 'min-width', + 'nav-down', + 'nav-index', + 'nav-left', + 'nav-right', + 'nav-up', + 'none', + 'normal', + 'object-fit', + 'object-position', + 'opacity', + 'order', + 'orphans', + 'outline', + 'outline-color', + 'outline-offset', + 'outline-style', + 'outline-width', + 'overflow', + 'overflow-wrap', + 'overflow-x', + 'overflow-y', + 'padding', + 'padding-bottom', + 'padding-left', + 'padding-right', + 'padding-top', + 'page-break-after', + 'page-break-before', + 'page-break-inside', + 'perspective', + 'perspective-origin', + 'pointer-events', + 'position', + 'quotes', + 'resize', + 'right', + 'src', // @font-face + 'tab-size', + 'table-layout', + 'text-align', + 'text-align-last', + 'text-decoration', + 'text-decoration-color', + 'text-decoration-line', + 'text-decoration-style', + 'text-indent', + 'text-overflow', + 'text-rendering', + 'text-shadow', + 'text-transform', + 'text-underline-position', + 'top', + 'transform', + 'transform-origin', + 'transform-style', + 'transition', + 'transition-delay', + 'transition-duration', + 'transition-property', + 'transition-timing-function', + 'unicode-bidi', + 'vertical-align', + 'visibility', + 'white-space', + 'widows', + 'width', + 'word-break', + 'word-spacing', + 'word-wrap', + 'z-index' + // reverse makes sure longer attributes `font-weight` are matched fully + // instead of getting false positives on say `font` +].reverse(); + +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function lookahead(re) { + return concat('(?=', re, ')'); +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/* +Language: CSS +Category: common, css +Website: https://developer.mozilla.org/en-US/docs/Web/CSS +*/ + +/** @type LanguageFn */ +function css(hljs) { + const modes = MODES(hljs); + const FUNCTION_DISPATCH = { + className: "built_in", + begin: /[\w-]+(?=\()/ + }; + const VENDOR_PREFIX = { + begin: /-(webkit|moz|ms|o)-(?=[a-z])/ + }; + const AT_MODIFIERS = "and or not only"; + const AT_PROPERTY_RE = /@-?\w[\w]*(-\w+)*/; // @-webkit-keyframes + const IDENT_RE = '[a-zA-Z-][a-zA-Z0-9_-]*'; + const STRINGS = [ + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE + ]; + + return { + name: 'CSS', + case_insensitive: true, + illegal: /[=|'\$]/, + keywords: { + keyframePosition: "from to" + }, + classNameAliases: { + // for visual continuity with `tag {}` and because we + // don't have a great class for this? + keyframePosition: "selector-tag" + }, + contains: [ + hljs.C_BLOCK_COMMENT_MODE, + VENDOR_PREFIX, + // to recognize keyframe 40% etc which are outside the scope of our + // attribute value mode + hljs.CSS_NUMBER_MODE, + { + className: 'selector-id', + begin: /#[A-Za-z0-9_-]+/, + relevance: 0 + }, + { + className: 'selector-class', + begin: '\\.' + IDENT_RE, + relevance: 0 + }, + modes.ATTRIBUTE_SELECTOR_MODE, + { + className: 'selector-pseudo', + variants: [ + { + begin: ':(' + PSEUDO_CLASSES.join('|') + ')' + }, + { + begin: '::(' + PSEUDO_ELEMENTS.join('|') + ')' + } + ] + }, + // we may actually need this (12/2020) + // { // pseudo-selector params + // begin: /\(/, + // end: /\)/, + // contains: [ hljs.CSS_NUMBER_MODE ] + // }, + { + className: 'attribute', + begin: '\\b(' + ATTRIBUTES.join('|') + ')\\b' + }, + // attribute values + { + begin: ':', + end: '[;}]', + contains: [ + modes.HEXCOLOR, + modes.IMPORTANT, + hljs.CSS_NUMBER_MODE, + ...STRINGS, + // needed to highlight these as strings and to avoid issues with + // illegal characters that might be inside urls that would tigger the + // languages illegal stack + { + begin: /(url|data-uri)\(/, + end: /\)/, + relevance: 0, // from keywords + keywords: { + built_in: "url data-uri" + }, + contains: [ + { + className: "string", + // any character other than `)` as in `url()` will be the start + // of a string, which ends with `)` (from the parent mode) + begin: /[^)]/, + endsWithParent: true, + excludeEnd: true + } + ] + }, + FUNCTION_DISPATCH + ] + }, + { + begin: lookahead(/@/), + end: '[{;]', + relevance: 0, + illegal: /:/, // break on Less variables @var: ... + contains: [ + { + className: 'keyword', + begin: AT_PROPERTY_RE + }, + { + begin: /\s/, + endsWithParent: true, + excludeEnd: true, + relevance: 0, + keywords: { + $pattern: /[a-z-]+/, + keyword: AT_MODIFIERS, + attribute: MEDIA_FEATURES.join(" ") + }, + contains: [ + { + begin: /[a-z-]+(?=:)/, + className: "attribute" + }, + ...STRINGS, + hljs.CSS_NUMBER_MODE + ] + } + ] + }, + { + className: 'selector-tag', + begin: '\\b(' + TAGS.join('|') + ')\\b' + } + ] + }; +} + +module.exports = css; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/d.js b/claude-code-source/node_modules/highlight.js/lib/languages/d.js new file mode 100644 index 00000000..f302283f --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/d.js @@ -0,0 +1,271 @@ +/* +Language: D +Author: Aleksandar Ruzicic +Description: D is a language with C-like syntax and static typing. It pragmatically combines efficiency, control, and modeling power, with safety and programmer productivity. +Version: 1.0a +Website: https://dlang.org +Date: 2012-04-08 +*/ + +/** + * Known issues: + * + * - invalid hex string literals will be recognized as a double quoted strings + * but 'x' at the beginning of string will not be matched + * + * - delimited string literals are not checked for matching end delimiter + * (not possible to do with js regexp) + * + * - content of token string is colored as a string (i.e. no keyword coloring inside a token string) + * also, content of token string is not validated to contain only valid D tokens + * + * - special token sequence rule is not strictly following D grammar (anything following #line + * up to the end of line is matched as special token sequence) + */ + +/** @type LanguageFn */ +function d(hljs) { + /** + * Language keywords + * + * @type {Object} + */ + const D_KEYWORDS = { + $pattern: hljs.UNDERSCORE_IDENT_RE, + keyword: + 'abstract alias align asm assert auto body break byte case cast catch class ' + + 'const continue debug default delete deprecated do else enum export extern final ' + + 'finally for foreach foreach_reverse|10 goto if immutable import in inout int ' + + 'interface invariant is lazy macro mixin module new nothrow out override package ' + + 'pragma private protected public pure ref return scope shared static struct ' + + 'super switch synchronized template this throw try typedef typeid typeof union ' + + 'unittest version void volatile while with __FILE__ __LINE__ __gshared|10 ' + + '__thread __traits __DATE__ __EOF__ __TIME__ __TIMESTAMP__ __VENDOR__ __VERSION__', + built_in: + 'bool cdouble cent cfloat char creal dchar delegate double dstring float function ' + + 'idouble ifloat ireal long real short string ubyte ucent uint ulong ushort wchar ' + + 'wstring', + literal: + 'false null true' + }; + + /** + * Number literal regexps + * + * @type {String} + */ + const decimal_integer_re = '(0|[1-9][\\d_]*)'; + const decimal_integer_nosus_re = '(0|[1-9][\\d_]*|\\d[\\d_]*|[\\d_]+?\\d)'; + const binary_integer_re = '0[bB][01_]+'; + const hexadecimal_digits_re = '([\\da-fA-F][\\da-fA-F_]*|_[\\da-fA-F][\\da-fA-F_]*)'; + const hexadecimal_integer_re = '0[xX]' + hexadecimal_digits_re; + + const decimal_exponent_re = '([eE][+-]?' + decimal_integer_nosus_re + ')'; + const decimal_float_re = '(' + decimal_integer_nosus_re + '(\\.\\d*|' + decimal_exponent_re + ')|' + + '\\d+\\.' + decimal_integer_nosus_re + '|' + + '\\.' + decimal_integer_re + decimal_exponent_re + '?' + + ')'; + const hexadecimal_float_re = '(0[xX](' + + hexadecimal_digits_re + '\\.' + hexadecimal_digits_re + '|' + + '\\.?' + hexadecimal_digits_re + + ')[pP][+-]?' + decimal_integer_nosus_re + ')'; + + const integer_re = '(' + + decimal_integer_re + '|' + + binary_integer_re + '|' + + hexadecimal_integer_re + + ')'; + + const float_re = '(' + + hexadecimal_float_re + '|' + + decimal_float_re + + ')'; + + /** + * Escape sequence supported in D string and character literals + * + * @type {String} + */ + const escape_sequence_re = '\\\\(' + + '[\'"\\?\\\\abfnrtv]|' + // common escapes + 'u[\\dA-Fa-f]{4}|' + // four hex digit unicode codepoint + '[0-7]{1,3}|' + // one to three octal digit ascii char code + 'x[\\dA-Fa-f]{2}|' + // two hex digit ascii char code + 'U[\\dA-Fa-f]{8}' + // eight hex digit unicode codepoint + ')|' + + '&[a-zA-Z\\d]{2,};'; // named character entity + + /** + * D integer number literals + * + * @type {Object} + */ + const D_INTEGER_MODE = { + className: 'number', + begin: '\\b' + integer_re + '(L|u|U|Lu|LU|uL|UL)?', + relevance: 0 + }; + + /** + * [D_FLOAT_MODE description] + * @type {Object} + */ + const D_FLOAT_MODE = { + className: 'number', + begin: '\\b(' + + float_re + '([fF]|L|i|[fF]i|Li)?|' + + integer_re + '(i|[fF]i|Li)' + + ')', + relevance: 0 + }; + + /** + * D character literal + * + * @type {Object} + */ + const D_CHARACTER_MODE = { + className: 'string', + begin: '\'(' + escape_sequence_re + '|.)', + end: '\'', + illegal: '.' + }; + + /** + * D string escape sequence + * + * @type {Object} + */ + const D_ESCAPE_SEQUENCE = { + begin: escape_sequence_re, + relevance: 0 + }; + + /** + * D double quoted string literal + * + * @type {Object} + */ + const D_STRING_MODE = { + className: 'string', + begin: '"', + contains: [D_ESCAPE_SEQUENCE], + end: '"[cwd]?' + }; + + /** + * D wysiwyg and delimited string literals + * + * @type {Object} + */ + const D_WYSIWYG_DELIMITED_STRING_MODE = { + className: 'string', + begin: '[rq]"', + end: '"[cwd]?', + relevance: 5 + }; + + /** + * D alternate wysiwyg string literal + * + * @type {Object} + */ + const D_ALTERNATE_WYSIWYG_STRING_MODE = { + className: 'string', + begin: '`', + end: '`[cwd]?' + }; + + /** + * D hexadecimal string literal + * + * @type {Object} + */ + const D_HEX_STRING_MODE = { + className: 'string', + begin: 'x"[\\da-fA-F\\s\\n\\r]*"[cwd]?', + relevance: 10 + }; + + /** + * D delimited string literal + * + * @type {Object} + */ + const D_TOKEN_STRING_MODE = { + className: 'string', + begin: 'q"\\{', + end: '\\}"' + }; + + /** + * Hashbang support + * + * @type {Object} + */ + const D_HASHBANG_MODE = { + className: 'meta', + begin: '^#!', + end: '$', + relevance: 5 + }; + + /** + * D special token sequence + * + * @type {Object} + */ + const D_SPECIAL_TOKEN_SEQUENCE_MODE = { + className: 'meta', + begin: '#(line)', + end: '$', + relevance: 5 + }; + + /** + * D attributes + * + * @type {Object} + */ + const D_ATTRIBUTE_MODE = { + className: 'keyword', + begin: '@[a-zA-Z_][a-zA-Z_\\d]*' + }; + + /** + * D nesting comment + * + * @type {Object} + */ + const D_NESTING_COMMENT_MODE = hljs.COMMENT( + '\\/\\+', + '\\+\\/', + { + contains: ['self'], + relevance: 10 + } + ); + + return { + name: 'D', + keywords: D_KEYWORDS, + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + D_NESTING_COMMENT_MODE, + D_HEX_STRING_MODE, + D_STRING_MODE, + D_WYSIWYG_DELIMITED_STRING_MODE, + D_ALTERNATE_WYSIWYG_STRING_MODE, + D_TOKEN_STRING_MODE, + D_FLOAT_MODE, + D_INTEGER_MODE, + D_CHARACTER_MODE, + D_HASHBANG_MODE, + D_SPECIAL_TOKEN_SEQUENCE_MODE, + D_ATTRIBUTE_MODE + ] + }; +} + +module.exports = d; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/dart.js b/claude-code-source/node_modules/highlight.js/lib/languages/dart.js new file mode 100644 index 00000000..e8961c89 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/dart.js @@ -0,0 +1,199 @@ +/* +Language: Dart +Requires: markdown.js +Author: Maxim Dikun +Description: Dart a modern, object-oriented language developed by Google. For more information see https://www.dartlang.org/ +Website: https://dart.dev +Category: scripting +*/ + +/** @type LanguageFn */ +function dart(hljs) { + const SUBST = { + className: 'subst', + variants: [{ + begin: '\\$[A-Za-z0-9_]+' + }] + }; + + const BRACED_SUBST = { + className: 'subst', + variants: [{ + begin: /\$\{/, + end: /\}/ + }], + keywords: 'true false null this is new super' + }; + + const STRING = { + className: 'string', + variants: [ + { + begin: 'r\'\'\'', + end: '\'\'\'' + }, + { + begin: 'r"""', + end: '"""' + }, + { + begin: 'r\'', + end: '\'', + illegal: '\\n' + }, + { + begin: 'r"', + end: '"', + illegal: '\\n' + }, + { + begin: '\'\'\'', + end: '\'\'\'', + contains: [ + hljs.BACKSLASH_ESCAPE, + SUBST, + BRACED_SUBST + ] + }, + { + begin: '"""', + end: '"""', + contains: [ + hljs.BACKSLASH_ESCAPE, + SUBST, + BRACED_SUBST + ] + }, + { + begin: '\'', + end: '\'', + illegal: '\\n', + contains: [ + hljs.BACKSLASH_ESCAPE, + SUBST, + BRACED_SUBST + ] + }, + { + begin: '"', + end: '"', + illegal: '\\n', + contains: [ + hljs.BACKSLASH_ESCAPE, + SUBST, + BRACED_SUBST + ] + } + ] + }; + BRACED_SUBST.contains = [ + hljs.C_NUMBER_MODE, + STRING + ]; + + const BUILT_IN_TYPES = [ + // dart:core + 'Comparable', + 'DateTime', + 'Duration', + 'Function', + 'Iterable', + 'Iterator', + 'List', + 'Map', + 'Match', + 'Object', + 'Pattern', + 'RegExp', + 'Set', + 'Stopwatch', + 'String', + 'StringBuffer', + 'StringSink', + 'Symbol', + 'Type', + 'Uri', + 'bool', + 'double', + 'int', + 'num', + // dart:html + 'Element', + 'ElementList' + ]; + const NULLABLE_BUILT_IN_TYPES = BUILT_IN_TYPES.map((e) => `${e}?`); + + const KEYWORDS = { + keyword: 'abstract as assert async await break case catch class const continue covariant default deferred do ' + + 'dynamic else enum export extends extension external factory false final finally for Function get hide if ' + + 'implements import in inferface is late library mixin new null on operator part required rethrow return set ' + + 'show static super switch sync this throw true try typedef var void while with yield', + built_in: + BUILT_IN_TYPES + .concat(NULLABLE_BUILT_IN_TYPES) + .concat([ + // dart:core + 'Never', + 'Null', + 'dynamic', + 'print', + // dart:html + 'document', + 'querySelector', + 'querySelectorAll', + 'window' + ]), + $pattern: /[A-Za-z][A-Za-z0-9_]*\??/ + }; + + return { + name: 'Dart', + keywords: KEYWORDS, + contains: [ + STRING, + hljs.COMMENT( + /\/\*\*(?!\/)/, + /\*\//, + { + subLanguage: 'markdown', + relevance: 0 + } + ), + hljs.COMMENT( + /\/{3,} ?/, + /$/, { + contains: [{ + subLanguage: 'markdown', + begin: '.', + end: '$', + relevance: 0 + }] + } + ), + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + { + className: 'class', + beginKeywords: 'class interface', + end: /\{/, + excludeEnd: true, + contains: [ + { + beginKeywords: 'extends implements' + }, + hljs.UNDERSCORE_TITLE_MODE + ] + }, + hljs.C_NUMBER_MODE, + { + className: 'meta', + begin: '@[A-Za-z]+' + }, + { + begin: '=>' // No markup, just a relevance booster + } + ] + }; +} + +module.exports = dart; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/delphi.js b/claude-code-source/node_modules/highlight.js/lib/languages/delphi.js new file mode 100644 index 00000000..668b11bc --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/delphi.js @@ -0,0 +1,126 @@ +/* +Language: Delphi +Website: https://www.embarcadero.com/products/delphi +*/ + +/** @type LanguageFn */ +function delphi(hljs) { + const KEYWORDS = + 'exports register file shl array record property for mod while set ally label uses raise not ' + + 'stored class safecall var interface or private static exit index inherited to else stdcall ' + + 'override shr asm far resourcestring finalization packed virtual out and protected library do ' + + 'xorwrite goto near function end div overload object unit begin string on inline repeat until ' + + 'destructor write message program with read initialization except default nil if case cdecl in ' + + 'downto threadvar of try pascal const external constructor type public then implementation ' + + 'finally published procedure absolute reintroduce operator as is abstract alias assembler ' + + 'bitpacked break continue cppdecl cvar enumerator experimental platform deprecated ' + + 'unimplemented dynamic export far16 forward generic helper implements interrupt iochecks ' + + 'local name nodefault noreturn nostackframe oldfpccall otherwise saveregisters softfloat ' + + 'specialize strict unaligned varargs '; + const COMMENT_MODES = [ + hljs.C_LINE_COMMENT_MODE, + hljs.COMMENT(/\{/, /\}/, { + relevance: 0 + }), + hljs.COMMENT(/\(\*/, /\*\)/, { + relevance: 10 + }) + ]; + const DIRECTIVE = { + className: 'meta', + variants: [ + { + begin: /\{\$/, + end: /\}/ + }, + { + begin: /\(\*\$/, + end: /\*\)/ + } + ] + }; + const STRING = { + className: 'string', + begin: /'/, + end: /'/, + contains: [{ + begin: /''/ + }] + }; + const NUMBER = { + className: 'number', + relevance: 0, + // Source: https://www.freepascal.org/docs-html/ref/refse6.html + variants: [ + { + // Hexadecimal notation, e.g., $7F. + begin: '\\$[0-9A-Fa-f]+' + }, + { + // Octal notation, e.g., &42. + begin: '&[0-7]+' + }, + { + // Binary notation, e.g., %1010. + begin: '%[01]+' + } + ] + }; + const CHAR_STRING = { + className: 'string', + begin: /(#\d+)+/ + }; + const CLASS = { + begin: hljs.IDENT_RE + '\\s*=\\s*class\\s*\\(', + returnBegin: true, + contains: [hljs.TITLE_MODE] + }; + const FUNCTION = { + className: 'function', + beginKeywords: 'function constructor destructor procedure', + end: /[:;]/, + keywords: 'function constructor|10 destructor|10 procedure|10', + contains: [ + hljs.TITLE_MODE, + { + className: 'params', + begin: /\(/, + end: /\)/, + keywords: KEYWORDS, + contains: [ + STRING, + CHAR_STRING, + DIRECTIVE + ].concat(COMMENT_MODES) + }, + DIRECTIVE + ].concat(COMMENT_MODES) + }; + return { + name: 'Delphi', + aliases: [ + 'dpr', + 'dfm', + 'pas', + 'pascal', + 'freepascal', + 'lazarus', + 'lpr', + 'lfm' + ], + case_insensitive: true, + keywords: KEYWORDS, + illegal: /"|\$[G-Zg-z]|\/\*|<\/|\|/, + contains: [ + STRING, + CHAR_STRING, + hljs.NUMBER_MODE, + NUMBER, + CLASS, + FUNCTION, + DIRECTIVE + ].concat(COMMENT_MODES) + }; +} + +module.exports = delphi; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/diff.js b/claude-code-source/node_modules/highlight.js/lib/languages/diff.js new file mode 100644 index 00000000..db2feb8f --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/diff.js @@ -0,0 +1,85 @@ +/* +Language: Diff +Description: Unified and context diff +Author: Vasily Polovnyov +Website: https://www.gnu.org/software/diffutils/ +Category: common +*/ + +/** @type LanguageFn */ +function diff(hljs) { + return { + name: 'Diff', + aliases: ['patch'], + contains: [ + { + className: 'meta', + relevance: 10, + variants: [ + { + begin: /^@@ +-\d+,\d+ +\+\d+,\d+ +@@/ + }, + { + begin: /^\*\*\* +\d+,\d+ +\*\*\*\*$/ + }, + { + begin: /^--- +\d+,\d+ +----$/ + } + ] + }, + { + className: 'comment', + variants: [ + { + begin: /Index: /, + end: /$/ + }, + { + begin: /^index/, + end: /$/ + }, + { + begin: /={3,}/, + end: /$/ + }, + { + begin: /^-{3}/, + end: /$/ + }, + { + begin: /^\*{3} /, + end: /$/ + }, + { + begin: /^\+{3}/, + end: /$/ + }, + { + begin: /^\*{15}$/ + }, + { + begin: /^diff --git/, + end: /$/ + } + ] + }, + { + className: 'addition', + begin: /^\+/, + end: /$/ + }, + { + className: 'deletion', + begin: /^-/, + end: /$/ + }, + { + className: 'addition', + begin: /^!/, + end: /$/ + } + ] + }; +} + +module.exports = diff; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/django.js b/claude-code-source/node_modules/highlight.js/lib/languages/django.js new file mode 100644 index 00000000..4826c0f7 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/django.js @@ -0,0 +1,77 @@ +/* +Language: Django +Description: Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. +Requires: xml.js +Author: Ivan Sagalaev +Contributors: Ilya Baryshev +Website: https://www.djangoproject.com +Category: template +*/ + +/** @type LanguageFn */ +function django(hljs) { + const FILTER = { + begin: /\|[A-Za-z]+:?/, + keywords: { + name: + 'truncatewords removetags linebreaksbr yesno get_digit timesince random striptags ' + + 'filesizeformat escape linebreaks length_is ljust rjust cut urlize fix_ampersands ' + + 'title floatformat capfirst pprint divisibleby add make_list unordered_list urlencode ' + + 'timeuntil urlizetrunc wordcount stringformat linenumbers slice date dictsort ' + + 'dictsortreversed default_if_none pluralize lower join center default ' + + 'truncatewords_html upper length phone2numeric wordwrap time addslashes slugify first ' + + 'escapejs force_escape iriencode last safe safeseq truncatechars localize unlocalize ' + + 'localtime utc timezone' + }, + contains: [ + hljs.QUOTE_STRING_MODE, + hljs.APOS_STRING_MODE + ] + }; + + return { + name: 'Django', + aliases: ['jinja'], + case_insensitive: true, + subLanguage: 'xml', + contains: [ + hljs.COMMENT(/\{%\s*comment\s*%\}/, /\{%\s*endcomment\s*%\}/), + hljs.COMMENT(/\{#/, /#\}/), + { + className: 'template-tag', + begin: /\{%/, + end: /%\}/, + contains: [{ + className: 'name', + begin: /\w+/, + keywords: { + name: + 'comment endcomment load templatetag ifchanged endifchanged if endif firstof for ' + + 'endfor ifnotequal endifnotequal widthratio extends include spaceless ' + + 'endspaceless regroup ifequal endifequal ssi now with cycle url filter ' + + 'endfilter debug block endblock else autoescape endautoescape csrf_token empty elif ' + + 'endwith static trans blocktrans endblocktrans get_static_prefix get_media_prefix ' + + 'plural get_current_language language get_available_languages ' + + 'get_current_language_bidi get_language_info get_language_info_list localize ' + + 'endlocalize localtime endlocaltime timezone endtimezone get_current_timezone ' + + 'verbatim' + }, + starts: { + endsWithParent: true, + keywords: 'in by as', + contains: [FILTER], + relevance: 0 + } + }] + }, + { + className: 'template-variable', + begin: /\{\{/, + end: /\}\}/, + contains: [FILTER] + } + ] + }; +} + +module.exports = django; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/dns.js b/claude-code-source/node_modules/highlight.js/lib/languages/dns.js new file mode 100644 index 00000000..0c3f4b6d --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/dns.js @@ -0,0 +1,46 @@ +/* +Language: DNS Zone +Author: Tim Schumacher +Category: config +Website: https://en.wikipedia.org/wiki/Zone_file +*/ + +/** @type LanguageFn */ +function dns(hljs) { + return { + name: 'DNS Zone', + aliases: [ + 'bind', + 'zone' + ], + keywords: { + keyword: + 'IN A AAAA AFSDB APL CAA CDNSKEY CDS CERT CNAME DHCID DLV DNAME DNSKEY DS HIP IPSECKEY KEY KX ' + + 'LOC MX NAPTR NS NSEC NSEC3 NSEC3PARAM PTR RRSIG RP SIG SOA SRV SSHFP TA TKEY TLSA TSIG TXT' + }, + contains: [ + hljs.COMMENT(';', '$', { + relevance: 0 + }), + { + className: 'meta', + begin: /^\$(TTL|GENERATE|INCLUDE|ORIGIN)\b/ + }, + // IPv6 + { + className: 'number', + begin: '((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))\\b' + }, + // IPv4 + { + className: 'number', + begin: '((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\b' + }, + hljs.inherit(hljs.NUMBER_MODE, { + begin: /\b\d+[dhwm]?/ + }) + ] + }; +} + +module.exports = dns; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/dockerfile.js b/claude-code-source/node_modules/highlight.js/lib/languages/dockerfile.js new file mode 100644 index 00000000..73405bff --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/dockerfile.js @@ -0,0 +1,34 @@ +/* +Language: Dockerfile +Requires: bash.js +Author: Alexis Hénaut +Description: language definition for Dockerfile files +Website: https://docs.docker.com/engine/reference/builder/ +Category: config +*/ + +/** @type LanguageFn */ +function dockerfile(hljs) { + return { + name: 'Dockerfile', + aliases: ['docker'], + case_insensitive: true, + keywords: 'from maintainer expose env arg user onbuild stopsignal', + contains: [ + hljs.HASH_COMMENT_MODE, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + hljs.NUMBER_MODE, + { + beginKeywords: 'run cmd entrypoint volume add copy workdir label healthcheck shell', + starts: { + end: /[^\\]$/, + subLanguage: 'bash' + } + } + ], + illegal: ' +Contributors: Anton Kochkov +Website: https://en.wikipedia.org/wiki/Batch_file +*/ + +/** @type LanguageFn */ +function dos(hljs) { + const COMMENT = hljs.COMMENT( + /^\s*@?rem\b/, /$/, + { + relevance: 10 + } + ); + const LABEL = { + className: 'symbol', + begin: '^\\s*[A-Za-z._?][A-Za-z0-9_$#@~.?]*(:|\\s+label)', + relevance: 0 + }; + return { + name: 'Batch file (DOS)', + aliases: [ + 'bat', + 'cmd' + ], + case_insensitive: true, + illegal: /\/\*/, + keywords: { + keyword: + 'if else goto for in do call exit not exist errorlevel defined ' + + 'equ neq lss leq gtr geq', + built_in: + 'prn nul lpt3 lpt2 lpt1 con com4 com3 com2 com1 aux ' + + 'shift cd dir echo setlocal endlocal set pause copy ' + + 'append assoc at attrib break cacls cd chcp chdir chkdsk chkntfs cls cmd color ' + + 'comp compact convert date dir diskcomp diskcopy doskey erase fs ' + + 'find findstr format ftype graftabl help keyb label md mkdir mode more move path ' + + 'pause print popd pushd promt rd recover rem rename replace restore rmdir shift ' + + 'sort start subst time title tree type ver verify vol ' + + // winutils + 'ping net ipconfig taskkill xcopy ren del' + }, + contains: [ + { + className: 'variable', + begin: /%%[^ ]|%[^ ]+?%|![^ ]+?!/ + }, + { + className: 'function', + begin: LABEL.begin, + end: 'goto:eof', + contains: [ + hljs.inherit(hljs.TITLE_MODE, { + begin: '([_a-zA-Z]\\w*\\.)*([_a-zA-Z]\\w*:)?[_a-zA-Z]\\w*' + }), + COMMENT + ] + }, + { + className: 'number', + begin: '\\b\\d+', + relevance: 0 + }, + COMMENT + ] + }; +} + +module.exports = dos; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/dsconfig.js b/claude-code-source/node_modules/highlight.js/lib/languages/dsconfig.js new file mode 100644 index 00000000..b51d2e7d --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/dsconfig.js @@ -0,0 +1,66 @@ +/* + Language: dsconfig + Description: dsconfig batch configuration language for LDAP directory servers + Contributors: Jacob Childress + Category: enterprise, config + */ + + /** @type LanguageFn */ +function dsconfig(hljs) { + const QUOTED_PROPERTY = { + className: 'string', + begin: /"/, + end: /"/ + }; + const APOS_PROPERTY = { + className: 'string', + begin: /'/, + end: /'/ + }; + const UNQUOTED_PROPERTY = { + className: 'string', + begin: /[\w\-?]+:\w+/, + end: /\W/, + relevance: 0 + }; + const VALUELESS_PROPERTY = { + className: 'string', + begin: /\w+(\-\w+)*/, + end: /(?=\W)/, + relevance: 0 + }; + + return { + keywords: 'dsconfig', + contains: [ + { + className: 'keyword', + begin: '^dsconfig', + end: /\s/, + excludeEnd: true, + relevance: 10 + }, + { + className: 'built_in', + begin: /(list|create|get|set|delete)-(\w+)/, + end: /\s/, + excludeEnd: true, + illegal: '!@#$%^&*()', + relevance: 10 + }, + { + className: 'built_in', + begin: /--(\w+)/, + end: /\s/, + excludeEnd: true + }, + QUOTED_PROPERTY, + APOS_PROPERTY, + UNQUOTED_PROPERTY, + VALUELESS_PROPERTY, + hljs.HASH_COMMENT_MODE + ] + }; +} + +module.exports = dsconfig; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/dts.js b/claude-code-source/node_modules/highlight.js/lib/languages/dts.js new file mode 100644 index 00000000..fc1a46e2 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/dts.js @@ -0,0 +1,153 @@ +/* +Language: Device Tree +Description: *.dts files used in the Linux kernel +Author: Martin Braun , Moritz Fischer +Website: https://elinux.org/Device_Tree_Reference +Category: config +*/ + +/** @type LanguageFn */ +function dts(hljs) { + const STRINGS = { + className: 'string', + variants: [ + hljs.inherit(hljs.QUOTE_STRING_MODE, { + begin: '((u8?|U)|L)?"' + }), + { + begin: '(u8?|U)?R"', + end: '"', + contains: [hljs.BACKSLASH_ESCAPE] + }, + { + begin: '\'\\\\?.', + end: '\'', + illegal: '.' + } + ] + }; + + const NUMBERS = { + className: 'number', + variants: [ + { + begin: '\\b(\\d+(\\.\\d*)?|\\.\\d+)(u|U|l|L|ul|UL|f|F)' + }, + { + begin: hljs.C_NUMBER_RE + } + ], + relevance: 0 + }; + + const PREPROCESSOR = { + className: 'meta', + begin: '#', + end: '$', + keywords: { + 'meta-keyword': 'if else elif endif define undef ifdef ifndef' + }, + contains: [ + { + begin: /\\\n/, + relevance: 0 + }, + { + beginKeywords: 'include', + end: '$', + keywords: { + 'meta-keyword': 'include' + }, + contains: [ + hljs.inherit(STRINGS, { + className: 'meta-string' + }), + { + className: 'meta-string', + begin: '<', + end: '>', + illegal: '\\n' + } + ] + }, + STRINGS, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE + ] + }; + + const DTS_REFERENCE = { + className: 'variable', + begin: /&[a-z\d_]*\b/ + }; + + const DTS_KEYWORD = { + className: 'meta-keyword', + begin: '/[a-z][a-z\\d-]*/' + }; + + const DTS_LABEL = { + className: 'symbol', + begin: '^\\s*[a-zA-Z_][a-zA-Z\\d_]*:' + }; + + const DTS_CELL_PROPERTY = { + className: 'params', + begin: '<', + end: '>', + contains: [ + NUMBERS, + DTS_REFERENCE + ] + }; + + const DTS_NODE = { + className: 'class', + begin: /[a-zA-Z_][a-zA-Z\d_@]*\s\{/, + end: /[{;=]/, + returnBegin: true, + excludeEnd: true + }; + + const DTS_ROOT_NODE = { + className: 'class', + begin: '/\\s*\\{', + end: /\};/, + relevance: 10, + contains: [ + DTS_REFERENCE, + DTS_KEYWORD, + DTS_LABEL, + DTS_NODE, + DTS_CELL_PROPERTY, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + NUMBERS, + STRINGS + ] + }; + + return { + name: 'Device Tree', + keywords: "", + contains: [ + DTS_ROOT_NODE, + DTS_REFERENCE, + DTS_KEYWORD, + DTS_LABEL, + DTS_NODE, + DTS_CELL_PROPERTY, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + NUMBERS, + STRINGS, + PREPROCESSOR, + { + begin: hljs.IDENT_RE + '::', + keywords: "" + } + ] + }; +} + +module.exports = dts; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/dust.js b/claude-code-source/node_modules/highlight.js/lib/languages/dust.js new file mode 100644 index 00000000..aa9d6da5 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/dust.js @@ -0,0 +1,45 @@ +/* +Language: Dust +Requires: xml.js +Author: Michael Allen +Description: Matcher for dust.js templates. +Website: https://www.dustjs.com +Category: template +*/ + +/** @type LanguageFn */ +function dust(hljs) { + const EXPRESSION_KEYWORDS = 'if eq ne lt lte gt gte select default math sep'; + return { + name: 'Dust', + aliases: ['dst'], + case_insensitive: true, + subLanguage: 'xml', + contains: [ + { + className: 'template-tag', + begin: /\{[#\/]/, + end: /\}/, + illegal: /;/, + contains: [{ + className: 'name', + begin: /[a-zA-Z\.-]+/, + starts: { + endsWithParent: true, + relevance: 0, + contains: [hljs.QUOTE_STRING_MODE] + } + }] + }, + { + className: 'template-variable', + begin: /\{/, + end: /\}/, + illegal: /;/, + keywords: EXPRESSION_KEYWORDS + } + ] + }; +} + +module.exports = dust; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/ebnf.js b/claude-code-source/node_modules/highlight.js/lib/languages/ebnf.js new file mode 100644 index 00000000..192ded7b --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/ebnf.js @@ -0,0 +1,53 @@ +/* +Language: Extended Backus-Naur Form +Author: Alex McKibben +Website: https://en.wikipedia.org/wiki/Extended_Backus–Naur_form +*/ + +/** @type LanguageFn */ +function ebnf(hljs) { + const commentMode = hljs.COMMENT(/\(\*/, /\*\)/); + + const nonTerminalMode = { + className: "attribute", + begin: /^[ ]*[a-zA-Z]+([\s_-]+[a-zA-Z]+)*/ + }; + + const specialSequenceMode = { + className: "meta", + begin: /\?.*\?/ + }; + + const ruleBodyMode = { + begin: /=/, + end: /[.;]/, + contains: [ + commentMode, + specialSequenceMode, + { + // terminals + className: 'string', + variants: [ + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + { + begin: '`', + end: '`' + } + ] + } + ] + }; + + return { + name: 'Extended Backus-Naur Form', + illegal: /\S/, + contains: [ + commentMode, + nonTerminalMode, + ruleBodyMode + ] + }; +} + +module.exports = ebnf; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/elixir.js b/claude-code-source/node_modules/highlight.js/lib/languages/elixir.js new file mode 100644 index 00000000..758e107b --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/elixir.js @@ -0,0 +1,259 @@ +/* +Language: Elixir +Author: Josh Adams +Description: language definition for Elixir source code files (.ex and .exs). Based on ruby language support. +Category: functional +Website: https://elixir-lang.org +*/ + +/** @type LanguageFn */ +function elixir(hljs) { + const ELIXIR_IDENT_RE = '[a-zA-Z_][a-zA-Z0-9_.]*(!|\\?)?'; + const ELIXIR_METHOD_RE = '[a-zA-Z_]\\w*[!?=]?|[-+~]@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?'; + const ELIXIR_KEYWORDS = { + $pattern: ELIXIR_IDENT_RE, + keyword: 'and false then defined module in return redo retry end for true self when ' + + 'next until do begin unless nil break not case cond alias while ensure or ' + + 'include use alias fn quote require import with|0' + }; + const SUBST = { + className: 'subst', + begin: /#\{/, + end: /\}/, + keywords: ELIXIR_KEYWORDS + }; + const NUMBER = { + className: 'number', + begin: '(\\b0o[0-7_]+)|(\\b0b[01_]+)|(\\b0x[0-9a-fA-F_]+)|(-?\\b[1-9][0-9_]*(\\.[0-9_]+([eE][-+]?[0-9]+)?)?)', + relevance: 0 + }; + const SIGIL_DELIMITERS = '[/|([{<"\']'; + const LOWERCASE_SIGIL = { + className: 'string', + begin: '~[a-z]' + '(?=' + SIGIL_DELIMITERS + ')', + contains: [ + { + endsParent: true, + contains: [ + { + contains: [ + hljs.BACKSLASH_ESCAPE, + SUBST + ], + variants: [ + { + begin: /"/, + end: /"/ + }, + { + begin: /'/, + end: /'/ + }, + { + begin: /\//, + end: /\// + }, + { + begin: /\|/, + end: /\|/ + }, + { + begin: /\(/, + end: /\)/ + }, + { + begin: /\[/, + end: /\]/ + }, + { + begin: /\{/, + end: /\}/ + }, + { + begin: // + } + ] + } + ] + } + ] + }; + + const UPCASE_SIGIL = { + className: 'string', + begin: '~[A-Z]' + '(?=' + SIGIL_DELIMITERS + ')', + contains: [ + { + begin: /"/, + end: /"/ + }, + { + begin: /'/, + end: /'/ + }, + { + begin: /\//, + end: /\// + }, + { + begin: /\|/, + end: /\|/ + }, + { + begin: /\(/, + end: /\)/ + }, + { + begin: /\[/, + end: /\]/ + }, + { + begin: /\{/, + end: /\}/ + }, + { + begin: // + } + ] + }; + + const STRING = { + className: 'string', + contains: [ + hljs.BACKSLASH_ESCAPE, + SUBST + ], + variants: [ + { + begin: /"""/, + end: /"""/ + }, + { + begin: /'''/, + end: /'''/ + }, + { + begin: /~S"""/, + end: /"""/, + contains: [] // override default + }, + { + begin: /~S"/, + end: /"/, + contains: [] // override default + }, + { + begin: /~S'''/, + end: /'''/, + contains: [] // override default + }, + { + begin: /~S'/, + end: /'/, + contains: [] // override default + }, + { + begin: /'/, + end: /'/ + }, + { + begin: /"/, + end: /"/ + } + ] + }; + const FUNCTION = { + className: 'function', + beginKeywords: 'def defp defmacro', + end: /\B\b/, // the mode is ended by the title + contains: [ + hljs.inherit(hljs.TITLE_MODE, { + begin: ELIXIR_IDENT_RE, + endsParent: true + }) + ] + }; + const CLASS = hljs.inherit(FUNCTION, { + className: 'class', + beginKeywords: 'defimpl defmodule defprotocol defrecord', + end: /\bdo\b|$|;/ + }); + const ELIXIR_DEFAULT_CONTAINS = [ + STRING, + UPCASE_SIGIL, + LOWERCASE_SIGIL, + hljs.HASH_COMMENT_MODE, + CLASS, + FUNCTION, + { + begin: '::' + }, + { + className: 'symbol', + begin: ':(?![\\s:])', + contains: [ + STRING, + { + begin: ELIXIR_METHOD_RE + } + ], + relevance: 0 + }, + { + className: 'symbol', + begin: ELIXIR_IDENT_RE + ':(?!:)', + relevance: 0 + }, + NUMBER, + { + className: 'variable', + begin: '(\\$\\W)|((\\$|@@?)(\\w+))' + }, + { + begin: '->' + }, + { // regexp container + begin: '(' + hljs.RE_STARTERS_RE + ')\\s*', + contains: [ + hljs.HASH_COMMENT_MODE, + { + // to prevent false regex triggers for the division function: + // /: + begin: /\/: (?=\d+\s*[,\]])/, + relevance: 0, + contains: [NUMBER] + }, + { + className: 'regexp', + illegal: '\\n', + contains: [ + hljs.BACKSLASH_ESCAPE, + SUBST + ], + variants: [ + { + begin: '/', + end: '/[a-z]*' + }, + { + begin: '%r\\[', + end: '\\][a-z]*' + } + ] + } + ], + relevance: 0 + } + ]; + SUBST.contains = ELIXIR_DEFAULT_CONTAINS; + + return { + name: 'Elixir', + keywords: ELIXIR_KEYWORDS, + contains: ELIXIR_DEFAULT_CONTAINS + }; +} + +module.exports = elixir; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/elm.js b/claude-code-source/node_modules/highlight.js/lib/languages/elm.js new file mode 100644 index 00000000..d986f7c4 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/elm.js @@ -0,0 +1,129 @@ +/* +Language: Elm +Author: Janis Voigtlaender +Website: https://elm-lang.org +Category: functional +*/ + +/** @type LanguageFn */ +function elm(hljs) { + const COMMENT = { + variants: [ + hljs.COMMENT('--', '$'), + hljs.COMMENT( + /\{-/, + /-\}/, + { + contains: ['self'] + } + ) + ] + }; + + const CONSTRUCTOR = { + className: 'type', + begin: '\\b[A-Z][\\w\']*', // TODO: other constructors (built-in, infix). + relevance: 0 + }; + + const LIST = { + begin: '\\(', + end: '\\)', + illegal: '"', + contains: [ + { + className: 'type', + begin: '\\b[A-Z][\\w]*(\\((\\.\\.|,|\\w+)\\))?' + }, + COMMENT + ] + }; + + const RECORD = { + begin: /\{/, + end: /\}/, + contains: LIST.contains + }; + + const CHARACTER = { + className: 'string', + begin: '\'\\\\?.', + end: '\'', + illegal: '.' + }; + + return { + name: 'Elm', + keywords: + 'let in if then else case of where module import exposing ' + + 'type alias as infix infixl infixr port effect command subscription', + contains: [ + + // Top-level constructions. + + { + beginKeywords: 'port effect module', + end: 'exposing', + keywords: 'port effect module where command subscription exposing', + contains: [ + LIST, + COMMENT + ], + illegal: '\\W\\.|;' + }, + { + begin: 'import', + end: '$', + keywords: 'import as exposing', + contains: [ + LIST, + COMMENT + ], + illegal: '\\W\\.|;' + }, + { + begin: 'type', + end: '$', + keywords: 'type alias', + contains: [ + CONSTRUCTOR, + LIST, + RECORD, + COMMENT + ] + }, + { + beginKeywords: 'infix infixl infixr', + end: '$', + contains: [ + hljs.C_NUMBER_MODE, + COMMENT + ] + }, + { + begin: 'port', + end: '$', + keywords: 'port', + contains: [COMMENT] + }, + + // Literals and names. + + CHARACTER, + hljs.QUOTE_STRING_MODE, + hljs.C_NUMBER_MODE, + CONSTRUCTOR, + hljs.inherit(hljs.TITLE_MODE, { + begin: '^[_a-z][\\w\']*' + }), + COMMENT, + + { + begin: '->|<-' + } // No markup, relevance booster + ], + illegal: /;/ + }; +} + +module.exports = elm; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/erb.js b/claude-code-source/node_modules/highlight.js/lib/languages/erb.js new file mode 100644 index 00000000..16649232 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/erb.js @@ -0,0 +1,29 @@ +/* +Language: ERB (Embedded Ruby) +Requires: xml.js, ruby.js +Author: Lucas Mazza +Contributors: Kassio Borges +Description: "Bridge" language defining fragments of Ruby in HTML within <% .. %> +Website: https://ruby-doc.org/stdlib-2.6.5/libdoc/erb/rdoc/ERB.html +Category: template +*/ + +/** @type LanguageFn */ +function erb(hljs) { + return { + name: 'ERB', + subLanguage: 'xml', + contains: [ + hljs.COMMENT('<%#', '%>'), + { + begin: '<%[%=-]?', + end: '[%-]?%>', + subLanguage: 'ruby', + excludeBegin: true, + excludeEnd: true + } + ] + }; +} + +module.exports = erb; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/erlang-repl.js b/claude-code-source/node_modules/highlight.js/lib/languages/erlang-repl.js new file mode 100644 index 00000000..17e153b6 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/erlang-repl.js @@ -0,0 +1,86 @@ +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/* +Language: Erlang REPL +Author: Sergey Ignatov +Website: https://www.erlang.org +Category: functional +*/ + +/** @type LanguageFn */ +function erlangRepl(hljs) { + return { + name: 'Erlang REPL', + keywords: { + built_in: + 'spawn spawn_link self', + keyword: + 'after and andalso|10 band begin bnot bor bsl bsr bxor case catch cond div end fun if ' + + 'let not of or orelse|10 query receive rem try when xor' + }, + contains: [ + { + className: 'meta', + begin: '^[0-9]+> ', + relevance: 10 + }, + hljs.COMMENT('%', '$'), + { + className: 'number', + begin: '\\b(\\d+(_\\d+)*#[a-fA-F0-9]+(_[a-fA-F0-9]+)*|\\d+(_\\d+)*(\\.\\d+(_\\d+)*)?([eE][-+]?\\d+)?)', + relevance: 0 + }, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + { + begin: concat( + /\?(::)?/, + /([A-Z]\w*)/, // at least one identifier + /((::)[A-Z]\w*)*/ // perhaps more + ) + }, + { + begin: '->' + }, + { + begin: 'ok' + }, + { + begin: '!' + }, + { + begin: '(\\b[a-z\'][a-zA-Z0-9_\']*:[a-z\'][a-zA-Z0-9_\']*)|(\\b[a-z\'][a-zA-Z0-9_\']*)', + relevance: 0 + }, + { + begin: '[A-Z][a-zA-Z0-9_\']*', + relevance: 0 + } + ] + }; +} + +module.exports = erlangRepl; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/erlang.js b/claude-code-source/node_modules/highlight.js/lib/languages/erlang.js new file mode 100644 index 00000000..52feb68c --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/erlang.js @@ -0,0 +1,199 @@ +/* +Language: Erlang +Description: Erlang is a general-purpose functional language, with strict evaluation, single assignment, and dynamic typing. +Author: Nikolay Zakharov , Dmitry Kovega +Website: https://www.erlang.org +Category: functional +*/ + +/** @type LanguageFn */ +function erlang(hljs) { + const BASIC_ATOM_RE = '[a-z\'][a-zA-Z0-9_\']*'; + const FUNCTION_NAME_RE = '(' + BASIC_ATOM_RE + ':' + BASIC_ATOM_RE + '|' + BASIC_ATOM_RE + ')'; + const ERLANG_RESERVED = { + keyword: + 'after and andalso|10 band begin bnot bor bsl bzr bxor case catch cond div end fun if ' + + 'let not of orelse|10 query receive rem try when xor', + literal: + 'false true' + }; + + const COMMENT = hljs.COMMENT('%', '$'); + const NUMBER = { + className: 'number', + begin: '\\b(\\d+(_\\d+)*#[a-fA-F0-9]+(_[a-fA-F0-9]+)*|\\d+(_\\d+)*(\\.\\d+(_\\d+)*)?([eE][-+]?\\d+)?)', + relevance: 0 + }; + const NAMED_FUN = { + begin: 'fun\\s+' + BASIC_ATOM_RE + '/\\d+' + }; + const FUNCTION_CALL = { + begin: FUNCTION_NAME_RE + '\\(', + end: '\\)', + returnBegin: true, + relevance: 0, + contains: [ + { + begin: FUNCTION_NAME_RE, + relevance: 0 + }, + { + begin: '\\(', + end: '\\)', + endsWithParent: true, + returnEnd: true, + relevance: 0 + // "contains" defined later + } + ] + }; + const TUPLE = { + begin: /\{/, + end: /\}/, + relevance: 0 + // "contains" defined later + }; + const VAR1 = { + begin: '\\b_([A-Z][A-Za-z0-9_]*)?', + relevance: 0 + }; + const VAR2 = { + begin: '[A-Z][a-zA-Z0-9_]*', + relevance: 0 + }; + const RECORD_ACCESS = { + begin: '#' + hljs.UNDERSCORE_IDENT_RE, + relevance: 0, + returnBegin: true, + contains: [ + { + begin: '#' + hljs.UNDERSCORE_IDENT_RE, + relevance: 0 + }, + { + begin: /\{/, + end: /\}/, + relevance: 0 + // "contains" defined later + } + ] + }; + + const BLOCK_STATEMENTS = { + beginKeywords: 'fun receive if try case', + end: 'end', + keywords: ERLANG_RESERVED + }; + BLOCK_STATEMENTS.contains = [ + COMMENT, + NAMED_FUN, + hljs.inherit(hljs.APOS_STRING_MODE, { + className: '' + }), + BLOCK_STATEMENTS, + FUNCTION_CALL, + hljs.QUOTE_STRING_MODE, + NUMBER, + TUPLE, + VAR1, + VAR2, + RECORD_ACCESS + ]; + + const BASIC_MODES = [ + COMMENT, + NAMED_FUN, + BLOCK_STATEMENTS, + FUNCTION_CALL, + hljs.QUOTE_STRING_MODE, + NUMBER, + TUPLE, + VAR1, + VAR2, + RECORD_ACCESS + ]; + FUNCTION_CALL.contains[1].contains = BASIC_MODES; + TUPLE.contains = BASIC_MODES; + RECORD_ACCESS.contains[1].contains = BASIC_MODES; + + const DIRECTIVES = [ + "-module", + "-record", + "-undef", + "-export", + "-ifdef", + "-ifndef", + "-author", + "-copyright", + "-doc", + "-vsn", + "-import", + "-include", + "-include_lib", + "-compile", + "-define", + "-else", + "-endif", + "-file", + "-behaviour", + "-behavior", + "-spec" + ]; + + const PARAMS = { + className: 'params', + begin: '\\(', + end: '\\)', + contains: BASIC_MODES + }; + return { + name: 'Erlang', + aliases: ['erl'], + keywords: ERLANG_RESERVED, + illegal: '(', + returnBegin: true, + illegal: '\\(|#|//|/\\*|\\\\|:|;', + contains: [ + PARAMS, + hljs.inherit(hljs.TITLE_MODE, { + begin: BASIC_ATOM_RE + }) + ], + starts: { + end: ';|\\.', + keywords: ERLANG_RESERVED, + contains: BASIC_MODES + } + }, + COMMENT, + { + begin: '^-', + end: '\\.', + relevance: 0, + excludeEnd: true, + returnBegin: true, + keywords: { + $pattern: '-' + hljs.IDENT_RE, + keyword: DIRECTIVES.map(x => `${x}|1.5`).join(" ") + }, + contains: [PARAMS] + }, + NUMBER, + hljs.QUOTE_STRING_MODE, + RECORD_ACCESS, + VAR1, + VAR2, + TUPLE, + { + begin: /\.$/ + } // relevance booster + ] + }; +} + +module.exports = erlang; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/excel.js b/claude-code-source/node_modules/highlight.js/lib/languages/excel.js new file mode 100644 index 00000000..4f20fbcf --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/excel.js @@ -0,0 +1,64 @@ +/* +Language: Excel formulae +Author: Victor Zhou +Description: Excel formulae +Website: https://products.office.com/en-us/excel/ +*/ + +/** @type LanguageFn */ +function excel(hljs) { + return { + name: 'Excel formulae', + aliases: [ + 'xlsx', + 'xls' + ], + case_insensitive: true, + // built-in functions imported from https://web.archive.org/web/20160513042710/https://support.office.com/en-us/article/Excel-functions-alphabetical-b3944572-255d-4efb-bb96-c6d90033e188 + keywords: { + $pattern: /[a-zA-Z][\w\.]*/, + built_in: 'ABS ACCRINT ACCRINTM ACOS ACOSH ACOT ACOTH AGGREGATE ADDRESS AMORDEGRC AMORLINC AND ARABIC AREAS ASC ASIN ASINH ATAN ATAN2 ATANH AVEDEV AVERAGE AVERAGEA AVERAGEIF AVERAGEIFS BAHTTEXT BASE BESSELI BESSELJ BESSELK BESSELY BETADIST BETA.DIST BETAINV BETA.INV BIN2DEC BIN2HEX BIN2OCT BINOMDIST BINOM.DIST BINOM.DIST.RANGE BINOM.INV BITAND BITLSHIFT BITOR BITRSHIFT BITXOR CALL CEILING CEILING.MATH CEILING.PRECISE CELL CHAR CHIDIST CHIINV CHITEST CHISQ.DIST CHISQ.DIST.RT CHISQ.INV CHISQ.INV.RT CHISQ.TEST CHOOSE CLEAN CODE COLUMN COLUMNS COMBIN COMBINA COMPLEX CONCAT CONCATENATE CONFIDENCE CONFIDENCE.NORM CONFIDENCE.T CONVERT CORREL COS COSH COT COTH COUNT COUNTA COUNTBLANK COUNTIF COUNTIFS COUPDAYBS COUPDAYS COUPDAYSNC COUPNCD COUPNUM COUPPCD COVAR COVARIANCE.P COVARIANCE.S CRITBINOM CSC CSCH CUBEKPIMEMBER CUBEMEMBER CUBEMEMBERPROPERTY CUBERANKEDMEMBER CUBESET CUBESETCOUNT CUBEVALUE CUMIPMT CUMPRINC DATE DATEDIF DATEVALUE DAVERAGE DAY DAYS DAYS360 DB DBCS DCOUNT DCOUNTA DDB DEC2BIN DEC2HEX DEC2OCT DECIMAL DEGREES DELTA DEVSQ DGET DISC DMAX DMIN DOLLAR DOLLARDE DOLLARFR DPRODUCT DSTDEV DSTDEVP DSUM DURATION DVAR DVARP EDATE EFFECT ENCODEURL EOMONTH ERF ERF.PRECISE ERFC ERFC.PRECISE ERROR.TYPE EUROCONVERT EVEN EXACT EXP EXPON.DIST EXPONDIST FACT FACTDOUBLE FALSE|0 F.DIST FDIST F.DIST.RT FILTERXML FIND FINDB F.INV F.INV.RT FINV FISHER FISHERINV FIXED FLOOR FLOOR.MATH FLOOR.PRECISE FORECAST FORECAST.ETS FORECAST.ETS.CONFINT FORECAST.ETS.SEASONALITY FORECAST.ETS.STAT FORECAST.LINEAR FORMULATEXT FREQUENCY F.TEST FTEST FV FVSCHEDULE GAMMA GAMMA.DIST GAMMADIST GAMMA.INV GAMMAINV GAMMALN GAMMALN.PRECISE GAUSS GCD GEOMEAN GESTEP GETPIVOTDATA GROWTH HARMEAN HEX2BIN HEX2DEC HEX2OCT HLOOKUP HOUR HYPERLINK HYPGEOM.DIST HYPGEOMDIST IF IFERROR IFNA IFS IMABS IMAGINARY IMARGUMENT IMCONJUGATE IMCOS IMCOSH IMCOT IMCSC IMCSCH IMDIV IMEXP IMLN IMLOG10 IMLOG2 IMPOWER IMPRODUCT IMREAL IMSEC IMSECH IMSIN IMSINH IMSQRT IMSUB IMSUM IMTAN INDEX INDIRECT INFO INT INTERCEPT INTRATE IPMT IRR ISBLANK ISERR ISERROR ISEVEN ISFORMULA ISLOGICAL ISNA ISNONTEXT ISNUMBER ISODD ISREF ISTEXT ISO.CEILING ISOWEEKNUM ISPMT JIS KURT LARGE LCM LEFT LEFTB LEN LENB LINEST LN LOG LOG10 LOGEST LOGINV LOGNORM.DIST LOGNORMDIST LOGNORM.INV LOOKUP LOWER MATCH MAX MAXA MAXIFS MDETERM MDURATION MEDIAN MID MIDBs MIN MINIFS MINA MINUTE MINVERSE MIRR MMULT MOD MODE MODE.MULT MODE.SNGL MONTH MROUND MULTINOMIAL MUNIT N NA NEGBINOM.DIST NEGBINOMDIST NETWORKDAYS NETWORKDAYS.INTL NOMINAL NORM.DIST NORMDIST NORMINV NORM.INV NORM.S.DIST NORMSDIST NORM.S.INV NORMSINV NOT NOW NPER NPV NUMBERVALUE OCT2BIN OCT2DEC OCT2HEX ODD ODDFPRICE ODDFYIELD ODDLPRICE ODDLYIELD OFFSET OR PDURATION PEARSON PERCENTILE.EXC PERCENTILE.INC PERCENTILE PERCENTRANK.EXC PERCENTRANK.INC PERCENTRANK PERMUT PERMUTATIONA PHI PHONETIC PI PMT POISSON.DIST POISSON POWER PPMT PRICE PRICEDISC PRICEMAT PROB PRODUCT PROPER PV QUARTILE QUARTILE.EXC QUARTILE.INC QUOTIENT RADIANS RAND RANDBETWEEN RANK.AVG RANK.EQ RANK RATE RECEIVED REGISTER.ID REPLACE REPLACEB REPT RIGHT RIGHTB ROMAN ROUND ROUNDDOWN ROUNDUP ROW ROWS RRI RSQ RTD SEARCH SEARCHB SEC SECH SECOND SERIESSUM SHEET SHEETS SIGN SIN SINH SKEW SKEW.P SLN SLOPE SMALL SQL.REQUEST SQRT SQRTPI STANDARDIZE STDEV STDEV.P STDEV.S STDEVA STDEVP STDEVPA STEYX SUBSTITUTE SUBTOTAL SUM SUMIF SUMIFS SUMPRODUCT SUMSQ SUMX2MY2 SUMX2PY2 SUMXMY2 SWITCH SYD T TAN TANH TBILLEQ TBILLPRICE TBILLYIELD T.DIST T.DIST.2T T.DIST.RT TDIST TEXT TEXTJOIN TIME TIMEVALUE T.INV T.INV.2T TINV TODAY TRANSPOSE TREND TRIM TRIMMEAN TRUE|0 TRUNC T.TEST TTEST TYPE UNICHAR UNICODE UPPER VALUE VAR VAR.P VAR.S VARA VARP VARPA VDB VLOOKUP WEBSERVICE WEEKDAY WEEKNUM WEIBULL WEIBULL.DIST WORKDAY WORKDAY.INTL XIRR XNPV XOR YEAR YEARFRAC YIELD YIELDDISC YIELDMAT Z.TEST ZTEST' + }, + contains: [ + { + /* matches a beginning equal sign found in Excel formula examples */ + begin: /^=/, + end: /[^=]/, + returnEnd: true, + illegal: /=/, /* only allow single equal sign at front of line */ + relevance: 10 + }, + /* technically, there can be more than 2 letters in column names, but this prevents conflict with some keywords */ + { + /* matches a reference to a single cell */ + className: 'symbol', + begin: /\b[A-Z]{1,2}\d+\b/, + end: /[^\d]/, + excludeEnd: true, + relevance: 0 + }, + { + /* matches a reference to a range of cells */ + className: 'symbol', + begin: /[A-Z]{0,2}\d*:[A-Z]{0,2}\d*/, + relevance: 0 + }, + hljs.BACKSLASH_ESCAPE, + hljs.QUOTE_STRING_MODE, + { + className: 'number', + begin: hljs.NUMBER_RE + '(%)?', + relevance: 0 + }, + /* Excel formula comments are done by putting the comment in a function call to N() */ + hljs.COMMENT(/\bN\(/, /\)/, + { + excludeBegin: true, + excludeEnd: true, + illegal: /\n/ + }) + ] + }; +} + +module.exports = excel; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/fix.js b/claude-code-source/node_modules/highlight.js/lib/languages/fix.js new file mode 100644 index 00000000..137015cf --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/fix.js @@ -0,0 +1,37 @@ +/* +Language: FIX +Author: Brent Bradbury +*/ + +/** @type LanguageFn */ +function fix(hljs) { + return { + name: 'FIX', + contains: [{ + begin: /[^\u2401\u0001]+/, + end: /[\u2401\u0001]/, + excludeEnd: true, + returnBegin: true, + returnEnd: false, + contains: [ + { + begin: /([^\u2401\u0001=]+)/, + end: /=([^\u2401\u0001=]+)/, + returnEnd: true, + returnBegin: false, + className: 'attr' + }, + { + begin: /=/, + end: /([\u2401\u0001])/, + excludeEnd: true, + excludeBegin: true, + className: 'string' + } + ] + }], + case_insensitive: true + }; +} + +module.exports = fix; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/flix.js b/claude-code-source/node_modules/highlight.js/lib/languages/flix.js new file mode 100644 index 00000000..cca423e5 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/flix.js @@ -0,0 +1,54 @@ +/* + Language: Flix + Category: functional + Author: Magnus Madsen + Website: https://flix.dev/ + */ + + /** @type LanguageFn */ +function flix(hljs) { + const CHAR = { + className: 'string', + begin: /'(.|\\[xXuU][a-zA-Z0-9]+)'/ + }; + + const STRING = { + className: 'string', + variants: [{ + begin: '"', + end: '"' + }] + }; + + const NAME = { + className: 'title', + relevance: 0, + begin: /[^0-9\n\t "'(),.`{}\[\]:;][^\n\t "'(),.`{}\[\]:;]+|[^0-9\n\t "'(),.`{}\[\]:;=]/ + }; + + const METHOD = { + className: 'function', + beginKeywords: 'def', + end: /[:={\[(\n;]/, + excludeEnd: true, + contains: [NAME] + }; + + return { + name: 'Flix', + keywords: { + literal: 'true false', + keyword: 'case class def else enum if impl import in lat rel index let match namespace switch type yield with' + }, + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + CHAR, + STRING, + METHOD, + hljs.C_NUMBER_MODE + ] + }; +} + +module.exports = flix; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/fortran.js b/claude-code-source/node_modules/highlight.js/lib/languages/fortran.js new file mode 100644 index 00000000..06adc645 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/fortran.js @@ -0,0 +1,159 @@ +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/* +Language: Fortran +Author: Anthony Scemama +Website: https://en.wikipedia.org/wiki/Fortran +Category: scientific +*/ + +/** @type LanguageFn */ +function fortran(hljs) { + const PARAMS = { + className: 'params', + begin: '\\(', + end: '\\)' + }; + + const COMMENT = { + variants: [ + hljs.COMMENT('!', '$', { + relevance: 0 + }), + // allow FORTRAN 77 style comments + hljs.COMMENT('^C[ ]', '$', { + relevance: 0 + }), + hljs.COMMENT('^C$', '$', { + relevance: 0 + }) + ] + }; + + // regex in both fortran and irpf90 should match + const OPTIONAL_NUMBER_SUFFIX = /(_[a-z_\d]+)?/; + const OPTIONAL_NUMBER_EXP = /([de][+-]?\d+)?/; + const NUMBER = { + className: 'number', + variants: [ + { + begin: concat(/\b\d+/, /\.(\d*)/, OPTIONAL_NUMBER_EXP, OPTIONAL_NUMBER_SUFFIX) + }, + { + begin: concat(/\b\d+/, OPTIONAL_NUMBER_EXP, OPTIONAL_NUMBER_SUFFIX) + }, + { + begin: concat(/\.\d+/, OPTIONAL_NUMBER_EXP, OPTIONAL_NUMBER_SUFFIX) + } + ], + relevance: 0 + }; + + const FUNCTION_DEF = { + className: 'function', + beginKeywords: 'subroutine function program', + illegal: '[${=\\n]', + contains: [ + hljs.UNDERSCORE_TITLE_MODE, + PARAMS + ] + }; + + const STRING = { + className: 'string', + relevance: 0, + variants: [ + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE + ] + }; + + const KEYWORDS = { + literal: '.False. .True.', + keyword: 'kind do concurrent local shared while private call intrinsic where elsewhere ' + + 'type endtype endmodule endselect endinterface end enddo endif if forall endforall only contains default return stop then block endblock endassociate ' + + 'public subroutine|10 function program .and. .or. .not. .le. .eq. .ge. .gt. .lt. ' + + 'goto save else use module select case ' + + 'access blank direct exist file fmt form formatted iostat name named nextrec number opened rec recl sequential status unformatted unit ' + + 'continue format pause cycle exit ' + + 'c_null_char c_alert c_backspace c_form_feed flush wait decimal round iomsg ' + + 'synchronous nopass non_overridable pass protected volatile abstract extends import ' + + 'non_intrinsic value deferred generic final enumerator class associate bind enum ' + + 'c_int c_short c_long c_long_long c_signed_char c_size_t c_int8_t c_int16_t c_int32_t c_int64_t c_int_least8_t c_int_least16_t ' + + 'c_int_least32_t c_int_least64_t c_int_fast8_t c_int_fast16_t c_int_fast32_t c_int_fast64_t c_intmax_t C_intptr_t c_float c_double ' + + 'c_long_double c_float_complex c_double_complex c_long_double_complex c_bool c_char c_null_ptr c_null_funptr ' + + 'c_new_line c_carriage_return c_horizontal_tab c_vertical_tab iso_c_binding c_loc c_funloc c_associated c_f_pointer ' + + 'c_ptr c_funptr iso_fortran_env character_storage_size error_unit file_storage_size input_unit iostat_end iostat_eor ' + + 'numeric_storage_size output_unit c_f_procpointer ieee_arithmetic ieee_support_underflow_control ' + + 'ieee_get_underflow_mode ieee_set_underflow_mode newunit contiguous recursive ' + + 'pad position action delim readwrite eor advance nml interface procedure namelist include sequence elemental pure impure ' + + 'integer real character complex logical codimension dimension allocatable|10 parameter ' + + 'external implicit|10 none double precision assign intent optional pointer ' + + 'target in out common equivalence data', + built_in: 'alog alog10 amax0 amax1 amin0 amin1 amod cabs ccos cexp clog csin csqrt dabs dacos dasin datan datan2 dcos dcosh ddim dexp dint ' + + 'dlog dlog10 dmax1 dmin1 dmod dnint dsign dsin dsinh dsqrt dtan dtanh float iabs idim idint idnint ifix isign max0 max1 min0 min1 sngl ' + + 'algama cdabs cdcos cdexp cdlog cdsin cdsqrt cqabs cqcos cqexp cqlog cqsin cqsqrt dcmplx dconjg derf derfc dfloat dgamma dimag dlgama ' + + 'iqint qabs qacos qasin qatan qatan2 qcmplx qconjg qcos qcosh qdim qerf qerfc qexp qgamma qimag qlgama qlog qlog10 qmax1 qmin1 qmod ' + + 'qnint qsign qsin qsinh qsqrt qtan qtanh abs acos aimag aint anint asin atan atan2 char cmplx conjg cos cosh exp ichar index int log ' + + 'log10 max min nint sign sin sinh sqrt tan tanh print write dim lge lgt lle llt mod nullify allocate deallocate ' + + 'adjustl adjustr all allocated any associated bit_size btest ceiling count cshift date_and_time digits dot_product ' + + 'eoshift epsilon exponent floor fraction huge iand ibclr ibits ibset ieor ior ishft ishftc lbound len_trim matmul ' + + 'maxexponent maxloc maxval merge minexponent minloc minval modulo mvbits nearest pack present product ' + + 'radix random_number random_seed range repeat reshape rrspacing scale scan selected_int_kind selected_real_kind ' + + 'set_exponent shape size spacing spread sum system_clock tiny transpose trim ubound unpack verify achar iachar transfer ' + + 'dble entry dprod cpu_time command_argument_count get_command get_command_argument get_environment_variable is_iostat_end ' + + 'ieee_arithmetic ieee_support_underflow_control ieee_get_underflow_mode ieee_set_underflow_mode ' + + 'is_iostat_eor move_alloc new_line selected_char_kind same_type_as extends_type_of ' + + 'acosh asinh atanh bessel_j0 bessel_j1 bessel_jn bessel_y0 bessel_y1 bessel_yn erf erfc erfc_scaled gamma log_gamma hypot norm2 ' + + 'atomic_define atomic_ref execute_command_line leadz trailz storage_size merge_bits ' + + 'bge bgt ble blt dshiftl dshiftr findloc iall iany iparity image_index lcobound ucobound maskl maskr ' + + 'num_images parity popcnt poppar shifta shiftl shiftr this_image sync change team co_broadcast co_max co_min co_sum co_reduce' + }; + return { + name: 'Fortran', + case_insensitive: true, + aliases: [ + 'f90', + 'f95' + ], + keywords: KEYWORDS, + illegal: /\/\*/, + contains: [ + STRING, + FUNCTION_DEF, + // allow `C = value` for assignments so they aren't misdetected + // as Fortran 77 style comments + { + begin: /^C\s*=(?!=)/, + relevance: 0 + }, + COMMENT, + NUMBER + ] + }; +} + +module.exports = fortran; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/fsharp.js b/claude-code-source/node_modules/highlight.js/lib/languages/fsharp.js new file mode 100644 index 00000000..89488a03 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/fsharp.js @@ -0,0 +1,86 @@ +/* +Language: F# +Author: Jonas Follesø +Contributors: Troy Kershaw , Henrik Feldt +Website: https://docs.microsoft.com/en-us/dotnet/fsharp/ +Category: functional +*/ + +/** @type LanguageFn */ +function fsharp(hljs) { + const TYPEPARAM = { + begin: '<', + end: '>', + contains: [ + hljs.inherit(hljs.TITLE_MODE, { + begin: /'[a-zA-Z0-9_]+/ + }) + ] + }; + + return { + name: 'F#', + aliases: ['fs'], + keywords: + 'abstract and as assert base begin class default delegate do done ' + + 'downcast downto elif else end exception extern false finally for ' + + 'fun function global if in inherit inline interface internal lazy let ' + + 'match member module mutable namespace new null of open or ' + + 'override private public rec return sig static struct then to ' + + 'true try type upcast use val void when while with yield', + illegal: /\/\*/, + contains: [ + { + // monad builder keywords (matches before non-bang kws) + className: 'keyword', + begin: /\b(yield|return|let|do)!/ + }, + { + className: 'string', + begin: '@"', + end: '"', + contains: [ + { + begin: '""' + } + ] + }, + { + className: 'string', + begin: '"""', + end: '"""' + }, + hljs.COMMENT('\\(\\*(\\s)', '\\*\\)', { + contains: ["self"] + }), + { + className: 'class', + beginKeywords: 'type', + end: '\\(|=|$', + excludeEnd: true, + contains: [ + hljs.UNDERSCORE_TITLE_MODE, + TYPEPARAM + ] + }, + { + className: 'meta', + begin: '\\[<', + end: '>\\]', + relevance: 10 + }, + { + className: 'symbol', + begin: '\\B(\'[A-Za-z])\\b', + contains: [hljs.BACKSLASH_ESCAPE] + }, + hljs.C_LINE_COMMENT_MODE, + hljs.inherit(hljs.QUOTE_STRING_MODE, { + illegal: null + }), + hljs.C_NUMBER_MODE + ] + }; +} + +module.exports = fsharp; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/gams.js b/claude-code-source/node_modules/highlight.js/lib/languages/gams.js new file mode 100644 index 00000000..5398fdc3 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/gams.js @@ -0,0 +1,208 @@ +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function anyNumberOfTimes(re) { + return concat('(', re, ')*'); +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/** @type LanguageFn */ +function gams(hljs) { + const KEYWORDS = { + keyword: + 'abort acronym acronyms alias all and assign binary card diag display ' + + 'else eq file files for free ge gt if integer le loop lt maximizing ' + + 'minimizing model models ne negative no not option options or ord ' + + 'positive prod put putpage puttl repeat sameas semicont semiint smax ' + + 'smin solve sos1 sos2 sum system table then until using while xor yes', + literal: + 'eps inf na', + built_in: + 'abs arccos arcsin arctan arctan2 Beta betaReg binomial ceil centropy ' + + 'cos cosh cvPower div div0 eDist entropy errorf execSeed exp fact ' + + 'floor frac gamma gammaReg log logBeta logGamma log10 log2 mapVal max ' + + 'min mod ncpCM ncpF ncpVUpow ncpVUsin normal pi poly power ' + + 'randBinomial randLinear randTriangle round rPower sigmoid sign ' + + 'signPower sin sinh slexp sllog10 slrec sqexp sqlog10 sqr sqrec sqrt ' + + 'tan tanh trunc uniform uniformInt vcPower bool_and bool_eqv bool_imp ' + + 'bool_not bool_or bool_xor ifThen rel_eq rel_ge rel_gt rel_le rel_lt ' + + 'rel_ne gday gdow ghour gleap gmillisec gminute gmonth gsecond gyear ' + + 'jdate jnow jstart jtime errorLevel execError gamsRelease gamsVersion ' + + 'handleCollect handleDelete handleStatus handleSubmit heapFree ' + + 'heapLimit heapSize jobHandle jobKill jobStatus jobTerminate ' + + 'licenseLevel licenseStatus maxExecError sleep timeClose timeComp ' + + 'timeElapsed timeExec timeStart' + }; + const PARAMS = { + className: 'params', + begin: /\(/, + end: /\)/, + excludeBegin: true, + excludeEnd: true + }; + const SYMBOLS = { + className: 'symbol', + variants: [ + { + begin: /=[lgenxc]=/ + }, + { + begin: /\$/ + } + ] + }; + const QSTR = { // One-line quoted comment string + className: 'comment', + variants: [ + { + begin: '\'', + end: '\'' + }, + { + begin: '"', + end: '"' + } + ], + illegal: '\\n', + contains: [hljs.BACKSLASH_ESCAPE] + }; + const ASSIGNMENT = { + begin: '/', + end: '/', + keywords: KEYWORDS, + contains: [ + QSTR, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.QUOTE_STRING_MODE, + hljs.APOS_STRING_MODE, + hljs.C_NUMBER_MODE + ] + }; + const COMMENT_WORD = /[a-z0-9&#*=?@\\><:,()$[\]_.{}!+%^-]+/; + const DESCTEXT = { // Parameter/set/variable description text + begin: /[a-z][a-z0-9_]*(\([a-z0-9_, ]*\))?[ \t]+/, + excludeBegin: true, + end: '$', + endsWithParent: true, + contains: [ + QSTR, + ASSIGNMENT, + { + className: 'comment', + // one comment word, then possibly more + begin: concat( + COMMENT_WORD, + // [ ] because \s would be too broad (matching newlines) + anyNumberOfTimes(concat(/[ ]+/, COMMENT_WORD)) + ), + relevance: 0 + } + ] + }; + + return { + name: 'GAMS', + aliases: ['gms'], + case_insensitive: true, + keywords: KEYWORDS, + contains: [ + hljs.COMMENT(/^\$ontext/, /^\$offtext/), + { + className: 'meta', + begin: '^\\$[a-z0-9]+', + end: '$', + returnBegin: true, + contains: [ + { + className: 'meta-keyword', + begin: '^\\$[a-z0-9]+' + } + ] + }, + hljs.COMMENT('^\\*', '$'), + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.QUOTE_STRING_MODE, + hljs.APOS_STRING_MODE, + // Declarations + { + beginKeywords: + 'set sets parameter parameters variable variables ' + + 'scalar scalars equation equations', + end: ';', + contains: [ + hljs.COMMENT('^\\*', '$'), + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.QUOTE_STRING_MODE, + hljs.APOS_STRING_MODE, + ASSIGNMENT, + DESCTEXT + ] + }, + { // table environment + beginKeywords: 'table', + end: ';', + returnBegin: true, + contains: [ + { // table header row + beginKeywords: 'table', + end: '$', + contains: [DESCTEXT] + }, + hljs.COMMENT('^\\*', '$'), + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.QUOTE_STRING_MODE, + hljs.APOS_STRING_MODE, + hljs.C_NUMBER_MODE + // Table does not contain DESCTEXT or ASSIGNMENT + ] + }, + // Function definitions + { + className: 'function', + begin: /^[a-z][a-z0-9_,\-+' ()$]+\.{2}/, + returnBegin: true, + contains: [ + { // Function title + className: 'title', + begin: /^[a-z0-9_]+/ + }, + PARAMS, + SYMBOLS + ] + }, + hljs.C_NUMBER_MODE, + SYMBOLS + ] + }; +} + +module.exports = gams; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/gauss.js b/claude-code-source/node_modules/highlight.js/lib/languages/gauss.js new file mode 100644 index 00000000..29254f00 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/gauss.js @@ -0,0 +1,316 @@ +/* +Language: GAUSS +Author: Matt Evans +Description: GAUSS Mathematical and Statistical language +Website: https://www.aptech.com +Category: scientific +*/ +function gauss(hljs) { + const KEYWORDS = { + keyword: 'bool break call callexe checkinterrupt clear clearg closeall cls comlog compile ' + + 'continue create debug declare delete disable dlibrary dllcall do dos ed edit else ' + + 'elseif enable end endfor endif endp endo errorlog errorlogat expr external fn ' + + 'for format goto gosub graph if keyword let lib library line load loadarray loadexe ' + + 'loadf loadk loadm loadp loads loadx local locate loopnextindex lprint lpwidth lshow ' + + 'matrix msym ndpclex new open output outwidth plot plotsym pop prcsn print ' + + 'printdos proc push retp return rndcon rndmod rndmult rndseed run save saveall screen ' + + 'scroll setarray show sparse stop string struct system trace trap threadfor ' + + 'threadendfor threadbegin threadjoin threadstat threadend until use while winprint ' + + 'ne ge le gt lt and xor or not eq eqv', + built_in: 'abs acf aconcat aeye amax amean AmericanBinomCall AmericanBinomCall_Greeks AmericanBinomCall_ImpVol ' + + 'AmericanBinomPut AmericanBinomPut_Greeks AmericanBinomPut_ImpVol AmericanBSCall AmericanBSCall_Greeks ' + + 'AmericanBSCall_ImpVol AmericanBSPut AmericanBSPut_Greeks AmericanBSPut_ImpVol amin amult annotationGetDefaults ' + + 'annotationSetBkd annotationSetFont annotationSetLineColor annotationSetLineStyle annotationSetLineThickness ' + + 'annualTradingDays arccos arcsin areshape arrayalloc arrayindex arrayinit arraytomat asciiload asclabel astd ' + + 'astds asum atan atan2 atranspose axmargin balance band bandchol bandcholsol bandltsol bandrv bandsolpd bar ' + + 'base10 begwind besselj bessely beta box boxcox cdfBeta cdfBetaInv cdfBinomial cdfBinomialInv cdfBvn cdfBvn2 ' + + 'cdfBvn2e cdfCauchy cdfCauchyInv cdfChic cdfChii cdfChinc cdfChincInv cdfExp cdfExpInv cdfFc cdfFnc cdfFncInv ' + + 'cdfGam cdfGenPareto cdfHyperGeo cdfLaplace cdfLaplaceInv cdfLogistic cdfLogisticInv cdfmControlCreate cdfMvn ' + + 'cdfMvn2e cdfMvnce cdfMvne cdfMvt2e cdfMvtce cdfMvte cdfN cdfN2 cdfNc cdfNegBinomial cdfNegBinomialInv cdfNi ' + + 'cdfPoisson cdfPoissonInv cdfRayleigh cdfRayleighInv cdfTc cdfTci cdfTnc cdfTvn cdfWeibull cdfWeibullInv cdir ' + + 'ceil ChangeDir chdir chiBarSquare chol choldn cholsol cholup chrs close code cols colsf combinate combinated ' + + 'complex con cond conj cons ConScore contour conv convertsatostr convertstrtosa corrm corrms corrvc corrx corrxs ' + + 'cos cosh counts countwts crossprd crout croutp csrcol csrlin csvReadM csvReadSA cumprodc cumsumc curve cvtos ' + + 'datacreate datacreatecomplex datalist dataload dataloop dataopen datasave date datestr datestring datestrymd ' + + 'dayinyr dayofweek dbAddDatabase dbClose dbCommit dbCreateQuery dbExecQuery dbGetConnectOptions dbGetDatabaseName ' + + 'dbGetDriverName dbGetDrivers dbGetHostName dbGetLastErrorNum dbGetLastErrorText dbGetNumericalPrecPolicy ' + + 'dbGetPassword dbGetPort dbGetTableHeaders dbGetTables dbGetUserName dbHasFeature dbIsDriverAvailable dbIsOpen ' + + 'dbIsOpenError dbOpen dbQueryBindValue dbQueryClear dbQueryCols dbQueryExecPrepared dbQueryFetchAllM dbQueryFetchAllSA ' + + 'dbQueryFetchOneM dbQueryFetchOneSA dbQueryFinish dbQueryGetBoundValue dbQueryGetBoundValues dbQueryGetField ' + + 'dbQueryGetLastErrorNum dbQueryGetLastErrorText dbQueryGetLastInsertID dbQueryGetLastQuery dbQueryGetPosition ' + + 'dbQueryIsActive dbQueryIsForwardOnly dbQueryIsNull dbQueryIsSelect dbQueryIsValid dbQueryPrepare dbQueryRows ' + + 'dbQuerySeek dbQuerySeekFirst dbQuerySeekLast dbQuerySeekNext dbQuerySeekPrevious dbQuerySetForwardOnly ' + + 'dbRemoveDatabase dbRollback dbSetConnectOptions dbSetDatabaseName dbSetHostName dbSetNumericalPrecPolicy ' + + 'dbSetPort dbSetUserName dbTransaction DeleteFile delif delrows denseToSp denseToSpRE denToZero design det detl ' + + 'dfft dffti diag diagrv digamma doswin DOSWinCloseall DOSWinOpen dotfeq dotfeqmt dotfge dotfgemt dotfgt dotfgtmt ' + + 'dotfle dotflemt dotflt dotfltmt dotfne dotfnemt draw drop dsCreate dstat dstatmt dstatmtControlCreate dtdate dtday ' + + 'dttime dttodtv dttostr dttoutc dtvnormal dtvtodt dtvtoutc dummy dummybr dummydn eig eigh eighv eigv elapsedTradingDays ' + + 'endwind envget eof eqSolve eqSolvemt eqSolvemtControlCreate eqSolvemtOutCreate eqSolveset erf erfc erfccplx erfcplx error ' + + 'etdays ethsec etstr EuropeanBinomCall EuropeanBinomCall_Greeks EuropeanBinomCall_ImpVol EuropeanBinomPut ' + + 'EuropeanBinomPut_Greeks EuropeanBinomPut_ImpVol EuropeanBSCall EuropeanBSCall_Greeks EuropeanBSCall_ImpVol ' + + 'EuropeanBSPut EuropeanBSPut_Greeks EuropeanBSPut_ImpVol exctsmpl exec execbg exp extern eye fcheckerr fclearerr feq ' + + 'feqmt fflush fft ffti fftm fftmi fftn fge fgemt fgets fgetsa fgetsat fgetst fgt fgtmt fileinfo filesa fle flemt ' + + 'floor flt fltmt fmod fne fnemt fonts fopen formatcv formatnv fputs fputst fseek fstrerror ftell ftocv ftos ftostrC ' + + 'gamma gammacplx gammaii gausset gdaAppend gdaCreate gdaDStat gdaDStatMat gdaGetIndex gdaGetName gdaGetNames gdaGetOrders ' + + 'gdaGetType gdaGetTypes gdaGetVarInfo gdaIsCplx gdaLoad gdaPack gdaRead gdaReadByIndex gdaReadSome gdaReadSparse ' + + 'gdaReadStruct gdaReportVarInfo gdaSave gdaUpdate gdaUpdateAndPack gdaVars gdaWrite gdaWrite32 gdaWriteSome getarray ' + + 'getdims getf getGAUSShome getmatrix getmatrix4D getname getnamef getNextTradingDay getNextWeekDay getnr getorders ' + + 'getpath getPreviousTradingDay getPreviousWeekDay getRow getscalar3D getscalar4D getTrRow getwind glm gradcplx gradMT ' + + 'gradMTm gradMTT gradMTTm gradp graphprt graphset hasimag header headermt hess hessMT hessMTg hessMTgw hessMTm ' + + 'hessMTmw hessMTT hessMTTg hessMTTgw hessMTTm hessMTw hessp hist histf histp hsec imag indcv indexcat indices indices2 ' + + 'indicesf indicesfn indnv indsav integrate1d integrateControlCreate intgrat2 intgrat3 inthp1 inthp2 inthp3 inthp4 ' + + 'inthpControlCreate intquad1 intquad2 intquad3 intrleav intrleavsa intrsect intsimp inv invpd invswp iscplx iscplxf ' + + 'isden isinfnanmiss ismiss key keyav keyw lag lag1 lagn lapEighb lapEighi lapEighvb lapEighvi lapgEig lapgEigh lapgEighv ' + + 'lapgEigv lapgSchur lapgSvdcst lapgSvds lapgSvdst lapSvdcusv lapSvds lapSvdusv ldlp ldlsol linSolve listwise ln lncdfbvn ' + + 'lncdfbvn2 lncdfmvn lncdfn lncdfn2 lncdfnc lnfact lngammacplx lnpdfmvn lnpdfmvt lnpdfn lnpdft loadd loadstruct loadwind ' + + 'loess loessmt loessmtControlCreate log loglog logx logy lower lowmat lowmat1 ltrisol lu lusol machEpsilon make makevars ' + + 'makewind margin matalloc matinit mattoarray maxbytes maxc maxindc maxv maxvec mbesselei mbesselei0 mbesselei1 mbesseli ' + + 'mbesseli0 mbesseli1 meanc median mergeby mergevar minc minindc minv miss missex missrv moment momentd movingave ' + + 'movingaveExpwgt movingaveWgt nextindex nextn nextnevn nextwind ntos null null1 numCombinations ols olsmt olsmtControlCreate ' + + 'olsqr olsqr2 olsqrmt ones optn optnevn orth outtyp pacf packedToSp packr parse pause pdfCauchy pdfChi pdfExp pdfGenPareto ' + + 'pdfHyperGeo pdfLaplace pdfLogistic pdfn pdfPoisson pdfRayleigh pdfWeibull pi pinv pinvmt plotAddArrow plotAddBar plotAddBox ' + + 'plotAddHist plotAddHistF plotAddHistP plotAddPolar plotAddScatter plotAddShape plotAddTextbox plotAddTS plotAddXY plotArea ' + + 'plotBar plotBox plotClearLayout plotContour plotCustomLayout plotGetDefaults plotHist plotHistF plotHistP plotLayout ' + + 'plotLogLog plotLogX plotLogY plotOpenWindow plotPolar plotSave plotScatter plotSetAxesPen plotSetBar plotSetBarFill ' + + 'plotSetBarStacked plotSetBkdColor plotSetFill plotSetGrid plotSetLegend plotSetLineColor plotSetLineStyle plotSetLineSymbol ' + + 'plotSetLineThickness plotSetNewWindow plotSetTitle plotSetWhichYAxis plotSetXAxisShow plotSetXLabel plotSetXRange ' + + 'plotSetXTicInterval plotSetXTicLabel plotSetYAxisShow plotSetYLabel plotSetYRange plotSetZAxisShow plotSetZLabel ' + + 'plotSurface plotTS plotXY polar polychar polyeval polygamma polyint polymake polymat polymroot polymult polyroot ' + + 'pqgwin previousindex princomp printfm printfmt prodc psi putarray putf putvals pvCreate pvGetIndex pvGetParNames ' + + 'pvGetParVector pvLength pvList pvPack pvPacki pvPackm pvPackmi pvPacks pvPacksi pvPacksm pvPacksmi pvPutParVector ' + + 'pvTest pvUnpack QNewton QNewtonmt QNewtonmtControlCreate QNewtonmtOutCreate QNewtonSet QProg QProgmt QProgmtInCreate ' + + 'qqr qqre qqrep qr qre qrep qrsol qrtsol qtyr qtyre qtyrep quantile quantiled qyr qyre qyrep qz rank rankindx readr ' + + 'real reclassify reclassifyCuts recode recserar recsercp recserrc rerun rescale reshape rets rev rfft rffti rfftip rfftn ' + + 'rfftnp rfftp rndBernoulli rndBeta rndBinomial rndCauchy rndChiSquare rndCon rndCreateState rndExp rndGamma rndGeo rndGumbel ' + + 'rndHyperGeo rndi rndKMbeta rndKMgam rndKMi rndKMn rndKMnb rndKMp rndKMu rndKMvm rndLaplace rndLCbeta rndLCgam rndLCi rndLCn ' + + 'rndLCnb rndLCp rndLCu rndLCvm rndLogNorm rndMTu rndMVn rndMVt rndn rndnb rndNegBinomial rndp rndPoisson rndRayleigh ' + + 'rndStateSkip rndu rndvm rndWeibull rndWishart rotater round rows rowsf rref sampleData satostrC saved saveStruct savewind ' + + 'scale scale3d scalerr scalinfnanmiss scalmiss schtoc schur searchsourcepath seekr select selif seqa seqm setdif setdifsa ' + + 'setvars setvwrmode setwind shell shiftr sin singleindex sinh sleep solpd sortc sortcc sortd sorthc sorthcc sortind ' + + 'sortindc sortmc sortr sortrc spBiconjGradSol spChol spConjGradSol spCreate spDenseSubmat spDiagRvMat spEigv spEye spLDL ' + + 'spline spLU spNumNZE spOnes spreadSheetReadM spreadSheetReadSA spreadSheetWrite spScale spSubmat spToDense spTrTDense ' + + 'spTScalar spZeros sqpSolve sqpSolveMT sqpSolveMTControlCreate sqpSolveMTlagrangeCreate sqpSolveMToutCreate sqpSolveSet ' + + 'sqrt statements stdc stdsc stocv stof strcombine strindx strlen strput strrindx strsect strsplit strsplitPad strtodt ' + + 'strtof strtofcplx strtriml strtrimr strtrunc strtruncl strtruncpad strtruncr submat subscat substute subvec sumc sumr ' + + 'surface svd svd1 svd2 svdcusv svds svdusv sysstate tab tan tanh tempname ' + + 'time timedt timestr timeutc title tkf2eps tkf2ps tocart todaydt toeplitz token topolar trapchk ' + + 'trigamma trimr trunc type typecv typef union unionsa uniqindx uniqindxsa unique uniquesa upmat upmat1 upper utctodt ' + + 'utctodtv utrisol vals varCovMS varCovXS varget vargetl varmall varmares varput varputl vartypef vcm vcms vcx vcxs ' + + 'vec vech vecr vector vget view viewxyz vlist vnamecv volume vput vread vtypecv wait waitc walkindex where window ' + + 'writer xlabel xlsGetSheetCount xlsGetSheetSize xlsGetSheetTypes xlsMakeRange xlsReadM xlsReadSA xlsWrite xlsWriteM ' + + 'xlsWriteSA xpnd xtics xy xyz ylabel ytics zeros zeta zlabel ztics cdfEmpirical dot h5create h5open h5read h5readAttribute ' + + 'h5write h5writeAttribute ldl plotAddErrorBar plotAddSurface plotCDFEmpirical plotSetColormap plotSetContourLabels ' + + 'plotSetLegendFont plotSetTextInterpreter plotSetXTicCount plotSetYTicCount plotSetZLevels powerm strjoin sylvester ' + + 'strtrim', + literal: 'DB_AFTER_LAST_ROW DB_ALL_TABLES DB_BATCH_OPERATIONS DB_BEFORE_FIRST_ROW DB_BLOB DB_EVENT_NOTIFICATIONS ' + + 'DB_FINISH_QUERY DB_HIGH_PRECISION DB_LAST_INSERT_ID DB_LOW_PRECISION_DOUBLE DB_LOW_PRECISION_INT32 ' + + 'DB_LOW_PRECISION_INT64 DB_LOW_PRECISION_NUMBERS DB_MULTIPLE_RESULT_SETS DB_NAMED_PLACEHOLDERS ' + + 'DB_POSITIONAL_PLACEHOLDERS DB_PREPARED_QUERIES DB_QUERY_SIZE DB_SIMPLE_LOCKING DB_SYSTEM_TABLES DB_TABLES ' + + 'DB_TRANSACTIONS DB_UNICODE DB_VIEWS __STDIN __STDOUT __STDERR __FILE_DIR' + }; + + const AT_COMMENT_MODE = hljs.COMMENT('@', '@'); + + const PREPROCESSOR = + { + className: 'meta', + begin: '#', + end: '$', + keywords: { + 'meta-keyword': 'define definecs|10 undef ifdef ifndef iflight ifdllcall ifmac ifos2win ifunix else endif lineson linesoff srcfile srcline' + }, + contains: [ + { + begin: /\\\n/, + relevance: 0 + }, + { + beginKeywords: 'include', + end: '$', + keywords: { + 'meta-keyword': 'include' + }, + contains: [ + { + className: 'meta-string', + begin: '"', + end: '"', + illegal: '\\n' + } + ] + }, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + AT_COMMENT_MODE + ] + }; + + const STRUCT_TYPE = + { + begin: /\bstruct\s+/, + end: /\s/, + keywords: "struct", + contains: [ + { + className: "type", + begin: hljs.UNDERSCORE_IDENT_RE, + relevance: 0 + } + ] + }; + + // only for definitions + const PARSE_PARAMS = [ + { + className: 'params', + begin: /\(/, + end: /\)/, + excludeBegin: true, + excludeEnd: true, + endsWithParent: true, + relevance: 0, + contains: [ + { // dots + className: 'literal', + begin: /\.\.\./ + }, + hljs.C_NUMBER_MODE, + hljs.C_BLOCK_COMMENT_MODE, + AT_COMMENT_MODE, + STRUCT_TYPE + ] + } + ]; + + const FUNCTION_DEF = + { + className: "title", + begin: hljs.UNDERSCORE_IDENT_RE, + relevance: 0 + }; + + const DEFINITION = function(beginKeywords, end, inherits) { + const mode = hljs.inherit( + { + className: "function", + beginKeywords: beginKeywords, + end: end, + excludeEnd: true, + contains: [].concat(PARSE_PARAMS) + }, + inherits || {} + ); + mode.contains.push(FUNCTION_DEF); + mode.contains.push(hljs.C_NUMBER_MODE); + mode.contains.push(hljs.C_BLOCK_COMMENT_MODE); + mode.contains.push(AT_COMMENT_MODE); + return mode; + }; + + const BUILT_IN_REF = + { // these are explicitly named internal function calls + className: 'built_in', + begin: '\\b(' + KEYWORDS.built_in.split(' ').join('|') + ')\\b' + }; + + const STRING_REF = + { + className: 'string', + begin: '"', + end: '"', + contains: [hljs.BACKSLASH_ESCAPE], + relevance: 0 + }; + + const FUNCTION_REF = + { + // className: "fn_ref", + begin: hljs.UNDERSCORE_IDENT_RE + '\\s*\\(', + returnBegin: true, + keywords: KEYWORDS, + relevance: 0, + contains: [ + { + beginKeywords: KEYWORDS.keyword + }, + BUILT_IN_REF, + { // ambiguously named function calls get a relevance of 0 + className: 'built_in', + begin: hljs.UNDERSCORE_IDENT_RE, + relevance: 0 + } + ] + }; + + const FUNCTION_REF_PARAMS = + { + // className: "fn_ref_params", + begin: /\(/, + end: /\)/, + relevance: 0, + keywords: { + built_in: KEYWORDS.built_in, + literal: KEYWORDS.literal + }, + contains: [ + hljs.C_NUMBER_MODE, + hljs.C_BLOCK_COMMENT_MODE, + AT_COMMENT_MODE, + BUILT_IN_REF, + FUNCTION_REF, + STRING_REF, + 'self' + ] + }; + + FUNCTION_REF.contains.push(FUNCTION_REF_PARAMS); + + return { + name: 'GAUSS', + aliases: ['gss'], + case_insensitive: true, // language is case-insensitive + keywords: KEYWORDS, + illegal: /(\{[%#]|[%#]\}| <- )/, + contains: [ + hljs.C_NUMBER_MODE, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + AT_COMMENT_MODE, + STRING_REF, + PREPROCESSOR, + { + className: 'keyword', + begin: /\bexternal (matrix|string|array|sparse matrix|struct|proc|keyword|fn)/ + }, + DEFINITION('proc keyword', ';'), + DEFINITION('fn', '='), + { + beginKeywords: 'for threadfor', + end: /;/, + // end: /\(/, + relevance: 0, + contains: [ + hljs.C_BLOCK_COMMENT_MODE, + AT_COMMENT_MODE, + FUNCTION_REF_PARAMS + ] + }, + { // custom method guard + // excludes method names from keyword processing + variants: [ + { + begin: hljs.UNDERSCORE_IDENT_RE + '\\.' + hljs.UNDERSCORE_IDENT_RE + }, + { + begin: hljs.UNDERSCORE_IDENT_RE + '\\s*=' + } + ], + relevance: 0 + }, + FUNCTION_REF, + STRUCT_TYPE + ] + }; +} + +module.exports = gauss; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/gcode.js b/claude-code-source/node_modules/highlight.js/lib/languages/gcode.js new file mode 100644 index 00000000..0f5cbe25 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/gcode.js @@ -0,0 +1,88 @@ +/* + Language: G-code (ISO 6983) + Contributors: Adam Joseph Cook + Description: G-code syntax highlighter for Fanuc and other common CNC machine tool controls. + Website: https://www.sis.se/api/document/preview/911952/ + */ + +function gcode(hljs) { + const GCODE_IDENT_RE = '[A-Z_][A-Z0-9_.]*'; + const GCODE_CLOSE_RE = '%'; + const GCODE_KEYWORDS = { + $pattern: GCODE_IDENT_RE, + keyword: 'IF DO WHILE ENDWHILE CALL ENDIF SUB ENDSUB GOTO REPEAT ENDREPEAT ' + + 'EQ LT GT NE GE LE OR XOR' + }; + const GCODE_START = { + className: 'meta', + begin: '([O])([0-9]+)' + }; + const NUMBER = hljs.inherit(hljs.C_NUMBER_MODE, { + begin: '([-+]?((\\.\\d+)|(\\d+)(\\.\\d*)?))|' + hljs.C_NUMBER_RE + }); + const GCODE_CODE = [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.COMMENT(/\(/, /\)/), + NUMBER, + hljs.inherit(hljs.APOS_STRING_MODE, { + illegal: null + }), + hljs.inherit(hljs.QUOTE_STRING_MODE, { + illegal: null + }), + { + className: 'name', + begin: '([G])([0-9]+\\.?[0-9]?)' + }, + { + className: 'name', + begin: '([M])([0-9]+\\.?[0-9]?)' + }, + { + className: 'attr', + begin: '(VC|VS|#)', + end: '(\\d+)' + }, + { + className: 'attr', + begin: '(VZOFX|VZOFY|VZOFZ)' + }, + { + className: 'built_in', + begin: '(ATAN|ABS|ACOS|ASIN|SIN|COS|EXP|FIX|FUP|ROUND|LN|TAN)(\\[)', + contains: [ + NUMBER + ], + end: '\\]' + }, + { + className: 'symbol', + variants: [ + { + begin: 'N', + end: '\\d+', + illegal: '\\W' + } + ] + } + ]; + + return { + name: 'G-code (ISO 6983)', + aliases: ['nc'], + // Some implementations (CNC controls) of G-code are interoperable with uppercase and lowercase letters seamlessly. + // However, most prefer all uppercase and uppercase is customary. + case_insensitive: true, + keywords: GCODE_KEYWORDS, + contains: [ + { + className: 'meta', + begin: GCODE_CLOSE_RE + }, + GCODE_START + ].concat(GCODE_CODE) + }; +} + +module.exports = gcode; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/gherkin.js b/claude-code-source/node_modules/highlight.js/lib/languages/gherkin.js new file mode 100644 index 00000000..2cae1e28 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/gherkin.js @@ -0,0 +1,49 @@ +/* + Language: Gherkin + Author: Sam Pikesley (@pikesley) + Description: Gherkin is the format for cucumber specifications. It is a domain specific language which helps you to describe business behavior without the need to go into detail of implementation. + Website: https://cucumber.io/docs/gherkin/ + */ + +function gherkin(hljs) { + return { + name: 'Gherkin', + aliases: ['feature'], + keywords: 'Feature Background Ability Business\ Need Scenario Scenarios Scenario\ Outline Scenario\ Template Examples Given And Then But When', + contains: [ + { + className: 'symbol', + begin: '\\*', + relevance: 0 + }, + { + className: 'meta', + begin: '@[^@\\s]+' + }, + { + begin: '\\|', + end: '\\|\\w*$', + contains: [ + { + className: 'string', + begin: '[^|]+' + } + ] + }, + { + className: 'variable', + begin: '<', + end: '>' + }, + hljs.HASH_COMMENT_MODE, + { + className: 'string', + begin: '"""', + end: '"""' + }, + hljs.QUOTE_STRING_MODE + ] + }; +} + +module.exports = gherkin; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/glsl.js b/claude-code-source/node_modules/highlight.js/lib/languages/glsl.js new file mode 100644 index 00000000..4f52116a --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/glsl.js @@ -0,0 +1,128 @@ +/* +Language: GLSL +Description: OpenGL Shading Language +Author: Sergey Tikhomirov +Website: https://en.wikipedia.org/wiki/OpenGL_Shading_Language +Category: graphics +*/ + +function glsl(hljs) { + return { + name: 'GLSL', + keywords: { + keyword: + // Statements + 'break continue discard do else for if return while switch case default ' + + // Qualifiers + 'attribute binding buffer ccw centroid centroid varying coherent column_major const cw ' + + 'depth_any depth_greater depth_less depth_unchanged early_fragment_tests equal_spacing ' + + 'flat fractional_even_spacing fractional_odd_spacing highp in index inout invariant ' + + 'invocations isolines layout line_strip lines lines_adjacency local_size_x local_size_y ' + + 'local_size_z location lowp max_vertices mediump noperspective offset origin_upper_left ' + + 'out packed patch pixel_center_integer point_mode points precise precision quads r11f_g11f_b10f ' + + 'r16 r16_snorm r16f r16i r16ui r32f r32i r32ui r8 r8_snorm r8i r8ui readonly restrict ' + + 'rg16 rg16_snorm rg16f rg16i rg16ui rg32f rg32i rg32ui rg8 rg8_snorm rg8i rg8ui rgb10_a2 ' + + 'rgb10_a2ui rgba16 rgba16_snorm rgba16f rgba16i rgba16ui rgba32f rgba32i rgba32ui rgba8 ' + + 'rgba8_snorm rgba8i rgba8ui row_major sample shared smooth std140 std430 stream triangle_strip ' + + 'triangles triangles_adjacency uniform varying vertices volatile writeonly', + type: + 'atomic_uint bool bvec2 bvec3 bvec4 dmat2 dmat2x2 dmat2x3 dmat2x4 dmat3 dmat3x2 dmat3x3 ' + + 'dmat3x4 dmat4 dmat4x2 dmat4x3 dmat4x4 double dvec2 dvec3 dvec4 float iimage1D iimage1DArray ' + + 'iimage2D iimage2DArray iimage2DMS iimage2DMSArray iimage2DRect iimage3D iimageBuffer ' + + 'iimageCube iimageCubeArray image1D image1DArray image2D image2DArray image2DMS image2DMSArray ' + + 'image2DRect image3D imageBuffer imageCube imageCubeArray int isampler1D isampler1DArray ' + + 'isampler2D isampler2DArray isampler2DMS isampler2DMSArray isampler2DRect isampler3D ' + + 'isamplerBuffer isamplerCube isamplerCubeArray ivec2 ivec3 ivec4 mat2 mat2x2 mat2x3 ' + + 'mat2x4 mat3 mat3x2 mat3x3 mat3x4 mat4 mat4x2 mat4x3 mat4x4 sampler1D sampler1DArray ' + + 'sampler1DArrayShadow sampler1DShadow sampler2D sampler2DArray sampler2DArrayShadow ' + + 'sampler2DMS sampler2DMSArray sampler2DRect sampler2DRectShadow sampler2DShadow sampler3D ' + + 'samplerBuffer samplerCube samplerCubeArray samplerCubeArrayShadow samplerCubeShadow ' + + 'image1D uimage1DArray uimage2D uimage2DArray uimage2DMS uimage2DMSArray uimage2DRect ' + + 'uimage3D uimageBuffer uimageCube uimageCubeArray uint usampler1D usampler1DArray ' + + 'usampler2D usampler2DArray usampler2DMS usampler2DMSArray usampler2DRect usampler3D ' + + 'samplerBuffer usamplerCube usamplerCubeArray uvec2 uvec3 uvec4 vec2 vec3 vec4 void', + built_in: + // Constants + 'gl_MaxAtomicCounterBindings gl_MaxAtomicCounterBufferSize gl_MaxClipDistances gl_MaxClipPlanes ' + + 'gl_MaxCombinedAtomicCounterBuffers gl_MaxCombinedAtomicCounters gl_MaxCombinedImageUniforms ' + + 'gl_MaxCombinedImageUnitsAndFragmentOutputs gl_MaxCombinedTextureImageUnits gl_MaxComputeAtomicCounterBuffers ' + + 'gl_MaxComputeAtomicCounters gl_MaxComputeImageUniforms gl_MaxComputeTextureImageUnits ' + + 'gl_MaxComputeUniformComponents gl_MaxComputeWorkGroupCount gl_MaxComputeWorkGroupSize ' + + 'gl_MaxDrawBuffers gl_MaxFragmentAtomicCounterBuffers gl_MaxFragmentAtomicCounters ' + + 'gl_MaxFragmentImageUniforms gl_MaxFragmentInputComponents gl_MaxFragmentInputVectors ' + + 'gl_MaxFragmentUniformComponents gl_MaxFragmentUniformVectors gl_MaxGeometryAtomicCounterBuffers ' + + 'gl_MaxGeometryAtomicCounters gl_MaxGeometryImageUniforms gl_MaxGeometryInputComponents ' + + 'gl_MaxGeometryOutputComponents gl_MaxGeometryOutputVertices gl_MaxGeometryTextureImageUnits ' + + 'gl_MaxGeometryTotalOutputComponents gl_MaxGeometryUniformComponents gl_MaxGeometryVaryingComponents ' + + 'gl_MaxImageSamples gl_MaxImageUnits gl_MaxLights gl_MaxPatchVertices gl_MaxProgramTexelOffset ' + + 'gl_MaxTessControlAtomicCounterBuffers gl_MaxTessControlAtomicCounters gl_MaxTessControlImageUniforms ' + + 'gl_MaxTessControlInputComponents gl_MaxTessControlOutputComponents gl_MaxTessControlTextureImageUnits ' + + 'gl_MaxTessControlTotalOutputComponents gl_MaxTessControlUniformComponents ' + + 'gl_MaxTessEvaluationAtomicCounterBuffers gl_MaxTessEvaluationAtomicCounters ' + + 'gl_MaxTessEvaluationImageUniforms gl_MaxTessEvaluationInputComponents gl_MaxTessEvaluationOutputComponents ' + + 'gl_MaxTessEvaluationTextureImageUnits gl_MaxTessEvaluationUniformComponents ' + + 'gl_MaxTessGenLevel gl_MaxTessPatchComponents gl_MaxTextureCoords gl_MaxTextureImageUnits ' + + 'gl_MaxTextureUnits gl_MaxVaryingComponents gl_MaxVaryingFloats gl_MaxVaryingVectors ' + + 'gl_MaxVertexAtomicCounterBuffers gl_MaxVertexAtomicCounters gl_MaxVertexAttribs gl_MaxVertexImageUniforms ' + + 'gl_MaxVertexOutputComponents gl_MaxVertexOutputVectors gl_MaxVertexTextureImageUnits ' + + 'gl_MaxVertexUniformComponents gl_MaxVertexUniformVectors gl_MaxViewports gl_MinProgramTexelOffset ' + + // Variables + 'gl_BackColor gl_BackLightModelProduct gl_BackLightProduct gl_BackMaterial ' + + 'gl_BackSecondaryColor gl_ClipDistance gl_ClipPlane gl_ClipVertex gl_Color ' + + 'gl_DepthRange gl_EyePlaneQ gl_EyePlaneR gl_EyePlaneS gl_EyePlaneT gl_Fog gl_FogCoord ' + + 'gl_FogFragCoord gl_FragColor gl_FragCoord gl_FragData gl_FragDepth gl_FrontColor ' + + 'gl_FrontFacing gl_FrontLightModelProduct gl_FrontLightProduct gl_FrontMaterial ' + + 'gl_FrontSecondaryColor gl_GlobalInvocationID gl_InstanceID gl_InvocationID gl_Layer gl_LightModel ' + + 'gl_LightSource gl_LocalInvocationID gl_LocalInvocationIndex gl_ModelViewMatrix ' + + 'gl_ModelViewMatrixInverse gl_ModelViewMatrixInverseTranspose gl_ModelViewMatrixTranspose ' + + 'gl_ModelViewProjectionMatrix gl_ModelViewProjectionMatrixInverse gl_ModelViewProjectionMatrixInverseTranspose ' + + 'gl_ModelViewProjectionMatrixTranspose gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 ' + + 'gl_MultiTexCoord3 gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 ' + + 'gl_Normal gl_NormalMatrix gl_NormalScale gl_NumSamples gl_NumWorkGroups gl_ObjectPlaneQ ' + + 'gl_ObjectPlaneR gl_ObjectPlaneS gl_ObjectPlaneT gl_PatchVerticesIn gl_Point gl_PointCoord ' + + 'gl_PointSize gl_Position gl_PrimitiveID gl_PrimitiveIDIn gl_ProjectionMatrix gl_ProjectionMatrixInverse ' + + 'gl_ProjectionMatrixInverseTranspose gl_ProjectionMatrixTranspose gl_SampleID gl_SampleMask ' + + 'gl_SampleMaskIn gl_SamplePosition gl_SecondaryColor gl_TessCoord gl_TessLevelInner gl_TessLevelOuter ' + + 'gl_TexCoord gl_TextureEnvColor gl_TextureMatrix gl_TextureMatrixInverse gl_TextureMatrixInverseTranspose ' + + 'gl_TextureMatrixTranspose gl_Vertex gl_VertexID gl_ViewportIndex gl_WorkGroupID gl_WorkGroupSize gl_in gl_out ' + + // Functions + 'EmitStreamVertex EmitVertex EndPrimitive EndStreamPrimitive abs acos acosh all any asin ' + + 'asinh atan atanh atomicAdd atomicAnd atomicCompSwap atomicCounter atomicCounterDecrement ' + + 'atomicCounterIncrement atomicExchange atomicMax atomicMin atomicOr atomicXor barrier ' + + 'bitCount bitfieldExtract bitfieldInsert bitfieldReverse ceil clamp cos cosh cross ' + + 'dFdx dFdy degrees determinant distance dot equal exp exp2 faceforward findLSB findMSB ' + + 'floatBitsToInt floatBitsToUint floor fma fract frexp ftransform fwidth greaterThan ' + + 'greaterThanEqual groupMemoryBarrier imageAtomicAdd imageAtomicAnd imageAtomicCompSwap ' + + 'imageAtomicExchange imageAtomicMax imageAtomicMin imageAtomicOr imageAtomicXor imageLoad ' + + 'imageSize imageStore imulExtended intBitsToFloat interpolateAtCentroid interpolateAtOffset ' + + 'interpolateAtSample inverse inversesqrt isinf isnan ldexp length lessThan lessThanEqual log ' + + 'log2 matrixCompMult max memoryBarrier memoryBarrierAtomicCounter memoryBarrierBuffer ' + + 'memoryBarrierImage memoryBarrierShared min mix mod modf noise1 noise2 noise3 noise4 ' + + 'normalize not notEqual outerProduct packDouble2x32 packHalf2x16 packSnorm2x16 packSnorm4x8 ' + + 'packUnorm2x16 packUnorm4x8 pow radians reflect refract round roundEven shadow1D shadow1DLod ' + + 'shadow1DProj shadow1DProjLod shadow2D shadow2DLod shadow2DProj shadow2DProjLod sign sin sinh ' + + 'smoothstep sqrt step tan tanh texelFetch texelFetchOffset texture texture1D texture1DLod ' + + 'texture1DProj texture1DProjLod texture2D texture2DLod texture2DProj texture2DProjLod ' + + 'texture3D texture3DLod texture3DProj texture3DProjLod textureCube textureCubeLod ' + + 'textureGather textureGatherOffset textureGatherOffsets textureGrad textureGradOffset ' + + 'textureLod textureLodOffset textureOffset textureProj textureProjGrad textureProjGradOffset ' + + 'textureProjLod textureProjLodOffset textureProjOffset textureQueryLevels textureQueryLod ' + + 'textureSize transpose trunc uaddCarry uintBitsToFloat umulExtended unpackDouble2x32 ' + + 'unpackHalf2x16 unpackSnorm2x16 unpackSnorm4x8 unpackUnorm2x16 unpackUnorm4x8 usubBorrow', + literal: 'true false' + }, + illegal: '"', + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.C_NUMBER_MODE, + { + className: 'meta', + begin: '#', + end: '$' + } + ] + }; +} + +module.exports = glsl; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/gml.js b/claude-code-source/node_modules/highlight.js/lib/languages/gml.js new file mode 100644 index 00000000..52b01877 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/gml.js @@ -0,0 +1,885 @@ +/* +Language: GML +Author: Meseta +Description: Game Maker Language for GameMaker Studio 2 +Website: https://docs2.yoyogames.com +Category: scripting +*/ + +function gml(hljs) { + const GML_KEYWORDS = { + keyword: 'begin end if then else while do for break continue with until ' + + 'repeat exit and or xor not return mod div switch case default var ' + + 'globalvar enum function constructor delete #macro #region #endregion', + built_in: 'is_real is_string is_array is_undefined is_int32 is_int64 is_ptr ' + + 'is_vec3 is_vec4 is_matrix is_bool is_method is_struct is_infinity is_nan ' + + 'is_numeric typeof variable_global_exists variable_global_get variable_global_set ' + + 'variable_instance_exists variable_instance_get variable_instance_set ' + + 'variable_instance_get_names variable_struct_exists variable_struct_get ' + + 'variable_struct_get_names variable_struct_names_count variable_struct_remove ' + + 'variable_struct_set array_delete array_insert array_length array_length_1d ' + + 'array_length_2d array_height_2d array_equals array_create ' + + 'array_copy array_pop array_push array_resize array_sort ' + + 'random random_range irandom irandom_range random_set_seed random_get_seed ' + + 'randomize randomise choose abs round floor ceil sign frac sqrt sqr ' + + 'exp ln log2 log10 sin cos tan arcsin arccos arctan arctan2 dsin dcos ' + + 'dtan darcsin darccos darctan darctan2 degtorad radtodeg power logn ' + + 'min max mean median clamp lerp dot_product dot_product_3d ' + + 'dot_product_normalised dot_product_3d_normalised ' + + 'dot_product_normalized dot_product_3d_normalized math_set_epsilon ' + + 'math_get_epsilon angle_difference point_distance_3d point_distance ' + + 'point_direction lengthdir_x lengthdir_y real string int64 ptr ' + + 'string_format chr ansi_char ord string_length string_byte_length ' + + 'string_pos string_copy string_char_at string_ord_at string_byte_at ' + + 'string_set_byte_at string_delete string_insert string_lower ' + + 'string_upper string_repeat string_letters string_digits ' + + 'string_lettersdigits string_replace string_replace_all string_count ' + + 'string_hash_to_newline clipboard_has_text clipboard_set_text ' + + 'clipboard_get_text date_current_datetime date_create_datetime ' + + 'date_valid_datetime date_inc_year date_inc_month date_inc_week ' + + 'date_inc_day date_inc_hour date_inc_minute date_inc_second ' + + 'date_get_year date_get_month date_get_week date_get_day ' + + 'date_get_hour date_get_minute date_get_second date_get_weekday ' + + 'date_get_day_of_year date_get_hour_of_year date_get_minute_of_year ' + + 'date_get_second_of_year date_year_span date_month_span ' + + 'date_week_span date_day_span date_hour_span date_minute_span ' + + 'date_second_span date_compare_datetime date_compare_date ' + + 'date_compare_time date_date_of date_time_of date_datetime_string ' + + 'date_date_string date_time_string date_days_in_month ' + + 'date_days_in_year date_leap_year date_is_today date_set_timezone ' + + 'date_get_timezone game_set_speed game_get_speed motion_set ' + + 'motion_add place_free place_empty place_meeting place_snapped ' + + 'move_random move_snap move_towards_point move_contact_solid ' + + 'move_contact_all move_outside_solid move_outside_all ' + + 'move_bounce_solid move_bounce_all move_wrap distance_to_point ' + + 'distance_to_object position_empty position_meeting path_start ' + + 'path_end mp_linear_step mp_potential_step mp_linear_step_object ' + + 'mp_potential_step_object mp_potential_settings mp_linear_path ' + + 'mp_potential_path mp_linear_path_object mp_potential_path_object ' + + 'mp_grid_create mp_grid_destroy mp_grid_clear_all mp_grid_clear_cell ' + + 'mp_grid_clear_rectangle mp_grid_add_cell mp_grid_get_cell ' + + 'mp_grid_add_rectangle mp_grid_add_instances mp_grid_path ' + + 'mp_grid_draw mp_grid_to_ds_grid collision_point collision_rectangle ' + + 'collision_circle collision_ellipse collision_line ' + + 'collision_point_list collision_rectangle_list collision_circle_list ' + + 'collision_ellipse_list collision_line_list instance_position_list ' + + 'instance_place_list point_in_rectangle ' + + 'point_in_triangle point_in_circle rectangle_in_rectangle ' + + 'rectangle_in_triangle rectangle_in_circle instance_find ' + + 'instance_exists instance_number instance_position instance_nearest ' + + 'instance_furthest instance_place instance_create_depth ' + + 'instance_create_layer instance_copy instance_change instance_destroy ' + + 'position_destroy position_change instance_id_get ' + + 'instance_deactivate_all instance_deactivate_object ' + + 'instance_deactivate_region instance_activate_all ' + + 'instance_activate_object instance_activate_region room_goto ' + + 'room_goto_previous room_goto_next room_previous room_next ' + + 'room_restart game_end game_restart game_load game_save ' + + 'game_save_buffer game_load_buffer event_perform event_user ' + + 'event_perform_object event_inherited show_debug_message ' + + 'show_debug_overlay debug_event debug_get_callstack alarm_get ' + + 'alarm_set font_texture_page_size keyboard_set_map keyboard_get_map ' + + 'keyboard_unset_map keyboard_check keyboard_check_pressed ' + + 'keyboard_check_released keyboard_check_direct keyboard_get_numlock ' + + 'keyboard_set_numlock keyboard_key_press keyboard_key_release ' + + 'keyboard_clear io_clear mouse_check_button ' + + 'mouse_check_button_pressed mouse_check_button_released ' + + 'mouse_wheel_up mouse_wheel_down mouse_clear draw_self draw_sprite ' + + 'draw_sprite_pos draw_sprite_ext draw_sprite_stretched ' + + 'draw_sprite_stretched_ext draw_sprite_tiled draw_sprite_tiled_ext ' + + 'draw_sprite_part draw_sprite_part_ext draw_sprite_general draw_clear ' + + 'draw_clear_alpha draw_point draw_line draw_line_width draw_rectangle ' + + 'draw_roundrect draw_roundrect_ext draw_triangle draw_circle ' + + 'draw_ellipse draw_set_circle_precision draw_arrow draw_button ' + + 'draw_path draw_healthbar draw_getpixel draw_getpixel_ext ' + + 'draw_set_colour draw_set_color draw_set_alpha draw_get_colour ' + + 'draw_get_color draw_get_alpha merge_colour make_colour_rgb ' + + 'make_colour_hsv colour_get_red colour_get_green colour_get_blue ' + + 'colour_get_hue colour_get_saturation colour_get_value merge_color ' + + 'make_color_rgb make_color_hsv color_get_red color_get_green ' + + 'color_get_blue color_get_hue color_get_saturation color_get_value ' + + 'merge_color screen_save screen_save_part draw_set_font ' + + 'draw_set_halign draw_set_valign draw_text draw_text_ext string_width ' + + 'string_height string_width_ext string_height_ext ' + + 'draw_text_transformed draw_text_ext_transformed draw_text_colour ' + + 'draw_text_ext_colour draw_text_transformed_colour ' + + 'draw_text_ext_transformed_colour draw_text_color draw_text_ext_color ' + + 'draw_text_transformed_color draw_text_ext_transformed_color ' + + 'draw_point_colour draw_line_colour draw_line_width_colour ' + + 'draw_rectangle_colour draw_roundrect_colour ' + + 'draw_roundrect_colour_ext draw_triangle_colour draw_circle_colour ' + + 'draw_ellipse_colour draw_point_color draw_line_color ' + + 'draw_line_width_color draw_rectangle_color draw_roundrect_color ' + + 'draw_roundrect_color_ext draw_triangle_color draw_circle_color ' + + 'draw_ellipse_color draw_primitive_begin draw_vertex ' + + 'draw_vertex_colour draw_vertex_color draw_primitive_end ' + + 'sprite_get_uvs font_get_uvs sprite_get_texture font_get_texture ' + + 'texture_get_width texture_get_height texture_get_uvs ' + + 'draw_primitive_begin_texture draw_vertex_texture ' + + 'draw_vertex_texture_colour draw_vertex_texture_color ' + + 'texture_global_scale surface_create surface_create_ext ' + + 'surface_resize surface_free surface_exists surface_get_width ' + + 'surface_get_height surface_get_texture surface_set_target ' + + 'surface_set_target_ext surface_reset_target surface_depth_disable ' + + 'surface_get_depth_disable draw_surface draw_surface_stretched ' + + 'draw_surface_tiled draw_surface_part draw_surface_ext ' + + 'draw_surface_stretched_ext draw_surface_tiled_ext ' + + 'draw_surface_part_ext draw_surface_general surface_getpixel ' + + 'surface_getpixel_ext surface_save surface_save_part surface_copy ' + + 'surface_copy_part application_surface_draw_enable ' + + 'application_get_position application_surface_enable ' + + 'application_surface_is_enabled display_get_width display_get_height ' + + 'display_get_orientation display_get_gui_width display_get_gui_height ' + + 'display_reset display_mouse_get_x display_mouse_get_y ' + + 'display_mouse_set display_set_ui_visibility ' + + 'window_set_fullscreen window_get_fullscreen ' + + 'window_set_caption window_set_min_width window_set_max_width ' + + 'window_set_min_height window_set_max_height window_get_visible_rects ' + + 'window_get_caption window_set_cursor window_get_cursor ' + + 'window_set_colour window_get_colour window_set_color ' + + 'window_get_color window_set_position window_set_size ' + + 'window_set_rectangle window_center window_get_x window_get_y ' + + 'window_get_width window_get_height window_mouse_get_x ' + + 'window_mouse_get_y window_mouse_set window_view_mouse_get_x ' + + 'window_view_mouse_get_y window_views_mouse_get_x ' + + 'window_views_mouse_get_y audio_listener_position ' + + 'audio_listener_velocity audio_listener_orientation ' + + 'audio_emitter_position audio_emitter_create audio_emitter_free ' + + 'audio_emitter_exists audio_emitter_pitch audio_emitter_velocity ' + + 'audio_emitter_falloff audio_emitter_gain audio_play_sound ' + + 'audio_play_sound_on audio_play_sound_at audio_stop_sound ' + + 'audio_resume_music audio_music_is_playing audio_resume_sound ' + + 'audio_pause_sound audio_pause_music audio_channel_num ' + + 'audio_sound_length audio_get_type audio_falloff_set_model ' + + 'audio_play_music audio_stop_music audio_master_gain audio_music_gain ' + + 'audio_sound_gain audio_sound_pitch audio_stop_all audio_resume_all ' + + 'audio_pause_all audio_is_playing audio_is_paused audio_exists ' + + 'audio_sound_set_track_position audio_sound_get_track_position ' + + 'audio_emitter_get_gain audio_emitter_get_pitch audio_emitter_get_x ' + + 'audio_emitter_get_y audio_emitter_get_z audio_emitter_get_vx ' + + 'audio_emitter_get_vy audio_emitter_get_vz ' + + 'audio_listener_set_position audio_listener_set_velocity ' + + 'audio_listener_set_orientation audio_listener_get_data ' + + 'audio_set_master_gain audio_get_master_gain audio_sound_get_gain ' + + 'audio_sound_get_pitch audio_get_name audio_sound_set_track_position ' + + 'audio_sound_get_track_position audio_create_stream ' + + 'audio_destroy_stream audio_create_sync_group ' + + 'audio_destroy_sync_group audio_play_in_sync_group ' + + 'audio_start_sync_group audio_stop_sync_group audio_pause_sync_group ' + + 'audio_resume_sync_group audio_sync_group_get_track_pos ' + + 'audio_sync_group_debug audio_sync_group_is_playing audio_debug ' + + 'audio_group_load audio_group_unload audio_group_is_loaded ' + + 'audio_group_load_progress audio_group_name audio_group_stop_all ' + + 'audio_group_set_gain audio_create_buffer_sound ' + + 'audio_free_buffer_sound audio_create_play_queue ' + + 'audio_free_play_queue audio_queue_sound audio_get_recorder_count ' + + 'audio_get_recorder_info audio_start_recording audio_stop_recording ' + + 'audio_sound_get_listener_mask audio_emitter_get_listener_mask ' + + 'audio_get_listener_mask audio_sound_set_listener_mask ' + + 'audio_emitter_set_listener_mask audio_set_listener_mask ' + + 'audio_get_listener_count audio_get_listener_info audio_system ' + + 'show_message show_message_async clickable_add clickable_add_ext ' + + 'clickable_change clickable_change_ext clickable_delete ' + + 'clickable_exists clickable_set_style show_question ' + + 'show_question_async get_integer get_string get_integer_async ' + + 'get_string_async get_login_async get_open_filename get_save_filename ' + + 'get_open_filename_ext get_save_filename_ext show_error ' + + 'highscore_clear highscore_add highscore_value highscore_name ' + + 'draw_highscore sprite_exists sprite_get_name sprite_get_number ' + + 'sprite_get_width sprite_get_height sprite_get_xoffset ' + + 'sprite_get_yoffset sprite_get_bbox_left sprite_get_bbox_right ' + + 'sprite_get_bbox_top sprite_get_bbox_bottom sprite_save ' + + 'sprite_save_strip sprite_set_cache_size sprite_set_cache_size_ext ' + + 'sprite_get_tpe sprite_prefetch sprite_prefetch_multi sprite_flush ' + + 'sprite_flush_multi sprite_set_speed sprite_get_speed_type ' + + 'sprite_get_speed font_exists font_get_name font_get_fontname ' + + 'font_get_bold font_get_italic font_get_first font_get_last ' + + 'font_get_size font_set_cache_size path_exists path_get_name ' + + 'path_get_length path_get_time path_get_kind path_get_closed ' + + 'path_get_precision path_get_number path_get_point_x path_get_point_y ' + + 'path_get_point_speed path_get_x path_get_y path_get_speed ' + + 'script_exists script_get_name timeline_add timeline_delete ' + + 'timeline_clear timeline_exists timeline_get_name ' + + 'timeline_moment_clear timeline_moment_add_script timeline_size ' + + 'timeline_max_moment object_exists object_get_name object_get_sprite ' + + 'object_get_solid object_get_visible object_get_persistent ' + + 'object_get_mask object_get_parent object_get_physics ' + + 'object_is_ancestor room_exists room_get_name sprite_set_offset ' + + 'sprite_duplicate sprite_assign sprite_merge sprite_add ' + + 'sprite_replace sprite_create_from_surface sprite_add_from_surface ' + + 'sprite_delete sprite_set_alpha_from_sprite sprite_collision_mask ' + + 'font_add_enable_aa font_add_get_enable_aa font_add font_add_sprite ' + + 'font_add_sprite_ext font_replace font_replace_sprite ' + + 'font_replace_sprite_ext font_delete path_set_kind path_set_closed ' + + 'path_set_precision path_add path_assign path_duplicate path_append ' + + 'path_delete path_add_point path_insert_point path_change_point ' + + 'path_delete_point path_clear_points path_reverse path_mirror ' + + 'path_flip path_rotate path_rescale path_shift script_execute ' + + 'object_set_sprite object_set_solid object_set_visible ' + + 'object_set_persistent object_set_mask room_set_width room_set_height ' + + 'room_set_persistent room_set_background_colour ' + + 'room_set_background_color room_set_view room_set_viewport ' + + 'room_get_viewport room_set_view_enabled room_add room_duplicate ' + + 'room_assign room_instance_add room_instance_clear room_get_camera ' + + 'room_set_camera asset_get_index asset_get_type ' + + 'file_text_open_from_string file_text_open_read file_text_open_write ' + + 'file_text_open_append file_text_close file_text_write_string ' + + 'file_text_write_real file_text_writeln file_text_read_string ' + + 'file_text_read_real file_text_readln file_text_eof file_text_eoln ' + + 'file_exists file_delete file_rename file_copy directory_exists ' + + 'directory_create directory_destroy file_find_first file_find_next ' + + 'file_find_close file_attributes filename_name filename_path ' + + 'filename_dir filename_drive filename_ext filename_change_ext ' + + 'file_bin_open file_bin_rewrite file_bin_close file_bin_position ' + + 'file_bin_size file_bin_seek file_bin_write_byte file_bin_read_byte ' + + 'parameter_count parameter_string environment_get_variable ' + + 'ini_open_from_string ini_open ini_close ini_read_string ' + + 'ini_read_real ini_write_string ini_write_real ini_key_exists ' + + 'ini_section_exists ini_key_delete ini_section_delete ' + + 'ds_set_precision ds_exists ds_stack_create ds_stack_destroy ' + + 'ds_stack_clear ds_stack_copy ds_stack_size ds_stack_empty ' + + 'ds_stack_push ds_stack_pop ds_stack_top ds_stack_write ds_stack_read ' + + 'ds_queue_create ds_queue_destroy ds_queue_clear ds_queue_copy ' + + 'ds_queue_size ds_queue_empty ds_queue_enqueue ds_queue_dequeue ' + + 'ds_queue_head ds_queue_tail ds_queue_write ds_queue_read ' + + 'ds_list_create ds_list_destroy ds_list_clear ds_list_copy ' + + 'ds_list_size ds_list_empty ds_list_add ds_list_insert ' + + 'ds_list_replace ds_list_delete ds_list_find_index ds_list_find_value ' + + 'ds_list_mark_as_list ds_list_mark_as_map ds_list_sort ' + + 'ds_list_shuffle ds_list_write ds_list_read ds_list_set ds_map_create ' + + 'ds_map_destroy ds_map_clear ds_map_copy ds_map_size ds_map_empty ' + + 'ds_map_add ds_map_add_list ds_map_add_map ds_map_replace ' + + 'ds_map_replace_map ds_map_replace_list ds_map_delete ds_map_exists ' + + 'ds_map_find_value ds_map_find_previous ds_map_find_next ' + + 'ds_map_find_first ds_map_find_last ds_map_write ds_map_read ' + + 'ds_map_secure_save ds_map_secure_load ds_map_secure_load_buffer ' + + 'ds_map_secure_save_buffer ds_map_set ds_priority_create ' + + 'ds_priority_destroy ds_priority_clear ds_priority_copy ' + + 'ds_priority_size ds_priority_empty ds_priority_add ' + + 'ds_priority_change_priority ds_priority_find_priority ' + + 'ds_priority_delete_value ds_priority_delete_min ds_priority_find_min ' + + 'ds_priority_delete_max ds_priority_find_max ds_priority_write ' + + 'ds_priority_read ds_grid_create ds_grid_destroy ds_grid_copy ' + + 'ds_grid_resize ds_grid_width ds_grid_height ds_grid_clear ' + + 'ds_grid_set ds_grid_add ds_grid_multiply ds_grid_set_region ' + + 'ds_grid_add_region ds_grid_multiply_region ds_grid_set_disk ' + + 'ds_grid_add_disk ds_grid_multiply_disk ds_grid_set_grid_region ' + + 'ds_grid_add_grid_region ds_grid_multiply_grid_region ds_grid_get ' + + 'ds_grid_get_sum ds_grid_get_max ds_grid_get_min ds_grid_get_mean ' + + 'ds_grid_get_disk_sum ds_grid_get_disk_min ds_grid_get_disk_max ' + + 'ds_grid_get_disk_mean ds_grid_value_exists ds_grid_value_x ' + + 'ds_grid_value_y ds_grid_value_disk_exists ds_grid_value_disk_x ' + + 'ds_grid_value_disk_y ds_grid_shuffle ds_grid_write ds_grid_read ' + + 'ds_grid_sort ds_grid_set ds_grid_get effect_create_below ' + + 'effect_create_above effect_clear part_type_create part_type_destroy ' + + 'part_type_exists part_type_clear part_type_shape part_type_sprite ' + + 'part_type_size part_type_scale part_type_orientation part_type_life ' + + 'part_type_step part_type_death part_type_speed part_type_direction ' + + 'part_type_gravity part_type_colour1 part_type_colour2 ' + + 'part_type_colour3 part_type_colour_mix part_type_colour_rgb ' + + 'part_type_colour_hsv part_type_color1 part_type_color2 ' + + 'part_type_color3 part_type_color_mix part_type_color_rgb ' + + 'part_type_color_hsv part_type_alpha1 part_type_alpha2 ' + + 'part_type_alpha3 part_type_blend part_system_create ' + + 'part_system_create_layer part_system_destroy part_system_exists ' + + 'part_system_clear part_system_draw_order part_system_depth ' + + 'part_system_position part_system_automatic_update ' + + 'part_system_automatic_draw part_system_update part_system_drawit ' + + 'part_system_get_layer part_system_layer part_particles_create ' + + 'part_particles_create_colour part_particles_create_color ' + + 'part_particles_clear part_particles_count part_emitter_create ' + + 'part_emitter_destroy part_emitter_destroy_all part_emitter_exists ' + + 'part_emitter_clear part_emitter_region part_emitter_burst ' + + 'part_emitter_stream external_call external_define external_free ' + + 'window_handle window_device matrix_get matrix_set ' + + 'matrix_build_identity matrix_build matrix_build_lookat ' + + 'matrix_build_projection_ortho matrix_build_projection_perspective ' + + 'matrix_build_projection_perspective_fov matrix_multiply ' + + 'matrix_transform_vertex matrix_stack_push matrix_stack_pop ' + + 'matrix_stack_multiply matrix_stack_set matrix_stack_clear ' + + 'matrix_stack_top matrix_stack_is_empty browser_input_capture ' + + 'os_get_config os_get_info os_get_language os_get_region ' + + 'os_lock_orientation display_get_dpi_x display_get_dpi_y ' + + 'display_set_gui_size display_set_gui_maximise ' + + 'display_set_gui_maximize device_mouse_dbclick_enable ' + + 'display_set_timing_method display_get_timing_method ' + + 'display_set_sleep_margin display_get_sleep_margin virtual_key_add ' + + 'virtual_key_hide virtual_key_delete virtual_key_show ' + + 'draw_enable_drawevent draw_enable_swf_aa draw_set_swf_aa_level ' + + 'draw_get_swf_aa_level draw_texture_flush draw_flush ' + + 'gpu_set_blendenable gpu_set_ztestenable gpu_set_zfunc ' + + 'gpu_set_zwriteenable gpu_set_lightingenable gpu_set_fog ' + + 'gpu_set_cullmode gpu_set_blendmode gpu_set_blendmode_ext ' + + 'gpu_set_blendmode_ext_sepalpha gpu_set_colorwriteenable ' + + 'gpu_set_colourwriteenable gpu_set_alphatestenable ' + + 'gpu_set_alphatestref gpu_set_alphatestfunc gpu_set_texfilter ' + + 'gpu_set_texfilter_ext gpu_set_texrepeat gpu_set_texrepeat_ext ' + + 'gpu_set_tex_filter gpu_set_tex_filter_ext gpu_set_tex_repeat ' + + 'gpu_set_tex_repeat_ext gpu_set_tex_mip_filter ' + + 'gpu_set_tex_mip_filter_ext gpu_set_tex_mip_bias ' + + 'gpu_set_tex_mip_bias_ext gpu_set_tex_min_mip gpu_set_tex_min_mip_ext ' + + 'gpu_set_tex_max_mip gpu_set_tex_max_mip_ext gpu_set_tex_max_aniso ' + + 'gpu_set_tex_max_aniso_ext gpu_set_tex_mip_enable ' + + 'gpu_set_tex_mip_enable_ext gpu_get_blendenable gpu_get_ztestenable ' + + 'gpu_get_zfunc gpu_get_zwriteenable gpu_get_lightingenable ' + + 'gpu_get_fog gpu_get_cullmode gpu_get_blendmode gpu_get_blendmode_ext ' + + 'gpu_get_blendmode_ext_sepalpha gpu_get_blendmode_src ' + + 'gpu_get_blendmode_dest gpu_get_blendmode_srcalpha ' + + 'gpu_get_blendmode_destalpha gpu_get_colorwriteenable ' + + 'gpu_get_colourwriteenable gpu_get_alphatestenable ' + + 'gpu_get_alphatestref gpu_get_alphatestfunc gpu_get_texfilter ' + + 'gpu_get_texfilter_ext gpu_get_texrepeat gpu_get_texrepeat_ext ' + + 'gpu_get_tex_filter gpu_get_tex_filter_ext gpu_get_tex_repeat ' + + 'gpu_get_tex_repeat_ext gpu_get_tex_mip_filter ' + + 'gpu_get_tex_mip_filter_ext gpu_get_tex_mip_bias ' + + 'gpu_get_tex_mip_bias_ext gpu_get_tex_min_mip gpu_get_tex_min_mip_ext ' + + 'gpu_get_tex_max_mip gpu_get_tex_max_mip_ext gpu_get_tex_max_aniso ' + + 'gpu_get_tex_max_aniso_ext gpu_get_tex_mip_enable ' + + 'gpu_get_tex_mip_enable_ext gpu_push_state gpu_pop_state ' + + 'gpu_get_state gpu_set_state draw_light_define_ambient ' + + 'draw_light_define_direction draw_light_define_point ' + + 'draw_light_enable draw_set_lighting draw_light_get_ambient ' + + 'draw_light_get draw_get_lighting shop_leave_rating url_get_domain ' + + 'url_open url_open_ext url_open_full get_timer achievement_login ' + + 'achievement_logout achievement_post achievement_increment ' + + 'achievement_post_score achievement_available ' + + 'achievement_show_achievements achievement_show_leaderboards ' + + 'achievement_load_friends achievement_load_leaderboard ' + + 'achievement_send_challenge achievement_load_progress ' + + 'achievement_reset achievement_login_status achievement_get_pic ' + + 'achievement_show_challenge_notifications achievement_get_challenges ' + + 'achievement_event achievement_show achievement_get_info ' + + 'cloud_file_save cloud_string_save cloud_synchronise ads_enable ' + + 'ads_disable ads_setup ads_engagement_launch ads_engagement_available ' + + 'ads_engagement_active ads_event ads_event_preload ' + + 'ads_set_reward_callback ads_get_display_height ads_get_display_width ' + + 'ads_move ads_interstitial_available ads_interstitial_display ' + + 'device_get_tilt_x device_get_tilt_y device_get_tilt_z ' + + 'device_is_keypad_open device_mouse_check_button ' + + 'device_mouse_check_button_pressed device_mouse_check_button_released ' + + 'device_mouse_x device_mouse_y device_mouse_raw_x device_mouse_raw_y ' + + 'device_mouse_x_to_gui device_mouse_y_to_gui iap_activate iap_status ' + + 'iap_enumerate_products iap_restore_all iap_acquire iap_consume ' + + 'iap_product_details iap_purchase_details facebook_init ' + + 'facebook_login facebook_status facebook_graph_request ' + + 'facebook_dialog facebook_logout facebook_launch_offerwall ' + + 'facebook_post_message facebook_send_invite facebook_user_id ' + + 'facebook_accesstoken facebook_check_permission ' + + 'facebook_request_read_permissions ' + + 'facebook_request_publish_permissions gamepad_is_supported ' + + 'gamepad_get_device_count gamepad_is_connected ' + + 'gamepad_get_description gamepad_get_button_threshold ' + + 'gamepad_set_button_threshold gamepad_get_axis_deadzone ' + + 'gamepad_set_axis_deadzone gamepad_button_count gamepad_button_check ' + + 'gamepad_button_check_pressed gamepad_button_check_released ' + + 'gamepad_button_value gamepad_axis_count gamepad_axis_value ' + + 'gamepad_set_vibration gamepad_set_colour gamepad_set_color ' + + 'os_is_paused window_has_focus code_is_compiled http_get ' + + 'http_get_file http_post_string http_request json_encode json_decode ' + + 'zip_unzip load_csv base64_encode base64_decode md5_string_unicode ' + + 'md5_string_utf8 md5_file os_is_network_connected sha1_string_unicode ' + + 'sha1_string_utf8 sha1_file os_powersave_enable analytics_event ' + + 'analytics_event_ext win8_livetile_tile_notification ' + + 'win8_livetile_tile_clear win8_livetile_badge_notification ' + + 'win8_livetile_badge_clear win8_livetile_queue_enable ' + + 'win8_secondarytile_pin win8_secondarytile_badge_notification ' + + 'win8_secondarytile_delete win8_livetile_notification_begin ' + + 'win8_livetile_notification_secondary_begin ' + + 'win8_livetile_notification_expiry win8_livetile_notification_tag ' + + 'win8_livetile_notification_text_add ' + + 'win8_livetile_notification_image_add win8_livetile_notification_end ' + + 'win8_appbar_enable win8_appbar_add_element ' + + 'win8_appbar_remove_element win8_settingscharm_add_entry ' + + 'win8_settingscharm_add_html_entry win8_settingscharm_add_xaml_entry ' + + 'win8_settingscharm_set_xaml_property ' + + 'win8_settingscharm_get_xaml_property win8_settingscharm_remove_entry ' + + 'win8_share_image win8_share_screenshot win8_share_file ' + + 'win8_share_url win8_share_text win8_search_enable ' + + 'win8_search_disable win8_search_add_suggestions ' + + 'win8_device_touchscreen_available win8_license_initialize_sandbox ' + + 'win8_license_trial_version winphone_license_trial_version ' + + 'winphone_tile_title winphone_tile_count winphone_tile_back_title ' + + 'winphone_tile_back_content winphone_tile_back_content_wide ' + + 'winphone_tile_front_image winphone_tile_front_image_small ' + + 'winphone_tile_front_image_wide winphone_tile_back_image ' + + 'winphone_tile_back_image_wide winphone_tile_background_colour ' + + 'winphone_tile_background_color winphone_tile_icon_image ' + + 'winphone_tile_small_icon_image winphone_tile_wide_content ' + + 'winphone_tile_cycle_images winphone_tile_small_background_image ' + + 'physics_world_create physics_world_gravity ' + + 'physics_world_update_speed physics_world_update_iterations ' + + 'physics_world_draw_debug physics_pause_enable physics_fixture_create ' + + 'physics_fixture_set_kinematic physics_fixture_set_density ' + + 'physics_fixture_set_awake physics_fixture_set_restitution ' + + 'physics_fixture_set_friction physics_fixture_set_collision_group ' + + 'physics_fixture_set_sensor physics_fixture_set_linear_damping ' + + 'physics_fixture_set_angular_damping physics_fixture_set_circle_shape ' + + 'physics_fixture_set_box_shape physics_fixture_set_edge_shape ' + + 'physics_fixture_set_polygon_shape physics_fixture_set_chain_shape ' + + 'physics_fixture_add_point physics_fixture_bind ' + + 'physics_fixture_bind_ext physics_fixture_delete physics_apply_force ' + + 'physics_apply_impulse physics_apply_angular_impulse ' + + 'physics_apply_local_force physics_apply_local_impulse ' + + 'physics_apply_torque physics_mass_properties physics_draw_debug ' + + 'physics_test_overlap physics_remove_fixture physics_set_friction ' + + 'physics_set_density physics_set_restitution physics_get_friction ' + + 'physics_get_density physics_get_restitution ' + + 'physics_joint_distance_create physics_joint_rope_create ' + + 'physics_joint_revolute_create physics_joint_prismatic_create ' + + 'physics_joint_pulley_create physics_joint_wheel_create ' + + 'physics_joint_weld_create physics_joint_friction_create ' + + 'physics_joint_gear_create physics_joint_enable_motor ' + + 'physics_joint_get_value physics_joint_set_value physics_joint_delete ' + + 'physics_particle_create physics_particle_delete ' + + 'physics_particle_delete_region_circle ' + + 'physics_particle_delete_region_box ' + + 'physics_particle_delete_region_poly physics_particle_set_flags ' + + 'physics_particle_set_category_flags physics_particle_draw ' + + 'physics_particle_draw_ext physics_particle_count ' + + 'physics_particle_get_data physics_particle_get_data_particle ' + + 'physics_particle_group_begin physics_particle_group_circle ' + + 'physics_particle_group_box physics_particle_group_polygon ' + + 'physics_particle_group_add_point physics_particle_group_end ' + + 'physics_particle_group_join physics_particle_group_delete ' + + 'physics_particle_group_count physics_particle_group_get_data ' + + 'physics_particle_group_get_mass physics_particle_group_get_inertia ' + + 'physics_particle_group_get_centre_x ' + + 'physics_particle_group_get_centre_y physics_particle_group_get_vel_x ' + + 'physics_particle_group_get_vel_y physics_particle_group_get_ang_vel ' + + 'physics_particle_group_get_x physics_particle_group_get_y ' + + 'physics_particle_group_get_angle physics_particle_set_group_flags ' + + 'physics_particle_get_group_flags physics_particle_get_max_count ' + + 'physics_particle_get_radius physics_particle_get_density ' + + 'physics_particle_get_damping physics_particle_get_gravity_scale ' + + 'physics_particle_set_max_count physics_particle_set_radius ' + + 'physics_particle_set_density physics_particle_set_damping ' + + 'physics_particle_set_gravity_scale network_create_socket ' + + 'network_create_socket_ext network_create_server ' + + 'network_create_server_raw network_connect network_connect_raw ' + + 'network_send_packet network_send_raw network_send_broadcast ' + + 'network_send_udp network_send_udp_raw network_set_timeout ' + + 'network_set_config network_resolve network_destroy buffer_create ' + + 'buffer_write buffer_read buffer_seek buffer_get_surface ' + + 'buffer_set_surface buffer_delete buffer_exists buffer_get_type ' + + 'buffer_get_alignment buffer_poke buffer_peek buffer_save ' + + 'buffer_save_ext buffer_load buffer_load_ext buffer_load_partial ' + + 'buffer_copy buffer_fill buffer_get_size buffer_tell buffer_resize ' + + 'buffer_md5 buffer_sha1 buffer_base64_encode buffer_base64_decode ' + + 'buffer_base64_decode_ext buffer_sizeof buffer_get_address ' + + 'buffer_create_from_vertex_buffer ' + + 'buffer_create_from_vertex_buffer_ext buffer_copy_from_vertex_buffer ' + + 'buffer_async_group_begin buffer_async_group_option ' + + 'buffer_async_group_end buffer_load_async buffer_save_async ' + + 'gml_release_mode gml_pragma steam_activate_overlay ' + + 'steam_is_overlay_enabled steam_is_overlay_activated ' + + 'steam_get_persona_name steam_initialised ' + + 'steam_is_cloud_enabled_for_app steam_is_cloud_enabled_for_account ' + + 'steam_file_persisted steam_get_quota_total steam_get_quota_free ' + + 'steam_file_write steam_file_write_file steam_file_read ' + + 'steam_file_delete steam_file_exists steam_file_size steam_file_share ' + + 'steam_is_screenshot_requested steam_send_screenshot ' + + 'steam_is_user_logged_on steam_get_user_steam_id steam_user_owns_dlc ' + + 'steam_user_installed_dlc steam_set_achievement steam_get_achievement ' + + 'steam_clear_achievement steam_set_stat_int steam_set_stat_float ' + + 'steam_set_stat_avg_rate steam_get_stat_int steam_get_stat_float ' + + 'steam_get_stat_avg_rate steam_reset_all_stats ' + + 'steam_reset_all_stats_achievements steam_stats_ready ' + + 'steam_create_leaderboard steam_upload_score steam_upload_score_ext ' + + 'steam_download_scores_around_user steam_download_scores ' + + 'steam_download_friends_scores steam_upload_score_buffer ' + + 'steam_upload_score_buffer_ext steam_current_game_language ' + + 'steam_available_languages steam_activate_overlay_browser ' + + 'steam_activate_overlay_user steam_activate_overlay_store ' + + 'steam_get_user_persona_name steam_get_app_id ' + + 'steam_get_user_account_id steam_ugc_download steam_ugc_create_item ' + + 'steam_ugc_start_item_update steam_ugc_set_item_title ' + + 'steam_ugc_set_item_description steam_ugc_set_item_visibility ' + + 'steam_ugc_set_item_tags steam_ugc_set_item_content ' + + 'steam_ugc_set_item_preview steam_ugc_submit_item_update ' + + 'steam_ugc_get_item_update_progress steam_ugc_subscribe_item ' + + 'steam_ugc_unsubscribe_item steam_ugc_num_subscribed_items ' + + 'steam_ugc_get_subscribed_items steam_ugc_get_item_install_info ' + + 'steam_ugc_get_item_update_info steam_ugc_request_item_details ' + + 'steam_ugc_create_query_user steam_ugc_create_query_user_ex ' + + 'steam_ugc_create_query_all steam_ugc_create_query_all_ex ' + + 'steam_ugc_query_set_cloud_filename_filter ' + + 'steam_ugc_query_set_match_any_tag steam_ugc_query_set_search_text ' + + 'steam_ugc_query_set_ranked_by_trend_days ' + + 'steam_ugc_query_add_required_tag steam_ugc_query_add_excluded_tag ' + + 'steam_ugc_query_set_return_long_description ' + + 'steam_ugc_query_set_return_total_only ' + + 'steam_ugc_query_set_allow_cached_response steam_ugc_send_query ' + + 'shader_set shader_get_name shader_reset shader_current ' + + 'shader_is_compiled shader_get_sampler_index shader_get_uniform ' + + 'shader_set_uniform_i shader_set_uniform_i_array shader_set_uniform_f ' + + 'shader_set_uniform_f_array shader_set_uniform_matrix ' + + 'shader_set_uniform_matrix_array shader_enable_corner_id ' + + 'texture_set_stage texture_get_texel_width texture_get_texel_height ' + + 'shaders_are_supported vertex_format_begin vertex_format_end ' + + 'vertex_format_delete vertex_format_add_position ' + + 'vertex_format_add_position_3d vertex_format_add_colour ' + + 'vertex_format_add_color vertex_format_add_normal ' + + 'vertex_format_add_texcoord vertex_format_add_textcoord ' + + 'vertex_format_add_custom vertex_create_buffer ' + + 'vertex_create_buffer_ext vertex_delete_buffer vertex_begin ' + + 'vertex_end vertex_position vertex_position_3d vertex_colour ' + + 'vertex_color vertex_argb vertex_texcoord vertex_normal vertex_float1 ' + + 'vertex_float2 vertex_float3 vertex_float4 vertex_ubyte4 ' + + 'vertex_submit vertex_freeze vertex_get_number vertex_get_buffer_size ' + + 'vertex_create_buffer_from_buffer ' + + 'vertex_create_buffer_from_buffer_ext push_local_notification ' + + 'push_get_first_local_notification push_get_next_local_notification ' + + 'push_cancel_local_notification skeleton_animation_set ' + + 'skeleton_animation_get skeleton_animation_mix ' + + 'skeleton_animation_set_ext skeleton_animation_get_ext ' + + 'skeleton_animation_get_duration skeleton_animation_get_frames ' + + 'skeleton_animation_clear skeleton_skin_set skeleton_skin_get ' + + 'skeleton_attachment_set skeleton_attachment_get ' + + 'skeleton_attachment_create skeleton_collision_draw_set ' + + 'skeleton_bone_data_get skeleton_bone_data_set ' + + 'skeleton_bone_state_get skeleton_bone_state_set skeleton_get_minmax ' + + 'skeleton_get_num_bounds skeleton_get_bounds ' + + 'skeleton_animation_get_frame skeleton_animation_set_frame ' + + 'draw_skeleton draw_skeleton_time draw_skeleton_instance ' + + 'draw_skeleton_collision skeleton_animation_list skeleton_skin_list ' + + 'skeleton_slot_data layer_get_id layer_get_id_at_depth ' + + 'layer_get_depth layer_create layer_destroy layer_destroy_instances ' + + 'layer_add_instance layer_has_instance layer_set_visible ' + + 'layer_get_visible layer_exists layer_x layer_y layer_get_x ' + + 'layer_get_y layer_hspeed layer_vspeed layer_get_hspeed ' + + 'layer_get_vspeed layer_script_begin layer_script_end layer_shader ' + + 'layer_get_script_begin layer_get_script_end layer_get_shader ' + + 'layer_set_target_room layer_get_target_room layer_reset_target_room ' + + 'layer_get_all layer_get_all_elements layer_get_name layer_depth ' + + 'layer_get_element_layer layer_get_element_type layer_element_move ' + + 'layer_force_draw_depth layer_is_draw_depth_forced ' + + 'layer_get_forced_depth layer_background_get_id ' + + 'layer_background_exists layer_background_create ' + + 'layer_background_destroy layer_background_visible ' + + 'layer_background_change layer_background_sprite ' + + 'layer_background_htiled layer_background_vtiled ' + + 'layer_background_stretch layer_background_yscale ' + + 'layer_background_xscale layer_background_blend ' + + 'layer_background_alpha layer_background_index layer_background_speed ' + + 'layer_background_get_visible layer_background_get_sprite ' + + 'layer_background_get_htiled layer_background_get_vtiled ' + + 'layer_background_get_stretch layer_background_get_yscale ' + + 'layer_background_get_xscale layer_background_get_blend ' + + 'layer_background_get_alpha layer_background_get_index ' + + 'layer_background_get_speed layer_sprite_get_id layer_sprite_exists ' + + 'layer_sprite_create layer_sprite_destroy layer_sprite_change ' + + 'layer_sprite_index layer_sprite_speed layer_sprite_xscale ' + + 'layer_sprite_yscale layer_sprite_angle layer_sprite_blend ' + + 'layer_sprite_alpha layer_sprite_x layer_sprite_y ' + + 'layer_sprite_get_sprite layer_sprite_get_index ' + + 'layer_sprite_get_speed layer_sprite_get_xscale ' + + 'layer_sprite_get_yscale layer_sprite_get_angle ' + + 'layer_sprite_get_blend layer_sprite_get_alpha layer_sprite_get_x ' + + 'layer_sprite_get_y layer_tilemap_get_id layer_tilemap_exists ' + + 'layer_tilemap_create layer_tilemap_destroy tilemap_tileset tilemap_x ' + + 'tilemap_y tilemap_set tilemap_set_at_pixel tilemap_get_tileset ' + + 'tilemap_get_tile_width tilemap_get_tile_height tilemap_get_width ' + + 'tilemap_get_height tilemap_get_x tilemap_get_y tilemap_get ' + + 'tilemap_get_at_pixel tilemap_get_cell_x_at_pixel ' + + 'tilemap_get_cell_y_at_pixel tilemap_clear draw_tilemap draw_tile ' + + 'tilemap_set_global_mask tilemap_get_global_mask tilemap_set_mask ' + + 'tilemap_get_mask tilemap_get_frame tile_set_empty tile_set_index ' + + 'tile_set_flip tile_set_mirror tile_set_rotate tile_get_empty ' + + 'tile_get_index tile_get_flip tile_get_mirror tile_get_rotate ' + + 'layer_tile_exists layer_tile_create layer_tile_destroy ' + + 'layer_tile_change layer_tile_xscale layer_tile_yscale ' + + 'layer_tile_blend layer_tile_alpha layer_tile_x layer_tile_y ' + + 'layer_tile_region layer_tile_visible layer_tile_get_sprite ' + + 'layer_tile_get_xscale layer_tile_get_yscale layer_tile_get_blend ' + + 'layer_tile_get_alpha layer_tile_get_x layer_tile_get_y ' + + 'layer_tile_get_region layer_tile_get_visible ' + + 'layer_instance_get_instance instance_activate_layer ' + + 'instance_deactivate_layer camera_create camera_create_view ' + + 'camera_destroy camera_apply camera_get_active camera_get_default ' + + 'camera_set_default camera_set_view_mat camera_set_proj_mat ' + + 'camera_set_update_script camera_set_begin_script ' + + 'camera_set_end_script camera_set_view_pos camera_set_view_size ' + + 'camera_set_view_speed camera_set_view_border camera_set_view_angle ' + + 'camera_set_view_target camera_get_view_mat camera_get_proj_mat ' + + 'camera_get_update_script camera_get_begin_script ' + + 'camera_get_end_script camera_get_view_x camera_get_view_y ' + + 'camera_get_view_width camera_get_view_height camera_get_view_speed_x ' + + 'camera_get_view_speed_y camera_get_view_border_x ' + + 'camera_get_view_border_y camera_get_view_angle ' + + 'camera_get_view_target view_get_camera view_get_visible ' + + 'view_get_xport view_get_yport view_get_wport view_get_hport ' + + 'view_get_surface_id view_set_camera view_set_visible view_set_xport ' + + 'view_set_yport view_set_wport view_set_hport view_set_surface_id ' + + 'gesture_drag_time gesture_drag_distance gesture_flick_speed ' + + 'gesture_double_tap_time gesture_double_tap_distance ' + + 'gesture_pinch_distance gesture_pinch_angle_towards ' + + 'gesture_pinch_angle_away gesture_rotate_time gesture_rotate_angle ' + + 'gesture_tap_count gesture_get_drag_time gesture_get_drag_distance ' + + 'gesture_get_flick_speed gesture_get_double_tap_time ' + + 'gesture_get_double_tap_distance gesture_get_pinch_distance ' + + 'gesture_get_pinch_angle_towards gesture_get_pinch_angle_away ' + + 'gesture_get_rotate_time gesture_get_rotate_angle ' + + 'gesture_get_tap_count keyboard_virtual_show keyboard_virtual_hide ' + + 'keyboard_virtual_status keyboard_virtual_height', + literal: 'self other all noone global local undefined pointer_invalid ' + + 'pointer_null path_action_stop path_action_restart ' + + 'path_action_continue path_action_reverse true false pi GM_build_date ' + + 'GM_version GM_runtime_version timezone_local timezone_utc ' + + 'gamespeed_fps gamespeed_microseconds ev_create ev_destroy ev_step ' + + 'ev_alarm ev_keyboard ev_mouse ev_collision ev_other ev_draw ' + + 'ev_draw_begin ev_draw_end ev_draw_pre ev_draw_post ev_keypress ' + + 'ev_keyrelease ev_trigger ev_left_button ev_right_button ' + + 'ev_middle_button ev_no_button ev_left_press ev_right_press ' + + 'ev_middle_press ev_left_release ev_right_release ev_middle_release ' + + 'ev_mouse_enter ev_mouse_leave ev_mouse_wheel_up ev_mouse_wheel_down ' + + 'ev_global_left_button ev_global_right_button ev_global_middle_button ' + + 'ev_global_left_press ev_global_right_press ev_global_middle_press ' + + 'ev_global_left_release ev_global_right_release ' + + 'ev_global_middle_release ev_joystick1_left ev_joystick1_right ' + + 'ev_joystick1_up ev_joystick1_down ev_joystick1_button1 ' + + 'ev_joystick1_button2 ev_joystick1_button3 ev_joystick1_button4 ' + + 'ev_joystick1_button5 ev_joystick1_button6 ev_joystick1_button7 ' + + 'ev_joystick1_button8 ev_joystick2_left ev_joystick2_right ' + + 'ev_joystick2_up ev_joystick2_down ev_joystick2_button1 ' + + 'ev_joystick2_button2 ev_joystick2_button3 ev_joystick2_button4 ' + + 'ev_joystick2_button5 ev_joystick2_button6 ev_joystick2_button7 ' + + 'ev_joystick2_button8 ev_outside ev_boundary ev_game_start ' + + 'ev_game_end ev_room_start ev_room_end ev_no_more_lives ' + + 'ev_animation_end ev_end_of_path ev_no_more_health ev_close_button ' + + 'ev_user0 ev_user1 ev_user2 ev_user3 ev_user4 ev_user5 ev_user6 ' + + 'ev_user7 ev_user8 ev_user9 ev_user10 ev_user11 ev_user12 ev_user13 ' + + 'ev_user14 ev_user15 ev_step_normal ev_step_begin ev_step_end ev_gui ' + + 'ev_gui_begin ev_gui_end ev_cleanup ev_gesture ev_gesture_tap ' + + 'ev_gesture_double_tap ev_gesture_drag_start ev_gesture_dragging ' + + 'ev_gesture_drag_end ev_gesture_flick ev_gesture_pinch_start ' + + 'ev_gesture_pinch_in ev_gesture_pinch_out ev_gesture_pinch_end ' + + 'ev_gesture_rotate_start ev_gesture_rotating ev_gesture_rotate_end ' + + 'ev_global_gesture_tap ev_global_gesture_double_tap ' + + 'ev_global_gesture_drag_start ev_global_gesture_dragging ' + + 'ev_global_gesture_drag_end ev_global_gesture_flick ' + + 'ev_global_gesture_pinch_start ev_global_gesture_pinch_in ' + + 'ev_global_gesture_pinch_out ev_global_gesture_pinch_end ' + + 'ev_global_gesture_rotate_start ev_global_gesture_rotating ' + + 'ev_global_gesture_rotate_end vk_nokey vk_anykey vk_enter vk_return ' + + 'vk_shift vk_control vk_alt vk_escape vk_space vk_backspace vk_tab ' + + 'vk_pause vk_printscreen vk_left vk_right vk_up vk_down vk_home ' + + 'vk_end vk_delete vk_insert vk_pageup vk_pagedown vk_f1 vk_f2 vk_f3 ' + + 'vk_f4 vk_f5 vk_f6 vk_f7 vk_f8 vk_f9 vk_f10 vk_f11 vk_f12 vk_numpad0 ' + + 'vk_numpad1 vk_numpad2 vk_numpad3 vk_numpad4 vk_numpad5 vk_numpad6 ' + + 'vk_numpad7 vk_numpad8 vk_numpad9 vk_divide vk_multiply vk_subtract ' + + 'vk_add vk_decimal vk_lshift vk_lcontrol vk_lalt vk_rshift ' + + 'vk_rcontrol vk_ralt mb_any mb_none mb_left mb_right mb_middle ' + + 'c_aqua c_black c_blue c_dkgray c_fuchsia c_gray c_green c_lime ' + + 'c_ltgray c_maroon c_navy c_olive c_purple c_red c_silver c_teal ' + + 'c_white c_yellow c_orange fa_left fa_center fa_right fa_top ' + + 'fa_middle fa_bottom pr_pointlist pr_linelist pr_linestrip ' + + 'pr_trianglelist pr_trianglestrip pr_trianglefan bm_complex bm_normal ' + + 'bm_add bm_max bm_subtract bm_zero bm_one bm_src_colour ' + + 'bm_inv_src_colour bm_src_color bm_inv_src_color bm_src_alpha ' + + 'bm_inv_src_alpha bm_dest_alpha bm_inv_dest_alpha bm_dest_colour ' + + 'bm_inv_dest_colour bm_dest_color bm_inv_dest_color bm_src_alpha_sat ' + + 'tf_point tf_linear tf_anisotropic mip_off mip_on mip_markedonly ' + + 'audio_falloff_none audio_falloff_inverse_distance ' + + 'audio_falloff_inverse_distance_clamped audio_falloff_linear_distance ' + + 'audio_falloff_linear_distance_clamped ' + + 'audio_falloff_exponent_distance ' + + 'audio_falloff_exponent_distance_clamped audio_old_system ' + + 'audio_new_system audio_mono audio_stereo audio_3d cr_default cr_none ' + + 'cr_arrow cr_cross cr_beam cr_size_nesw cr_size_ns cr_size_nwse ' + + 'cr_size_we cr_uparrow cr_hourglass cr_drag cr_appstart cr_handpoint ' + + 'cr_size_all spritespeed_framespersecond ' + + 'spritespeed_framespergameframe asset_object asset_unknown ' + + 'asset_sprite asset_sound asset_room asset_path asset_script ' + + 'asset_font asset_timeline asset_tiles asset_shader fa_readonly ' + + 'fa_hidden fa_sysfile fa_volumeid fa_directory fa_archive ' + + 'ds_type_map ds_type_list ds_type_stack ds_type_queue ds_type_grid ' + + 'ds_type_priority ef_explosion ef_ring ef_ellipse ef_firework ' + + 'ef_smoke ef_smokeup ef_star ef_spark ef_flare ef_cloud ef_rain ' + + 'ef_snow pt_shape_pixel pt_shape_disk pt_shape_square pt_shape_line ' + + 'pt_shape_star pt_shape_circle pt_shape_ring pt_shape_sphere ' + + 'pt_shape_flare pt_shape_spark pt_shape_explosion pt_shape_cloud ' + + 'pt_shape_smoke pt_shape_snow ps_distr_linear ps_distr_gaussian ' + + 'ps_distr_invgaussian ps_shape_rectangle ps_shape_ellipse ' + + 'ps_shape_diamond ps_shape_line ty_real ty_string dll_cdecl ' + + 'dll_stdcall matrix_view matrix_projection matrix_world os_win32 ' + + 'os_windows os_macosx os_ios os_android os_symbian os_linux ' + + 'os_unknown os_winphone os_tizen os_win8native ' + + 'os_wiiu os_3ds os_psvita os_bb10 os_ps4 os_xboxone ' + + 'os_ps3 os_xbox360 os_uwp os_tvos os_switch ' + + 'browser_not_a_browser browser_unknown browser_ie browser_firefox ' + + 'browser_chrome browser_safari browser_safari_mobile browser_opera ' + + 'browser_tizen browser_edge browser_windows_store browser_ie_mobile ' + + 'device_ios_unknown device_ios_iphone device_ios_iphone_retina ' + + 'device_ios_ipad device_ios_ipad_retina device_ios_iphone5 ' + + 'device_ios_iphone6 device_ios_iphone6plus device_emulator ' + + 'device_tablet display_landscape display_landscape_flipped ' + + 'display_portrait display_portrait_flipped tm_sleep tm_countvsyncs ' + + 'of_challenge_win of_challen ge_lose of_challenge_tie ' + + 'leaderboard_type_number leaderboard_type_time_mins_secs ' + + 'cmpfunc_never cmpfunc_less cmpfunc_equal cmpfunc_lessequal ' + + 'cmpfunc_greater cmpfunc_notequal cmpfunc_greaterequal cmpfunc_always ' + + 'cull_noculling cull_clockwise cull_counterclockwise lighttype_dir ' + + 'lighttype_point iap_ev_storeload iap_ev_product iap_ev_purchase ' + + 'iap_ev_consume iap_ev_restore iap_storeload_ok iap_storeload_failed ' + + 'iap_status_uninitialised iap_status_unavailable iap_status_loading ' + + 'iap_status_available iap_status_processing iap_status_restoring ' + + 'iap_failed iap_unavailable iap_available iap_purchased iap_canceled ' + + 'iap_refunded fb_login_default fb_login_fallback_to_webview ' + + 'fb_login_no_fallback_to_webview fb_login_forcing_webview ' + + 'fb_login_use_system_account fb_login_forcing_safari ' + + 'phy_joint_anchor_1_x phy_joint_anchor_1_y phy_joint_anchor_2_x ' + + 'phy_joint_anchor_2_y phy_joint_reaction_force_x ' + + 'phy_joint_reaction_force_y phy_joint_reaction_torque ' + + 'phy_joint_motor_speed phy_joint_angle phy_joint_motor_torque ' + + 'phy_joint_max_motor_torque phy_joint_translation phy_joint_speed ' + + 'phy_joint_motor_force phy_joint_max_motor_force phy_joint_length_1 ' + + 'phy_joint_length_2 phy_joint_damping_ratio phy_joint_frequency ' + + 'phy_joint_lower_angle_limit phy_joint_upper_angle_limit ' + + 'phy_joint_angle_limits phy_joint_max_length phy_joint_max_torque ' + + 'phy_joint_max_force phy_debug_render_aabb ' + + 'phy_debug_render_collision_pairs phy_debug_render_coms ' + + 'phy_debug_render_core_shapes phy_debug_render_joints ' + + 'phy_debug_render_obb phy_debug_render_shapes ' + + 'phy_particle_flag_water phy_particle_flag_zombie ' + + 'phy_particle_flag_wall phy_particle_flag_spring ' + + 'phy_particle_flag_elastic phy_particle_flag_viscous ' + + 'phy_particle_flag_powder phy_particle_flag_tensile ' + + 'phy_particle_flag_colourmixing phy_particle_flag_colormixing ' + + 'phy_particle_group_flag_solid phy_particle_group_flag_rigid ' + + 'phy_particle_data_flag_typeflags phy_particle_data_flag_position ' + + 'phy_particle_data_flag_velocity phy_particle_data_flag_colour ' + + 'phy_particle_data_flag_color phy_particle_data_flag_category ' + + 'achievement_our_info achievement_friends_info ' + + 'achievement_leaderboard_info achievement_achievement_info ' + + 'achievement_filter_all_players achievement_filter_friends_only ' + + 'achievement_filter_favorites_only ' + + 'achievement_type_achievement_challenge ' + + 'achievement_type_score_challenge achievement_pic_loaded ' + + 'achievement_show_ui achievement_show_profile ' + + 'achievement_show_leaderboard achievement_show_achievement ' + + 'achievement_show_bank achievement_show_friend_picker ' + + 'achievement_show_purchase_prompt network_socket_tcp ' + + 'network_socket_udp network_socket_bluetooth network_type_connect ' + + 'network_type_disconnect network_type_data ' + + 'network_type_non_blocking_connect network_config_connect_timeout ' + + 'network_config_use_non_blocking_socket ' + + 'network_config_enable_reliable_udp ' + + 'network_config_disable_reliable_udp buffer_fixed buffer_grow ' + + 'buffer_wrap buffer_fast buffer_vbuffer buffer_network buffer_u8 ' + + 'buffer_s8 buffer_u16 buffer_s16 buffer_u32 buffer_s32 buffer_u64 ' + + 'buffer_f16 buffer_f32 buffer_f64 buffer_bool buffer_text ' + + 'buffer_string buffer_surface_copy buffer_seek_start ' + + 'buffer_seek_relative buffer_seek_end ' + + 'buffer_generalerror buffer_outofspace buffer_outofbounds ' + + 'buffer_invalidtype text_type button_type input_type ANSI_CHARSET ' + + 'DEFAULT_CHARSET EASTEUROPE_CHARSET RUSSIAN_CHARSET SYMBOL_CHARSET ' + + 'SHIFTJIS_CHARSET HANGEUL_CHARSET GB2312_CHARSET CHINESEBIG5_CHARSET ' + + 'JOHAB_CHARSET HEBREW_CHARSET ARABIC_CHARSET GREEK_CHARSET ' + + 'TURKISH_CHARSET VIETNAMESE_CHARSET THAI_CHARSET MAC_CHARSET ' + + 'BALTIC_CHARSET OEM_CHARSET gp_face1 gp_face2 gp_face3 gp_face4 ' + + 'gp_shoulderl gp_shoulderr gp_shoulderlb gp_shoulderrb gp_select ' + + 'gp_start gp_stickl gp_stickr gp_padu gp_padd gp_padl gp_padr ' + + 'gp_axislh gp_axislv gp_axisrh gp_axisrv ov_friends ov_community ' + + 'ov_players ov_settings ov_gamegroup ov_achievements lb_sort_none ' + + 'lb_sort_ascending lb_sort_descending lb_disp_none lb_disp_numeric ' + + 'lb_disp_time_sec lb_disp_time_ms ugc_result_success ' + + 'ugc_filetype_community ugc_filetype_microtrans ugc_visibility_public ' + + 'ugc_visibility_friends_only ugc_visibility_private ' + + 'ugc_query_RankedByVote ugc_query_RankedByPublicationDate ' + + 'ugc_query_AcceptedForGameRankedByAcceptanceDate ' + + 'ugc_query_RankedByTrend ' + + 'ugc_query_FavoritedByFriendsRankedByPublicationDate ' + + 'ugc_query_CreatedByFriendsRankedByPublicationDate ' + + 'ugc_query_RankedByNumTimesReported ' + + 'ugc_query_CreatedByFollowedUsersRankedByPublicationDate ' + + 'ugc_query_NotYetRated ugc_query_RankedByTotalVotesAsc ' + + 'ugc_query_RankedByVotesUp ugc_query_RankedByTextSearch ' + + 'ugc_sortorder_CreationOrderDesc ugc_sortorder_CreationOrderAsc ' + + 'ugc_sortorder_TitleAsc ugc_sortorder_LastUpdatedDesc ' + + 'ugc_sortorder_SubscriptionDateDesc ugc_sortorder_VoteScoreDesc ' + + 'ugc_sortorder_ForModeration ugc_list_Published ugc_list_VotedOn ' + + 'ugc_list_VotedUp ugc_list_VotedDown ugc_list_WillVoteLater ' + + 'ugc_list_Favorited ugc_list_Subscribed ugc_list_UsedOrPlayed ' + + 'ugc_list_Followed ugc_match_Items ugc_match_Items_Mtx ' + + 'ugc_match_Items_ReadyToUse ugc_match_Collections ugc_match_Artwork ' + + 'ugc_match_Videos ugc_match_Screenshots ugc_match_AllGuides ' + + 'ugc_match_WebGuides ugc_match_IntegratedGuides ' + + 'ugc_match_UsableInGame ugc_match_ControllerBindings ' + + 'vertex_usage_position vertex_usage_colour vertex_usage_color ' + + 'vertex_usage_normal vertex_usage_texcoord vertex_usage_textcoord ' + + 'vertex_usage_blendweight vertex_usage_blendindices ' + + 'vertex_usage_psize vertex_usage_tangent vertex_usage_binormal ' + + 'vertex_usage_fog vertex_usage_depth vertex_usage_sample ' + + 'vertex_type_float1 vertex_type_float2 vertex_type_float3 ' + + 'vertex_type_float4 vertex_type_colour vertex_type_color ' + + 'vertex_type_ubyte4 layerelementtype_undefined ' + + 'layerelementtype_background layerelementtype_instance ' + + 'layerelementtype_oldtilemap layerelementtype_sprite ' + + 'layerelementtype_tilemap layerelementtype_particlesystem ' + + 'layerelementtype_tile tile_rotate tile_flip tile_mirror ' + + 'tile_index_mask kbv_type_default kbv_type_ascii kbv_type_url ' + + 'kbv_type_email kbv_type_numbers kbv_type_phone kbv_type_phone_name ' + + 'kbv_returnkey_default kbv_returnkey_go kbv_returnkey_google ' + + 'kbv_returnkey_join kbv_returnkey_next kbv_returnkey_route ' + + 'kbv_returnkey_search kbv_returnkey_send kbv_returnkey_yahoo ' + + 'kbv_returnkey_done kbv_returnkey_continue kbv_returnkey_emergency ' + + 'kbv_autocapitalize_none kbv_autocapitalize_words ' + + 'kbv_autocapitalize_sentences kbv_autocapitalize_characters', + symbol: 'argument_relative argument argument0 argument1 argument2 ' + + 'argument3 argument4 argument5 argument6 argument7 argument8 ' + + 'argument9 argument10 argument11 argument12 argument13 argument14 ' + + 'argument15 argument_count x|0 y|0 xprevious yprevious xstart ystart ' + + 'hspeed vspeed direction speed friction gravity gravity_direction ' + + 'path_index path_position path_positionprevious path_speed ' + + 'path_scale path_orientation path_endaction object_index id solid ' + + 'persistent mask_index instance_count instance_id room_speed fps ' + + 'fps_real current_time current_year current_month current_day ' + + 'current_weekday current_hour current_minute current_second alarm ' + + 'timeline_index timeline_position timeline_speed timeline_running ' + + 'timeline_loop room room_first room_last room_width room_height ' + + 'room_caption room_persistent score lives health show_score ' + + 'show_lives show_health caption_score caption_lives caption_health ' + + 'event_type event_number event_object event_action ' + + 'application_surface gamemaker_pro gamemaker_registered ' + + 'gamemaker_version error_occurred error_last debug_mode ' + + 'keyboard_key keyboard_lastkey keyboard_lastchar keyboard_string ' + + 'mouse_x mouse_y mouse_button mouse_lastbutton cursor_sprite ' + + 'visible sprite_index sprite_width sprite_height sprite_xoffset ' + + 'sprite_yoffset image_number image_index image_speed depth ' + + 'image_xscale image_yscale image_angle image_alpha image_blend ' + + 'bbox_left bbox_right bbox_top bbox_bottom layer background_colour ' + + 'background_showcolour background_color background_showcolor ' + + 'view_enabled view_current view_visible view_xview view_yview ' + + 'view_wview view_hview view_xport view_yport view_wport view_hport ' + + 'view_angle view_hborder view_vborder view_hspeed view_vspeed ' + + 'view_object view_surface_id view_camera game_id game_display_name ' + + 'game_project_name game_save_id working_directory temp_directory ' + + 'program_directory browser_width browser_height os_type os_device ' + + 'os_browser os_version display_aa async_load delta_time ' + + 'webgl_enabled event_data iap_data phy_rotation phy_position_x ' + + 'phy_position_y phy_angular_velocity phy_linear_velocity_x ' + + 'phy_linear_velocity_y phy_speed_x phy_speed_y phy_speed ' + + 'phy_angular_damping phy_linear_damping phy_bullet ' + + 'phy_fixed_rotation phy_active phy_mass phy_inertia phy_com_x ' + + 'phy_com_y phy_dynamic phy_kinematic phy_sleeping ' + + 'phy_collision_points phy_collision_x phy_collision_y ' + + 'phy_col_normal_x phy_col_normal_y phy_position_xprevious ' + + 'phy_position_yprevious' + }; + + return { + name: 'GML', + case_insensitive: false, // language is case-insensitive + keywords: GML_KEYWORDS, + + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + hljs.C_NUMBER_MODE + ] + }; +} + +module.exports = gml; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/go.js b/claude-code-source/node_modules/highlight.js/lib/languages/go.js new file mode 100644 index 00000000..4c809922 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/go.js @@ -0,0 +1,74 @@ +/* +Language: Go +Author: Stephan Kountso aka StepLg +Contributors: Evgeny Stepanischev +Description: Google go language (golang). For info about language +Website: http://golang.org/ +Category: common, system +*/ + +function go(hljs) { + const GO_KEYWORDS = { + keyword: + 'break default func interface select case map struct chan else goto package switch ' + + 'const fallthrough if range type continue for import return var go defer ' + + 'bool byte complex64 complex128 float32 float64 int8 int16 int32 int64 string uint8 ' + + 'uint16 uint32 uint64 int uint uintptr rune', + literal: + 'true false iota nil', + built_in: + 'append cap close complex copy imag len make new panic print println real recover delete' + }; + return { + name: 'Go', + aliases: ['golang'], + keywords: GO_KEYWORDS, + illegal: ' +Description: a lightweight dynamic language for the JVM +Website: http://golo-lang.org/ +*/ + +function golo(hljs) { + return { + name: 'Golo', + keywords: { + keyword: + 'println readln print import module function local return let var ' + + 'while for foreach times in case when match with break continue ' + + 'augment augmentation each find filter reduce ' + + 'if then else otherwise try catch finally raise throw orIfNull ' + + 'DynamicObject|10 DynamicVariable struct Observable map set vector list array', + literal: + 'true false null' + }, + contains: [ + hljs.HASH_COMMENT_MODE, + hljs.QUOTE_STRING_MODE, + hljs.C_NUMBER_MODE, + { + className: 'meta', + begin: '@[A-Za-z]+' + } + ] + }; +} + +module.exports = golo; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/gradle.js b/claude-code-source/node_modules/highlight.js/lib/languages/gradle.js new file mode 100644 index 00000000..59b663ea --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/gradle.js @@ -0,0 +1,44 @@ +/* +Language: Gradle +Description: Gradle is an open-source build automation tool focused on flexibility and performance. +Website: https://gradle.org +Author: Damian Mee +*/ + +function gradle(hljs) { + return { + name: 'Gradle', + case_insensitive: true, + keywords: { + keyword: + 'task project allprojects subprojects artifacts buildscript configurations ' + + 'dependencies repositories sourceSets description delete from into include ' + + 'exclude source classpath destinationDir includes options sourceCompatibility ' + + 'targetCompatibility group flatDir doLast doFirst flatten todir fromdir ant ' + + 'def abstract break case catch continue default do else extends final finally ' + + 'for if implements instanceof native new private protected public return static ' + + 'switch synchronized throw throws transient try volatile while strictfp package ' + + 'import false null super this true antlrtask checkstyle codenarc copy boolean ' + + 'byte char class double float int interface long short void compile runTime ' + + 'file fileTree abs any append asList asWritable call collect compareTo count ' + + 'div dump each eachByte eachFile eachLine every find findAll flatten getAt ' + + 'getErr getIn getOut getText grep immutable inject inspect intersect invokeMethods ' + + 'isCase join leftShift minus multiply newInputStream newOutputStream newPrintWriter ' + + 'newReader newWriter next plus pop power previous print println push putAt read ' + + 'readBytes readLines reverse reverseEach round size sort splitEachLine step subMap ' + + 'times toInteger toList tokenize upto waitForOrKill withPrintWriter withReader ' + + 'withStream withWriter withWriterAppend write writeLine' + }, + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + hljs.NUMBER_MODE, + hljs.REGEXP_MODE + + ] + }; +} + +module.exports = gradle; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/groovy.js b/claude-code-source/node_modules/highlight.js/lib/languages/groovy.js new file mode 100644 index 00000000..b6dfd33f --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/groovy.js @@ -0,0 +1,174 @@ +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function lookahead(re) { + return concat('(?=', re, ')'); +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/* + Language: Groovy + Author: Guillaume Laforge + Description: Groovy programming language implementation inspired from Vsevolod's Java mode + Website: https://groovy-lang.org + */ + +function variants(variants, obj = {}) { + obj.variants = variants; + return obj; +} + +function groovy(hljs) { + const IDENT_RE = '[A-Za-z0-9_$]+'; + const COMMENT = variants([ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.COMMENT( + '/\\*\\*', + '\\*/', + { + relevance: 0, + contains: [ + { + // eat up @'s in emails to prevent them to be recognized as doctags + begin: /\w+@/, + relevance: 0 + }, + { + className: 'doctag', + begin: '@[A-Za-z]+' + } + ] + } + ) + ]); + const REGEXP = { + className: 'regexp', + begin: /~?\/[^\/\n]+\//, + contains: [ hljs.BACKSLASH_ESCAPE ] + }; + const NUMBER = variants([ + hljs.BINARY_NUMBER_MODE, + hljs.C_NUMBER_MODE + ]); + const STRING = variants([ + { + begin: /"""/, + end: /"""/ + }, + { + begin: /'''/, + end: /'''/ + }, + { + begin: "\\$/", + end: "/\\$", + relevance: 10 + }, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE + ], + { + className: "string" + } + ); + + return { + name: 'Groovy', + keywords: { + built_in: 'this super', + literal: 'true false null', + keyword: + 'byte short char int long boolean float double void ' + + // groovy specific keywords + 'def as in assert trait ' + + // common keywords with Java + 'abstract static volatile transient public private protected synchronized final ' + + 'class interface enum if else for while switch case break default continue ' + + 'throw throws try catch finally implements extends new import package return instanceof' + }, + contains: [ + hljs.SHEBANG({ + binary: "groovy", + relevance: 10 + }), + COMMENT, + STRING, + REGEXP, + NUMBER, + { + className: 'class', + beginKeywords: 'class interface trait enum', + end: /\{/, + illegal: ':', + contains: [ + { + beginKeywords: 'extends implements' + }, + hljs.UNDERSCORE_TITLE_MODE + ] + }, + { + className: 'meta', + begin: '@[A-Za-z]+', + relevance: 0 + }, + { + // highlight map keys and named parameters as attrs + className: 'attr', + begin: IDENT_RE + '[ \t]*:', + relevance: 0 + }, + { + // catch middle element of the ternary operator + // to avoid highlight it as a label, named parameter, or map key + begin: /\?/, + end: /:/, + relevance: 0, + contains: [ + COMMENT, + STRING, + REGEXP, + NUMBER, + 'self' + ] + }, + { + // highlight labeled statements + className: 'symbol', + begin: '^[ \t]*' + lookahead(IDENT_RE + ':'), + excludeBegin: true, + end: IDENT_RE + ':', + relevance: 0 + } + ], + illegal: /#|<\// + }; +} + +module.exports = groovy; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/haml.js b/claude-code-source/node_modules/highlight.js/lib/languages/haml.js new file mode 100644 index 00000000..cb6a5363 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/haml.js @@ -0,0 +1,117 @@ +/* +Language: HAML +Requires: ruby.js +Author: Dan Allen +Website: http://haml.info +Category: template +*/ + +// TODO support filter tags like :javascript, support inline HTML +function haml(hljs) { + return { + name: 'HAML', + case_insensitive: true, + contains: [ + { + className: 'meta', + begin: '^!!!( (5|1\\.1|Strict|Frameset|Basic|Mobile|RDFa|XML\\b.*))?$', + relevance: 10 + }, + // FIXME these comments should be allowed to span indented lines + hljs.COMMENT( + '^\\s*(!=#|=#|-#|/).*$', + false, + { + relevance: 0 + } + ), + { + begin: '^\\s*(-|=|!=)(?!#)', + starts: { + end: '\\n', + subLanguage: 'ruby' + } + }, + { + className: 'tag', + begin: '^\\s*%', + contains: [ + { + className: 'selector-tag', + begin: '\\w+' + }, + { + className: 'selector-id', + begin: '#[\\w-]+' + }, + { + className: 'selector-class', + begin: '\\.[\\w-]+' + }, + { + begin: /\{\s*/, + end: /\s*\}/, + contains: [ + { + begin: ':\\w+\\s*=>', + end: ',\\s+', + returnBegin: true, + endsWithParent: true, + contains: [ + { + className: 'attr', + begin: ':\\w+' + }, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + { + begin: '\\w+', + relevance: 0 + } + ] + } + ] + }, + { + begin: '\\(\\s*', + end: '\\s*\\)', + excludeEnd: true, + contains: [ + { + begin: '\\w+\\s*=', + end: '\\s+', + returnBegin: true, + endsWithParent: true, + contains: [ + { + className: 'attr', + begin: '\\w+', + relevance: 0 + }, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + { + begin: '\\w+', + relevance: 0 + } + ] + } + ] + } + ] + }, + { + begin: '^\\s*[=~]\\s*' + }, + { + begin: /#\{/, + starts: { + end: /\}/, + subLanguage: 'ruby' + } + } + ] + }; +} + +module.exports = haml; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/handlebars.js b/claude-code-source/node_modules/highlight.js/lib/languages/handlebars.js new file mode 100644 index 00000000..88ae05a8 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/handlebars.js @@ -0,0 +1,324 @@ +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function anyNumberOfTimes(re) { + return concat('(', re, ')*'); +} + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function optional(re) { + return concat('(', re, ')?'); +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/** + * Any of the passed expresssions may match + * + * Creates a huge this | this | that | that match + * @param {(RegExp | string)[] } args + * @returns {string} + */ +function either(...args) { + const joined = '(' + args.map((x) => source(x)).join("|") + ")"; + return joined; +} + +/* +Language: Handlebars +Requires: xml.js +Author: Robin Ward +Description: Matcher for Handlebars as well as EmberJS additions. +Website: https://handlebarsjs.com +Category: template +*/ + +function handlebars(hljs) { + const BUILT_INS = { + 'builtin-name': [ + 'action', + 'bindattr', + 'collection', + 'component', + 'concat', + 'debugger', + 'each', + 'each-in', + 'get', + 'hash', + 'if', + 'in', + 'input', + 'link-to', + 'loc', + 'log', + 'lookup', + 'mut', + 'outlet', + 'partial', + 'query-params', + 'render', + 'template', + 'textarea', + 'unbound', + 'unless', + 'view', + 'with', + 'yield' + ] + }; + + const LITERALS = { + literal: [ + 'true', + 'false', + 'undefined', + 'null' + ] + }; + + // as defined in https://handlebarsjs.com/guide/expressions.html#literal-segments + // this regex matches literal segments like ' abc ' or [ abc ] as well as helpers and paths + // like a/b, ./abc/cde, and abc.bcd + + const DOUBLE_QUOTED_ID_REGEX = /""|"[^"]+"/; + const SINGLE_QUOTED_ID_REGEX = /''|'[^']+'/; + const BRACKET_QUOTED_ID_REGEX = /\[\]|\[[^\]]+\]/; + const PLAIN_ID_REGEX = /[^\s!"#%&'()*+,.\/;<=>@\[\\\]^`{|}~]+/; + const PATH_DELIMITER_REGEX = /(\.|\/)/; + const ANY_ID = either( + DOUBLE_QUOTED_ID_REGEX, + SINGLE_QUOTED_ID_REGEX, + BRACKET_QUOTED_ID_REGEX, + PLAIN_ID_REGEX + ); + + const IDENTIFIER_REGEX = concat( + optional(/\.|\.\/|\//), // relative or absolute path + ANY_ID, + anyNumberOfTimes(concat( + PATH_DELIMITER_REGEX, + ANY_ID + )) + ); + + // identifier followed by a equal-sign (without the equal sign) + const HASH_PARAM_REGEX = concat( + '(', + BRACKET_QUOTED_ID_REGEX, '|', + PLAIN_ID_REGEX, + ')(?==)' + ); + + const HELPER_NAME_OR_PATH_EXPRESSION = { + begin: IDENTIFIER_REGEX, + lexemes: /[\w.\/]+/ + }; + + const HELPER_PARAMETER = hljs.inherit(HELPER_NAME_OR_PATH_EXPRESSION, { + keywords: LITERALS + }); + + const SUB_EXPRESSION = { + begin: /\(/, + end: /\)/ + // the "contains" is added below when all necessary sub-modes are defined + }; + + const HASH = { + // fka "attribute-assignment", parameters of the form 'key=value' + className: 'attr', + begin: HASH_PARAM_REGEX, + relevance: 0, + starts: { + begin: /=/, + end: /=/, + starts: { + contains: [ + hljs.NUMBER_MODE, + hljs.QUOTE_STRING_MODE, + hljs.APOS_STRING_MODE, + HELPER_PARAMETER, + SUB_EXPRESSION + ] + } + } + }; + + const BLOCK_PARAMS = { + // parameters of the form '{{#with x as | y |}}...{{/with}}' + begin: /as\s+\|/, + keywords: { + keyword: 'as' + }, + end: /\|/, + contains: [ + { + // define sub-mode in order to prevent highlighting of block-parameter named "as" + begin: /\w+/ + } + ] + }; + + const HELPER_PARAMETERS = { + contains: [ + hljs.NUMBER_MODE, + hljs.QUOTE_STRING_MODE, + hljs.APOS_STRING_MODE, + BLOCK_PARAMS, + HASH, + HELPER_PARAMETER, + SUB_EXPRESSION + ], + returnEnd: true + // the property "end" is defined through inheritance when the mode is used. If depends + // on the surrounding mode, but "endsWithParent" does not work here (i.e. it includes the + // end-token of the surrounding mode) + }; + + const SUB_EXPRESSION_CONTENTS = hljs.inherit(HELPER_NAME_OR_PATH_EXPRESSION, { + className: 'name', + keywords: BUILT_INS, + starts: hljs.inherit(HELPER_PARAMETERS, { + end: /\)/ + }) + }); + + SUB_EXPRESSION.contains = [SUB_EXPRESSION_CONTENTS]; + + const OPENING_BLOCK_MUSTACHE_CONTENTS = hljs.inherit(HELPER_NAME_OR_PATH_EXPRESSION, { + keywords: BUILT_INS, + className: 'name', + starts: hljs.inherit(HELPER_PARAMETERS, { + end: /\}\}/ + }) + }); + + const CLOSING_BLOCK_MUSTACHE_CONTENTS = hljs.inherit(HELPER_NAME_OR_PATH_EXPRESSION, { + keywords: BUILT_INS, + className: 'name' + }); + + const BASIC_MUSTACHE_CONTENTS = hljs.inherit(HELPER_NAME_OR_PATH_EXPRESSION, { + className: 'name', + keywords: BUILT_INS, + starts: hljs.inherit(HELPER_PARAMETERS, { + end: /\}\}/ + }) + }); + + const ESCAPE_MUSTACHE_WITH_PRECEEDING_BACKSLASH = { + begin: /\\\{\{/, + skip: true + }; + const PREVENT_ESCAPE_WITH_ANOTHER_PRECEEDING_BACKSLASH = { + begin: /\\\\(?=\{\{)/, + skip: true + }; + + return { + name: 'Handlebars', + aliases: [ + 'hbs', + 'html.hbs', + 'html.handlebars', + 'htmlbars' + ], + case_insensitive: true, + subLanguage: 'xml', + contains: [ + ESCAPE_MUSTACHE_WITH_PRECEEDING_BACKSLASH, + PREVENT_ESCAPE_WITH_ANOTHER_PRECEEDING_BACKSLASH, + hljs.COMMENT(/\{\{!--/, /--\}\}/), + hljs.COMMENT(/\{\{!/, /\}\}/), + { + // open raw block "{{{{raw}}}} content not evaluated {{{{/raw}}}}" + className: 'template-tag', + begin: /\{\{\{\{(?!\/)/, + end: /\}\}\}\}/, + contains: [OPENING_BLOCK_MUSTACHE_CONTENTS], + starts: { + end: /\{\{\{\{\//, + returnEnd: true, + subLanguage: 'xml' + } + }, + { + // close raw block + className: 'template-tag', + begin: /\{\{\{\{\//, + end: /\}\}\}\}/, + contains: [CLOSING_BLOCK_MUSTACHE_CONTENTS] + }, + { + // open block statement + className: 'template-tag', + begin: /\{\{#/, + end: /\}\}/, + contains: [OPENING_BLOCK_MUSTACHE_CONTENTS] + }, + { + className: 'template-tag', + begin: /\{\{(?=else\}\})/, + end: /\}\}/, + keywords: 'else' + }, + { + className: 'template-tag', + begin: /\{\{(?=else if)/, + end: /\}\}/, + keywords: 'else if' + }, + { + // closing block statement + className: 'template-tag', + begin: /\{\{\//, + end: /\}\}/, + contains: [CLOSING_BLOCK_MUSTACHE_CONTENTS] + }, + { + // template variable or helper-call that is NOT html-escaped + className: 'template-variable', + begin: /\{\{\{/, + end: /\}\}\}/, + contains: [BASIC_MUSTACHE_CONTENTS] + }, + { + // template variable or helper-call that is html-escaped + className: 'template-variable', + begin: /\{\{/, + end: /\}\}/, + contains: [BASIC_MUSTACHE_CONTENTS] + } + ] + }; +} + +module.exports = handlebars; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/haskell.js b/claude-code-source/node_modules/highlight.js/lib/languages/haskell.js new file mode 100644 index 00000000..5d6a3673 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/haskell.js @@ -0,0 +1,173 @@ +/* +Language: Haskell +Author: Jeremy Hull +Contributors: Zena Treep +Website: https://www.haskell.org +Category: functional +*/ + +function haskell(hljs) { + const COMMENT = { + variants: [ + hljs.COMMENT('--', '$'), + hljs.COMMENT( + /\{-/, + /-\}/, + { + contains: ['self'] + } + ) + ] + }; + + const PRAGMA = { + className: 'meta', + begin: /\{-#/, + end: /#-\}/ + }; + + const PREPROCESSOR = { + className: 'meta', + begin: '^#', + end: '$' + }; + + const CONSTRUCTOR = { + className: 'type', + begin: '\\b[A-Z][\\w\']*', // TODO: other constructors (build-in, infix). + relevance: 0 + }; + + const LIST = { + begin: '\\(', + end: '\\)', + illegal: '"', + contains: [ + PRAGMA, + PREPROCESSOR, + { + className: 'type', + begin: '\\b[A-Z][\\w]*(\\((\\.\\.|,|\\w+)\\))?' + }, + hljs.inherit(hljs.TITLE_MODE, { + begin: '[_a-z][\\w\']*' + }), + COMMENT + ] + }; + + const RECORD = { + begin: /\{/, + end: /\}/, + contains: LIST.contains + }; + + return { + name: 'Haskell', + aliases: ['hs'], + keywords: + 'let in if then else case of where do module import hiding ' + + 'qualified type data newtype deriving class instance as default ' + + 'infix infixl infixr foreign export ccall stdcall cplusplus ' + + 'jvm dotnet safe unsafe family forall mdo proc rec', + contains: [ + // Top-level constructions. + { + beginKeywords: 'module', + end: 'where', + keywords: 'module where', + contains: [ + LIST, + COMMENT + ], + illegal: '\\W\\.|;' + }, + { + begin: '\\bimport\\b', + end: '$', + keywords: 'import qualified as hiding', + contains: [ + LIST, + COMMENT + ], + illegal: '\\W\\.|;' + }, + { + className: 'class', + begin: '^(\\s*)?(class|instance)\\b', + end: 'where', + keywords: 'class family instance where', + contains: [ + CONSTRUCTOR, + LIST, + COMMENT + ] + }, + { + className: 'class', + begin: '\\b(data|(new)?type)\\b', + end: '$', + keywords: 'data family type newtype deriving', + contains: [ + PRAGMA, + CONSTRUCTOR, + LIST, + RECORD, + COMMENT + ] + }, + { + beginKeywords: 'default', + end: '$', + contains: [ + CONSTRUCTOR, + LIST, + COMMENT + ] + }, + { + beginKeywords: 'infix infixl infixr', + end: '$', + contains: [ + hljs.C_NUMBER_MODE, + COMMENT + ] + }, + { + begin: '\\bforeign\\b', + end: '$', + keywords: 'foreign import export ccall stdcall cplusplus jvm ' + + 'dotnet safe unsafe', + contains: [ + CONSTRUCTOR, + hljs.QUOTE_STRING_MODE, + COMMENT + ] + }, + { + className: 'meta', + begin: '#!\\/usr\\/bin\\/env\ runhaskell', + end: '$' + }, + // "Whitespaces". + PRAGMA, + PREPROCESSOR, + + // Literals and names. + + // TODO: characters. + hljs.QUOTE_STRING_MODE, + hljs.C_NUMBER_MODE, + CONSTRUCTOR, + hljs.inherit(hljs.TITLE_MODE, { + begin: '^[_a-z][\\w\']*' + }), + COMMENT, + { // No markup, relevance booster + begin: '->|<-' + } + ] + }; +} + +module.exports = haskell; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/haxe.js b/claude-code-source/node_modules/highlight.js/lib/languages/haxe.js new file mode 100644 index 00000000..10045b37 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/haxe.js @@ -0,0 +1,157 @@ +/* +Language: Haxe +Description: Haxe is an open source toolkit based on a modern, high level, strictly typed programming language. +Author: Christopher Kaster (Based on the actionscript.js language file by Alexander Myadzel) +Contributors: Kenton Hamaluik +Website: https://haxe.org +*/ + +function haxe(hljs) { + + const HAXE_BASIC_TYPES = 'Int Float String Bool Dynamic Void Array '; + + return { + name: 'Haxe', + aliases: ['hx'], + keywords: { + keyword: 'break case cast catch continue default do dynamic else enum extern ' + + 'for function here if import in inline never new override package private get set ' + + 'public return static super switch this throw trace try typedef untyped using var while ' + + HAXE_BASIC_TYPES, + built_in: + 'trace this', + literal: + 'true false null _' + }, + contains: [ + { + className: 'string', // interpolate-able strings + begin: '\'', + end: '\'', + contains: [ + hljs.BACKSLASH_ESCAPE, + { + className: 'subst', // interpolation + begin: '\\$\\{', + end: '\\}' + }, + { + className: 'subst', // interpolation + begin: '\\$', + end: /\W\}/ + } + ] + }, + hljs.QUOTE_STRING_MODE, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.C_NUMBER_MODE, + { + className: 'meta', // compiler meta + begin: '@:', + end: '$' + }, + { + className: 'meta', // compiler conditionals + begin: '#', + end: '$', + keywords: { + 'meta-keyword': 'if else elseif end error' + } + }, + { + className: 'type', // function types + begin: ':[ \t]*', + end: '[^A-Za-z0-9_ \t\\->]', + excludeBegin: true, + excludeEnd: true, + relevance: 0 + }, + { + className: 'type', // types + begin: ':[ \t]*', + end: '\\W', + excludeBegin: true, + excludeEnd: true + }, + { + className: 'type', // instantiation + begin: 'new *', + end: '\\W', + excludeBegin: true, + excludeEnd: true + }, + { + className: 'class', // enums + beginKeywords: 'enum', + end: '\\{', + contains: [hljs.TITLE_MODE] + }, + { + className: 'class', // abstracts + beginKeywords: 'abstract', + end: '[\\{$]', + contains: [ + { + className: 'type', + begin: '\\(', + end: '\\)', + excludeBegin: true, + excludeEnd: true + }, + { + className: 'type', + begin: 'from +', + end: '\\W', + excludeBegin: true, + excludeEnd: true + }, + { + className: 'type', + begin: 'to +', + end: '\\W', + excludeBegin: true, + excludeEnd: true + }, + hljs.TITLE_MODE + ], + keywords: { + keyword: 'abstract from to' + } + }, + { + className: 'class', // classes + begin: '\\b(class|interface) +', + end: '[\\{$]', + excludeEnd: true, + keywords: 'class interface', + contains: [ + { + className: 'keyword', + begin: '\\b(extends|implements) +', + keywords: 'extends implements', + contains: [ + { + className: 'type', + begin: hljs.IDENT_RE, + relevance: 0 + } + ] + }, + hljs.TITLE_MODE + ] + }, + { + className: 'function', + beginKeywords: 'function', + end: '\\(', + excludeEnd: true, + illegal: '\\S', + contains: [hljs.TITLE_MODE] + } + ], + illegal: /<\// + }; +} + +module.exports = haxe; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/hsp.js b/claude-code-source/node_modules/highlight.js/lib/languages/hsp.js new file mode 100644 index 00000000..d2c09d6c --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/hsp.js @@ -0,0 +1,65 @@ +/* +Language: HSP +Author: prince +Website: https://en.wikipedia.org/wiki/Hot_Soup_Processor +Category: scripting +*/ + +function hsp(hljs) { + return { + name: 'HSP', + case_insensitive: true, + keywords: { + $pattern: /[\w._]+/, + keyword: 'goto gosub return break repeat loop continue wait await dim sdim foreach dimtype dup dupptr end stop newmod delmod mref run exgoto on mcall assert logmes newlab resume yield onexit onerror onkey onclick oncmd exist delete mkdir chdir dirlist bload bsave bcopy memfile if else poke wpoke lpoke getstr chdpm memexpand memcpy memset notesel noteadd notedel noteload notesave randomize noteunsel noteget split strrep setease button chgdisp exec dialog mmload mmplay mmstop mci pset pget syscolor mes print title pos circle cls font sysfont objsize picload color palcolor palette redraw width gsel gcopy gzoom gmode bmpsave hsvcolor getkey listbox chkbox combox input mesbox buffer screen bgscr mouse objsel groll line clrobj boxf objprm objmode stick grect grotate gsquare gradf objimage objskip objenable celload celdiv celput newcom querycom delcom cnvstow comres axobj winobj sendmsg comevent comevarg sarrayconv callfunc cnvwtos comevdisp libptr system hspstat hspver stat cnt err strsize looplev sublev iparam wparam lparam refstr refdval int rnd strlen length length2 length3 length4 vartype gettime peek wpeek lpeek varptr varuse noteinfo instr abs limit getease str strmid strf getpath strtrim sin cos tan atan sqrt double absf expf logf limitf powf geteasef mousex mousey mousew hwnd hinstance hdc ginfo objinfo dirinfo sysinfo thismod __hspver__ __hsp30__ __date__ __time__ __line__ __file__ _debug __hspdef__ and or xor not screen_normal screen_palette screen_hide screen_fixedsize screen_tool screen_frame gmode_gdi gmode_mem gmode_rgb0 gmode_alpha gmode_rgb0alpha gmode_add gmode_sub gmode_pixela ginfo_mx ginfo_my ginfo_act ginfo_sel ginfo_wx1 ginfo_wy1 ginfo_wx2 ginfo_wy2 ginfo_vx ginfo_vy ginfo_sizex ginfo_sizey ginfo_winx ginfo_winy ginfo_mesx ginfo_mesy ginfo_r ginfo_g ginfo_b ginfo_paluse ginfo_dispx ginfo_dispy ginfo_cx ginfo_cy ginfo_intid ginfo_newid ginfo_sx ginfo_sy objinfo_mode objinfo_bmscr objinfo_hwnd notemax notesize dir_cur dir_exe dir_win dir_sys dir_cmdline dir_desktop dir_mydoc dir_tv font_normal font_bold font_italic font_underline font_strikeout font_antialias objmode_normal objmode_guifont objmode_usefont gsquare_grad msgothic msmincho do until while wend for next _break _continue switch case default swbreak swend ddim ldim alloc m_pi rad2deg deg2rad ease_linear ease_quad_in ease_quad_out ease_quad_inout ease_cubic_in ease_cubic_out ease_cubic_inout ease_quartic_in ease_quartic_out ease_quartic_inout ease_bounce_in ease_bounce_out ease_bounce_inout ease_shake_in ease_shake_out ease_shake_inout ease_loop' + }, + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.QUOTE_STRING_MODE, + hljs.APOS_STRING_MODE, + + { + // multi-line string + className: 'string', + begin: /\{"/, + end: /"\}/, + contains: [hljs.BACKSLASH_ESCAPE] + }, + + hljs.COMMENT(';', '$', { + relevance: 0 + }), + + { + // pre-processor + className: 'meta', + begin: '#', + end: '$', + keywords: { + 'meta-keyword': 'addion cfunc cmd cmpopt comfunc const defcfunc deffunc define else endif enum epack func global if ifdef ifndef include modcfunc modfunc modinit modterm module pack packopt regcmd runtime undef usecom uselib' + }, + contains: [ + hljs.inherit(hljs.QUOTE_STRING_MODE, { + className: 'meta-string' + }), + hljs.NUMBER_MODE, + hljs.C_NUMBER_MODE, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE + ] + }, + + { + // label + className: 'symbol', + begin: '^\\*(\\w+|@)' + }, + + hljs.NUMBER_MODE, + hljs.C_NUMBER_MODE + ] + }; +} + +module.exports = hsp; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/htmlbars.js b/claude-code-source/node_modules/highlight.js/lib/languages/htmlbars.js new file mode 100644 index 00000000..7fb718c2 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/htmlbars.js @@ -0,0 +1,352 @@ +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function anyNumberOfTimes(re) { + return concat('(', re, ')*'); +} + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function optional(re) { + return concat('(', re, ')?'); +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/** + * Any of the passed expresssions may match + * + * Creates a huge this | this | that | that match + * @param {(RegExp | string)[] } args + * @returns {string} + */ +function either(...args) { + const joined = '(' + args.map((x) => source(x)).join("|") + ")"; + return joined; +} + +/* +Language: Handlebars +Requires: xml.js +Author: Robin Ward +Description: Matcher for Handlebars as well as EmberJS additions. +Website: https://handlebarsjs.com +Category: template +*/ + +function handlebars(hljs) { + const BUILT_INS = { + 'builtin-name': [ + 'action', + 'bindattr', + 'collection', + 'component', + 'concat', + 'debugger', + 'each', + 'each-in', + 'get', + 'hash', + 'if', + 'in', + 'input', + 'link-to', + 'loc', + 'log', + 'lookup', + 'mut', + 'outlet', + 'partial', + 'query-params', + 'render', + 'template', + 'textarea', + 'unbound', + 'unless', + 'view', + 'with', + 'yield' + ] + }; + + const LITERALS = { + literal: [ + 'true', + 'false', + 'undefined', + 'null' + ] + }; + + // as defined in https://handlebarsjs.com/guide/expressions.html#literal-segments + // this regex matches literal segments like ' abc ' or [ abc ] as well as helpers and paths + // like a/b, ./abc/cde, and abc.bcd + + const DOUBLE_QUOTED_ID_REGEX = /""|"[^"]+"/; + const SINGLE_QUOTED_ID_REGEX = /''|'[^']+'/; + const BRACKET_QUOTED_ID_REGEX = /\[\]|\[[^\]]+\]/; + const PLAIN_ID_REGEX = /[^\s!"#%&'()*+,.\/;<=>@\[\\\]^`{|}~]+/; + const PATH_DELIMITER_REGEX = /(\.|\/)/; + const ANY_ID = either( + DOUBLE_QUOTED_ID_REGEX, + SINGLE_QUOTED_ID_REGEX, + BRACKET_QUOTED_ID_REGEX, + PLAIN_ID_REGEX + ); + + const IDENTIFIER_REGEX = concat( + optional(/\.|\.\/|\//), // relative or absolute path + ANY_ID, + anyNumberOfTimes(concat( + PATH_DELIMITER_REGEX, + ANY_ID + )) + ); + + // identifier followed by a equal-sign (without the equal sign) + const HASH_PARAM_REGEX = concat( + '(', + BRACKET_QUOTED_ID_REGEX, '|', + PLAIN_ID_REGEX, + ')(?==)' + ); + + const HELPER_NAME_OR_PATH_EXPRESSION = { + begin: IDENTIFIER_REGEX, + lexemes: /[\w.\/]+/ + }; + + const HELPER_PARAMETER = hljs.inherit(HELPER_NAME_OR_PATH_EXPRESSION, { + keywords: LITERALS + }); + + const SUB_EXPRESSION = { + begin: /\(/, + end: /\)/ + // the "contains" is added below when all necessary sub-modes are defined + }; + + const HASH = { + // fka "attribute-assignment", parameters of the form 'key=value' + className: 'attr', + begin: HASH_PARAM_REGEX, + relevance: 0, + starts: { + begin: /=/, + end: /=/, + starts: { + contains: [ + hljs.NUMBER_MODE, + hljs.QUOTE_STRING_MODE, + hljs.APOS_STRING_MODE, + HELPER_PARAMETER, + SUB_EXPRESSION + ] + } + } + }; + + const BLOCK_PARAMS = { + // parameters of the form '{{#with x as | y |}}...{{/with}}' + begin: /as\s+\|/, + keywords: { + keyword: 'as' + }, + end: /\|/, + contains: [ + { + // define sub-mode in order to prevent highlighting of block-parameter named "as" + begin: /\w+/ + } + ] + }; + + const HELPER_PARAMETERS = { + contains: [ + hljs.NUMBER_MODE, + hljs.QUOTE_STRING_MODE, + hljs.APOS_STRING_MODE, + BLOCK_PARAMS, + HASH, + HELPER_PARAMETER, + SUB_EXPRESSION + ], + returnEnd: true + // the property "end" is defined through inheritance when the mode is used. If depends + // on the surrounding mode, but "endsWithParent" does not work here (i.e. it includes the + // end-token of the surrounding mode) + }; + + const SUB_EXPRESSION_CONTENTS = hljs.inherit(HELPER_NAME_OR_PATH_EXPRESSION, { + className: 'name', + keywords: BUILT_INS, + starts: hljs.inherit(HELPER_PARAMETERS, { + end: /\)/ + }) + }); + + SUB_EXPRESSION.contains = [SUB_EXPRESSION_CONTENTS]; + + const OPENING_BLOCK_MUSTACHE_CONTENTS = hljs.inherit(HELPER_NAME_OR_PATH_EXPRESSION, { + keywords: BUILT_INS, + className: 'name', + starts: hljs.inherit(HELPER_PARAMETERS, { + end: /\}\}/ + }) + }); + + const CLOSING_BLOCK_MUSTACHE_CONTENTS = hljs.inherit(HELPER_NAME_OR_PATH_EXPRESSION, { + keywords: BUILT_INS, + className: 'name' + }); + + const BASIC_MUSTACHE_CONTENTS = hljs.inherit(HELPER_NAME_OR_PATH_EXPRESSION, { + className: 'name', + keywords: BUILT_INS, + starts: hljs.inherit(HELPER_PARAMETERS, { + end: /\}\}/ + }) + }); + + const ESCAPE_MUSTACHE_WITH_PRECEEDING_BACKSLASH = { + begin: /\\\{\{/, + skip: true + }; + const PREVENT_ESCAPE_WITH_ANOTHER_PRECEEDING_BACKSLASH = { + begin: /\\\\(?=\{\{)/, + skip: true + }; + + return { + name: 'Handlebars', + aliases: [ + 'hbs', + 'html.hbs', + 'html.handlebars', + 'htmlbars' + ], + case_insensitive: true, + subLanguage: 'xml', + contains: [ + ESCAPE_MUSTACHE_WITH_PRECEEDING_BACKSLASH, + PREVENT_ESCAPE_WITH_ANOTHER_PRECEEDING_BACKSLASH, + hljs.COMMENT(/\{\{!--/, /--\}\}/), + hljs.COMMENT(/\{\{!/, /\}\}/), + { + // open raw block "{{{{raw}}}} content not evaluated {{{{/raw}}}}" + className: 'template-tag', + begin: /\{\{\{\{(?!\/)/, + end: /\}\}\}\}/, + contains: [OPENING_BLOCK_MUSTACHE_CONTENTS], + starts: { + end: /\{\{\{\{\//, + returnEnd: true, + subLanguage: 'xml' + } + }, + { + // close raw block + className: 'template-tag', + begin: /\{\{\{\{\//, + end: /\}\}\}\}/, + contains: [CLOSING_BLOCK_MUSTACHE_CONTENTS] + }, + { + // open block statement + className: 'template-tag', + begin: /\{\{#/, + end: /\}\}/, + contains: [OPENING_BLOCK_MUSTACHE_CONTENTS] + }, + { + className: 'template-tag', + begin: /\{\{(?=else\}\})/, + end: /\}\}/, + keywords: 'else' + }, + { + className: 'template-tag', + begin: /\{\{(?=else if)/, + end: /\}\}/, + keywords: 'else if' + }, + { + // closing block statement + className: 'template-tag', + begin: /\{\{\//, + end: /\}\}/, + contains: [CLOSING_BLOCK_MUSTACHE_CONTENTS] + }, + { + // template variable or helper-call that is NOT html-escaped + className: 'template-variable', + begin: /\{\{\{/, + end: /\}\}\}/, + contains: [BASIC_MUSTACHE_CONTENTS] + }, + { + // template variable or helper-call that is html-escaped + className: 'template-variable', + begin: /\{\{/, + end: /\}\}/, + contains: [BASIC_MUSTACHE_CONTENTS] + } + ] + }; +} + +/* + Language: HTMLBars (legacy) + Requires: xml.js + Description: Matcher for Handlebars as well as EmberJS additions. + Website: https://github.com/tildeio/htmlbars + Category: template + */ + +function htmlbars(hljs) { + const definition = handlebars(hljs); + + definition.name = "HTMLbars"; + + // HACK: This lets handlebars do the auto-detection if it's been loaded (by + // default the build script will load in alphabetical order) and if not (perhaps + // an install is only using `htmlbars`, not `handlebars`) then this will still + // allow HTMLBars to participate in the auto-detection + + // worse case someone will have HTMLbars and handlebars competing for the same + // content and will need to change their setup to only require handlebars, but + // I don't consider this a breaking change + if (hljs.getLanguage("handlebars")) { + definition.disableAutodetect = true; + } + + return definition; +} + +module.exports = htmlbars; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/http.js b/claude-code-source/node_modules/highlight.js/lib/languages/http.js new file mode 100644 index 00000000..d9c3681a --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/http.js @@ -0,0 +1,121 @@ +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/* +Language: HTTP +Description: HTTP request and response headers with automatic body highlighting +Author: Ivan Sagalaev +Category: common, protocols +Website: https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview +*/ + +function http(hljs) { + const VERSION = 'HTTP/(2|1\\.[01])'; + const HEADER_NAME = /[A-Za-z][A-Za-z0-9-]*/; + const HEADER = { + className: 'attribute', + begin: concat('^', HEADER_NAME, '(?=\\:\\s)'), + starts: { + contains: [ + { + className: "punctuation", + begin: /: /, + relevance: 0, + starts: { + end: '$', + relevance: 0 + } + } + ] + } + }; + const HEADERS_AND_BODY = [ + HEADER, + { + begin: '\\n\\n', + starts: { subLanguage: [], endsWithParent: true } + } + ]; + + return { + name: 'HTTP', + aliases: ['https'], + illegal: /\S/, + contains: [ + // response + { + begin: '^(?=' + VERSION + " \\d{3})", + end: /$/, + contains: [ + { + className: "meta", + begin: VERSION + }, + { + className: 'number', begin: '\\b\\d{3}\\b' + } + ], + starts: { + end: /\b\B/, + illegal: /\S/, + contains: HEADERS_AND_BODY + } + }, + // request + { + begin: '(?=^[A-Z]+ (.*?) ' + VERSION + '$)', + end: /$/, + contains: [ + { + className: 'string', + begin: ' ', + end: ' ', + excludeBegin: true, + excludeEnd: true + }, + { + className: "meta", + begin: VERSION + }, + { + className: 'keyword', + begin: '[A-Z]+' + } + ], + starts: { + end: /\b\B/, + illegal: /\S/, + contains: HEADERS_AND_BODY + } + }, + // to allow headers to work even without a preamble + hljs.inherit(HEADER, { + relevance: 0 + }) + ] + }; +} + +module.exports = http; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/hy.js b/claude-code-source/node_modules/highlight.js/lib/languages/hy.js new file mode 100644 index 00000000..43ff6ba3 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/hy.js @@ -0,0 +1,109 @@ +/* +Language: Hy +Description: Hy is a wonderful dialect of Lisp that’s embedded in Python. +Author: Sergey Sobko +Website: http://docs.hylang.org/en/stable/ +Category: lisp +*/ + +function hy(hljs) { + var SYMBOLSTART = 'a-zA-Z_\\-!.?+*=<>&#\''; + var SYMBOL_RE = '[' + SYMBOLSTART + '][' + SYMBOLSTART + '0-9/;:]*'; + var keywords = { + $pattern: SYMBOL_RE, + 'builtin-name': + // keywords + '!= % %= & &= * ** **= *= *map ' + + '+ += , --build-class-- --import-- -= . / // //= ' + + '/= < << <<= <= = > >= >> >>= ' + + '@ @= ^ ^= abs accumulate all and any ap-compose ' + + 'ap-dotimes ap-each ap-each-while ap-filter ap-first ap-if ap-last ap-map ap-map-when ap-pipe ' + + 'ap-reduce ap-reject apply as-> ascii assert assoc bin break butlast ' + + 'callable calling-module-name car case cdr chain chr coll? combinations compile ' + + 'compress cond cons cons? continue count curry cut cycle dec ' + + 'def default-method defclass defmacro defmacro-alias defmacro/g! defmain defmethod defmulti defn ' + + 'defn-alias defnc defnr defreader defseq del delattr delete-route dict-comp dir ' + + 'disassemble dispatch-reader-macro distinct divmod do doto drop drop-last drop-while empty? ' + + 'end-sequence eval eval-and-compile eval-when-compile even? every? except exec filter first ' + + 'flatten float? fn fnc fnr for for* format fraction genexpr ' + + 'gensym get getattr global globals group-by hasattr hash hex id ' + + 'identity if if* if-not if-python2 import in inc input instance? ' + + 'integer integer-char? integer? interleave interpose is is-coll is-cons is-empty is-even ' + + 'is-every is-float is-instance is-integer is-integer-char is-iterable is-iterator is-keyword is-neg is-none ' + + 'is-not is-numeric is-odd is-pos is-string is-symbol is-zero isinstance islice issubclass ' + + 'iter iterable? iterate iterator? keyword keyword? lambda last len let ' + + 'lif lif-not list* list-comp locals loop macro-error macroexpand macroexpand-1 macroexpand-all ' + + 'map max merge-with method-decorator min multi-decorator multicombinations name neg? next ' + + 'none? nonlocal not not-in not? nth numeric? oct odd? open ' + + 'or ord partition permutations pos? post-route postwalk pow prewalk print ' + + 'product profile/calls profile/cpu put-route quasiquote quote raise range read read-str ' + + 'recursive-replace reduce remove repeat repeatedly repr require rest round route ' + + 'route-with-methods rwm second seq set-comp setattr setv some sorted string ' + + 'string? sum switch symbol? take take-nth take-while tee try unless ' + + 'unquote unquote-splicing vars walk when while with with* with-decorator with-gensyms ' + + 'xi xor yield yield-from zero? zip zip-longest | |= ~' + }; + + var SIMPLE_NUMBER_RE = '[-+]?\\d+(\\.\\d+)?'; + + var SYMBOL = { + begin: SYMBOL_RE, + relevance: 0 + }; + var NUMBER = { + className: 'number', begin: SIMPLE_NUMBER_RE, + relevance: 0 + }; + var STRING = hljs.inherit(hljs.QUOTE_STRING_MODE, {illegal: null}); + var COMMENT = hljs.COMMENT( + ';', + '$', + { + relevance: 0 + } + ); + var LITERAL = { + className: 'literal', + begin: /\b([Tt]rue|[Ff]alse|nil|None)\b/ + }; + var COLLECTION = { + begin: '[\\[\\{]', end: '[\\]\\}]' + }; + var HINT = { + className: 'comment', + begin: '\\^' + SYMBOL_RE + }; + var HINT_COL = hljs.COMMENT('\\^\\{', '\\}'); + var KEY = { + className: 'symbol', + begin: '[:]{1,2}' + SYMBOL_RE + }; + var LIST = { + begin: '\\(', end: '\\)' + }; + var BODY = { + endsWithParent: true, + relevance: 0 + }; + var NAME = { + className: 'name', + relevance: 0, + keywords: keywords, + begin: SYMBOL_RE, + starts: BODY + }; + var DEFAULT_CONTAINS = [LIST, STRING, HINT, HINT_COL, COMMENT, KEY, COLLECTION, NUMBER, LITERAL, SYMBOL]; + + LIST.contains = [hljs.COMMENT('comment', ''), NAME, BODY]; + BODY.contains = DEFAULT_CONTAINS; + COLLECTION.contains = DEFAULT_CONTAINS; + + return { + name: 'Hy', + aliases: ['hylang'], + illegal: /\S/, + contains: [hljs.SHEBANG(), LIST, STRING, HINT, HINT_COL, COMMENT, KEY, COLLECTION, NUMBER, LITERAL] + }; +} + +module.exports = hy; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/inform7.js b/claude-code-source/node_modules/highlight.js/lib/languages/inform7.js new file mode 100644 index 00000000..8570468b --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/inform7.js @@ -0,0 +1,70 @@ +/* +Language: Inform 7 +Author: Bruno Dias +Description: Language definition for Inform 7, a DSL for writing parser interactive fiction. +Website: http://inform7.com +*/ + +function inform7(hljs) { + const START_BRACKET = '\\['; + const END_BRACKET = '\\]'; + return { + name: 'Inform 7', + aliases: ['i7'], + case_insensitive: true, + keywords: { + // Some keywords more or less unique to I7, for relevance. + keyword: + // kind: + 'thing room person man woman animal container ' + + 'supporter backdrop door ' + + // characteristic: + 'scenery open closed locked inside gender ' + + // verb: + 'is are say understand ' + + // misc keyword: + 'kind of rule' + }, + contains: [ + { + className: 'string', + begin: '"', + end: '"', + relevance: 0, + contains: [ + { + className: 'subst', + begin: START_BRACKET, + end: END_BRACKET + } + ] + }, + { + className: 'section', + begin: /^(Volume|Book|Part|Chapter|Section|Table)\b/, + end: '$' + }, + { + // Rule definition + // This is here for relevance. + begin: /^(Check|Carry out|Report|Instead of|To|Rule|When|Before|After)\b/, + end: ':', + contains: [ + { + // Rule name + begin: '\\(This', + end: '\\)' + } + ] + }, + { + className: 'comment', + begin: START_BRACKET, + end: END_BRACKET, + contains: ['self'] + } + ] + }; +} + +module.exports = inform7; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/ini.js b/claude-code-source/node_modules/highlight.js/lib/languages/ini.js new file mode 100644 index 00000000..1e027314 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/ini.js @@ -0,0 +1,173 @@ +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function lookahead(re) { + return concat('(?=', re, ')'); +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/** + * Any of the passed expresssions may match + * + * Creates a huge this | this | that | that match + * @param {(RegExp | string)[] } args + * @returns {string} + */ +function either(...args) { + const joined = '(' + args.map((x) => source(x)).join("|") + ")"; + return joined; +} + +/* +Language: TOML, also INI +Description: TOML aims to be a minimal configuration file format that's easy to read due to obvious semantics. +Contributors: Guillaume Gomez +Category: common, config +Website: https://github.com/toml-lang/toml +*/ + +function ini(hljs) { + const NUMBERS = { + className: 'number', + relevance: 0, + variants: [ + { + begin: /([+-]+)?[\d]+_[\d_]+/ + }, + { + begin: hljs.NUMBER_RE + } + ] + }; + const COMMENTS = hljs.COMMENT(); + COMMENTS.variants = [ + { + begin: /;/, + end: /$/ + }, + { + begin: /#/, + end: /$/ + } + ]; + const VARIABLES = { + className: 'variable', + variants: [ + { + begin: /\$[\w\d"][\w\d_]*/ + }, + { + begin: /\$\{(.*?)\}/ + } + ] + }; + const LITERALS = { + className: 'literal', + begin: /\bon|off|true|false|yes|no\b/ + }; + const STRINGS = { + className: "string", + contains: [hljs.BACKSLASH_ESCAPE], + variants: [ + { + begin: "'''", + end: "'''", + relevance: 10 + }, + { + begin: '"""', + end: '"""', + relevance: 10 + }, + { + begin: '"', + end: '"' + }, + { + begin: "'", + end: "'" + } + ] + }; + const ARRAY = { + begin: /\[/, + end: /\]/, + contains: [ + COMMENTS, + LITERALS, + VARIABLES, + STRINGS, + NUMBERS, + 'self' + ], + relevance: 0 + }; + + const BARE_KEY = /[A-Za-z0-9_-]+/; + const QUOTED_KEY_DOUBLE_QUOTE = /"(\\"|[^"])*"/; + const QUOTED_KEY_SINGLE_QUOTE = /'[^']*'/; + const ANY_KEY = either( + BARE_KEY, QUOTED_KEY_DOUBLE_QUOTE, QUOTED_KEY_SINGLE_QUOTE + ); + const DOTTED_KEY = concat( + ANY_KEY, '(\\s*\\.\\s*', ANY_KEY, ')*', + lookahead(/\s*=\s*[^#\s]/) + ); + + return { + name: 'TOML, also INI', + aliases: ['toml'], + case_insensitive: true, + illegal: /\S/, + contains: [ + COMMENTS, + { + className: 'section', + begin: /\[+/, + end: /\]+/ + }, + { + begin: DOTTED_KEY, + className: 'attr', + starts: { + end: /$/, + contains: [ + COMMENTS, + ARRAY, + LITERALS, + VARIABLES, + STRINGS, + NUMBERS + ] + } + } + ] + }; +} + +module.exports = ini; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/irpf90.js b/claude-code-source/node_modules/highlight.js/lib/languages/irpf90.js new file mode 100644 index 00000000..1f2a27af --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/irpf90.js @@ -0,0 +1,141 @@ +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/* +Language: IRPF90 +Author: Anthony Scemama +Description: IRPF90 is an open-source Fortran code generator +Website: http://irpf90.ups-tlse.fr +Category: scientific +*/ + +/** @type LanguageFn */ +function irpf90(hljs) { + const PARAMS = { + className: 'params', + begin: '\\(', + end: '\\)' + }; + + // regex in both fortran and irpf90 should match + const OPTIONAL_NUMBER_SUFFIX = /(_[a-z_\d]+)?/; + const OPTIONAL_NUMBER_EXP = /([de][+-]?\d+)?/; + const NUMBER = { + className: 'number', + variants: [ + { + begin: concat(/\b\d+/, /\.(\d*)/, OPTIONAL_NUMBER_EXP, OPTIONAL_NUMBER_SUFFIX) + }, + { + begin: concat(/\b\d+/, OPTIONAL_NUMBER_EXP, OPTIONAL_NUMBER_SUFFIX) + }, + { + begin: concat(/\.\d+/, OPTIONAL_NUMBER_EXP, OPTIONAL_NUMBER_SUFFIX) + } + ], + relevance: 0 + }; + + const F_KEYWORDS = { + literal: '.False. .True.', + keyword: 'kind do while private call intrinsic where elsewhere ' + + 'type endtype endmodule endselect endinterface end enddo endif if forall endforall only contains default return stop then ' + + 'public subroutine|10 function program .and. .or. .not. .le. .eq. .ge. .gt. .lt. ' + + 'goto save else use module select case ' + + 'access blank direct exist file fmt form formatted iostat name named nextrec number opened rec recl sequential status unformatted unit ' + + 'continue format pause cycle exit ' + + 'c_null_char c_alert c_backspace c_form_feed flush wait decimal round iomsg ' + + 'synchronous nopass non_overridable pass protected volatile abstract extends import ' + + 'non_intrinsic value deferred generic final enumerator class associate bind enum ' + + 'c_int c_short c_long c_long_long c_signed_char c_size_t c_int8_t c_int16_t c_int32_t c_int64_t c_int_least8_t c_int_least16_t ' + + 'c_int_least32_t c_int_least64_t c_int_fast8_t c_int_fast16_t c_int_fast32_t c_int_fast64_t c_intmax_t C_intptr_t c_float c_double ' + + 'c_long_double c_float_complex c_double_complex c_long_double_complex c_bool c_char c_null_ptr c_null_funptr ' + + 'c_new_line c_carriage_return c_horizontal_tab c_vertical_tab iso_c_binding c_loc c_funloc c_associated c_f_pointer ' + + 'c_ptr c_funptr iso_fortran_env character_storage_size error_unit file_storage_size input_unit iostat_end iostat_eor ' + + 'numeric_storage_size output_unit c_f_procpointer ieee_arithmetic ieee_support_underflow_control ' + + 'ieee_get_underflow_mode ieee_set_underflow_mode newunit contiguous recursive ' + + 'pad position action delim readwrite eor advance nml interface procedure namelist include sequence elemental pure ' + + 'integer real character complex logical dimension allocatable|10 parameter ' + + 'external implicit|10 none double precision assign intent optional pointer ' + + 'target in out common equivalence data ' + + // IRPF90 special keywords + 'begin_provider &begin_provider end_provider begin_shell end_shell begin_template end_template subst assert touch ' + + 'soft_touch provide no_dep free irp_if irp_else irp_endif irp_write irp_read', + built_in: 'alog alog10 amax0 amax1 amin0 amin1 amod cabs ccos cexp clog csin csqrt dabs dacos dasin datan datan2 dcos dcosh ddim dexp dint ' + + 'dlog dlog10 dmax1 dmin1 dmod dnint dsign dsin dsinh dsqrt dtan dtanh float iabs idim idint idnint ifix isign max0 max1 min0 min1 sngl ' + + 'algama cdabs cdcos cdexp cdlog cdsin cdsqrt cqabs cqcos cqexp cqlog cqsin cqsqrt dcmplx dconjg derf derfc dfloat dgamma dimag dlgama ' + + 'iqint qabs qacos qasin qatan qatan2 qcmplx qconjg qcos qcosh qdim qerf qerfc qexp qgamma qimag qlgama qlog qlog10 qmax1 qmin1 qmod ' + + 'qnint qsign qsin qsinh qsqrt qtan qtanh abs acos aimag aint anint asin atan atan2 char cmplx conjg cos cosh exp ichar index int log ' + + 'log10 max min nint sign sin sinh sqrt tan tanh print write dim lge lgt lle llt mod nullify allocate deallocate ' + + 'adjustl adjustr all allocated any associated bit_size btest ceiling count cshift date_and_time digits dot_product ' + + 'eoshift epsilon exponent floor fraction huge iand ibclr ibits ibset ieor ior ishft ishftc lbound len_trim matmul ' + + 'maxexponent maxloc maxval merge minexponent minloc minval modulo mvbits nearest pack present product ' + + 'radix random_number random_seed range repeat reshape rrspacing scale scan selected_int_kind selected_real_kind ' + + 'set_exponent shape size spacing spread sum system_clock tiny transpose trim ubound unpack verify achar iachar transfer ' + + 'dble entry dprod cpu_time command_argument_count get_command get_command_argument get_environment_variable is_iostat_end ' + + 'ieee_arithmetic ieee_support_underflow_control ieee_get_underflow_mode ieee_set_underflow_mode ' + + 'is_iostat_eor move_alloc new_line selected_char_kind same_type_as extends_type_of ' + + 'acosh asinh atanh bessel_j0 bessel_j1 bessel_jn bessel_y0 bessel_y1 bessel_yn erf erfc erfc_scaled gamma log_gamma hypot norm2 ' + + 'atomic_define atomic_ref execute_command_line leadz trailz storage_size merge_bits ' + + 'bge bgt ble blt dshiftl dshiftr findloc iall iany iparity image_index lcobound ucobound maskl maskr ' + + 'num_images parity popcnt poppar shifta shiftl shiftr this_image ' + + // IRPF90 special built_ins + 'IRP_ALIGN irp_here' + }; + return { + name: 'IRPF90', + case_insensitive: true, + keywords: F_KEYWORDS, + illegal: /\/\*/, + contains: [ + hljs.inherit(hljs.APOS_STRING_MODE, { + className: 'string', + relevance: 0 + }), + hljs.inherit(hljs.QUOTE_STRING_MODE, { + className: 'string', + relevance: 0 + }), + { + className: 'function', + beginKeywords: 'subroutine function program', + illegal: '[${=\\n]', + contains: [ + hljs.UNDERSCORE_TITLE_MODE, + PARAMS + ] + }, + hljs.COMMENT('!', '$', { + relevance: 0 + }), + hljs.COMMENT('begin_doc', 'end_doc', { + relevance: 10 + }), + NUMBER + ] + }; +} + +module.exports = irpf90; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/isbl.js b/claude-code-source/node_modules/highlight.js/lib/languages/isbl.js new file mode 100644 index 00000000..e76891b9 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/isbl.js @@ -0,0 +1,3207 @@ +/* +Language: ISBL +Author: Dmitriy Tarasov +Description: built-in language DIRECTUM +Category: enterprise +*/ + +function isbl(hljs) { + // Определение идентификаторов + const UNDERSCORE_IDENT_RE = "[A-Za-zА-Яа-яёЁ_!][A-Za-zА-Яа-яёЁ_0-9]*"; + + // Определение имен функций + const FUNCTION_NAME_IDENT_RE = "[A-Za-zА-Яа-яёЁ_][A-Za-zА-Яа-яёЁ_0-9]*"; + + // keyword : ключевые слова + const KEYWORD = + "and и else иначе endexcept endfinally endforeach конецвсе endif конецесли endwhile конецпока " + + "except exitfor finally foreach все if если in в not не or или try while пока "; + + // SYSRES Constants + const sysres_constants = + "SYSRES_CONST_ACCES_RIGHT_TYPE_EDIT " + + "SYSRES_CONST_ACCES_RIGHT_TYPE_FULL " + + "SYSRES_CONST_ACCES_RIGHT_TYPE_VIEW " + + "SYSRES_CONST_ACCESS_MODE_REQUISITE_CODE " + + "SYSRES_CONST_ACCESS_NO_ACCESS_VIEW " + + "SYSRES_CONST_ACCESS_NO_ACCESS_VIEW_CODE " + + "SYSRES_CONST_ACCESS_RIGHTS_ADD_REQUISITE_CODE " + + "SYSRES_CONST_ACCESS_RIGHTS_ADD_REQUISITE_YES_CODE " + + "SYSRES_CONST_ACCESS_RIGHTS_CHANGE_REQUISITE_CODE " + + "SYSRES_CONST_ACCESS_RIGHTS_CHANGE_REQUISITE_YES_CODE " + + "SYSRES_CONST_ACCESS_RIGHTS_DELETE_REQUISITE_CODE " + + "SYSRES_CONST_ACCESS_RIGHTS_DELETE_REQUISITE_YES_CODE " + + "SYSRES_CONST_ACCESS_RIGHTS_EXECUTE_REQUISITE_CODE " + + "SYSRES_CONST_ACCESS_RIGHTS_EXECUTE_REQUISITE_YES_CODE " + + "SYSRES_CONST_ACCESS_RIGHTS_NO_ACCESS_REQUISITE_CODE " + + "SYSRES_CONST_ACCESS_RIGHTS_NO_ACCESS_REQUISITE_YES_CODE " + + "SYSRES_CONST_ACCESS_RIGHTS_RATIFY_REQUISITE_CODE " + + "SYSRES_CONST_ACCESS_RIGHTS_RATIFY_REQUISITE_YES_CODE " + + "SYSRES_CONST_ACCESS_RIGHTS_REQUISITE_CODE " + + "SYSRES_CONST_ACCESS_RIGHTS_VIEW " + + "SYSRES_CONST_ACCESS_RIGHTS_VIEW_CODE " + + "SYSRES_CONST_ACCESS_RIGHTS_VIEW_REQUISITE_CODE " + + "SYSRES_CONST_ACCESS_RIGHTS_VIEW_REQUISITE_YES_CODE " + + "SYSRES_CONST_ACCESS_TYPE_CHANGE " + + "SYSRES_CONST_ACCESS_TYPE_CHANGE_CODE " + + "SYSRES_CONST_ACCESS_TYPE_EXISTS " + + "SYSRES_CONST_ACCESS_TYPE_EXISTS_CODE " + + "SYSRES_CONST_ACCESS_TYPE_FULL " + + "SYSRES_CONST_ACCESS_TYPE_FULL_CODE " + + "SYSRES_CONST_ACCESS_TYPE_VIEW " + + "SYSRES_CONST_ACCESS_TYPE_VIEW_CODE " + + "SYSRES_CONST_ACTION_TYPE_ABORT " + + "SYSRES_CONST_ACTION_TYPE_ACCEPT " + + "SYSRES_CONST_ACTION_TYPE_ACCESS_RIGHTS " + + "SYSRES_CONST_ACTION_TYPE_ADD_ATTACHMENT " + + "SYSRES_CONST_ACTION_TYPE_CHANGE_CARD " + + "SYSRES_CONST_ACTION_TYPE_CHANGE_KIND " + + "SYSRES_CONST_ACTION_TYPE_CHANGE_STORAGE " + + "SYSRES_CONST_ACTION_TYPE_CONTINUE " + + "SYSRES_CONST_ACTION_TYPE_COPY " + + "SYSRES_CONST_ACTION_TYPE_CREATE " + + "SYSRES_CONST_ACTION_TYPE_CREATE_VERSION " + + "SYSRES_CONST_ACTION_TYPE_DELETE " + + "SYSRES_CONST_ACTION_TYPE_DELETE_ATTACHMENT " + + "SYSRES_CONST_ACTION_TYPE_DELETE_VERSION " + + "SYSRES_CONST_ACTION_TYPE_DISABLE_DELEGATE_ACCESS_RIGHTS " + + "SYSRES_CONST_ACTION_TYPE_ENABLE_DELEGATE_ACCESS_RIGHTS " + + "SYSRES_CONST_ACTION_TYPE_ENCRYPTION_BY_CERTIFICATE " + + "SYSRES_CONST_ACTION_TYPE_ENCRYPTION_BY_CERTIFICATE_AND_PASSWORD " + + "SYSRES_CONST_ACTION_TYPE_ENCRYPTION_BY_PASSWORD " + + "SYSRES_CONST_ACTION_TYPE_EXPORT_WITH_LOCK " + + "SYSRES_CONST_ACTION_TYPE_EXPORT_WITHOUT_LOCK " + + "SYSRES_CONST_ACTION_TYPE_IMPORT_WITH_UNLOCK " + + "SYSRES_CONST_ACTION_TYPE_IMPORT_WITHOUT_UNLOCK " + + "SYSRES_CONST_ACTION_TYPE_LIFE_CYCLE_STAGE " + + "SYSRES_CONST_ACTION_TYPE_LOCK " + + "SYSRES_CONST_ACTION_TYPE_LOCK_FOR_SERVER " + + "SYSRES_CONST_ACTION_TYPE_LOCK_MODIFY " + + "SYSRES_CONST_ACTION_TYPE_MARK_AS_READED " + + "SYSRES_CONST_ACTION_TYPE_MARK_AS_UNREADED " + + "SYSRES_CONST_ACTION_TYPE_MODIFY " + + "SYSRES_CONST_ACTION_TYPE_MODIFY_CARD " + + "SYSRES_CONST_ACTION_TYPE_MOVE_TO_ARCHIVE " + + "SYSRES_CONST_ACTION_TYPE_OFF_ENCRYPTION " + + "SYSRES_CONST_ACTION_TYPE_PASSWORD_CHANGE " + + "SYSRES_CONST_ACTION_TYPE_PERFORM " + + "SYSRES_CONST_ACTION_TYPE_RECOVER_FROM_LOCAL_COPY " + + "SYSRES_CONST_ACTION_TYPE_RESTART " + + "SYSRES_CONST_ACTION_TYPE_RESTORE_FROM_ARCHIVE " + + "SYSRES_CONST_ACTION_TYPE_REVISION " + + "SYSRES_CONST_ACTION_TYPE_SEND_BY_MAIL " + + "SYSRES_CONST_ACTION_TYPE_SIGN " + + "SYSRES_CONST_ACTION_TYPE_START " + + "SYSRES_CONST_ACTION_TYPE_UNLOCK " + + "SYSRES_CONST_ACTION_TYPE_UNLOCK_FROM_SERVER " + + "SYSRES_CONST_ACTION_TYPE_VERSION_STATE " + + "SYSRES_CONST_ACTION_TYPE_VERSION_VISIBILITY " + + "SYSRES_CONST_ACTION_TYPE_VIEW " + + "SYSRES_CONST_ACTION_TYPE_VIEW_SHADOW_COPY " + + "SYSRES_CONST_ACTION_TYPE_WORKFLOW_DESCRIPTION_MODIFY " + + "SYSRES_CONST_ACTION_TYPE_WRITE_HISTORY " + + "SYSRES_CONST_ACTIVE_VERSION_STATE_PICK_VALUE " + + "SYSRES_CONST_ADD_REFERENCE_MODE_NAME " + + "SYSRES_CONST_ADDITION_REQUISITE_CODE " + + "SYSRES_CONST_ADDITIONAL_PARAMS_REQUISITE_CODE " + + "SYSRES_CONST_ADITIONAL_JOB_END_DATE_REQUISITE_NAME " + + "SYSRES_CONST_ADITIONAL_JOB_READ_REQUISITE_NAME " + + "SYSRES_CONST_ADITIONAL_JOB_START_DATE_REQUISITE_NAME " + + "SYSRES_CONST_ADITIONAL_JOB_STATE_REQUISITE_NAME " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_ADDING_USER_TO_GROUP_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_ADDING_USER_TO_GROUP_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_CREATION_COMP_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_CREATION_COMP_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_CREATION_GROUP_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_CREATION_GROUP_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_CREATION_USER_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_CREATION_USER_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_DATABASE_USER_CREATION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_DATABASE_USER_CREATION_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_DATABASE_USER_DELETION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_DATABASE_USER_DELETION_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_COMP_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_COMP_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_GROUP_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_GROUP_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_USER_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_USER_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_USER_FROM_GROUP_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_USER_FROM_GROUP_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_FILTERER_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_FILTERER_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_FILTERER_RESTRICTION_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_FILTERER_RESTRICTION_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_PRIVILEGE_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_PRIVILEGE_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_RIGHTS_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_RIGHTS_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_IS_MAIN_SERVER_CHANGED_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_IS_MAIN_SERVER_CHANGED_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_IS_PUBLIC_CHANGED_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_IS_PUBLIC_CHANGED_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_FILTERER_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_FILTERER_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_FILTERER_RESTRICTION_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_FILTERER_RESTRICTION_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_PRIVILEGE_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_PRIVILEGE_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_RIGHTS_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_RIGHTS_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_SERVER_LOGIN_CREATION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_SERVER_LOGIN_CREATION_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_SERVER_LOGIN_DELETION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_SERVER_LOGIN_DELETION_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_CATEGORY_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_CATEGORY_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_COMP_TITLE_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_COMP_TITLE_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_FULL_NAME_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_FULL_NAME_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_GROUP_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_GROUP_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_PARENT_GROUP_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_PARENT_GROUP_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_USER_AUTH_TYPE_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_USER_AUTH_TYPE_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_USER_LOGIN_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_USER_LOGIN_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_USER_STATUS_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_USER_STATUS_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_USER_PASSWORD_CHANGE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_USER_PASSWORD_CHANGE_ACTION " + + "SYSRES_CONST_ALL_ACCEPT_CONDITION_RUS " + + "SYSRES_CONST_ALL_USERS_GROUP " + + "SYSRES_CONST_ALL_USERS_GROUP_NAME " + + "SYSRES_CONST_ALL_USERS_SERVER_GROUP_NAME " + + "SYSRES_CONST_ALLOWED_ACCESS_TYPE_CODE " + + "SYSRES_CONST_ALLOWED_ACCESS_TYPE_NAME " + + "SYSRES_CONST_APP_VIEWER_TYPE_REQUISITE_CODE " + + "SYSRES_CONST_APPROVING_SIGNATURE_NAME " + + "SYSRES_CONST_APPROVING_SIGNATURE_REQUISITE_CODE " + + "SYSRES_CONST_ASSISTANT_SUBSTITUE_TYPE " + + "SYSRES_CONST_ASSISTANT_SUBSTITUE_TYPE_CODE " + + "SYSRES_CONST_ATTACH_TYPE_COMPONENT_TOKEN " + + "SYSRES_CONST_ATTACH_TYPE_DOC " + + "SYSRES_CONST_ATTACH_TYPE_EDOC " + + "SYSRES_CONST_ATTACH_TYPE_FOLDER " + + "SYSRES_CONST_ATTACH_TYPE_JOB " + + "SYSRES_CONST_ATTACH_TYPE_REFERENCE " + + "SYSRES_CONST_ATTACH_TYPE_TASK " + + "SYSRES_CONST_AUTH_ENCODED_PASSWORD " + + "SYSRES_CONST_AUTH_ENCODED_PASSWORD_CODE " + + "SYSRES_CONST_AUTH_NOVELL " + + "SYSRES_CONST_AUTH_PASSWORD " + + "SYSRES_CONST_AUTH_PASSWORD_CODE " + + "SYSRES_CONST_AUTH_WINDOWS " + + "SYSRES_CONST_AUTHENTICATING_SIGNATURE_NAME " + + "SYSRES_CONST_AUTHENTICATING_SIGNATURE_REQUISITE_CODE " + + "SYSRES_CONST_AUTO_ENUM_METHOD_FLAG " + + "SYSRES_CONST_AUTO_NUMERATION_CODE " + + "SYSRES_CONST_AUTO_STRONG_ENUM_METHOD_FLAG " + + "SYSRES_CONST_AUTOTEXT_NAME_REQUISITE_CODE " + + "SYSRES_CONST_AUTOTEXT_TEXT_REQUISITE_CODE " + + "SYSRES_CONST_AUTOTEXT_USAGE_ALL " + + "SYSRES_CONST_AUTOTEXT_USAGE_ALL_CODE " + + "SYSRES_CONST_AUTOTEXT_USAGE_SIGN " + + "SYSRES_CONST_AUTOTEXT_USAGE_SIGN_CODE " + + "SYSRES_CONST_AUTOTEXT_USAGE_WORK " + + "SYSRES_CONST_AUTOTEXT_USAGE_WORK_CODE " + + "SYSRES_CONST_AUTOTEXT_USE_ANYWHERE_CODE " + + "SYSRES_CONST_AUTOTEXT_USE_ON_SIGNING_CODE " + + "SYSRES_CONST_AUTOTEXT_USE_ON_WORK_CODE " + + "SYSRES_CONST_BEGIN_DATE_REQUISITE_CODE " + + "SYSRES_CONST_BLACK_LIFE_CYCLE_STAGE_FONT_COLOR " + + "SYSRES_CONST_BLUE_LIFE_CYCLE_STAGE_FONT_COLOR " + + "SYSRES_CONST_BTN_PART " + + "SYSRES_CONST_CALCULATED_ROLE_TYPE_CODE " + + "SYSRES_CONST_CALL_TYPE_VARIABLE_BUTTON_VALUE " + + "SYSRES_CONST_CALL_TYPE_VARIABLE_PROGRAM_VALUE " + + "SYSRES_CONST_CANCEL_MESSAGE_FUNCTION_RESULT " + + "SYSRES_CONST_CARD_PART " + + "SYSRES_CONST_CARD_REFERENCE_MODE_NAME " + + "SYSRES_CONST_CERTIFICATE_TYPE_REQUISITE_ENCRYPT_VALUE " + + "SYSRES_CONST_CERTIFICATE_TYPE_REQUISITE_SIGN_AND_ENCRYPT_VALUE " + + "SYSRES_CONST_CERTIFICATE_TYPE_REQUISITE_SIGN_VALUE " + + "SYSRES_CONST_CHECK_PARAM_VALUE_DATE_PARAM_TYPE " + + "SYSRES_CONST_CHECK_PARAM_VALUE_FLOAT_PARAM_TYPE " + + "SYSRES_CONST_CHECK_PARAM_VALUE_INTEGER_PARAM_TYPE " + + "SYSRES_CONST_CHECK_PARAM_VALUE_PICK_PARAM_TYPE " + + "SYSRES_CONST_CHECK_PARAM_VALUE_REEFRENCE_PARAM_TYPE " + + "SYSRES_CONST_CLOSED_RECORD_FLAG_VALUE_FEMININE " + + "SYSRES_CONST_CLOSED_RECORD_FLAG_VALUE_MASCULINE " + + "SYSRES_CONST_CODE_COMPONENT_TYPE_ADMIN " + + "SYSRES_CONST_CODE_COMPONENT_TYPE_DEVELOPER " + + "SYSRES_CONST_CODE_COMPONENT_TYPE_DOCS " + + "SYSRES_CONST_CODE_COMPONENT_TYPE_EDOC_CARDS " + + "SYSRES_CONST_CODE_COMPONENT_TYPE_EXTERNAL_EXECUTABLE " + + "SYSRES_CONST_CODE_COMPONENT_TYPE_OTHER " + + "SYSRES_CONST_CODE_COMPONENT_TYPE_REFERENCE " + + "SYSRES_CONST_CODE_COMPONENT_TYPE_REPORT " + + "SYSRES_CONST_CODE_COMPONENT_TYPE_SCRIPT " + + "SYSRES_CONST_CODE_COMPONENT_TYPE_URL " + + "SYSRES_CONST_CODE_REQUISITE_ACCESS " + + "SYSRES_CONST_CODE_REQUISITE_CODE " + + "SYSRES_CONST_CODE_REQUISITE_COMPONENT " + + "SYSRES_CONST_CODE_REQUISITE_DESCRIPTION " + + "SYSRES_CONST_CODE_REQUISITE_EXCLUDE_COMPONENT " + + "SYSRES_CONST_CODE_REQUISITE_RECORD " + + "SYSRES_CONST_COMMENT_REQ_CODE " + + "SYSRES_CONST_COMMON_SETTINGS_REQUISITE_CODE " + + "SYSRES_CONST_COMP_CODE_GRD " + + "SYSRES_CONST_COMPONENT_GROUP_TYPE_REQUISITE_CODE " + + "SYSRES_CONST_COMPONENT_TYPE_ADMIN_COMPONENTS " + + "SYSRES_CONST_COMPONENT_TYPE_DEVELOPER_COMPONENTS " + + "SYSRES_CONST_COMPONENT_TYPE_DOCS " + + "SYSRES_CONST_COMPONENT_TYPE_EDOC_CARDS " + + "SYSRES_CONST_COMPONENT_TYPE_EDOCS " + + "SYSRES_CONST_COMPONENT_TYPE_EXTERNAL_EXECUTABLE " + + "SYSRES_CONST_COMPONENT_TYPE_OTHER " + + "SYSRES_CONST_COMPONENT_TYPE_REFERENCE_TYPES " + + "SYSRES_CONST_COMPONENT_TYPE_REFERENCES " + + "SYSRES_CONST_COMPONENT_TYPE_REPORTS " + + "SYSRES_CONST_COMPONENT_TYPE_SCRIPTS " + + "SYSRES_CONST_COMPONENT_TYPE_URL " + + "SYSRES_CONST_COMPONENTS_REMOTE_SERVERS_VIEW_CODE " + + "SYSRES_CONST_CONDITION_BLOCK_DESCRIPTION " + + "SYSRES_CONST_CONST_FIRM_STATUS_COMMON " + + "SYSRES_CONST_CONST_FIRM_STATUS_INDIVIDUAL " + + "SYSRES_CONST_CONST_NEGATIVE_VALUE " + + "SYSRES_CONST_CONST_POSITIVE_VALUE " + + "SYSRES_CONST_CONST_SERVER_STATUS_DONT_REPLICATE " + + "SYSRES_CONST_CONST_SERVER_STATUS_REPLICATE " + + "SYSRES_CONST_CONTENTS_REQUISITE_CODE " + + "SYSRES_CONST_DATA_TYPE_BOOLEAN " + + "SYSRES_CONST_DATA_TYPE_DATE " + + "SYSRES_CONST_DATA_TYPE_FLOAT " + + "SYSRES_CONST_DATA_TYPE_INTEGER " + + "SYSRES_CONST_DATA_TYPE_PICK " + + "SYSRES_CONST_DATA_TYPE_REFERENCE " + + "SYSRES_CONST_DATA_TYPE_STRING " + + "SYSRES_CONST_DATA_TYPE_TEXT " + + "SYSRES_CONST_DATA_TYPE_VARIANT " + + "SYSRES_CONST_DATE_CLOSE_REQ_CODE " + + "SYSRES_CONST_DATE_FORMAT_DATE_ONLY_CHAR " + + "SYSRES_CONST_DATE_OPEN_REQ_CODE " + + "SYSRES_CONST_DATE_REQUISITE " + + "SYSRES_CONST_DATE_REQUISITE_CODE " + + "SYSRES_CONST_DATE_REQUISITE_NAME " + + "SYSRES_CONST_DATE_REQUISITE_TYPE " + + "SYSRES_CONST_DATE_TYPE_CHAR " + + "SYSRES_CONST_DATETIME_FORMAT_VALUE " + + "SYSRES_CONST_DEA_ACCESS_RIGHTS_ACTION_CODE " + + "SYSRES_CONST_DESCRIPTION_LOCALIZE_ID_REQUISITE_CODE " + + "SYSRES_CONST_DESCRIPTION_REQUISITE_CODE " + + "SYSRES_CONST_DET1_PART " + + "SYSRES_CONST_DET2_PART " + + "SYSRES_CONST_DET3_PART " + + "SYSRES_CONST_DET4_PART " + + "SYSRES_CONST_DET5_PART " + + "SYSRES_CONST_DET6_PART " + + "SYSRES_CONST_DETAIL_DATASET_KEY_REQUISITE_CODE " + + "SYSRES_CONST_DETAIL_PICK_REQUISITE_CODE " + + "SYSRES_CONST_DETAIL_REQ_CODE " + + "SYSRES_CONST_DO_NOT_USE_ACCESS_TYPE_CODE " + + "SYSRES_CONST_DO_NOT_USE_ACCESS_TYPE_NAME " + + "SYSRES_CONST_DO_NOT_USE_ON_VIEW_ACCESS_TYPE_CODE " + + "SYSRES_CONST_DO_NOT_USE_ON_VIEW_ACCESS_TYPE_NAME " + + "SYSRES_CONST_DOCUMENT_STORAGES_CODE " + + "SYSRES_CONST_DOCUMENT_TEMPLATES_TYPE_NAME " + + "SYSRES_CONST_DOUBLE_REQUISITE_CODE " + + "SYSRES_CONST_EDITOR_CLOSE_FILE_OBSERV_TYPE_CODE " + + "SYSRES_CONST_EDITOR_CLOSE_PROCESS_OBSERV_TYPE_CODE " + + "SYSRES_CONST_EDITOR_TYPE_REQUISITE_CODE " + + "SYSRES_CONST_EDITORS_APPLICATION_NAME_REQUISITE_CODE " + + "SYSRES_CONST_EDITORS_CREATE_SEVERAL_PROCESSES_REQUISITE_CODE " + + "SYSRES_CONST_EDITORS_EXTENSION_REQUISITE_CODE " + + "SYSRES_CONST_EDITORS_OBSERVER_BY_PROCESS_TYPE " + + "SYSRES_CONST_EDITORS_REFERENCE_CODE " + + "SYSRES_CONST_EDITORS_REPLACE_SPEC_CHARS_REQUISITE_CODE " + + "SYSRES_CONST_EDITORS_USE_PLUGINS_REQUISITE_CODE " + + "SYSRES_CONST_EDITORS_VIEW_DOCUMENT_OPENED_TO_EDIT_CODE " + + "SYSRES_CONST_EDOC_CARD_TYPE_REQUISITE_CODE " + + "SYSRES_CONST_EDOC_CARD_TYPES_LINK_REQUISITE_CODE " + + "SYSRES_CONST_EDOC_CERTIFICATE_AND_PASSWORD_ENCODE_CODE " + + "SYSRES_CONST_EDOC_CERTIFICATE_ENCODE_CODE " + + "SYSRES_CONST_EDOC_DATE_REQUISITE_CODE " + + "SYSRES_CONST_EDOC_KIND_REFERENCE_CODE " + + "SYSRES_CONST_EDOC_KINDS_BY_TEMPLATE_ACTION_CODE " + + "SYSRES_CONST_EDOC_MANAGE_ACCESS_CODE " + + "SYSRES_CONST_EDOC_NONE_ENCODE_CODE " + + "SYSRES_CONST_EDOC_NUMBER_REQUISITE_CODE " + + "SYSRES_CONST_EDOC_PASSWORD_ENCODE_CODE " + + "SYSRES_CONST_EDOC_READONLY_ACCESS_CODE " + + "SYSRES_CONST_EDOC_SHELL_LIFE_TYPE_VIEW_VALUE " + + "SYSRES_CONST_EDOC_SIZE_RESTRICTION_PRIORITY_REQUISITE_CODE " + + "SYSRES_CONST_EDOC_STORAGE_CHECK_ACCESS_RIGHTS_REQUISITE_CODE " + + "SYSRES_CONST_EDOC_STORAGE_COMPUTER_NAME_REQUISITE_CODE " + + "SYSRES_CONST_EDOC_STORAGE_DATABASE_NAME_REQUISITE_CODE " + + "SYSRES_CONST_EDOC_STORAGE_EDIT_IN_STORAGE_REQUISITE_CODE " + + "SYSRES_CONST_EDOC_STORAGE_LOCAL_PATH_REQUISITE_CODE " + + "SYSRES_CONST_EDOC_STORAGE_SHARED_SOURCE_NAME_REQUISITE_CODE " + + "SYSRES_CONST_EDOC_TEMPLATE_REQUISITE_CODE " + + "SYSRES_CONST_EDOC_TYPES_REFERENCE_CODE " + + "SYSRES_CONST_EDOC_VERSION_ACTIVE_STAGE_CODE " + + "SYSRES_CONST_EDOC_VERSION_DESIGN_STAGE_CODE " + + "SYSRES_CONST_EDOC_VERSION_OBSOLETE_STAGE_CODE " + + "SYSRES_CONST_EDOC_WRITE_ACCES_CODE " + + "SYSRES_CONST_EDOCUMENT_CARD_REQUISITES_REFERENCE_CODE_SELECTED_REQUISITE " + + "SYSRES_CONST_ENCODE_CERTIFICATE_TYPE_CODE " + + "SYSRES_CONST_END_DATE_REQUISITE_CODE " + + "SYSRES_CONST_ENUMERATION_TYPE_REQUISITE_CODE " + + "SYSRES_CONST_EXECUTE_ACCESS_RIGHTS_TYPE_CODE " + + "SYSRES_CONST_EXECUTIVE_FILE_STORAGE_TYPE " + + "SYSRES_CONST_EXIST_CONST " + + "SYSRES_CONST_EXIST_VALUE " + + "SYSRES_CONST_EXPORT_LOCK_TYPE_ASK " + + "SYSRES_CONST_EXPORT_LOCK_TYPE_WITH_LOCK " + + "SYSRES_CONST_EXPORT_LOCK_TYPE_WITHOUT_LOCK " + + "SYSRES_CONST_EXPORT_VERSION_TYPE_ASK " + + "SYSRES_CONST_EXPORT_VERSION_TYPE_LAST " + + "SYSRES_CONST_EXPORT_VERSION_TYPE_LAST_ACTIVE " + + "SYSRES_CONST_EXTENSION_REQUISITE_CODE " + + "SYSRES_CONST_FILTER_NAME_REQUISITE_CODE " + + "SYSRES_CONST_FILTER_REQUISITE_CODE " + + "SYSRES_CONST_FILTER_TYPE_COMMON_CODE " + + "SYSRES_CONST_FILTER_TYPE_COMMON_NAME " + + "SYSRES_CONST_FILTER_TYPE_USER_CODE " + + "SYSRES_CONST_FILTER_TYPE_USER_NAME " + + "SYSRES_CONST_FILTER_VALUE_REQUISITE_NAME " + + "SYSRES_CONST_FLOAT_NUMBER_FORMAT_CHAR " + + "SYSRES_CONST_FLOAT_REQUISITE_TYPE " + + "SYSRES_CONST_FOLDER_AUTHOR_VALUE " + + "SYSRES_CONST_FOLDER_KIND_ANY_OBJECTS " + + "SYSRES_CONST_FOLDER_KIND_COMPONENTS " + + "SYSRES_CONST_FOLDER_KIND_EDOCS " + + "SYSRES_CONST_FOLDER_KIND_JOBS " + + "SYSRES_CONST_FOLDER_KIND_TASKS " + + "SYSRES_CONST_FOLDER_TYPE_COMMON " + + "SYSRES_CONST_FOLDER_TYPE_COMPONENT " + + "SYSRES_CONST_FOLDER_TYPE_FAVORITES " + + "SYSRES_CONST_FOLDER_TYPE_INBOX " + + "SYSRES_CONST_FOLDER_TYPE_OUTBOX " + + "SYSRES_CONST_FOLDER_TYPE_QUICK_LAUNCH " + + "SYSRES_CONST_FOLDER_TYPE_SEARCH " + + "SYSRES_CONST_FOLDER_TYPE_SHORTCUTS " + + "SYSRES_CONST_FOLDER_TYPE_USER " + + "SYSRES_CONST_FROM_DICTIONARY_ENUM_METHOD_FLAG " + + "SYSRES_CONST_FULL_SUBSTITUTE_TYPE " + + "SYSRES_CONST_FULL_SUBSTITUTE_TYPE_CODE " + + "SYSRES_CONST_FUNCTION_CANCEL_RESULT " + + "SYSRES_CONST_FUNCTION_CATEGORY_SYSTEM " + + "SYSRES_CONST_FUNCTION_CATEGORY_USER " + + "SYSRES_CONST_FUNCTION_FAILURE_RESULT " + + "SYSRES_CONST_FUNCTION_SAVE_RESULT " + + "SYSRES_CONST_GENERATED_REQUISITE " + + "SYSRES_CONST_GREEN_LIFE_CYCLE_STAGE_FONT_COLOR " + + "SYSRES_CONST_GROUP_ACCOUNT_TYPE_VALUE_CODE " + + "SYSRES_CONST_GROUP_CATEGORY_NORMAL_CODE " + + "SYSRES_CONST_GROUP_CATEGORY_NORMAL_NAME " + + "SYSRES_CONST_GROUP_CATEGORY_SERVICE_CODE " + + "SYSRES_CONST_GROUP_CATEGORY_SERVICE_NAME " + + "SYSRES_CONST_GROUP_COMMON_CATEGORY_FIELD_VALUE " + + "SYSRES_CONST_GROUP_FULL_NAME_REQUISITE_CODE " + + "SYSRES_CONST_GROUP_NAME_REQUISITE_CODE " + + "SYSRES_CONST_GROUP_RIGHTS_T_REQUISITE_CODE " + + "SYSRES_CONST_GROUP_SERVER_CODES_REQUISITE_CODE " + + "SYSRES_CONST_GROUP_SERVER_NAME_REQUISITE_CODE " + + "SYSRES_CONST_GROUP_SERVICE_CATEGORY_FIELD_VALUE " + + "SYSRES_CONST_GROUP_USER_REQUISITE_CODE " + + "SYSRES_CONST_GROUPS_REFERENCE_CODE " + + "SYSRES_CONST_GROUPS_REQUISITE_CODE " + + "SYSRES_CONST_HIDDEN_MODE_NAME " + + "SYSRES_CONST_HIGH_LVL_REQUISITE_CODE " + + "SYSRES_CONST_HISTORY_ACTION_CREATE_CODE " + + "SYSRES_CONST_HISTORY_ACTION_DELETE_CODE " + + "SYSRES_CONST_HISTORY_ACTION_EDIT_CODE " + + "SYSRES_CONST_HOUR_CHAR " + + "SYSRES_CONST_ID_REQUISITE_CODE " + + "SYSRES_CONST_IDSPS_REQUISITE_CODE " + + "SYSRES_CONST_IMAGE_MODE_COLOR " + + "SYSRES_CONST_IMAGE_MODE_GREYSCALE " + + "SYSRES_CONST_IMAGE_MODE_MONOCHROME " + + "SYSRES_CONST_IMPORTANCE_HIGH " + + "SYSRES_CONST_IMPORTANCE_LOW " + + "SYSRES_CONST_IMPORTANCE_NORMAL " + + "SYSRES_CONST_IN_DESIGN_VERSION_STATE_PICK_VALUE " + + "SYSRES_CONST_INCOMING_WORK_RULE_TYPE_CODE " + + "SYSRES_CONST_INT_REQUISITE " + + "SYSRES_CONST_INT_REQUISITE_TYPE " + + "SYSRES_CONST_INTEGER_NUMBER_FORMAT_CHAR " + + "SYSRES_CONST_INTEGER_TYPE_CHAR " + + "SYSRES_CONST_IS_GENERATED_REQUISITE_NEGATIVE_VALUE " + + "SYSRES_CONST_IS_PUBLIC_ROLE_REQUISITE_CODE " + + "SYSRES_CONST_IS_REMOTE_USER_NEGATIVE_VALUE " + + "SYSRES_CONST_IS_REMOTE_USER_POSITIVE_VALUE " + + "SYSRES_CONST_IS_STORED_REQUISITE_NEGATIVE_VALUE " + + "SYSRES_CONST_IS_STORED_REQUISITE_STORED_VALUE " + + "SYSRES_CONST_ITALIC_LIFE_CYCLE_STAGE_DRAW_STYLE " + + "SYSRES_CONST_JOB_BLOCK_DESCRIPTION " + + "SYSRES_CONST_JOB_KIND_CONTROL_JOB " + + "SYSRES_CONST_JOB_KIND_JOB " + + "SYSRES_CONST_JOB_KIND_NOTICE " + + "SYSRES_CONST_JOB_STATE_ABORTED " + + "SYSRES_CONST_JOB_STATE_COMPLETE " + + "SYSRES_CONST_JOB_STATE_WORKING " + + "SYSRES_CONST_KIND_REQUISITE_CODE " + + "SYSRES_CONST_KIND_REQUISITE_NAME " + + "SYSRES_CONST_KINDS_CREATE_SHADOW_COPIES_REQUISITE_CODE " + + "SYSRES_CONST_KINDS_DEFAULT_EDOC_LIFE_STAGE_REQUISITE_CODE " + + "SYSRES_CONST_KINDS_EDOC_ALL_TEPLATES_ALLOWED_REQUISITE_CODE " + + "SYSRES_CONST_KINDS_EDOC_ALLOW_LIFE_CYCLE_STAGE_CHANGING_REQUISITE_CODE " + + "SYSRES_CONST_KINDS_EDOC_ALLOW_MULTIPLE_ACTIVE_VERSIONS_REQUISITE_CODE " + + "SYSRES_CONST_KINDS_EDOC_SHARE_ACCES_RIGHTS_BY_DEFAULT_CODE " + + "SYSRES_CONST_KINDS_EDOC_TEMPLATE_REQUISITE_CODE " + + "SYSRES_CONST_KINDS_EDOC_TYPE_REQUISITE_CODE " + + "SYSRES_CONST_KINDS_SIGNERS_REQUISITES_CODE " + + "SYSRES_CONST_KOD_INPUT_TYPE " + + "SYSRES_CONST_LAST_UPDATE_DATE_REQUISITE_CODE " + + "SYSRES_CONST_LIFE_CYCLE_START_STAGE_REQUISITE_CODE " + + "SYSRES_CONST_LILAC_LIFE_CYCLE_STAGE_FONT_COLOR " + + "SYSRES_CONST_LINK_OBJECT_KIND_COMPONENT " + + "SYSRES_CONST_LINK_OBJECT_KIND_DOCUMENT " + + "SYSRES_CONST_LINK_OBJECT_KIND_EDOC " + + "SYSRES_CONST_LINK_OBJECT_KIND_FOLDER " + + "SYSRES_CONST_LINK_OBJECT_KIND_JOB " + + "SYSRES_CONST_LINK_OBJECT_KIND_REFERENCE " + + "SYSRES_CONST_LINK_OBJECT_KIND_TASK " + + "SYSRES_CONST_LINK_REF_TYPE_REQUISITE_CODE " + + "SYSRES_CONST_LIST_REFERENCE_MODE_NAME " + + "SYSRES_CONST_LOCALIZATION_DICTIONARY_MAIN_VIEW_CODE " + + "SYSRES_CONST_MAIN_VIEW_CODE " + + "SYSRES_CONST_MANUAL_ENUM_METHOD_FLAG " + + "SYSRES_CONST_MASTER_COMP_TYPE_REQUISITE_CODE " + + "SYSRES_CONST_MASTER_TABLE_REC_ID_REQUISITE_CODE " + + "SYSRES_CONST_MAXIMIZED_MODE_NAME " + + "SYSRES_CONST_ME_VALUE " + + "SYSRES_CONST_MESSAGE_ATTENTION_CAPTION " + + "SYSRES_CONST_MESSAGE_CONFIRMATION_CAPTION " + + "SYSRES_CONST_MESSAGE_ERROR_CAPTION " + + "SYSRES_CONST_MESSAGE_INFORMATION_CAPTION " + + "SYSRES_CONST_MINIMIZED_MODE_NAME " + + "SYSRES_CONST_MINUTE_CHAR " + + "SYSRES_CONST_MODULE_REQUISITE_CODE " + + "SYSRES_CONST_MONITORING_BLOCK_DESCRIPTION " + + "SYSRES_CONST_MONTH_FORMAT_VALUE " + + "SYSRES_CONST_NAME_LOCALIZE_ID_REQUISITE_CODE " + + "SYSRES_CONST_NAME_REQUISITE_CODE " + + "SYSRES_CONST_NAME_SINGULAR_REQUISITE_CODE " + + "SYSRES_CONST_NAMEAN_INPUT_TYPE " + + "SYSRES_CONST_NEGATIVE_PICK_VALUE " + + "SYSRES_CONST_NEGATIVE_VALUE " + + "SYSRES_CONST_NO " + + "SYSRES_CONST_NO_PICK_VALUE " + + "SYSRES_CONST_NO_SIGNATURE_REQUISITE_CODE " + + "SYSRES_CONST_NO_VALUE " + + "SYSRES_CONST_NONE_ACCESS_RIGHTS_TYPE_CODE " + + "SYSRES_CONST_NONOPERATING_RECORD_FLAG_VALUE " + + "SYSRES_CONST_NONOPERATING_RECORD_FLAG_VALUE_MASCULINE " + + "SYSRES_CONST_NORMAL_ACCESS_RIGHTS_TYPE_CODE " + + "SYSRES_CONST_NORMAL_LIFE_CYCLE_STAGE_DRAW_STYLE " + + "SYSRES_CONST_NORMAL_MODE_NAME " + + "SYSRES_CONST_NOT_ALLOWED_ACCESS_TYPE_CODE " + + "SYSRES_CONST_NOT_ALLOWED_ACCESS_TYPE_NAME " + + "SYSRES_CONST_NOTE_REQUISITE_CODE " + + "SYSRES_CONST_NOTICE_BLOCK_DESCRIPTION " + + "SYSRES_CONST_NUM_REQUISITE " + + "SYSRES_CONST_NUM_STR_REQUISITE_CODE " + + "SYSRES_CONST_NUMERATION_AUTO_NOT_STRONG " + + "SYSRES_CONST_NUMERATION_AUTO_STRONG " + + "SYSRES_CONST_NUMERATION_FROM_DICTONARY " + + "SYSRES_CONST_NUMERATION_MANUAL " + + "SYSRES_CONST_NUMERIC_TYPE_CHAR " + + "SYSRES_CONST_NUMREQ_REQUISITE_CODE " + + "SYSRES_CONST_OBSOLETE_VERSION_STATE_PICK_VALUE " + + "SYSRES_CONST_OPERATING_RECORD_FLAG_VALUE " + + "SYSRES_CONST_OPERATING_RECORD_FLAG_VALUE_CODE " + + "SYSRES_CONST_OPERATING_RECORD_FLAG_VALUE_FEMININE " + + "SYSRES_CONST_OPERATING_RECORD_FLAG_VALUE_MASCULINE " + + "SYSRES_CONST_OPTIONAL_FORM_COMP_REQCODE_PREFIX " + + "SYSRES_CONST_ORANGE_LIFE_CYCLE_STAGE_FONT_COLOR " + + "SYSRES_CONST_ORIGINALREF_REQUISITE_CODE " + + "SYSRES_CONST_OURFIRM_REF_CODE " + + "SYSRES_CONST_OURFIRM_REQUISITE_CODE " + + "SYSRES_CONST_OURFIRM_VAR " + + "SYSRES_CONST_OUTGOING_WORK_RULE_TYPE_CODE " + + "SYSRES_CONST_PICK_NEGATIVE_RESULT " + + "SYSRES_CONST_PICK_POSITIVE_RESULT " + + "SYSRES_CONST_PICK_REQUISITE " + + "SYSRES_CONST_PICK_REQUISITE_TYPE " + + "SYSRES_CONST_PICK_TYPE_CHAR " + + "SYSRES_CONST_PLAN_STATUS_REQUISITE_CODE " + + "SYSRES_CONST_PLATFORM_VERSION_COMMENT " + + "SYSRES_CONST_PLUGINS_SETTINGS_DESCRIPTION_REQUISITE_CODE " + + "SYSRES_CONST_POSITIVE_PICK_VALUE " + + "SYSRES_CONST_POWER_TO_CREATE_ACTION_CODE " + + "SYSRES_CONST_POWER_TO_SIGN_ACTION_CODE " + + "SYSRES_CONST_PRIORITY_REQUISITE_CODE " + + "SYSRES_CONST_QUALIFIED_TASK_TYPE " + + "SYSRES_CONST_QUALIFIED_TASK_TYPE_CODE " + + "SYSRES_CONST_RECSTAT_REQUISITE_CODE " + + "SYSRES_CONST_RED_LIFE_CYCLE_STAGE_FONT_COLOR " + + "SYSRES_CONST_REF_ID_T_REF_TYPE_REQUISITE_CODE " + + "SYSRES_CONST_REF_REQUISITE " + + "SYSRES_CONST_REF_REQUISITE_TYPE " + + "SYSRES_CONST_REF_REQUISITES_REFERENCE_CODE_SELECTED_REQUISITE " + + "SYSRES_CONST_REFERENCE_RECORD_HISTORY_CREATE_ACTION_CODE " + + "SYSRES_CONST_REFERENCE_RECORD_HISTORY_DELETE_ACTION_CODE " + + "SYSRES_CONST_REFERENCE_RECORD_HISTORY_MODIFY_ACTION_CODE " + + "SYSRES_CONST_REFERENCE_TYPE_CHAR " + + "SYSRES_CONST_REFERENCE_TYPE_REQUISITE_NAME " + + "SYSRES_CONST_REFERENCES_ADD_PARAMS_REQUISITE_CODE " + + "SYSRES_CONST_REFERENCES_DISPLAY_REQUISITE_REQUISITE_CODE " + + "SYSRES_CONST_REMOTE_SERVER_STATUS_WORKING " + + "SYSRES_CONST_REMOTE_SERVER_TYPE_MAIN " + + "SYSRES_CONST_REMOTE_SERVER_TYPE_SECONDARY " + + "SYSRES_CONST_REMOTE_USER_FLAG_VALUE_CODE " + + "SYSRES_CONST_REPORT_APP_EDITOR_INTERNAL " + + "SYSRES_CONST_REPORT_BASE_REPORT_ID_REQUISITE_CODE " + + "SYSRES_CONST_REPORT_BASE_REPORT_REQUISITE_CODE " + + "SYSRES_CONST_REPORT_SCRIPT_REQUISITE_CODE " + + "SYSRES_CONST_REPORT_TEMPLATE_REQUISITE_CODE " + + "SYSRES_CONST_REPORT_VIEWER_CODE_REQUISITE_CODE " + + "SYSRES_CONST_REQ_ALLOW_COMPONENT_DEFAULT_VALUE " + + "SYSRES_CONST_REQ_ALLOW_RECORD_DEFAULT_VALUE " + + "SYSRES_CONST_REQ_ALLOW_SERVER_COMPONENT_DEFAULT_VALUE " + + "SYSRES_CONST_REQ_MODE_AVAILABLE_CODE " + + "SYSRES_CONST_REQ_MODE_EDIT_CODE " + + "SYSRES_CONST_REQ_MODE_HIDDEN_CODE " + + "SYSRES_CONST_REQ_MODE_NOT_AVAILABLE_CODE " + + "SYSRES_CONST_REQ_MODE_VIEW_CODE " + + "SYSRES_CONST_REQ_NUMBER_REQUISITE_CODE " + + "SYSRES_CONST_REQ_SECTION_VALUE " + + "SYSRES_CONST_REQ_TYPE_VALUE " + + "SYSRES_CONST_REQUISITE_FORMAT_BY_UNIT " + + "SYSRES_CONST_REQUISITE_FORMAT_DATE_FULL " + + "SYSRES_CONST_REQUISITE_FORMAT_DATE_TIME " + + "SYSRES_CONST_REQUISITE_FORMAT_LEFT " + + "SYSRES_CONST_REQUISITE_FORMAT_RIGHT " + + "SYSRES_CONST_REQUISITE_FORMAT_WITHOUT_UNIT " + + "SYSRES_CONST_REQUISITE_NUMBER_REQUISITE_CODE " + + "SYSRES_CONST_REQUISITE_SECTION_ACTIONS " + + "SYSRES_CONST_REQUISITE_SECTION_BUTTON " + + "SYSRES_CONST_REQUISITE_SECTION_BUTTONS " + + "SYSRES_CONST_REQUISITE_SECTION_CARD " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE10 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE11 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE12 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE13 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE14 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE15 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE16 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE17 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE18 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE19 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE2 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE20 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE21 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE22 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE23 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE24 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE3 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE4 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE5 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE6 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE7 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE8 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE9 " + + "SYSRES_CONST_REQUISITES_PSEUDOREFERENCE_REQUISITE_NUMBER_REQUISITE_CODE " + + "SYSRES_CONST_RIGHT_ALIGNMENT_CODE " + + "SYSRES_CONST_ROLES_REFERENCE_CODE " + + "SYSRES_CONST_ROUTE_STEP_AFTER_RUS " + + "SYSRES_CONST_ROUTE_STEP_AND_CONDITION_RUS " + + "SYSRES_CONST_ROUTE_STEP_OR_CONDITION_RUS " + + "SYSRES_CONST_ROUTE_TYPE_COMPLEX " + + "SYSRES_CONST_ROUTE_TYPE_PARALLEL " + + "SYSRES_CONST_ROUTE_TYPE_SERIAL " + + "SYSRES_CONST_SBDATASETDESC_NEGATIVE_VALUE " + + "SYSRES_CONST_SBDATASETDESC_POSITIVE_VALUE " + + "SYSRES_CONST_SBVIEWSDESC_POSITIVE_VALUE " + + "SYSRES_CONST_SCRIPT_BLOCK_DESCRIPTION " + + "SYSRES_CONST_SEARCH_BY_TEXT_REQUISITE_CODE " + + "SYSRES_CONST_SEARCHES_COMPONENT_CONTENT " + + "SYSRES_CONST_SEARCHES_CRITERIA_ACTION_NAME " + + "SYSRES_CONST_SEARCHES_EDOC_CONTENT " + + "SYSRES_CONST_SEARCHES_FOLDER_CONTENT " + + "SYSRES_CONST_SEARCHES_JOB_CONTENT " + + "SYSRES_CONST_SEARCHES_REFERENCE_CODE " + + "SYSRES_CONST_SEARCHES_TASK_CONTENT " + + "SYSRES_CONST_SECOND_CHAR " + + "SYSRES_CONST_SECTION_REQUISITE_ACTIONS_VALUE " + + "SYSRES_CONST_SECTION_REQUISITE_CARD_VALUE " + + "SYSRES_CONST_SECTION_REQUISITE_CODE " + + "SYSRES_CONST_SECTION_REQUISITE_DETAIL_1_VALUE " + + "SYSRES_CONST_SECTION_REQUISITE_DETAIL_2_VALUE " + + "SYSRES_CONST_SECTION_REQUISITE_DETAIL_3_VALUE " + + "SYSRES_CONST_SECTION_REQUISITE_DETAIL_4_VALUE " + + "SYSRES_CONST_SECTION_REQUISITE_DETAIL_5_VALUE " + + "SYSRES_CONST_SECTION_REQUISITE_DETAIL_6_VALUE " + + "SYSRES_CONST_SELECT_REFERENCE_MODE_NAME " + + "SYSRES_CONST_SELECT_TYPE_SELECTABLE " + + "SYSRES_CONST_SELECT_TYPE_SELECTABLE_ONLY_CHILD " + + "SYSRES_CONST_SELECT_TYPE_SELECTABLE_WITH_CHILD " + + "SYSRES_CONST_SELECT_TYPE_UNSLECTABLE " + + "SYSRES_CONST_SERVER_TYPE_MAIN " + + "SYSRES_CONST_SERVICE_USER_CATEGORY_FIELD_VALUE " + + "SYSRES_CONST_SETTINGS_USER_REQUISITE_CODE " + + "SYSRES_CONST_SIGNATURE_AND_ENCODE_CERTIFICATE_TYPE_CODE " + + "SYSRES_CONST_SIGNATURE_CERTIFICATE_TYPE_CODE " + + "SYSRES_CONST_SINGULAR_TITLE_REQUISITE_CODE " + + "SYSRES_CONST_SQL_SERVER_AUTHENTIFICATION_FLAG_VALUE_CODE " + + "SYSRES_CONST_SQL_SERVER_ENCODE_AUTHENTIFICATION_FLAG_VALUE_CODE " + + "SYSRES_CONST_STANDART_ROUTE_REFERENCE_CODE " + + "SYSRES_CONST_STANDART_ROUTE_REFERENCE_COMMENT_REQUISITE_CODE " + + "SYSRES_CONST_STANDART_ROUTES_GROUPS_REFERENCE_CODE " + + "SYSRES_CONST_STATE_REQ_NAME " + + "SYSRES_CONST_STATE_REQUISITE_ACTIVE_VALUE " + + "SYSRES_CONST_STATE_REQUISITE_CLOSED_VALUE " + + "SYSRES_CONST_STATE_REQUISITE_CODE " + + "SYSRES_CONST_STATIC_ROLE_TYPE_CODE " + + "SYSRES_CONST_STATUS_PLAN_DEFAULT_VALUE " + + "SYSRES_CONST_STATUS_VALUE_AUTOCLEANING " + + "SYSRES_CONST_STATUS_VALUE_BLUE_SQUARE " + + "SYSRES_CONST_STATUS_VALUE_COMPLETE " + + "SYSRES_CONST_STATUS_VALUE_GREEN_SQUARE " + + "SYSRES_CONST_STATUS_VALUE_ORANGE_SQUARE " + + "SYSRES_CONST_STATUS_VALUE_PURPLE_SQUARE " + + "SYSRES_CONST_STATUS_VALUE_RED_SQUARE " + + "SYSRES_CONST_STATUS_VALUE_SUSPEND " + + "SYSRES_CONST_STATUS_VALUE_YELLOW_SQUARE " + + "SYSRES_CONST_STDROUTE_SHOW_TO_USERS_REQUISITE_CODE " + + "SYSRES_CONST_STORAGE_TYPE_FILE " + + "SYSRES_CONST_STORAGE_TYPE_SQL_SERVER " + + "SYSRES_CONST_STR_REQUISITE " + + "SYSRES_CONST_STRIKEOUT_LIFE_CYCLE_STAGE_DRAW_STYLE " + + "SYSRES_CONST_STRING_FORMAT_LEFT_ALIGN_CHAR " + + "SYSRES_CONST_STRING_FORMAT_RIGHT_ALIGN_CHAR " + + "SYSRES_CONST_STRING_REQUISITE_CODE " + + "SYSRES_CONST_STRING_REQUISITE_TYPE " + + "SYSRES_CONST_STRING_TYPE_CHAR " + + "SYSRES_CONST_SUBSTITUTES_PSEUDOREFERENCE_CODE " + + "SYSRES_CONST_SUBTASK_BLOCK_DESCRIPTION " + + "SYSRES_CONST_SYSTEM_SETTING_CURRENT_USER_PARAM_VALUE " + + "SYSRES_CONST_SYSTEM_SETTING_EMPTY_VALUE_PARAM_VALUE " + + "SYSRES_CONST_SYSTEM_VERSION_COMMENT " + + "SYSRES_CONST_TASK_ACCESS_TYPE_ALL " + + "SYSRES_CONST_TASK_ACCESS_TYPE_ALL_MEMBERS " + + "SYSRES_CONST_TASK_ACCESS_TYPE_MANUAL " + + "SYSRES_CONST_TASK_ENCODE_TYPE_CERTIFICATION " + + "SYSRES_CONST_TASK_ENCODE_TYPE_CERTIFICATION_AND_PASSWORD " + + "SYSRES_CONST_TASK_ENCODE_TYPE_NONE " + + "SYSRES_CONST_TASK_ENCODE_TYPE_PASSWORD " + + "SYSRES_CONST_TASK_ROUTE_ALL_CONDITION " + + "SYSRES_CONST_TASK_ROUTE_AND_CONDITION " + + "SYSRES_CONST_TASK_ROUTE_OR_CONDITION " + + "SYSRES_CONST_TASK_STATE_ABORTED " + + "SYSRES_CONST_TASK_STATE_COMPLETE " + + "SYSRES_CONST_TASK_STATE_CONTINUED " + + "SYSRES_CONST_TASK_STATE_CONTROL " + + "SYSRES_CONST_TASK_STATE_INIT " + + "SYSRES_CONST_TASK_STATE_WORKING " + + "SYSRES_CONST_TASK_TITLE " + + "SYSRES_CONST_TASK_TYPES_GROUPS_REFERENCE_CODE " + + "SYSRES_CONST_TASK_TYPES_REFERENCE_CODE " + + "SYSRES_CONST_TEMPLATES_REFERENCE_CODE " + + "SYSRES_CONST_TEST_DATE_REQUISITE_NAME " + + "SYSRES_CONST_TEST_DEV_DATABASE_NAME " + + "SYSRES_CONST_TEST_DEV_SYSTEM_CODE " + + "SYSRES_CONST_TEST_EDMS_DATABASE_NAME " + + "SYSRES_CONST_TEST_EDMS_MAIN_CODE " + + "SYSRES_CONST_TEST_EDMS_MAIN_DB_NAME " + + "SYSRES_CONST_TEST_EDMS_SECOND_CODE " + + "SYSRES_CONST_TEST_EDMS_SECOND_DB_NAME " + + "SYSRES_CONST_TEST_EDMS_SYSTEM_CODE " + + "SYSRES_CONST_TEST_NUMERIC_REQUISITE_NAME " + + "SYSRES_CONST_TEXT_REQUISITE " + + "SYSRES_CONST_TEXT_REQUISITE_CODE " + + "SYSRES_CONST_TEXT_REQUISITE_TYPE " + + "SYSRES_CONST_TEXT_TYPE_CHAR " + + "SYSRES_CONST_TYPE_CODE_REQUISITE_CODE " + + "SYSRES_CONST_TYPE_REQUISITE_CODE " + + "SYSRES_CONST_UNDEFINED_LIFE_CYCLE_STAGE_FONT_COLOR " + + "SYSRES_CONST_UNITS_SECTION_ID_REQUISITE_CODE " + + "SYSRES_CONST_UNITS_SECTION_REQUISITE_CODE " + + "SYSRES_CONST_UNOPERATING_RECORD_FLAG_VALUE_CODE " + + "SYSRES_CONST_UNSTORED_DATA_REQUISITE_CODE " + + "SYSRES_CONST_UNSTORED_DATA_REQUISITE_NAME " + + "SYSRES_CONST_USE_ACCESS_TYPE_CODE " + + "SYSRES_CONST_USE_ACCESS_TYPE_NAME " + + "SYSRES_CONST_USER_ACCOUNT_TYPE_VALUE_CODE " + + "SYSRES_CONST_USER_ADDITIONAL_INFORMATION_REQUISITE_CODE " + + "SYSRES_CONST_USER_AND_GROUP_ID_FROM_PSEUDOREFERENCE_REQUISITE_CODE " + + "SYSRES_CONST_USER_CATEGORY_NORMAL " + + "SYSRES_CONST_USER_CERTIFICATE_REQUISITE_CODE " + + "SYSRES_CONST_USER_CERTIFICATE_STATE_REQUISITE_CODE " + + "SYSRES_CONST_USER_CERTIFICATE_SUBJECT_NAME_REQUISITE_CODE " + + "SYSRES_CONST_USER_CERTIFICATE_THUMBPRINT_REQUISITE_CODE " + + "SYSRES_CONST_USER_COMMON_CATEGORY " + + "SYSRES_CONST_USER_COMMON_CATEGORY_CODE " + + "SYSRES_CONST_USER_FULL_NAME_REQUISITE_CODE " + + "SYSRES_CONST_USER_GROUP_TYPE_REQUISITE_CODE " + + "SYSRES_CONST_USER_LOGIN_REQUISITE_CODE " + + "SYSRES_CONST_USER_REMOTE_CONTROLLER_REQUISITE_CODE " + + "SYSRES_CONST_USER_REMOTE_SYSTEM_REQUISITE_CODE " + + "SYSRES_CONST_USER_RIGHTS_T_REQUISITE_CODE " + + "SYSRES_CONST_USER_SERVER_NAME_REQUISITE_CODE " + + "SYSRES_CONST_USER_SERVICE_CATEGORY " + + "SYSRES_CONST_USER_SERVICE_CATEGORY_CODE " + + "SYSRES_CONST_USER_STATUS_ADMINISTRATOR_CODE " + + "SYSRES_CONST_USER_STATUS_ADMINISTRATOR_NAME " + + "SYSRES_CONST_USER_STATUS_DEVELOPER_CODE " + + "SYSRES_CONST_USER_STATUS_DEVELOPER_NAME " + + "SYSRES_CONST_USER_STATUS_DISABLED_CODE " + + "SYSRES_CONST_USER_STATUS_DISABLED_NAME " + + "SYSRES_CONST_USER_STATUS_SYSTEM_DEVELOPER_CODE " + + "SYSRES_CONST_USER_STATUS_USER_CODE " + + "SYSRES_CONST_USER_STATUS_USER_NAME " + + "SYSRES_CONST_USER_STATUS_USER_NAME_DEPRECATED " + + "SYSRES_CONST_USER_TYPE_FIELD_VALUE_USER " + + "SYSRES_CONST_USER_TYPE_REQUISITE_CODE " + + "SYSRES_CONST_USERS_CONTROLLER_REQUISITE_CODE " + + "SYSRES_CONST_USERS_IS_MAIN_SERVER_REQUISITE_CODE " + + "SYSRES_CONST_USERS_REFERENCE_CODE " + + "SYSRES_CONST_USERS_REGISTRATION_CERTIFICATES_ACTION_NAME " + + "SYSRES_CONST_USERS_REQUISITE_CODE " + + "SYSRES_CONST_USERS_SYSTEM_REQUISITE_CODE " + + "SYSRES_CONST_USERS_USER_ACCESS_RIGHTS_TYPR_REQUISITE_CODE " + + "SYSRES_CONST_USERS_USER_AUTHENTICATION_REQUISITE_CODE " + + "SYSRES_CONST_USERS_USER_COMPONENT_REQUISITE_CODE " + + "SYSRES_CONST_USERS_USER_GROUP_REQUISITE_CODE " + + "SYSRES_CONST_USERS_VIEW_CERTIFICATES_ACTION_NAME " + + "SYSRES_CONST_VIEW_DEFAULT_CODE " + + "SYSRES_CONST_VIEW_DEFAULT_NAME " + + "SYSRES_CONST_VIEWER_REQUISITE_CODE " + + "SYSRES_CONST_WAITING_BLOCK_DESCRIPTION " + + "SYSRES_CONST_WIZARD_FORM_LABEL_TEST_STRING " + + "SYSRES_CONST_WIZARD_QUERY_PARAM_HEIGHT_ETALON_STRING " + + "SYSRES_CONST_WIZARD_REFERENCE_COMMENT_REQUISITE_CODE " + + "SYSRES_CONST_WORK_RULES_DESCRIPTION_REQUISITE_CODE " + + "SYSRES_CONST_WORK_TIME_CALENDAR_REFERENCE_CODE " + + "SYSRES_CONST_WORK_WORKFLOW_HARD_ROUTE_TYPE_VALUE " + + "SYSRES_CONST_WORK_WORKFLOW_HARD_ROUTE_TYPE_VALUE_CODE " + + "SYSRES_CONST_WORK_WORKFLOW_HARD_ROUTE_TYPE_VALUE_CODE_RUS " + + "SYSRES_CONST_WORK_WORKFLOW_SOFT_ROUTE_TYPE_VALUE_CODE_RUS " + + "SYSRES_CONST_WORKFLOW_ROUTE_TYPR_HARD " + + "SYSRES_CONST_WORKFLOW_ROUTE_TYPR_SOFT " + + "SYSRES_CONST_XML_ENCODING " + + "SYSRES_CONST_XREC_STAT_REQUISITE_CODE " + + "SYSRES_CONST_XRECID_FIELD_NAME " + + "SYSRES_CONST_YES " + + "SYSRES_CONST_YES_NO_2_REQUISITE_CODE " + + "SYSRES_CONST_YES_NO_REQUISITE_CODE " + + "SYSRES_CONST_YES_NO_T_REF_TYPE_REQUISITE_CODE " + + "SYSRES_CONST_YES_PICK_VALUE " + + "SYSRES_CONST_YES_VALUE "; + + // Base constant + const base_constants = "CR FALSE nil NO_VALUE NULL TAB TRUE YES_VALUE "; + + // Base group name + const base_group_name_constants = + "ADMINISTRATORS_GROUP_NAME CUSTOMIZERS_GROUP_NAME DEVELOPERS_GROUP_NAME SERVICE_USERS_GROUP_NAME "; + + // Decision block properties + const decision_block_properties_constants = + "DECISION_BLOCK_FIRST_OPERAND_PROPERTY DECISION_BLOCK_NAME_PROPERTY DECISION_BLOCK_OPERATION_PROPERTY " + + "DECISION_BLOCK_RESULT_TYPE_PROPERTY DECISION_BLOCK_SECOND_OPERAND_PROPERTY "; + + // File extension + const file_extension_constants = + "ANY_FILE_EXTENTION COMPRESSED_DOCUMENT_EXTENSION EXTENDED_DOCUMENT_EXTENSION " + + "SHORT_COMPRESSED_DOCUMENT_EXTENSION SHORT_EXTENDED_DOCUMENT_EXTENSION "; + + // Job block properties + const job_block_properties_constants = + "JOB_BLOCK_ABORT_DEADLINE_PROPERTY " + + "JOB_BLOCK_AFTER_FINISH_EVENT " + + "JOB_BLOCK_AFTER_QUERY_PARAMETERS_EVENT " + + "JOB_BLOCK_ATTACHMENT_PROPERTY " + + "JOB_BLOCK_ATTACHMENTS_RIGHTS_GROUP_PROPERTY " + + "JOB_BLOCK_ATTACHMENTS_RIGHTS_TYPE_PROPERTY " + + "JOB_BLOCK_BEFORE_QUERY_PARAMETERS_EVENT " + + "JOB_BLOCK_BEFORE_START_EVENT " + + "JOB_BLOCK_CREATED_JOBS_PROPERTY " + + "JOB_BLOCK_DEADLINE_PROPERTY " + + "JOB_BLOCK_EXECUTION_RESULTS_PROPERTY " + + "JOB_BLOCK_IS_PARALLEL_PROPERTY " + + "JOB_BLOCK_IS_RELATIVE_ABORT_DEADLINE_PROPERTY " + + "JOB_BLOCK_IS_RELATIVE_DEADLINE_PROPERTY " + + "JOB_BLOCK_JOB_TEXT_PROPERTY " + + "JOB_BLOCK_NAME_PROPERTY " + + "JOB_BLOCK_NEED_SIGN_ON_PERFORM_PROPERTY " + + "JOB_BLOCK_PERFORMER_PROPERTY " + + "JOB_BLOCK_RELATIVE_ABORT_DEADLINE_TYPE_PROPERTY " + + "JOB_BLOCK_RELATIVE_DEADLINE_TYPE_PROPERTY " + + "JOB_BLOCK_SUBJECT_PROPERTY "; + + // Language code + const language_code_constants = "ENGLISH_LANGUAGE_CODE RUSSIAN_LANGUAGE_CODE "; + + // Launching external applications + const launching_external_applications_constants = + "smHidden smMaximized smMinimized smNormal wmNo wmYes "; + + // Link kind + const link_kind_constants = + "COMPONENT_TOKEN_LINK_KIND " + + "DOCUMENT_LINK_KIND " + + "EDOCUMENT_LINK_KIND " + + "FOLDER_LINK_KIND " + + "JOB_LINK_KIND " + + "REFERENCE_LINK_KIND " + + "TASK_LINK_KIND "; + + // Lock type + const lock_type_constants = + "COMPONENT_TOKEN_LOCK_TYPE EDOCUMENT_VERSION_LOCK_TYPE "; + + // Monitor block properties + const monitor_block_properties_constants = + "MONITOR_BLOCK_AFTER_FINISH_EVENT " + + "MONITOR_BLOCK_BEFORE_START_EVENT " + + "MONITOR_BLOCK_DEADLINE_PROPERTY " + + "MONITOR_BLOCK_INTERVAL_PROPERTY " + + "MONITOR_BLOCK_INTERVAL_TYPE_PROPERTY " + + "MONITOR_BLOCK_IS_RELATIVE_DEADLINE_PROPERTY " + + "MONITOR_BLOCK_NAME_PROPERTY " + + "MONITOR_BLOCK_RELATIVE_DEADLINE_TYPE_PROPERTY " + + "MONITOR_BLOCK_SEARCH_SCRIPT_PROPERTY "; + + // Notice block properties + const notice_block_properties_constants = + "NOTICE_BLOCK_AFTER_FINISH_EVENT " + + "NOTICE_BLOCK_ATTACHMENT_PROPERTY " + + "NOTICE_BLOCK_ATTACHMENTS_RIGHTS_GROUP_PROPERTY " + + "NOTICE_BLOCK_ATTACHMENTS_RIGHTS_TYPE_PROPERTY " + + "NOTICE_BLOCK_BEFORE_START_EVENT " + + "NOTICE_BLOCK_CREATED_NOTICES_PROPERTY " + + "NOTICE_BLOCK_DEADLINE_PROPERTY " + + "NOTICE_BLOCK_IS_RELATIVE_DEADLINE_PROPERTY " + + "NOTICE_BLOCK_NAME_PROPERTY " + + "NOTICE_BLOCK_NOTICE_TEXT_PROPERTY " + + "NOTICE_BLOCK_PERFORMER_PROPERTY " + + "NOTICE_BLOCK_RELATIVE_DEADLINE_TYPE_PROPERTY " + + "NOTICE_BLOCK_SUBJECT_PROPERTY "; + + // Object events + const object_events_constants = + "dseAfterCancel " + + "dseAfterClose " + + "dseAfterDelete " + + "dseAfterDeleteOutOfTransaction " + + "dseAfterInsert " + + "dseAfterOpen " + + "dseAfterScroll " + + "dseAfterUpdate " + + "dseAfterUpdateOutOfTransaction " + + "dseBeforeCancel " + + "dseBeforeClose " + + "dseBeforeDelete " + + "dseBeforeDetailUpdate " + + "dseBeforeInsert " + + "dseBeforeOpen " + + "dseBeforeUpdate " + + "dseOnAnyRequisiteChange " + + "dseOnCloseRecord " + + "dseOnDeleteError " + + "dseOnOpenRecord " + + "dseOnPrepareUpdate " + + "dseOnUpdateError " + + "dseOnUpdateRatifiedRecord " + + "dseOnValidDelete " + + "dseOnValidUpdate " + + "reOnChange " + + "reOnChangeValues " + + "SELECTION_BEGIN_ROUTE_EVENT " + + "SELECTION_END_ROUTE_EVENT "; + + // Object params + const object_params_constants = + "CURRENT_PERIOD_IS_REQUIRED " + + "PREVIOUS_CARD_TYPE_NAME " + + "SHOW_RECORD_PROPERTIES_FORM "; + + // Other + const other_constants = + "ACCESS_RIGHTS_SETTING_DIALOG_CODE " + + "ADMINISTRATOR_USER_CODE " + + "ANALYTIC_REPORT_TYPE " + + "asrtHideLocal " + + "asrtHideRemote " + + "CALCULATED_ROLE_TYPE_CODE " + + "COMPONENTS_REFERENCE_DEVELOPER_VIEW_CODE " + + "DCTS_TEST_PROTOCOLS_FOLDER_PATH " + + "E_EDOC_VERSION_ALREADY_APPROVINGLY_SIGNED " + + "E_EDOC_VERSION_ALREADY_APPROVINGLY_SIGNED_BY_USER " + + "E_EDOC_VERSION_ALREDY_SIGNED " + + "E_EDOC_VERSION_ALREDY_SIGNED_BY_USER " + + "EDOC_TYPES_CODE_REQUISITE_FIELD_NAME " + + "EDOCUMENTS_ALIAS_NAME " + + "FILES_FOLDER_PATH " + + "FILTER_OPERANDS_DELIMITER " + + "FILTER_OPERATIONS_DELIMITER " + + "FORMCARD_NAME " + + "FORMLIST_NAME " + + "GET_EXTENDED_DOCUMENT_EXTENSION_CREATION_MODE " + + "GET_EXTENDED_DOCUMENT_EXTENSION_IMPORT_MODE " + + "INTEGRATED_REPORT_TYPE " + + "IS_BUILDER_APPLICATION_ROLE " + + "IS_BUILDER_APPLICATION_ROLE2 " + + "IS_BUILDER_USERS " + + "ISBSYSDEV " + + "LOG_FOLDER_PATH " + + "mbCancel " + + "mbNo " + + "mbNoToAll " + + "mbOK " + + "mbYes " + + "mbYesToAll " + + "MEMORY_DATASET_DESRIPTIONS_FILENAME " + + "mrNo " + + "mrNoToAll " + + "mrYes " + + "mrYesToAll " + + "MULTIPLE_SELECT_DIALOG_CODE " + + "NONOPERATING_RECORD_FLAG_FEMININE " + + "NONOPERATING_RECORD_FLAG_MASCULINE " + + "OPERATING_RECORD_FLAG_FEMININE " + + "OPERATING_RECORD_FLAG_MASCULINE " + + "PROFILING_SETTINGS_COMMON_SETTINGS_CODE_VALUE " + + "PROGRAM_INITIATED_LOOKUP_ACTION " + + "ratDelete " + + "ratEdit " + + "ratInsert " + + "REPORT_TYPE " + + "REQUIRED_PICK_VALUES_VARIABLE " + + "rmCard " + + "rmList " + + "SBRTE_PROGID_DEV " + + "SBRTE_PROGID_RELEASE " + + "STATIC_ROLE_TYPE_CODE " + + "SUPPRESS_EMPTY_TEMPLATE_CREATION " + + "SYSTEM_USER_CODE " + + "UPDATE_DIALOG_DATASET " + + "USED_IN_OBJECT_HINT_PARAM " + + "USER_INITIATED_LOOKUP_ACTION " + + "USER_NAME_FORMAT " + + "USER_SELECTION_RESTRICTIONS " + + "WORKFLOW_TEST_PROTOCOLS_FOLDER_PATH " + + "ELS_SUBTYPE_CONTROL_NAME " + + "ELS_FOLDER_KIND_CONTROL_NAME " + + "REPEAT_PROCESS_CURRENT_OBJECT_EXCEPTION_NAME "; + + // Privileges + const privileges_constants = + "PRIVILEGE_COMPONENT_FULL_ACCESS " + + "PRIVILEGE_DEVELOPMENT_EXPORT " + + "PRIVILEGE_DEVELOPMENT_IMPORT " + + "PRIVILEGE_DOCUMENT_DELETE " + + "PRIVILEGE_ESD " + + "PRIVILEGE_FOLDER_DELETE " + + "PRIVILEGE_MANAGE_ACCESS_RIGHTS " + + "PRIVILEGE_MANAGE_REPLICATION " + + "PRIVILEGE_MANAGE_SESSION_SERVER " + + "PRIVILEGE_OBJECT_FULL_ACCESS " + + "PRIVILEGE_OBJECT_VIEW " + + "PRIVILEGE_RESERVE_LICENSE " + + "PRIVILEGE_SYSTEM_CUSTOMIZE " + + "PRIVILEGE_SYSTEM_DEVELOP " + + "PRIVILEGE_SYSTEM_INSTALL " + + "PRIVILEGE_TASK_DELETE " + + "PRIVILEGE_USER_PLUGIN_SETTINGS_CUSTOMIZE " + + "PRIVILEGES_PSEUDOREFERENCE_CODE "; + + // Pseudoreference code + const pseudoreference_code_constants = + "ACCESS_TYPES_PSEUDOREFERENCE_CODE " + + "ALL_AVAILABLE_COMPONENTS_PSEUDOREFERENCE_CODE " + + "ALL_AVAILABLE_PRIVILEGES_PSEUDOREFERENCE_CODE " + + "ALL_REPLICATE_COMPONENTS_PSEUDOREFERENCE_CODE " + + "AVAILABLE_DEVELOPERS_COMPONENTS_PSEUDOREFERENCE_CODE " + + "COMPONENTS_PSEUDOREFERENCE_CODE " + + "FILTRATER_SETTINGS_CONFLICTS_PSEUDOREFERENCE_CODE " + + "GROUPS_PSEUDOREFERENCE_CODE " + + "RECEIVE_PROTOCOL_PSEUDOREFERENCE_CODE " + + "REFERENCE_REQUISITE_PSEUDOREFERENCE_CODE " + + "REFERENCE_REQUISITES_PSEUDOREFERENCE_CODE " + + "REFTYPES_PSEUDOREFERENCE_CODE " + + "REPLICATION_SEANCES_DIARY_PSEUDOREFERENCE_CODE " + + "SEND_PROTOCOL_PSEUDOREFERENCE_CODE " + + "SUBSTITUTES_PSEUDOREFERENCE_CODE " + + "SYSTEM_SETTINGS_PSEUDOREFERENCE_CODE " + + "UNITS_PSEUDOREFERENCE_CODE " + + "USERS_PSEUDOREFERENCE_CODE " + + "VIEWERS_PSEUDOREFERENCE_CODE "; + + // Requisite ISBCertificateType values + const requisite_ISBCertificateType_values_constants = + "CERTIFICATE_TYPE_ENCRYPT " + + "CERTIFICATE_TYPE_SIGN " + + "CERTIFICATE_TYPE_SIGN_AND_ENCRYPT "; + + // Requisite ISBEDocStorageType values + const requisite_ISBEDocStorageType_values_constants = + "STORAGE_TYPE_FILE " + + "STORAGE_TYPE_NAS_CIFS " + + "STORAGE_TYPE_SAPERION " + + "STORAGE_TYPE_SQL_SERVER "; + + // Requisite CompType2 values + const requisite_compType2_values_constants = + "COMPTYPE2_REQUISITE_DOCUMENTS_VALUE " + + "COMPTYPE2_REQUISITE_TASKS_VALUE " + + "COMPTYPE2_REQUISITE_FOLDERS_VALUE " + + "COMPTYPE2_REQUISITE_REFERENCES_VALUE "; + + // Requisite name + const requisite_name_constants = + "SYSREQ_CODE " + + "SYSREQ_COMPTYPE2 " + + "SYSREQ_CONST_AVAILABLE_FOR_WEB " + + "SYSREQ_CONST_COMMON_CODE " + + "SYSREQ_CONST_COMMON_VALUE " + + "SYSREQ_CONST_FIRM_CODE " + + "SYSREQ_CONST_FIRM_STATUS " + + "SYSREQ_CONST_FIRM_VALUE " + + "SYSREQ_CONST_SERVER_STATUS " + + "SYSREQ_CONTENTS " + + "SYSREQ_DATE_OPEN " + + "SYSREQ_DATE_CLOSE " + + "SYSREQ_DESCRIPTION " + + "SYSREQ_DESCRIPTION_LOCALIZE_ID " + + "SYSREQ_DOUBLE " + + "SYSREQ_EDOC_ACCESS_TYPE " + + "SYSREQ_EDOC_AUTHOR " + + "SYSREQ_EDOC_CREATED " + + "SYSREQ_EDOC_DELEGATE_RIGHTS_REQUISITE_CODE " + + "SYSREQ_EDOC_EDITOR " + + "SYSREQ_EDOC_ENCODE_TYPE " + + "SYSREQ_EDOC_ENCRYPTION_PLUGIN_NAME " + + "SYSREQ_EDOC_ENCRYPTION_PLUGIN_VERSION " + + "SYSREQ_EDOC_EXPORT_DATE " + + "SYSREQ_EDOC_EXPORTER " + + "SYSREQ_EDOC_KIND " + + "SYSREQ_EDOC_LIFE_STAGE_NAME " + + "SYSREQ_EDOC_LOCKED_FOR_SERVER_CODE " + + "SYSREQ_EDOC_MODIFIED " + + "SYSREQ_EDOC_NAME " + + "SYSREQ_EDOC_NOTE " + + "SYSREQ_EDOC_QUALIFIED_ID " + + "SYSREQ_EDOC_SESSION_KEY " + + "SYSREQ_EDOC_SESSION_KEY_ENCRYPTION_PLUGIN_NAME " + + "SYSREQ_EDOC_SESSION_KEY_ENCRYPTION_PLUGIN_VERSION " + + "SYSREQ_EDOC_SIGNATURE_TYPE " + + "SYSREQ_EDOC_SIGNED " + + "SYSREQ_EDOC_STORAGE " + + "SYSREQ_EDOC_STORAGES_ARCHIVE_STORAGE " + + "SYSREQ_EDOC_STORAGES_CHECK_RIGHTS " + + "SYSREQ_EDOC_STORAGES_COMPUTER_NAME " + + "SYSREQ_EDOC_STORAGES_EDIT_IN_STORAGE " + + "SYSREQ_EDOC_STORAGES_EXECUTIVE_STORAGE " + + "SYSREQ_EDOC_STORAGES_FUNCTION " + + "SYSREQ_EDOC_STORAGES_INITIALIZED " + + "SYSREQ_EDOC_STORAGES_LOCAL_PATH " + + "SYSREQ_EDOC_STORAGES_SAPERION_DATABASE_NAME " + + "SYSREQ_EDOC_STORAGES_SEARCH_BY_TEXT " + + "SYSREQ_EDOC_STORAGES_SERVER_NAME " + + "SYSREQ_EDOC_STORAGES_SHARED_SOURCE_NAME " + + "SYSREQ_EDOC_STORAGES_TYPE " + + "SYSREQ_EDOC_TEXT_MODIFIED " + + "SYSREQ_EDOC_TYPE_ACT_CODE " + + "SYSREQ_EDOC_TYPE_ACT_DESCRIPTION " + + "SYSREQ_EDOC_TYPE_ACT_DESCRIPTION_LOCALIZE_ID " + + "SYSREQ_EDOC_TYPE_ACT_ON_EXECUTE " + + "SYSREQ_EDOC_TYPE_ACT_ON_EXECUTE_EXISTS " + + "SYSREQ_EDOC_TYPE_ACT_SECTION " + + "SYSREQ_EDOC_TYPE_ADD_PARAMS " + + "SYSREQ_EDOC_TYPE_COMMENT " + + "SYSREQ_EDOC_TYPE_EVENT_TEXT " + + "SYSREQ_EDOC_TYPE_NAME_IN_SINGULAR " + + "SYSREQ_EDOC_TYPE_NAME_IN_SINGULAR_LOCALIZE_ID " + + "SYSREQ_EDOC_TYPE_NAME_LOCALIZE_ID " + + "SYSREQ_EDOC_TYPE_NUMERATION_METHOD " + + "SYSREQ_EDOC_TYPE_PSEUDO_REQUISITE_CODE " + + "SYSREQ_EDOC_TYPE_REQ_CODE " + + "SYSREQ_EDOC_TYPE_REQ_DESCRIPTION " + + "SYSREQ_EDOC_TYPE_REQ_DESCRIPTION_LOCALIZE_ID " + + "SYSREQ_EDOC_TYPE_REQ_IS_LEADING " + + "SYSREQ_EDOC_TYPE_REQ_IS_REQUIRED " + + "SYSREQ_EDOC_TYPE_REQ_NUMBER " + + "SYSREQ_EDOC_TYPE_REQ_ON_CHANGE " + + "SYSREQ_EDOC_TYPE_REQ_ON_CHANGE_EXISTS " + + "SYSREQ_EDOC_TYPE_REQ_ON_SELECT " + + "SYSREQ_EDOC_TYPE_REQ_ON_SELECT_KIND " + + "SYSREQ_EDOC_TYPE_REQ_SECTION " + + "SYSREQ_EDOC_TYPE_VIEW_CARD " + + "SYSREQ_EDOC_TYPE_VIEW_CODE " + + "SYSREQ_EDOC_TYPE_VIEW_COMMENT " + + "SYSREQ_EDOC_TYPE_VIEW_IS_MAIN " + + "SYSREQ_EDOC_TYPE_VIEW_NAME " + + "SYSREQ_EDOC_TYPE_VIEW_NAME_LOCALIZE_ID " + + "SYSREQ_EDOC_VERSION_AUTHOR " + + "SYSREQ_EDOC_VERSION_CRC " + + "SYSREQ_EDOC_VERSION_DATA " + + "SYSREQ_EDOC_VERSION_EDITOR " + + "SYSREQ_EDOC_VERSION_EXPORT_DATE " + + "SYSREQ_EDOC_VERSION_EXPORTER " + + "SYSREQ_EDOC_VERSION_HIDDEN " + + "SYSREQ_EDOC_VERSION_LIFE_STAGE " + + "SYSREQ_EDOC_VERSION_MODIFIED " + + "SYSREQ_EDOC_VERSION_NOTE " + + "SYSREQ_EDOC_VERSION_SIGNATURE_TYPE " + + "SYSREQ_EDOC_VERSION_SIGNED " + + "SYSREQ_EDOC_VERSION_SIZE " + + "SYSREQ_EDOC_VERSION_SOURCE " + + "SYSREQ_EDOC_VERSION_TEXT_MODIFIED " + + "SYSREQ_EDOCKIND_DEFAULT_VERSION_STATE_CODE " + + "SYSREQ_FOLDER_KIND " + + "SYSREQ_FUNC_CATEGORY " + + "SYSREQ_FUNC_COMMENT " + + "SYSREQ_FUNC_GROUP " + + "SYSREQ_FUNC_GROUP_COMMENT " + + "SYSREQ_FUNC_GROUP_NUMBER " + + "SYSREQ_FUNC_HELP " + + "SYSREQ_FUNC_PARAM_DEF_VALUE " + + "SYSREQ_FUNC_PARAM_IDENT " + + "SYSREQ_FUNC_PARAM_NUMBER " + + "SYSREQ_FUNC_PARAM_TYPE " + + "SYSREQ_FUNC_TEXT " + + "SYSREQ_GROUP_CATEGORY " + + "SYSREQ_ID " + + "SYSREQ_LAST_UPDATE " + + "SYSREQ_LEADER_REFERENCE " + + "SYSREQ_LINE_NUMBER " + + "SYSREQ_MAIN_RECORD_ID " + + "SYSREQ_NAME " + + "SYSREQ_NAME_LOCALIZE_ID " + + "SYSREQ_NOTE " + + "SYSREQ_ORIGINAL_RECORD " + + "SYSREQ_OUR_FIRM " + + "SYSREQ_PROFILING_SETTINGS_BATCH_LOGING " + + "SYSREQ_PROFILING_SETTINGS_BATCH_SIZE " + + "SYSREQ_PROFILING_SETTINGS_PROFILING_ENABLED " + + "SYSREQ_PROFILING_SETTINGS_SQL_PROFILING_ENABLED " + + "SYSREQ_PROFILING_SETTINGS_START_LOGGED " + + "SYSREQ_RECORD_STATUS " + + "SYSREQ_REF_REQ_FIELD_NAME " + + "SYSREQ_REF_REQ_FORMAT " + + "SYSREQ_REF_REQ_GENERATED " + + "SYSREQ_REF_REQ_LENGTH " + + "SYSREQ_REF_REQ_PRECISION " + + "SYSREQ_REF_REQ_REFERENCE " + + "SYSREQ_REF_REQ_SECTION " + + "SYSREQ_REF_REQ_STORED " + + "SYSREQ_REF_REQ_TOKENS " + + "SYSREQ_REF_REQ_TYPE " + + "SYSREQ_REF_REQ_VIEW " + + "SYSREQ_REF_TYPE_ACT_CODE " + + "SYSREQ_REF_TYPE_ACT_DESCRIPTION " + + "SYSREQ_REF_TYPE_ACT_DESCRIPTION_LOCALIZE_ID " + + "SYSREQ_REF_TYPE_ACT_ON_EXECUTE " + + "SYSREQ_REF_TYPE_ACT_ON_EXECUTE_EXISTS " + + "SYSREQ_REF_TYPE_ACT_SECTION " + + "SYSREQ_REF_TYPE_ADD_PARAMS " + + "SYSREQ_REF_TYPE_COMMENT " + + "SYSREQ_REF_TYPE_COMMON_SETTINGS " + + "SYSREQ_REF_TYPE_DISPLAY_REQUISITE_NAME " + + "SYSREQ_REF_TYPE_EVENT_TEXT " + + "SYSREQ_REF_TYPE_MAIN_LEADING_REF " + + "SYSREQ_REF_TYPE_NAME_IN_SINGULAR " + + "SYSREQ_REF_TYPE_NAME_IN_SINGULAR_LOCALIZE_ID " + + "SYSREQ_REF_TYPE_NAME_LOCALIZE_ID " + + "SYSREQ_REF_TYPE_NUMERATION_METHOD " + + "SYSREQ_REF_TYPE_REQ_CODE " + + "SYSREQ_REF_TYPE_REQ_DESCRIPTION " + + "SYSREQ_REF_TYPE_REQ_DESCRIPTION_LOCALIZE_ID " + + "SYSREQ_REF_TYPE_REQ_IS_CONTROL " + + "SYSREQ_REF_TYPE_REQ_IS_FILTER " + + "SYSREQ_REF_TYPE_REQ_IS_LEADING " + + "SYSREQ_REF_TYPE_REQ_IS_REQUIRED " + + "SYSREQ_REF_TYPE_REQ_NUMBER " + + "SYSREQ_REF_TYPE_REQ_ON_CHANGE " + + "SYSREQ_REF_TYPE_REQ_ON_CHANGE_EXISTS " + + "SYSREQ_REF_TYPE_REQ_ON_SELECT " + + "SYSREQ_REF_TYPE_REQ_ON_SELECT_KIND " + + "SYSREQ_REF_TYPE_REQ_SECTION " + + "SYSREQ_REF_TYPE_VIEW_CARD " + + "SYSREQ_REF_TYPE_VIEW_CODE " + + "SYSREQ_REF_TYPE_VIEW_COMMENT " + + "SYSREQ_REF_TYPE_VIEW_IS_MAIN " + + "SYSREQ_REF_TYPE_VIEW_NAME " + + "SYSREQ_REF_TYPE_VIEW_NAME_LOCALIZE_ID " + + "SYSREQ_REFERENCE_TYPE_ID " + + "SYSREQ_STATE " + + "SYSREQ_STATЕ " + + "SYSREQ_SYSTEM_SETTINGS_VALUE " + + "SYSREQ_TYPE " + + "SYSREQ_UNIT " + + "SYSREQ_UNIT_ID " + + "SYSREQ_USER_GROUPS_GROUP_FULL_NAME " + + "SYSREQ_USER_GROUPS_GROUP_NAME " + + "SYSREQ_USER_GROUPS_GROUP_SERVER_NAME " + + "SYSREQ_USERS_ACCESS_RIGHTS " + + "SYSREQ_USERS_AUTHENTICATION " + + "SYSREQ_USERS_CATEGORY " + + "SYSREQ_USERS_COMPONENT " + + "SYSREQ_USERS_COMPONENT_USER_IS_PUBLIC " + + "SYSREQ_USERS_DOMAIN " + + "SYSREQ_USERS_FULL_USER_NAME " + + "SYSREQ_USERS_GROUP " + + "SYSREQ_USERS_IS_MAIN_SERVER " + + "SYSREQ_USERS_LOGIN " + + "SYSREQ_USERS_REFERENCE_USER_IS_PUBLIC " + + "SYSREQ_USERS_STATUS " + + "SYSREQ_USERS_USER_CERTIFICATE " + + "SYSREQ_USERS_USER_CERTIFICATE_INFO " + + "SYSREQ_USERS_USER_CERTIFICATE_PLUGIN_NAME " + + "SYSREQ_USERS_USER_CERTIFICATE_PLUGIN_VERSION " + + "SYSREQ_USERS_USER_CERTIFICATE_STATE " + + "SYSREQ_USERS_USER_CERTIFICATE_SUBJECT_NAME " + + "SYSREQ_USERS_USER_CERTIFICATE_THUMBPRINT " + + "SYSREQ_USERS_USER_DEFAULT_CERTIFICATE " + + "SYSREQ_USERS_USER_DESCRIPTION " + + "SYSREQ_USERS_USER_GLOBAL_NAME " + + "SYSREQ_USERS_USER_LOGIN " + + "SYSREQ_USERS_USER_MAIN_SERVER " + + "SYSREQ_USERS_USER_TYPE " + + "SYSREQ_WORK_RULES_FOLDER_ID "; + + // Result + const result_constants = "RESULT_VAR_NAME RESULT_VAR_NAME_ENG "; + + // Rule identification + const rule_identification_constants = + "AUTO_NUMERATION_RULE_ID " + + "CANT_CHANGE_ID_REQUISITE_RULE_ID " + + "CANT_CHANGE_OURFIRM_REQUISITE_RULE_ID " + + "CHECK_CHANGING_REFERENCE_RECORD_USE_RULE_ID " + + "CHECK_CODE_REQUISITE_RULE_ID " + + "CHECK_DELETING_REFERENCE_RECORD_USE_RULE_ID " + + "CHECK_FILTRATER_CHANGES_RULE_ID " + + "CHECK_RECORD_INTERVAL_RULE_ID " + + "CHECK_REFERENCE_INTERVAL_RULE_ID " + + "CHECK_REQUIRED_DATA_FULLNESS_RULE_ID " + + "CHECK_REQUIRED_REQUISITES_FULLNESS_RULE_ID " + + "MAKE_RECORD_UNRATIFIED_RULE_ID " + + "RESTORE_AUTO_NUMERATION_RULE_ID " + + "SET_FIRM_CONTEXT_FROM_RECORD_RULE_ID " + + "SET_FIRST_RECORD_IN_LIST_FORM_RULE_ID " + + "SET_IDSPS_VALUE_RULE_ID " + + "SET_NEXT_CODE_VALUE_RULE_ID " + + "SET_OURFIRM_BOUNDS_RULE_ID " + + "SET_OURFIRM_REQUISITE_RULE_ID "; + + // Script block properties + const script_block_properties_constants = + "SCRIPT_BLOCK_AFTER_FINISH_EVENT " + + "SCRIPT_BLOCK_BEFORE_START_EVENT " + + "SCRIPT_BLOCK_EXECUTION_RESULTS_PROPERTY " + + "SCRIPT_BLOCK_NAME_PROPERTY " + + "SCRIPT_BLOCK_SCRIPT_PROPERTY "; + + // Subtask block properties + const subtask_block_properties_constants = + "SUBTASK_BLOCK_ABORT_DEADLINE_PROPERTY " + + "SUBTASK_BLOCK_AFTER_FINISH_EVENT " + + "SUBTASK_BLOCK_ASSIGN_PARAMS_EVENT " + + "SUBTASK_BLOCK_ATTACHMENTS_PROPERTY " + + "SUBTASK_BLOCK_ATTACHMENTS_RIGHTS_GROUP_PROPERTY " + + "SUBTASK_BLOCK_ATTACHMENTS_RIGHTS_TYPE_PROPERTY " + + "SUBTASK_BLOCK_BEFORE_START_EVENT " + + "SUBTASK_BLOCK_CREATED_TASK_PROPERTY " + + "SUBTASK_BLOCK_CREATION_EVENT " + + "SUBTASK_BLOCK_DEADLINE_PROPERTY " + + "SUBTASK_BLOCK_IMPORTANCE_PROPERTY " + + "SUBTASK_BLOCK_INITIATOR_PROPERTY " + + "SUBTASK_BLOCK_IS_RELATIVE_ABORT_DEADLINE_PROPERTY " + + "SUBTASK_BLOCK_IS_RELATIVE_DEADLINE_PROPERTY " + + "SUBTASK_BLOCK_JOBS_TYPE_PROPERTY " + + "SUBTASK_BLOCK_NAME_PROPERTY " + + "SUBTASK_BLOCK_PARALLEL_ROUTE_PROPERTY " + + "SUBTASK_BLOCK_PERFORMERS_PROPERTY " + + "SUBTASK_BLOCK_RELATIVE_ABORT_DEADLINE_TYPE_PROPERTY " + + "SUBTASK_BLOCK_RELATIVE_DEADLINE_TYPE_PROPERTY " + + "SUBTASK_BLOCK_REQUIRE_SIGN_PROPERTY " + + "SUBTASK_BLOCK_STANDARD_ROUTE_PROPERTY " + + "SUBTASK_BLOCK_START_EVENT " + + "SUBTASK_BLOCK_STEP_CONTROL_PROPERTY " + + "SUBTASK_BLOCK_SUBJECT_PROPERTY " + + "SUBTASK_BLOCK_TASK_CONTROL_PROPERTY " + + "SUBTASK_BLOCK_TEXT_PROPERTY " + + "SUBTASK_BLOCK_UNLOCK_ATTACHMENTS_ON_STOP_PROPERTY " + + "SUBTASK_BLOCK_USE_STANDARD_ROUTE_PROPERTY " + + "SUBTASK_BLOCK_WAIT_FOR_TASK_COMPLETE_PROPERTY "; + + // System component + const system_component_constants = + "SYSCOMP_CONTROL_JOBS " + + "SYSCOMP_FOLDERS " + + "SYSCOMP_JOBS " + + "SYSCOMP_NOTICES " + + "SYSCOMP_TASKS "; + + // System dialogs + const system_dialogs_constants = + "SYSDLG_CREATE_EDOCUMENT " + + "SYSDLG_CREATE_EDOCUMENT_VERSION " + + "SYSDLG_CURRENT_PERIOD " + + "SYSDLG_EDIT_FUNCTION_HELP " + + "SYSDLG_EDOCUMENT_KINDS_FOR_TEMPLATE " + + "SYSDLG_EXPORT_MULTIPLE_EDOCUMENTS " + + "SYSDLG_EXPORT_SINGLE_EDOCUMENT " + + "SYSDLG_IMPORT_EDOCUMENT " + + "SYSDLG_MULTIPLE_SELECT " + + "SYSDLG_SETUP_ACCESS_RIGHTS " + + "SYSDLG_SETUP_DEFAULT_RIGHTS " + + "SYSDLG_SETUP_FILTER_CONDITION " + + "SYSDLG_SETUP_SIGN_RIGHTS " + + "SYSDLG_SETUP_TASK_OBSERVERS " + + "SYSDLG_SETUP_TASK_ROUTE " + + "SYSDLG_SETUP_USERS_LIST " + + "SYSDLG_SIGN_EDOCUMENT " + + "SYSDLG_SIGN_MULTIPLE_EDOCUMENTS "; + + // System reference names + const system_reference_names_constants = + "SYSREF_ACCESS_RIGHTS_TYPES " + + "SYSREF_ADMINISTRATION_HISTORY " + + "SYSREF_ALL_AVAILABLE_COMPONENTS " + + "SYSREF_ALL_AVAILABLE_PRIVILEGES " + + "SYSREF_ALL_REPLICATING_COMPONENTS " + + "SYSREF_AVAILABLE_DEVELOPERS_COMPONENTS " + + "SYSREF_CALENDAR_EVENTS " + + "SYSREF_COMPONENT_TOKEN_HISTORY " + + "SYSREF_COMPONENT_TOKENS " + + "SYSREF_COMPONENTS " + + "SYSREF_CONSTANTS " + + "SYSREF_DATA_RECEIVE_PROTOCOL " + + "SYSREF_DATA_SEND_PROTOCOL " + + "SYSREF_DIALOGS " + + "SYSREF_DIALOGS_REQUISITES " + + "SYSREF_EDITORS " + + "SYSREF_EDOC_CARDS " + + "SYSREF_EDOC_TYPES " + + "SYSREF_EDOCUMENT_CARD_REQUISITES " + + "SYSREF_EDOCUMENT_CARD_TYPES " + + "SYSREF_EDOCUMENT_CARD_TYPES_REFERENCE " + + "SYSREF_EDOCUMENT_CARDS " + + "SYSREF_EDOCUMENT_HISTORY " + + "SYSREF_EDOCUMENT_KINDS " + + "SYSREF_EDOCUMENT_REQUISITES " + + "SYSREF_EDOCUMENT_SIGNATURES " + + "SYSREF_EDOCUMENT_TEMPLATES " + + "SYSREF_EDOCUMENT_TEXT_STORAGES " + + "SYSREF_EDOCUMENT_VIEWS " + + "SYSREF_FILTERER_SETUP_CONFLICTS " + + "SYSREF_FILTRATER_SETTING_CONFLICTS " + + "SYSREF_FOLDER_HISTORY " + + "SYSREF_FOLDERS " + + "SYSREF_FUNCTION_GROUPS " + + "SYSREF_FUNCTION_PARAMS " + + "SYSREF_FUNCTIONS " + + "SYSREF_JOB_HISTORY " + + "SYSREF_LINKS " + + "SYSREF_LOCALIZATION_DICTIONARY " + + "SYSREF_LOCALIZATION_LANGUAGES " + + "SYSREF_MODULES " + + "SYSREF_PRIVILEGES " + + "SYSREF_RECORD_HISTORY " + + "SYSREF_REFERENCE_REQUISITES " + + "SYSREF_REFERENCE_TYPE_VIEWS " + + "SYSREF_REFERENCE_TYPES " + + "SYSREF_REFERENCES " + + "SYSREF_REFERENCES_REQUISITES " + + "SYSREF_REMOTE_SERVERS " + + "SYSREF_REPLICATION_SESSIONS_LOG " + + "SYSREF_REPLICATION_SESSIONS_PROTOCOL " + + "SYSREF_REPORTS " + + "SYSREF_ROLES " + + "SYSREF_ROUTE_BLOCK_GROUPS " + + "SYSREF_ROUTE_BLOCKS " + + "SYSREF_SCRIPTS " + + "SYSREF_SEARCHES " + + "SYSREF_SERVER_EVENTS " + + "SYSREF_SERVER_EVENTS_HISTORY " + + "SYSREF_STANDARD_ROUTE_GROUPS " + + "SYSREF_STANDARD_ROUTES " + + "SYSREF_STATUSES " + + "SYSREF_SYSTEM_SETTINGS " + + "SYSREF_TASK_HISTORY " + + "SYSREF_TASK_KIND_GROUPS " + + "SYSREF_TASK_KINDS " + + "SYSREF_TASK_RIGHTS " + + "SYSREF_TASK_SIGNATURES " + + "SYSREF_TASKS " + + "SYSREF_UNITS " + + "SYSREF_USER_GROUPS " + + "SYSREF_USER_GROUPS_REFERENCE " + + "SYSREF_USER_SUBSTITUTION " + + "SYSREF_USERS " + + "SYSREF_USERS_REFERENCE " + + "SYSREF_VIEWERS " + + "SYSREF_WORKING_TIME_CALENDARS "; + + // Table name + const table_name_constants = + "ACCESS_RIGHTS_TABLE_NAME " + + "EDMS_ACCESS_TABLE_NAME " + + "EDOC_TYPES_TABLE_NAME "; + + // Test + const test_constants = + "TEST_DEV_DB_NAME " + + "TEST_DEV_SYSTEM_CODE " + + "TEST_EDMS_DB_NAME " + + "TEST_EDMS_MAIN_CODE " + + "TEST_EDMS_MAIN_DB_NAME " + + "TEST_EDMS_SECOND_CODE " + + "TEST_EDMS_SECOND_DB_NAME " + + "TEST_EDMS_SYSTEM_CODE " + + "TEST_ISB5_MAIN_CODE " + + "TEST_ISB5_SECOND_CODE " + + "TEST_SQL_SERVER_2005_NAME " + + "TEST_SQL_SERVER_NAME "; + + // Using the dialog windows + const using_the_dialog_windows_constants = + "ATTENTION_CAPTION " + + "cbsCommandLinks " + + "cbsDefault " + + "CONFIRMATION_CAPTION " + + "ERROR_CAPTION " + + "INFORMATION_CAPTION " + + "mrCancel " + + "mrOk "; + + // Using the document + const using_the_document_constants = + "EDOC_VERSION_ACTIVE_STAGE_CODE " + + "EDOC_VERSION_DESIGN_STAGE_CODE " + + "EDOC_VERSION_OBSOLETE_STAGE_CODE "; + + // Using the EA and encryption + const using_the_EA_and_encryption_constants = + "cpDataEnciphermentEnabled " + + "cpDigitalSignatureEnabled " + + "cpID " + + "cpIssuer " + + "cpPluginVersion " + + "cpSerial " + + "cpSubjectName " + + "cpSubjSimpleName " + + "cpValidFromDate " + + "cpValidToDate "; + + // Using the ISBL-editor + const using_the_ISBL_editor_constants = + "ISBL_SYNTAX " + "NO_SYNTAX " + "XML_SYNTAX "; + + // Wait block properties + const wait_block_properties_constants = + "WAIT_BLOCK_AFTER_FINISH_EVENT " + + "WAIT_BLOCK_BEFORE_START_EVENT " + + "WAIT_BLOCK_DEADLINE_PROPERTY " + + "WAIT_BLOCK_IS_RELATIVE_DEADLINE_PROPERTY " + + "WAIT_BLOCK_NAME_PROPERTY " + + "WAIT_BLOCK_RELATIVE_DEADLINE_TYPE_PROPERTY "; + + // SYSRES Common + const sysres_common_constants = + "SYSRES_COMMON " + + "SYSRES_CONST " + + "SYSRES_MBFUNC " + + "SYSRES_SBDATA " + + "SYSRES_SBGUI " + + "SYSRES_SBINTF " + + "SYSRES_SBREFDSC " + + "SYSRES_SQLERRORS " + + "SYSRES_SYSCOMP "; + + // Константы ==> built_in + const CONSTANTS = + sysres_constants + + base_constants + + base_group_name_constants + + decision_block_properties_constants + + file_extension_constants + + job_block_properties_constants + + language_code_constants + + launching_external_applications_constants + + link_kind_constants + + lock_type_constants + + monitor_block_properties_constants + + notice_block_properties_constants + + object_events_constants + + object_params_constants + + other_constants + + privileges_constants + + pseudoreference_code_constants + + requisite_ISBCertificateType_values_constants + + requisite_ISBEDocStorageType_values_constants + + requisite_compType2_values_constants + + requisite_name_constants + + result_constants + + rule_identification_constants + + script_block_properties_constants + + subtask_block_properties_constants + + system_component_constants + + system_dialogs_constants + + system_reference_names_constants + + table_name_constants + + test_constants + + using_the_dialog_windows_constants + + using_the_document_constants + + using_the_EA_and_encryption_constants + + using_the_ISBL_editor_constants + + wait_block_properties_constants + + sysres_common_constants; + + // enum TAccountType + const TAccountType = "atUser atGroup atRole "; + + // enum TActionEnabledMode + const TActionEnabledMode = + "aemEnabledAlways " + + "aemDisabledAlways " + + "aemEnabledOnBrowse " + + "aemEnabledOnEdit " + + "aemDisabledOnBrowseEmpty "; + + // enum TAddPosition + const TAddPosition = "apBegin apEnd "; + + // enum TAlignment + const TAlignment = "alLeft alRight "; + + // enum TAreaShowMode + const TAreaShowMode = + "asmNever " + + "asmNoButCustomize " + + "asmAsLastTime " + + "asmYesButCustomize " + + "asmAlways "; + + // enum TCertificateInvalidationReason + const TCertificateInvalidationReason = "cirCommon cirRevoked "; + + // enum TCertificateType + const TCertificateType = "ctSignature ctEncode ctSignatureEncode "; + + // enum TCheckListBoxItemState + const TCheckListBoxItemState = "clbUnchecked clbChecked clbGrayed "; + + // enum TCloseOnEsc + const TCloseOnEsc = "ceISB ceAlways ceNever "; + + // enum TCompType + const TCompType = + "ctDocument " + + "ctReference " + + "ctScript " + + "ctUnknown " + + "ctReport " + + "ctDialog " + + "ctFunction " + + "ctFolder " + + "ctEDocument " + + "ctTask " + + "ctJob " + + "ctNotice " + + "ctControlJob "; + + // enum TConditionFormat + const TConditionFormat = "cfInternal cfDisplay "; + + // enum TConnectionIntent + const TConnectionIntent = "ciUnspecified ciWrite ciRead "; + + // enum TContentKind + const TContentKind = + "ckFolder " + + "ckEDocument " + + "ckTask " + + "ckJob " + + "ckComponentToken " + + "ckAny " + + "ckReference " + + "ckScript " + + "ckReport " + + "ckDialog "; + + // enum TControlType + const TControlType = + "ctISBLEditor " + + "ctBevel " + + "ctButton " + + "ctCheckListBox " + + "ctComboBox " + + "ctComboEdit " + + "ctGrid " + + "ctDBCheckBox " + + "ctDBComboBox " + + "ctDBEdit " + + "ctDBEllipsis " + + "ctDBMemo " + + "ctDBNavigator " + + "ctDBRadioGroup " + + "ctDBStatusLabel " + + "ctEdit " + + "ctGroupBox " + + "ctInplaceHint " + + "ctMemo " + + "ctPanel " + + "ctListBox " + + "ctRadioButton " + + "ctRichEdit " + + "ctTabSheet " + + "ctWebBrowser " + + "ctImage " + + "ctHyperLink " + + "ctLabel " + + "ctDBMultiEllipsis " + + "ctRibbon " + + "ctRichView " + + "ctInnerPanel " + + "ctPanelGroup " + + "ctBitButton "; + + // enum TCriterionContentType + const TCriterionContentType = + "cctDate " + + "cctInteger " + + "cctNumeric " + + "cctPick " + + "cctReference " + + "cctString " + + "cctText "; + + // enum TCultureType + const TCultureType = "cltInternal cltPrimary cltGUI "; + + // enum TDataSetEventType + const TDataSetEventType = + "dseBeforeOpen " + + "dseAfterOpen " + + "dseBeforeClose " + + "dseAfterClose " + + "dseOnValidDelete " + + "dseBeforeDelete " + + "dseAfterDelete " + + "dseAfterDeleteOutOfTransaction " + + "dseOnDeleteError " + + "dseBeforeInsert " + + "dseAfterInsert " + + "dseOnValidUpdate " + + "dseBeforeUpdate " + + "dseOnUpdateRatifiedRecord " + + "dseAfterUpdate " + + "dseAfterUpdateOutOfTransaction " + + "dseOnUpdateError " + + "dseAfterScroll " + + "dseOnOpenRecord " + + "dseOnCloseRecord " + + "dseBeforeCancel " + + "dseAfterCancel " + + "dseOnUpdateDeadlockError " + + "dseBeforeDetailUpdate " + + "dseOnPrepareUpdate " + + "dseOnAnyRequisiteChange "; + + // enum TDataSetState + const TDataSetState = "dssEdit dssInsert dssBrowse dssInActive "; + + // enum TDateFormatType + const TDateFormatType = "dftDate dftShortDate dftDateTime dftTimeStamp "; + + // enum TDateOffsetType + const TDateOffsetType = "dotDays dotHours dotMinutes dotSeconds "; + + // enum TDateTimeKind + const TDateTimeKind = "dtkndLocal dtkndUTC "; + + // enum TDeaAccessRights + const TDeaAccessRights = "arNone arView arEdit arFull "; + + // enum TDocumentDefaultAction + const TDocumentDefaultAction = "ddaView ddaEdit "; + + // enum TEditMode + const TEditMode = + "emLock " + + "emEdit " + + "emSign " + + "emExportWithLock " + + "emImportWithUnlock " + + "emChangeVersionNote " + + "emOpenForModify " + + "emChangeLifeStage " + + "emDelete " + + "emCreateVersion " + + "emImport " + + "emUnlockExportedWithLock " + + "emStart " + + "emAbort " + + "emReInit " + + "emMarkAsReaded " + + "emMarkAsUnreaded " + + "emPerform " + + "emAccept " + + "emResume " + + "emChangeRights " + + "emEditRoute " + + "emEditObserver " + + "emRecoveryFromLocalCopy " + + "emChangeWorkAccessType " + + "emChangeEncodeTypeToCertificate " + + "emChangeEncodeTypeToPassword " + + "emChangeEncodeTypeToNone " + + "emChangeEncodeTypeToCertificatePassword " + + "emChangeStandardRoute " + + "emGetText " + + "emOpenForView " + + "emMoveToStorage " + + "emCreateObject " + + "emChangeVersionHidden " + + "emDeleteVersion " + + "emChangeLifeCycleStage " + + "emApprovingSign " + + "emExport " + + "emContinue " + + "emLockFromEdit " + + "emUnLockForEdit " + + "emLockForServer " + + "emUnlockFromServer " + + "emDelegateAccessRights " + + "emReEncode "; + + // enum TEditorCloseObservType + const TEditorCloseObservType = "ecotFile ecotProcess "; + + // enum TEdmsApplicationAction + const TEdmsApplicationAction = "eaGet eaCopy eaCreate eaCreateStandardRoute "; + + // enum TEDocumentLockType + const TEDocumentLockType = "edltAll edltNothing edltQuery "; + + // enum TEDocumentStepShowMode + const TEDocumentStepShowMode = "essmText essmCard "; + + // enum TEDocumentStepVersionType + const TEDocumentStepVersionType = "esvtLast esvtLastActive esvtSpecified "; + + // enum TEDocumentStorageFunction + const TEDocumentStorageFunction = "edsfExecutive edsfArchive "; + + // enum TEDocumentStorageType + const TEDocumentStorageType = "edstSQLServer edstFile "; + + // enum TEDocumentVersionSourceType + const TEDocumentVersionSourceType = + "edvstNone edvstEDocumentVersionCopy edvstFile edvstTemplate edvstScannedFile "; + + // enum TEDocumentVersionState + const TEDocumentVersionState = "vsDefault vsDesign vsActive vsObsolete "; + + // enum TEncodeType + const TEncodeType = "etNone etCertificate etPassword etCertificatePassword "; + + // enum TExceptionCategory + const TExceptionCategory = "ecException ecWarning ecInformation "; + + // enum TExportedSignaturesType + const TExportedSignaturesType = "estAll estApprovingOnly "; + + // enum TExportedVersionType + const TExportedVersionType = "evtLast evtLastActive evtQuery "; + + // enum TFieldDataType + const TFieldDataType = + "fdtString " + + "fdtNumeric " + + "fdtInteger " + + "fdtDate " + + "fdtText " + + "fdtUnknown " + + "fdtWideString " + + "fdtLargeInteger "; + + // enum TFolderType + const TFolderType = + "ftInbox " + + "ftOutbox " + + "ftFavorites " + + "ftCommonFolder " + + "ftUserFolder " + + "ftComponents " + + "ftQuickLaunch " + + "ftShortcuts " + + "ftSearch "; + + // enum TGridRowHeight + const TGridRowHeight = "grhAuto " + "grhX1 " + "grhX2 " + "grhX3 "; + + // enum THyperlinkType + const THyperlinkType = "hltText " + "hltRTF " + "hltHTML "; + + // enum TImageFileFormat + const TImageFileFormat = + "iffBMP " + + "iffJPEG " + + "iffMultiPageTIFF " + + "iffSinglePageTIFF " + + "iffTIFF " + + "iffPNG "; + + // enum TImageMode + const TImageMode = "im8bGrayscale " + "im24bRGB " + "im1bMonochrome "; + + // enum TImageType + const TImageType = "itBMP " + "itJPEG " + "itWMF " + "itPNG "; + + // enum TInplaceHintKind + const TInplaceHintKind = + "ikhInformation " + "ikhWarning " + "ikhError " + "ikhNoIcon "; + + // enum TISBLContext + const TISBLContext = + "icUnknown " + + "icScript " + + "icFunction " + + "icIntegratedReport " + + "icAnalyticReport " + + "icDataSetEventHandler " + + "icActionHandler " + + "icFormEventHandler " + + "icLookUpEventHandler " + + "icRequisiteChangeEventHandler " + + "icBeforeSearchEventHandler " + + "icRoleCalculation " + + "icSelectRouteEventHandler " + + "icBlockPropertyCalculation " + + "icBlockQueryParamsEventHandler " + + "icChangeSearchResultEventHandler " + + "icBlockEventHandler " + + "icSubTaskInitEventHandler " + + "icEDocDataSetEventHandler " + + "icEDocLookUpEventHandler " + + "icEDocActionHandler " + + "icEDocFormEventHandler " + + "icEDocRequisiteChangeEventHandler " + + "icStructuredConversionRule " + + "icStructuredConversionEventBefore " + + "icStructuredConversionEventAfter " + + "icWizardEventHandler " + + "icWizardFinishEventHandler " + + "icWizardStepEventHandler " + + "icWizardStepFinishEventHandler " + + "icWizardActionEnableEventHandler " + + "icWizardActionExecuteEventHandler " + + "icCreateJobsHandler " + + "icCreateNoticesHandler " + + "icBeforeLookUpEventHandler " + + "icAfterLookUpEventHandler " + + "icTaskAbortEventHandler " + + "icWorkflowBlockActionHandler " + + "icDialogDataSetEventHandler " + + "icDialogActionHandler " + + "icDialogLookUpEventHandler " + + "icDialogRequisiteChangeEventHandler " + + "icDialogFormEventHandler " + + "icDialogValidCloseEventHandler " + + "icBlockFormEventHandler " + + "icTaskFormEventHandler " + + "icReferenceMethod " + + "icEDocMethod " + + "icDialogMethod " + + "icProcessMessageHandler "; + + // enum TItemShow + const TItemShow = "isShow " + "isHide " + "isByUserSettings "; + + // enum TJobKind + const TJobKind = "jkJob " + "jkNotice " + "jkControlJob "; + + // enum TJoinType + const TJoinType = "jtInner " + "jtLeft " + "jtRight " + "jtFull " + "jtCross "; + + // enum TLabelPos + const TLabelPos = "lbpAbove " + "lbpBelow " + "lbpLeft " + "lbpRight "; + + // enum TLicensingType + const TLicensingType = "eltPerConnection " + "eltPerUser "; + + // enum TLifeCycleStageFontColor + const TLifeCycleStageFontColor = + "sfcUndefined " + + "sfcBlack " + + "sfcGreen " + + "sfcRed " + + "sfcBlue " + + "sfcOrange " + + "sfcLilac "; + + // enum TLifeCycleStageFontStyle + const TLifeCycleStageFontStyle = "sfsItalic " + "sfsStrikeout " + "sfsNormal "; + + // enum TLockableDevelopmentComponentType + const TLockableDevelopmentComponentType = + "ldctStandardRoute " + + "ldctWizard " + + "ldctScript " + + "ldctFunction " + + "ldctRouteBlock " + + "ldctIntegratedReport " + + "ldctAnalyticReport " + + "ldctReferenceType " + + "ldctEDocumentType " + + "ldctDialog " + + "ldctServerEvents "; + + // enum TMaxRecordCountRestrictionType + const TMaxRecordCountRestrictionType = + "mrcrtNone " + "mrcrtUser " + "mrcrtMaximal " + "mrcrtCustom "; + + // enum TRangeValueType + const TRangeValueType = + "vtEqual " + "vtGreaterOrEqual " + "vtLessOrEqual " + "vtRange "; + + // enum TRelativeDate + const TRelativeDate = + "rdYesterday " + + "rdToday " + + "rdTomorrow " + + "rdThisWeek " + + "rdThisMonth " + + "rdThisYear " + + "rdNextMonth " + + "rdNextWeek " + + "rdLastWeek " + + "rdLastMonth "; + + // enum TReportDestination + const TReportDestination = "rdWindow " + "rdFile " + "rdPrinter "; + + // enum TReqDataType + const TReqDataType = + "rdtString " + + "rdtNumeric " + + "rdtInteger " + + "rdtDate " + + "rdtReference " + + "rdtAccount " + + "rdtText " + + "rdtPick " + + "rdtUnknown " + + "rdtLargeInteger " + + "rdtDocument "; + + // enum TRequisiteEventType + const TRequisiteEventType = "reOnChange " + "reOnChangeValues "; + + // enum TSBTimeType + const TSBTimeType = "ttGlobal " + "ttLocal " + "ttUser " + "ttSystem "; + + // enum TSearchShowMode + const TSearchShowMode = + "ssmBrowse " + "ssmSelect " + "ssmMultiSelect " + "ssmBrowseModal "; + + // enum TSelectMode + const TSelectMode = "smSelect " + "smLike " + "smCard "; + + // enum TSignatureType + const TSignatureType = "stNone " + "stAuthenticating " + "stApproving "; + + // enum TSignerContentType + const TSignerContentType = "sctString " + "sctStream "; + + // enum TStringsSortType + const TStringsSortType = "sstAnsiSort " + "sstNaturalSort "; + + // enum TStringValueType + const TStringValueType = "svtEqual " + "svtContain "; + + // enum TStructuredObjectAttributeType + const TStructuredObjectAttributeType = + "soatString " + + "soatNumeric " + + "soatInteger " + + "soatDatetime " + + "soatReferenceRecord " + + "soatText " + + "soatPick " + + "soatBoolean " + + "soatEDocument " + + "soatAccount " + + "soatIntegerCollection " + + "soatNumericCollection " + + "soatStringCollection " + + "soatPickCollection " + + "soatDatetimeCollection " + + "soatBooleanCollection " + + "soatReferenceRecordCollection " + + "soatEDocumentCollection " + + "soatAccountCollection " + + "soatContents " + + "soatUnknown "; + + // enum TTaskAbortReason + const TTaskAbortReason = "tarAbortByUser " + "tarAbortByWorkflowException "; + + // enum TTextValueType + const TTextValueType = "tvtAllWords " + "tvtExactPhrase " + "tvtAnyWord "; + + // enum TUserObjectStatus + const TUserObjectStatus = + "usNone " + + "usCompleted " + + "usRedSquare " + + "usBlueSquare " + + "usYellowSquare " + + "usGreenSquare " + + "usOrangeSquare " + + "usPurpleSquare " + + "usFollowUp "; + + // enum TUserType + const TUserType = + "utUnknown " + + "utUser " + + "utDeveloper " + + "utAdministrator " + + "utSystemDeveloper " + + "utDisconnected "; + + // enum TValuesBuildType + const TValuesBuildType = + "btAnd " + "btDetailAnd " + "btOr " + "btNotOr " + "btOnly "; + + // enum TViewMode + const TViewMode = "vmView " + "vmSelect " + "vmNavigation "; + + // enum TViewSelectionMode + const TViewSelectionMode = + "vsmSingle " + "vsmMultiple " + "vsmMultipleCheck " + "vsmNoSelection "; + + // enum TWizardActionType + const TWizardActionType = + "wfatPrevious " + "wfatNext " + "wfatCancel " + "wfatFinish "; + + // enum TWizardFormElementProperty + const TWizardFormElementProperty = + "wfepUndefined " + + "wfepText3 " + + "wfepText6 " + + "wfepText9 " + + "wfepSpinEdit " + + "wfepDropDown " + + "wfepRadioGroup " + + "wfepFlag " + + "wfepText12 " + + "wfepText15 " + + "wfepText18 " + + "wfepText21 " + + "wfepText24 " + + "wfepText27 " + + "wfepText30 " + + "wfepRadioGroupColumn1 " + + "wfepRadioGroupColumn2 " + + "wfepRadioGroupColumn3 "; + + // enum TWizardFormElementType + const TWizardFormElementType = + "wfetQueryParameter " + "wfetText " + "wfetDelimiter " + "wfetLabel "; + + // enum TWizardParamType + const TWizardParamType = + "wptString " + + "wptInteger " + + "wptNumeric " + + "wptBoolean " + + "wptDateTime " + + "wptPick " + + "wptText " + + "wptUser " + + "wptUserList " + + "wptEDocumentInfo " + + "wptEDocumentInfoList " + + "wptReferenceRecordInfo " + + "wptReferenceRecordInfoList " + + "wptFolderInfo " + + "wptTaskInfo " + + "wptContents " + + "wptFileName " + + "wptDate "; + + // enum TWizardStepResult + const TWizardStepResult = + "wsrComplete " + + "wsrGoNext " + + "wsrGoPrevious " + + "wsrCustom " + + "wsrCancel " + + "wsrGoFinal "; + + // enum TWizardStepType + const TWizardStepType = + "wstForm " + + "wstEDocument " + + "wstTaskCard " + + "wstReferenceRecordCard " + + "wstFinal "; + + // enum TWorkAccessType + const TWorkAccessType = "waAll " + "waPerformers " + "waManual "; + + // enum TWorkflowBlockType + const TWorkflowBlockType = + "wsbStart " + + "wsbFinish " + + "wsbNotice " + + "wsbStep " + + "wsbDecision " + + "wsbWait " + + "wsbMonitor " + + "wsbScript " + + "wsbConnector " + + "wsbSubTask " + + "wsbLifeCycleStage " + + "wsbPause "; + + // enum TWorkflowDataType + const TWorkflowDataType = + "wdtInteger " + + "wdtFloat " + + "wdtString " + + "wdtPick " + + "wdtDateTime " + + "wdtBoolean " + + "wdtTask " + + "wdtJob " + + "wdtFolder " + + "wdtEDocument " + + "wdtReferenceRecord " + + "wdtUser " + + "wdtGroup " + + "wdtRole " + + "wdtIntegerCollection " + + "wdtFloatCollection " + + "wdtStringCollection " + + "wdtPickCollection " + + "wdtDateTimeCollection " + + "wdtBooleanCollection " + + "wdtTaskCollection " + + "wdtJobCollection " + + "wdtFolderCollection " + + "wdtEDocumentCollection " + + "wdtReferenceRecordCollection " + + "wdtUserCollection " + + "wdtGroupCollection " + + "wdtRoleCollection " + + "wdtContents " + + "wdtUserList " + + "wdtSearchDescription " + + "wdtDeadLine " + + "wdtPickSet " + + "wdtAccountCollection "; + + // enum TWorkImportance + const TWorkImportance = "wiLow " + "wiNormal " + "wiHigh "; + + // enum TWorkRouteType + const TWorkRouteType = "wrtSoft " + "wrtHard "; + + // enum TWorkState + const TWorkState = + "wsInit " + + "wsRunning " + + "wsDone " + + "wsControlled " + + "wsAborted " + + "wsContinued "; + + // enum TWorkTextBuildingMode + const TWorkTextBuildingMode = + "wtmFull " + "wtmFromCurrent " + "wtmOnlyCurrent "; + + // Перечисления + const ENUMS = + TAccountType + + TActionEnabledMode + + TAddPosition + + TAlignment + + TAreaShowMode + + TCertificateInvalidationReason + + TCertificateType + + TCheckListBoxItemState + + TCloseOnEsc + + TCompType + + TConditionFormat + + TConnectionIntent + + TContentKind + + TControlType + + TCriterionContentType + + TCultureType + + TDataSetEventType + + TDataSetState + + TDateFormatType + + TDateOffsetType + + TDateTimeKind + + TDeaAccessRights + + TDocumentDefaultAction + + TEditMode + + TEditorCloseObservType + + TEdmsApplicationAction + + TEDocumentLockType + + TEDocumentStepShowMode + + TEDocumentStepVersionType + + TEDocumentStorageFunction + + TEDocumentStorageType + + TEDocumentVersionSourceType + + TEDocumentVersionState + + TEncodeType + + TExceptionCategory + + TExportedSignaturesType + + TExportedVersionType + + TFieldDataType + + TFolderType + + TGridRowHeight + + THyperlinkType + + TImageFileFormat + + TImageMode + + TImageType + + TInplaceHintKind + + TISBLContext + + TItemShow + + TJobKind + + TJoinType + + TLabelPos + + TLicensingType + + TLifeCycleStageFontColor + + TLifeCycleStageFontStyle + + TLockableDevelopmentComponentType + + TMaxRecordCountRestrictionType + + TRangeValueType + + TRelativeDate + + TReportDestination + + TReqDataType + + TRequisiteEventType + + TSBTimeType + + TSearchShowMode + + TSelectMode + + TSignatureType + + TSignerContentType + + TStringsSortType + + TStringValueType + + TStructuredObjectAttributeType + + TTaskAbortReason + + TTextValueType + + TUserObjectStatus + + TUserType + + TValuesBuildType + + TViewMode + + TViewSelectionMode + + TWizardActionType + + TWizardFormElementProperty + + TWizardFormElementType + + TWizardParamType + + TWizardStepResult + + TWizardStepType + + TWorkAccessType + + TWorkflowBlockType + + TWorkflowDataType + + TWorkImportance + + TWorkRouteType + + TWorkState + + TWorkTextBuildingMode; + + // Системные функции ==> SYSFUNCTIONS + const system_functions = + "AddSubString " + + "AdjustLineBreaks " + + "AmountInWords " + + "Analysis " + + "ArrayDimCount " + + "ArrayHighBound " + + "ArrayLowBound " + + "ArrayOf " + + "ArrayReDim " + + "Assert " + + "Assigned " + + "BeginOfMonth " + + "BeginOfPeriod " + + "BuildProfilingOperationAnalysis " + + "CallProcedure " + + "CanReadFile " + + "CArrayElement " + + "CDataSetRequisite " + + "ChangeDate " + + "ChangeReferenceDataset " + + "Char " + + "CharPos " + + "CheckParam " + + "CheckParamValue " + + "CompareStrings " + + "ConstantExists " + + "ControlState " + + "ConvertDateStr " + + "Copy " + + "CopyFile " + + "CreateArray " + + "CreateCachedReference " + + "CreateConnection " + + "CreateDialog " + + "CreateDualListDialog " + + "CreateEditor " + + "CreateException " + + "CreateFile " + + "CreateFolderDialog " + + "CreateInputDialog " + + "CreateLinkFile " + + "CreateList " + + "CreateLock " + + "CreateMemoryDataSet " + + "CreateObject " + + "CreateOpenDialog " + + "CreateProgress " + + "CreateQuery " + + "CreateReference " + + "CreateReport " + + "CreateSaveDialog " + + "CreateScript " + + "CreateSQLPivotFunction " + + "CreateStringList " + + "CreateTreeListSelectDialog " + + "CSelectSQL " + + "CSQL " + + "CSubString " + + "CurrentUserID " + + "CurrentUserName " + + "CurrentVersion " + + "DataSetLocateEx " + + "DateDiff " + + "DateTimeDiff " + + "DateToStr " + + "DayOfWeek " + + "DeleteFile " + + "DirectoryExists " + + "DisableCheckAccessRights " + + "DisableCheckFullShowingRestriction " + + "DisableMassTaskSendingRestrictions " + + "DropTable " + + "DupeString " + + "EditText " + + "EnableCheckAccessRights " + + "EnableCheckFullShowingRestriction " + + "EnableMassTaskSendingRestrictions " + + "EndOfMonth " + + "EndOfPeriod " + + "ExceptionExists " + + "ExceptionsOff " + + "ExceptionsOn " + + "Execute " + + "ExecuteProcess " + + "Exit " + + "ExpandEnvironmentVariables " + + "ExtractFileDrive " + + "ExtractFileExt " + + "ExtractFileName " + + "ExtractFilePath " + + "ExtractParams " + + "FileExists " + + "FileSize " + + "FindFile " + + "FindSubString " + + "FirmContext " + + "ForceDirectories " + + "Format " + + "FormatDate " + + "FormatNumeric " + + "FormatSQLDate " + + "FormatString " + + "FreeException " + + "GetComponent " + + "GetComponentLaunchParam " + + "GetConstant " + + "GetLastException " + + "GetReferenceRecord " + + "GetRefTypeByRefID " + + "GetTableID " + + "GetTempFolder " + + "IfThen " + + "In " + + "IndexOf " + + "InputDialog " + + "InputDialogEx " + + "InteractiveMode " + + "IsFileLocked " + + "IsGraphicFile " + + "IsNumeric " + + "Length " + + "LoadString " + + "LoadStringFmt " + + "LocalTimeToUTC " + + "LowerCase " + + "Max " + + "MessageBox " + + "MessageBoxEx " + + "MimeDecodeBinary " + + "MimeDecodeString " + + "MimeEncodeBinary " + + "MimeEncodeString " + + "Min " + + "MoneyInWords " + + "MoveFile " + + "NewID " + + "Now " + + "OpenFile " + + "Ord " + + "Precision " + + "Raise " + + "ReadCertificateFromFile " + + "ReadFile " + + "ReferenceCodeByID " + + "ReferenceNumber " + + "ReferenceRequisiteMode " + + "ReferenceRequisiteValue " + + "RegionDateSettings " + + "RegionNumberSettings " + + "RegionTimeSettings " + + "RegRead " + + "RegWrite " + + "RenameFile " + + "Replace " + + "Round " + + "SelectServerCode " + + "SelectSQL " + + "ServerDateTime " + + "SetConstant " + + "SetManagedFolderFieldsState " + + "ShowConstantsInputDialog " + + "ShowMessage " + + "Sleep " + + "Split " + + "SQL " + + "SQL2XLSTAB " + + "SQLProfilingSendReport " + + "StrToDate " + + "SubString " + + "SubStringCount " + + "SystemSetting " + + "Time " + + "TimeDiff " + + "Today " + + "Transliterate " + + "Trim " + + "UpperCase " + + "UserStatus " + + "UTCToLocalTime " + + "ValidateXML " + + "VarIsClear " + + "VarIsEmpty " + + "VarIsNull " + + "WorkTimeDiff " + + "WriteFile " + + "WriteFileEx " + + "WriteObjectHistory " + + "Анализ " + + "БазаДанных " + + "БлокЕсть " + + "БлокЕстьРасш " + + "БлокИнфо " + + "БлокСнять " + + "БлокСнятьРасш " + + "БлокУстановить " + + "Ввод " + + "ВводМеню " + + "ВедС " + + "ВедСпр " + + "ВерхняяГраницаМассива " + + "ВнешПрогр " + + "Восст " + + "ВременнаяПапка " + + "Время " + + "ВыборSQL " + + "ВыбратьЗапись " + + "ВыделитьСтр " + + "Вызвать " + + "Выполнить " + + "ВыпПрогр " + + "ГрафическийФайл " + + "ГруппаДополнительно " + + "ДатаВремяСерв " + + "ДеньНедели " + + "ДиалогДаНет " + + "ДлинаСтр " + + "ДобПодстр " + + "ЕПусто " + + "ЕслиТо " + + "ЕЧисло " + + "ЗамПодстр " + + "ЗаписьСправочника " + + "ЗначПоляСпр " + + "ИДТипСпр " + + "ИзвлечьДиск " + + "ИзвлечьИмяФайла " + + "ИзвлечьПуть " + + "ИзвлечьРасширение " + + "ИзмДат " + + "ИзменитьРазмерМассива " + + "ИзмеренийМассива " + + "ИмяОрг " + + "ИмяПоляСпр " + + "Индекс " + + "ИндикаторЗакрыть " + + "ИндикаторОткрыть " + + "ИндикаторШаг " + + "ИнтерактивныйРежим " + + "ИтогТблСпр " + + "КодВидВедСпр " + + "КодВидСпрПоИД " + + "КодПоAnalit " + + "КодСимвола " + + "КодСпр " + + "КолПодстр " + + "КолПроп " + + "КонМес " + + "Конст " + + "КонстЕсть " + + "КонстЗнач " + + "КонТран " + + "КопироватьФайл " + + "КопияСтр " + + "КПериод " + + "КСтрТблСпр " + + "Макс " + + "МаксСтрТблСпр " + + "Массив " + + "Меню " + + "МенюРасш " + + "Мин " + + "НаборДанныхНайтиРасш " + + "НаимВидСпр " + + "НаимПоAnalit " + + "НаимСпр " + + "НастроитьПереводыСтрок " + + "НачМес " + + "НачТран " + + "НижняяГраницаМассива " + + "НомерСпр " + + "НПериод " + + "Окно " + + "Окр " + + "Окружение " + + "ОтлИнфДобавить " + + "ОтлИнфУдалить " + + "Отчет " + + "ОтчетАнал " + + "ОтчетИнт " + + "ПапкаСуществует " + + "Пауза " + + "ПВыборSQL " + + "ПереименоватьФайл " + + "Переменные " + + "ПереместитьФайл " + + "Подстр " + + "ПоискПодстр " + + "ПоискСтр " + + "ПолучитьИДТаблицы " + + "ПользовательДополнительно " + + "ПользовательИД " + + "ПользовательИмя " + + "ПользовательСтатус " + + "Прервать " + + "ПроверитьПараметр " + + "ПроверитьПараметрЗнач " + + "ПроверитьУсловие " + + "РазбСтр " + + "РазнВремя " + + "РазнДат " + + "РазнДатаВремя " + + "РазнРабВремя " + + "РегУстВрем " + + "РегУстДат " + + "РегУстЧсл " + + "РедТекст " + + "РеестрЗапись " + + "РеестрСписокИменПарам " + + "РеестрЧтение " + + "РеквСпр " + + "РеквСпрПр " + + "Сегодня " + + "Сейчас " + + "Сервер " + + "СерверПроцессИД " + + "СертификатФайлСчитать " + + "СжПроб " + + "Символ " + + "СистемаДиректумКод " + + "СистемаИнформация " + + "СистемаКод " + + "Содержит " + + "СоединениеЗакрыть " + + "СоединениеОткрыть " + + "СоздатьДиалог " + + "СоздатьДиалогВыбораИзДвухСписков " + + "СоздатьДиалогВыбораПапки " + + "СоздатьДиалогОткрытияФайла " + + "СоздатьДиалогСохраненияФайла " + + "СоздатьЗапрос " + + "СоздатьИндикатор " + + "СоздатьИсключение " + + "СоздатьКэшированныйСправочник " + + "СоздатьМассив " + + "СоздатьНаборДанных " + + "СоздатьОбъект " + + "СоздатьОтчет " + + "СоздатьПапку " + + "СоздатьРедактор " + + "СоздатьСоединение " + + "СоздатьСписок " + + "СоздатьСписокСтрок " + + "СоздатьСправочник " + + "СоздатьСценарий " + + "СоздСпр " + + "СостСпр " + + "Сохр " + + "СохрСпр " + + "СписокСистем " + + "Спр " + + "Справочник " + + "СпрБлокЕсть " + + "СпрБлокСнять " + + "СпрБлокСнятьРасш " + + "СпрБлокУстановить " + + "СпрИзмНабДан " + + "СпрКод " + + "СпрНомер " + + "СпрОбновить " + + "СпрОткрыть " + + "СпрОтменить " + + "СпрПарам " + + "СпрПолеЗнач " + + "СпрПолеИмя " + + "СпрРекв " + + "СпрРеквВведЗн " + + "СпрРеквНовые " + + "СпрРеквПр " + + "СпрРеквПредЗн " + + "СпрРеквРежим " + + "СпрРеквТипТекст " + + "СпрСоздать " + + "СпрСост " + + "СпрСохранить " + + "СпрТблИтог " + + "СпрТблСтр " + + "СпрТблСтрКол " + + "СпрТблСтрМакс " + + "СпрТблСтрМин " + + "СпрТблСтрПред " + + "СпрТблСтрСлед " + + "СпрТблСтрСозд " + + "СпрТблСтрУд " + + "СпрТекПредст " + + "СпрУдалить " + + "СравнитьСтр " + + "СтрВерхРегистр " + + "СтрНижнРегистр " + + "СтрТблСпр " + + "СумПроп " + + "Сценарий " + + "СценарийПарам " + + "ТекВерсия " + + "ТекОрг " + + "Точн " + + "Тран " + + "Транслитерация " + + "УдалитьТаблицу " + + "УдалитьФайл " + + "УдСпр " + + "УдСтрТблСпр " + + "Уст " + + "УстановкиКонстант " + + "ФайлАтрибутСчитать " + + "ФайлАтрибутУстановить " + + "ФайлВремя " + + "ФайлВремяУстановить " + + "ФайлВыбрать " + + "ФайлЗанят " + + "ФайлЗаписать " + + "ФайлИскать " + + "ФайлКопировать " + + "ФайлМожноЧитать " + + "ФайлОткрыть " + + "ФайлПереименовать " + + "ФайлПерекодировать " + + "ФайлПереместить " + + "ФайлПросмотреть " + + "ФайлРазмер " + + "ФайлСоздать " + + "ФайлСсылкаСоздать " + + "ФайлСуществует " + + "ФайлСчитать " + + "ФайлУдалить " + + "ФмтSQLДат " + + "ФмтДат " + + "ФмтСтр " + + "ФмтЧсл " + + "Формат " + + "ЦМассивЭлемент " + + "ЦНаборДанныхРеквизит " + + "ЦПодстр "; + + // Предопределенные переменные ==> built_in + const predefined_variables = + "AltState " + + "Application " + + "CallType " + + "ComponentTokens " + + "CreatedJobs " + + "CreatedNotices " + + "ControlState " + + "DialogResult " + + "Dialogs " + + "EDocuments " + + "EDocumentVersionSource " + + "Folders " + + "GlobalIDs " + + "Job " + + "Jobs " + + "InputValue " + + "LookUpReference " + + "LookUpRequisiteNames " + + "LookUpSearch " + + "Object " + + "ParentComponent " + + "Processes " + + "References " + + "Requisite " + + "ReportName " + + "Reports " + + "Result " + + "Scripts " + + "Searches " + + "SelectedAttachments " + + "SelectedItems " + + "SelectMode " + + "Sender " + + "ServerEvents " + + "ServiceFactory " + + "ShiftState " + + "SubTask " + + "SystemDialogs " + + "Tasks " + + "Wizard " + + "Wizards " + + "Work " + + "ВызовСпособ " + + "ИмяОтчета " + + "РеквЗнач "; + + // Интерфейсы ==> type + const interfaces = + "IApplication " + + "IAccessRights " + + "IAccountRepository " + + "IAccountSelectionRestrictions " + + "IAction " + + "IActionList " + + "IAdministrationHistoryDescription " + + "IAnchors " + + "IApplication " + + "IArchiveInfo " + + "IAttachment " + + "IAttachmentList " + + "ICheckListBox " + + "ICheckPointedList " + + "IColumn " + + "IComponent " + + "IComponentDescription " + + "IComponentToken " + + "IComponentTokenFactory " + + "IComponentTokenInfo " + + "ICompRecordInfo " + + "IConnection " + + "IContents " + + "IControl " + + "IControlJob " + + "IControlJobInfo " + + "IControlList " + + "ICrypto " + + "ICrypto2 " + + "ICustomJob " + + "ICustomJobInfo " + + "ICustomListBox " + + "ICustomObjectWizardStep " + + "ICustomWork " + + "ICustomWorkInfo " + + "IDataSet " + + "IDataSetAccessInfo " + + "IDataSigner " + + "IDateCriterion " + + "IDateRequisite " + + "IDateRequisiteDescription " + + "IDateValue " + + "IDeaAccessRights " + + "IDeaObjectInfo " + + "IDevelopmentComponentLock " + + "IDialog " + + "IDialogFactory " + + "IDialogPickRequisiteItems " + + "IDialogsFactory " + + "IDICSFactory " + + "IDocRequisite " + + "IDocumentInfo " + + "IDualListDialog " + + "IECertificate " + + "IECertificateInfo " + + "IECertificates " + + "IEditControl " + + "IEditorForm " + + "IEdmsExplorer " + + "IEdmsObject " + + "IEdmsObjectDescription " + + "IEdmsObjectFactory " + + "IEdmsObjectInfo " + + "IEDocument " + + "IEDocumentAccessRights " + + "IEDocumentDescription " + + "IEDocumentEditor " + + "IEDocumentFactory " + + "IEDocumentInfo " + + "IEDocumentStorage " + + "IEDocumentVersion " + + "IEDocumentVersionListDialog " + + "IEDocumentVersionSource " + + "IEDocumentWizardStep " + + "IEDocVerSignature " + + "IEDocVersionState " + + "IEnabledMode " + + "IEncodeProvider " + + "IEncrypter " + + "IEvent " + + "IEventList " + + "IException " + + "IExternalEvents " + + "IExternalHandler " + + "IFactory " + + "IField " + + "IFileDialog " + + "IFolder " + + "IFolderDescription " + + "IFolderDialog " + + "IFolderFactory " + + "IFolderInfo " + + "IForEach " + + "IForm " + + "IFormTitle " + + "IFormWizardStep " + + "IGlobalIDFactory " + + "IGlobalIDInfo " + + "IGrid " + + "IHasher " + + "IHistoryDescription " + + "IHyperLinkControl " + + "IImageButton " + + "IImageControl " + + "IInnerPanel " + + "IInplaceHint " + + "IIntegerCriterion " + + "IIntegerList " + + "IIntegerRequisite " + + "IIntegerValue " + + "IISBLEditorForm " + + "IJob " + + "IJobDescription " + + "IJobFactory " + + "IJobForm " + + "IJobInfo " + + "ILabelControl " + + "ILargeIntegerCriterion " + + "ILargeIntegerRequisite " + + "ILargeIntegerValue " + + "ILicenseInfo " + + "ILifeCycleStage " + + "IList " + + "IListBox " + + "ILocalIDInfo " + + "ILocalization " + + "ILock " + + "IMemoryDataSet " + + "IMessagingFactory " + + "IMetadataRepository " + + "INotice " + + "INoticeInfo " + + "INumericCriterion " + + "INumericRequisite " + + "INumericValue " + + "IObject " + + "IObjectDescription " + + "IObjectImporter " + + "IObjectInfo " + + "IObserver " + + "IPanelGroup " + + "IPickCriterion " + + "IPickProperty " + + "IPickRequisite " + + "IPickRequisiteDescription " + + "IPickRequisiteItem " + + "IPickRequisiteItems " + + "IPickValue " + + "IPrivilege " + + "IPrivilegeList " + + "IProcess " + + "IProcessFactory " + + "IProcessMessage " + + "IProgress " + + "IProperty " + + "IPropertyChangeEvent " + + "IQuery " + + "IReference " + + "IReferenceCriterion " + + "IReferenceEnabledMode " + + "IReferenceFactory " + + "IReferenceHistoryDescription " + + "IReferenceInfo " + + "IReferenceRecordCardWizardStep " + + "IReferenceRequisiteDescription " + + "IReferencesFactory " + + "IReferenceValue " + + "IRefRequisite " + + "IReport " + + "IReportFactory " + + "IRequisite " + + "IRequisiteDescription " + + "IRequisiteDescriptionList " + + "IRequisiteFactory " + + "IRichEdit " + + "IRouteStep " + + "IRule " + + "IRuleList " + + "ISchemeBlock " + + "IScript " + + "IScriptFactory " + + "ISearchCriteria " + + "ISearchCriterion " + + "ISearchDescription " + + "ISearchFactory " + + "ISearchFolderInfo " + + "ISearchForObjectDescription " + + "ISearchResultRestrictions " + + "ISecuredContext " + + "ISelectDialog " + + "IServerEvent " + + "IServerEventFactory " + + "IServiceDialog " + + "IServiceFactory " + + "ISignature " + + "ISignProvider " + + "ISignProvider2 " + + "ISignProvider3 " + + "ISimpleCriterion " + + "IStringCriterion " + + "IStringList " + + "IStringRequisite " + + "IStringRequisiteDescription " + + "IStringValue " + + "ISystemDialogsFactory " + + "ISystemInfo " + + "ITabSheet " + + "ITask " + + "ITaskAbortReasonInfo " + + "ITaskCardWizardStep " + + "ITaskDescription " + + "ITaskFactory " + + "ITaskInfo " + + "ITaskRoute " + + "ITextCriterion " + + "ITextRequisite " + + "ITextValue " + + "ITreeListSelectDialog " + + "IUser " + + "IUserList " + + "IValue " + + "IView " + + "IWebBrowserControl " + + "IWizard " + + "IWizardAction " + + "IWizardFactory " + + "IWizardFormElement " + + "IWizardParam " + + "IWizardPickParam " + + "IWizardReferenceParam " + + "IWizardStep " + + "IWorkAccessRights " + + "IWorkDescription " + + "IWorkflowAskableParam " + + "IWorkflowAskableParams " + + "IWorkflowBlock " + + "IWorkflowBlockResult " + + "IWorkflowEnabledMode " + + "IWorkflowParam " + + "IWorkflowPickParam " + + "IWorkflowReferenceParam " + + "IWorkState " + + "IWorkTreeCustomNode " + + "IWorkTreeJobNode " + + "IWorkTreeTaskNode " + + "IXMLEditorForm " + + "SBCrypto "; + + // built_in : встроенные или библиотечные объекты (константы, перечисления) + const BUILTIN = CONSTANTS + ENUMS; + + // class: встроенные наборы значений, системные объекты, фабрики + const CLASS = predefined_variables; + + // literal : примитивные типы + const LITERAL = "null true false nil "; + + // number : числа + const NUMBERS = { + className: "number", + begin: hljs.NUMBER_RE, + relevance: 0 + }; + + // string : строки + const STRINGS = { + className: "string", + variants: [ + { + begin: '"', + end: '"' + }, + { + begin: "'", + end: "'" + } + ] + }; + + // Токены + const DOCTAGS = { + className: "doctag", + begin: "\\b(?:TODO|DONE|BEGIN|END|STUB|CHG|FIXME|NOTE|BUG|XXX)\\b", + relevance: 0 + }; + + // Однострочный комментарий + const ISBL_LINE_COMMENT_MODE = { + className: "comment", + begin: "//", + end: "$", + relevance: 0, + contains: [ + hljs.PHRASAL_WORDS_MODE, + DOCTAGS + ] + }; + + // Многострочный комментарий + const ISBL_BLOCK_COMMENT_MODE = { + className: "comment", + begin: "/\\*", + end: "\\*/", + relevance: 0, + contains: [ + hljs.PHRASAL_WORDS_MODE, + DOCTAGS + ] + }; + + // comment : комментарии + const COMMENTS = { + variants: [ + ISBL_LINE_COMMENT_MODE, + ISBL_BLOCK_COMMENT_MODE + ] + }; + + // keywords : ключевые слова + const KEYWORDS = { + $pattern: UNDERSCORE_IDENT_RE, + keyword: KEYWORD, + built_in: BUILTIN, + class: CLASS, + literal: LITERAL + }; + + // methods : методы + const METHODS = { + begin: "\\.\\s*" + hljs.UNDERSCORE_IDENT_RE, + keywords: KEYWORDS, + relevance: 0 + }; + + // type : встроенные типы + const TYPES = { + className: "type", + begin: ":[ \\t]*(" + interfaces.trim().replace(/\s/g, "|") + ")", + end: "[ \\t]*=", + excludeEnd: true + }; + + // variables : переменные + const VARIABLES = { + className: "variable", + keywords: KEYWORDS, + begin: UNDERSCORE_IDENT_RE, + relevance: 0, + contains: [ + TYPES, + METHODS + ] + }; + + // Имена функций + const FUNCTION_TITLE = FUNCTION_NAME_IDENT_RE + "\\("; + + const TITLE_MODE = { + className: "title", + keywords: { + $pattern: UNDERSCORE_IDENT_RE, + built_in: system_functions + }, + begin: FUNCTION_TITLE, + end: "\\(", + returnBegin: true, + excludeEnd: true + }; + + // function : функции + const FUNCTIONS = { + className: "function", + begin: FUNCTION_TITLE, + end: "\\)$", + returnBegin: true, + keywords: KEYWORDS, + illegal: "[\\[\\]\\|\\$\\?%,~#@]", + contains: [ + TITLE_MODE, + METHODS, + VARIABLES, + STRINGS, + NUMBERS, + COMMENTS + ] + }; + + return { + name: 'ISBL', + case_insensitive: true, + keywords: KEYWORDS, + illegal: "\\$|\\?|%|,|;$|~|#|@| +Category: common, enterprise +Website: https://www.java.com/ +*/ + +function java(hljs) { + var JAVA_IDENT_RE = '[\u00C0-\u02B8a-zA-Z_$][\u00C0-\u02B8a-zA-Z_$0-9]*'; + var GENERIC_IDENT_RE = JAVA_IDENT_RE + '(<' + JAVA_IDENT_RE + '(\\s*,\\s*' + JAVA_IDENT_RE + ')*>)?'; + var KEYWORDS = 'false synchronized int abstract float private char boolean var static null if const ' + + 'for true while long strictfp finally protected import native final void ' + + 'enum else break transient catch instanceof byte super volatile case assert short ' + + 'package default double public try this switch continue throws protected public private ' + + 'module requires exports do'; + + var ANNOTATION = { + className: 'meta', + begin: '@' + JAVA_IDENT_RE, + contains: [ + { + begin: /\(/, + end: /\)/, + contains: ["self"] // allow nested () inside our annotation + }, + ] + }; + const NUMBER = NUMERIC; + + return { + name: 'Java', + aliases: ['jsp'], + keywords: KEYWORDS, + illegal: /<\/|#/, + contains: [ + hljs.COMMENT( + '/\\*\\*', + '\\*/', + { + relevance: 0, + contains: [ + { + // eat up @'s in emails to prevent them to be recognized as doctags + begin: /\w+@/, relevance: 0 + }, + { + className: 'doctag', + begin: '@[A-Za-z]+' + } + ] + } + ), + // relevance boost + { + begin: /import java\.[a-z]+\./, + keywords: "import", + relevance: 2 + }, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + { + className: 'class', + beginKeywords: 'class interface enum', end: /[{;=]/, excludeEnd: true, + // TODO: can this be removed somehow? + // an extra boost because Java is more popular than other languages with + // this same syntax feature (this is just to preserve our tests passing + // for now) + relevance: 1, + keywords: 'class interface enum', + illegal: /[:"\[\]]/, + contains: [ + { beginKeywords: 'extends implements' }, + hljs.UNDERSCORE_TITLE_MODE + ] + }, + { + // Expression keywords prevent 'keyword Name(...)' from being + // recognized as a function definition + beginKeywords: 'new throw return else', + relevance: 0 + }, + { + className: 'class', + begin: 'record\\s+' + hljs.UNDERSCORE_IDENT_RE + '\\s*\\(', + returnBegin: true, + excludeEnd: true, + end: /[{;=]/, + keywords: KEYWORDS, + contains: [ + { beginKeywords: "record" }, + { + begin: hljs.UNDERSCORE_IDENT_RE + '\\s*\\(', + returnBegin: true, + relevance: 0, + contains: [hljs.UNDERSCORE_TITLE_MODE] + }, + { + className: 'params', + begin: /\(/, end: /\)/, + keywords: KEYWORDS, + relevance: 0, + contains: [ + hljs.C_BLOCK_COMMENT_MODE + ] + }, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE + ] + }, + { + className: 'function', + begin: '(' + GENERIC_IDENT_RE + '\\s+)+' + hljs.UNDERSCORE_IDENT_RE + '\\s*\\(', returnBegin: true, end: /[{;=]/, + excludeEnd: true, + keywords: KEYWORDS, + contains: [ + { + begin: hljs.UNDERSCORE_IDENT_RE + '\\s*\\(', returnBegin: true, + relevance: 0, + contains: [hljs.UNDERSCORE_TITLE_MODE] + }, + { + className: 'params', + begin: /\(/, end: /\)/, + keywords: KEYWORDS, + relevance: 0, + contains: [ + ANNOTATION, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + NUMBER, + hljs.C_BLOCK_COMMENT_MODE + ] + }, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE + ] + }, + NUMBER, + ANNOTATION + ] + }; +} + +module.exports = java; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/javascript.js b/claude-code-source/node_modules/highlight.js/lib/languages/javascript.js new file mode 100644 index 00000000..bfbc616a --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/javascript.js @@ -0,0 +1,604 @@ +const IDENT_RE = '[A-Za-z$_][0-9A-Za-z$_]*'; +const KEYWORDS = [ + "as", // for exports + "in", + "of", + "if", + "for", + "while", + "finally", + "var", + "new", + "function", + "do", + "return", + "void", + "else", + "break", + "catch", + "instanceof", + "with", + "throw", + "case", + "default", + "try", + "switch", + "continue", + "typeof", + "delete", + "let", + "yield", + "const", + "class", + // JS handles these with a special rule + // "get", + // "set", + "debugger", + "async", + "await", + "static", + "import", + "from", + "export", + "extends" +]; +const LITERALS = [ + "true", + "false", + "null", + "undefined", + "NaN", + "Infinity" +]; + +const TYPES = [ + "Intl", + "DataView", + "Number", + "Math", + "Date", + "String", + "RegExp", + "Object", + "Function", + "Boolean", + "Error", + "Symbol", + "Set", + "Map", + "WeakSet", + "WeakMap", + "Proxy", + "Reflect", + "JSON", + "Promise", + "Float64Array", + "Int16Array", + "Int32Array", + "Int8Array", + "Uint16Array", + "Uint32Array", + "Float32Array", + "Array", + "Uint8Array", + "Uint8ClampedArray", + "ArrayBuffer", + "BigInt64Array", + "BigUint64Array", + "BigInt" +]; + +const ERROR_TYPES = [ + "EvalError", + "InternalError", + "RangeError", + "ReferenceError", + "SyntaxError", + "TypeError", + "URIError" +]; + +const BUILT_IN_GLOBALS = [ + "setInterval", + "setTimeout", + "clearInterval", + "clearTimeout", + + "require", + "exports", + + "eval", + "isFinite", + "isNaN", + "parseFloat", + "parseInt", + "decodeURI", + "decodeURIComponent", + "encodeURI", + "encodeURIComponent", + "escape", + "unescape" +]; + +const BUILT_IN_VARIABLES = [ + "arguments", + "this", + "super", + "console", + "window", + "document", + "localStorage", + "module", + "global" // Node.js +]; + +const BUILT_INS = [].concat( + BUILT_IN_GLOBALS, + BUILT_IN_VARIABLES, + TYPES, + ERROR_TYPES +); + +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function lookahead(re) { + return concat('(?=', re, ')'); +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/* +Language: JavaScript +Description: JavaScript (JS) is a lightweight, interpreted, or just-in-time compiled programming language with first-class functions. +Category: common, scripting +Website: https://developer.mozilla.org/en-US/docs/Web/JavaScript +*/ + +/** @type LanguageFn */ +function javascript(hljs) { + /** + * Takes a string like " { + const tag = "', + end: '' + }; + const XML_TAG = { + begin: /<[A-Za-z0-9\\._:-]+/, + end: /\/[A-Za-z0-9\\._:-]+>|\/>/, + /** + * @param {RegExpMatchArray} match + * @param {CallbackResponse} response + */ + isTrulyOpeningTag: (match, response) => { + const afterMatchIndex = match[0].length + match.index; + const nextChar = match.input[afterMatchIndex]; + // nested type? + // HTML should not include another raw `<` inside a tag + // But a type might: `>`, etc. + if (nextChar === "<") { + response.ignoreMatch(); + return; + } + // + // This is now either a tag or a type. + if (nextChar === ">") { + // if we cannot find a matching closing tag, then we + // will ignore it + if (!hasClosingTag(match, { after: afterMatchIndex })) { + response.ignoreMatch(); + } + } + } + }; + const KEYWORDS$1 = { + $pattern: IDENT_RE, + keyword: KEYWORDS, + literal: LITERALS, + built_in: BUILT_INS + }; + + // https://tc39.es/ecma262/#sec-literals-numeric-literals + const decimalDigits = '[0-9](_?[0-9])*'; + const frac = `\\.(${decimalDigits})`; + // DecimalIntegerLiteral, including Annex B NonOctalDecimalIntegerLiteral + // https://tc39.es/ecma262/#sec-additional-syntax-numeric-literals + const decimalInteger = `0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*`; + const NUMBER = { + className: 'number', + variants: [ + // DecimalLiteral + { begin: `(\\b(${decimalInteger})((${frac})|\\.)?|(${frac}))` + + `[eE][+-]?(${decimalDigits})\\b` }, + { begin: `\\b(${decimalInteger})\\b((${frac})\\b|\\.)?|(${frac})\\b` }, + + // DecimalBigIntegerLiteral + { begin: `\\b(0|[1-9](_?[0-9])*)n\\b` }, + + // NonDecimalIntegerLiteral + { begin: "\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b" }, + { begin: "\\b0[bB][0-1](_?[0-1])*n?\\b" }, + { begin: "\\b0[oO][0-7](_?[0-7])*n?\\b" }, + + // LegacyOctalIntegerLiteral (does not include underscore separators) + // https://tc39.es/ecma262/#sec-additional-syntax-numeric-literals + { begin: "\\b0[0-7]+n?\\b" }, + ], + relevance: 0 + }; + + const SUBST = { + className: 'subst', + begin: '\\$\\{', + end: '\\}', + keywords: KEYWORDS$1, + contains: [] // defined later + }; + const HTML_TEMPLATE = { + begin: 'html`', + end: '', + starts: { + end: '`', + returnEnd: false, + contains: [ + hljs.BACKSLASH_ESCAPE, + SUBST + ], + subLanguage: 'xml' + } + }; + const CSS_TEMPLATE = { + begin: 'css`', + end: '', + starts: { + end: '`', + returnEnd: false, + contains: [ + hljs.BACKSLASH_ESCAPE, + SUBST + ], + subLanguage: 'css' + } + }; + const TEMPLATE_STRING = { + className: 'string', + begin: '`', + end: '`', + contains: [ + hljs.BACKSLASH_ESCAPE, + SUBST + ] + }; + const JSDOC_COMMENT = hljs.COMMENT( + /\/\*\*(?!\/)/, + '\\*/', + { + relevance: 0, + contains: [ + { + className: 'doctag', + begin: '@[A-Za-z]+', + contains: [ + { + className: 'type', + begin: '\\{', + end: '\\}', + relevance: 0 + }, + { + className: 'variable', + begin: IDENT_RE$1 + '(?=\\s*(-)|$)', + endsParent: true, + relevance: 0 + }, + // eat spaces (not newlines) so we can find + // types or variables + { + begin: /(?=[^\n])\s/, + relevance: 0 + } + ] + } + ] + } + ); + const COMMENT = { + className: "comment", + variants: [ + JSDOC_COMMENT, + hljs.C_BLOCK_COMMENT_MODE, + hljs.C_LINE_COMMENT_MODE + ] + }; + const SUBST_INTERNALS = [ + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + HTML_TEMPLATE, + CSS_TEMPLATE, + TEMPLATE_STRING, + NUMBER, + hljs.REGEXP_MODE + ]; + SUBST.contains = SUBST_INTERNALS + .concat({ + // we need to pair up {} inside our subst to prevent + // it from ending too early by matching another } + begin: /\{/, + end: /\}/, + keywords: KEYWORDS$1, + contains: [ + "self" + ].concat(SUBST_INTERNALS) + }); + const SUBST_AND_COMMENTS = [].concat(COMMENT, SUBST.contains); + const PARAMS_CONTAINS = SUBST_AND_COMMENTS.concat([ + // eat recursive parens in sub expressions + { + begin: /\(/, + end: /\)/, + keywords: KEYWORDS$1, + contains: ["self"].concat(SUBST_AND_COMMENTS) + } + ]); + const PARAMS = { + className: 'params', + begin: /\(/, + end: /\)/, + excludeBegin: true, + excludeEnd: true, + keywords: KEYWORDS$1, + contains: PARAMS_CONTAINS + }; + + return { + name: 'Javascript', + aliases: ['js', 'jsx', 'mjs', 'cjs'], + keywords: KEYWORDS$1, + // this will be extended by TypeScript + exports: { PARAMS_CONTAINS }, + illegal: /#(?![$_A-z])/, + contains: [ + hljs.SHEBANG({ + label: "shebang", + binary: "node", + relevance: 5 + }), + { + label: "use_strict", + className: 'meta', + relevance: 10, + begin: /^\s*['"]use (strict|asm)['"]/ + }, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + HTML_TEMPLATE, + CSS_TEMPLATE, + TEMPLATE_STRING, + COMMENT, + NUMBER, + { // object attr container + begin: concat(/[{,\n]\s*/, + // we need to look ahead to make sure that we actually have an + // attribute coming up so we don't steal a comma from a potential + // "value" container + // + // NOTE: this might not work how you think. We don't actually always + // enter this mode and stay. Instead it might merely match `, + // ` and then immediately end after the , because it + // fails to find any actual attrs. But this still does the job because + // it prevents the value contain rule from grabbing this instead and + // prevening this rule from firing when we actually DO have keys. + lookahead(concat( + // we also need to allow for multiple possible comments inbetween + // the first key:value pairing + /(((\/\/.*$)|(\/\*(\*[^/]|[^*])*\*\/))\s*)*/, + IDENT_RE$1 + '\\s*:'))), + relevance: 0, + contains: [ + { + className: 'attr', + begin: IDENT_RE$1 + lookahead('\\s*:'), + relevance: 0 + } + ] + }, + { // "value" container + begin: '(' + hljs.RE_STARTERS_RE + '|\\b(case|return|throw)\\b)\\s*', + keywords: 'return throw case', + contains: [ + COMMENT, + hljs.REGEXP_MODE, + { + className: 'function', + // we have to count the parens to make sure we actually have the + // correct bounding ( ) before the =>. There could be any number of + // sub-expressions inside also surrounded by parens. + begin: '(\\(' + + '[^()]*(\\(' + + '[^()]*(\\(' + + '[^()]*' + + '\\)[^()]*)*' + + '\\)[^()]*)*' + + '\\)|' + hljs.UNDERSCORE_IDENT_RE + ')\\s*=>', + returnBegin: true, + end: '\\s*=>', + contains: [ + { + className: 'params', + variants: [ + { + begin: hljs.UNDERSCORE_IDENT_RE, + relevance: 0 + }, + { + className: null, + begin: /\(\s*\)/, + skip: true + }, + { + begin: /\(/, + end: /\)/, + excludeBegin: true, + excludeEnd: true, + keywords: KEYWORDS$1, + contains: PARAMS_CONTAINS + } + ] + } + ] + }, + { // could be a comma delimited list of params to a function call + begin: /,/, relevance: 0 + }, + { + className: '', + begin: /\s/, + end: /\s*/, + skip: true + }, + { // JSX + variants: [ + { begin: FRAGMENT.begin, end: FRAGMENT.end }, + { + begin: XML_TAG.begin, + // we carefully check the opening tag to see if it truly + // is a tag and not a false positive + 'on:begin': XML_TAG.isTrulyOpeningTag, + end: XML_TAG.end + } + ], + subLanguage: 'xml', + contains: [ + { + begin: XML_TAG.begin, + end: XML_TAG.end, + skip: true, + contains: ['self'] + } + ] + } + ], + relevance: 0 + }, + { + className: 'function', + beginKeywords: 'function', + end: /[{;]/, + excludeEnd: true, + keywords: KEYWORDS$1, + contains: [ + 'self', + hljs.inherit(hljs.TITLE_MODE, { begin: IDENT_RE$1 }), + PARAMS + ], + illegal: /%/ + }, + { + // prevent this from getting swallowed up by function + // since they appear "function like" + beginKeywords: "while if switch catch for" + }, + { + className: 'function', + // we have to count the parens to make sure we actually have the correct + // bounding ( ). There could be any number of sub-expressions inside + // also surrounded by parens. + begin: hljs.UNDERSCORE_IDENT_RE + + '\\(' + // first parens + '[^()]*(\\(' + + '[^()]*(\\(' + + '[^()]*' + + '\\)[^()]*)*' + + '\\)[^()]*)*' + + '\\)\\s*\\{', // end parens + returnBegin:true, + contains: [ + PARAMS, + hljs.inherit(hljs.TITLE_MODE, { begin: IDENT_RE$1 }), + ] + }, + // hack: prevents detection of keywords in some circumstances + // .keyword() + // $keyword = x + { + variants: [ + { begin: '\\.' + IDENT_RE$1 }, + { begin: '\\$' + IDENT_RE$1 } + ], + relevance: 0 + }, + { // ES6 class + className: 'class', + beginKeywords: 'class', + end: /[{;=]/, + excludeEnd: true, + illegal: /[:"[\]]/, + contains: [ + { beginKeywords: 'extends' }, + hljs.UNDERSCORE_TITLE_MODE + ] + }, + { + begin: /\b(?=constructor)/, + end: /[{;]/, + excludeEnd: true, + contains: [ + hljs.inherit(hljs.TITLE_MODE, { begin: IDENT_RE$1 }), + 'self', + PARAMS + ] + }, + { + begin: '(get|set)\\s+(?=' + IDENT_RE$1 + '\\()', + end: /\{/, + keywords: "get set", + contains: [ + hljs.inherit(hljs.TITLE_MODE, { begin: IDENT_RE$1 }), + { begin: /\(\)/ }, // eat to avoid empty params + PARAMS + ] + }, + { + begin: /\$[(.]/ // relevance booster for a pattern common to JS libs: `$(something)` and `$.something` + } + ] + }; +} + +module.exports = javascript; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/jboss-cli.js b/claude-code-source/node_modules/highlight.js/lib/languages/jboss-cli.js new file mode 100644 index 00000000..64519d1c --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/jboss-cli.js @@ -0,0 +1,63 @@ +/* + Language: JBoss CLI + Author: Raphaël Parrëe + Description: language definition jboss cli + Website: https://docs.jboss.org/author/display/WFLY/Command+Line+Interface + Category: config + */ + +function jbossCli(hljs) { + const PARAM = { + begin: /[\w-]+ *=/, + returnBegin: true, + relevance: 0, + contains: [ + { + className: 'attr', + begin: /[\w-]+/ + } + ] + }; + const PARAMSBLOCK = { + className: 'params', + begin: /\(/, + end: /\)/, + contains: [PARAM], + relevance: 0 + }; + const OPERATION = { + className: 'function', + begin: /:[\w\-.]+/, + relevance: 0 + }; + const PATH = { + className: 'string', + begin: /\B([\/.])[\w\-.\/=]+/ + }; + const COMMAND_PARAMS = { + className: 'params', + begin: /--[\w\-=\/]+/ + }; + return { + name: 'JBoss CLI', + aliases: ['wildfly-cli'], + keywords: { + $pattern: '[a-z\-]+', + keyword: 'alias batch cd clear command connect connection-factory connection-info data-source deploy ' + + 'deployment-info deployment-overlay echo echo-dmr help history if jdbc-driver-info jms-queue|20 jms-topic|20 ls ' + + 'patch pwd quit read-attribute read-operation reload rollout-plan run-batch set shutdown try unalias ' + + 'undeploy unset version xa-data-source', // module + literal: 'true false' + }, + contains: [ + hljs.HASH_COMMENT_MODE, + hljs.QUOTE_STRING_MODE, + COMMAND_PARAMS, + OPERATION, + PATH, + PARAMSBLOCK + ] + }; +} + +module.exports = jbossCli; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/json.js b/claude-code-source/node_modules/highlight.js/lib/languages/json.js new file mode 100644 index 00000000..83e52bb3 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/json.js @@ -0,0 +1,63 @@ +/* +Language: JSON +Description: JSON (JavaScript Object Notation) is a lightweight data-interchange format. +Author: Ivan Sagalaev +Website: http://www.json.org +Category: common, protocols +*/ + +function json(hljs) { + const LITERALS = { + literal: 'true false null' + }; + const ALLOWED_COMMENTS = [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE + ]; + const TYPES = [ + hljs.QUOTE_STRING_MODE, + hljs.C_NUMBER_MODE + ]; + const VALUE_CONTAINER = { + end: ',', + endsWithParent: true, + excludeEnd: true, + contains: TYPES, + keywords: LITERALS + }; + const OBJECT = { + begin: /\{/, + end: /\}/, + contains: [ + { + className: 'attr', + begin: /"/, + end: /"/, + contains: [hljs.BACKSLASH_ESCAPE], + illegal: '\\n' + }, + hljs.inherit(VALUE_CONTAINER, { + begin: /:/ + }) + ].concat(ALLOWED_COMMENTS), + illegal: '\\S' + }; + const ARRAY = { + begin: '\\[', + end: '\\]', + contains: [hljs.inherit(VALUE_CONTAINER)], // inherit is a workaround for a bug that makes shared modes with endsWithParent compile only the ending of one of the parents + illegal: '\\S' + }; + TYPES.push(OBJECT, ARRAY); + ALLOWED_COMMENTS.forEach(function(rule) { + TYPES.push(rule); + }); + return { + name: 'JSON', + contains: TYPES, + keywords: LITERALS, + illegal: '\\S' + }; +} + +module.exports = json; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/julia-repl.js b/claude-code-source/node_modules/highlight.js/lib/languages/julia-repl.js new file mode 100644 index 00000000..60fec985 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/julia-repl.js @@ -0,0 +1,50 @@ +/* +Language: Julia REPL +Description: Julia REPL sessions +Author: Morten Piibeleht +Website: https://julialang.org +Requires: julia.js + +The Julia REPL code blocks look something like the following: + + julia> function foo(x) + x + 1 + end + foo (generic function with 1 method) + +They start on a new line with "julia>". Usually there should also be a space after this, but +we also allow the code to start right after the > character. The code may run over multiple +lines, but the additional lines must start with six spaces (i.e. be indented to match +"julia>"). The rest of the code is assumed to be output from the executed code and will be +left un-highlighted. + +Using simply spaces to identify line continuations may get a false-positive if the output +also prints out six spaces, but such cases should be rare. +*/ + +function juliaRepl(hljs) { + return { + name: 'Julia REPL', + contains: [ + { + className: 'meta', + begin: /^julia>/, + relevance: 10, + starts: { + // end the highlighting if we are on a new line and the line does not have at + // least six spaces in the beginning + end: /^(?![ ]{6})/, + subLanguage: 'julia' + }, + // jldoctest Markdown blocks are used in the Julia manual and package docs indicate + // code snippets that should be verified when the documentation is built. They can be + // either REPL-like or script-like, but are usually REPL-like and therefore we apply + // julia-repl highlighting to them. More information can be found in Documenter's + // manual: https://juliadocs.github.io/Documenter.jl/latest/man/doctests.html + aliases: ['jldoctest'] + } + ] + } +} + +module.exports = juliaRepl; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/julia.js b/claude-code-source/node_modules/highlight.js/lib/languages/julia.js new file mode 100644 index 00000000..4486357b --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/julia.js @@ -0,0 +1,416 @@ +/* +Language: Julia +Description: Julia is a high-level, high-performance, dynamic programming language. +Author: Kenta Sato +Contributors: Alex Arslan , Fredrik Ekre +Website: https://julialang.org +*/ + +function julia(hljs) { + // Since there are numerous special names in Julia, it is too much trouble + // to maintain them by hand. Hence these names (i.e. keywords, literals and + // built-ins) are automatically generated from Julia 1.5.2 itself through + // the following scripts for each. + + // ref: https://docs.julialang.org/en/v1/manual/variables/#Allowed-Variable-Names + var VARIABLE_NAME_RE = '[A-Za-z_\\u00A1-\\uFFFF][A-Za-z_0-9\\u00A1-\\uFFFF]*'; + + // # keyword generator, multi-word keywords handled manually below (Julia 1.5.2) + // import REPL.REPLCompletions + // res = String["in", "isa", "where"] + // for kw in collect(x.keyword for x in REPLCompletions.complete_keyword("")) + // if !(contains(kw, " ") || kw == "struct") + // push!(res, kw) + // end + // end + // sort!(unique!(res)) + // foreach(x -> println("\'", x, "\',"), res) + var KEYWORD_LIST = [ + 'baremodule', + 'begin', + 'break', + 'catch', + 'ccall', + 'const', + 'continue', + 'do', + 'else', + 'elseif', + 'end', + 'export', + 'false', + 'finally', + 'for', + 'function', + 'global', + 'if', + 'import', + 'in', + 'isa', + 'let', + 'local', + 'macro', + 'module', + 'quote', + 'return', + 'true', + 'try', + 'using', + 'where', + 'while', + ]; + + // # literal generator (Julia 1.5.2) + // import REPL.REPLCompletions + // res = String["true", "false"] + // for compl in filter!(x -> isa(x, REPLCompletions.ModuleCompletion) && (x.parent === Base || x.parent === Core), + // REPLCompletions.completions("", 0)[1]) + // try + // v = eval(Symbol(compl.mod)) + // if !(v isa Function || v isa Type || v isa TypeVar || v isa Module || v isa Colon) + // push!(res, compl.mod) + // end + // catch e + // end + // end + // sort!(unique!(res)) + // foreach(x -> println("\'", x, "\',"), res) + var LITERAL_LIST = [ + 'ARGS', + 'C_NULL', + 'DEPOT_PATH', + 'ENDIAN_BOM', + 'ENV', + 'Inf', + 'Inf16', + 'Inf32', + 'Inf64', + 'InsertionSort', + 'LOAD_PATH', + 'MergeSort', + 'NaN', + 'NaN16', + 'NaN32', + 'NaN64', + 'PROGRAM_FILE', + 'QuickSort', + 'RoundDown', + 'RoundFromZero', + 'RoundNearest', + 'RoundNearestTiesAway', + 'RoundNearestTiesUp', + 'RoundToZero', + 'RoundUp', + 'VERSION|0', + 'devnull', + 'false', + 'im', + 'missing', + 'nothing', + 'pi', + 'stderr', + 'stdin', + 'stdout', + 'true', + 'undef', + 'π', + 'ℯ', + ]; + + // # built_in generator (Julia 1.5.2) + // import REPL.REPLCompletions + // res = String[] + // for compl in filter!(x -> isa(x, REPLCompletions.ModuleCompletion) && (x.parent === Base || x.parent === Core), + // REPLCompletions.completions("", 0)[1]) + // try + // v = eval(Symbol(compl.mod)) + // if (v isa Type || v isa TypeVar) && (compl.mod != "=>") + // push!(res, compl.mod) + // end + // catch e + // end + // end + // sort!(unique!(res)) + // foreach(x -> println("\'", x, "\',"), res) + var BUILT_IN_LIST = [ + 'AbstractArray', + 'AbstractChannel', + 'AbstractChar', + 'AbstractDict', + 'AbstractDisplay', + 'AbstractFloat', + 'AbstractIrrational', + 'AbstractMatrix', + 'AbstractRange', + 'AbstractSet', + 'AbstractString', + 'AbstractUnitRange', + 'AbstractVecOrMat', + 'AbstractVector', + 'Any', + 'ArgumentError', + 'Array', + 'AssertionError', + 'BigFloat', + 'BigInt', + 'BitArray', + 'BitMatrix', + 'BitSet', + 'BitVector', + 'Bool', + 'BoundsError', + 'CapturedException', + 'CartesianIndex', + 'CartesianIndices', + 'Cchar', + 'Cdouble', + 'Cfloat', + 'Channel', + 'Char', + 'Cint', + 'Cintmax_t', + 'Clong', + 'Clonglong', + 'Cmd', + 'Colon', + 'Complex', + 'ComplexF16', + 'ComplexF32', + 'ComplexF64', + 'CompositeException', + 'Condition', + 'Cptrdiff_t', + 'Cshort', + 'Csize_t', + 'Cssize_t', + 'Cstring', + 'Cuchar', + 'Cuint', + 'Cuintmax_t', + 'Culong', + 'Culonglong', + 'Cushort', + 'Cvoid', + 'Cwchar_t', + 'Cwstring', + 'DataType', + 'DenseArray', + 'DenseMatrix', + 'DenseVecOrMat', + 'DenseVector', + 'Dict', + 'DimensionMismatch', + 'Dims', + 'DivideError', + 'DomainError', + 'EOFError', + 'Enum', + 'ErrorException', + 'Exception', + 'ExponentialBackOff', + 'Expr', + 'Float16', + 'Float32', + 'Float64', + 'Function', + 'GlobalRef', + 'HTML', + 'IO', + 'IOBuffer', + 'IOContext', + 'IOStream', + 'IdDict', + 'IndexCartesian', + 'IndexLinear', + 'IndexStyle', + 'InexactError', + 'InitError', + 'Int', + 'Int128', + 'Int16', + 'Int32', + 'Int64', + 'Int8', + 'Integer', + 'InterruptException', + 'InvalidStateException', + 'Irrational', + 'KeyError', + 'LinRange', + 'LineNumberNode', + 'LinearIndices', + 'LoadError', + 'MIME', + 'Matrix', + 'Method', + 'MethodError', + 'Missing', + 'MissingException', + 'Module', + 'NTuple', + 'NamedTuple', + 'Nothing', + 'Number', + 'OrdinalRange', + 'OutOfMemoryError', + 'OverflowError', + 'Pair', + 'PartialQuickSort', + 'PermutedDimsArray', + 'Pipe', + 'ProcessFailedException', + 'Ptr', + 'QuoteNode', + 'Rational', + 'RawFD', + 'ReadOnlyMemoryError', + 'Real', + 'ReentrantLock', + 'Ref', + 'Regex', + 'RegexMatch', + 'RoundingMode', + 'SegmentationFault', + 'Set', + 'Signed', + 'Some', + 'StackOverflowError', + 'StepRange', + 'StepRangeLen', + 'StridedArray', + 'StridedMatrix', + 'StridedVecOrMat', + 'StridedVector', + 'String', + 'StringIndexError', + 'SubArray', + 'SubString', + 'SubstitutionString', + 'Symbol', + 'SystemError', + 'Task', + 'TaskFailedException', + 'Text', + 'TextDisplay', + 'Timer', + 'Tuple', + 'Type', + 'TypeError', + 'TypeVar', + 'UInt', + 'UInt128', + 'UInt16', + 'UInt32', + 'UInt64', + 'UInt8', + 'UndefInitializer', + 'UndefKeywordError', + 'UndefRefError', + 'UndefVarError', + 'Union', + 'UnionAll', + 'UnitRange', + 'Unsigned', + 'Val', + 'Vararg', + 'VecElement', + 'VecOrMat', + 'Vector', + 'VersionNumber', + 'WeakKeyDict', + 'WeakRef', + ]; + + var KEYWORDS = { + $pattern: VARIABLE_NAME_RE, + keyword: KEYWORD_LIST, + literal: LITERAL_LIST, + built_in: BUILT_IN_LIST, + }; + + // placeholder for recursive self-reference + var DEFAULT = { + keywords: KEYWORDS, illegal: /<\// + }; + + // ref: https://docs.julialang.org/en/v1/manual/integers-and-floating-point-numbers/ + var NUMBER = { + className: 'number', + // supported numeric literals: + // * binary literal (e.g. 0x10) + // * octal literal (e.g. 0o76543210) + // * hexadecimal literal (e.g. 0xfedcba876543210) + // * hexadecimal floating point literal (e.g. 0x1p0, 0x1.2p2) + // * decimal literal (e.g. 9876543210, 100_000_000) + // * floating pointe literal (e.g. 1.2, 1.2f, .2, 1., 1.2e10, 1.2e-10) + begin: /(\b0x[\d_]*(\.[\d_]*)?|0x\.\d[\d_]*)p[-+]?\d+|\b0[box][a-fA-F0-9][a-fA-F0-9_]*|(\b\d[\d_]*(\.[\d_]*)?|\.\d[\d_]*)([eEfF][-+]?\d+)?/, + relevance: 0 + }; + + var CHAR = { + className: 'string', + begin: /'(.|\\[xXuU][a-zA-Z0-9]+)'/ + }; + + var INTERPOLATION = { + className: 'subst', + begin: /\$\(/, end: /\)/, + keywords: KEYWORDS + }; + + var INTERPOLATED_VARIABLE = { + className: 'variable', + begin: '\\$' + VARIABLE_NAME_RE + }; + + // TODO: neatly escape normal code in string literal + var STRING = { + className: 'string', + contains: [hljs.BACKSLASH_ESCAPE, INTERPOLATION, INTERPOLATED_VARIABLE], + variants: [ + { begin: /\w*"""/, end: /"""\w*/, relevance: 10 }, + { begin: /\w*"/, end: /"\w*/ } + ] + }; + + var COMMAND = { + className: 'string', + contains: [hljs.BACKSLASH_ESCAPE, INTERPOLATION, INTERPOLATED_VARIABLE], + begin: '`', end: '`' + }; + + var MACROCALL = { + className: 'meta', + begin: '@' + VARIABLE_NAME_RE + }; + + var COMMENT = { + className: 'comment', + variants: [ + { begin: '#=', end: '=#', relevance: 10 }, + { begin: '#', end: '$' } + ] + }; + + DEFAULT.name = 'Julia'; + DEFAULT.contains = [ + NUMBER, + CHAR, + STRING, + COMMAND, + MACROCALL, + COMMENT, + hljs.HASH_COMMENT_MODE, + { + className: 'keyword', + begin: + '\\b(((abstract|primitive)\\s+)type|(mutable\\s+)?struct)\\b' + }, + {begin: /<:/} // relevance booster + ]; + INTERPOLATION.contains = DEFAULT.contains; + + return DEFAULT; +} + +module.exports = julia; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/kotlin.js b/claude-code-source/node_modules/highlight.js/lib/languages/kotlin.js new file mode 100644 index 00000000..89d3d8cd --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/kotlin.js @@ -0,0 +1,284 @@ +// https://docs.oracle.com/javase/specs/jls/se15/html/jls-3.html#jls-3.10 +var decimalDigits = '[0-9](_*[0-9])*'; +var frac = `\\.(${decimalDigits})`; +var hexDigits = '[0-9a-fA-F](_*[0-9a-fA-F])*'; +var NUMERIC = { + className: 'number', + variants: [ + // DecimalFloatingPointLiteral + // including ExponentPart + { begin: `(\\b(${decimalDigits})((${frac})|\\.)?|(${frac}))` + + `[eE][+-]?(${decimalDigits})[fFdD]?\\b` }, + // excluding ExponentPart + { begin: `\\b(${decimalDigits})((${frac})[fFdD]?\\b|\\.([fFdD]\\b)?)` }, + { begin: `(${frac})[fFdD]?\\b` }, + { begin: `\\b(${decimalDigits})[fFdD]\\b` }, + + // HexadecimalFloatingPointLiteral + { begin: `\\b0[xX]((${hexDigits})\\.?|(${hexDigits})?\\.(${hexDigits}))` + + `[pP][+-]?(${decimalDigits})[fFdD]?\\b` }, + + // DecimalIntegerLiteral + { begin: '\\b(0|[1-9](_*[0-9])*)[lL]?\\b' }, + + // HexIntegerLiteral + { begin: `\\b0[xX](${hexDigits})[lL]?\\b` }, + + // OctalIntegerLiteral + { begin: '\\b0(_*[0-7])*[lL]?\\b' }, + + // BinaryIntegerLiteral + { begin: '\\b0[bB][01](_*[01])*[lL]?\\b' }, + ], + relevance: 0 +}; + +/* + Language: Kotlin + Description: Kotlin is an OSS statically typed programming language that targets the JVM, Android, JavaScript and Native. + Author: Sergey Mashkov + Website: https://kotlinlang.org + Category: common + */ + +function kotlin(hljs) { + const KEYWORDS = { + keyword: + 'abstract as val var vararg get set class object open private protected public noinline ' + + 'crossinline dynamic final enum if else do while for when throw try catch finally ' + + 'import package is in fun override companion reified inline lateinit init ' + + 'interface annotation data sealed internal infix operator out by constructor super ' + + 'tailrec where const inner suspend typealias external expect actual', + built_in: + 'Byte Short Char Int Long Boolean Float Double Void Unit Nothing', + literal: + 'true false null' + }; + const KEYWORDS_WITH_LABEL = { + className: 'keyword', + begin: /\b(break|continue|return|this)\b/, + starts: { + contains: [ + { + className: 'symbol', + begin: /@\w+/ + } + ] + } + }; + const LABEL = { + className: 'symbol', + begin: hljs.UNDERSCORE_IDENT_RE + '@' + }; + + // for string templates + const SUBST = { + className: 'subst', + begin: /\$\{/, + end: /\}/, + contains: [ hljs.C_NUMBER_MODE ] + }; + const VARIABLE = { + className: 'variable', + begin: '\\$' + hljs.UNDERSCORE_IDENT_RE + }; + const STRING = { + className: 'string', + variants: [ + { + begin: '"""', + end: '"""(?=[^"])', + contains: [ + VARIABLE, + SUBST + ] + }, + // Can't use built-in modes easily, as we want to use STRING in the meta + // context as 'meta-string' and there's no syntax to remove explicitly set + // classNames in built-in modes. + { + begin: '\'', + end: '\'', + illegal: /\n/, + contains: [ hljs.BACKSLASH_ESCAPE ] + }, + { + begin: '"', + end: '"', + illegal: /\n/, + contains: [ + hljs.BACKSLASH_ESCAPE, + VARIABLE, + SUBST + ] + } + ] + }; + SUBST.contains.push(STRING); + + const ANNOTATION_USE_SITE = { + className: 'meta', + begin: '@(?:file|property|field|get|set|receiver|param|setparam|delegate)\\s*:(?:\\s*' + hljs.UNDERSCORE_IDENT_RE + ')?' + }; + const ANNOTATION = { + className: 'meta', + begin: '@' + hljs.UNDERSCORE_IDENT_RE, + contains: [ + { + begin: /\(/, + end: /\)/, + contains: [ + hljs.inherit(STRING, { + className: 'meta-string' + }) + ] + } + ] + }; + + // https://kotlinlang.org/docs/reference/whatsnew11.html#underscores-in-numeric-literals + // According to the doc above, the number mode of kotlin is the same as java 8, + // so the code below is copied from java.js + const KOTLIN_NUMBER_MODE = NUMERIC; + const KOTLIN_NESTED_COMMENT = hljs.COMMENT( + '/\\*', '\\*/', + { + contains: [ hljs.C_BLOCK_COMMENT_MODE ] + } + ); + const KOTLIN_PAREN_TYPE = { + variants: [ + { + className: 'type', + begin: hljs.UNDERSCORE_IDENT_RE + }, + { + begin: /\(/, + end: /\)/, + contains: [] // defined later + } + ] + }; + const KOTLIN_PAREN_TYPE2 = KOTLIN_PAREN_TYPE; + KOTLIN_PAREN_TYPE2.variants[1].contains = [ KOTLIN_PAREN_TYPE ]; + KOTLIN_PAREN_TYPE.variants[1].contains = [ KOTLIN_PAREN_TYPE2 ]; + + return { + name: 'Kotlin', + aliases: [ 'kt', 'kts' ], + keywords: KEYWORDS, + contains: [ + hljs.COMMENT( + '/\\*\\*', + '\\*/', + { + relevance: 0, + contains: [ + { + className: 'doctag', + begin: '@[A-Za-z]+' + } + ] + } + ), + hljs.C_LINE_COMMENT_MODE, + KOTLIN_NESTED_COMMENT, + KEYWORDS_WITH_LABEL, + LABEL, + ANNOTATION_USE_SITE, + ANNOTATION, + { + className: 'function', + beginKeywords: 'fun', + end: '[(]|$', + returnBegin: true, + excludeEnd: true, + keywords: KEYWORDS, + relevance: 5, + contains: [ + { + begin: hljs.UNDERSCORE_IDENT_RE + '\\s*\\(', + returnBegin: true, + relevance: 0, + contains: [ hljs.UNDERSCORE_TITLE_MODE ] + }, + { + className: 'type', + begin: //, + keywords: 'reified', + relevance: 0 + }, + { + className: 'params', + begin: /\(/, + end: /\)/, + endsParent: true, + keywords: KEYWORDS, + relevance: 0, + contains: [ + { + begin: /:/, + end: /[=,\/]/, + endsWithParent: true, + contains: [ + KOTLIN_PAREN_TYPE, + hljs.C_LINE_COMMENT_MODE, + KOTLIN_NESTED_COMMENT + ], + relevance: 0 + }, + hljs.C_LINE_COMMENT_MODE, + KOTLIN_NESTED_COMMENT, + ANNOTATION_USE_SITE, + ANNOTATION, + STRING, + hljs.C_NUMBER_MODE + ] + }, + KOTLIN_NESTED_COMMENT + ] + }, + { + className: 'class', + beginKeywords: 'class interface trait', // remove 'trait' when removed from KEYWORDS + end: /[:\{(]|$/, + excludeEnd: true, + illegal: 'extends implements', + contains: [ + { + beginKeywords: 'public protected internal private constructor' + }, + hljs.UNDERSCORE_TITLE_MODE, + { + className: 'type', + begin: //, + excludeBegin: true, + excludeEnd: true, + relevance: 0 + }, + { + className: 'type', + begin: /[,:]\s*/, + end: /[<\(,]|$/, + excludeBegin: true, + returnEnd: true + }, + ANNOTATION_USE_SITE, + ANNOTATION + ] + }, + STRING, + { + className: 'meta', + begin: "^#!/usr/bin/env", + end: '$', + illegal: '\n' + }, + KOTLIN_NUMBER_MODE + ] + }; +} + +module.exports = kotlin; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/lasso.js b/claude-code-source/node_modules/highlight.js/lib/languages/lasso.js new file mode 100644 index 00000000..184b4904 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/lasso.js @@ -0,0 +1,187 @@ +/* +Language: Lasso +Author: Eric Knibbe +Description: Lasso is a language and server platform for database-driven web applications. This definition handles Lasso 9 syntax and LassoScript for Lasso 8.6 and earlier. +Website: http://www.lassosoft.com/What-Is-Lasso +*/ + +function lasso(hljs) { + const LASSO_IDENT_RE = '[a-zA-Z_][\\w.]*'; + const LASSO_ANGLE_RE = '<\\?(lasso(script)?|=)'; + const LASSO_CLOSE_RE = '\\]|\\?>'; + const LASSO_KEYWORDS = { + $pattern: LASSO_IDENT_RE + '|&[lg]t;', + literal: + 'true false none minimal full all void and or not ' + + 'bw nbw ew new cn ncn lt lte gt gte eq neq rx nrx ft', + built_in: + 'array date decimal duration integer map pair string tag xml null ' + + 'boolean bytes keyword list locale queue set stack staticarray ' + + 'local var variable global data self inherited currentcapture givenblock', + keyword: + 'cache database_names database_schemanames database_tablenames ' + + 'define_tag define_type email_batch encode_set html_comment handle ' + + 'handle_error header if inline iterate ljax_target link ' + + 'link_currentaction link_currentgroup link_currentrecord link_detail ' + + 'link_firstgroup link_firstrecord link_lastgroup link_lastrecord ' + + 'link_nextgroup link_nextrecord link_prevgroup link_prevrecord log ' + + 'loop namespace_using output_none portal private protect records ' + + 'referer referrer repeating resultset rows search_args ' + + 'search_arguments select sort_args sort_arguments thread_atomic ' + + 'value_list while abort case else fail_if fail_ifnot fail if_empty ' + + 'if_false if_null if_true loop_abort loop_continue loop_count params ' + + 'params_up return return_value run_children soap_definetag ' + + 'soap_lastrequest soap_lastresponse tag_name ascending average by ' + + 'define descending do equals frozen group handle_failure import in ' + + 'into join let match max min on order parent protected provide public ' + + 'require returnhome skip split_thread sum take thread to trait type ' + + 'where with yield yieldhome' + }; + const HTML_COMMENT = hljs.COMMENT( + '', + { + relevance: 0 + } + ); + const LASSO_NOPROCESS = { + className: 'meta', + begin: '\\[noprocess\\]', + starts: { + end: '\\[/noprocess\\]', + returnEnd: true, + contains: [HTML_COMMENT] + } + }; + const LASSO_START = { + className: 'meta', + begin: '\\[/noprocess|' + LASSO_ANGLE_RE + }; + const LASSO_DATAMEMBER = { + className: 'symbol', + begin: '\'' + LASSO_IDENT_RE + '\'' + }; + const LASSO_CODE = [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.inherit(hljs.C_NUMBER_MODE, { + begin: hljs.C_NUMBER_RE + '|(-?infinity|NaN)\\b' + }), + hljs.inherit(hljs.APOS_STRING_MODE, { + illegal: null + }), + hljs.inherit(hljs.QUOTE_STRING_MODE, { + illegal: null + }), + { + className: 'string', + begin: '`', + end: '`' + }, + { // variables + variants: [ + { + begin: '[#$]' + LASSO_IDENT_RE + }, + { + begin: '#', + end: '\\d+', + illegal: '\\W' + } + ] + }, + { + className: 'type', + begin: '::\\s*', + end: LASSO_IDENT_RE, + illegal: '\\W' + }, + { + className: 'params', + variants: [ + { + begin: '-(?!infinity)' + LASSO_IDENT_RE, + relevance: 0 + }, + { + begin: '(\\.\\.\\.)' + } + ] + }, + { + begin: /(->|\.)\s*/, + relevance: 0, + contains: [LASSO_DATAMEMBER] + }, + { + className: 'class', + beginKeywords: 'define', + returnEnd: true, + end: '\\(|=>', + contains: [ + hljs.inherit(hljs.TITLE_MODE, { + begin: LASSO_IDENT_RE + '(=(?!>))?|[-+*/%](?!>)' + }) + ] + } + ]; + return { + name: 'Lasso', + aliases: [ + 'ls', + 'lassoscript' + ], + case_insensitive: true, + keywords: LASSO_KEYWORDS, + contains: [ + { + className: 'meta', + begin: LASSO_CLOSE_RE, + relevance: 0, + starts: { // markup + end: '\\[|' + LASSO_ANGLE_RE, + returnEnd: true, + relevance: 0, + contains: [HTML_COMMENT] + } + }, + LASSO_NOPROCESS, + LASSO_START, + { + className: 'meta', + begin: '\\[no_square_brackets', + starts: { + end: '\\[/no_square_brackets\\]', // not implemented in the language + keywords: LASSO_KEYWORDS, + contains: [ + { + className: 'meta', + begin: LASSO_CLOSE_RE, + relevance: 0, + starts: { + end: '\\[noprocess\\]|' + LASSO_ANGLE_RE, + returnEnd: true, + contains: [HTML_COMMENT] + } + }, + LASSO_NOPROCESS, + LASSO_START + ].concat(LASSO_CODE) + } + }, + { + className: 'meta', + begin: '\\[', + relevance: 0 + }, + { + className: 'meta', + begin: '^#!', + end: 'lasso9$', + relevance: 10 + } + ].concat(LASSO_CODE) + }; +} + +module.exports = lasso; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/latex.js b/claude-code-source/node_modules/highlight.js/lib/languages/latex.js new file mode 100644 index 00000000..e61c98a6 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/latex.js @@ -0,0 +1,276 @@ +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * Any of the passed expresssions may match + * + * Creates a huge this | this | that | that match + * @param {(RegExp | string)[] } args + * @returns {string} + */ +function either(...args) { + const joined = '(' + args.map((x) => source(x)).join("|") + ")"; + return joined; +} + +/* +Language: LaTeX +Author: Benedikt Wilde +Website: https://www.latex-project.org +Category: markup +*/ + +/** @type LanguageFn */ +function latex(hljs) { + const KNOWN_CONTROL_WORDS = either(...[ + '(?:NeedsTeXFormat|RequirePackage|GetIdInfo)', + 'Provides(?:Expl)?(?:Package|Class|File)', + '(?:DeclareOption|ProcessOptions)', + '(?:documentclass|usepackage|input|include)', + 'makeat(?:letter|other)', + 'ExplSyntax(?:On|Off)', + '(?:new|renew|provide)?command', + '(?:re)newenvironment', + '(?:New|Renew|Provide|Declare)(?:Expandable)?DocumentCommand', + '(?:New|Renew|Provide|Declare)DocumentEnvironment', + '(?:(?:e|g|x)?def|let)', + '(?:begin|end)', + '(?:part|chapter|(?:sub){0,2}section|(?:sub)?paragraph)', + 'caption', + '(?:label|(?:eq|page|name)?ref|(?:paren|foot|super)?cite)', + '(?:alpha|beta|[Gg]amma|[Dd]elta|(?:var)?epsilon|zeta|eta|[Tt]heta|vartheta)', + '(?:iota|(?:var)?kappa|[Ll]ambda|mu|nu|[Xx]i|[Pp]i|varpi|(?:var)rho)', + '(?:[Ss]igma|varsigma|tau|[Uu]psilon|[Pp]hi|varphi|chi|[Pp]si|[Oo]mega)', + '(?:frac|sum|prod|lim|infty|times|sqrt|leq|geq|left|right|middle|[bB]igg?)', + '(?:[lr]angle|q?quad|[lcvdi]?dots|d?dot|hat|tilde|bar)' + ].map(word => word + '(?![a-zA-Z@:_])')); + const L3_REGEX = new RegExp([ + // A function \module_function_name:signature or \__module_function_name:signature, + // where both module and function_name need at least two characters and + // function_name may contain single underscores. + '(?:__)?[a-zA-Z]{2,}_[a-zA-Z](?:_?[a-zA-Z])+:[a-zA-Z]*', + // A variable \scope_module_and_name_type or \scope__module_ane_name_type, + // where scope is one of l, g or c, type needs at least two characters + // and module_and_name may contain single underscores. + '[lgc]__?[a-zA-Z](?:_?[a-zA-Z])*_[a-zA-Z]{2,}', + // A quark \q_the_name or \q__the_name or + // scan mark \s_the_name or \s__vthe_name, + // where variable_name needs at least two characters and + // may contain single underscores. + '[qs]__?[a-zA-Z](?:_?[a-zA-Z])+', + // Other LaTeX3 macro names that are not covered by the three rules above. + 'use(?:_i)?:[a-zA-Z]*', + '(?:else|fi|or):', + '(?:if|cs|exp):w', + '(?:hbox|vbox):n', + '::[a-zA-Z]_unbraced', + '::[a-zA-Z:]' + ].map(pattern => pattern + '(?![a-zA-Z:_])').join('|')); + const L2_VARIANTS = [ + {begin: /[a-zA-Z@]+/}, // control word + {begin: /[^a-zA-Z@]?/} // control symbol + ]; + const DOUBLE_CARET_VARIANTS = [ + {begin: /\^{6}[0-9a-f]{6}/}, + {begin: /\^{5}[0-9a-f]{5}/}, + {begin: /\^{4}[0-9a-f]{4}/}, + {begin: /\^{3}[0-9a-f]{3}/}, + {begin: /\^{2}[0-9a-f]{2}/}, + {begin: /\^{2}[\u0000-\u007f]/} + ]; + const CONTROL_SEQUENCE = { + className: 'keyword', + begin: /\\/, + relevance: 0, + contains: [ + { + endsParent: true, + begin: KNOWN_CONTROL_WORDS + }, + { + endsParent: true, + begin: L3_REGEX + }, + { + endsParent: true, + variants: DOUBLE_CARET_VARIANTS + }, + { + endsParent: true, + relevance: 0, + variants: L2_VARIANTS + } + ] + }; + const MACRO_PARAM = { + className: 'params', + relevance: 0, + begin: /#+\d?/ + }; + const DOUBLE_CARET_CHAR = { + // relevance: 1 + variants: DOUBLE_CARET_VARIANTS + }; + const SPECIAL_CATCODE = { + className: 'built_in', + relevance: 0, + begin: /[$&^_]/ + }; + const MAGIC_COMMENT = { + className: 'meta', + begin: '% !TeX', + end: '$', + relevance: 10 + }; + const COMMENT = hljs.COMMENT( + '%', + '$', + { + relevance: 0 + } + ); + const EVERYTHING_BUT_VERBATIM = [ + CONTROL_SEQUENCE, + MACRO_PARAM, + DOUBLE_CARET_CHAR, + SPECIAL_CATCODE, + MAGIC_COMMENT, + COMMENT + ]; + const BRACE_GROUP_NO_VERBATIM = { + begin: /\{/, end: /\}/, + relevance: 0, + contains: ['self', ...EVERYTHING_BUT_VERBATIM] + }; + const ARGUMENT_BRACES = hljs.inherit( + BRACE_GROUP_NO_VERBATIM, + { + relevance: 0, + endsParent: true, + contains: [BRACE_GROUP_NO_VERBATIM, ...EVERYTHING_BUT_VERBATIM] + } + ); + const ARGUMENT_BRACKETS = { + begin: /\[/, + end: /\]/, + endsParent: true, + relevance: 0, + contains: [BRACE_GROUP_NO_VERBATIM, ...EVERYTHING_BUT_VERBATIM] + }; + const SPACE_GOBBLER = { + begin: /\s+/, + relevance: 0 + }; + const ARGUMENT_M = [ARGUMENT_BRACES]; + const ARGUMENT_O = [ARGUMENT_BRACKETS]; + const ARGUMENT_AND_THEN = function(arg, starts_mode) { + return { + contains: [SPACE_GOBBLER], + starts: { + relevance: 0, + contains: arg, + starts: starts_mode + } + }; + }; + const CSNAME = function(csname, starts_mode) { + return { + begin: '\\\\' + csname + '(?![a-zA-Z@:_])', + keywords: {$pattern: /\\[a-zA-Z]+/, keyword: '\\' + csname}, + relevance: 0, + contains: [SPACE_GOBBLER], + starts: starts_mode + }; + }; + const BEGIN_ENV = function(envname, starts_mode) { + return hljs.inherit( + { + begin: '\\\\begin(?=[ \t]*(\\r?\\n[ \t]*)?\\{' + envname + '\\})', + keywords: {$pattern: /\\[a-zA-Z]+/, keyword: '\\begin'}, + relevance: 0, + }, + ARGUMENT_AND_THEN(ARGUMENT_M, starts_mode) + ); + }; + const VERBATIM_DELIMITED_EQUAL = (innerName = "string") => { + return hljs.END_SAME_AS_BEGIN({ + className: innerName, + begin: /(.|\r?\n)/, + end: /(.|\r?\n)/, + excludeBegin: true, + excludeEnd: true, + endsParent: true + }); + }; + const VERBATIM_DELIMITED_ENV = function(envname) { + return { + className: 'string', + end: '(?=\\\\end\\{' + envname + '\\})' + }; + }; + + const VERBATIM_DELIMITED_BRACES = (innerName = "string") => { + return { + relevance: 0, + begin: /\{/, + starts: { + endsParent: true, + contains: [ + { + className: innerName, + end: /(?=\})/, + endsParent:true, + contains: [ + { + begin: /\{/, + end: /\}/, + relevance: 0, + contains: ["self"] + } + ], + } + ] + } + }; + }; + const VERBATIM = [ + ...['verb', 'lstinline'].map(csname => CSNAME(csname, {contains: [VERBATIM_DELIMITED_EQUAL()]})), + CSNAME('mint', ARGUMENT_AND_THEN(ARGUMENT_M, {contains: [VERBATIM_DELIMITED_EQUAL()]})), + CSNAME('mintinline', ARGUMENT_AND_THEN(ARGUMENT_M, {contains: [VERBATIM_DELIMITED_BRACES(), VERBATIM_DELIMITED_EQUAL()]})), + CSNAME('url', {contains: [VERBATIM_DELIMITED_BRACES("link"), VERBATIM_DELIMITED_BRACES("link")]}), + CSNAME('hyperref', {contains: [VERBATIM_DELIMITED_BRACES("link")]}), + CSNAME('href', ARGUMENT_AND_THEN(ARGUMENT_O, {contains: [VERBATIM_DELIMITED_BRACES("link")]})), + ...[].concat(...['', '\\*'].map(suffix => [ + BEGIN_ENV('verbatim' + suffix, VERBATIM_DELIMITED_ENV('verbatim' + suffix)), + BEGIN_ENV('filecontents' + suffix, ARGUMENT_AND_THEN(ARGUMENT_M, VERBATIM_DELIMITED_ENV('filecontents' + suffix))), + ...['', 'B', 'L'].map(prefix => + BEGIN_ENV(prefix + 'Verbatim' + suffix, ARGUMENT_AND_THEN(ARGUMENT_O, VERBATIM_DELIMITED_ENV(prefix + 'Verbatim' + suffix))) + ) + ])), + BEGIN_ENV('minted', ARGUMENT_AND_THEN(ARGUMENT_O, ARGUMENT_AND_THEN(ARGUMENT_M, VERBATIM_DELIMITED_ENV('minted')))), + ]; + + return { + name: 'LaTeX', + aliases: ['tex'], + contains: [ + ...VERBATIM, + ...EVERYTHING_BUT_VERBATIM + ] + }; +} + +module.exports = latex; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/ldif.js b/claude-code-source/node_modules/highlight.js/lib/languages/ldif.js new file mode 100644 index 00000000..3b8d37b6 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/ldif.js @@ -0,0 +1,42 @@ +/* +Language: LDIF +Contributors: Jacob Childress +Category: enterprise, config +Website: https://en.wikipedia.org/wiki/LDAP_Data_Interchange_Format +*/ +function ldif(hljs) { + return { + name: 'LDIF', + contains: [ + { + className: 'attribute', + begin: '^dn', + end: ': ', + excludeEnd: true, + starts: { + end: '$', + relevance: 0 + }, + relevance: 10 + }, + { + className: 'attribute', + begin: '^\\w', + end: ': ', + excludeEnd: true, + starts: { + end: '$', + relevance: 0 + } + }, + { + className: 'literal', + begin: '^-', + end: '$' + }, + hljs.HASH_COMMENT_MODE + ] + }; +} + +module.exports = ldif; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/leaf.js b/claude-code-source/node_modules/highlight.js/lib/languages/leaf.js new file mode 100644 index 00000000..e0ec10d2 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/leaf.js @@ -0,0 +1,49 @@ +/* +Language: Leaf +Author: Hale Chan +Description: Based on the Leaf reference from https://vapor.github.io/documentation/guide/leaf.html. +*/ + +function leaf(hljs) { + return { + name: 'Leaf', + contains: [ + { + className: 'function', + begin: '#+' + '[A-Za-z_0-9]*' + '\\(', + end: / \{/, + returnBegin: true, + excludeEnd: true, + contains: [ + { + className: 'keyword', + begin: '#+' + }, + { + className: 'title', + begin: '[A-Za-z_][A-Za-z_0-9]*' + }, + { + className: 'params', + begin: '\\(', + end: '\\)', + endsParent: true, + contains: [ + { + className: 'string', + begin: '"', + end: '"' + }, + { + className: 'variable', + begin: '[A-Za-z_][A-Za-z_0-9]*' + } + ] + } + ] + } + ] + }; +} + +module.exports = leaf; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/less.js b/claude-code-source/node_modules/highlight.js/lib/languages/less.js new file mode 100644 index 00000000..d228acba --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/less.js @@ -0,0 +1,666 @@ +const MODES = (hljs) => { + return { + IMPORTANT: { + className: 'meta', + begin: '!important' + }, + HEXCOLOR: { + className: 'number', + begin: '#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})' + }, + ATTRIBUTE_SELECTOR_MODE: { + className: 'selector-attr', + begin: /\[/, + end: /\]/, + illegal: '$', + contains: [ + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE + ] + } + }; +}; + +const TAGS = [ + 'a', + 'abbr', + 'address', + 'article', + 'aside', + 'audio', + 'b', + 'blockquote', + 'body', + 'button', + 'canvas', + 'caption', + 'cite', + 'code', + 'dd', + 'del', + 'details', + 'dfn', + 'div', + 'dl', + 'dt', + 'em', + 'fieldset', + 'figcaption', + 'figure', + 'footer', + 'form', + 'h1', + 'h2', + 'h3', + 'h4', + 'h5', + 'h6', + 'header', + 'hgroup', + 'html', + 'i', + 'iframe', + 'img', + 'input', + 'ins', + 'kbd', + 'label', + 'legend', + 'li', + 'main', + 'mark', + 'menu', + 'nav', + 'object', + 'ol', + 'p', + 'q', + 'quote', + 'samp', + 'section', + 'span', + 'strong', + 'summary', + 'sup', + 'table', + 'tbody', + 'td', + 'textarea', + 'tfoot', + 'th', + 'thead', + 'time', + 'tr', + 'ul', + 'var', + 'video' +]; + +const MEDIA_FEATURES = [ + 'any-hover', + 'any-pointer', + 'aspect-ratio', + 'color', + 'color-gamut', + 'color-index', + 'device-aspect-ratio', + 'device-height', + 'device-width', + 'display-mode', + 'forced-colors', + 'grid', + 'height', + 'hover', + 'inverted-colors', + 'monochrome', + 'orientation', + 'overflow-block', + 'overflow-inline', + 'pointer', + 'prefers-color-scheme', + 'prefers-contrast', + 'prefers-reduced-motion', + 'prefers-reduced-transparency', + 'resolution', + 'scan', + 'scripting', + 'update', + 'width', + // TODO: find a better solution? + 'min-width', + 'max-width', + 'min-height', + 'max-height' +]; + +// https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes +const PSEUDO_CLASSES = [ + 'active', + 'any-link', + 'blank', + 'checked', + 'current', + 'default', + 'defined', + 'dir', // dir() + 'disabled', + 'drop', + 'empty', + 'enabled', + 'first', + 'first-child', + 'first-of-type', + 'fullscreen', + 'future', + 'focus', + 'focus-visible', + 'focus-within', + 'has', // has() + 'host', // host or host() + 'host-context', // host-context() + 'hover', + 'indeterminate', + 'in-range', + 'invalid', + 'is', // is() + 'lang', // lang() + 'last-child', + 'last-of-type', + 'left', + 'link', + 'local-link', + 'not', // not() + 'nth-child', // nth-child() + 'nth-col', // nth-col() + 'nth-last-child', // nth-last-child() + 'nth-last-col', // nth-last-col() + 'nth-last-of-type', //nth-last-of-type() + 'nth-of-type', //nth-of-type() + 'only-child', + 'only-of-type', + 'optional', + 'out-of-range', + 'past', + 'placeholder-shown', + 'read-only', + 'read-write', + 'required', + 'right', + 'root', + 'scope', + 'target', + 'target-within', + 'user-invalid', + 'valid', + 'visited', + 'where' // where() +]; + +// https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements +const PSEUDO_ELEMENTS = [ + 'after', + 'backdrop', + 'before', + 'cue', + 'cue-region', + 'first-letter', + 'first-line', + 'grammar-error', + 'marker', + 'part', + 'placeholder', + 'selection', + 'slotted', + 'spelling-error' +]; + +const ATTRIBUTES = [ + 'align-content', + 'align-items', + 'align-self', + 'animation', + 'animation-delay', + 'animation-direction', + 'animation-duration', + 'animation-fill-mode', + 'animation-iteration-count', + 'animation-name', + 'animation-play-state', + 'animation-timing-function', + 'auto', + 'backface-visibility', + 'background', + 'background-attachment', + 'background-clip', + 'background-color', + 'background-image', + 'background-origin', + 'background-position', + 'background-repeat', + 'background-size', + 'border', + 'border-bottom', + 'border-bottom-color', + 'border-bottom-left-radius', + 'border-bottom-right-radius', + 'border-bottom-style', + 'border-bottom-width', + 'border-collapse', + 'border-color', + 'border-image', + 'border-image-outset', + 'border-image-repeat', + 'border-image-slice', + 'border-image-source', + 'border-image-width', + 'border-left', + 'border-left-color', + 'border-left-style', + 'border-left-width', + 'border-radius', + 'border-right', + 'border-right-color', + 'border-right-style', + 'border-right-width', + 'border-spacing', + 'border-style', + 'border-top', + 'border-top-color', + 'border-top-left-radius', + 'border-top-right-radius', + 'border-top-style', + 'border-top-width', + 'border-width', + 'bottom', + 'box-decoration-break', + 'box-shadow', + 'box-sizing', + 'break-after', + 'break-before', + 'break-inside', + 'caption-side', + 'clear', + 'clip', + 'clip-path', + 'color', + 'column-count', + 'column-fill', + 'column-gap', + 'column-rule', + 'column-rule-color', + 'column-rule-style', + 'column-rule-width', + 'column-span', + 'column-width', + 'columns', + 'content', + 'counter-increment', + 'counter-reset', + 'cursor', + 'direction', + 'display', + 'empty-cells', + 'filter', + 'flex', + 'flex-basis', + 'flex-direction', + 'flex-flow', + 'flex-grow', + 'flex-shrink', + 'flex-wrap', + 'float', + 'font', + 'font-display', + 'font-family', + 'font-feature-settings', + 'font-kerning', + 'font-language-override', + 'font-size', + 'font-size-adjust', + 'font-smoothing', + 'font-stretch', + 'font-style', + 'font-variant', + 'font-variant-ligatures', + 'font-variation-settings', + 'font-weight', + 'height', + 'hyphens', + 'icon', + 'image-orientation', + 'image-rendering', + 'image-resolution', + 'ime-mode', + 'inherit', + 'initial', + 'justify-content', + 'left', + 'letter-spacing', + 'line-height', + 'list-style', + 'list-style-image', + 'list-style-position', + 'list-style-type', + 'margin', + 'margin-bottom', + 'margin-left', + 'margin-right', + 'margin-top', + 'marks', + 'mask', + 'max-height', + 'max-width', + 'min-height', + 'min-width', + 'nav-down', + 'nav-index', + 'nav-left', + 'nav-right', + 'nav-up', + 'none', + 'normal', + 'object-fit', + 'object-position', + 'opacity', + 'order', + 'orphans', + 'outline', + 'outline-color', + 'outline-offset', + 'outline-style', + 'outline-width', + 'overflow', + 'overflow-wrap', + 'overflow-x', + 'overflow-y', + 'padding', + 'padding-bottom', + 'padding-left', + 'padding-right', + 'padding-top', + 'page-break-after', + 'page-break-before', + 'page-break-inside', + 'perspective', + 'perspective-origin', + 'pointer-events', + 'position', + 'quotes', + 'resize', + 'right', + 'src', // @font-face + 'tab-size', + 'table-layout', + 'text-align', + 'text-align-last', + 'text-decoration', + 'text-decoration-color', + 'text-decoration-line', + 'text-decoration-style', + 'text-indent', + 'text-overflow', + 'text-rendering', + 'text-shadow', + 'text-transform', + 'text-underline-position', + 'top', + 'transform', + 'transform-origin', + 'transform-style', + 'transition', + 'transition-delay', + 'transition-duration', + 'transition-property', + 'transition-timing-function', + 'unicode-bidi', + 'vertical-align', + 'visibility', + 'white-space', + 'widows', + 'width', + 'word-break', + 'word-spacing', + 'word-wrap', + 'z-index' + // reverse makes sure longer attributes `font-weight` are matched fully + // instead of getting false positives on say `font` +].reverse(); + +// some grammars use them all as a single group +const PSEUDO_SELECTORS = PSEUDO_CLASSES.concat(PSEUDO_ELEMENTS); + +/* +Language: Less +Description: It's CSS, with just a little more. +Author: Max Mikhailov +Website: http://lesscss.org +Category: common, css +*/ + +/** @type LanguageFn */ +function less(hljs) { + const modes = MODES(hljs); + const PSEUDO_SELECTORS$1 = PSEUDO_SELECTORS; + + const AT_MODIFIERS = "and or not only"; + const IDENT_RE = '[\\w-]+'; // yes, Less identifiers may begin with a digit + const INTERP_IDENT_RE = '(' + IDENT_RE + '|@\\{' + IDENT_RE + '\\})'; + + /* Generic Modes */ + + const RULES = []; const VALUE_MODES = []; // forward def. for recursive modes + + const STRING_MODE = function(c) { + return { + // Less strings are not multiline (also include '~' for more consistent coloring of "escaped" strings) + className: 'string', + begin: '~?' + c + '.*?' + c + }; + }; + + const IDENT_MODE = function(name, begin, relevance) { + return { + className: name, + begin: begin, + relevance: relevance + }; + }; + + const AT_KEYWORDS = { + $pattern: /[a-z-]+/, + keyword: AT_MODIFIERS, + attribute: MEDIA_FEATURES.join(" ") + }; + + const PARENS_MODE = { + // used only to properly balance nested parens inside mixin call, def. arg list + begin: '\\(', + end: '\\)', + contains: VALUE_MODES, + keywords: AT_KEYWORDS, + relevance: 0 + }; + + // generic Less highlighter (used almost everywhere except selectors): + VALUE_MODES.push( + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + STRING_MODE("'"), + STRING_MODE('"'), + hljs.CSS_NUMBER_MODE, // fixme: it does not include dot for numbers like .5em :( + { + begin: '(url|data-uri)\\(', + starts: { + className: 'string', + end: '[\\)\\n]', + excludeEnd: true + } + }, + modes.HEXCOLOR, + PARENS_MODE, + IDENT_MODE('variable', '@@?' + IDENT_RE, 10), + IDENT_MODE('variable', '@\\{' + IDENT_RE + '\\}'), + IDENT_MODE('built_in', '~?`[^`]*?`'), // inline javascript (or whatever host language) *multiline* string + { // @media features (it’s here to not duplicate things in AT_RULE_MODE with extra PARENS_MODE overriding): + className: 'attribute', + begin: IDENT_RE + '\\s*:', + end: ':', + returnBegin: true, + excludeEnd: true + }, + modes.IMPORTANT + ); + + const VALUE_WITH_RULESETS = VALUE_MODES.concat({ + begin: /\{/, + end: /\}/, + contains: RULES + }); + + const MIXIN_GUARD_MODE = { + beginKeywords: 'when', + endsWithParent: true, + contains: [ + { + beginKeywords: 'and not' + } + ].concat(VALUE_MODES) // using this form to override VALUE’s 'function' match + }; + + /* Rule-Level Modes */ + + const RULE_MODE = { + begin: INTERP_IDENT_RE + '\\s*:', + returnBegin: true, + end: /[;}]/, + relevance: 0, + contains: [ + { + begin: /-(webkit|moz|ms|o)-/ + }, + { + className: 'attribute', + begin: '\\b(' + ATTRIBUTES.join('|') + ')\\b', + end: /(?=:)/, + starts: { + endsWithParent: true, + illegal: '[<=$]', + relevance: 0, + contains: VALUE_MODES + } + } + ] + }; + + const AT_RULE_MODE = { + className: 'keyword', + begin: '@(import|media|charset|font-face|(-[a-z]+-)?keyframes|supports|document|namespace|page|viewport|host)\\b', + starts: { + end: '[;{}]', + keywords: AT_KEYWORDS, + returnEnd: true, + contains: VALUE_MODES, + relevance: 0 + } + }; + + // variable definitions and calls + const VAR_RULE_MODE = { + className: 'variable', + variants: [ + // using more strict pattern for higher relevance to increase chances of Less detection. + // this is *the only* Less specific statement used in most of the sources, so... + // (we’ll still often loose to the css-parser unless there's '//' comment, + // simply because 1 variable just can't beat 99 properties :) + { + begin: '@' + IDENT_RE + '\\s*:', + relevance: 15 + }, + { + begin: '@' + IDENT_RE + } + ], + starts: { + end: '[;}]', + returnEnd: true, + contains: VALUE_WITH_RULESETS + } + }; + + const SELECTOR_MODE = { + // first parse unambiguous selectors (i.e. those not starting with tag) + // then fall into the scary lookahead-discriminator variant. + // this mode also handles mixin definitions and calls + variants: [ + { + begin: '[\\.#:&\\[>]', + end: '[;{}]' // mixin calls end with ';' + }, + { + begin: INTERP_IDENT_RE, + end: /\{/ + } + ], + returnBegin: true, + returnEnd: true, + illegal: '[<=\'$"]', + relevance: 0, + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + MIXIN_GUARD_MODE, + IDENT_MODE('keyword', 'all\\b'), + IDENT_MODE('variable', '@\\{' + IDENT_RE + '\\}'), // otherwise it’s identified as tag + { + begin: '\\b(' + TAGS.join('|') + ')\\b', + className: 'selector-tag' + }, + IDENT_MODE('selector-tag', INTERP_IDENT_RE + '%?', 0), // '%' for more consistent coloring of @keyframes "tags" + IDENT_MODE('selector-id', '#' + INTERP_IDENT_RE), + IDENT_MODE('selector-class', '\\.' + INTERP_IDENT_RE, 0), + IDENT_MODE('selector-tag', '&', 0), + modes.ATTRIBUTE_SELECTOR_MODE, + { + className: 'selector-pseudo', + begin: ':(' + PSEUDO_CLASSES.join('|') + ')' + }, + { + className: 'selector-pseudo', + begin: '::(' + PSEUDO_ELEMENTS.join('|') + ')' + }, + { + begin: '\\(', + end: '\\)', + contains: VALUE_WITH_RULESETS + }, // argument list of parametric mixins + { + begin: '!important' + } // eat !important after mixin call or it will be colored as tag + ] + }; + + const PSEUDO_SELECTOR_MODE = { + begin: IDENT_RE + ':(:)?' + `(${PSEUDO_SELECTORS$1.join('|')})`, + returnBegin: true, + contains: [ SELECTOR_MODE ] + }; + + RULES.push( + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + AT_RULE_MODE, + VAR_RULE_MODE, + PSEUDO_SELECTOR_MODE, + RULE_MODE, + SELECTOR_MODE + ); + + return { + name: 'Less', + case_insensitive: true, + illegal: '[=>\'/<($"]', + contains: RULES + }; +} + +module.exports = less; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/lisp.js b/claude-code-source/node_modules/highlight.js/lib/languages/lisp.js new file mode 100644 index 00000000..4c84d8f0 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/lisp.js @@ -0,0 +1,111 @@ +/* +Language: Lisp +Description: Generic lisp syntax +Author: Vasily Polovnyov +Category: lisp +*/ + +function lisp(hljs) { + var LISP_IDENT_RE = '[a-zA-Z_\\-+\\*\\/<=>&#][a-zA-Z0-9_\\-+*\\/<=>&#!]*'; + var MEC_RE = '\\|[^]*?\\|'; + var LISP_SIMPLE_NUMBER_RE = '(-|\\+)?\\d+(\\.\\d+|\\/\\d+)?((d|e|f|l|s|D|E|F|L|S)(\\+|-)?\\d+)?'; + var LITERAL = { + className: 'literal', + begin: '\\b(t{1}|nil)\\b' + }; + var NUMBER = { + className: 'number', + variants: [ + {begin: LISP_SIMPLE_NUMBER_RE, relevance: 0}, + {begin: '#(b|B)[0-1]+(/[0-1]+)?'}, + {begin: '#(o|O)[0-7]+(/[0-7]+)?'}, + {begin: '#(x|X)[0-9a-fA-F]+(/[0-9a-fA-F]+)?'}, + {begin: '#(c|C)\\(' + LISP_SIMPLE_NUMBER_RE + ' +' + LISP_SIMPLE_NUMBER_RE, end: '\\)'} + ] + }; + var STRING = hljs.inherit(hljs.QUOTE_STRING_MODE, {illegal: null}); + var COMMENT = hljs.COMMENT( + ';', '$', + { + relevance: 0 + } + ); + var VARIABLE = { + begin: '\\*', end: '\\*' + }; + var KEYWORD = { + className: 'symbol', + begin: '[:&]' + LISP_IDENT_RE + }; + var IDENT = { + begin: LISP_IDENT_RE, + relevance: 0 + }; + var MEC = { + begin: MEC_RE + }; + var QUOTED_LIST = { + begin: '\\(', end: '\\)', + contains: ['self', LITERAL, STRING, NUMBER, IDENT] + }; + var QUOTED = { + contains: [NUMBER, STRING, VARIABLE, KEYWORD, QUOTED_LIST, IDENT], + variants: [ + { + begin: '[\'`]\\(', end: '\\)' + }, + { + begin: '\\(quote ', end: '\\)', + keywords: {name: 'quote'} + }, + { + begin: '\'' + MEC_RE + } + ] + }; + var QUOTED_ATOM = { + variants: [ + {begin: '\'' + LISP_IDENT_RE}, + {begin: '#\'' + LISP_IDENT_RE + '(::' + LISP_IDENT_RE + ')*'} + ] + }; + var LIST = { + begin: '\\(\\s*', end: '\\)' + }; + var BODY = { + endsWithParent: true, + relevance: 0 + }; + LIST.contains = [ + { + className: 'name', + variants: [ + { + begin: LISP_IDENT_RE, + relevance: 0, + }, + {begin: MEC_RE} + ] + }, + BODY + ]; + BODY.contains = [QUOTED, QUOTED_ATOM, LIST, LITERAL, NUMBER, STRING, COMMENT, VARIABLE, KEYWORD, MEC, IDENT]; + + return { + name: 'Lisp', + illegal: /\S/, + contains: [ + NUMBER, + hljs.SHEBANG(), + LITERAL, + STRING, + COMMENT, + QUOTED, + QUOTED_ATOM, + LIST, + IDENT + ] + }; +} + +module.exports = lisp; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/livecodeserver.js b/claude-code-source/node_modules/highlight.js/lib/languages/livecodeserver.js new file mode 100644 index 00000000..b78c9b14 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/livecodeserver.js @@ -0,0 +1,189 @@ +/* +Language: LiveCode +Author: Ralf Bitter +Description: Language definition for LiveCode server accounting for revIgniter (a web application framework) characteristics. +Version: 1.1 +Date: 2019-04-17 +Category: enterprise +*/ + +function livecodeserver(hljs) { + const VARIABLE = { + className: 'variable', + variants: [ + { + begin: '\\b([gtps][A-Z]{1}[a-zA-Z0-9]*)(\\[.+\\])?(?:\\s*?)' + }, + { + begin: '\\$_[A-Z]+' + } + ], + relevance: 0 + }; + const COMMENT_MODES = [ + hljs.C_BLOCK_COMMENT_MODE, + hljs.HASH_COMMENT_MODE, + hljs.COMMENT('--', '$'), + hljs.COMMENT('[^:]//', '$') + ]; + const TITLE1 = hljs.inherit(hljs.TITLE_MODE, { + variants: [ + { + begin: '\\b_*rig[A-Z][A-Za-z0-9_\\-]*' + }, + { + begin: '\\b_[a-z0-9\\-]+' + } + ] + }); + const TITLE2 = hljs.inherit(hljs.TITLE_MODE, { + begin: '\\b([A-Za-z0-9_\\-]+)\\b' + }); + return { + name: 'LiveCode', + case_insensitive: false, + keywords: { + keyword: + '$_COOKIE $_FILES $_GET $_GET_BINARY $_GET_RAW $_POST $_POST_BINARY $_POST_RAW $_SESSION $_SERVER ' + + 'codepoint codepoints segment segments codeunit codeunits sentence sentences trueWord trueWords paragraph ' + + 'after byte bytes english the until http forever descending using line real8 with seventh ' + + 'for stdout finally element word words fourth before black ninth sixth characters chars stderr ' + + 'uInt1 uInt1s uInt2 uInt2s stdin string lines relative rel any fifth items from middle mid ' + + 'at else of catch then third it file milliseconds seconds second secs sec int1 int1s int4 ' + + 'int4s internet int2 int2s normal text item last long detailed effective uInt4 uInt4s repeat ' + + 'end repeat URL in try into switch to words https token binfile each tenth as ticks tick ' + + 'system real4 by dateItems without char character ascending eighth whole dateTime numeric short ' + + 'first ftp integer abbreviated abbr abbrev private case while if ' + + 'div mod wrap and or bitAnd bitNot bitOr bitXor among not in a an within ' + + 'contains ends with begins the keys of keys', + literal: + 'SIX TEN FORMFEED NINE ZERO NONE SPACE FOUR FALSE COLON CRLF PI COMMA ENDOFFILE EOF EIGHT FIVE ' + + 'QUOTE EMPTY ONE TRUE RETURN CR LINEFEED RIGHT BACKSLASH NULL SEVEN TAB THREE TWO ' + + 'six ten formfeed nine zero none space four false colon crlf pi comma endoffile eof eight five ' + + 'quote empty one true return cr linefeed right backslash null seven tab three two ' + + 'RIVERSION RISTATE FILE_READ_MODE FILE_WRITE_MODE FILE_WRITE_MODE DIR_WRITE_MODE FILE_READ_UMASK ' + + 'FILE_WRITE_UMASK DIR_READ_UMASK DIR_WRITE_UMASK', + built_in: + 'put abs acos aliasReference annuity arrayDecode arrayEncode asin atan atan2 average avg avgDev base64Decode ' + + 'base64Encode baseConvert binaryDecode binaryEncode byteOffset byteToNum cachedURL cachedURLs charToNum ' + + 'cipherNames codepointOffset codepointProperty codepointToNum codeunitOffset commandNames compound compress ' + + 'constantNames cos date dateFormat decompress difference directories ' + + 'diskSpace DNSServers exp exp1 exp2 exp10 extents files flushEvents folders format functionNames geometricMean global ' + + 'globals hasMemory harmonicMean hostAddress hostAddressToName hostName hostNameToAddress isNumber ISOToMac itemOffset ' + + 'keys len length libURLErrorData libUrlFormData libURLftpCommand libURLLastHTTPHeaders libURLLastRHHeaders ' + + 'libUrlMultipartFormAddPart libUrlMultipartFormData libURLVersion lineOffset ln ln1 localNames log log2 log10 ' + + 'longFilePath lower macToISO matchChunk matchText matrixMultiply max md5Digest median merge messageAuthenticationCode messageDigest millisec ' + + 'millisecs millisecond milliseconds min monthNames nativeCharToNum normalizeText num number numToByte numToChar ' + + 'numToCodepoint numToNativeChar offset open openfiles openProcesses openProcessIDs openSockets ' + + 'paragraphOffset paramCount param params peerAddress pendingMessages platform popStdDev populationStandardDeviation ' + + 'populationVariance popVariance processID random randomBytes replaceText result revCreateXMLTree revCreateXMLTreeFromFile ' + + 'revCurrentRecord revCurrentRecordIsFirst revCurrentRecordIsLast revDatabaseColumnCount revDatabaseColumnIsNull ' + + 'revDatabaseColumnLengths revDatabaseColumnNames revDatabaseColumnNamed revDatabaseColumnNumbered ' + + 'revDatabaseColumnTypes revDatabaseConnectResult revDatabaseCursors revDatabaseID revDatabaseTableNames ' + + 'revDatabaseType revDataFromQuery revdb_closeCursor revdb_columnbynumber revdb_columncount revdb_columnisnull ' + + 'revdb_columnlengths revdb_columnnames revdb_columntypes revdb_commit revdb_connect revdb_connections ' + + 'revdb_connectionerr revdb_currentrecord revdb_cursorconnection revdb_cursorerr revdb_cursors revdb_dbtype ' + + 'revdb_disconnect revdb_execute revdb_iseof revdb_isbof revdb_movefirst revdb_movelast revdb_movenext ' + + 'revdb_moveprev revdb_query revdb_querylist revdb_recordcount revdb_rollback revdb_tablenames ' + + 'revGetDatabaseDriverPath revNumberOfRecords revOpenDatabase revOpenDatabases revQueryDatabase ' + + 'revQueryDatabaseBlob revQueryResult revQueryIsAtStart revQueryIsAtEnd revUnixFromMacPath revXMLAttribute ' + + 'revXMLAttributes revXMLAttributeValues revXMLChildContents revXMLChildNames revXMLCreateTreeFromFileWithNamespaces ' + + 'revXMLCreateTreeWithNamespaces revXMLDataFromXPathQuery revXMLEvaluateXPath revXMLFirstChild revXMLMatchingNode ' + + 'revXMLNextSibling revXMLNodeContents revXMLNumberOfChildren revXMLParent revXMLPreviousSibling ' + + 'revXMLRootNode revXMLRPC_CreateRequest revXMLRPC_Documents revXMLRPC_Error ' + + 'revXMLRPC_GetHost revXMLRPC_GetMethod revXMLRPC_GetParam revXMLText revXMLRPC_Execute ' + + 'revXMLRPC_GetParamCount revXMLRPC_GetParamNode revXMLRPC_GetParamType revXMLRPC_GetPath revXMLRPC_GetPort ' + + 'revXMLRPC_GetProtocol revXMLRPC_GetRequest revXMLRPC_GetResponse revXMLRPC_GetSocket revXMLTree ' + + 'revXMLTrees revXMLValidateDTD revZipDescribeItem revZipEnumerateItems revZipOpenArchives round sampVariance ' + + 'sec secs seconds sentenceOffset sha1Digest shell shortFilePath sin specialFolderPath sqrt standardDeviation statRound ' + + 'stdDev sum sysError systemVersion tan tempName textDecode textEncode tick ticks time to tokenOffset toLower toUpper ' + + 'transpose truewordOffset trunc uniDecode uniEncode upper URLDecode URLEncode URLStatus uuid value variableNames ' + + 'variance version waitDepth weekdayNames wordOffset xsltApplyStylesheet xsltApplyStylesheetFromFile xsltLoadStylesheet ' + + 'xsltLoadStylesheetFromFile add breakpoint cancel clear local variable file word line folder directory URL close socket process ' + + 'combine constant convert create new alias folder directory decrypt delete variable word line folder ' + + 'directory URL dispatch divide do encrypt filter get include intersect kill libURLDownloadToFile ' + + 'libURLFollowHttpRedirects libURLftpUpload libURLftpUploadFile libURLresetAll libUrlSetAuthCallback libURLSetDriver ' + + 'libURLSetCustomHTTPHeaders libUrlSetExpect100 libURLSetFTPListCommand libURLSetFTPMode libURLSetFTPStopTime ' + + 'libURLSetStatusCallback load extension loadedExtensions multiply socket prepare process post seek rel relative read from process rename ' + + 'replace require resetAll resolve revAddXMLNode revAppendXML revCloseCursor revCloseDatabase revCommitDatabase ' + + 'revCopyFile revCopyFolder revCopyXMLNode revDeleteFolder revDeleteXMLNode revDeleteAllXMLTrees ' + + 'revDeleteXMLTree revExecuteSQL revGoURL revInsertXMLNode revMoveFolder revMoveToFirstRecord revMoveToLastRecord ' + + 'revMoveToNextRecord revMoveToPreviousRecord revMoveToRecord revMoveXMLNode revPutIntoXMLNode revRollBackDatabase ' + + 'revSetDatabaseDriverPath revSetXMLAttribute revXMLRPC_AddParam revXMLRPC_DeleteAllDocuments revXMLAddDTD ' + + 'revXMLRPC_Free revXMLRPC_FreeAll revXMLRPC_DeleteDocument revXMLRPC_DeleteParam revXMLRPC_SetHost ' + + 'revXMLRPC_SetMethod revXMLRPC_SetPort revXMLRPC_SetProtocol revXMLRPC_SetSocket revZipAddItemWithData ' + + 'revZipAddItemWithFile revZipAddUncompressedItemWithData revZipAddUncompressedItemWithFile revZipCancel ' + + 'revZipCloseArchive revZipDeleteItem revZipExtractItemToFile revZipExtractItemToVariable revZipSetProgressCallback ' + + 'revZipRenameItem revZipReplaceItemWithData revZipReplaceItemWithFile revZipOpenArchive send set sort split start stop ' + + 'subtract symmetric union unload vectorDotProduct wait write' + }, + contains: [ + VARIABLE, + { + className: 'keyword', + begin: '\\bend\\sif\\b' + }, + { + className: 'function', + beginKeywords: 'function', + end: '$', + contains: [ + VARIABLE, + TITLE2, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + hljs.BINARY_NUMBER_MODE, + hljs.C_NUMBER_MODE, + TITLE1 + ] + }, + { + className: 'function', + begin: '\\bend\\s+', + end: '$', + keywords: 'end', + contains: [ + TITLE2, + TITLE1 + ], + relevance: 0 + }, + { + beginKeywords: 'command on', + end: '$', + contains: [ + VARIABLE, + TITLE2, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + hljs.BINARY_NUMBER_MODE, + hljs.C_NUMBER_MODE, + TITLE1 + ] + }, + { + className: 'meta', + variants: [ + { + begin: '<\\?(rev|lc|livecode)', + relevance: 10 + }, + { + begin: '<\\?' + }, + { + begin: '\\?>' + } + ] + }, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + hljs.BINARY_NUMBER_MODE, + hljs.C_NUMBER_MODE, + TITLE1 + ].concat(COMMENT_MODES), + illegal: ';$|^\\[|^=|&|\\{' + }; +} + +module.exports = livecodeserver; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/livescript.js b/claude-code-source/node_modules/highlight.js/lib/languages/livescript.js new file mode 100644 index 00000000..b22cb9b4 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/livescript.js @@ -0,0 +1,374 @@ +const KEYWORDS = [ + "as", // for exports + "in", + "of", + "if", + "for", + "while", + "finally", + "var", + "new", + "function", + "do", + "return", + "void", + "else", + "break", + "catch", + "instanceof", + "with", + "throw", + "case", + "default", + "try", + "switch", + "continue", + "typeof", + "delete", + "let", + "yield", + "const", + "class", + // JS handles these with a special rule + // "get", + // "set", + "debugger", + "async", + "await", + "static", + "import", + "from", + "export", + "extends" +]; +const LITERALS = [ + "true", + "false", + "null", + "undefined", + "NaN", + "Infinity" +]; + +const TYPES = [ + "Intl", + "DataView", + "Number", + "Math", + "Date", + "String", + "RegExp", + "Object", + "Function", + "Boolean", + "Error", + "Symbol", + "Set", + "Map", + "WeakSet", + "WeakMap", + "Proxy", + "Reflect", + "JSON", + "Promise", + "Float64Array", + "Int16Array", + "Int32Array", + "Int8Array", + "Uint16Array", + "Uint32Array", + "Float32Array", + "Array", + "Uint8Array", + "Uint8ClampedArray", + "ArrayBuffer", + "BigInt64Array", + "BigUint64Array", + "BigInt" +]; + +const ERROR_TYPES = [ + "EvalError", + "InternalError", + "RangeError", + "ReferenceError", + "SyntaxError", + "TypeError", + "URIError" +]; + +const BUILT_IN_GLOBALS = [ + "setInterval", + "setTimeout", + "clearInterval", + "clearTimeout", + + "require", + "exports", + + "eval", + "isFinite", + "isNaN", + "parseFloat", + "parseInt", + "decodeURI", + "decodeURIComponent", + "encodeURI", + "encodeURIComponent", + "escape", + "unescape" +]; + +const BUILT_IN_VARIABLES = [ + "arguments", + "this", + "super", + "console", + "window", + "document", + "localStorage", + "module", + "global" // Node.js +]; + +const BUILT_INS = [].concat( + BUILT_IN_GLOBALS, + BUILT_IN_VARIABLES, + TYPES, + ERROR_TYPES +); + +/* +Language: LiveScript +Author: Taneli Vatanen +Contributors: Jen Evers-Corvina +Origin: coffeescript.js +Description: LiveScript is a programming language that transcompiles to JavaScript. For info about language see http://livescript.net/ +Website: https://livescript.net +Category: scripting +*/ + +function livescript(hljs) { + const LIVESCRIPT_BUILT_INS = [ + 'npm', + 'print' + ]; + const LIVESCRIPT_LITERALS = [ + 'yes', + 'no', + 'on', + 'off', + 'it', + 'that', + 'void' + ]; + const LIVESCRIPT_KEYWORDS = [ + 'then', + 'unless', + 'until', + 'loop', + 'of', + 'by', + 'when', + 'and', + 'or', + 'is', + 'isnt', + 'not', + 'it', + 'that', + 'otherwise', + 'from', + 'to', + 'til', + 'fallthrough', + 'case', + 'enum', + 'native', + 'list', + 'map', + '__hasProp', + '__extends', + '__slice', + '__bind', + '__indexOf' + ]; + const KEYWORDS$1 = { + keyword: KEYWORDS.concat(LIVESCRIPT_KEYWORDS), + literal: LITERALS.concat(LIVESCRIPT_LITERALS), + built_in: BUILT_INS.concat(LIVESCRIPT_BUILT_INS) + }; + const JS_IDENT_RE = '[A-Za-z$_](?:-[0-9A-Za-z$_]|[0-9A-Za-z$_])*'; + const TITLE = hljs.inherit(hljs.TITLE_MODE, { + begin: JS_IDENT_RE + }); + const SUBST = { + className: 'subst', + begin: /#\{/, + end: /\}/, + keywords: KEYWORDS$1 + }; + const SUBST_SIMPLE = { + className: 'subst', + begin: /#[A-Za-z$_]/, + end: /(?:-[0-9A-Za-z$_]|[0-9A-Za-z$_])*/, + keywords: KEYWORDS$1 + }; + const EXPRESSIONS = [ + hljs.BINARY_NUMBER_MODE, + { + className: 'number', + begin: '(\\b0[xX][a-fA-F0-9_]+)|(\\b\\d(\\d|_\\d)*(\\.(\\d(\\d|_\\d)*)?)?(_*[eE]([-+]\\d(_\\d|\\d)*)?)?[_a-z]*)', + relevance: 0, + starts: { + end: '(\\s*/)?', + relevance: 0 + } // a number tries to eat the following slash to prevent treating it as a regexp + }, + { + className: 'string', + variants: [ + { + begin: /'''/, + end: /'''/, + contains: [hljs.BACKSLASH_ESCAPE] + }, + { + begin: /'/, + end: /'/, + contains: [hljs.BACKSLASH_ESCAPE] + }, + { + begin: /"""/, + end: /"""/, + contains: [ + hljs.BACKSLASH_ESCAPE, + SUBST, + SUBST_SIMPLE + ] + }, + { + begin: /"/, + end: /"/, + contains: [ + hljs.BACKSLASH_ESCAPE, + SUBST, + SUBST_SIMPLE + ] + }, + { + begin: /\\/, + end: /(\s|$)/, + excludeEnd: true + } + ] + }, + { + className: 'regexp', + variants: [ + { + begin: '//', + end: '//[gim]*', + contains: [ + SUBST, + hljs.HASH_COMMENT_MODE + ] + }, + { + // regex can't start with space to parse x / 2 / 3 as two divisions + // regex can't start with *, and it supports an "illegal" in the main mode + begin: /\/(?![ *])(\\.|[^\\\n])*?\/[gim]*(?=\W)/ + } + ] + }, + { + begin: '@' + JS_IDENT_RE + }, + { + begin: '``', + end: '``', + excludeBegin: true, + excludeEnd: true, + subLanguage: 'javascript' + } + ]; + SUBST.contains = EXPRESSIONS; + + const PARAMS = { + className: 'params', + begin: '\\(', + returnBegin: true, + /* We need another contained nameless mode to not have every nested + pair of parens to be called "params" */ + contains: [ + { + begin: /\(/, + end: /\)/, + keywords: KEYWORDS$1, + contains: ['self'].concat(EXPRESSIONS) + } + ] + }; + + const SYMBOLS = { + begin: '(#=>|=>|\\|>>|-?->|!->)' + }; + + return { + name: 'LiveScript', + aliases: ['ls'], + keywords: KEYWORDS$1, + illegal: /\/\*/, + contains: EXPRESSIONS.concat([ + hljs.COMMENT('\\/\\*', '\\*\\/'), + hljs.HASH_COMMENT_MODE, + SYMBOLS, // relevance booster + { + className: 'function', + contains: [ + TITLE, + PARAMS + ], + returnBegin: true, + variants: [ + { + begin: '(' + JS_IDENT_RE + '\\s*(?:=|:=)\\s*)?(\\(.*\\)\\s*)?\\B->\\*?', + end: '->\\*?' + }, + { + begin: '(' + JS_IDENT_RE + '\\s*(?:=|:=)\\s*)?!?(\\(.*\\)\\s*)?\\B[-~]{1,2}>\\*?', + end: '[-~]{1,2}>\\*?' + }, + { + begin: '(' + JS_IDENT_RE + '\\s*(?:=|:=)\\s*)?(\\(.*\\)\\s*)?\\B!?[-~]{1,2}>\\*?', + end: '!?[-~]{1,2}>\\*?' + } + ] + }, + { + className: 'class', + beginKeywords: 'class', + end: '$', + illegal: /[:="\[\]]/, + contains: [ + { + beginKeywords: 'extends', + endsWithParent: true, + illegal: /[:="\[\]]/, + contains: [TITLE] + }, + TITLE + ] + }, + { + begin: JS_IDENT_RE + ':', + end: ':', + returnBegin: true, + returnEnd: true, + relevance: 0 + } + ]) + }; +} + +module.exports = livescript; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/llvm.js b/claude-code-source/node_modules/highlight.js/lib/languages/llvm.js new file mode 100644 index 00000000..b7eac64b --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/llvm.js @@ -0,0 +1,154 @@ +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/* +Language: LLVM IR +Author: Michael Rodler +Description: language used as intermediate representation in the LLVM compiler framework +Website: https://llvm.org/docs/LangRef.html +Category: assembler +Audit: 2020 +*/ + +/** @type LanguageFn */ +function llvm(hljs) { + const IDENT_RE = /([-a-zA-Z$._][\w$.-]*)/; + const TYPE = { + className: 'type', + begin: /\bi\d+(?=\s|\b)/ + }; + const OPERATOR = { + className: 'operator', + relevance: 0, + begin: /=/ + }; + const PUNCTUATION = { + className: 'punctuation', + relevance: 0, + begin: /,/ + }; + const NUMBER = { + className: 'number', + variants: [ + { begin: /0[xX][a-fA-F0-9]+/ }, + { begin: /-?\d+(?:[.]\d+)?(?:[eE][-+]?\d+(?:[.]\d+)?)?/ } + ], + relevance: 0 + }; + const LABEL = { + className: 'symbol', + variants: [ + { begin: /^\s*[a-z]+:/ }, // labels + ], + relevance: 0 + }; + const VARIABLE = { + className: 'variable', + variants: [ + { begin: concat(/%/, IDENT_RE) }, + { begin: /%\d+/ }, + { begin: /#\d+/ }, + ] + }; + const FUNCTION = { + className: 'title', + variants: [ + { begin: concat(/@/, IDENT_RE) }, + { begin: /@\d+/ }, + { begin: concat(/!/, IDENT_RE) }, + { begin: concat(/!\d+/, IDENT_RE) }, + // https://llvm.org/docs/LangRef.html#namedmetadatastructure + // obviously a single digit can also be used in this fashion + { begin: /!\d+/ } + ] + }; + + return { + name: 'LLVM IR', + // TODO: split into different categories of keywords + keywords: + 'begin end true false declare define global ' + + 'constant private linker_private internal ' + + 'available_externally linkonce linkonce_odr weak ' + + 'weak_odr appending dllimport dllexport common ' + + 'default hidden protected extern_weak external ' + + 'thread_local zeroinitializer undef null to tail ' + + 'target triple datalayout volatile nuw nsw nnan ' + + 'ninf nsz arcp fast exact inbounds align ' + + 'addrspace section alias module asm sideeffect ' + + 'gc dbg linker_private_weak attributes blockaddress ' + + 'initialexec localdynamic localexec prefix unnamed_addr ' + + 'ccc fastcc coldcc x86_stdcallcc x86_fastcallcc ' + + 'arm_apcscc arm_aapcscc arm_aapcs_vfpcc ptx_device ' + + 'ptx_kernel intel_ocl_bicc msp430_intrcc spir_func ' + + 'spir_kernel x86_64_sysvcc x86_64_win64cc x86_thiscallcc ' + + 'cc c signext zeroext inreg sret nounwind ' + + 'noreturn noalias nocapture byval nest readnone ' + + 'readonly inlinehint noinline alwaysinline optsize ssp ' + + 'sspreq noredzone noimplicitfloat naked builtin cold ' + + 'nobuiltin noduplicate nonlazybind optnone returns_twice ' + + 'sanitize_address sanitize_memory sanitize_thread sspstrong ' + + 'uwtable returned type opaque eq ne slt sgt ' + + 'sle sge ult ugt ule uge oeq one olt ogt ' + + 'ole oge ord uno ueq une x acq_rel acquire ' + + 'alignstack atomic catch cleanup filter inteldialect ' + + 'max min monotonic nand personality release seq_cst ' + + 'singlethread umax umin unordered xchg add fadd ' + + 'sub fsub mul fmul udiv sdiv fdiv urem srem ' + + 'frem shl lshr ashr and or xor icmp fcmp ' + + 'phi call trunc zext sext fptrunc fpext uitofp ' + + 'sitofp fptoui fptosi inttoptr ptrtoint bitcast ' + + 'addrspacecast select va_arg ret br switch invoke ' + + 'unwind unreachable indirectbr landingpad resume ' + + 'malloc alloca free load store getelementptr ' + + 'extractelement insertelement shufflevector getresult ' + + 'extractvalue insertvalue atomicrmw cmpxchg fence ' + + 'argmemonly double', + contains: [ + TYPE, + // this matches "empty comments"... + // ...because it's far more likely this is a statement terminator in + // another language than an actual comment + hljs.COMMENT(/;\s*$/, null, { relevance: 0 }), + hljs.COMMENT(/;/, /$/), + hljs.QUOTE_STRING_MODE, + { + className: 'string', + variants: [ + // Double-quoted string + { begin: /"/, end: /[^\\]"/ }, + ] + }, + FUNCTION, + PUNCTUATION, + OPERATOR, + VARIABLE, + LABEL, + NUMBER + ] + }; +} + +module.exports = llvm; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/lsl.js b/claude-code-source/node_modules/highlight.js/lib/languages/lsl.js new file mode 100644 index 00000000..279fc46d --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/lsl.js @@ -0,0 +1,95 @@ +/* +Language: LSL (Linden Scripting Language) +Description: The Linden Scripting Language is used in Second Life by Linden Labs. +Author: Builder's Brewery +Website: http://wiki.secondlife.com/wiki/LSL_Portal +Category: scripting +*/ + +function lsl(hljs) { + + var LSL_STRING_ESCAPE_CHARS = { + className: 'subst', + begin: /\\[tn"\\]/ + }; + + var LSL_STRINGS = { + className: 'string', + begin: '"', + end: '"', + contains: [ + LSL_STRING_ESCAPE_CHARS + ] + }; + + var LSL_NUMBERS = { + className: 'number', + relevance:0, + begin: hljs.C_NUMBER_RE + }; + + var LSL_CONSTANTS = { + className: 'literal', + variants: [ + { + begin: '\\b(PI|TWO_PI|PI_BY_TWO|DEG_TO_RAD|RAD_TO_DEG|SQRT2)\\b' + }, + { + begin: '\\b(XP_ERROR_(EXPERIENCES_DISABLED|EXPERIENCE_(DISABLED|SUSPENDED)|INVALID_(EXPERIENCE|PARAMETERS)|KEY_NOT_FOUND|MATURITY_EXCEEDED|NONE|NOT_(FOUND|PERMITTED(_LAND)?)|NO_EXPERIENCE|QUOTA_EXCEEDED|RETRY_UPDATE|STORAGE_EXCEPTION|STORE_DISABLED|THROTTLED|UNKNOWN_ERROR)|JSON_APPEND|STATUS_(PHYSICS|ROTATE_[XYZ]|PHANTOM|SANDBOX|BLOCK_GRAB(_OBJECT)?|(DIE|RETURN)_AT_EDGE|CAST_SHADOWS|OK|MALFORMED_PARAMS|TYPE_MISMATCH|BOUNDS_ERROR|NOT_(FOUND|SUPPORTED)|INTERNAL_ERROR|WHITELIST_FAILED)|AGENT(_(BY_(LEGACY_|USER)NAME|FLYING|ATTACHMENTS|SCRIPTED|MOUSELOOK|SITTING|ON_OBJECT|AWAY|WALKING|IN_AIR|TYPING|CROUCHING|BUSY|ALWAYS_RUN|AUTOPILOT|LIST_(PARCEL(_OWNER)?|REGION)))?|CAMERA_(PITCH|DISTANCE|BEHINDNESS_(ANGLE|LAG)|(FOCUS|POSITION)(_(THRESHOLD|LOCKED|LAG))?|FOCUS_OFFSET|ACTIVE)|ANIM_ON|LOOP|REVERSE|PING_PONG|SMOOTH|ROTATE|SCALE|ALL_SIDES|LINK_(ROOT|SET|ALL_(OTHERS|CHILDREN)|THIS)|ACTIVE|PASS(IVE|_(ALWAYS|IF_NOT_HANDLED|NEVER))|SCRIPTED|CONTROL_(FWD|BACK|(ROT_)?(LEFT|RIGHT)|UP|DOWN|(ML_)?LBUTTON)|PERMISSION_(RETURN_OBJECTS|DEBIT|OVERRIDE_ANIMATIONS|SILENT_ESTATE_MANAGEMENT|TAKE_CONTROLS|TRIGGER_ANIMATION|ATTACH|CHANGE_LINKS|(CONTROL|TRACK)_CAMERA|TELEPORT)|INVENTORY_(TEXTURE|SOUND|OBJECT|SCRIPT|LANDMARK|CLOTHING|NOTECARD|BODYPART|ANIMATION|GESTURE|ALL|NONE)|CHANGED_(INVENTORY|COLOR|SHAPE|SCALE|TEXTURE|LINK|ALLOWED_DROP|OWNER|REGION(_START)?|TELEPORT|MEDIA)|OBJECT_(CLICK_ACTION|HOVER_HEIGHT|LAST_OWNER_ID|(PHYSICS|SERVER|STREAMING)_COST|UNKNOWN_DETAIL|CHARACTER_TIME|PHANTOM|PHYSICS|TEMP_(ATTACHED|ON_REZ)|NAME|DESC|POS|PRIM_(COUNT|EQUIVALENCE)|RETURN_(PARCEL(_OWNER)?|REGION)|REZZER_KEY|ROO?T|VELOCITY|OMEGA|OWNER|GROUP(_TAG)?|CREATOR|ATTACHED_(POINT|SLOTS_AVAILABLE)|RENDER_WEIGHT|(BODY_SHAPE|PATHFINDING)_TYPE|(RUNNING|TOTAL)_SCRIPT_COUNT|TOTAL_INVENTORY_COUNT|SCRIPT_(MEMORY|TIME))|TYPE_(INTEGER|FLOAT|STRING|KEY|VECTOR|ROTATION|INVALID)|(DEBUG|PUBLIC)_CHANNEL|ATTACH_(AVATAR_CENTER|CHEST|HEAD|BACK|PELVIS|MOUTH|CHIN|NECK|NOSE|BELLY|[LR](SHOULDER|HAND|FOOT|EAR|EYE|[UL](ARM|LEG)|HIP)|(LEFT|RIGHT)_PEC|HUD_(CENTER_[12]|TOP_(RIGHT|CENTER|LEFT)|BOTTOM(_(RIGHT|LEFT))?)|[LR]HAND_RING1|TAIL_(BASE|TIP)|[LR]WING|FACE_(JAW|[LR]EAR|[LR]EYE|TOUNGE)|GROIN|HIND_[LR]FOOT)|LAND_(LEVEL|RAISE|LOWER|SMOOTH|NOISE|REVERT)|DATA_(ONLINE|NAME|BORN|SIM_(POS|STATUS|RATING)|PAYINFO)|PAYMENT_INFO_(ON_FILE|USED)|REMOTE_DATA_(CHANNEL|REQUEST|REPLY)|PSYS_(PART_(BF_(ZERO|ONE(_MINUS_(DEST_COLOR|SOURCE_(ALPHA|COLOR)))?|DEST_COLOR|SOURCE_(ALPHA|COLOR))|BLEND_FUNC_(DEST|SOURCE)|FLAGS|(START|END)_(COLOR|ALPHA|SCALE|GLOW)|MAX_AGE|(RIBBON|WIND|INTERP_(COLOR|SCALE)|BOUNCE|FOLLOW_(SRC|VELOCITY)|TARGET_(POS|LINEAR)|EMISSIVE)_MASK)|SRC_(MAX_AGE|PATTERN|ANGLE_(BEGIN|END)|BURST_(RATE|PART_COUNT|RADIUS|SPEED_(MIN|MAX))|ACCEL|TEXTURE|TARGET_KEY|OMEGA|PATTERN_(DROP|EXPLODE|ANGLE(_CONE(_EMPTY)?)?)))|VEHICLE_(REFERENCE_FRAME|TYPE_(NONE|SLED|CAR|BOAT|AIRPLANE|BALLOON)|(LINEAR|ANGULAR)_(FRICTION_TIMESCALE|MOTOR_DIRECTION)|LINEAR_MOTOR_OFFSET|HOVER_(HEIGHT|EFFICIENCY|TIMESCALE)|BUOYANCY|(LINEAR|ANGULAR)_(DEFLECTION_(EFFICIENCY|TIMESCALE)|MOTOR_(DECAY_)?TIMESCALE)|VERTICAL_ATTRACTION_(EFFICIENCY|TIMESCALE)|BANKING_(EFFICIENCY|MIX|TIMESCALE)|FLAG_(NO_DEFLECTION_UP|LIMIT_(ROLL_ONLY|MOTOR_UP)|HOVER_((WATER|TERRAIN|UP)_ONLY|GLOBAL_HEIGHT)|MOUSELOOK_(STEER|BANK)|CAMERA_DECOUPLED))|PRIM_(ALLOW_UNSIT|ALPHA_MODE(_(BLEND|EMISSIVE|MASK|NONE))?|NORMAL|SPECULAR|TYPE(_(BOX|CYLINDER|PRISM|SPHERE|TORUS|TUBE|RING|SCULPT))?|HOLE_(DEFAULT|CIRCLE|SQUARE|TRIANGLE)|MATERIAL(_(STONE|METAL|GLASS|WOOD|FLESH|PLASTIC|RUBBER))?|SHINY_(NONE|LOW|MEDIUM|HIGH)|BUMP_(NONE|BRIGHT|DARK|WOOD|BARK|BRICKS|CHECKER|CONCRETE|TILE|STONE|DISKS|GRAVEL|BLOBS|SIDING|LARGETILE|STUCCO|SUCTION|WEAVE)|TEXGEN_(DEFAULT|PLANAR)|SCRIPTED_SIT_ONLY|SCULPT_(TYPE_(SPHERE|TORUS|PLANE|CYLINDER|MASK)|FLAG_(MIRROR|INVERT))|PHYSICS(_(SHAPE_(CONVEX|NONE|PRIM|TYPE)))?|(POS|ROT)_LOCAL|SLICE|TEXT|FLEXIBLE|POINT_LIGHT|TEMP_ON_REZ|PHANTOM|POSITION|SIT_TARGET|SIZE|ROTATION|TEXTURE|NAME|OMEGA|DESC|LINK_TARGET|COLOR|BUMP_SHINY|FULLBRIGHT|TEXGEN|GLOW|MEDIA_(ALT_IMAGE_ENABLE|CONTROLS|(CURRENT|HOME)_URL|AUTO_(LOOP|PLAY|SCALE|ZOOM)|FIRST_CLICK_INTERACT|(WIDTH|HEIGHT)_PIXELS|WHITELIST(_ENABLE)?|PERMS_(INTERACT|CONTROL)|PARAM_MAX|CONTROLS_(STANDARD|MINI)|PERM_(NONE|OWNER|GROUP|ANYONE)|MAX_(URL_LENGTH|WHITELIST_(SIZE|COUNT)|(WIDTH|HEIGHT)_PIXELS)))|MASK_(BASE|OWNER|GROUP|EVERYONE|NEXT)|PERM_(TRANSFER|MODIFY|COPY|MOVE|ALL)|PARCEL_(MEDIA_COMMAND_(STOP|PAUSE|PLAY|LOOP|TEXTURE|URL|TIME|AGENT|UNLOAD|AUTO_ALIGN|TYPE|SIZE|DESC|LOOP_SET)|FLAG_(ALLOW_(FLY|(GROUP_)?SCRIPTS|LANDMARK|TERRAFORM|DAMAGE|CREATE_(GROUP_)?OBJECTS)|USE_(ACCESS_(GROUP|LIST)|BAN_LIST|LAND_PASS_LIST)|LOCAL_SOUND_ONLY|RESTRICT_PUSHOBJECT|ALLOW_(GROUP|ALL)_OBJECT_ENTRY)|COUNT_(TOTAL|OWNER|GROUP|OTHER|SELECTED|TEMP)|DETAILS_(NAME|DESC|OWNER|GROUP|AREA|ID|SEE_AVATARS))|LIST_STAT_(MAX|MIN|MEAN|MEDIAN|STD_DEV|SUM(_SQUARES)?|NUM_COUNT|GEOMETRIC_MEAN|RANGE)|PAY_(HIDE|DEFAULT)|REGION_FLAG_(ALLOW_DAMAGE|FIXED_SUN|BLOCK_TERRAFORM|SANDBOX|DISABLE_(COLLISIONS|PHYSICS)|BLOCK_FLY|ALLOW_DIRECT_TELEPORT|RESTRICT_PUSHOBJECT)|HTTP_(METHOD|MIMETYPE|BODY_(MAXLENGTH|TRUNCATED)|CUSTOM_HEADER|PRAGMA_NO_CACHE|VERBOSE_THROTTLE|VERIFY_CERT)|SIT_(INVALID_(AGENT|LINK_OBJECT)|NO(T_EXPERIENCE|_(ACCESS|EXPERIENCE_PERMISSION|SIT_TARGET)))|STRING_(TRIM(_(HEAD|TAIL))?)|CLICK_ACTION_(NONE|TOUCH|SIT|BUY|PAY|OPEN(_MEDIA)?|PLAY|ZOOM)|TOUCH_INVALID_FACE|PROFILE_(NONE|SCRIPT_MEMORY)|RC_(DATA_FLAGS|DETECT_PHANTOM|GET_(LINK_NUM|NORMAL|ROOT_KEY)|MAX_HITS|REJECT_(TYPES|AGENTS|(NON)?PHYSICAL|LAND))|RCERR_(CAST_TIME_EXCEEDED|SIM_PERF_LOW|UNKNOWN)|ESTATE_ACCESS_(ALLOWED_(AGENT|GROUP)_(ADD|REMOVE)|BANNED_AGENT_(ADD|REMOVE))|DENSITY|FRICTION|RESTITUTION|GRAVITY_MULTIPLIER|KFM_(COMMAND|CMD_(PLAY|STOP|PAUSE)|MODE|FORWARD|LOOP|PING_PONG|REVERSE|DATA|ROTATION|TRANSLATION)|ERR_(GENERIC|PARCEL_PERMISSIONS|MALFORMED_PARAMS|RUNTIME_PERMISSIONS|THROTTLED)|CHARACTER_(CMD_((SMOOTH_)?STOP|JUMP)|DESIRED_(TURN_)?SPEED|RADIUS|STAY_WITHIN_PARCEL|LENGTH|ORIENTATION|ACCOUNT_FOR_SKIPPED_FRAMES|AVOIDANCE_MODE|TYPE(_([ABCD]|NONE))?|MAX_(DECEL|TURN_RADIUS|(ACCEL|SPEED)))|PURSUIT_(OFFSET|FUZZ_FACTOR|GOAL_TOLERANCE|INTERCEPT)|REQUIRE_LINE_OF_SIGHT|FORCE_DIRECT_PATH|VERTICAL|HORIZONTAL|AVOID_(CHARACTERS|DYNAMIC_OBSTACLES|NONE)|PU_(EVADE_(HIDDEN|SPOTTED)|FAILURE_(DYNAMIC_PATHFINDING_DISABLED|INVALID_(GOAL|START)|NO_(NAVMESH|VALID_DESTINATION)|OTHER|TARGET_GONE|(PARCEL_)?UNREACHABLE)|(GOAL|SLOWDOWN_DISTANCE)_REACHED)|TRAVERSAL_TYPE(_(FAST|NONE|SLOW))?|CONTENT_TYPE_(ATOM|FORM|HTML|JSON|LLSD|RSS|TEXT|XHTML|XML)|GCNP_(RADIUS|STATIC)|(PATROL|WANDER)_PAUSE_AT_WAYPOINTS|OPT_(AVATAR|CHARACTER|EXCLUSION_VOLUME|LEGACY_LINKSET|MATERIAL_VOLUME|OTHER|STATIC_OBSTACLE|WALKABLE)|SIM_STAT_PCT_CHARS_STEPPED)\\b' + }, + { + begin: '\\b(FALSE|TRUE)\\b' + }, + { + begin: '\\b(ZERO_ROTATION)\\b' + }, + { + begin: '\\b(EOF|JSON_(ARRAY|DELETE|FALSE|INVALID|NULL|NUMBER|OBJECT|STRING|TRUE)|NULL_KEY|TEXTURE_(BLANK|DEFAULT|MEDIA|PLYWOOD|TRANSPARENT)|URL_REQUEST_(GRANTED|DENIED))\\b' + }, + { + begin: '\\b(ZERO_VECTOR|TOUCH_INVALID_(TEXCOORD|VECTOR))\\b' + } + ] + }; + + var LSL_FUNCTIONS = { + className: 'built_in', + begin: '\\b(ll(AgentInExperience|(Create|DataSize|Delete|KeyCount|Keys|Read|Update)KeyValue|GetExperience(Details|ErrorMessage)|ReturnObjectsBy(ID|Owner)|Json(2List|[GS]etValue|ValueType)|Sin|Cos|Tan|Atan2|Sqrt|Pow|Abs|Fabs|Frand|Floor|Ceil|Round|Vec(Mag|Norm|Dist)|Rot(Between|2(Euler|Fwd|Left|Up))|(Euler|Axes)2Rot|Whisper|(Region|Owner)?Say|Shout|Listen(Control|Remove)?|Sensor(Repeat|Remove)?|Detected(Name|Key|Owner|Type|Pos|Vel|Grab|Rot|Group|LinkNumber)|Die|Ground|Wind|([GS]et)(AnimationOverride|MemoryLimit|PrimMediaParams|ParcelMusicURL|Object(Desc|Name)|PhysicsMaterial|Status|Scale|Color|Alpha|Texture|Pos|Rot|Force|Torque)|ResetAnimationOverride|(Scale|Offset|Rotate)Texture|(Rot)?Target(Remove)?|(Stop)?MoveToTarget|Apply(Rotational)?Impulse|Set(KeyframedMotion|ContentType|RegionPos|(Angular)?Velocity|Buoyancy|HoverHeight|ForceAndTorque|TimerEvent|ScriptState|Damage|TextureAnim|Sound(Queueing|Radius)|Vehicle(Type|(Float|Vector|Rotation)Param)|(Touch|Sit)?Text|Camera(Eye|At)Offset|PrimitiveParams|ClickAction|Link(Alpha|Color|PrimitiveParams(Fast)?|Texture(Anim)?|Camera|Media)|RemoteScriptAccessPin|PayPrice|LocalRot)|ScaleByFactor|Get((Max|Min)ScaleFactor|ClosestNavPoint|StaticPath|SimStats|Env|PrimitiveParams|Link(PrimitiveParams|Number(OfSides)?|Key|Name|Media)|HTTPHeader|FreeURLs|Object(Details|PermMask|PrimCount)|Parcel(MaxPrims|Details|Prim(Count|Owners))|Attached(List)?|(SPMax|Free|Used)Memory|Region(Name|TimeDilation|FPS|Corner|AgentCount)|Root(Position|Rotation)|UnixTime|(Parcel|Region)Flags|(Wall|GMT)clock|SimulatorHostname|BoundingBox|GeometricCenter|Creator|NumberOf(Prims|NotecardLines|Sides)|Animation(List)?|(Camera|Local)(Pos|Rot)|Vel|Accel|Omega|Time(stamp|OfDay)|(Object|CenterOf)?Mass|MassMKS|Energy|Owner|(Owner)?Key|SunDirection|Texture(Offset|Scale|Rot)|Inventory(Number|Name|Key|Type|Creator|PermMask)|Permissions(Key)?|StartParameter|List(Length|EntryType)|Date|Agent(Size|Info|Language|List)|LandOwnerAt|NotecardLine|Script(Name|State))|(Get|Reset|GetAndReset)Time|PlaySound(Slave)?|LoopSound(Master|Slave)?|(Trigger|Stop|Preload)Sound|((Get|Delete)Sub|Insert)String|To(Upper|Lower)|Give(InventoryList|Money)|RezObject|(Stop)?LookAt|Sleep|CollisionFilter|(Take|Release)Controls|DetachFromAvatar|AttachToAvatar(Temp)?|InstantMessage|(GetNext)?Email|StopHover|MinEventDelay|RotLookAt|String(Length|Trim)|(Start|Stop)Animation|TargetOmega|Request(Experience)?Permissions|(Create|Break)Link|BreakAllLinks|(Give|Remove)Inventory|Water|PassTouches|Request(Agent|Inventory)Data|TeleportAgent(Home|GlobalCoords)?|ModifyLand|CollisionSound|ResetScript|MessageLinked|PushObject|PassCollisions|AxisAngle2Rot|Rot2(Axis|Angle)|A(cos|sin)|AngleBetween|AllowInventoryDrop|SubStringIndex|List2(CSV|Integer|Json|Float|String|Key|Vector|Rot|List(Strided)?)|DeleteSubList|List(Statistics|Sort|Randomize|(Insert|Find|Replace)List)|EdgeOfWorld|AdjustSoundVolume|Key2Name|TriggerSoundLimited|EjectFromLand|(CSV|ParseString)2List|OverMyLand|SameGroup|UnSit|Ground(Slope|Normal|Contour)|GroundRepel|(Set|Remove)VehicleFlags|SitOnLink|(AvatarOn)?(Link)?SitTarget|Script(Danger|Profiler)|Dialog|VolumeDetect|ResetOtherScript|RemoteLoadScriptPin|(Open|Close)RemoteDataChannel|SendRemoteData|RemoteDataReply|(Integer|String)ToBase64|XorBase64|Log(10)?|Base64To(String|Integer)|ParseStringKeepNulls|RezAtRoot|RequestSimulatorData|ForceMouselook|(Load|Release|(E|Une)scape)URL|ParcelMedia(CommandList|Query)|ModPow|MapDestination|(RemoveFrom|AddTo|Reset)Land(Pass|Ban)List|(Set|Clear)CameraParams|HTTP(Request|Response)|TextBox|DetectedTouch(UV|Face|Pos|(N|Bin)ormal|ST)|(MD5|SHA1|DumpList2)String|Request(Secure)?URL|Clear(Prim|Link)Media|(Link)?ParticleSystem|(Get|Request)(Username|DisplayName)|RegionSayTo|CastRay|GenerateKey|TransferLindenDollars|ManageEstateAccess|(Create|Delete)Character|ExecCharacterCmd|Evade|FleeFrom|NavigateTo|PatrolPoints|Pursue|UpdateCharacter|WanderWithin))\\b' + }; + + return { + name: 'LSL (Linden Scripting Language)', + illegal: ':', + contains: [ + LSL_STRINGS, + { + className: 'comment', + variants: [ + hljs.COMMENT('//', '$'), + hljs.COMMENT('/\\*', '\\*/') + ], + relevance: 0 + }, + LSL_NUMBERS, + { + className: 'section', + variants: [ + { + begin: '\\b(state|default)\\b' + }, + { + begin: '\\b(state_(entry|exit)|touch(_(start|end))?|(land_)?collision(_(start|end))?|timer|listen|(no_)?sensor|control|(not_)?at_(rot_)?target|money|email|experience_permissions(_denied)?|run_time_permissions|changed|attach|dataserver|moving_(start|end)|link_message|(on|object)_rez|remote_data|http_re(sponse|quest)|path_update|transaction_result)\\b' + } + ] + }, + LSL_FUNCTIONS, + LSL_CONSTANTS, + { + className: 'type', + begin: '\\b(integer|float|string|key|vector|quaternion|rotation|list)\\b' + } + ] + }; +} + +module.exports = lsl; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/lua.js b/claude-code-source/node_modules/highlight.js/lib/languages/lua.js new file mode 100644 index 00000000..210669d2 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/lua.js @@ -0,0 +1,82 @@ +/* +Language: Lua +Description: Lua is a powerful, efficient, lightweight, embeddable scripting language. +Author: Andrew Fedorov +Category: common, scripting +Website: https://www.lua.org +*/ + +function lua(hljs) { + const OPENING_LONG_BRACKET = '\\[=*\\['; + const CLOSING_LONG_BRACKET = '\\]=*\\]'; + const LONG_BRACKETS = { + begin: OPENING_LONG_BRACKET, + end: CLOSING_LONG_BRACKET, + contains: ['self'] + }; + const COMMENTS = [ + hljs.COMMENT('--(?!' + OPENING_LONG_BRACKET + ')', '$'), + hljs.COMMENT( + '--' + OPENING_LONG_BRACKET, + CLOSING_LONG_BRACKET, + { + contains: [LONG_BRACKETS], + relevance: 10 + } + ) + ]; + return { + name: 'Lua', + keywords: { + $pattern: hljs.UNDERSCORE_IDENT_RE, + literal: "true false nil", + keyword: "and break do else elseif end for goto if in local not or repeat return then until while", + built_in: + // Metatags and globals: + '_G _ENV _VERSION __index __newindex __mode __call __metatable __tostring __len ' + + '__gc __add __sub __mul __div __mod __pow __concat __unm __eq __lt __le assert ' + + // Standard methods and properties: + 'collectgarbage dofile error getfenv getmetatable ipairs load loadfile loadstring ' + + 'module next pairs pcall print rawequal rawget rawset require select setfenv ' + + 'setmetatable tonumber tostring type unpack xpcall arg self ' + + // Library methods and properties (one line per library): + 'coroutine resume yield status wrap create running debug getupvalue ' + + 'debug sethook getmetatable gethook setmetatable setlocal traceback setfenv getinfo setupvalue getlocal getregistry getfenv ' + + 'io lines write close flush open output type read stderr stdin input stdout popen tmpfile ' + + 'math log max acos huge ldexp pi cos tanh pow deg tan cosh sinh random randomseed frexp ceil floor rad abs sqrt modf asin min mod fmod log10 atan2 exp sin atan ' + + 'os exit setlocale date getenv difftime remove time clock tmpname rename execute package preload loadlib loaded loaders cpath config path seeall ' + + 'string sub upper len gfind rep find match char dump gmatch reverse byte format gsub lower ' + + 'table setn insert getn foreachi maxn foreach concat sort remove' + }, + contains: COMMENTS.concat([ + { + className: 'function', + beginKeywords: 'function', + end: '\\)', + contains: [ + hljs.inherit(hljs.TITLE_MODE, { + begin: '([_a-zA-Z]\\w*\\.)*([_a-zA-Z]\\w*:)?[_a-zA-Z]\\w*' + }), + { + className: 'params', + begin: '\\(', + endsWithParent: true, + contains: COMMENTS + } + ].concat(COMMENTS) + }, + hljs.C_NUMBER_MODE, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + { + className: 'string', + begin: OPENING_LONG_BRACKET, + end: CLOSING_LONG_BRACKET, + contains: [LONG_BRACKETS], + relevance: 5 + } + ]) + }; +} + +module.exports = lua; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/makefile.js b/claude-code-source/node_modules/highlight.js/lib/languages/makefile.js new file mode 100644 index 00000000..b1c55dda --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/makefile.js @@ -0,0 +1,92 @@ +/* +Language: Makefile +Author: Ivan Sagalaev +Contributors: Joël Porquet +Website: https://www.gnu.org/software/make/manual/html_node/Introduction.html +Category: common +*/ + +function makefile(hljs) { + /* Variables: simple (eg $(var)) and special (eg $@) */ + const VARIABLE = { + className: 'variable', + variants: [ + { + begin: '\\$\\(' + hljs.UNDERSCORE_IDENT_RE + '\\)', + contains: [ hljs.BACKSLASH_ESCAPE ] + }, + { + begin: /\$[@% source(x)).join(""); + return joined; +} + +/* +Language: Markdown +Requires: xml.js +Author: John Crepezzi +Website: https://daringfireball.net/projects/markdown/ +Category: common, markup +*/ + +function markdown(hljs) { + const INLINE_HTML = { + begin: /<\/?[A-Za-z_]/, + end: '>', + subLanguage: 'xml', + relevance: 0 + }; + const HORIZONTAL_RULE = { + begin: '^[-\\*]{3,}', + end: '$' + }; + const CODE = { + className: 'code', + variants: [ + // TODO: fix to allow these to work with sublanguage also + { + begin: '(`{3,})[^`](.|\\n)*?\\1`*[ ]*' + }, + { + begin: '(~{3,})[^~](.|\\n)*?\\1~*[ ]*' + }, + // needed to allow markdown as a sublanguage to work + { + begin: '```', + end: '```+[ ]*$' + }, + { + begin: '~~~', + end: '~~~+[ ]*$' + }, + { + begin: '`.+?`' + }, + { + begin: '(?=^( {4}|\\t))', + // use contains to gobble up multiple lines to allow the block to be whatever size + // but only have a single open/close tag vs one per line + contains: [ + { + begin: '^( {4}|\\t)', + end: '(\\n)$' + } + ], + relevance: 0 + } + ] + }; + const LIST = { + className: 'bullet', + begin: '^[ \t]*([*+-]|(\\d+\\.))(?=\\s+)', + end: '\\s+', + excludeEnd: true + }; + const LINK_REFERENCE = { + begin: /^\[[^\n]+\]:/, + returnBegin: true, + contains: [ + { + className: 'symbol', + begin: /\[/, + end: /\]/, + excludeBegin: true, + excludeEnd: true + }, + { + className: 'link', + begin: /:\s*/, + end: /$/, + excludeBegin: true + } + ] + }; + const URL_SCHEME = /[A-Za-z][A-Za-z0-9+.-]*/; + const LINK = { + variants: [ + // too much like nested array access in so many languages + // to have any real relevance + { + begin: /\[.+?\]\[.*?\]/, + relevance: 0 + }, + // popular internet URLs + { + begin: /\[.+?\]\(((data|javascript|mailto):|(?:http|ftp)s?:\/\/).*?\)/, + relevance: 2 + }, + { + begin: concat(/\[.+?\]\(/, URL_SCHEME, /:\/\/.*?\)/), + relevance: 2 + }, + // relative urls + { + begin: /\[.+?\]\([./?&#].*?\)/, + relevance: 1 + }, + // whatever else, lower relevance (might not be a link at all) + { + begin: /\[.+?\]\(.*?\)/, + relevance: 0 + } + ], + returnBegin: true, + contains: [ + { + className: 'string', + relevance: 0, + begin: '\\[', + end: '\\]', + excludeBegin: true, + returnEnd: true + }, + { + className: 'link', + relevance: 0, + begin: '\\]\\(', + end: '\\)', + excludeBegin: true, + excludeEnd: true + }, + { + className: 'symbol', + relevance: 0, + begin: '\\]\\[', + end: '\\]', + excludeBegin: true, + excludeEnd: true + } + ] + }; + const BOLD = { + className: 'strong', + contains: [], // defined later + variants: [ + { + begin: /_{2}/, + end: /_{2}/ + }, + { + begin: /\*{2}/, + end: /\*{2}/ + } + ] + }; + const ITALIC = { + className: 'emphasis', + contains: [], // defined later + variants: [ + { + begin: /\*(?!\*)/, + end: /\*/ + }, + { + begin: /_(?!_)/, + end: /_/, + relevance: 0 + } + ] + }; + BOLD.contains.push(ITALIC); + ITALIC.contains.push(BOLD); + + let CONTAINABLE = [ + INLINE_HTML, + LINK + ]; + + BOLD.contains = BOLD.contains.concat(CONTAINABLE); + ITALIC.contains = ITALIC.contains.concat(CONTAINABLE); + + CONTAINABLE = CONTAINABLE.concat(BOLD, ITALIC); + + const HEADER = { + className: 'section', + variants: [ + { + begin: '^#{1,6}', + end: '$', + contains: CONTAINABLE + }, + { + begin: '(?=^.+?\\n[=-]{2,}$)', + contains: [ + { + begin: '^[=-]*$' + }, + { + begin: '^', + end: "\\n", + contains: CONTAINABLE + } + ] + } + ] + }; + + const BLOCKQUOTE = { + className: 'quote', + begin: '^>\\s+', + contains: CONTAINABLE, + end: '$' + }; + + return { + name: 'Markdown', + aliases: [ + 'md', + 'mkdown', + 'mkd' + ], + contains: [ + HEADER, + INLINE_HTML, + LIST, + BOLD, + ITALIC, + BLOCKQUOTE, + CODE, + HORIZONTAL_RULE, + LINK, + LINK_REFERENCE + ] + }; +} + +module.exports = markdown; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/mathematica.js b/claude-code-source/node_modules/highlight.js/lib/languages/mathematica.js new file mode 100644 index 00000000..f376cb0b --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/mathematica.js @@ -0,0 +1,6797 @@ +const SYSTEM_SYMBOLS = [ + "AASTriangle", + "AbelianGroup", + "Abort", + "AbortKernels", + "AbortProtect", + "AbortScheduledTask", + "Above", + "Abs", + "AbsArg", + "AbsArgPlot", + "Absolute", + "AbsoluteCorrelation", + "AbsoluteCorrelationFunction", + "AbsoluteCurrentValue", + "AbsoluteDashing", + "AbsoluteFileName", + "AbsoluteOptions", + "AbsolutePointSize", + "AbsoluteThickness", + "AbsoluteTime", + "AbsoluteTiming", + "AcceptanceThreshold", + "AccountingForm", + "Accumulate", + "Accuracy", + "AccuracyGoal", + "ActionDelay", + "ActionMenu", + "ActionMenuBox", + "ActionMenuBoxOptions", + "Activate", + "Active", + "ActiveClassification", + "ActiveClassificationObject", + "ActiveItem", + "ActivePrediction", + "ActivePredictionObject", + "ActiveStyle", + "AcyclicGraphQ", + "AddOnHelpPath", + "AddSides", + "AddTo", + "AddToSearchIndex", + "AddUsers", + "AdjacencyGraph", + "AdjacencyList", + "AdjacencyMatrix", + "AdjacentMeshCells", + "AdjustmentBox", + "AdjustmentBoxOptions", + "AdjustTimeSeriesForecast", + "AdministrativeDivisionData", + "AffineHalfSpace", + "AffineSpace", + "AffineStateSpaceModel", + "AffineTransform", + "After", + "AggregatedEntityClass", + "AggregationLayer", + "AircraftData", + "AirportData", + "AirPressureData", + "AirTemperatureData", + "AiryAi", + "AiryAiPrime", + "AiryAiZero", + "AiryBi", + "AiryBiPrime", + "AiryBiZero", + "AlgebraicIntegerQ", + "AlgebraicNumber", + "AlgebraicNumberDenominator", + "AlgebraicNumberNorm", + "AlgebraicNumberPolynomial", + "AlgebraicNumberTrace", + "AlgebraicRules", + "AlgebraicRulesData", + "Algebraics", + "AlgebraicUnitQ", + "Alignment", + "AlignmentMarker", + "AlignmentPoint", + "All", + "AllowAdultContent", + "AllowedCloudExtraParameters", + "AllowedCloudParameterExtensions", + "AllowedDimensions", + "AllowedFrequencyRange", + "AllowedHeads", + "AllowGroupClose", + "AllowIncomplete", + "AllowInlineCells", + "AllowKernelInitialization", + "AllowLooseGrammar", + "AllowReverseGroupClose", + "AllowScriptLevelChange", + "AllowVersionUpdate", + "AllTrue", + "Alphabet", + "AlphabeticOrder", + "AlphabeticSort", + "AlphaChannel", + "AlternateImage", + "AlternatingFactorial", + "AlternatingGroup", + "AlternativeHypothesis", + "Alternatives", + "AltitudeMethod", + "AmbientLight", + "AmbiguityFunction", + "AmbiguityList", + "Analytic", + "AnatomyData", + "AnatomyForm", + "AnatomyPlot3D", + "AnatomySkinStyle", + "AnatomyStyling", + "AnchoredSearch", + "And", + "AndersonDarlingTest", + "AngerJ", + "AngleBisector", + "AngleBracket", + "AnglePath", + "AnglePath3D", + "AngleVector", + "AngularGauge", + "Animate", + "AnimationCycleOffset", + "AnimationCycleRepetitions", + "AnimationDirection", + "AnimationDisplayTime", + "AnimationRate", + "AnimationRepetitions", + "AnimationRunning", + "AnimationRunTime", + "AnimationTimeIndex", + "Animator", + "AnimatorBox", + "AnimatorBoxOptions", + "AnimatorElements", + "Annotate", + "Annotation", + "AnnotationDelete", + "AnnotationKeys", + "AnnotationRules", + "AnnotationValue", + "Annuity", + "AnnuityDue", + "Annulus", + "AnomalyDetection", + "AnomalyDetector", + "AnomalyDetectorFunction", + "Anonymous", + "Antialiasing", + "AntihermitianMatrixQ", + "Antisymmetric", + "AntisymmetricMatrixQ", + "Antonyms", + "AnyOrder", + "AnySubset", + "AnyTrue", + "Apart", + "ApartSquareFree", + "APIFunction", + "Appearance", + "AppearanceElements", + "AppearanceRules", + "AppellF1", + "Append", + "AppendCheck", + "AppendLayer", + "AppendTo", + "Apply", + "ApplySides", + "ArcCos", + "ArcCosh", + "ArcCot", + "ArcCoth", + "ArcCsc", + "ArcCsch", + "ArcCurvature", + "ARCHProcess", + "ArcLength", + "ArcSec", + "ArcSech", + "ArcSin", + "ArcSinDistribution", + "ArcSinh", + "ArcTan", + "ArcTanh", + "Area", + "Arg", + "ArgMax", + "ArgMin", + "ArgumentCountQ", + "ARIMAProcess", + "ArithmeticGeometricMean", + "ARMAProcess", + "Around", + "AroundReplace", + "ARProcess", + "Array", + "ArrayComponents", + "ArrayDepth", + "ArrayFilter", + "ArrayFlatten", + "ArrayMesh", + "ArrayPad", + "ArrayPlot", + "ArrayQ", + "ArrayResample", + "ArrayReshape", + "ArrayRules", + "Arrays", + "Arrow", + "Arrow3DBox", + "ArrowBox", + "Arrowheads", + "ASATriangle", + "Ask", + "AskAppend", + "AskConfirm", + "AskDisplay", + "AskedQ", + "AskedValue", + "AskFunction", + "AskState", + "AskTemplateDisplay", + "AspectRatio", + "AspectRatioFixed", + "Assert", + "AssociateTo", + "Association", + "AssociationFormat", + "AssociationMap", + "AssociationQ", + "AssociationThread", + "AssumeDeterministic", + "Assuming", + "Assumptions", + "AstronomicalData", + "Asymptotic", + "AsymptoticDSolveValue", + "AsymptoticEqual", + "AsymptoticEquivalent", + "AsymptoticGreater", + "AsymptoticGreaterEqual", + "AsymptoticIntegrate", + "AsymptoticLess", + "AsymptoticLessEqual", + "AsymptoticOutputTracker", + "AsymptoticProduct", + "AsymptoticRSolveValue", + "AsymptoticSolve", + "AsymptoticSum", + "Asynchronous", + "AsynchronousTaskObject", + "AsynchronousTasks", + "Atom", + "AtomCoordinates", + "AtomCount", + "AtomDiagramCoordinates", + "AtomList", + "AtomQ", + "AttentionLayer", + "Attributes", + "Audio", + "AudioAmplify", + "AudioAnnotate", + "AudioAnnotationLookup", + "AudioBlockMap", + "AudioCapture", + "AudioChannelAssignment", + "AudioChannelCombine", + "AudioChannelMix", + "AudioChannels", + "AudioChannelSeparate", + "AudioData", + "AudioDelay", + "AudioDelete", + "AudioDevice", + "AudioDistance", + "AudioEncoding", + "AudioFade", + "AudioFrequencyShift", + "AudioGenerator", + "AudioIdentify", + "AudioInputDevice", + "AudioInsert", + "AudioInstanceQ", + "AudioIntervals", + "AudioJoin", + "AudioLabel", + "AudioLength", + "AudioLocalMeasurements", + "AudioLooping", + "AudioLoudness", + "AudioMeasurements", + "AudioNormalize", + "AudioOutputDevice", + "AudioOverlay", + "AudioPad", + "AudioPan", + "AudioPartition", + "AudioPause", + "AudioPitchShift", + "AudioPlay", + "AudioPlot", + "AudioQ", + "AudioRecord", + "AudioReplace", + "AudioResample", + "AudioReverb", + "AudioReverse", + "AudioSampleRate", + "AudioSpectralMap", + "AudioSpectralTransformation", + "AudioSplit", + "AudioStop", + "AudioStream", + "AudioStreams", + "AudioTimeStretch", + "AudioTracks", + "AudioTrim", + "AudioType", + "AugmentedPolyhedron", + "AugmentedSymmetricPolynomial", + "Authenticate", + "Authentication", + "AuthenticationDialog", + "AutoAction", + "Autocomplete", + "AutocompletionFunction", + "AutoCopy", + "AutocorrelationTest", + "AutoDelete", + "AutoEvaluateEvents", + "AutoGeneratedPackage", + "AutoIndent", + "AutoIndentSpacings", + "AutoItalicWords", + "AutoloadPath", + "AutoMatch", + "Automatic", + "AutomaticImageSize", + "AutoMultiplicationSymbol", + "AutoNumberFormatting", + "AutoOpenNotebooks", + "AutoOpenPalettes", + "AutoQuoteCharacters", + "AutoRefreshed", + "AutoRemove", + "AutorunSequencing", + "AutoScaling", + "AutoScroll", + "AutoSpacing", + "AutoStyleOptions", + "AutoStyleWords", + "AutoSubmitting", + "Axes", + "AxesEdge", + "AxesLabel", + "AxesOrigin", + "AxesStyle", + "AxiomaticTheory", + "Axis", + "BabyMonsterGroupB", + "Back", + "Background", + "BackgroundAppearance", + "BackgroundTasksSettings", + "Backslash", + "Backsubstitution", + "Backward", + "Ball", + "Band", + "BandpassFilter", + "BandstopFilter", + "BarabasiAlbertGraphDistribution", + "BarChart", + "BarChart3D", + "BarcodeImage", + "BarcodeRecognize", + "BaringhausHenzeTest", + "BarLegend", + "BarlowProschanImportance", + "BarnesG", + "BarOrigin", + "BarSpacing", + "BartlettHannWindow", + "BartlettWindow", + "BaseDecode", + "BaseEncode", + "BaseForm", + "Baseline", + "BaselinePosition", + "BaseStyle", + "BasicRecurrentLayer", + "BatchNormalizationLayer", + "BatchSize", + "BatesDistribution", + "BattleLemarieWavelet", + "BayesianMaximization", + "BayesianMaximizationObject", + "BayesianMinimization", + "BayesianMinimizationObject", + "Because", + "BeckmannDistribution", + "Beep", + "Before", + "Begin", + "BeginDialogPacket", + "BeginFrontEndInteractionPacket", + "BeginPackage", + "BellB", + "BellY", + "Below", + "BenfordDistribution", + "BeniniDistribution", + "BenktanderGibratDistribution", + "BenktanderWeibullDistribution", + "BernoulliB", + "BernoulliDistribution", + "BernoulliGraphDistribution", + "BernoulliProcess", + "BernsteinBasis", + "BesselFilterModel", + "BesselI", + "BesselJ", + "BesselJZero", + "BesselK", + "BesselY", + "BesselYZero", + "Beta", + "BetaBinomialDistribution", + "BetaDistribution", + "BetaNegativeBinomialDistribution", + "BetaPrimeDistribution", + "BetaRegularized", + "Between", + "BetweennessCentrality", + "BeveledPolyhedron", + "BezierCurve", + "BezierCurve3DBox", + "BezierCurve3DBoxOptions", + "BezierCurveBox", + "BezierCurveBoxOptions", + "BezierFunction", + "BilateralFilter", + "Binarize", + "BinaryDeserialize", + "BinaryDistance", + "BinaryFormat", + "BinaryImageQ", + "BinaryRead", + "BinaryReadList", + "BinarySerialize", + "BinaryWrite", + "BinCounts", + "BinLists", + "Binomial", + "BinomialDistribution", + "BinomialProcess", + "BinormalDistribution", + "BiorthogonalSplineWavelet", + "BipartiteGraphQ", + "BiquadraticFilterModel", + "BirnbaumImportance", + "BirnbaumSaundersDistribution", + "BitAnd", + "BitClear", + "BitGet", + "BitLength", + "BitNot", + "BitOr", + "BitSet", + "BitShiftLeft", + "BitShiftRight", + "BitXor", + "BiweightLocation", + "BiweightMidvariance", + "Black", + "BlackmanHarrisWindow", + "BlackmanNuttallWindow", + "BlackmanWindow", + "Blank", + "BlankForm", + "BlankNullSequence", + "BlankSequence", + "Blend", + "Block", + "BlockchainAddressData", + "BlockchainBase", + "BlockchainBlockData", + "BlockchainContractValue", + "BlockchainData", + "BlockchainGet", + "BlockchainKeyEncode", + "BlockchainPut", + "BlockchainTokenData", + "BlockchainTransaction", + "BlockchainTransactionData", + "BlockchainTransactionSign", + "BlockchainTransactionSubmit", + "BlockMap", + "BlockRandom", + "BlomqvistBeta", + "BlomqvistBetaTest", + "Blue", + "Blur", + "BodePlot", + "BohmanWindow", + "Bold", + "Bond", + "BondCount", + "BondList", + "BondQ", + "Bookmarks", + "Boole", + "BooleanConsecutiveFunction", + "BooleanConvert", + "BooleanCountingFunction", + "BooleanFunction", + "BooleanGraph", + "BooleanMaxterms", + "BooleanMinimize", + "BooleanMinterms", + "BooleanQ", + "BooleanRegion", + "Booleans", + "BooleanStrings", + "BooleanTable", + "BooleanVariables", + "BorderDimensions", + "BorelTannerDistribution", + "Bottom", + "BottomHatTransform", + "BoundaryDiscretizeGraphics", + "BoundaryDiscretizeRegion", + "BoundaryMesh", + "BoundaryMeshRegion", + "BoundaryMeshRegionQ", + "BoundaryStyle", + "BoundedRegionQ", + "BoundingRegion", + "Bounds", + "Box", + "BoxBaselineShift", + "BoxData", + "BoxDimensions", + "Boxed", + "Boxes", + "BoxForm", + "BoxFormFormatTypes", + "BoxFrame", + "BoxID", + "BoxMargins", + "BoxMatrix", + "BoxObject", + "BoxRatios", + "BoxRotation", + "BoxRotationPoint", + "BoxStyle", + "BoxWhiskerChart", + "Bra", + "BracketingBar", + "BraKet", + "BrayCurtisDistance", + "BreadthFirstScan", + "Break", + "BridgeData", + "BrightnessEqualize", + "BroadcastStationData", + "Brown", + "BrownForsytheTest", + "BrownianBridgeProcess", + "BrowserCategory", + "BSplineBasis", + "BSplineCurve", + "BSplineCurve3DBox", + "BSplineCurve3DBoxOptions", + "BSplineCurveBox", + "BSplineCurveBoxOptions", + "BSplineFunction", + "BSplineSurface", + "BSplineSurface3DBox", + "BSplineSurface3DBoxOptions", + "BubbleChart", + "BubbleChart3D", + "BubbleScale", + "BubbleSizes", + "BuildingData", + "BulletGauge", + "BusinessDayQ", + "ButterflyGraph", + "ButterworthFilterModel", + "Button", + "ButtonBar", + "ButtonBox", + "ButtonBoxOptions", + "ButtonCell", + "ButtonContents", + "ButtonData", + "ButtonEvaluator", + "ButtonExpandable", + "ButtonFrame", + "ButtonFunction", + "ButtonMargins", + "ButtonMinHeight", + "ButtonNote", + "ButtonNotebook", + "ButtonSource", + "ButtonStyle", + "ButtonStyleMenuListing", + "Byte", + "ByteArray", + "ByteArrayFormat", + "ByteArrayQ", + "ByteArrayToString", + "ByteCount", + "ByteOrdering", + "C", + "CachedValue", + "CacheGraphics", + "CachePersistence", + "CalendarConvert", + "CalendarData", + "CalendarType", + "Callout", + "CalloutMarker", + "CalloutStyle", + "CallPacket", + "CanberraDistance", + "Cancel", + "CancelButton", + "CandlestickChart", + "CanonicalGraph", + "CanonicalizePolygon", + "CanonicalizePolyhedron", + "CanonicalName", + "CanonicalWarpingCorrespondence", + "CanonicalWarpingDistance", + "CantorMesh", + "CantorStaircase", + "Cap", + "CapForm", + "CapitalDifferentialD", + "Capitalize", + "CapsuleShape", + "CaptureRunning", + "CardinalBSplineBasis", + "CarlemanLinearize", + "CarmichaelLambda", + "CaseOrdering", + "Cases", + "CaseSensitive", + "Cashflow", + "Casoratian", + "Catalan", + "CatalanNumber", + "Catch", + "CategoricalDistribution", + "Catenate", + "CatenateLayer", + "CauchyDistribution", + "CauchyWindow", + "CayleyGraph", + "CDF", + "CDFDeploy", + "CDFInformation", + "CDFWavelet", + "Ceiling", + "CelestialSystem", + "Cell", + "CellAutoOverwrite", + "CellBaseline", + "CellBoundingBox", + "CellBracketOptions", + "CellChangeTimes", + "CellContents", + "CellContext", + "CellDingbat", + "CellDynamicExpression", + "CellEditDuplicate", + "CellElementsBoundingBox", + "CellElementSpacings", + "CellEpilog", + "CellEvaluationDuplicate", + "CellEvaluationFunction", + "CellEvaluationLanguage", + "CellEventActions", + "CellFrame", + "CellFrameColor", + "CellFrameLabelMargins", + "CellFrameLabels", + "CellFrameMargins", + "CellGroup", + "CellGroupData", + "CellGrouping", + "CellGroupingRules", + "CellHorizontalScrolling", + "CellID", + "CellLabel", + "CellLabelAutoDelete", + "CellLabelMargins", + "CellLabelPositioning", + "CellLabelStyle", + "CellLabelTemplate", + "CellMargins", + "CellObject", + "CellOpen", + "CellPrint", + "CellProlog", + "Cells", + "CellSize", + "CellStyle", + "CellTags", + "CellularAutomaton", + "CensoredDistribution", + "Censoring", + "Center", + "CenterArray", + "CenterDot", + "CentralFeature", + "CentralMoment", + "CentralMomentGeneratingFunction", + "Cepstrogram", + "CepstrogramArray", + "CepstrumArray", + "CForm", + "ChampernowneNumber", + "ChangeOptions", + "ChannelBase", + "ChannelBrokerAction", + "ChannelDatabin", + "ChannelHistoryLength", + "ChannelListen", + "ChannelListener", + "ChannelListeners", + "ChannelListenerWait", + "ChannelObject", + "ChannelPreSendFunction", + "ChannelReceiverFunction", + "ChannelSend", + "ChannelSubscribers", + "ChanVeseBinarize", + "Character", + "CharacterCounts", + "CharacterEncoding", + "CharacterEncodingsPath", + "CharacteristicFunction", + "CharacteristicPolynomial", + "CharacterName", + "CharacterNormalize", + "CharacterRange", + "Characters", + "ChartBaseStyle", + "ChartElementData", + "ChartElementDataFunction", + "ChartElementFunction", + "ChartElements", + "ChartLabels", + "ChartLayout", + "ChartLegends", + "ChartStyle", + "Chebyshev1FilterModel", + "Chebyshev2FilterModel", + "ChebyshevDistance", + "ChebyshevT", + "ChebyshevU", + "Check", + "CheckAbort", + "CheckAll", + "Checkbox", + "CheckboxBar", + "CheckboxBox", + "CheckboxBoxOptions", + "ChemicalData", + "ChessboardDistance", + "ChiDistribution", + "ChineseRemainder", + "ChiSquareDistribution", + "ChoiceButtons", + "ChoiceDialog", + "CholeskyDecomposition", + "Chop", + "ChromaticityPlot", + "ChromaticityPlot3D", + "ChromaticPolynomial", + "Circle", + "CircleBox", + "CircleDot", + "CircleMinus", + "CirclePlus", + "CirclePoints", + "CircleThrough", + "CircleTimes", + "CirculantGraph", + "CircularOrthogonalMatrixDistribution", + "CircularQuaternionMatrixDistribution", + "CircularRealMatrixDistribution", + "CircularSymplecticMatrixDistribution", + "CircularUnitaryMatrixDistribution", + "Circumsphere", + "CityData", + "ClassifierFunction", + "ClassifierInformation", + "ClassifierMeasurements", + "ClassifierMeasurementsObject", + "Classify", + "ClassPriors", + "Clear", + "ClearAll", + "ClearAttributes", + "ClearCookies", + "ClearPermissions", + "ClearSystemCache", + "ClebschGordan", + "ClickPane", + "Clip", + "ClipboardNotebook", + "ClipFill", + "ClippingStyle", + "ClipPlanes", + "ClipPlanesStyle", + "ClipRange", + "Clock", + "ClockGauge", + "ClockwiseContourIntegral", + "Close", + "Closed", + "CloseKernels", + "ClosenessCentrality", + "Closing", + "ClosingAutoSave", + "ClosingEvent", + "ClosingSaveDialog", + "CloudAccountData", + "CloudBase", + "CloudConnect", + "CloudConnections", + "CloudDeploy", + "CloudDirectory", + "CloudDisconnect", + "CloudEvaluate", + "CloudExport", + "CloudExpression", + "CloudExpressions", + "CloudFunction", + "CloudGet", + "CloudImport", + "CloudLoggingData", + "CloudObject", + "CloudObjectInformation", + "CloudObjectInformationData", + "CloudObjectNameFormat", + "CloudObjects", + "CloudObjectURLType", + "CloudPublish", + "CloudPut", + "CloudRenderingMethod", + "CloudSave", + "CloudShare", + "CloudSubmit", + "CloudSymbol", + "CloudUnshare", + "CloudUserID", + "ClusterClassify", + "ClusterDissimilarityFunction", + "ClusteringComponents", + "ClusteringTree", + "CMYKColor", + "Coarse", + "CodeAssistOptions", + "Coefficient", + "CoefficientArrays", + "CoefficientDomain", + "CoefficientList", + "CoefficientRules", + "CoifletWavelet", + "Collect", + "Colon", + "ColonForm", + "ColorBalance", + "ColorCombine", + "ColorConvert", + "ColorCoverage", + "ColorData", + "ColorDataFunction", + "ColorDetect", + "ColorDistance", + "ColorFunction", + "ColorFunctionScaling", + "Colorize", + "ColorNegate", + "ColorOutput", + "ColorProfileData", + "ColorQ", + "ColorQuantize", + "ColorReplace", + "ColorRules", + "ColorSelectorSettings", + "ColorSeparate", + "ColorSetter", + "ColorSetterBox", + "ColorSetterBoxOptions", + "ColorSlider", + "ColorsNear", + "ColorSpace", + "ColorToneMapping", + "Column", + "ColumnAlignments", + "ColumnBackgrounds", + "ColumnForm", + "ColumnLines", + "ColumnsEqual", + "ColumnSpacings", + "ColumnWidths", + "CombinedEntityClass", + "CombinerFunction", + "CometData", + "CommonDefaultFormatTypes", + "Commonest", + "CommonestFilter", + "CommonName", + "CommonUnits", + "CommunityBoundaryStyle", + "CommunityGraphPlot", + "CommunityLabels", + "CommunityRegionStyle", + "CompanyData", + "CompatibleUnitQ", + "CompilationOptions", + "CompilationTarget", + "Compile", + "Compiled", + "CompiledCodeFunction", + "CompiledFunction", + "CompilerOptions", + "Complement", + "ComplementedEntityClass", + "CompleteGraph", + "CompleteGraphQ", + "CompleteKaryTree", + "CompletionsListPacket", + "Complex", + "ComplexContourPlot", + "Complexes", + "ComplexExpand", + "ComplexInfinity", + "ComplexityFunction", + "ComplexListPlot", + "ComplexPlot", + "ComplexPlot3D", + "ComplexRegionPlot", + "ComplexStreamPlot", + "ComplexVectorPlot", + "ComponentMeasurements", + "ComponentwiseContextMenu", + "Compose", + "ComposeList", + "ComposeSeries", + "CompositeQ", + "Composition", + "CompoundElement", + "CompoundExpression", + "CompoundPoissonDistribution", + "CompoundPoissonProcess", + "CompoundRenewalProcess", + "Compress", + "CompressedData", + "CompressionLevel", + "ComputeUncertainty", + "Condition", + "ConditionalExpression", + "Conditioned", + "Cone", + "ConeBox", + "ConfidenceLevel", + "ConfidenceRange", + "ConfidenceTransform", + "ConfigurationPath", + "ConformAudio", + "ConformImages", + "Congruent", + "ConicHullRegion", + "ConicHullRegion3DBox", + "ConicHullRegionBox", + "ConicOptimization", + "Conjugate", + "ConjugateTranspose", + "Conjunction", + "Connect", + "ConnectedComponents", + "ConnectedGraphComponents", + "ConnectedGraphQ", + "ConnectedMeshComponents", + "ConnectedMoleculeComponents", + "ConnectedMoleculeQ", + "ConnectionSettings", + "ConnectLibraryCallbackFunction", + "ConnectSystemModelComponents", + "ConnesWindow", + "ConoverTest", + "ConsoleMessage", + "ConsoleMessagePacket", + "Constant", + "ConstantArray", + "ConstantArrayLayer", + "ConstantImage", + "ConstantPlusLayer", + "ConstantRegionQ", + "Constants", + "ConstantTimesLayer", + "ConstellationData", + "ConstrainedMax", + "ConstrainedMin", + "Construct", + "Containing", + "ContainsAll", + "ContainsAny", + "ContainsExactly", + "ContainsNone", + "ContainsOnly", + "ContentFieldOptions", + "ContentLocationFunction", + "ContentObject", + "ContentPadding", + "ContentsBoundingBox", + "ContentSelectable", + "ContentSize", + "Context", + "ContextMenu", + "Contexts", + "ContextToFileName", + "Continuation", + "Continue", + "ContinuedFraction", + "ContinuedFractionK", + "ContinuousAction", + "ContinuousMarkovProcess", + "ContinuousTask", + "ContinuousTimeModelQ", + "ContinuousWaveletData", + "ContinuousWaveletTransform", + "ContourDetect", + "ContourGraphics", + "ContourIntegral", + "ContourLabels", + "ContourLines", + "ContourPlot", + "ContourPlot3D", + "Contours", + "ContourShading", + "ContourSmoothing", + "ContourStyle", + "ContraharmonicMean", + "ContrastiveLossLayer", + "Control", + "ControlActive", + "ControlAlignment", + "ControlGroupContentsBox", + "ControllabilityGramian", + "ControllabilityMatrix", + "ControllableDecomposition", + "ControllableModelQ", + "ControllerDuration", + "ControllerInformation", + "ControllerInformationData", + "ControllerLinking", + "ControllerManipulate", + "ControllerMethod", + "ControllerPath", + "ControllerState", + "ControlPlacement", + "ControlsRendering", + "ControlType", + "Convergents", + "ConversionOptions", + "ConversionRules", + "ConvertToBitmapPacket", + "ConvertToPostScript", + "ConvertToPostScriptPacket", + "ConvexHullMesh", + "ConvexPolygonQ", + "ConvexPolyhedronQ", + "ConvolutionLayer", + "Convolve", + "ConwayGroupCo1", + "ConwayGroupCo2", + "ConwayGroupCo3", + "CookieFunction", + "Cookies", + "CoordinateBoundingBox", + "CoordinateBoundingBoxArray", + "CoordinateBounds", + "CoordinateBoundsArray", + "CoordinateChartData", + "CoordinatesToolOptions", + "CoordinateTransform", + "CoordinateTransformData", + "CoprimeQ", + "Coproduct", + "CopulaDistribution", + "Copyable", + "CopyDatabin", + "CopyDirectory", + "CopyFile", + "CopyTag", + "CopyToClipboard", + "CornerFilter", + "CornerNeighbors", + "Correlation", + "CorrelationDistance", + "CorrelationFunction", + "CorrelationTest", + "Cos", + "Cosh", + "CoshIntegral", + "CosineDistance", + "CosineWindow", + "CosIntegral", + "Cot", + "Coth", + "Count", + "CountDistinct", + "CountDistinctBy", + "CounterAssignments", + "CounterBox", + "CounterBoxOptions", + "CounterClockwiseContourIntegral", + "CounterEvaluator", + "CounterFunction", + "CounterIncrements", + "CounterStyle", + "CounterStyleMenuListing", + "CountRoots", + "CountryData", + "Counts", + "CountsBy", + "Covariance", + "CovarianceEstimatorFunction", + "CovarianceFunction", + "CoxianDistribution", + "CoxIngersollRossProcess", + "CoxModel", + "CoxModelFit", + "CramerVonMisesTest", + "CreateArchive", + "CreateCellID", + "CreateChannel", + "CreateCloudExpression", + "CreateDatabin", + "CreateDataStructure", + "CreateDataSystemModel", + "CreateDialog", + "CreateDirectory", + "CreateDocument", + "CreateFile", + "CreateIntermediateDirectories", + "CreateManagedLibraryExpression", + "CreateNotebook", + "CreatePacletArchive", + "CreatePalette", + "CreatePalettePacket", + "CreatePermissionsGroup", + "CreateScheduledTask", + "CreateSearchIndex", + "CreateSystemModel", + "CreateTemporary", + "CreateUUID", + "CreateWindow", + "CriterionFunction", + "CriticalityFailureImportance", + "CriticalitySuccessImportance", + "CriticalSection", + "Cross", + "CrossEntropyLossLayer", + "CrossingCount", + "CrossingDetect", + "CrossingPolygon", + "CrossMatrix", + "Csc", + "Csch", + "CTCLossLayer", + "Cube", + "CubeRoot", + "Cubics", + "Cuboid", + "CuboidBox", + "Cumulant", + "CumulantGeneratingFunction", + "Cup", + "CupCap", + "Curl", + "CurlyDoubleQuote", + "CurlyQuote", + "CurrencyConvert", + "CurrentDate", + "CurrentImage", + "CurrentlySpeakingPacket", + "CurrentNotebookImage", + "CurrentScreenImage", + "CurrentValue", + "Curry", + "CurryApplied", + "CurvatureFlowFilter", + "CurveClosed", + "Cyan", + "CycleGraph", + "CycleIndexPolynomial", + "Cycles", + "CyclicGroup", + "Cyclotomic", + "Cylinder", + "CylinderBox", + "CylindricalDecomposition", + "D", + "DagumDistribution", + "DamData", + "DamerauLevenshteinDistance", + "DampingFactor", + "Darker", + "Dashed", + "Dashing", + "DatabaseConnect", + "DatabaseDisconnect", + "DatabaseReference", + "Databin", + "DatabinAdd", + "DatabinRemove", + "Databins", + "DatabinUpload", + "DataCompression", + "DataDistribution", + "DataRange", + "DataReversed", + "Dataset", + "DatasetDisplayPanel", + "DataStructure", + "DataStructureQ", + "Date", + "DateBounds", + "Dated", + "DateDelimiters", + "DateDifference", + "DatedUnit", + "DateFormat", + "DateFunction", + "DateHistogram", + "DateInterval", + "DateList", + "DateListLogPlot", + "DateListPlot", + "DateListStepPlot", + "DateObject", + "DateObjectQ", + "DateOverlapsQ", + "DatePattern", + "DatePlus", + "DateRange", + "DateReduction", + "DateString", + "DateTicksFormat", + "DateValue", + "DateWithinQ", + "DaubechiesWavelet", + "DavisDistribution", + "DawsonF", + "DayCount", + "DayCountConvention", + "DayHemisphere", + "DaylightQ", + "DayMatchQ", + "DayName", + "DayNightTerminator", + "DayPlus", + "DayRange", + "DayRound", + "DeBruijnGraph", + "DeBruijnSequence", + "Debug", + "DebugTag", + "Decapitalize", + "Decimal", + "DecimalForm", + "DeclareKnownSymbols", + "DeclarePackage", + "Decompose", + "DeconvolutionLayer", + "Decrement", + "Decrypt", + "DecryptFile", + "DedekindEta", + "DeepSpaceProbeData", + "Default", + "DefaultAxesStyle", + "DefaultBaseStyle", + "DefaultBoxStyle", + "DefaultButton", + "DefaultColor", + "DefaultControlPlacement", + "DefaultDuplicateCellStyle", + "DefaultDuration", + "DefaultElement", + "DefaultFaceGridsStyle", + "DefaultFieldHintStyle", + "DefaultFont", + "DefaultFontProperties", + "DefaultFormatType", + "DefaultFormatTypeForStyle", + "DefaultFrameStyle", + "DefaultFrameTicksStyle", + "DefaultGridLinesStyle", + "DefaultInlineFormatType", + "DefaultInputFormatType", + "DefaultLabelStyle", + "DefaultMenuStyle", + "DefaultNaturalLanguage", + "DefaultNewCellStyle", + "DefaultNewInlineCellStyle", + "DefaultNotebook", + "DefaultOptions", + "DefaultOutputFormatType", + "DefaultPrintPrecision", + "DefaultStyle", + "DefaultStyleDefinitions", + "DefaultTextFormatType", + "DefaultTextInlineFormatType", + "DefaultTicksStyle", + "DefaultTooltipStyle", + "DefaultValue", + "DefaultValues", + "Defer", + "DefineExternal", + "DefineInputStreamMethod", + "DefineOutputStreamMethod", + "DefineResourceFunction", + "Definition", + "Degree", + "DegreeCentrality", + "DegreeGraphDistribution", + "DegreeLexicographic", + "DegreeReverseLexicographic", + "DEigensystem", + "DEigenvalues", + "Deinitialization", + "Del", + "DelaunayMesh", + "Delayed", + "Deletable", + "Delete", + "DeleteAnomalies", + "DeleteBorderComponents", + "DeleteCases", + "DeleteChannel", + "DeleteCloudExpression", + "DeleteContents", + "DeleteDirectory", + "DeleteDuplicates", + "DeleteDuplicatesBy", + "DeleteFile", + "DeleteMissing", + "DeleteObject", + "DeletePermissionsKey", + "DeleteSearchIndex", + "DeleteSmallComponents", + "DeleteStopwords", + "DeleteWithContents", + "DeletionWarning", + "DelimitedArray", + "DelimitedSequence", + "Delimiter", + "DelimiterFlashTime", + "DelimiterMatching", + "Delimiters", + "DeliveryFunction", + "Dendrogram", + "Denominator", + "DensityGraphics", + "DensityHistogram", + "DensityPlot", + "DensityPlot3D", + "DependentVariables", + "Deploy", + "Deployed", + "Depth", + "DepthFirstScan", + "Derivative", + "DerivativeFilter", + "DerivedKey", + "DescriptorStateSpace", + "DesignMatrix", + "DestroyAfterEvaluation", + "Det", + "DeviceClose", + "DeviceConfigure", + "DeviceExecute", + "DeviceExecuteAsynchronous", + "DeviceObject", + "DeviceOpen", + "DeviceOpenQ", + "DeviceRead", + "DeviceReadBuffer", + "DeviceReadLatest", + "DeviceReadList", + "DeviceReadTimeSeries", + "Devices", + "DeviceStreams", + "DeviceWrite", + "DeviceWriteBuffer", + "DGaussianWavelet", + "DiacriticalPositioning", + "Diagonal", + "DiagonalizableMatrixQ", + "DiagonalMatrix", + "DiagonalMatrixQ", + "Dialog", + "DialogIndent", + "DialogInput", + "DialogLevel", + "DialogNotebook", + "DialogProlog", + "DialogReturn", + "DialogSymbols", + "Diamond", + "DiamondMatrix", + "DiceDissimilarity", + "DictionaryLookup", + "DictionaryWordQ", + "DifferenceDelta", + "DifferenceOrder", + "DifferenceQuotient", + "DifferenceRoot", + "DifferenceRootReduce", + "Differences", + "DifferentialD", + "DifferentialRoot", + "DifferentialRootReduce", + "DifferentiatorFilter", + "DigitalSignature", + "DigitBlock", + "DigitBlockMinimum", + "DigitCharacter", + "DigitCount", + "DigitQ", + "DihedralAngle", + "DihedralGroup", + "Dilation", + "DimensionalCombinations", + "DimensionalMeshComponents", + "DimensionReduce", + "DimensionReducerFunction", + "DimensionReduction", + "Dimensions", + "DiracComb", + "DiracDelta", + "DirectedEdge", + "DirectedEdges", + "DirectedGraph", + "DirectedGraphQ", + "DirectedInfinity", + "Direction", + "Directive", + "Directory", + "DirectoryName", + "DirectoryQ", + "DirectoryStack", + "DirichletBeta", + "DirichletCharacter", + "DirichletCondition", + "DirichletConvolve", + "DirichletDistribution", + "DirichletEta", + "DirichletL", + "DirichletLambda", + "DirichletTransform", + "DirichletWindow", + "DisableConsolePrintPacket", + "DisableFormatting", + "DiscreteAsymptotic", + "DiscreteChirpZTransform", + "DiscreteConvolve", + "DiscreteDelta", + "DiscreteHadamardTransform", + "DiscreteIndicator", + "DiscreteLimit", + "DiscreteLQEstimatorGains", + "DiscreteLQRegulatorGains", + "DiscreteLyapunovSolve", + "DiscreteMarkovProcess", + "DiscreteMaxLimit", + "DiscreteMinLimit", + "DiscretePlot", + "DiscretePlot3D", + "DiscreteRatio", + "DiscreteRiccatiSolve", + "DiscreteShift", + "DiscreteTimeModelQ", + "DiscreteUniformDistribution", + "DiscreteVariables", + "DiscreteWaveletData", + "DiscreteWaveletPacketTransform", + "DiscreteWaveletTransform", + "DiscretizeGraphics", + "DiscretizeRegion", + "Discriminant", + "DisjointQ", + "Disjunction", + "Disk", + "DiskBox", + "DiskMatrix", + "DiskSegment", + "Dispatch", + "DispatchQ", + "DispersionEstimatorFunction", + "Display", + "DisplayAllSteps", + "DisplayEndPacket", + "DisplayFlushImagePacket", + "DisplayForm", + "DisplayFunction", + "DisplayPacket", + "DisplayRules", + "DisplaySetSizePacket", + "DisplayString", + "DisplayTemporary", + "DisplayWith", + "DisplayWithRef", + "DisplayWithVariable", + "DistanceFunction", + "DistanceMatrix", + "DistanceTransform", + "Distribute", + "Distributed", + "DistributedContexts", + "DistributeDefinitions", + "DistributionChart", + "DistributionDomain", + "DistributionFitTest", + "DistributionParameterAssumptions", + "DistributionParameterQ", + "Dithering", + "Div", + "Divergence", + "Divide", + "DivideBy", + "Dividers", + "DivideSides", + "Divisible", + "Divisors", + "DivisorSigma", + "DivisorSum", + "DMSList", + "DMSString", + "Do", + "DockedCells", + "DocumentGenerator", + "DocumentGeneratorInformation", + "DocumentGeneratorInformationData", + "DocumentGenerators", + "DocumentNotebook", + "DocumentWeightingRules", + "Dodecahedron", + "DomainRegistrationInformation", + "DominantColors", + "DOSTextFormat", + "Dot", + "DotDashed", + "DotEqual", + "DotLayer", + "DotPlusLayer", + "Dotted", + "DoubleBracketingBar", + "DoubleContourIntegral", + "DoubleDownArrow", + "DoubleLeftArrow", + "DoubleLeftRightArrow", + "DoubleLeftTee", + "DoubleLongLeftArrow", + "DoubleLongLeftRightArrow", + "DoubleLongRightArrow", + "DoubleRightArrow", + "DoubleRightTee", + "DoubleUpArrow", + "DoubleUpDownArrow", + "DoubleVerticalBar", + "DoublyInfinite", + "Down", + "DownArrow", + "DownArrowBar", + "DownArrowUpArrow", + "DownLeftRightVector", + "DownLeftTeeVector", + "DownLeftVector", + "DownLeftVectorBar", + "DownRightTeeVector", + "DownRightVector", + "DownRightVectorBar", + "Downsample", + "DownTee", + "DownTeeArrow", + "DownValues", + "DragAndDrop", + "DrawEdges", + "DrawFrontFaces", + "DrawHighlighted", + "Drop", + "DropoutLayer", + "DSolve", + "DSolveValue", + "Dt", + "DualLinearProgramming", + "DualPolyhedron", + "DualSystemsModel", + "DumpGet", + "DumpSave", + "DuplicateFreeQ", + "Duration", + "Dynamic", + "DynamicBox", + "DynamicBoxOptions", + "DynamicEvaluationTimeout", + "DynamicGeoGraphics", + "DynamicImage", + "DynamicLocation", + "DynamicModule", + "DynamicModuleBox", + "DynamicModuleBoxOptions", + "DynamicModuleParent", + "DynamicModuleValues", + "DynamicName", + "DynamicNamespace", + "DynamicReference", + "DynamicSetting", + "DynamicUpdating", + "DynamicWrapper", + "DynamicWrapperBox", + "DynamicWrapperBoxOptions", + "E", + "EarthImpactData", + "EarthquakeData", + "EccentricityCentrality", + "Echo", + "EchoFunction", + "EclipseType", + "EdgeAdd", + "EdgeBetweennessCentrality", + "EdgeCapacity", + "EdgeCapForm", + "EdgeColor", + "EdgeConnectivity", + "EdgeContract", + "EdgeCost", + "EdgeCount", + "EdgeCoverQ", + "EdgeCycleMatrix", + "EdgeDashing", + "EdgeDelete", + "EdgeDetect", + "EdgeForm", + "EdgeIndex", + "EdgeJoinForm", + "EdgeLabeling", + "EdgeLabels", + "EdgeLabelStyle", + "EdgeList", + "EdgeOpacity", + "EdgeQ", + "EdgeRenderingFunction", + "EdgeRules", + "EdgeShapeFunction", + "EdgeStyle", + "EdgeTaggedGraph", + "EdgeTaggedGraphQ", + "EdgeTags", + "EdgeThickness", + "EdgeWeight", + "EdgeWeightedGraphQ", + "Editable", + "EditButtonSettings", + "EditCellTagsSettings", + "EditDistance", + "EffectiveInterest", + "Eigensystem", + "Eigenvalues", + "EigenvectorCentrality", + "Eigenvectors", + "Element", + "ElementData", + "ElementwiseLayer", + "ElidedForms", + "Eliminate", + "EliminationOrder", + "Ellipsoid", + "EllipticE", + "EllipticExp", + "EllipticExpPrime", + "EllipticF", + "EllipticFilterModel", + "EllipticK", + "EllipticLog", + "EllipticNomeQ", + "EllipticPi", + "EllipticReducedHalfPeriods", + "EllipticTheta", + "EllipticThetaPrime", + "EmbedCode", + "EmbeddedHTML", + "EmbeddedService", + "EmbeddingLayer", + "EmbeddingObject", + "EmitSound", + "EmphasizeSyntaxErrors", + "EmpiricalDistribution", + "Empty", + "EmptyGraphQ", + "EmptyRegion", + "EnableConsolePrintPacket", + "Enabled", + "Encode", + "Encrypt", + "EncryptedObject", + "EncryptFile", + "End", + "EndAdd", + "EndDialogPacket", + "EndFrontEndInteractionPacket", + "EndOfBuffer", + "EndOfFile", + "EndOfLine", + "EndOfString", + "EndPackage", + "EngineEnvironment", + "EngineeringForm", + "Enter", + "EnterExpressionPacket", + "EnterTextPacket", + "Entity", + "EntityClass", + "EntityClassList", + "EntityCopies", + "EntityFunction", + "EntityGroup", + "EntityInstance", + "EntityList", + "EntityPrefetch", + "EntityProperties", + "EntityProperty", + "EntityPropertyClass", + "EntityRegister", + "EntityStore", + "EntityStores", + "EntityTypeName", + "EntityUnregister", + "EntityValue", + "Entropy", + "EntropyFilter", + "Environment", + "Epilog", + "EpilogFunction", + "Equal", + "EqualColumns", + "EqualRows", + "EqualTilde", + "EqualTo", + "EquatedTo", + "Equilibrium", + "EquirippleFilterKernel", + "Equivalent", + "Erf", + "Erfc", + "Erfi", + "ErlangB", + "ErlangC", + "ErlangDistribution", + "Erosion", + "ErrorBox", + "ErrorBoxOptions", + "ErrorNorm", + "ErrorPacket", + "ErrorsDialogSettings", + "EscapeRadius", + "EstimatedBackground", + "EstimatedDistribution", + "EstimatedProcess", + "EstimatorGains", + "EstimatorRegulator", + "EuclideanDistance", + "EulerAngles", + "EulerCharacteristic", + "EulerE", + "EulerGamma", + "EulerianGraphQ", + "EulerMatrix", + "EulerPhi", + "Evaluatable", + "Evaluate", + "Evaluated", + "EvaluatePacket", + "EvaluateScheduledTask", + "EvaluationBox", + "EvaluationCell", + "EvaluationCompletionAction", + "EvaluationData", + "EvaluationElements", + "EvaluationEnvironment", + "EvaluationMode", + "EvaluationMonitor", + "EvaluationNotebook", + "EvaluationObject", + "EvaluationOrder", + "Evaluator", + "EvaluatorNames", + "EvenQ", + "EventData", + "EventEvaluator", + "EventHandler", + "EventHandlerTag", + "EventLabels", + "EventSeries", + "ExactBlackmanWindow", + "ExactNumberQ", + "ExactRootIsolation", + "ExampleData", + "Except", + "ExcludedForms", + "ExcludedLines", + "ExcludedPhysicalQuantities", + "ExcludePods", + "Exclusions", + "ExclusionsStyle", + "Exists", + "Exit", + "ExitDialog", + "ExoplanetData", + "Exp", + "Expand", + "ExpandAll", + "ExpandDenominator", + "ExpandFileName", + "ExpandNumerator", + "Expectation", + "ExpectationE", + "ExpectedValue", + "ExpGammaDistribution", + "ExpIntegralE", + "ExpIntegralEi", + "ExpirationDate", + "Exponent", + "ExponentFunction", + "ExponentialDistribution", + "ExponentialFamily", + "ExponentialGeneratingFunction", + "ExponentialMovingAverage", + "ExponentialPowerDistribution", + "ExponentPosition", + "ExponentStep", + "Export", + "ExportAutoReplacements", + "ExportByteArray", + "ExportForm", + "ExportPacket", + "ExportString", + "Expression", + "ExpressionCell", + "ExpressionGraph", + "ExpressionPacket", + "ExpressionUUID", + "ExpToTrig", + "ExtendedEntityClass", + "ExtendedGCD", + "Extension", + "ExtentElementFunction", + "ExtentMarkers", + "ExtentSize", + "ExternalBundle", + "ExternalCall", + "ExternalDataCharacterEncoding", + "ExternalEvaluate", + "ExternalFunction", + "ExternalFunctionName", + "ExternalIdentifier", + "ExternalObject", + "ExternalOptions", + "ExternalSessionObject", + "ExternalSessions", + "ExternalStorageBase", + "ExternalStorageDownload", + "ExternalStorageGet", + "ExternalStorageObject", + "ExternalStoragePut", + "ExternalStorageUpload", + "ExternalTypeSignature", + "ExternalValue", + "Extract", + "ExtractArchive", + "ExtractLayer", + "ExtractPacletArchive", + "ExtremeValueDistribution", + "FaceAlign", + "FaceForm", + "FaceGrids", + "FaceGridsStyle", + "FacialFeatures", + "Factor", + "FactorComplete", + "Factorial", + "Factorial2", + "FactorialMoment", + "FactorialMomentGeneratingFunction", + "FactorialPower", + "FactorInteger", + "FactorList", + "FactorSquareFree", + "FactorSquareFreeList", + "FactorTerms", + "FactorTermsList", + "Fail", + "Failure", + "FailureAction", + "FailureDistribution", + "FailureQ", + "False", + "FareySequence", + "FARIMAProcess", + "FeatureDistance", + "FeatureExtract", + "FeatureExtraction", + "FeatureExtractor", + "FeatureExtractorFunction", + "FeatureNames", + "FeatureNearest", + "FeatureSpacePlot", + "FeatureSpacePlot3D", + "FeatureTypes", + "FEDisableConsolePrintPacket", + "FeedbackLinearize", + "FeedbackSector", + "FeedbackSectorStyle", + "FeedbackType", + "FEEnableConsolePrintPacket", + "FetalGrowthData", + "Fibonacci", + "Fibonorial", + "FieldCompletionFunction", + "FieldHint", + "FieldHintStyle", + "FieldMasked", + "FieldSize", + "File", + "FileBaseName", + "FileByteCount", + "FileConvert", + "FileDate", + "FileExistsQ", + "FileExtension", + "FileFormat", + "FileHandler", + "FileHash", + "FileInformation", + "FileName", + "FileNameDepth", + "FileNameDialogSettings", + "FileNameDrop", + "FileNameForms", + "FileNameJoin", + "FileNames", + "FileNameSetter", + "FileNameSplit", + "FileNameTake", + "FilePrint", + "FileSize", + "FileSystemMap", + "FileSystemScan", + "FileTemplate", + "FileTemplateApply", + "FileType", + "FilledCurve", + "FilledCurveBox", + "FilledCurveBoxOptions", + "Filling", + "FillingStyle", + "FillingTransform", + "FilteredEntityClass", + "FilterRules", + "FinancialBond", + "FinancialData", + "FinancialDerivative", + "FinancialIndicator", + "Find", + "FindAnomalies", + "FindArgMax", + "FindArgMin", + "FindChannels", + "FindClique", + "FindClusters", + "FindCookies", + "FindCurvePath", + "FindCycle", + "FindDevices", + "FindDistribution", + "FindDistributionParameters", + "FindDivisions", + "FindEdgeCover", + "FindEdgeCut", + "FindEdgeIndependentPaths", + "FindEquationalProof", + "FindEulerianCycle", + "FindExternalEvaluators", + "FindFaces", + "FindFile", + "FindFit", + "FindFormula", + "FindFundamentalCycles", + "FindGeneratingFunction", + "FindGeoLocation", + "FindGeometricConjectures", + "FindGeometricTransform", + "FindGraphCommunities", + "FindGraphIsomorphism", + "FindGraphPartition", + "FindHamiltonianCycle", + "FindHamiltonianPath", + "FindHiddenMarkovStates", + "FindImageText", + "FindIndependentEdgeSet", + "FindIndependentVertexSet", + "FindInstance", + "FindIntegerNullVector", + "FindKClan", + "FindKClique", + "FindKClub", + "FindKPlex", + "FindLibrary", + "FindLinearRecurrence", + "FindList", + "FindMatchingColor", + "FindMaximum", + "FindMaximumCut", + "FindMaximumFlow", + "FindMaxValue", + "FindMeshDefects", + "FindMinimum", + "FindMinimumCostFlow", + "FindMinimumCut", + "FindMinValue", + "FindMoleculeSubstructure", + "FindPath", + "FindPeaks", + "FindPermutation", + "FindPostmanTour", + "FindProcessParameters", + "FindRepeat", + "FindRoot", + "FindSequenceFunction", + "FindSettings", + "FindShortestPath", + "FindShortestTour", + "FindSpanningTree", + "FindSystemModelEquilibrium", + "FindTextualAnswer", + "FindThreshold", + "FindTransientRepeat", + "FindVertexCover", + "FindVertexCut", + "FindVertexIndependentPaths", + "Fine", + "FinishDynamic", + "FiniteAbelianGroupCount", + "FiniteGroupCount", + "FiniteGroupData", + "First", + "FirstCase", + "FirstPassageTimeDistribution", + "FirstPosition", + "FischerGroupFi22", + "FischerGroupFi23", + "FischerGroupFi24Prime", + "FisherHypergeometricDistribution", + "FisherRatioTest", + "FisherZDistribution", + "Fit", + "FitAll", + "FitRegularization", + "FittedModel", + "FixedOrder", + "FixedPoint", + "FixedPointList", + "FlashSelection", + "Flat", + "Flatten", + "FlattenAt", + "FlattenLayer", + "FlatTopWindow", + "FlipView", + "Floor", + "FlowPolynomial", + "FlushPrintOutputPacket", + "Fold", + "FoldList", + "FoldPair", + "FoldPairList", + "FollowRedirects", + "Font", + "FontColor", + "FontFamily", + "FontForm", + "FontName", + "FontOpacity", + "FontPostScriptName", + "FontProperties", + "FontReencoding", + "FontSize", + "FontSlant", + "FontSubstitutions", + "FontTracking", + "FontVariations", + "FontWeight", + "For", + "ForAll", + "ForceVersionInstall", + "Format", + "FormatRules", + "FormatType", + "FormatTypeAutoConvert", + "FormatValues", + "FormBox", + "FormBoxOptions", + "FormControl", + "FormFunction", + "FormLayoutFunction", + "FormObject", + "FormPage", + "FormTheme", + "FormulaData", + "FormulaLookup", + "FortranForm", + "Forward", + "ForwardBackward", + "Fourier", + "FourierCoefficient", + "FourierCosCoefficient", + "FourierCosSeries", + "FourierCosTransform", + "FourierDCT", + "FourierDCTFilter", + "FourierDCTMatrix", + "FourierDST", + "FourierDSTMatrix", + "FourierMatrix", + "FourierParameters", + "FourierSequenceTransform", + "FourierSeries", + "FourierSinCoefficient", + "FourierSinSeries", + "FourierSinTransform", + "FourierTransform", + "FourierTrigSeries", + "FractionalBrownianMotionProcess", + "FractionalGaussianNoiseProcess", + "FractionalPart", + "FractionBox", + "FractionBoxOptions", + "FractionLine", + "Frame", + "FrameBox", + "FrameBoxOptions", + "Framed", + "FrameInset", + "FrameLabel", + "Frameless", + "FrameMargins", + "FrameRate", + "FrameStyle", + "FrameTicks", + "FrameTicksStyle", + "FRatioDistribution", + "FrechetDistribution", + "FreeQ", + "FrenetSerretSystem", + "FrequencySamplingFilterKernel", + "FresnelC", + "FresnelF", + "FresnelG", + "FresnelS", + "Friday", + "FrobeniusNumber", + "FrobeniusSolve", + "FromAbsoluteTime", + "FromCharacterCode", + "FromCoefficientRules", + "FromContinuedFraction", + "FromDate", + "FromDigits", + "FromDMS", + "FromEntity", + "FromJulianDate", + "FromLetterNumber", + "FromPolarCoordinates", + "FromRomanNumeral", + "FromSphericalCoordinates", + "FromUnixTime", + "Front", + "FrontEndDynamicExpression", + "FrontEndEventActions", + "FrontEndExecute", + "FrontEndObject", + "FrontEndResource", + "FrontEndResourceString", + "FrontEndStackSize", + "FrontEndToken", + "FrontEndTokenExecute", + "FrontEndValueCache", + "FrontEndVersion", + "FrontFaceColor", + "FrontFaceOpacity", + "Full", + "FullAxes", + "FullDefinition", + "FullForm", + "FullGraphics", + "FullInformationOutputRegulator", + "FullOptions", + "FullRegion", + "FullSimplify", + "Function", + "FunctionCompile", + "FunctionCompileExport", + "FunctionCompileExportByteArray", + "FunctionCompileExportLibrary", + "FunctionCompileExportString", + "FunctionDomain", + "FunctionExpand", + "FunctionInterpolation", + "FunctionPeriod", + "FunctionRange", + "FunctionSpace", + "FussellVeselyImportance", + "GaborFilter", + "GaborMatrix", + "GaborWavelet", + "GainMargins", + "GainPhaseMargins", + "GalaxyData", + "GalleryView", + "Gamma", + "GammaDistribution", + "GammaRegularized", + "GapPenalty", + "GARCHProcess", + "GatedRecurrentLayer", + "Gather", + "GatherBy", + "GaugeFaceElementFunction", + "GaugeFaceStyle", + "GaugeFrameElementFunction", + "GaugeFrameSize", + "GaugeFrameStyle", + "GaugeLabels", + "GaugeMarkers", + "GaugeStyle", + "GaussianFilter", + "GaussianIntegers", + "GaussianMatrix", + "GaussianOrthogonalMatrixDistribution", + "GaussianSymplecticMatrixDistribution", + "GaussianUnitaryMatrixDistribution", + "GaussianWindow", + "GCD", + "GegenbauerC", + "General", + "GeneralizedLinearModelFit", + "GenerateAsymmetricKeyPair", + "GenerateConditions", + "GeneratedCell", + "GeneratedDocumentBinding", + "GenerateDerivedKey", + "GenerateDigitalSignature", + "GenerateDocument", + "GeneratedParameters", + "GeneratedQuantityMagnitudes", + "GenerateFileSignature", + "GenerateHTTPResponse", + "GenerateSecuredAuthenticationKey", + "GenerateSymmetricKey", + "GeneratingFunction", + "GeneratorDescription", + "GeneratorHistoryLength", + "GeneratorOutputType", + "Generic", + "GenericCylindricalDecomposition", + "GenomeData", + "GenomeLookup", + "GeoAntipode", + "GeoArea", + "GeoArraySize", + "GeoBackground", + "GeoBoundingBox", + "GeoBounds", + "GeoBoundsRegion", + "GeoBubbleChart", + "GeoCenter", + "GeoCircle", + "GeoContourPlot", + "GeoDensityPlot", + "GeodesicClosing", + "GeodesicDilation", + "GeodesicErosion", + "GeodesicOpening", + "GeoDestination", + "GeodesyData", + "GeoDirection", + "GeoDisk", + "GeoDisplacement", + "GeoDistance", + "GeoDistanceList", + "GeoElevationData", + "GeoEntities", + "GeoGraphics", + "GeogravityModelData", + "GeoGridDirectionDifference", + "GeoGridLines", + "GeoGridLinesStyle", + "GeoGridPosition", + "GeoGridRange", + "GeoGridRangePadding", + "GeoGridUnitArea", + "GeoGridUnitDistance", + "GeoGridVector", + "GeoGroup", + "GeoHemisphere", + "GeoHemisphereBoundary", + "GeoHistogram", + "GeoIdentify", + "GeoImage", + "GeoLabels", + "GeoLength", + "GeoListPlot", + "GeoLocation", + "GeologicalPeriodData", + "GeomagneticModelData", + "GeoMarker", + "GeometricAssertion", + "GeometricBrownianMotionProcess", + "GeometricDistribution", + "GeometricMean", + "GeometricMeanFilter", + "GeometricOptimization", + "GeometricScene", + "GeometricTransformation", + "GeometricTransformation3DBox", + "GeometricTransformation3DBoxOptions", + "GeometricTransformationBox", + "GeometricTransformationBoxOptions", + "GeoModel", + "GeoNearest", + "GeoPath", + "GeoPosition", + "GeoPositionENU", + "GeoPositionXYZ", + "GeoProjection", + "GeoProjectionData", + "GeoRange", + "GeoRangePadding", + "GeoRegionValuePlot", + "GeoResolution", + "GeoScaleBar", + "GeoServer", + "GeoSmoothHistogram", + "GeoStreamPlot", + "GeoStyling", + "GeoStylingImageFunction", + "GeoVariant", + "GeoVector", + "GeoVectorENU", + "GeoVectorPlot", + "GeoVectorXYZ", + "GeoVisibleRegion", + "GeoVisibleRegionBoundary", + "GeoWithinQ", + "GeoZoomLevel", + "GestureHandler", + "GestureHandlerTag", + "Get", + "GetBoundingBoxSizePacket", + "GetContext", + "GetEnvironment", + "GetFileName", + "GetFrontEndOptionsDataPacket", + "GetLinebreakInformationPacket", + "GetMenusPacket", + "GetPageBreakInformationPacket", + "Glaisher", + "GlobalClusteringCoefficient", + "GlobalPreferences", + "GlobalSession", + "Glow", + "GoldenAngle", + "GoldenRatio", + "GompertzMakehamDistribution", + "GoochShading", + "GoodmanKruskalGamma", + "GoodmanKruskalGammaTest", + "Goto", + "Grad", + "Gradient", + "GradientFilter", + "GradientOrientationFilter", + "GrammarApply", + "GrammarRules", + "GrammarToken", + "Graph", + "Graph3D", + "GraphAssortativity", + "GraphAutomorphismGroup", + "GraphCenter", + "GraphComplement", + "GraphData", + "GraphDensity", + "GraphDiameter", + "GraphDifference", + "GraphDisjointUnion", + "GraphDistance", + "GraphDistanceMatrix", + "GraphElementData", + "GraphEmbedding", + "GraphHighlight", + "GraphHighlightStyle", + "GraphHub", + "Graphics", + "Graphics3D", + "Graphics3DBox", + "Graphics3DBoxOptions", + "GraphicsArray", + "GraphicsBaseline", + "GraphicsBox", + "GraphicsBoxOptions", + "GraphicsColor", + "GraphicsColumn", + "GraphicsComplex", + "GraphicsComplex3DBox", + "GraphicsComplex3DBoxOptions", + "GraphicsComplexBox", + "GraphicsComplexBoxOptions", + "GraphicsContents", + "GraphicsData", + "GraphicsGrid", + "GraphicsGridBox", + "GraphicsGroup", + "GraphicsGroup3DBox", + "GraphicsGroup3DBoxOptions", + "GraphicsGroupBox", + "GraphicsGroupBoxOptions", + "GraphicsGrouping", + "GraphicsHighlightColor", + "GraphicsRow", + "GraphicsSpacing", + "GraphicsStyle", + "GraphIntersection", + "GraphLayout", + "GraphLinkEfficiency", + "GraphPeriphery", + "GraphPlot", + "GraphPlot3D", + "GraphPower", + "GraphPropertyDistribution", + "GraphQ", + "GraphRadius", + "GraphReciprocity", + "GraphRoot", + "GraphStyle", + "GraphUnion", + "Gray", + "GrayLevel", + "Greater", + "GreaterEqual", + "GreaterEqualLess", + "GreaterEqualThan", + "GreaterFullEqual", + "GreaterGreater", + "GreaterLess", + "GreaterSlantEqual", + "GreaterThan", + "GreaterTilde", + "Green", + "GreenFunction", + "Grid", + "GridBaseline", + "GridBox", + "GridBoxAlignment", + "GridBoxBackground", + "GridBoxDividers", + "GridBoxFrame", + "GridBoxItemSize", + "GridBoxItemStyle", + "GridBoxOptions", + "GridBoxSpacings", + "GridCreationSettings", + "GridDefaultElement", + "GridElementStyleOptions", + "GridFrame", + "GridFrameMargins", + "GridGraph", + "GridLines", + "GridLinesStyle", + "GroebnerBasis", + "GroupActionBase", + "GroupBy", + "GroupCentralizer", + "GroupElementFromWord", + "GroupElementPosition", + "GroupElementQ", + "GroupElements", + "GroupElementToWord", + "GroupGenerators", + "Groupings", + "GroupMultiplicationTable", + "GroupOrbits", + "GroupOrder", + "GroupPageBreakWithin", + "GroupSetwiseStabilizer", + "GroupStabilizer", + "GroupStabilizerChain", + "GroupTogetherGrouping", + "GroupTogetherNestedGrouping", + "GrowCutComponents", + "Gudermannian", + "GuidedFilter", + "GumbelDistribution", + "HaarWavelet", + "HadamardMatrix", + "HalfLine", + "HalfNormalDistribution", + "HalfPlane", + "HalfSpace", + "HalftoneShading", + "HamiltonianGraphQ", + "HammingDistance", + "HammingWindow", + "HandlerFunctions", + "HandlerFunctionsKeys", + "HankelH1", + "HankelH2", + "HankelMatrix", + "HankelTransform", + "HannPoissonWindow", + "HannWindow", + "HaradaNortonGroupHN", + "HararyGraph", + "HarmonicMean", + "HarmonicMeanFilter", + "HarmonicNumber", + "Hash", + "HatchFilling", + "HatchShading", + "Haversine", + "HazardFunction", + "Head", + "HeadCompose", + "HeaderAlignment", + "HeaderBackground", + "HeaderDisplayFunction", + "HeaderLines", + "HeaderSize", + "HeaderStyle", + "Heads", + "HeavisideLambda", + "HeavisidePi", + "HeavisideTheta", + "HeldGroupHe", + "HeldPart", + "HelpBrowserLookup", + "HelpBrowserNotebook", + "HelpBrowserSettings", + "Here", + "HermiteDecomposition", + "HermiteH", + "HermitianMatrixQ", + "HessenbergDecomposition", + "Hessian", + "HeunB", + "HeunBPrime", + "HeunC", + "HeunCPrime", + "HeunD", + "HeunDPrime", + "HeunG", + "HeunGPrime", + "HeunT", + "HeunTPrime", + "HexadecimalCharacter", + "Hexahedron", + "HexahedronBox", + "HexahedronBoxOptions", + "HiddenItems", + "HiddenMarkovProcess", + "HiddenSurface", + "Highlighted", + "HighlightGraph", + "HighlightImage", + "HighlightMesh", + "HighpassFilter", + "HigmanSimsGroupHS", + "HilbertCurve", + "HilbertFilter", + "HilbertMatrix", + "Histogram", + "Histogram3D", + "HistogramDistribution", + "HistogramList", + "HistogramTransform", + "HistogramTransformInterpolation", + "HistoricalPeriodData", + "HitMissTransform", + "HITSCentrality", + "HjorthDistribution", + "HodgeDual", + "HoeffdingD", + "HoeffdingDTest", + "Hold", + "HoldAll", + "HoldAllComplete", + "HoldComplete", + "HoldFirst", + "HoldForm", + "HoldPattern", + "HoldRest", + "HolidayCalendar", + "HomeDirectory", + "HomePage", + "Horizontal", + "HorizontalForm", + "HorizontalGauge", + "HorizontalScrollPosition", + "HornerForm", + "HostLookup", + "HotellingTSquareDistribution", + "HoytDistribution", + "HTMLSave", + "HTTPErrorResponse", + "HTTPRedirect", + "HTTPRequest", + "HTTPRequestData", + "HTTPResponse", + "Hue", + "HumanGrowthData", + "HumpDownHump", + "HumpEqual", + "HurwitzLerchPhi", + "HurwitzZeta", + "HyperbolicDistribution", + "HypercubeGraph", + "HyperexponentialDistribution", + "Hyperfactorial", + "Hypergeometric0F1", + "Hypergeometric0F1Regularized", + "Hypergeometric1F1", + "Hypergeometric1F1Regularized", + "Hypergeometric2F1", + "Hypergeometric2F1Regularized", + "HypergeometricDistribution", + "HypergeometricPFQ", + "HypergeometricPFQRegularized", + "HypergeometricU", + "Hyperlink", + "HyperlinkAction", + "HyperlinkCreationSettings", + "Hyperplane", + "Hyphenation", + "HyphenationOptions", + "HypoexponentialDistribution", + "HypothesisTestData", + "I", + "IconData", + "Iconize", + "IconizedObject", + "IconRules", + "Icosahedron", + "Identity", + "IdentityMatrix", + "If", + "IgnoreCase", + "IgnoreDiacritics", + "IgnorePunctuation", + "IgnoreSpellCheck", + "IgnoringInactive", + "Im", + "Image", + "Image3D", + "Image3DProjection", + "Image3DSlices", + "ImageAccumulate", + "ImageAdd", + "ImageAdjust", + "ImageAlign", + "ImageApply", + "ImageApplyIndexed", + "ImageAspectRatio", + "ImageAssemble", + "ImageAugmentationLayer", + "ImageBoundingBoxes", + "ImageCache", + "ImageCacheValid", + "ImageCapture", + "ImageCaptureFunction", + "ImageCases", + "ImageChannels", + "ImageClip", + "ImageCollage", + "ImageColorSpace", + "ImageCompose", + "ImageContainsQ", + "ImageContents", + "ImageConvolve", + "ImageCooccurrence", + "ImageCorners", + "ImageCorrelate", + "ImageCorrespondingPoints", + "ImageCrop", + "ImageData", + "ImageDeconvolve", + "ImageDemosaic", + "ImageDifference", + "ImageDimensions", + "ImageDisplacements", + "ImageDistance", + "ImageEffect", + "ImageExposureCombine", + "ImageFeatureTrack", + "ImageFileApply", + "ImageFileFilter", + "ImageFileScan", + "ImageFilter", + "ImageFocusCombine", + "ImageForestingComponents", + "ImageFormattingWidth", + "ImageForwardTransformation", + "ImageGraphics", + "ImageHistogram", + "ImageIdentify", + "ImageInstanceQ", + "ImageKeypoints", + "ImageLabels", + "ImageLegends", + "ImageLevels", + "ImageLines", + "ImageMargins", + "ImageMarker", + "ImageMarkers", + "ImageMeasurements", + "ImageMesh", + "ImageMultiply", + "ImageOffset", + "ImagePad", + "ImagePadding", + "ImagePartition", + "ImagePeriodogram", + "ImagePerspectiveTransformation", + "ImagePosition", + "ImagePreviewFunction", + "ImagePyramid", + "ImagePyramidApply", + "ImageQ", + "ImageRangeCache", + "ImageRecolor", + "ImageReflect", + "ImageRegion", + "ImageResize", + "ImageResolution", + "ImageRestyle", + "ImageRotate", + "ImageRotated", + "ImageSaliencyFilter", + "ImageScaled", + "ImageScan", + "ImageSize", + "ImageSizeAction", + "ImageSizeCache", + "ImageSizeMultipliers", + "ImageSizeRaw", + "ImageSubtract", + "ImageTake", + "ImageTransformation", + "ImageTrim", + "ImageType", + "ImageValue", + "ImageValuePositions", + "ImagingDevice", + "ImplicitRegion", + "Implies", + "Import", + "ImportAutoReplacements", + "ImportByteArray", + "ImportOptions", + "ImportString", + "ImprovementImportance", + "In", + "Inactivate", + "Inactive", + "IncidenceGraph", + "IncidenceList", + "IncidenceMatrix", + "IncludeAromaticBonds", + "IncludeConstantBasis", + "IncludeDefinitions", + "IncludeDirectories", + "IncludeFileExtension", + "IncludeGeneratorTasks", + "IncludeHydrogens", + "IncludeInflections", + "IncludeMetaInformation", + "IncludePods", + "IncludeQuantities", + "IncludeRelatedTables", + "IncludeSingularTerm", + "IncludeWindowTimes", + "Increment", + "IndefiniteMatrixQ", + "Indent", + "IndentingNewlineSpacings", + "IndentMaxFraction", + "IndependenceTest", + "IndependentEdgeSetQ", + "IndependentPhysicalQuantity", + "IndependentUnit", + "IndependentUnitDimension", + "IndependentVertexSetQ", + "Indeterminate", + "IndeterminateThreshold", + "IndexCreationOptions", + "Indexed", + "IndexEdgeTaggedGraph", + "IndexGraph", + "IndexTag", + "Inequality", + "InexactNumberQ", + "InexactNumbers", + "InfiniteFuture", + "InfiniteLine", + "InfinitePast", + "InfinitePlane", + "Infinity", + "Infix", + "InflationAdjust", + "InflationMethod", + "Information", + "InformationData", + "InformationDataGrid", + "Inherited", + "InheritScope", + "InhomogeneousPoissonProcess", + "InitialEvaluationHistory", + "Initialization", + "InitializationCell", + "InitializationCellEvaluation", + "InitializationCellWarning", + "InitializationObjects", + "InitializationValue", + "Initialize", + "InitialSeeding", + "InlineCounterAssignments", + "InlineCounterIncrements", + "InlineRules", + "Inner", + "InnerPolygon", + "InnerPolyhedron", + "Inpaint", + "Input", + "InputAliases", + "InputAssumptions", + "InputAutoReplacements", + "InputField", + "InputFieldBox", + "InputFieldBoxOptions", + "InputForm", + "InputGrouping", + "InputNamePacket", + "InputNotebook", + "InputPacket", + "InputSettings", + "InputStream", + "InputString", + "InputStringPacket", + "InputToBoxFormPacket", + "Insert", + "InsertionFunction", + "InsertionPointObject", + "InsertLinebreaks", + "InsertResults", + "Inset", + "Inset3DBox", + "Inset3DBoxOptions", + "InsetBox", + "InsetBoxOptions", + "Insphere", + "Install", + "InstallService", + "InstanceNormalizationLayer", + "InString", + "Integer", + "IntegerDigits", + "IntegerExponent", + "IntegerLength", + "IntegerName", + "IntegerPart", + "IntegerPartitions", + "IntegerQ", + "IntegerReverse", + "Integers", + "IntegerString", + "Integral", + "Integrate", + "Interactive", + "InteractiveTradingChart", + "Interlaced", + "Interleaving", + "InternallyBalancedDecomposition", + "InterpolatingFunction", + "InterpolatingPolynomial", + "Interpolation", + "InterpolationOrder", + "InterpolationPoints", + "InterpolationPrecision", + "Interpretation", + "InterpretationBox", + "InterpretationBoxOptions", + "InterpretationFunction", + "Interpreter", + "InterpretTemplate", + "InterquartileRange", + "Interrupt", + "InterruptSettings", + "IntersectedEntityClass", + "IntersectingQ", + "Intersection", + "Interval", + "IntervalIntersection", + "IntervalMarkers", + "IntervalMarkersStyle", + "IntervalMemberQ", + "IntervalSlider", + "IntervalUnion", + "Into", + "Inverse", + "InverseBetaRegularized", + "InverseCDF", + "InverseChiSquareDistribution", + "InverseContinuousWaveletTransform", + "InverseDistanceTransform", + "InverseEllipticNomeQ", + "InverseErf", + "InverseErfc", + "InverseFourier", + "InverseFourierCosTransform", + "InverseFourierSequenceTransform", + "InverseFourierSinTransform", + "InverseFourierTransform", + "InverseFunction", + "InverseFunctions", + "InverseGammaDistribution", + "InverseGammaRegularized", + "InverseGaussianDistribution", + "InverseGudermannian", + "InverseHankelTransform", + "InverseHaversine", + "InverseImagePyramid", + "InverseJacobiCD", + "InverseJacobiCN", + "InverseJacobiCS", + "InverseJacobiDC", + "InverseJacobiDN", + "InverseJacobiDS", + "InverseJacobiNC", + "InverseJacobiND", + "InverseJacobiNS", + "InverseJacobiSC", + "InverseJacobiSD", + "InverseJacobiSN", + "InverseLaplaceTransform", + "InverseMellinTransform", + "InversePermutation", + "InverseRadon", + "InverseRadonTransform", + "InverseSeries", + "InverseShortTimeFourier", + "InverseSpectrogram", + "InverseSurvivalFunction", + "InverseTransformedRegion", + "InverseWaveletTransform", + "InverseWeierstrassP", + "InverseWishartMatrixDistribution", + "InverseZTransform", + "Invisible", + "InvisibleApplication", + "InvisibleTimes", + "IPAddress", + "IrreduciblePolynomialQ", + "IslandData", + "IsolatingInterval", + "IsomorphicGraphQ", + "IsotopeData", + "Italic", + "Item", + "ItemAspectRatio", + "ItemBox", + "ItemBoxOptions", + "ItemDisplayFunction", + "ItemSize", + "ItemStyle", + "ItoProcess", + "JaccardDissimilarity", + "JacobiAmplitude", + "Jacobian", + "JacobiCD", + "JacobiCN", + "JacobiCS", + "JacobiDC", + "JacobiDN", + "JacobiDS", + "JacobiNC", + "JacobiND", + "JacobiNS", + "JacobiP", + "JacobiSC", + "JacobiSD", + "JacobiSN", + "JacobiSymbol", + "JacobiZeta", + "JankoGroupJ1", + "JankoGroupJ2", + "JankoGroupJ3", + "JankoGroupJ4", + "JarqueBeraALMTest", + "JohnsonDistribution", + "Join", + "JoinAcross", + "Joined", + "JoinedCurve", + "JoinedCurveBox", + "JoinedCurveBoxOptions", + "JoinForm", + "JordanDecomposition", + "JordanModelDecomposition", + "JulianDate", + "JuliaSetBoettcher", + "JuliaSetIterationCount", + "JuliaSetPlot", + "JuliaSetPoints", + "K", + "KagiChart", + "KaiserBesselWindow", + "KaiserWindow", + "KalmanEstimator", + "KalmanFilter", + "KarhunenLoeveDecomposition", + "KaryTree", + "KatzCentrality", + "KCoreComponents", + "KDistribution", + "KEdgeConnectedComponents", + "KEdgeConnectedGraphQ", + "KeepExistingVersion", + "KelvinBei", + "KelvinBer", + "KelvinKei", + "KelvinKer", + "KendallTau", + "KendallTauTest", + "KernelExecute", + "KernelFunction", + "KernelMixtureDistribution", + "KernelObject", + "Kernels", + "Ket", + "Key", + "KeyCollisionFunction", + "KeyComplement", + "KeyDrop", + "KeyDropFrom", + "KeyExistsQ", + "KeyFreeQ", + "KeyIntersection", + "KeyMap", + "KeyMemberQ", + "KeypointStrength", + "Keys", + "KeySelect", + "KeySort", + "KeySortBy", + "KeyTake", + "KeyUnion", + "KeyValueMap", + "KeyValuePattern", + "Khinchin", + "KillProcess", + "KirchhoffGraph", + "KirchhoffMatrix", + "KleinInvariantJ", + "KnapsackSolve", + "KnightTourGraph", + "KnotData", + "KnownUnitQ", + "KochCurve", + "KolmogorovSmirnovTest", + "KroneckerDelta", + "KroneckerModelDecomposition", + "KroneckerProduct", + "KroneckerSymbol", + "KuiperTest", + "KumaraswamyDistribution", + "Kurtosis", + "KuwaharaFilter", + "KVertexConnectedComponents", + "KVertexConnectedGraphQ", + "LABColor", + "Label", + "Labeled", + "LabeledSlider", + "LabelingFunction", + "LabelingSize", + "LabelStyle", + "LabelVisibility", + "LaguerreL", + "LakeData", + "LambdaComponents", + "LambertW", + "LaminaData", + "LanczosWindow", + "LandauDistribution", + "Language", + "LanguageCategory", + "LanguageData", + "LanguageIdentify", + "LanguageOptions", + "LaplaceDistribution", + "LaplaceTransform", + "Laplacian", + "LaplacianFilter", + "LaplacianGaussianFilter", + "Large", + "Larger", + "Last", + "Latitude", + "LatitudeLongitude", + "LatticeData", + "LatticeReduce", + "Launch", + "LaunchKernels", + "LayeredGraphPlot", + "LayerSizeFunction", + "LayoutInformation", + "LCHColor", + "LCM", + "LeaderSize", + "LeafCount", + "LeapYearQ", + "LearnDistribution", + "LearnedDistribution", + "LearningRate", + "LearningRateMultipliers", + "LeastSquares", + "LeastSquaresFilterKernel", + "Left", + "LeftArrow", + "LeftArrowBar", + "LeftArrowRightArrow", + "LeftDownTeeVector", + "LeftDownVector", + "LeftDownVectorBar", + "LeftRightArrow", + "LeftRightVector", + "LeftTee", + "LeftTeeArrow", + "LeftTeeVector", + "LeftTriangle", + "LeftTriangleBar", + "LeftTriangleEqual", + "LeftUpDownVector", + "LeftUpTeeVector", + "LeftUpVector", + "LeftUpVectorBar", + "LeftVector", + "LeftVectorBar", + "LegendAppearance", + "Legended", + "LegendFunction", + "LegendLabel", + "LegendLayout", + "LegendMargins", + "LegendMarkers", + "LegendMarkerSize", + "LegendreP", + "LegendreQ", + "LegendreType", + "Length", + "LengthWhile", + "LerchPhi", + "Less", + "LessEqual", + "LessEqualGreater", + "LessEqualThan", + "LessFullEqual", + "LessGreater", + "LessLess", + "LessSlantEqual", + "LessThan", + "LessTilde", + "LetterCharacter", + "LetterCounts", + "LetterNumber", + "LetterQ", + "Level", + "LeveneTest", + "LeviCivitaTensor", + "LevyDistribution", + "Lexicographic", + "LibraryDataType", + "LibraryFunction", + "LibraryFunctionError", + "LibraryFunctionInformation", + "LibraryFunctionLoad", + "LibraryFunctionUnload", + "LibraryLoad", + "LibraryUnload", + "LicenseID", + "LiftingFilterData", + "LiftingWaveletTransform", + "LightBlue", + "LightBrown", + "LightCyan", + "Lighter", + "LightGray", + "LightGreen", + "Lighting", + "LightingAngle", + "LightMagenta", + "LightOrange", + "LightPink", + "LightPurple", + "LightRed", + "LightSources", + "LightYellow", + "Likelihood", + "Limit", + "LimitsPositioning", + "LimitsPositioningTokens", + "LindleyDistribution", + "Line", + "Line3DBox", + "Line3DBoxOptions", + "LinearFilter", + "LinearFractionalOptimization", + "LinearFractionalTransform", + "LinearGradientImage", + "LinearizingTransformationData", + "LinearLayer", + "LinearModelFit", + "LinearOffsetFunction", + "LinearOptimization", + "LinearProgramming", + "LinearRecurrence", + "LinearSolve", + "LinearSolveFunction", + "LineBox", + "LineBoxOptions", + "LineBreak", + "LinebreakAdjustments", + "LineBreakChart", + "LinebreakSemicolonWeighting", + "LineBreakWithin", + "LineColor", + "LineGraph", + "LineIndent", + "LineIndentMaxFraction", + "LineIntegralConvolutionPlot", + "LineIntegralConvolutionScale", + "LineLegend", + "LineOpacity", + "LineSpacing", + "LineWrapParts", + "LinkActivate", + "LinkClose", + "LinkConnect", + "LinkConnectedQ", + "LinkCreate", + "LinkError", + "LinkFlush", + "LinkFunction", + "LinkHost", + "LinkInterrupt", + "LinkLaunch", + "LinkMode", + "LinkObject", + "LinkOpen", + "LinkOptions", + "LinkPatterns", + "LinkProtocol", + "LinkRankCentrality", + "LinkRead", + "LinkReadHeld", + "LinkReadyQ", + "Links", + "LinkService", + "LinkWrite", + "LinkWriteHeld", + "LiouvilleLambda", + "List", + "Listable", + "ListAnimate", + "ListContourPlot", + "ListContourPlot3D", + "ListConvolve", + "ListCorrelate", + "ListCurvePathPlot", + "ListDeconvolve", + "ListDensityPlot", + "ListDensityPlot3D", + "Listen", + "ListFormat", + "ListFourierSequenceTransform", + "ListInterpolation", + "ListLineIntegralConvolutionPlot", + "ListLinePlot", + "ListLogLinearPlot", + "ListLogLogPlot", + "ListLogPlot", + "ListPicker", + "ListPickerBox", + "ListPickerBoxBackground", + "ListPickerBoxOptions", + "ListPlay", + "ListPlot", + "ListPlot3D", + "ListPointPlot3D", + "ListPolarPlot", + "ListQ", + "ListSliceContourPlot3D", + "ListSliceDensityPlot3D", + "ListSliceVectorPlot3D", + "ListStepPlot", + "ListStreamDensityPlot", + "ListStreamPlot", + "ListSurfacePlot3D", + "ListVectorDensityPlot", + "ListVectorPlot", + "ListVectorPlot3D", + "ListZTransform", + "Literal", + "LiteralSearch", + "LocalAdaptiveBinarize", + "LocalCache", + "LocalClusteringCoefficient", + "LocalizeDefinitions", + "LocalizeVariables", + "LocalObject", + "LocalObjects", + "LocalResponseNormalizationLayer", + "LocalSubmit", + "LocalSymbol", + "LocalTime", + "LocalTimeZone", + "LocationEquivalenceTest", + "LocationTest", + "Locator", + "LocatorAutoCreate", + "LocatorBox", + "LocatorBoxOptions", + "LocatorCentering", + "LocatorPane", + "LocatorPaneBox", + "LocatorPaneBoxOptions", + "LocatorRegion", + "Locked", + "Log", + "Log10", + "Log2", + "LogBarnesG", + "LogGamma", + "LogGammaDistribution", + "LogicalExpand", + "LogIntegral", + "LogisticDistribution", + "LogisticSigmoid", + "LogitModelFit", + "LogLikelihood", + "LogLinearPlot", + "LogLogisticDistribution", + "LogLogPlot", + "LogMultinormalDistribution", + "LogNormalDistribution", + "LogPlot", + "LogRankTest", + "LogSeriesDistribution", + "LongEqual", + "Longest", + "LongestCommonSequence", + "LongestCommonSequencePositions", + "LongestCommonSubsequence", + "LongestCommonSubsequencePositions", + "LongestMatch", + "LongestOrderedSequence", + "LongForm", + "Longitude", + "LongLeftArrow", + "LongLeftRightArrow", + "LongRightArrow", + "LongShortTermMemoryLayer", + "Lookup", + "Loopback", + "LoopFreeGraphQ", + "Looping", + "LossFunction", + "LowerCaseQ", + "LowerLeftArrow", + "LowerRightArrow", + "LowerTriangularize", + "LowerTriangularMatrixQ", + "LowpassFilter", + "LQEstimatorGains", + "LQGRegulator", + "LQOutputRegulatorGains", + "LQRegulatorGains", + "LUBackSubstitution", + "LucasL", + "LuccioSamiComponents", + "LUDecomposition", + "LunarEclipse", + "LUVColor", + "LyapunovSolve", + "LyonsGroupLy", + "MachineID", + "MachineName", + "MachineNumberQ", + "MachinePrecision", + "MacintoshSystemPageSetup", + "Magenta", + "Magnification", + "Magnify", + "MailAddressValidation", + "MailExecute", + "MailFolder", + "MailItem", + "MailReceiverFunction", + "MailResponseFunction", + "MailSearch", + "MailServerConnect", + "MailServerConnection", + "MailSettings", + "MainSolve", + "MaintainDynamicCaches", + "Majority", + "MakeBoxes", + "MakeExpression", + "MakeRules", + "ManagedLibraryExpressionID", + "ManagedLibraryExpressionQ", + "MandelbrotSetBoettcher", + "MandelbrotSetDistance", + "MandelbrotSetIterationCount", + "MandelbrotSetMemberQ", + "MandelbrotSetPlot", + "MangoldtLambda", + "ManhattanDistance", + "Manipulate", + "Manipulator", + "MannedSpaceMissionData", + "MannWhitneyTest", + "MantissaExponent", + "Manual", + "Map", + "MapAll", + "MapAt", + "MapIndexed", + "MAProcess", + "MapThread", + "MarchenkoPasturDistribution", + "MarcumQ", + "MardiaCombinedTest", + "MardiaKurtosisTest", + "MardiaSkewnessTest", + "MarginalDistribution", + "MarkovProcessProperties", + "Masking", + "MatchingDissimilarity", + "MatchLocalNameQ", + "MatchLocalNames", + "MatchQ", + "Material", + "MathematicalFunctionData", + "MathematicaNotation", + "MathieuC", + "MathieuCharacteristicA", + "MathieuCharacteristicB", + "MathieuCharacteristicExponent", + "MathieuCPrime", + "MathieuGroupM11", + "MathieuGroupM12", + "MathieuGroupM22", + "MathieuGroupM23", + "MathieuGroupM24", + "MathieuS", + "MathieuSPrime", + "MathMLForm", + "MathMLText", + "Matrices", + "MatrixExp", + "MatrixForm", + "MatrixFunction", + "MatrixLog", + "MatrixNormalDistribution", + "MatrixPlot", + "MatrixPower", + "MatrixPropertyDistribution", + "MatrixQ", + "MatrixRank", + "MatrixTDistribution", + "Max", + "MaxBend", + "MaxCellMeasure", + "MaxColorDistance", + "MaxDate", + "MaxDetect", + "MaxDuration", + "MaxExtraBandwidths", + "MaxExtraConditions", + "MaxFeatureDisplacement", + "MaxFeatures", + "MaxFilter", + "MaximalBy", + "Maximize", + "MaxItems", + "MaxIterations", + "MaxLimit", + "MaxMemoryUsed", + "MaxMixtureKernels", + "MaxOverlapFraction", + "MaxPlotPoints", + "MaxPoints", + "MaxRecursion", + "MaxStableDistribution", + "MaxStepFraction", + "MaxSteps", + "MaxStepSize", + "MaxTrainingRounds", + "MaxValue", + "MaxwellDistribution", + "MaxWordGap", + "McLaughlinGroupMcL", + "Mean", + "MeanAbsoluteLossLayer", + "MeanAround", + "MeanClusteringCoefficient", + "MeanDegreeConnectivity", + "MeanDeviation", + "MeanFilter", + "MeanGraphDistance", + "MeanNeighborDegree", + "MeanShift", + "MeanShiftFilter", + "MeanSquaredLossLayer", + "Median", + "MedianDeviation", + "MedianFilter", + "MedicalTestData", + "Medium", + "MeijerG", + "MeijerGReduce", + "MeixnerDistribution", + "MellinConvolve", + "MellinTransform", + "MemberQ", + "MemoryAvailable", + "MemoryConstrained", + "MemoryConstraint", + "MemoryInUse", + "MengerMesh", + "Menu", + "MenuAppearance", + "MenuCommandKey", + "MenuEvaluator", + "MenuItem", + "MenuList", + "MenuPacket", + "MenuSortingValue", + "MenuStyle", + "MenuView", + "Merge", + "MergeDifferences", + "MergingFunction", + "MersennePrimeExponent", + "MersennePrimeExponentQ", + "Mesh", + "MeshCellCentroid", + "MeshCellCount", + "MeshCellHighlight", + "MeshCellIndex", + "MeshCellLabel", + "MeshCellMarker", + "MeshCellMeasure", + "MeshCellQuality", + "MeshCells", + "MeshCellShapeFunction", + "MeshCellStyle", + "MeshConnectivityGraph", + "MeshCoordinates", + "MeshFunctions", + "MeshPrimitives", + "MeshQualityGoal", + "MeshRange", + "MeshRefinementFunction", + "MeshRegion", + "MeshRegionQ", + "MeshShading", + "MeshStyle", + "Message", + "MessageDialog", + "MessageList", + "MessageName", + "MessageObject", + "MessageOptions", + "MessagePacket", + "Messages", + "MessagesNotebook", + "MetaCharacters", + "MetaInformation", + "MeteorShowerData", + "Method", + "MethodOptions", + "MexicanHatWavelet", + "MeyerWavelet", + "Midpoint", + "Min", + "MinColorDistance", + "MinDate", + "MinDetect", + "MineralData", + "MinFilter", + "MinimalBy", + "MinimalPolynomial", + "MinimalStateSpaceModel", + "Minimize", + "MinimumTimeIncrement", + "MinIntervalSize", + "MinkowskiQuestionMark", + "MinLimit", + "MinMax", + "MinorPlanetData", + "Minors", + "MinRecursion", + "MinSize", + "MinStableDistribution", + "Minus", + "MinusPlus", + "MinValue", + "Missing", + "MissingBehavior", + "MissingDataMethod", + "MissingDataRules", + "MissingQ", + "MissingString", + "MissingStyle", + "MissingValuePattern", + "MittagLefflerE", + "MixedFractionParts", + "MixedGraphQ", + "MixedMagnitude", + "MixedRadix", + "MixedRadixQuantity", + "MixedUnit", + "MixtureDistribution", + "Mod", + "Modal", + "Mode", + "Modular", + "ModularInverse", + "ModularLambda", + "Module", + "Modulus", + "MoebiusMu", + "Molecule", + "MoleculeContainsQ", + "MoleculeEquivalentQ", + "MoleculeGraph", + "MoleculeModify", + "MoleculePattern", + "MoleculePlot", + "MoleculePlot3D", + "MoleculeProperty", + "MoleculeQ", + "MoleculeRecognize", + "MoleculeValue", + "Moment", + "Momentary", + "MomentConvert", + "MomentEvaluate", + "MomentGeneratingFunction", + "MomentOfInertia", + "Monday", + "Monitor", + "MonomialList", + "MonomialOrder", + "MonsterGroupM", + "MoonPhase", + "MoonPosition", + "MorletWavelet", + "MorphologicalBinarize", + "MorphologicalBranchPoints", + "MorphologicalComponents", + "MorphologicalEulerNumber", + "MorphologicalGraph", + "MorphologicalPerimeter", + "MorphologicalTransform", + "MortalityData", + "Most", + "MountainData", + "MouseAnnotation", + "MouseAppearance", + "MouseAppearanceTag", + "MouseButtons", + "Mouseover", + "MousePointerNote", + "MousePosition", + "MovieData", + "MovingAverage", + "MovingMap", + "MovingMedian", + "MoyalDistribution", + "Multicolumn", + "MultiedgeStyle", + "MultigraphQ", + "MultilaunchWarning", + "MultiLetterItalics", + "MultiLetterStyle", + "MultilineFunction", + "Multinomial", + "MultinomialDistribution", + "MultinormalDistribution", + "MultiplicativeOrder", + "Multiplicity", + "MultiplySides", + "Multiselection", + "MultivariateHypergeometricDistribution", + "MultivariatePoissonDistribution", + "MultivariateTDistribution", + "N", + "NakagamiDistribution", + "NameQ", + "Names", + "NamespaceBox", + "NamespaceBoxOptions", + "Nand", + "NArgMax", + "NArgMin", + "NBernoulliB", + "NBodySimulation", + "NBodySimulationData", + "NCache", + "NDEigensystem", + "NDEigenvalues", + "NDSolve", + "NDSolveValue", + "Nearest", + "NearestFunction", + "NearestMeshCells", + "NearestNeighborGraph", + "NearestTo", + "NebulaData", + "NeedCurrentFrontEndPackagePacket", + "NeedCurrentFrontEndSymbolsPacket", + "NeedlemanWunschSimilarity", + "Needs", + "Negative", + "NegativeBinomialDistribution", + "NegativeDefiniteMatrixQ", + "NegativeIntegers", + "NegativeMultinomialDistribution", + "NegativeRationals", + "NegativeReals", + "NegativeSemidefiniteMatrixQ", + "NeighborhoodData", + "NeighborhoodGraph", + "Nest", + "NestedGreaterGreater", + "NestedLessLess", + "NestedScriptRules", + "NestGraph", + "NestList", + "NestWhile", + "NestWhileList", + "NetAppend", + "NetBidirectionalOperator", + "NetChain", + "NetDecoder", + "NetDelete", + "NetDrop", + "NetEncoder", + "NetEvaluationMode", + "NetExtract", + "NetFlatten", + "NetFoldOperator", + "NetGANOperator", + "NetGraph", + "NetInformation", + "NetInitialize", + "NetInsert", + "NetInsertSharedArrays", + "NetJoin", + "NetMapOperator", + "NetMapThreadOperator", + "NetMeasurements", + "NetModel", + "NetNestOperator", + "NetPairEmbeddingOperator", + "NetPort", + "NetPortGradient", + "NetPrepend", + "NetRename", + "NetReplace", + "NetReplacePart", + "NetSharedArray", + "NetStateObject", + "NetTake", + "NetTrain", + "NetTrainResultsObject", + "NetworkPacketCapture", + "NetworkPacketRecording", + "NetworkPacketRecordingDuring", + "NetworkPacketTrace", + "NeumannValue", + "NevilleThetaC", + "NevilleThetaD", + "NevilleThetaN", + "NevilleThetaS", + "NewPrimitiveStyle", + "NExpectation", + "Next", + "NextCell", + "NextDate", + "NextPrime", + "NextScheduledTaskTime", + "NHoldAll", + "NHoldFirst", + "NHoldRest", + "NicholsGridLines", + "NicholsPlot", + "NightHemisphere", + "NIntegrate", + "NMaximize", + "NMaxValue", + "NMinimize", + "NMinValue", + "NominalVariables", + "NonAssociative", + "NoncentralBetaDistribution", + "NoncentralChiSquareDistribution", + "NoncentralFRatioDistribution", + "NoncentralStudentTDistribution", + "NonCommutativeMultiply", + "NonConstants", + "NondimensionalizationTransform", + "None", + "NoneTrue", + "NonlinearModelFit", + "NonlinearStateSpaceModel", + "NonlocalMeansFilter", + "NonNegative", + "NonNegativeIntegers", + "NonNegativeRationals", + "NonNegativeReals", + "NonPositive", + "NonPositiveIntegers", + "NonPositiveRationals", + "NonPositiveReals", + "Nor", + "NorlundB", + "Norm", + "Normal", + "NormalDistribution", + "NormalGrouping", + "NormalizationLayer", + "Normalize", + "Normalized", + "NormalizedSquaredEuclideanDistance", + "NormalMatrixQ", + "NormalsFunction", + "NormFunction", + "Not", + "NotCongruent", + "NotCupCap", + "NotDoubleVerticalBar", + "Notebook", + "NotebookApply", + "NotebookAutoSave", + "NotebookClose", + "NotebookConvertSettings", + "NotebookCreate", + "NotebookCreateReturnObject", + "NotebookDefault", + "NotebookDelete", + "NotebookDirectory", + "NotebookDynamicExpression", + "NotebookEvaluate", + "NotebookEventActions", + "NotebookFileName", + "NotebookFind", + "NotebookFindReturnObject", + "NotebookGet", + "NotebookGetLayoutInformationPacket", + "NotebookGetMisspellingsPacket", + "NotebookImport", + "NotebookInformation", + "NotebookInterfaceObject", + "NotebookLocate", + "NotebookObject", + "NotebookOpen", + "NotebookOpenReturnObject", + "NotebookPath", + "NotebookPrint", + "NotebookPut", + "NotebookPutReturnObject", + "NotebookRead", + "NotebookResetGeneratedCells", + "Notebooks", + "NotebookSave", + "NotebookSaveAs", + "NotebookSelection", + "NotebookSetupLayoutInformationPacket", + "NotebooksMenu", + "NotebookTemplate", + "NotebookWrite", + "NotElement", + "NotEqualTilde", + "NotExists", + "NotGreater", + "NotGreaterEqual", + "NotGreaterFullEqual", + "NotGreaterGreater", + "NotGreaterLess", + "NotGreaterSlantEqual", + "NotGreaterTilde", + "Nothing", + "NotHumpDownHump", + "NotHumpEqual", + "NotificationFunction", + "NotLeftTriangle", + "NotLeftTriangleBar", + "NotLeftTriangleEqual", + "NotLess", + "NotLessEqual", + "NotLessFullEqual", + "NotLessGreater", + "NotLessLess", + "NotLessSlantEqual", + "NotLessTilde", + "NotNestedGreaterGreater", + "NotNestedLessLess", + "NotPrecedes", + "NotPrecedesEqual", + "NotPrecedesSlantEqual", + "NotPrecedesTilde", + "NotReverseElement", + "NotRightTriangle", + "NotRightTriangleBar", + "NotRightTriangleEqual", + "NotSquareSubset", + "NotSquareSubsetEqual", + "NotSquareSuperset", + "NotSquareSupersetEqual", + "NotSubset", + "NotSubsetEqual", + "NotSucceeds", + "NotSucceedsEqual", + "NotSucceedsSlantEqual", + "NotSucceedsTilde", + "NotSuperset", + "NotSupersetEqual", + "NotTilde", + "NotTildeEqual", + "NotTildeFullEqual", + "NotTildeTilde", + "NotVerticalBar", + "Now", + "NoWhitespace", + "NProbability", + "NProduct", + "NProductFactors", + "NRoots", + "NSolve", + "NSum", + "NSumTerms", + "NuclearExplosionData", + "NuclearReactorData", + "Null", + "NullRecords", + "NullSpace", + "NullWords", + "Number", + "NumberCompose", + "NumberDecompose", + "NumberExpand", + "NumberFieldClassNumber", + "NumberFieldDiscriminant", + "NumberFieldFundamentalUnits", + "NumberFieldIntegralBasis", + "NumberFieldNormRepresentatives", + "NumberFieldRegulator", + "NumberFieldRootsOfUnity", + "NumberFieldSignature", + "NumberForm", + "NumberFormat", + "NumberLinePlot", + "NumberMarks", + "NumberMultiplier", + "NumberPadding", + "NumberPoint", + "NumberQ", + "NumberSeparator", + "NumberSigns", + "NumberString", + "Numerator", + "NumeratorDenominator", + "NumericalOrder", + "NumericalSort", + "NumericArray", + "NumericArrayQ", + "NumericArrayType", + "NumericFunction", + "NumericQ", + "NuttallWindow", + "NValues", + "NyquistGridLines", + "NyquistPlot", + "O", + "ObservabilityGramian", + "ObservabilityMatrix", + "ObservableDecomposition", + "ObservableModelQ", + "OceanData", + "Octahedron", + "OddQ", + "Off", + "Offset", + "OLEData", + "On", + "ONanGroupON", + "Once", + "OneIdentity", + "Opacity", + "OpacityFunction", + "OpacityFunctionScaling", + "Open", + "OpenAppend", + "Opener", + "OpenerBox", + "OpenerBoxOptions", + "OpenerView", + "OpenFunctionInspectorPacket", + "Opening", + "OpenRead", + "OpenSpecialOptions", + "OpenTemporary", + "OpenWrite", + "Operate", + "OperatingSystem", + "OperatorApplied", + "OptimumFlowData", + "Optional", + "OptionalElement", + "OptionInspectorSettings", + "OptionQ", + "Options", + "OptionsPacket", + "OptionsPattern", + "OptionValue", + "OptionValueBox", + "OptionValueBoxOptions", + "Or", + "Orange", + "Order", + "OrderDistribution", + "OrderedQ", + "Ordering", + "OrderingBy", + "OrderingLayer", + "Orderless", + "OrderlessPatternSequence", + "OrnsteinUhlenbeckProcess", + "Orthogonalize", + "OrthogonalMatrixQ", + "Out", + "Outer", + "OuterPolygon", + "OuterPolyhedron", + "OutputAutoOverwrite", + "OutputControllabilityMatrix", + "OutputControllableModelQ", + "OutputForm", + "OutputFormData", + "OutputGrouping", + "OutputMathEditExpression", + "OutputNamePacket", + "OutputResponse", + "OutputSizeLimit", + "OutputStream", + "Over", + "OverBar", + "OverDot", + "Overflow", + "OverHat", + "Overlaps", + "Overlay", + "OverlayBox", + "OverlayBoxOptions", + "Overscript", + "OverscriptBox", + "OverscriptBoxOptions", + "OverTilde", + "OverVector", + "OverwriteTarget", + "OwenT", + "OwnValues", + "Package", + "PackingMethod", + "PackPaclet", + "PacletDataRebuild", + "PacletDirectoryAdd", + "PacletDirectoryLoad", + "PacletDirectoryRemove", + "PacletDirectoryUnload", + "PacletDisable", + "PacletEnable", + "PacletFind", + "PacletFindRemote", + "PacletInformation", + "PacletInstall", + "PacletInstallSubmit", + "PacletNewerQ", + "PacletObject", + "PacletObjectQ", + "PacletSite", + "PacletSiteObject", + "PacletSiteRegister", + "PacletSites", + "PacletSiteUnregister", + "PacletSiteUpdate", + "PacletUninstall", + "PacletUpdate", + "PaddedForm", + "Padding", + "PaddingLayer", + "PaddingSize", + "PadeApproximant", + "PadLeft", + "PadRight", + "PageBreakAbove", + "PageBreakBelow", + "PageBreakWithin", + "PageFooterLines", + "PageFooters", + "PageHeaderLines", + "PageHeaders", + "PageHeight", + "PageRankCentrality", + "PageTheme", + "PageWidth", + "Pagination", + "PairedBarChart", + "PairedHistogram", + "PairedSmoothHistogram", + "PairedTTest", + "PairedZTest", + "PaletteNotebook", + "PalettePath", + "PalindromeQ", + "Pane", + "PaneBox", + "PaneBoxOptions", + "Panel", + "PanelBox", + "PanelBoxOptions", + "Paneled", + "PaneSelector", + "PaneSelectorBox", + "PaneSelectorBoxOptions", + "PaperWidth", + "ParabolicCylinderD", + "ParagraphIndent", + "ParagraphSpacing", + "ParallelArray", + "ParallelCombine", + "ParallelDo", + "Parallelepiped", + "ParallelEvaluate", + "Parallelization", + "Parallelize", + "ParallelMap", + "ParallelNeeds", + "Parallelogram", + "ParallelProduct", + "ParallelSubmit", + "ParallelSum", + "ParallelTable", + "ParallelTry", + "Parameter", + "ParameterEstimator", + "ParameterMixtureDistribution", + "ParameterVariables", + "ParametricFunction", + "ParametricNDSolve", + "ParametricNDSolveValue", + "ParametricPlot", + "ParametricPlot3D", + "ParametricRampLayer", + "ParametricRegion", + "ParentBox", + "ParentCell", + "ParentConnect", + "ParentDirectory", + "ParentForm", + "Parenthesize", + "ParentList", + "ParentNotebook", + "ParetoDistribution", + "ParetoPickandsDistribution", + "ParkData", + "Part", + "PartBehavior", + "PartialCorrelationFunction", + "PartialD", + "ParticleAcceleratorData", + "ParticleData", + "Partition", + "PartitionGranularity", + "PartitionsP", + "PartitionsQ", + "PartLayer", + "PartOfSpeech", + "PartProtection", + "ParzenWindow", + "PascalDistribution", + "PassEventsDown", + "PassEventsUp", + "Paste", + "PasteAutoQuoteCharacters", + "PasteBoxFormInlineCells", + "PasteButton", + "Path", + "PathGraph", + "PathGraphQ", + "Pattern", + "PatternFilling", + "PatternSequence", + "PatternTest", + "PauliMatrix", + "PaulWavelet", + "Pause", + "PausedTime", + "PDF", + "PeakDetect", + "PeanoCurve", + "PearsonChiSquareTest", + "PearsonCorrelationTest", + "PearsonDistribution", + "PercentForm", + "PerfectNumber", + "PerfectNumberQ", + "PerformanceGoal", + "Perimeter", + "PeriodicBoundaryCondition", + "PeriodicInterpolation", + "Periodogram", + "PeriodogramArray", + "Permanent", + "Permissions", + "PermissionsGroup", + "PermissionsGroupMemberQ", + "PermissionsGroups", + "PermissionsKey", + "PermissionsKeys", + "PermutationCycles", + "PermutationCyclesQ", + "PermutationGroup", + "PermutationLength", + "PermutationList", + "PermutationListQ", + "PermutationMax", + "PermutationMin", + "PermutationOrder", + "PermutationPower", + "PermutationProduct", + "PermutationReplace", + "Permutations", + "PermutationSupport", + "Permute", + "PeronaMalikFilter", + "Perpendicular", + "PerpendicularBisector", + "PersistenceLocation", + "PersistenceTime", + "PersistentObject", + "PersistentObjects", + "PersistentValue", + "PersonData", + "PERTDistribution", + "PetersenGraph", + "PhaseMargins", + "PhaseRange", + "PhysicalSystemData", + "Pi", + "Pick", + "PIDData", + "PIDDerivativeFilter", + "PIDFeedforward", + "PIDTune", + "Piecewise", + "PiecewiseExpand", + "PieChart", + "PieChart3D", + "PillaiTrace", + "PillaiTraceTest", + "PingTime", + "Pink", + "PitchRecognize", + "Pivoting", + "PixelConstrained", + "PixelValue", + "PixelValuePositions", + "Placed", + "Placeholder", + "PlaceholderReplace", + "Plain", + "PlanarAngle", + "PlanarGraph", + "PlanarGraphQ", + "PlanckRadiationLaw", + "PlaneCurveData", + "PlanetaryMoonData", + "PlanetData", + "PlantData", + "Play", + "PlayRange", + "Plot", + "Plot3D", + "Plot3Matrix", + "PlotDivision", + "PlotJoined", + "PlotLabel", + "PlotLabels", + "PlotLayout", + "PlotLegends", + "PlotMarkers", + "PlotPoints", + "PlotRange", + "PlotRangeClipping", + "PlotRangeClipPlanesStyle", + "PlotRangePadding", + "PlotRegion", + "PlotStyle", + "PlotTheme", + "Pluralize", + "Plus", + "PlusMinus", + "Pochhammer", + "PodStates", + "PodWidth", + "Point", + "Point3DBox", + "Point3DBoxOptions", + "PointBox", + "PointBoxOptions", + "PointFigureChart", + "PointLegend", + "PointSize", + "PoissonConsulDistribution", + "PoissonDistribution", + "PoissonProcess", + "PoissonWindow", + "PolarAxes", + "PolarAxesOrigin", + "PolarGridLines", + "PolarPlot", + "PolarTicks", + "PoleZeroMarkers", + "PolyaAeppliDistribution", + "PolyGamma", + "Polygon", + "Polygon3DBox", + "Polygon3DBoxOptions", + "PolygonalNumber", + "PolygonAngle", + "PolygonBox", + "PolygonBoxOptions", + "PolygonCoordinates", + "PolygonDecomposition", + "PolygonHoleScale", + "PolygonIntersections", + "PolygonScale", + "Polyhedron", + "PolyhedronAngle", + "PolyhedronCoordinates", + "PolyhedronData", + "PolyhedronDecomposition", + "PolyhedronGenus", + "PolyLog", + "PolynomialExtendedGCD", + "PolynomialForm", + "PolynomialGCD", + "PolynomialLCM", + "PolynomialMod", + "PolynomialQ", + "PolynomialQuotient", + "PolynomialQuotientRemainder", + "PolynomialReduce", + "PolynomialRemainder", + "Polynomials", + "PoolingLayer", + "PopupMenu", + "PopupMenuBox", + "PopupMenuBoxOptions", + "PopupView", + "PopupWindow", + "Position", + "PositionIndex", + "Positive", + "PositiveDefiniteMatrixQ", + "PositiveIntegers", + "PositiveRationals", + "PositiveReals", + "PositiveSemidefiniteMatrixQ", + "PossibleZeroQ", + "Postfix", + "PostScript", + "Power", + "PowerDistribution", + "PowerExpand", + "PowerMod", + "PowerModList", + "PowerRange", + "PowerSpectralDensity", + "PowersRepresentations", + "PowerSymmetricPolynomial", + "Precedence", + "PrecedenceForm", + "Precedes", + "PrecedesEqual", + "PrecedesSlantEqual", + "PrecedesTilde", + "Precision", + "PrecisionGoal", + "PreDecrement", + "Predict", + "PredictionRoot", + "PredictorFunction", + "PredictorInformation", + "PredictorMeasurements", + "PredictorMeasurementsObject", + "PreemptProtect", + "PreferencesPath", + "Prefix", + "PreIncrement", + "Prepend", + "PrependLayer", + "PrependTo", + "PreprocessingRules", + "PreserveColor", + "PreserveImageOptions", + "Previous", + "PreviousCell", + "PreviousDate", + "PriceGraphDistribution", + "PrimaryPlaceholder", + "Prime", + "PrimeNu", + "PrimeOmega", + "PrimePi", + "PrimePowerQ", + "PrimeQ", + "Primes", + "PrimeZetaP", + "PrimitivePolynomialQ", + "PrimitiveRoot", + "PrimitiveRootList", + "PrincipalComponents", + "PrincipalValue", + "Print", + "PrintableASCIIQ", + "PrintAction", + "PrintForm", + "PrintingCopies", + "PrintingOptions", + "PrintingPageRange", + "PrintingStartingPageNumber", + "PrintingStyleEnvironment", + "Printout3D", + "Printout3DPreviewer", + "PrintPrecision", + "PrintTemporary", + "Prism", + "PrismBox", + "PrismBoxOptions", + "PrivateCellOptions", + "PrivateEvaluationOptions", + "PrivateFontOptions", + "PrivateFrontEndOptions", + "PrivateKey", + "PrivateNotebookOptions", + "PrivatePaths", + "Probability", + "ProbabilityDistribution", + "ProbabilityPlot", + "ProbabilityPr", + "ProbabilityScalePlot", + "ProbitModelFit", + "ProcessConnection", + "ProcessDirectory", + "ProcessEnvironment", + "Processes", + "ProcessEstimator", + "ProcessInformation", + "ProcessObject", + "ProcessParameterAssumptions", + "ProcessParameterQ", + "ProcessStateDomain", + "ProcessStatus", + "ProcessTimeDomain", + "Product", + "ProductDistribution", + "ProductLog", + "ProgressIndicator", + "ProgressIndicatorBox", + "ProgressIndicatorBoxOptions", + "Projection", + "Prolog", + "PromptForm", + "ProofObject", + "Properties", + "Property", + "PropertyList", + "PropertyValue", + "Proportion", + "Proportional", + "Protect", + "Protected", + "ProteinData", + "Pruning", + "PseudoInverse", + "PsychrometricPropertyData", + "PublicKey", + "PublisherID", + "PulsarData", + "PunctuationCharacter", + "Purple", + "Put", + "PutAppend", + "Pyramid", + "PyramidBox", + "PyramidBoxOptions", + "QBinomial", + "QFactorial", + "QGamma", + "QHypergeometricPFQ", + "QnDispersion", + "QPochhammer", + "QPolyGamma", + "QRDecomposition", + "QuadraticIrrationalQ", + "QuadraticOptimization", + "Quantile", + "QuantilePlot", + "Quantity", + "QuantityArray", + "QuantityDistribution", + "QuantityForm", + "QuantityMagnitude", + "QuantityQ", + "QuantityUnit", + "QuantityVariable", + "QuantityVariableCanonicalUnit", + "QuantityVariableDimensions", + "QuantityVariableIdentifier", + "QuantityVariablePhysicalQuantity", + "Quartics", + "QuartileDeviation", + "Quartiles", + "QuartileSkewness", + "Query", + "QueueingNetworkProcess", + "QueueingProcess", + "QueueProperties", + "Quiet", + "Quit", + "Quotient", + "QuotientRemainder", + "RadialGradientImage", + "RadialityCentrality", + "RadicalBox", + "RadicalBoxOptions", + "RadioButton", + "RadioButtonBar", + "RadioButtonBox", + "RadioButtonBoxOptions", + "Radon", + "RadonTransform", + "RamanujanTau", + "RamanujanTauL", + "RamanujanTauTheta", + "RamanujanTauZ", + "Ramp", + "Random", + "RandomChoice", + "RandomColor", + "RandomComplex", + "RandomEntity", + "RandomFunction", + "RandomGeoPosition", + "RandomGraph", + "RandomImage", + "RandomInstance", + "RandomInteger", + "RandomPermutation", + "RandomPoint", + "RandomPolygon", + "RandomPolyhedron", + "RandomPrime", + "RandomReal", + "RandomSample", + "RandomSeed", + "RandomSeeding", + "RandomVariate", + "RandomWalkProcess", + "RandomWord", + "Range", + "RangeFilter", + "RangeSpecification", + "RankedMax", + "RankedMin", + "RarerProbability", + "Raster", + "Raster3D", + "Raster3DBox", + "Raster3DBoxOptions", + "RasterArray", + "RasterBox", + "RasterBoxOptions", + "Rasterize", + "RasterSize", + "Rational", + "RationalFunctions", + "Rationalize", + "Rationals", + "Ratios", + "RawArray", + "RawBoxes", + "RawData", + "RawMedium", + "RayleighDistribution", + "Re", + "Read", + "ReadByteArray", + "ReadLine", + "ReadList", + "ReadProtected", + "ReadString", + "Real", + "RealAbs", + "RealBlockDiagonalForm", + "RealDigits", + "RealExponent", + "Reals", + "RealSign", + "Reap", + "RebuildPacletData", + "RecognitionPrior", + "RecognitionThreshold", + "Record", + "RecordLists", + "RecordSeparators", + "Rectangle", + "RectangleBox", + "RectangleBoxOptions", + "RectangleChart", + "RectangleChart3D", + "RectangularRepeatingElement", + "RecurrenceFilter", + "RecurrenceTable", + "RecurringDigitsForm", + "Red", + "Reduce", + "RefBox", + "ReferenceLineStyle", + "ReferenceMarkers", + "ReferenceMarkerStyle", + "Refine", + "ReflectionMatrix", + "ReflectionTransform", + "Refresh", + "RefreshRate", + "Region", + "RegionBinarize", + "RegionBoundary", + "RegionBoundaryStyle", + "RegionBounds", + "RegionCentroid", + "RegionDifference", + "RegionDimension", + "RegionDisjoint", + "RegionDistance", + "RegionDistanceFunction", + "RegionEmbeddingDimension", + "RegionEqual", + "RegionFillingStyle", + "RegionFunction", + "RegionImage", + "RegionIntersection", + "RegionMeasure", + "RegionMember", + "RegionMemberFunction", + "RegionMoment", + "RegionNearest", + "RegionNearestFunction", + "RegionPlot", + "RegionPlot3D", + "RegionProduct", + "RegionQ", + "RegionResize", + "RegionSize", + "RegionSymmetricDifference", + "RegionUnion", + "RegionWithin", + "RegisterExternalEvaluator", + "RegularExpression", + "Regularization", + "RegularlySampledQ", + "RegularPolygon", + "ReIm", + "ReImLabels", + "ReImPlot", + "ReImStyle", + "Reinstall", + "RelationalDatabase", + "RelationGraph", + "Release", + "ReleaseHold", + "ReliabilityDistribution", + "ReliefImage", + "ReliefPlot", + "RemoteAuthorizationCaching", + "RemoteConnect", + "RemoteConnectionObject", + "RemoteFile", + "RemoteRun", + "RemoteRunProcess", + "Remove", + "RemoveAlphaChannel", + "RemoveAsynchronousTask", + "RemoveAudioStream", + "RemoveBackground", + "RemoveChannelListener", + "RemoveChannelSubscribers", + "Removed", + "RemoveDiacritics", + "RemoveInputStreamMethod", + "RemoveOutputStreamMethod", + "RemoveProperty", + "RemoveScheduledTask", + "RemoveUsers", + "RemoveVideoStream", + "RenameDirectory", + "RenameFile", + "RenderAll", + "RenderingOptions", + "RenewalProcess", + "RenkoChart", + "RepairMesh", + "Repeated", + "RepeatedNull", + "RepeatedString", + "RepeatedTiming", + "RepeatingElement", + "Replace", + "ReplaceAll", + "ReplaceHeldPart", + "ReplaceImageValue", + "ReplaceList", + "ReplacePart", + "ReplacePixelValue", + "ReplaceRepeated", + "ReplicateLayer", + "RequiredPhysicalQuantities", + "Resampling", + "ResamplingAlgorithmData", + "ResamplingMethod", + "Rescale", + "RescalingTransform", + "ResetDirectory", + "ResetMenusPacket", + "ResetScheduledTask", + "ReshapeLayer", + "Residue", + "ResizeLayer", + "Resolve", + "ResourceAcquire", + "ResourceData", + "ResourceFunction", + "ResourceObject", + "ResourceRegister", + "ResourceRemove", + "ResourceSearch", + "ResourceSubmissionObject", + "ResourceSubmit", + "ResourceSystemBase", + "ResourceSystemPath", + "ResourceUpdate", + "ResourceVersion", + "ResponseForm", + "Rest", + "RestartInterval", + "Restricted", + "Resultant", + "ResumePacket", + "Return", + "ReturnEntersInput", + "ReturnExpressionPacket", + "ReturnInputFormPacket", + "ReturnPacket", + "ReturnReceiptFunction", + "ReturnTextPacket", + "Reverse", + "ReverseApplied", + "ReverseBiorthogonalSplineWavelet", + "ReverseElement", + "ReverseEquilibrium", + "ReverseGraph", + "ReverseSort", + "ReverseSortBy", + "ReverseUpEquilibrium", + "RevolutionAxis", + "RevolutionPlot3D", + "RGBColor", + "RiccatiSolve", + "RiceDistribution", + "RidgeFilter", + "RiemannR", + "RiemannSiegelTheta", + "RiemannSiegelZ", + "RiemannXi", + "Riffle", + "Right", + "RightArrow", + "RightArrowBar", + "RightArrowLeftArrow", + "RightComposition", + "RightCosetRepresentative", + "RightDownTeeVector", + "RightDownVector", + "RightDownVectorBar", + "RightTee", + "RightTeeArrow", + "RightTeeVector", + "RightTriangle", + "RightTriangleBar", + "RightTriangleEqual", + "RightUpDownVector", + "RightUpTeeVector", + "RightUpVector", + "RightUpVectorBar", + "RightVector", + "RightVectorBar", + "RiskAchievementImportance", + "RiskReductionImportance", + "RogersTanimotoDissimilarity", + "RollPitchYawAngles", + "RollPitchYawMatrix", + "RomanNumeral", + "Root", + "RootApproximant", + "RootIntervals", + "RootLocusPlot", + "RootMeanSquare", + "RootOfUnityQ", + "RootReduce", + "Roots", + "RootSum", + "Rotate", + "RotateLabel", + "RotateLeft", + "RotateRight", + "RotationAction", + "RotationBox", + "RotationBoxOptions", + "RotationMatrix", + "RotationTransform", + "Round", + "RoundImplies", + "RoundingRadius", + "Row", + "RowAlignments", + "RowBackgrounds", + "RowBox", + "RowHeights", + "RowLines", + "RowMinHeight", + "RowReduce", + "RowsEqual", + "RowSpacings", + "RSolve", + "RSolveValue", + "RudinShapiro", + "RudvalisGroupRu", + "Rule", + "RuleCondition", + "RuleDelayed", + "RuleForm", + "RulePlot", + "RulerUnits", + "Run", + "RunProcess", + "RunScheduledTask", + "RunThrough", + "RuntimeAttributes", + "RuntimeOptions", + "RussellRaoDissimilarity", + "SameQ", + "SameTest", + "SameTestProperties", + "SampledEntityClass", + "SampleDepth", + "SampledSoundFunction", + "SampledSoundList", + "SampleRate", + "SamplingPeriod", + "SARIMAProcess", + "SARMAProcess", + "SASTriangle", + "SatelliteData", + "SatisfiabilityCount", + "SatisfiabilityInstances", + "SatisfiableQ", + "Saturday", + "Save", + "Saveable", + "SaveAutoDelete", + "SaveConnection", + "SaveDefinitions", + "SavitzkyGolayMatrix", + "SawtoothWave", + "Scale", + "Scaled", + "ScaleDivisions", + "ScaledMousePosition", + "ScaleOrigin", + "ScalePadding", + "ScaleRanges", + "ScaleRangeStyle", + "ScalingFunctions", + "ScalingMatrix", + "ScalingTransform", + "Scan", + "ScheduledTask", + "ScheduledTaskActiveQ", + "ScheduledTaskInformation", + "ScheduledTaskInformationData", + "ScheduledTaskObject", + "ScheduledTasks", + "SchurDecomposition", + "ScientificForm", + "ScientificNotationThreshold", + "ScorerGi", + "ScorerGiPrime", + "ScorerHi", + "ScorerHiPrime", + "ScreenRectangle", + "ScreenStyleEnvironment", + "ScriptBaselineShifts", + "ScriptForm", + "ScriptLevel", + "ScriptMinSize", + "ScriptRules", + "ScriptSizeMultipliers", + "Scrollbars", + "ScrollingOptions", + "ScrollPosition", + "SearchAdjustment", + "SearchIndexObject", + "SearchIndices", + "SearchQueryString", + "SearchResultObject", + "Sec", + "Sech", + "SechDistribution", + "SecondOrderConeOptimization", + "SectionGrouping", + "SectorChart", + "SectorChart3D", + "SectorOrigin", + "SectorSpacing", + "SecuredAuthenticationKey", + "SecuredAuthenticationKeys", + "SeedRandom", + "Select", + "Selectable", + "SelectComponents", + "SelectedCells", + "SelectedNotebook", + "SelectFirst", + "Selection", + "SelectionAnimate", + "SelectionCell", + "SelectionCellCreateCell", + "SelectionCellDefaultStyle", + "SelectionCellParentStyle", + "SelectionCreateCell", + "SelectionDebuggerTag", + "SelectionDuplicateCell", + "SelectionEvaluate", + "SelectionEvaluateCreateCell", + "SelectionMove", + "SelectionPlaceholder", + "SelectionSetStyle", + "SelectWithContents", + "SelfLoops", + "SelfLoopStyle", + "SemanticImport", + "SemanticImportString", + "SemanticInterpretation", + "SemialgebraicComponentInstances", + "SemidefiniteOptimization", + "SendMail", + "SendMessage", + "Sequence", + "SequenceAlignment", + "SequenceAttentionLayer", + "SequenceCases", + "SequenceCount", + "SequenceFold", + "SequenceFoldList", + "SequenceForm", + "SequenceHold", + "SequenceLastLayer", + "SequenceMostLayer", + "SequencePosition", + "SequencePredict", + "SequencePredictorFunction", + "SequenceReplace", + "SequenceRestLayer", + "SequenceReverseLayer", + "SequenceSplit", + "Series", + "SeriesCoefficient", + "SeriesData", + "SeriesTermGoal", + "ServiceConnect", + "ServiceDisconnect", + "ServiceExecute", + "ServiceObject", + "ServiceRequest", + "ServiceResponse", + "ServiceSubmit", + "SessionSubmit", + "SessionTime", + "Set", + "SetAccuracy", + "SetAlphaChannel", + "SetAttributes", + "Setbacks", + "SetBoxFormNamesPacket", + "SetCloudDirectory", + "SetCookies", + "SetDelayed", + "SetDirectory", + "SetEnvironment", + "SetEvaluationNotebook", + "SetFileDate", + "SetFileLoadingContext", + "SetNotebookStatusLine", + "SetOptions", + "SetOptionsPacket", + "SetPermissions", + "SetPrecision", + "SetProperty", + "SetSecuredAuthenticationKey", + "SetSelectedNotebook", + "SetSharedFunction", + "SetSharedVariable", + "SetSpeechParametersPacket", + "SetStreamPosition", + "SetSystemModel", + "SetSystemOptions", + "Setter", + "SetterBar", + "SetterBox", + "SetterBoxOptions", + "Setting", + "SetUsers", + "SetValue", + "Shading", + "Shallow", + "ShannonWavelet", + "ShapiroWilkTest", + "Share", + "SharingList", + "Sharpen", + "ShearingMatrix", + "ShearingTransform", + "ShellRegion", + "ShenCastanMatrix", + "ShiftedGompertzDistribution", + "ShiftRegisterSequence", + "Short", + "ShortDownArrow", + "Shortest", + "ShortestMatch", + "ShortestPathFunction", + "ShortLeftArrow", + "ShortRightArrow", + "ShortTimeFourier", + "ShortTimeFourierData", + "ShortUpArrow", + "Show", + "ShowAutoConvert", + "ShowAutoSpellCheck", + "ShowAutoStyles", + "ShowCellBracket", + "ShowCellLabel", + "ShowCellTags", + "ShowClosedCellArea", + "ShowCodeAssist", + "ShowContents", + "ShowControls", + "ShowCursorTracker", + "ShowGroupOpenCloseIcon", + "ShowGroupOpener", + "ShowInvisibleCharacters", + "ShowPageBreaks", + "ShowPredictiveInterface", + "ShowSelection", + "ShowShortBoxForm", + "ShowSpecialCharacters", + "ShowStringCharacters", + "ShowSyntaxStyles", + "ShrinkingDelay", + "ShrinkWrapBoundingBox", + "SiderealTime", + "SiegelTheta", + "SiegelTukeyTest", + "SierpinskiCurve", + "SierpinskiMesh", + "Sign", + "Signature", + "SignedRankTest", + "SignedRegionDistance", + "SignificanceLevel", + "SignPadding", + "SignTest", + "SimilarityRules", + "SimpleGraph", + "SimpleGraphQ", + "SimplePolygonQ", + "SimplePolyhedronQ", + "Simplex", + "Simplify", + "Sin", + "Sinc", + "SinghMaddalaDistribution", + "SingleEvaluation", + "SingleLetterItalics", + "SingleLetterStyle", + "SingularValueDecomposition", + "SingularValueList", + "SingularValuePlot", + "SingularValues", + "Sinh", + "SinhIntegral", + "SinIntegral", + "SixJSymbol", + "Skeleton", + "SkeletonTransform", + "SkellamDistribution", + "Skewness", + "SkewNormalDistribution", + "SkinStyle", + "Skip", + "SliceContourPlot3D", + "SliceDensityPlot3D", + "SliceDistribution", + "SliceVectorPlot3D", + "Slider", + "Slider2D", + "Slider2DBox", + "Slider2DBoxOptions", + "SliderBox", + "SliderBoxOptions", + "SlideView", + "Slot", + "SlotSequence", + "Small", + "SmallCircle", + "Smaller", + "SmithDecomposition", + "SmithDelayCompensator", + "SmithWatermanSimilarity", + "SmoothDensityHistogram", + "SmoothHistogram", + "SmoothHistogram3D", + "SmoothKernelDistribution", + "SnDispersion", + "Snippet", + "SnubPolyhedron", + "SocialMediaData", + "Socket", + "SocketConnect", + "SocketListen", + "SocketListener", + "SocketObject", + "SocketOpen", + "SocketReadMessage", + "SocketReadyQ", + "Sockets", + "SocketWaitAll", + "SocketWaitNext", + "SoftmaxLayer", + "SokalSneathDissimilarity", + "SolarEclipse", + "SolarSystemFeatureData", + "SolidAngle", + "SolidData", + "SolidRegionQ", + "Solve", + "SolveAlways", + "SolveDelayed", + "Sort", + "SortBy", + "SortedBy", + "SortedEntityClass", + "Sound", + "SoundAndGraphics", + "SoundNote", + "SoundVolume", + "SourceLink", + "Sow", + "Space", + "SpaceCurveData", + "SpaceForm", + "Spacer", + "Spacings", + "Span", + "SpanAdjustments", + "SpanCharacterRounding", + "SpanFromAbove", + "SpanFromBoth", + "SpanFromLeft", + "SpanLineThickness", + "SpanMaxSize", + "SpanMinSize", + "SpanningCharacters", + "SpanSymmetric", + "SparseArray", + "SpatialGraphDistribution", + "SpatialMedian", + "SpatialTransformationLayer", + "Speak", + "SpeakerMatchQ", + "SpeakTextPacket", + "SpearmanRankTest", + "SpearmanRho", + "SpeciesData", + "SpecificityGoal", + "SpectralLineData", + "Spectrogram", + "SpectrogramArray", + "Specularity", + "SpeechCases", + "SpeechInterpreter", + "SpeechRecognize", + "SpeechSynthesize", + "SpellingCorrection", + "SpellingCorrectionList", + "SpellingDictionaries", + "SpellingDictionariesPath", + "SpellingOptions", + "SpellingSuggestionsPacket", + "Sphere", + "SphereBox", + "SpherePoints", + "SphericalBesselJ", + "SphericalBesselY", + "SphericalHankelH1", + "SphericalHankelH2", + "SphericalHarmonicY", + "SphericalPlot3D", + "SphericalRegion", + "SphericalShell", + "SpheroidalEigenvalue", + "SpheroidalJoiningFactor", + "SpheroidalPS", + "SpheroidalPSPrime", + "SpheroidalQS", + "SpheroidalQSPrime", + "SpheroidalRadialFactor", + "SpheroidalS1", + "SpheroidalS1Prime", + "SpheroidalS2", + "SpheroidalS2Prime", + "Splice", + "SplicedDistribution", + "SplineClosed", + "SplineDegree", + "SplineKnots", + "SplineWeights", + "Split", + "SplitBy", + "SpokenString", + "Sqrt", + "SqrtBox", + "SqrtBoxOptions", + "Square", + "SquaredEuclideanDistance", + "SquareFreeQ", + "SquareIntersection", + "SquareMatrixQ", + "SquareRepeatingElement", + "SquaresR", + "SquareSubset", + "SquareSubsetEqual", + "SquareSuperset", + "SquareSupersetEqual", + "SquareUnion", + "SquareWave", + "SSSTriangle", + "StabilityMargins", + "StabilityMarginsStyle", + "StableDistribution", + "Stack", + "StackBegin", + "StackComplete", + "StackedDateListPlot", + "StackedListPlot", + "StackInhibit", + "StadiumShape", + "StandardAtmosphereData", + "StandardDeviation", + "StandardDeviationFilter", + "StandardForm", + "Standardize", + "Standardized", + "StandardOceanData", + "StandbyDistribution", + "Star", + "StarClusterData", + "StarData", + "StarGraph", + "StartAsynchronousTask", + "StartExternalSession", + "StartingStepSize", + "StartOfLine", + "StartOfString", + "StartProcess", + "StartScheduledTask", + "StartupSound", + "StartWebSession", + "StateDimensions", + "StateFeedbackGains", + "StateOutputEstimator", + "StateResponse", + "StateSpaceModel", + "StateSpaceRealization", + "StateSpaceTransform", + "StateTransformationLinearize", + "StationaryDistribution", + "StationaryWaveletPacketTransform", + "StationaryWaveletTransform", + "StatusArea", + "StatusCentrality", + "StepMonitor", + "StereochemistryElements", + "StieltjesGamma", + "StippleShading", + "StirlingS1", + "StirlingS2", + "StopAsynchronousTask", + "StoppingPowerData", + "StopScheduledTask", + "StrataVariables", + "StratonovichProcess", + "StreamColorFunction", + "StreamColorFunctionScaling", + "StreamDensityPlot", + "StreamMarkers", + "StreamPlot", + "StreamPoints", + "StreamPosition", + "Streams", + "StreamScale", + "StreamStyle", + "String", + "StringBreak", + "StringByteCount", + "StringCases", + "StringContainsQ", + "StringCount", + "StringDelete", + "StringDrop", + "StringEndsQ", + "StringExpression", + "StringExtract", + "StringForm", + "StringFormat", + "StringFreeQ", + "StringInsert", + "StringJoin", + "StringLength", + "StringMatchQ", + "StringPadLeft", + "StringPadRight", + "StringPart", + "StringPartition", + "StringPosition", + "StringQ", + "StringRepeat", + "StringReplace", + "StringReplaceList", + "StringReplacePart", + "StringReverse", + "StringRiffle", + "StringRotateLeft", + "StringRotateRight", + "StringSkeleton", + "StringSplit", + "StringStartsQ", + "StringTake", + "StringTemplate", + "StringToByteArray", + "StringToStream", + "StringTrim", + "StripBoxes", + "StripOnInput", + "StripWrapperBoxes", + "StrokeForm", + "StructuralImportance", + "StructuredArray", + "StructuredArrayHeadQ", + "StructuredSelection", + "StruveH", + "StruveL", + "Stub", + "StudentTDistribution", + "Style", + "StyleBox", + "StyleBoxAutoDelete", + "StyleData", + "StyleDefinitions", + "StyleForm", + "StyleHints", + "StyleKeyMapping", + "StyleMenuListing", + "StyleNameDialogSettings", + "StyleNames", + "StylePrint", + "StyleSheetPath", + "Subdivide", + "Subfactorial", + "Subgraph", + "SubMinus", + "SubPlus", + "SubresultantPolynomialRemainders", + "SubresultantPolynomials", + "Subresultants", + "Subscript", + "SubscriptBox", + "SubscriptBoxOptions", + "Subscripted", + "Subsequences", + "Subset", + "SubsetCases", + "SubsetCount", + "SubsetEqual", + "SubsetMap", + "SubsetPosition", + "SubsetQ", + "SubsetReplace", + "Subsets", + "SubStar", + "SubstitutionSystem", + "Subsuperscript", + "SubsuperscriptBox", + "SubsuperscriptBoxOptions", + "SubtitleEncoding", + "SubtitleTracks", + "Subtract", + "SubtractFrom", + "SubtractSides", + "SubValues", + "Succeeds", + "SucceedsEqual", + "SucceedsSlantEqual", + "SucceedsTilde", + "Success", + "SuchThat", + "Sum", + "SumConvergence", + "SummationLayer", + "Sunday", + "SunPosition", + "Sunrise", + "Sunset", + "SuperDagger", + "SuperMinus", + "SupernovaData", + "SuperPlus", + "Superscript", + "SuperscriptBox", + "SuperscriptBoxOptions", + "Superset", + "SupersetEqual", + "SuperStar", + "Surd", + "SurdForm", + "SurfaceAppearance", + "SurfaceArea", + "SurfaceColor", + "SurfaceData", + "SurfaceGraphics", + "SurvivalDistribution", + "SurvivalFunction", + "SurvivalModel", + "SurvivalModelFit", + "SuspendPacket", + "SuzukiDistribution", + "SuzukiGroupSuz", + "SwatchLegend", + "Switch", + "Symbol", + "SymbolName", + "SymletWavelet", + "Symmetric", + "SymmetricGroup", + "SymmetricKey", + "SymmetricMatrixQ", + "SymmetricPolynomial", + "SymmetricReduction", + "Symmetrize", + "SymmetrizedArray", + "SymmetrizedArrayRules", + "SymmetrizedDependentComponents", + "SymmetrizedIndependentComponents", + "SymmetrizedReplacePart", + "SynchronousInitialization", + "SynchronousUpdating", + "Synonyms", + "Syntax", + "SyntaxForm", + "SyntaxInformation", + "SyntaxLength", + "SyntaxPacket", + "SyntaxQ", + "SynthesizeMissingValues", + "SystemCredential", + "SystemCredentialData", + "SystemCredentialKey", + "SystemCredentialKeys", + "SystemCredentialStoreObject", + "SystemDialogInput", + "SystemException", + "SystemGet", + "SystemHelpPath", + "SystemInformation", + "SystemInformationData", + "SystemInstall", + "SystemModel", + "SystemModeler", + "SystemModelExamples", + "SystemModelLinearize", + "SystemModelParametricSimulate", + "SystemModelPlot", + "SystemModelProgressReporting", + "SystemModelReliability", + "SystemModels", + "SystemModelSimulate", + "SystemModelSimulateSensitivity", + "SystemModelSimulationData", + "SystemOpen", + "SystemOptions", + "SystemProcessData", + "SystemProcesses", + "SystemsConnectionsModel", + "SystemsModelDelay", + "SystemsModelDelayApproximate", + "SystemsModelDelete", + "SystemsModelDimensions", + "SystemsModelExtract", + "SystemsModelFeedbackConnect", + "SystemsModelLabels", + "SystemsModelLinearity", + "SystemsModelMerge", + "SystemsModelOrder", + "SystemsModelParallelConnect", + "SystemsModelSeriesConnect", + "SystemsModelStateFeedbackConnect", + "SystemsModelVectorRelativeOrders", + "SystemStub", + "SystemTest", + "Tab", + "TabFilling", + "Table", + "TableAlignments", + "TableDepth", + "TableDirections", + "TableForm", + "TableHeadings", + "TableSpacing", + "TableView", + "TableViewBox", + "TableViewBoxBackground", + "TableViewBoxItemSize", + "TableViewBoxOptions", + "TabSpacings", + "TabView", + "TabViewBox", + "TabViewBoxOptions", + "TagBox", + "TagBoxNote", + "TagBoxOptions", + "TaggingRules", + "TagSet", + "TagSetDelayed", + "TagStyle", + "TagUnset", + "Take", + "TakeDrop", + "TakeLargest", + "TakeLargestBy", + "TakeList", + "TakeSmallest", + "TakeSmallestBy", + "TakeWhile", + "Tally", + "Tan", + "Tanh", + "TargetDevice", + "TargetFunctions", + "TargetSystem", + "TargetUnits", + "TaskAbort", + "TaskExecute", + "TaskObject", + "TaskRemove", + "TaskResume", + "Tasks", + "TaskSuspend", + "TaskWait", + "TautologyQ", + "TelegraphProcess", + "TemplateApply", + "TemplateArgBox", + "TemplateBox", + "TemplateBoxOptions", + "TemplateEvaluate", + "TemplateExpression", + "TemplateIf", + "TemplateObject", + "TemplateSequence", + "TemplateSlot", + "TemplateSlotSequence", + "TemplateUnevaluated", + "TemplateVerbatim", + "TemplateWith", + "TemporalData", + "TemporalRegularity", + "Temporary", + "TemporaryVariable", + "TensorContract", + "TensorDimensions", + "TensorExpand", + "TensorProduct", + "TensorQ", + "TensorRank", + "TensorReduce", + "TensorSymmetry", + "TensorTranspose", + "TensorWedge", + "TestID", + "TestReport", + "TestReportObject", + "TestResultObject", + "Tetrahedron", + "TetrahedronBox", + "TetrahedronBoxOptions", + "TeXForm", + "TeXSave", + "Text", + "Text3DBox", + "Text3DBoxOptions", + "TextAlignment", + "TextBand", + "TextBoundingBox", + "TextBox", + "TextCases", + "TextCell", + "TextClipboardType", + "TextContents", + "TextData", + "TextElement", + "TextForm", + "TextGrid", + "TextJustification", + "TextLine", + "TextPacket", + "TextParagraph", + "TextPosition", + "TextRecognize", + "TextSearch", + "TextSearchReport", + "TextSentences", + "TextString", + "TextStructure", + "TextStyle", + "TextTranslation", + "Texture", + "TextureCoordinateFunction", + "TextureCoordinateScaling", + "TextWords", + "Therefore", + "ThermodynamicData", + "ThermometerGauge", + "Thick", + "Thickness", + "Thin", + "Thinning", + "ThisLink", + "ThompsonGroupTh", + "Thread", + "ThreadingLayer", + "ThreeJSymbol", + "Threshold", + "Through", + "Throw", + "ThueMorse", + "Thumbnail", + "Thursday", + "Ticks", + "TicksStyle", + "TideData", + "Tilde", + "TildeEqual", + "TildeFullEqual", + "TildeTilde", + "TimeConstrained", + "TimeConstraint", + "TimeDirection", + "TimeFormat", + "TimeGoal", + "TimelinePlot", + "TimeObject", + "TimeObjectQ", + "TimeRemaining", + "Times", + "TimesBy", + "TimeSeries", + "TimeSeriesAggregate", + "TimeSeriesForecast", + "TimeSeriesInsert", + "TimeSeriesInvertibility", + "TimeSeriesMap", + "TimeSeriesMapThread", + "TimeSeriesModel", + "TimeSeriesModelFit", + "TimeSeriesResample", + "TimeSeriesRescale", + "TimeSeriesShift", + "TimeSeriesThread", + "TimeSeriesWindow", + "TimeUsed", + "TimeValue", + "TimeWarpingCorrespondence", + "TimeWarpingDistance", + "TimeZone", + "TimeZoneConvert", + "TimeZoneOffset", + "Timing", + "Tiny", + "TitleGrouping", + "TitsGroupT", + "ToBoxes", + "ToCharacterCode", + "ToColor", + "ToContinuousTimeModel", + "ToDate", + "Today", + "ToDiscreteTimeModel", + "ToEntity", + "ToeplitzMatrix", + "ToExpression", + "ToFileName", + "Together", + "Toggle", + "ToggleFalse", + "Toggler", + "TogglerBar", + "TogglerBox", + "TogglerBoxOptions", + "ToHeldExpression", + "ToInvertibleTimeSeries", + "TokenWords", + "Tolerance", + "ToLowerCase", + "Tomorrow", + "ToNumberField", + "TooBig", + "Tooltip", + "TooltipBox", + "TooltipBoxOptions", + "TooltipDelay", + "TooltipStyle", + "ToonShading", + "Top", + "TopHatTransform", + "ToPolarCoordinates", + "TopologicalSort", + "ToRadicals", + "ToRules", + "ToSphericalCoordinates", + "ToString", + "Total", + "TotalHeight", + "TotalLayer", + "TotalVariationFilter", + "TotalWidth", + "TouchPosition", + "TouchscreenAutoZoom", + "TouchscreenControlPlacement", + "ToUpperCase", + "Tr", + "Trace", + "TraceAbove", + "TraceAction", + "TraceBackward", + "TraceDepth", + "TraceDialog", + "TraceForward", + "TraceInternal", + "TraceLevel", + "TraceOff", + "TraceOn", + "TraceOriginal", + "TracePrint", + "TraceScan", + "TrackedSymbols", + "TrackingFunction", + "TracyWidomDistribution", + "TradingChart", + "TraditionalForm", + "TraditionalFunctionNotation", + "TraditionalNotation", + "TraditionalOrder", + "TrainingProgressCheckpointing", + "TrainingProgressFunction", + "TrainingProgressMeasurements", + "TrainingProgressReporting", + "TrainingStoppingCriterion", + "TrainingUpdateSchedule", + "TransferFunctionCancel", + "TransferFunctionExpand", + "TransferFunctionFactor", + "TransferFunctionModel", + "TransferFunctionPoles", + "TransferFunctionTransform", + "TransferFunctionZeros", + "TransformationClass", + "TransformationFunction", + "TransformationFunctions", + "TransformationMatrix", + "TransformedDistribution", + "TransformedField", + "TransformedProcess", + "TransformedRegion", + "TransitionDirection", + "TransitionDuration", + "TransitionEffect", + "TransitiveClosureGraph", + "TransitiveReductionGraph", + "Translate", + "TranslationOptions", + "TranslationTransform", + "Transliterate", + "Transparent", + "TransparentColor", + "Transpose", + "TransposeLayer", + "TrapSelection", + "TravelDirections", + "TravelDirectionsData", + "TravelDistance", + "TravelDistanceList", + "TravelMethod", + "TravelTime", + "TreeForm", + "TreeGraph", + "TreeGraphQ", + "TreePlot", + "TrendStyle", + "Triangle", + "TriangleCenter", + "TriangleConstruct", + "TriangleMeasurement", + "TriangleWave", + "TriangularDistribution", + "TriangulateMesh", + "Trig", + "TrigExpand", + "TrigFactor", + "TrigFactorList", + "Trigger", + "TrigReduce", + "TrigToExp", + "TrimmedMean", + "TrimmedVariance", + "TropicalStormData", + "True", + "TrueQ", + "TruncatedDistribution", + "TruncatedPolyhedron", + "TsallisQExponentialDistribution", + "TsallisQGaussianDistribution", + "TTest", + "Tube", + "TubeBezierCurveBox", + "TubeBezierCurveBoxOptions", + "TubeBox", + "TubeBoxOptions", + "TubeBSplineCurveBox", + "TubeBSplineCurveBoxOptions", + "Tuesday", + "TukeyLambdaDistribution", + "TukeyWindow", + "TunnelData", + "Tuples", + "TuranGraph", + "TuringMachine", + "TuttePolynomial", + "TwoWayRule", + "Typed", + "TypeSpecifier", + "UnateQ", + "Uncompress", + "UnconstrainedParameters", + "Undefined", + "UnderBar", + "Underflow", + "Underlined", + "Underoverscript", + "UnderoverscriptBox", + "UnderoverscriptBoxOptions", + "Underscript", + "UnderscriptBox", + "UnderscriptBoxOptions", + "UnderseaFeatureData", + "UndirectedEdge", + "UndirectedGraph", + "UndirectedGraphQ", + "UndoOptions", + "UndoTrackedVariables", + "Unequal", + "UnequalTo", + "Unevaluated", + "UniformDistribution", + "UniformGraphDistribution", + "UniformPolyhedron", + "UniformSumDistribution", + "Uninstall", + "Union", + "UnionedEntityClass", + "UnionPlus", + "Unique", + "UnitaryMatrixQ", + "UnitBox", + "UnitConvert", + "UnitDimensions", + "Unitize", + "UnitRootTest", + "UnitSimplify", + "UnitStep", + "UnitSystem", + "UnitTriangle", + "UnitVector", + "UnitVectorLayer", + "UnityDimensions", + "UniverseModelData", + "UniversityData", + "UnixTime", + "Unprotect", + "UnregisterExternalEvaluator", + "UnsameQ", + "UnsavedVariables", + "Unset", + "UnsetShared", + "UntrackedVariables", + "Up", + "UpArrow", + "UpArrowBar", + "UpArrowDownArrow", + "Update", + "UpdateDynamicObjects", + "UpdateDynamicObjectsSynchronous", + "UpdateInterval", + "UpdatePacletSites", + "UpdateSearchIndex", + "UpDownArrow", + "UpEquilibrium", + "UpperCaseQ", + "UpperLeftArrow", + "UpperRightArrow", + "UpperTriangularize", + "UpperTriangularMatrixQ", + "Upsample", + "UpSet", + "UpSetDelayed", + "UpTee", + "UpTeeArrow", + "UpTo", + "UpValues", + "URL", + "URLBuild", + "URLDecode", + "URLDispatcher", + "URLDownload", + "URLDownloadSubmit", + "URLEncode", + "URLExecute", + "URLExpand", + "URLFetch", + "URLFetchAsynchronous", + "URLParse", + "URLQueryDecode", + "URLQueryEncode", + "URLRead", + "URLResponseTime", + "URLSave", + "URLSaveAsynchronous", + "URLShorten", + "URLSubmit", + "UseGraphicsRange", + "UserDefinedWavelet", + "Using", + "UsingFrontEnd", + "UtilityFunction", + "V2Get", + "ValenceErrorHandling", + "ValidationLength", + "ValidationSet", + "Value", + "ValueBox", + "ValueBoxOptions", + "ValueDimensions", + "ValueForm", + "ValuePreprocessingFunction", + "ValueQ", + "Values", + "ValuesData", + "Variables", + "Variance", + "VarianceEquivalenceTest", + "VarianceEstimatorFunction", + "VarianceGammaDistribution", + "VarianceTest", + "VectorAngle", + "VectorAround", + "VectorAspectRatio", + "VectorColorFunction", + "VectorColorFunctionScaling", + "VectorDensityPlot", + "VectorGlyphData", + "VectorGreater", + "VectorGreaterEqual", + "VectorLess", + "VectorLessEqual", + "VectorMarkers", + "VectorPlot", + "VectorPlot3D", + "VectorPoints", + "VectorQ", + "VectorRange", + "Vectors", + "VectorScale", + "VectorScaling", + "VectorSizes", + "VectorStyle", + "Vee", + "Verbatim", + "Verbose", + "VerboseConvertToPostScriptPacket", + "VerificationTest", + "VerifyConvergence", + "VerifyDerivedKey", + "VerifyDigitalSignature", + "VerifyFileSignature", + "VerifyInterpretation", + "VerifySecurityCertificates", + "VerifySolutions", + "VerifyTestAssumptions", + "Version", + "VersionedPreferences", + "VersionNumber", + "VertexAdd", + "VertexCapacity", + "VertexColors", + "VertexComponent", + "VertexConnectivity", + "VertexContract", + "VertexCoordinateRules", + "VertexCoordinates", + "VertexCorrelationSimilarity", + "VertexCosineSimilarity", + "VertexCount", + "VertexCoverQ", + "VertexDataCoordinates", + "VertexDegree", + "VertexDelete", + "VertexDiceSimilarity", + "VertexEccentricity", + "VertexInComponent", + "VertexInDegree", + "VertexIndex", + "VertexJaccardSimilarity", + "VertexLabeling", + "VertexLabels", + "VertexLabelStyle", + "VertexList", + "VertexNormals", + "VertexOutComponent", + "VertexOutDegree", + "VertexQ", + "VertexRenderingFunction", + "VertexReplace", + "VertexShape", + "VertexShapeFunction", + "VertexSize", + "VertexStyle", + "VertexTextureCoordinates", + "VertexWeight", + "VertexWeightedGraphQ", + "Vertical", + "VerticalBar", + "VerticalForm", + "VerticalGauge", + "VerticalSeparator", + "VerticalSlider", + "VerticalTilde", + "Video", + "VideoEncoding", + "VideoExtractFrames", + "VideoFrameList", + "VideoFrameMap", + "VideoPause", + "VideoPlay", + "VideoQ", + "VideoStop", + "VideoStream", + "VideoStreams", + "VideoTimeSeries", + "VideoTracks", + "VideoTrim", + "ViewAngle", + "ViewCenter", + "ViewMatrix", + "ViewPoint", + "ViewPointSelectorSettings", + "ViewPort", + "ViewProjection", + "ViewRange", + "ViewVector", + "ViewVertical", + "VirtualGroupData", + "Visible", + "VisibleCell", + "VoiceStyleData", + "VoigtDistribution", + "VolcanoData", + "Volume", + "VonMisesDistribution", + "VoronoiMesh", + "WaitAll", + "WaitAsynchronousTask", + "WaitNext", + "WaitUntil", + "WakebyDistribution", + "WalleniusHypergeometricDistribution", + "WaringYuleDistribution", + "WarpingCorrespondence", + "WarpingDistance", + "WatershedComponents", + "WatsonUSquareTest", + "WattsStrogatzGraphDistribution", + "WaveletBestBasis", + "WaveletFilterCoefficients", + "WaveletImagePlot", + "WaveletListPlot", + "WaveletMapIndexed", + "WaveletMatrixPlot", + "WaveletPhi", + "WaveletPsi", + "WaveletScale", + "WaveletScalogram", + "WaveletThreshold", + "WeaklyConnectedComponents", + "WeaklyConnectedGraphComponents", + "WeaklyConnectedGraphQ", + "WeakStationarity", + "WeatherData", + "WeatherForecastData", + "WebAudioSearch", + "WebElementObject", + "WeberE", + "WebExecute", + "WebImage", + "WebImageSearch", + "WebSearch", + "WebSessionObject", + "WebSessions", + "WebWindowObject", + "Wedge", + "Wednesday", + "WeibullDistribution", + "WeierstrassE1", + "WeierstrassE2", + "WeierstrassE3", + "WeierstrassEta1", + "WeierstrassEta2", + "WeierstrassEta3", + "WeierstrassHalfPeriods", + "WeierstrassHalfPeriodW1", + "WeierstrassHalfPeriodW2", + "WeierstrassHalfPeriodW3", + "WeierstrassInvariantG2", + "WeierstrassInvariantG3", + "WeierstrassInvariants", + "WeierstrassP", + "WeierstrassPPrime", + "WeierstrassSigma", + "WeierstrassZeta", + "WeightedAdjacencyGraph", + "WeightedAdjacencyMatrix", + "WeightedData", + "WeightedGraphQ", + "Weights", + "WelchWindow", + "WheelGraph", + "WhenEvent", + "Which", + "While", + "White", + "WhiteNoiseProcess", + "WhitePoint", + "Whitespace", + "WhitespaceCharacter", + "WhittakerM", + "WhittakerW", + "WienerFilter", + "WienerProcess", + "WignerD", + "WignerSemicircleDistribution", + "WikidataData", + "WikidataSearch", + "WikipediaData", + "WikipediaSearch", + "WilksW", + "WilksWTest", + "WindDirectionData", + "WindingCount", + "WindingPolygon", + "WindowClickSelect", + "WindowElements", + "WindowFloating", + "WindowFrame", + "WindowFrameElements", + "WindowMargins", + "WindowMovable", + "WindowOpacity", + "WindowPersistentStyles", + "WindowSelected", + "WindowSize", + "WindowStatusArea", + "WindowTitle", + "WindowToolbars", + "WindowWidth", + "WindSpeedData", + "WindVectorData", + "WinsorizedMean", + "WinsorizedVariance", + "WishartMatrixDistribution", + "With", + "WolframAlpha", + "WolframAlphaDate", + "WolframAlphaQuantity", + "WolframAlphaResult", + "WolframLanguageData", + "Word", + "WordBoundary", + "WordCharacter", + "WordCloud", + "WordCount", + "WordCounts", + "WordData", + "WordDefinition", + "WordFrequency", + "WordFrequencyData", + "WordList", + "WordOrientation", + "WordSearch", + "WordSelectionFunction", + "WordSeparators", + "WordSpacings", + "WordStem", + "WordTranslation", + "WorkingPrecision", + "WrapAround", + "Write", + "WriteLine", + "WriteString", + "Wronskian", + "XMLElement", + "XMLObject", + "XMLTemplate", + "Xnor", + "Xor", + "XYZColor", + "Yellow", + "Yesterday", + "YuleDissimilarity", + "ZernikeR", + "ZeroSymmetric", + "ZeroTest", + "ZeroWidthTimes", + "Zeta", + "ZetaZero", + "ZIPCodeData", + "ZipfDistribution", + "ZoomCenter", + "ZoomFactor", + "ZTest", + "ZTransform", + "$Aborted", + "$ActivationGroupID", + "$ActivationKey", + "$ActivationUserRegistered", + "$AddOnsDirectory", + "$AllowDataUpdates", + "$AllowExternalChannelFunctions", + "$AllowInternet", + "$AssertFunction", + "$Assumptions", + "$AsynchronousTask", + "$AudioDecoders", + "$AudioEncoders", + "$AudioInputDevices", + "$AudioOutputDevices", + "$BaseDirectory", + "$BasePacletsDirectory", + "$BatchInput", + "$BatchOutput", + "$BlockchainBase", + "$BoxForms", + "$ByteOrdering", + "$CacheBaseDirectory", + "$Canceled", + "$ChannelBase", + "$CharacterEncoding", + "$CharacterEncodings", + "$CloudAccountName", + "$CloudBase", + "$CloudConnected", + "$CloudConnection", + "$CloudCreditsAvailable", + "$CloudEvaluation", + "$CloudExpressionBase", + "$CloudObjectNameFormat", + "$CloudObjectURLType", + "$CloudRootDirectory", + "$CloudSymbolBase", + "$CloudUserID", + "$CloudUserUUID", + "$CloudVersion", + "$CloudVersionNumber", + "$CloudWolframEngineVersionNumber", + "$CommandLine", + "$CompilationTarget", + "$ConditionHold", + "$ConfiguredKernels", + "$Context", + "$ContextPath", + "$ControlActiveSetting", + "$Cookies", + "$CookieStore", + "$CreationDate", + "$CurrentLink", + "$CurrentTask", + "$CurrentWebSession", + "$DataStructures", + "$DateStringFormat", + "$DefaultAudioInputDevice", + "$DefaultAudioOutputDevice", + "$DefaultFont", + "$DefaultFrontEnd", + "$DefaultImagingDevice", + "$DefaultLocalBase", + "$DefaultMailbox", + "$DefaultNetworkInterface", + "$DefaultPath", + "$DefaultProxyRules", + "$DefaultSystemCredentialStore", + "$Display", + "$DisplayFunction", + "$DistributedContexts", + "$DynamicEvaluation", + "$Echo", + "$EmbedCodeEnvironments", + "$EmbeddableServices", + "$EntityStores", + "$Epilog", + "$EvaluationCloudBase", + "$EvaluationCloudObject", + "$EvaluationEnvironment", + "$ExportFormats", + "$ExternalIdentifierTypes", + "$ExternalStorageBase", + "$Failed", + "$FinancialDataSource", + "$FontFamilies", + "$FormatType", + "$FrontEnd", + "$FrontEndSession", + "$GeoEntityTypes", + "$GeoLocation", + "$GeoLocationCity", + "$GeoLocationCountry", + "$GeoLocationPrecision", + "$GeoLocationSource", + "$HistoryLength", + "$HomeDirectory", + "$HTMLExportRules", + "$HTTPCookies", + "$HTTPRequest", + "$IgnoreEOF", + "$ImageFormattingWidth", + "$ImageResolution", + "$ImagingDevice", + "$ImagingDevices", + "$ImportFormats", + "$IncomingMailSettings", + "$InitialDirectory", + "$Initialization", + "$InitializationContexts", + "$Input", + "$InputFileName", + "$InputStreamMethods", + "$Inspector", + "$InstallationDate", + "$InstallationDirectory", + "$InterfaceEnvironment", + "$InterpreterTypes", + "$IterationLimit", + "$KernelCount", + "$KernelID", + "$Language", + "$LaunchDirectory", + "$LibraryPath", + "$LicenseExpirationDate", + "$LicenseID", + "$LicenseProcesses", + "$LicenseServer", + "$LicenseSubprocesses", + "$LicenseType", + "$Line", + "$Linked", + "$LinkSupported", + "$LoadedFiles", + "$LocalBase", + "$LocalSymbolBase", + "$MachineAddresses", + "$MachineDomain", + "$MachineDomains", + "$MachineEpsilon", + "$MachineID", + "$MachineName", + "$MachinePrecision", + "$MachineType", + "$MaxExtraPrecision", + "$MaxLicenseProcesses", + "$MaxLicenseSubprocesses", + "$MaxMachineNumber", + "$MaxNumber", + "$MaxPiecewiseCases", + "$MaxPrecision", + "$MaxRootDegree", + "$MessageGroups", + "$MessageList", + "$MessagePrePrint", + "$Messages", + "$MinMachineNumber", + "$MinNumber", + "$MinorReleaseNumber", + "$MinPrecision", + "$MobilePhone", + "$ModuleNumber", + "$NetworkConnected", + "$NetworkInterfaces", + "$NetworkLicense", + "$NewMessage", + "$NewSymbol", + "$NotebookInlineStorageLimit", + "$Notebooks", + "$NoValue", + "$NumberMarks", + "$Off", + "$OperatingSystem", + "$Output", + "$OutputForms", + "$OutputSizeLimit", + "$OutputStreamMethods", + "$Packages", + "$ParentLink", + "$ParentProcessID", + "$PasswordFile", + "$PatchLevelID", + "$Path", + "$PathnameSeparator", + "$PerformanceGoal", + "$Permissions", + "$PermissionsGroupBase", + "$PersistenceBase", + "$PersistencePath", + "$PipeSupported", + "$PlotTheme", + "$Post", + "$Pre", + "$PreferencesDirectory", + "$PreInitialization", + "$PrePrint", + "$PreRead", + "$PrintForms", + "$PrintLiteral", + "$Printout3DPreviewer", + "$ProcessID", + "$ProcessorCount", + "$ProcessorType", + "$ProductInformation", + "$ProgramName", + "$PublisherID", + "$RandomState", + "$RecursionLimit", + "$RegisteredDeviceClasses", + "$RegisteredUserName", + "$ReleaseNumber", + "$RequesterAddress", + "$RequesterWolframID", + "$RequesterWolframUUID", + "$RootDirectory", + "$ScheduledTask", + "$ScriptCommandLine", + "$ScriptInputString", + "$SecuredAuthenticationKeyTokens", + "$ServiceCreditsAvailable", + "$Services", + "$SessionID", + "$SetParentLink", + "$SharedFunctions", + "$SharedVariables", + "$SoundDisplay", + "$SoundDisplayFunction", + "$SourceLink", + "$SSHAuthentication", + "$SubtitleDecoders", + "$SubtitleEncoders", + "$SummaryBoxDataSizeLimit", + "$SuppressInputFormHeads", + "$SynchronousEvaluation", + "$SyntaxHandler", + "$System", + "$SystemCharacterEncoding", + "$SystemCredentialStore", + "$SystemID", + "$SystemMemory", + "$SystemShell", + "$SystemTimeZone", + "$SystemWordLength", + "$TemplatePath", + "$TemporaryDirectory", + "$TemporaryPrefix", + "$TestFileName", + "$TextStyle", + "$TimedOut", + "$TimeUnit", + "$TimeZone", + "$TimeZoneEntity", + "$TopDirectory", + "$TraceOff", + "$TraceOn", + "$TracePattern", + "$TracePostAction", + "$TracePreAction", + "$UnitSystem", + "$Urgent", + "$UserAddOnsDirectory", + "$UserAgentLanguages", + "$UserAgentMachine", + "$UserAgentName", + "$UserAgentOperatingSystem", + "$UserAgentString", + "$UserAgentVersion", + "$UserBaseDirectory", + "$UserBasePacletsDirectory", + "$UserDocumentsDirectory", + "$Username", + "$UserName", + "$UserURLBase", + "$Version", + "$VersionNumber", + "$VideoDecoders", + "$VideoEncoders", + "$VoiceStyles", + "$WolframDocumentsDirectory", + "$WolframID", + "$WolframUUID" +]; + +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function optional(re) { + return concat('(', re, ')?'); +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/** + * Any of the passed expresssions may match + * + * Creates a huge this | this | that | that match + * @param {(RegExp | string)[] } args + * @returns {string} + */ +function either(...args) { + const joined = '(' + args.map((x) => source(x)).join("|") + ")"; + return joined; +} + +/* +Language: Wolfram Language +Description: The Wolfram Language is the programming language used in Wolfram Mathematica, a modern technical computing system spanning most areas of technical computing. +Authors: Patrick Scheibe , Robert Jacobson +Website: https://www.wolfram.com/mathematica/ +Category: scientific +*/ + +/** @type LanguageFn */ +function mathematica(hljs) { + /* + This rather scary looking matching of Mathematica numbers is carefully explained by Robert Jacobson here: + https://wltools.github.io/LanguageSpec/Specification/Syntax/Number-representations/ + */ + const BASE_RE = /([2-9]|[1-2]\d|[3][0-5])\^\^/; + const BASE_DIGITS_RE = /(\w*\.\w+|\w+\.\w*|\w+)/; + const NUMBER_RE = /(\d*\.\d+|\d+\.\d*|\d+)/; + const BASE_NUMBER_RE = either(concat(BASE_RE, BASE_DIGITS_RE), NUMBER_RE); + + const ACCURACY_RE = /``[+-]?(\d*\.\d+|\d+\.\d*|\d+)/; + const PRECISION_RE = /`([+-]?(\d*\.\d+|\d+\.\d*|\d+))?/; + const APPROXIMATE_NUMBER_RE = either(ACCURACY_RE, PRECISION_RE); + + const SCIENTIFIC_NOTATION_RE = /\*\^[+-]?\d+/; + + const MATHEMATICA_NUMBER_RE = concat( + BASE_NUMBER_RE, + optional(APPROXIMATE_NUMBER_RE), + optional(SCIENTIFIC_NOTATION_RE) + ); + + const NUMBERS = { + className: 'number', + relevance: 0, + begin: MATHEMATICA_NUMBER_RE + }; + + const SYMBOL_RE = /[a-zA-Z$][a-zA-Z0-9$]*/; + const SYSTEM_SYMBOLS_SET = new Set(SYSTEM_SYMBOLS); + /** @type {Mode} */ + const SYMBOLS = { + variants: [ + { + className: 'builtin-symbol', + begin: SYMBOL_RE, + // for performance out of fear of regex.either(...Mathematica.SYSTEM_SYMBOLS) + "on:begin": (match, response) => { + if (!SYSTEM_SYMBOLS_SET.has(match[0])) response.ignoreMatch(); + } + }, + { + className: 'symbol', + relevance: 0, + begin: SYMBOL_RE + } + ] + }; + + const NAMED_CHARACTER = { + className: 'named-character', + begin: /\\\[[$a-zA-Z][$a-zA-Z0-9]+\]/ + }; + + const OPERATORS = { + className: 'operator', + relevance: 0, + begin: /[+\-*/,;.:@~=><&|_`'^?!%]+/ + }; + const PATTERNS = { + className: 'pattern', + relevance: 0, + begin: /([a-zA-Z$][a-zA-Z0-9$]*)?_+([a-zA-Z$][a-zA-Z0-9$]*)?/ + }; + + const SLOTS = { + className: 'slot', + relevance: 0, + begin: /#[a-zA-Z$][a-zA-Z0-9$]*|#+[0-9]?/ + }; + + const BRACES = { + className: 'brace', + relevance: 0, + begin: /[[\](){}]/ + }; + + const MESSAGES = { + className: 'message-name', + relevance: 0, + begin: concat("::", SYMBOL_RE) + }; + + return { + name: 'Mathematica', + aliases: [ + 'mma', + 'wl' + ], + classNameAliases: { + brace: 'punctuation', + pattern: 'type', + slot: 'type', + symbol: 'variable', + 'named-character': 'variable', + 'builtin-symbol': 'built_in', + 'message-name': 'string' + }, + contains: [ + hljs.COMMENT(/\(\*/, /\*\)/, { + contains: [ 'self' ] + }), + PATTERNS, + SLOTS, + MESSAGES, + SYMBOLS, + NAMED_CHARACTER, + hljs.QUOTE_STRING_MODE, + NUMBERS, + OPERATORS, + BRACES + ] + }; +} + +module.exports = mathematica; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/matlab.js b/claude-code-source/node_modules/highlight.js/lib/languages/matlab.js new file mode 100644 index 00000000..af05c3d7 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/matlab.js @@ -0,0 +1,106 @@ +/* +Language: Matlab +Author: Denis Bardadym +Contributors: Eugene Nizhibitsky , Egor Rogov +Website: https://www.mathworks.com/products/matlab.html +Category: scientific +*/ + +/* + Formal syntax is not published, helpful link: + https://github.com/kornilova-l/matlab-IntelliJ-plugin/blob/master/src/main/grammar/Matlab.bnf +*/ +function matlab(hljs) { + + var TRANSPOSE_RE = '(\'|\\.\')+'; + var TRANSPOSE = { + relevance: 0, + contains: [ + { begin: TRANSPOSE_RE } + ] + }; + + return { + name: 'Matlab', + keywords: { + keyword: + 'arguments break case catch classdef continue else elseif end enumeration events for function ' + + 'global if methods otherwise parfor persistent properties return spmd switch try while', + built_in: + 'sin sind sinh asin asind asinh cos cosd cosh acos acosd acosh tan tand tanh atan ' + + 'atand atan2 atanh sec secd sech asec asecd asech csc cscd csch acsc acscd acsch cot ' + + 'cotd coth acot acotd acoth hypot exp expm1 log log1p log10 log2 pow2 realpow reallog ' + + 'realsqrt sqrt nthroot nextpow2 abs angle complex conj imag real unwrap isreal ' + + 'cplxpair fix floor ceil round mod rem sign airy besselj bessely besselh besseli ' + + 'besselk beta betainc betaln ellipj ellipke erf erfc erfcx erfinv expint gamma ' + + 'gammainc gammaln psi legendre cross dot factor isprime primes gcd lcm rat rats perms ' + + 'nchoosek factorial cart2sph cart2pol pol2cart sph2cart hsv2rgb rgb2hsv zeros ones ' + + 'eye repmat rand randn linspace logspace freqspace meshgrid accumarray size length ' + + 'ndims numel disp isempty isequal isequalwithequalnans cat reshape diag blkdiag tril ' + + 'triu fliplr flipud flipdim rot90 find sub2ind ind2sub bsxfun ndgrid permute ipermute ' + + 'shiftdim circshift squeeze isscalar isvector ans eps realmax realmin pi i|0 inf nan ' + + 'isnan isinf isfinite j|0 why compan gallery hadamard hankel hilb invhilb magic pascal ' + + 'rosser toeplitz vander wilkinson max min nanmax nanmin mean nanmean type table ' + + 'readtable writetable sortrows sort figure plot plot3 scatter scatter3 cellfun ' + + 'legend intersect ismember procrustes hold num2cell ' + }, + illegal: '(//|"|#|/\\*|\\s+/\\w+)', + contains: [ + { + className: 'function', + beginKeywords: 'function', end: '$', + contains: [ + hljs.UNDERSCORE_TITLE_MODE, + { + className: 'params', + variants: [ + {begin: '\\(', end: '\\)'}, + {begin: '\\[', end: '\\]'} + ] + } + ] + }, + { + className: 'built_in', + begin: /true|false/, + relevance: 0, + starts: TRANSPOSE + }, + { + begin: '[a-zA-Z][a-zA-Z_0-9]*' + TRANSPOSE_RE, + relevance: 0 + }, + { + className: 'number', + begin: hljs.C_NUMBER_RE, + relevance: 0, + starts: TRANSPOSE + }, + { + className: 'string', + begin: '\'', end: '\'', + contains: [ + hljs.BACKSLASH_ESCAPE, + {begin: '\'\''}] + }, + { + begin: /\]|\}|\)/, + relevance: 0, + starts: TRANSPOSE + }, + { + className: 'string', + begin: '"', end: '"', + contains: [ + hljs.BACKSLASH_ESCAPE, + {begin: '""'} + ], + starts: TRANSPOSE + }, + hljs.COMMENT('^\\s*%\\{\\s*$', '^\\s*%\\}\\s*$'), + hljs.COMMENT('%', '$') + ] + }; +} + +module.exports = matlab; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/maxima.js b/claude-code-source/node_modules/highlight.js/lib/languages/maxima.js new file mode 100644 index 00000000..d0b210aa --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/maxima.js @@ -0,0 +1,417 @@ +/* +Language: Maxima +Author: Robert Dodier +Website: http://maxima.sourceforge.net +Category: scientific +*/ + +function maxima(hljs) { + const KEYWORDS = + 'if then else elseif for thru do while unless step in and or not'; + const LITERALS = + 'true false unknown inf minf ind und %e %i %pi %phi %gamma'; + const BUILTIN_FUNCTIONS = + ' abasep abs absint absolute_real_time acos acosh acot acoth acsc acsch activate' + + ' addcol add_edge add_edges addmatrices addrow add_vertex add_vertices adjacency_matrix' + + ' adjoin adjoint af agd airy airy_ai airy_bi airy_dai airy_dbi algsys alg_type' + + ' alias allroots alphacharp alphanumericp amortization %and annuity_fv' + + ' annuity_pv antid antidiff AntiDifference append appendfile apply apply1 apply2' + + ' applyb1 apropos args arit_amortization arithmetic arithsum array arrayapply' + + ' arrayinfo arraymake arraysetapply ascii asec asech asin asinh askinteger' + + ' asksign assoc assoc_legendre_p assoc_legendre_q assume assume_external_byte_order' + + ' asympa at atan atan2 atanh atensimp atom atvalue augcoefmatrix augmented_lagrangian_method' + + ' av average_degree backtrace bars barsplot barsplot_description base64 base64_decode' + + ' bashindices batch batchload bc2 bdvac belln benefit_cost bern bernpoly bernstein_approx' + + ' bernstein_expand bernstein_poly bessel bessel_i bessel_j bessel_k bessel_simplify' + + ' bessel_y beta beta_incomplete beta_incomplete_generalized beta_incomplete_regularized' + + ' bezout bfallroots bffac bf_find_root bf_fmin_cobyla bfhzeta bfloat bfloatp' + + ' bfpsi bfpsi0 bfzeta biconnected_components bimetric binomial bipartition' + + ' block blockmatrixp bode_gain bode_phase bothcoef box boxplot boxplot_description' + + ' break bug_report build_info|10 buildq build_sample burn cabs canform canten' + + ' cardinality carg cartan cartesian_product catch cauchy_matrix cbffac cdf_bernoulli' + + ' cdf_beta cdf_binomial cdf_cauchy cdf_chi2 cdf_continuous_uniform cdf_discrete_uniform' + + ' cdf_exp cdf_f cdf_gamma cdf_general_finite_discrete cdf_geometric cdf_gumbel' + + ' cdf_hypergeometric cdf_laplace cdf_logistic cdf_lognormal cdf_negative_binomial' + + ' cdf_noncentral_chi2 cdf_noncentral_student_t cdf_normal cdf_pareto cdf_poisson' + + ' cdf_rank_sum cdf_rayleigh cdf_signed_rank cdf_student_t cdf_weibull cdisplay' + + ' ceiling central_moment cequal cequalignore cf cfdisrep cfexpand cgeodesic' + + ' cgreaterp cgreaterpignore changename changevar chaosgame charat charfun charfun2' + + ' charlist charp charpoly chdir chebyshev_t chebyshev_u checkdiv check_overlaps' + + ' chinese cholesky christof chromatic_index chromatic_number cint circulant_graph' + + ' clear_edge_weight clear_rules clear_vertex_label clebsch_gordan clebsch_graph' + + ' clessp clesspignore close closefile cmetric coeff coefmatrix cograd col collapse' + + ' collectterms columnop columnspace columnswap columnvector combination combine' + + ' comp2pui compare compfile compile compile_file complement_graph complete_bipartite_graph' + + ' complete_graph complex_number_p components compose_functions concan concat' + + ' conjugate conmetderiv connected_components connect_vertices cons constant' + + ' constantp constituent constvalue cont2part content continuous_freq contortion' + + ' contour_plot contract contract_edge contragrad contrib_ode convert coord' + + ' copy copy_file copy_graph copylist copymatrix cor cos cosh cot coth cov cov1' + + ' covdiff covect covers crc24sum create_graph create_list csc csch csetup cspline' + + ' ctaylor ct_coordsys ctransform ctranspose cube_graph cuboctahedron_graph' + + ' cunlisp cv cycle_digraph cycle_graph cylindrical days360 dblint deactivate' + + ' declare declare_constvalue declare_dimensions declare_fundamental_dimensions' + + ' declare_fundamental_units declare_qty declare_translated declare_unit_conversion' + + ' declare_units declare_weights decsym defcon define define_alt_display define_variable' + + ' defint defmatch defrule defstruct deftaylor degree_sequence del delete deleten' + + ' delta demo demoivre denom depends derivdegree derivlist describe desolve' + + ' determinant dfloat dgauss_a dgauss_b dgeev dgemm dgeqrf dgesv dgesvd diag' + + ' diagmatrix diag_matrix diagmatrixp diameter diff digitcharp dimacs_export' + + ' dimacs_import dimension dimensionless dimensions dimensions_as_list direct' + + ' directory discrete_freq disjoin disjointp disolate disp dispcon dispform' + + ' dispfun dispJordan display disprule dispterms distrib divide divisors divsum' + + ' dkummer_m dkummer_u dlange dodecahedron_graph dotproduct dotsimp dpart' + + ' draw draw2d draw3d drawdf draw_file draw_graph dscalar echelon edge_coloring' + + ' edge_connectivity edges eigens_by_jacobi eigenvalues eigenvectors eighth' + + ' einstein eivals eivects elapsed_real_time elapsed_run_time ele2comp ele2polynome' + + ' ele2pui elem elementp elevation_grid elim elim_allbut eliminate eliminate_using' + + ' ellipse elliptic_e elliptic_ec elliptic_eu elliptic_f elliptic_kc elliptic_pi' + + ' ematrix empty_graph emptyp endcons entermatrix entertensor entier equal equalp' + + ' equiv_classes erf erfc erf_generalized erfi errcatch error errormsg errors' + + ' euler ev eval_string evenp every evolution evolution2d evundiff example exp' + + ' expand expandwrt expandwrt_factored expint expintegral_chi expintegral_ci' + + ' expintegral_e expintegral_e1 expintegral_ei expintegral_e_simplify expintegral_li' + + ' expintegral_shi expintegral_si explicit explose exponentialize express expt' + + ' exsec extdiff extract_linear_equations extremal_subset ezgcd %f f90 facsum' + + ' factcomb factor factorfacsum factorial factorout factorsum facts fast_central_elements' + + ' fast_linsolve fasttimes featurep fernfale fft fib fibtophi fifth filename_merge' + + ' file_search file_type fillarray findde find_root find_root_abs find_root_error' + + ' find_root_rel first fix flatten flength float floatnump floor flower_snark' + + ' flush flush1deriv flushd flushnd flush_output fmin_cobyla forget fortran' + + ' fourcos fourexpand fourier fourier_elim fourint fourintcos fourintsin foursimp' + + ' foursin fourth fposition frame_bracket freeof freshline fresnel_c fresnel_s' + + ' from_adjacency_matrix frucht_graph full_listify fullmap fullmapl fullratsimp' + + ' fullratsubst fullsetify funcsolve fundamental_dimensions fundamental_units' + + ' fundef funmake funp fv g0 g1 gamma gamma_greek gamma_incomplete gamma_incomplete_generalized' + + ' gamma_incomplete_regularized gauss gauss_a gauss_b gaussprob gcd gcdex gcdivide' + + ' gcfac gcfactor gd generalized_lambert_w genfact gen_laguerre genmatrix gensym' + + ' geo_amortization geo_annuity_fv geo_annuity_pv geomap geometric geometric_mean' + + ' geosum get getcurrentdirectory get_edge_weight getenv get_lu_factors get_output_stream_string' + + ' get_pixel get_plot_option get_tex_environment get_tex_environment_default' + + ' get_vertex_label gfactor gfactorsum ggf girth global_variances gn gnuplot_close' + + ' gnuplot_replot gnuplot_reset gnuplot_restart gnuplot_start go Gosper GosperSum' + + ' gr2d gr3d gradef gramschmidt graph6_decode graph6_encode graph6_export graph6_import' + + ' graph_center graph_charpoly graph_eigenvalues graph_flow graph_order graph_periphery' + + ' graph_product graph_size graph_union great_rhombicosidodecahedron_graph great_rhombicuboctahedron_graph' + + ' grid_graph grind grobner_basis grotzch_graph hamilton_cycle hamilton_path' + + ' hankel hankel_1 hankel_2 harmonic harmonic_mean hav heawood_graph hermite' + + ' hessian hgfred hilbertmap hilbert_matrix hipow histogram histogram_description' + + ' hodge horner hypergeometric i0 i1 %ibes ic1 ic2 ic_convert ichr1 ichr2 icosahedron_graph' + + ' icosidodecahedron_graph icurvature ident identfor identity idiff idim idummy' + + ' ieqn %if ifactors iframes ifs igcdex igeodesic_coords ilt image imagpart' + + ' imetric implicit implicit_derivative implicit_plot indexed_tensor indices' + + ' induced_subgraph inferencep inference_result infix info_display init_atensor' + + ' init_ctensor in_neighbors innerproduct inpart inprod inrt integerp integer_partitions' + + ' integrate intersect intersection intervalp intopois intosum invariant1 invariant2' + + ' inverse_fft inverse_jacobi_cd inverse_jacobi_cn inverse_jacobi_cs inverse_jacobi_dc' + + ' inverse_jacobi_dn inverse_jacobi_ds inverse_jacobi_nc inverse_jacobi_nd inverse_jacobi_ns' + + ' inverse_jacobi_sc inverse_jacobi_sd inverse_jacobi_sn invert invert_by_adjoint' + + ' invert_by_lu inv_mod irr is is_biconnected is_bipartite is_connected is_digraph' + + ' is_edge_in_graph is_graph is_graph_or_digraph ishow is_isomorphic isolate' + + ' isomorphism is_planar isqrt isreal_p is_sconnected is_tree is_vertex_in_graph' + + ' items_inference %j j0 j1 jacobi jacobian jacobi_cd jacobi_cn jacobi_cs jacobi_dc' + + ' jacobi_dn jacobi_ds jacobi_nc jacobi_nd jacobi_ns jacobi_p jacobi_sc jacobi_sd' + + ' jacobi_sn JF jn join jordan julia julia_set julia_sin %k kdels kdelta kill' + + ' killcontext kostka kron_delta kronecker_product kummer_m kummer_u kurtosis' + + ' kurtosis_bernoulli kurtosis_beta kurtosis_binomial kurtosis_chi2 kurtosis_continuous_uniform' + + ' kurtosis_discrete_uniform kurtosis_exp kurtosis_f kurtosis_gamma kurtosis_general_finite_discrete' + + ' kurtosis_geometric kurtosis_gumbel kurtosis_hypergeometric kurtosis_laplace' + + ' kurtosis_logistic kurtosis_lognormal kurtosis_negative_binomial kurtosis_noncentral_chi2' + + ' kurtosis_noncentral_student_t kurtosis_normal kurtosis_pareto kurtosis_poisson' + + ' kurtosis_rayleigh kurtosis_student_t kurtosis_weibull label labels lagrange' + + ' laguerre lambda lambert_w laplace laplacian_matrix last lbfgs lc2kdt lcharp' + + ' lc_l lcm lc_u ldefint ldisp ldisplay legendre_p legendre_q leinstein length' + + ' let letrules letsimp levi_civita lfreeof lgtreillis lhs li liediff limit' + + ' Lindstedt linear linearinterpol linear_program linear_regression line_graph' + + ' linsolve listarray list_correlations listify list_matrix_entries list_nc_monomials' + + ' listoftens listofvars listp lmax lmin load loadfile local locate_matrix_entry' + + ' log logcontract log_gamma lopow lorentz_gauge lowercasep lpart lratsubst' + + ' lreduce lriemann lsquares_estimates lsquares_estimates_approximate lsquares_estimates_exact' + + ' lsquares_mse lsquares_residual_mse lsquares_residuals lsum ltreillis lu_backsub' + + ' lucas lu_factor %m macroexpand macroexpand1 make_array makebox makefact makegamma' + + ' make_graph make_level_picture makelist makeOrders make_poly_continent make_poly_country' + + ' make_polygon make_random_state make_rgb_picture makeset make_string_input_stream' + + ' make_string_output_stream make_transform mandelbrot mandelbrot_set map mapatom' + + ' maplist matchdeclare matchfix mat_cond mat_fullunblocker mat_function mathml_display' + + ' mat_norm matrix matrixmap matrixp matrix_size mattrace mat_trace mat_unblocker' + + ' max max_clique max_degree max_flow maximize_lp max_independent_set max_matching' + + ' maybe md5sum mean mean_bernoulli mean_beta mean_binomial mean_chi2 mean_continuous_uniform' + + ' mean_deviation mean_discrete_uniform mean_exp mean_f mean_gamma mean_general_finite_discrete' + + ' mean_geometric mean_gumbel mean_hypergeometric mean_laplace mean_logistic' + + ' mean_lognormal mean_negative_binomial mean_noncentral_chi2 mean_noncentral_student_t' + + ' mean_normal mean_pareto mean_poisson mean_rayleigh mean_student_t mean_weibull' + + ' median median_deviation member mesh metricexpandall mgf1_sha1 min min_degree' + + ' min_edge_cut minfactorial minimalPoly minimize_lp minimum_spanning_tree minor' + + ' minpack_lsquares minpack_solve min_vertex_cover min_vertex_cut mkdir mnewton' + + ' mod mode_declare mode_identity ModeMatrix moebius mon2schur mono monomial_dimensions' + + ' multibernstein_poly multi_display_for_texinfo multi_elem multinomial multinomial_coeff' + + ' multi_orbit multiplot_mode multi_pui multsym multthru mycielski_graph nary' + + ' natural_unit nc_degree ncexpt ncharpoly negative_picture neighbors new newcontext' + + ' newdet new_graph newline newton new_variable next_prime nicedummies niceindices' + + ' ninth nofix nonarray noncentral_moment nonmetricity nonnegintegerp nonscalarp' + + ' nonzeroandfreeof notequal nounify nptetrad npv nroots nterms ntermst' + + ' nthroot nullity nullspace num numbered_boundaries numberp number_to_octets' + + ' num_distinct_partitions numerval numfactor num_partitions nusum nzeta nzetai' + + ' nzetar octets_to_number octets_to_oid odd_girth oddp ode2 ode_check odelin' + + ' oid_to_octets op opena opena_binary openr openr_binary openw openw_binary' + + ' operatorp opsubst optimize %or orbit orbits ordergreat ordergreatp orderless' + + ' orderlessp orthogonal_complement orthopoly_recur orthopoly_weight outermap' + + ' out_neighbors outofpois pade parabolic_cylinder_d parametric parametric_surface' + + ' parg parGosper parse_string parse_timedate part part2cont partfrac partition' + + ' partition_set partpol path_digraph path_graph pathname_directory pathname_name' + + ' pathname_type pdf_bernoulli pdf_beta pdf_binomial pdf_cauchy pdf_chi2 pdf_continuous_uniform' + + ' pdf_discrete_uniform pdf_exp pdf_f pdf_gamma pdf_general_finite_discrete' + + ' pdf_geometric pdf_gumbel pdf_hypergeometric pdf_laplace pdf_logistic pdf_lognormal' + + ' pdf_negative_binomial pdf_noncentral_chi2 pdf_noncentral_student_t pdf_normal' + + ' pdf_pareto pdf_poisson pdf_rank_sum pdf_rayleigh pdf_signed_rank pdf_student_t' + + ' pdf_weibull pearson_skewness permanent permut permutation permutations petersen_graph' + + ' petrov pickapart picture_equalp picturep piechart piechart_description planar_embedding' + + ' playback plog plot2d plot3d plotdf ploteq plsquares pochhammer points poisdiff' + + ' poisexpt poisint poismap poisplus poissimp poissubst poistimes poistrim polar' + + ' polarform polartorect polar_to_xy poly_add poly_buchberger poly_buchberger_criterion' + + ' poly_colon_ideal poly_content polydecomp poly_depends_p poly_elimination_ideal' + + ' poly_exact_divide poly_expand poly_expt poly_gcd polygon poly_grobner poly_grobner_equal' + + ' poly_grobner_member poly_grobner_subsetp poly_ideal_intersection poly_ideal_polysaturation' + + ' poly_ideal_polysaturation1 poly_ideal_saturation poly_ideal_saturation1 poly_lcm' + + ' poly_minimization polymod poly_multiply polynome2ele polynomialp poly_normal_form' + + ' poly_normalize poly_normalize_list poly_polysaturation_extension poly_primitive_part' + + ' poly_pseudo_divide poly_reduced_grobner poly_reduction poly_saturation_extension' + + ' poly_s_polynomial poly_subtract polytocompanion pop postfix potential power_mod' + + ' powerseries powerset prefix prev_prime primep primes principal_components' + + ' print printf printfile print_graph printpois printprops prodrac product properties' + + ' propvars psi psubst ptriangularize pui pui2comp pui2ele pui2polynome pui_direct' + + ' puireduc push put pv qput qrange qty quad_control quad_qag quad_qagi quad_qagp' + + ' quad_qags quad_qawc quad_qawf quad_qawo quad_qaws quadrilateral quantile' + + ' quantile_bernoulli quantile_beta quantile_binomial quantile_cauchy quantile_chi2' + + ' quantile_continuous_uniform quantile_discrete_uniform quantile_exp quantile_f' + + ' quantile_gamma quantile_general_finite_discrete quantile_geometric quantile_gumbel' + + ' quantile_hypergeometric quantile_laplace quantile_logistic quantile_lognormal' + + ' quantile_negative_binomial quantile_noncentral_chi2 quantile_noncentral_student_t' + + ' quantile_normal quantile_pareto quantile_poisson quantile_rayleigh quantile_student_t' + + ' quantile_weibull quartile_skewness quit qunit quotient racah_v racah_w radcan' + + ' radius random random_bernoulli random_beta random_binomial random_bipartite_graph' + + ' random_cauchy random_chi2 random_continuous_uniform random_digraph random_discrete_uniform' + + ' random_exp random_f random_gamma random_general_finite_discrete random_geometric' + + ' random_graph random_graph1 random_gumbel random_hypergeometric random_laplace' + + ' random_logistic random_lognormal random_negative_binomial random_network' + + ' random_noncentral_chi2 random_noncentral_student_t random_normal random_pareto' + + ' random_permutation random_poisson random_rayleigh random_regular_graph random_student_t' + + ' random_tournament random_tree random_weibull range rank rat ratcoef ratdenom' + + ' ratdiff ratdisrep ratexpand ratinterpol rational rationalize ratnumer ratnump' + + ' ratp ratsimp ratsubst ratvars ratweight read read_array read_binary_array' + + ' read_binary_list read_binary_matrix readbyte readchar read_hashed_array readline' + + ' read_list read_matrix read_nested_list readonly read_xpm real_imagpart_to_conjugate' + + ' realpart realroots rearray rectangle rectform rectform_log_if_constant recttopolar' + + ' rediff reduce_consts reduce_order region region_boundaries region_boundaries_plus' + + ' rem remainder remarray rembox remcomps remcon remcoord remfun remfunction' + + ' remlet remove remove_constvalue remove_dimensions remove_edge remove_fundamental_dimensions' + + ' remove_fundamental_units remove_plot_option remove_vertex rempart remrule' + + ' remsym remvalue rename rename_file reset reset_displays residue resolvante' + + ' resolvante_alternee1 resolvante_bipartite resolvante_diedrale resolvante_klein' + + ' resolvante_klein3 resolvante_produit_sym resolvante_unitaire resolvante_vierer' + + ' rest resultant return reveal reverse revert revert2 rgb2level rhs ricci riemann' + + ' rinvariant risch rk rmdir rncombine romberg room rootscontract round row' + + ' rowop rowswap rreduce run_testsuite %s save saving scalarp scaled_bessel_i' + + ' scaled_bessel_i0 scaled_bessel_i1 scalefactors scanmap scatterplot scatterplot_description' + + ' scene schur2comp sconcat scopy scsimp scurvature sdowncase sec sech second' + + ' sequal sequalignore set_alt_display setdifference set_draw_defaults set_edge_weight' + + ' setelmx setequalp setify setp set_partitions set_plot_option set_prompt set_random_state' + + ' set_tex_environment set_tex_environment_default setunits setup_autoload set_up_dot_simplifications' + + ' set_vertex_label seventh sexplode sf sha1sum sha256sum shortest_path shortest_weighted_path' + + ' show showcomps showratvars sierpinskiale sierpinskimap sign signum similaritytransform' + + ' simp_inequality simplify_sum simplode simpmetderiv simtran sin sinh sinsert' + + ' sinvertcase sixth skewness skewness_bernoulli skewness_beta skewness_binomial' + + ' skewness_chi2 skewness_continuous_uniform skewness_discrete_uniform skewness_exp' + + ' skewness_f skewness_gamma skewness_general_finite_discrete skewness_geometric' + + ' skewness_gumbel skewness_hypergeometric skewness_laplace skewness_logistic' + + ' skewness_lognormal skewness_negative_binomial skewness_noncentral_chi2 skewness_noncentral_student_t' + + ' skewness_normal skewness_pareto skewness_poisson skewness_rayleigh skewness_student_t' + + ' skewness_weibull slength smake small_rhombicosidodecahedron_graph small_rhombicuboctahedron_graph' + + ' smax smin smismatch snowmap snub_cube_graph snub_dodecahedron_graph solve' + + ' solve_rec solve_rec_rat some somrac sort sparse6_decode sparse6_encode sparse6_export' + + ' sparse6_import specint spherical spherical_bessel_j spherical_bessel_y spherical_hankel1' + + ' spherical_hankel2 spherical_harmonic spherical_to_xyz splice split sposition' + + ' sprint sqfr sqrt sqrtdenest sremove sremovefirst sreverse ssearch ssort sstatus' + + ' ssubst ssubstfirst staircase standardize standardize_inverse_trig starplot' + + ' starplot_description status std std1 std_bernoulli std_beta std_binomial' + + ' std_chi2 std_continuous_uniform std_discrete_uniform std_exp std_f std_gamma' + + ' std_general_finite_discrete std_geometric std_gumbel std_hypergeometric std_laplace' + + ' std_logistic std_lognormal std_negative_binomial std_noncentral_chi2 std_noncentral_student_t' + + ' std_normal std_pareto std_poisson std_rayleigh std_student_t std_weibull' + + ' stemplot stirling stirling1 stirling2 strim striml strimr string stringout' + + ' stringp strong_components struve_h struve_l sublis sublist sublist_indices' + + ' submatrix subsample subset subsetp subst substinpart subst_parallel substpart' + + ' substring subvar subvarp sum sumcontract summand_to_rec supcase supcontext' + + ' symbolp symmdifference symmetricp system take_channel take_inference tan' + + ' tanh taylor taylorinfo taylorp taylor_simplifier taytorat tcl_output tcontract' + + ' tellrat tellsimp tellsimpafter tentex tenth test_mean test_means_difference' + + ' test_normality test_proportion test_proportions_difference test_rank_sum' + + ' test_sign test_signed_rank test_variance test_variance_ratio tex tex1 tex_display' + + ' texput %th third throw time timedate timer timer_info tldefint tlimit todd_coxeter' + + ' toeplitz tokens to_lisp topological_sort to_poly to_poly_solve totaldisrep' + + ' totalfourier totient tpartpol trace tracematrix trace_options transform_sample' + + ' translate translate_file transpose treefale tree_reduce treillis treinat' + + ' triangle triangularize trigexpand trigrat trigreduce trigsimp trunc truncate' + + ' truncated_cube_graph truncated_dodecahedron_graph truncated_icosahedron_graph' + + ' truncated_tetrahedron_graph tr_warnings_get tube tutte_graph ueivects uforget' + + ' ultraspherical underlying_graph undiff union unique uniteigenvectors unitp' + + ' units unit_step unitvector unorder unsum untellrat untimer' + + ' untrace uppercasep uricci uriemann uvect vandermonde_matrix var var1 var_bernoulli' + + ' var_beta var_binomial var_chi2 var_continuous_uniform var_discrete_uniform' + + ' var_exp var_f var_gamma var_general_finite_discrete var_geometric var_gumbel' + + ' var_hypergeometric var_laplace var_logistic var_lognormal var_negative_binomial' + + ' var_noncentral_chi2 var_noncentral_student_t var_normal var_pareto var_poisson' + + ' var_rayleigh var_student_t var_weibull vector vectorpotential vectorsimp' + + ' verbify vers vertex_coloring vertex_connectivity vertex_degree vertex_distance' + + ' vertex_eccentricity vertex_in_degree vertex_out_degree vertices vertices_to_cycle' + + ' vertices_to_path %w weyl wheel_graph wiener_index wigner_3j wigner_6j' + + ' wigner_9j with_stdout write_binary_data writebyte write_data writefile wronskian' + + ' xreduce xthru %y Zeilberger zeroequiv zerofor zeromatrix zeromatrixp zeta' + + ' zgeev zheev zlange zn_add_table zn_carmichael_lambda zn_characteristic_factors' + + ' zn_determinant zn_factor_generators zn_invert_by_lu zn_log zn_mult_table' + + ' absboxchar activecontexts adapt_depth additive adim aform algebraic' + + ' algepsilon algexact aliases allbut all_dotsimp_denoms allocation allsym alphabetic' + + ' animation antisymmetric arrays askexp assume_pos assume_pos_pred assumescalar' + + ' asymbol atomgrad atrig1 axes axis_3d axis_bottom axis_left axis_right axis_top' + + ' azimuth background background_color backsubst berlefact bernstein_explicit' + + ' besselexpand beta_args_sum_to_integer beta_expand bftorat bftrunc bindtest' + + ' border boundaries_array box boxchar breakup %c capping cauchysum cbrange' + + ' cbtics center cflength cframe_flag cnonmet_flag color color_bar color_bar_tics' + + ' colorbox columns commutative complex cone context contexts contour contour_levels' + + ' cosnpiflag ctaypov ctaypt ctayswitch ctayvar ct_coords ctorsion_flag ctrgsimp' + + ' cube current_let_rule_package cylinder data_file_name debugmode decreasing' + + ' default_let_rule_package delay dependencies derivabbrev derivsubst detout' + + ' diagmetric diff dim dimensions dispflag display2d|10 display_format_internal' + + ' distribute_over doallmxops domain domxexpt domxmxops domxnctimes dontfactor' + + ' doscmxops doscmxplus dot0nscsimp dot0simp dot1simp dotassoc dotconstrules' + + ' dotdistrib dotexptsimp dotident dotscrules draw_graph_program draw_realpart' + + ' edge_color edge_coloring edge_partition edge_type edge_width %edispflag' + + ' elevation %emode endphi endtheta engineering_format_floats enhanced3d %enumer' + + ' epsilon_lp erfflag erf_representation errormsg error_size error_syms error_type' + + ' %e_to_numlog eval even evenfun evflag evfun ev_point expandwrt_denom expintexpand' + + ' expintrep expon expop exptdispflag exptisolate exptsubst facexpand facsum_combine' + + ' factlim factorflag factorial_expand factors_only fb feature features' + + ' file_name file_output_append file_search_demo file_search_lisp file_search_maxima|10' + + ' file_search_tests file_search_usage file_type_lisp file_type_maxima|10 fill_color' + + ' fill_density filled_func fixed_vertices flipflag float2bf font font_size' + + ' fortindent fortspaces fpprec fpprintprec functions gamma_expand gammalim' + + ' gdet genindex gensumnum GGFCFMAX GGFINFINITY globalsolve gnuplot_command' + + ' gnuplot_curve_styles gnuplot_curve_titles gnuplot_default_term_command gnuplot_dumb_term_command' + + ' gnuplot_file_args gnuplot_file_name gnuplot_out_file gnuplot_pdf_term_command' + + ' gnuplot_pm3d gnuplot_png_term_command gnuplot_postamble gnuplot_preamble' + + ' gnuplot_ps_term_command gnuplot_svg_term_command gnuplot_term gnuplot_view_args' + + ' Gosper_in_Zeilberger gradefs grid grid2d grind halfangles head_angle head_both' + + ' head_length head_type height hypergeometric_representation %iargs ibase' + + ' icc1 icc2 icounter idummyx ieqnprint ifb ifc1 ifc2 ifg ifgi ifr iframe_bracket_form' + + ' ifri igeowedge_flag ikt1 ikt2 imaginary inchar increasing infeval' + + ' infinity inflag infolists inm inmc1 inmc2 intanalysis integer integervalued' + + ' integrate_use_rootsof integration_constant integration_constant_counter interpolate_color' + + ' intfaclim ip_grid ip_grid_in irrational isolate_wrt_times iterations itr' + + ' julia_parameter %k1 %k2 keepfloat key key_pos kinvariant kt label label_alignment' + + ' label_orientation labels lassociative lbfgs_ncorrections lbfgs_nfeval_max' + + ' leftjust legend letrat let_rule_packages lfg lg lhospitallim limsubst linear' + + ' linear_solver linechar linel|10 linenum line_type linewidth line_width linsolve_params' + + ' linsolvewarn lispdisp listarith listconstvars listdummyvars lmxchar load_pathname' + + ' loadprint logabs logarc logcb logconcoeffp logexpand lognegint logsimp logx' + + ' logx_secondary logy logy_secondary logz lriem m1pbranch macroexpansion macros' + + ' mainvar manual_demo maperror mapprint matrix_element_add matrix_element_mult' + + ' matrix_element_transpose maxapplydepth maxapplyheight maxima_tempdir|10 maxima_userdir|10' + + ' maxnegex MAX_ORD maxposex maxpsifracdenom maxpsifracnum maxpsinegint maxpsiposint' + + ' maxtayorder mesh_lines_color method mod_big_prime mode_check_errorp' + + ' mode_checkp mode_check_warnp mod_test mod_threshold modular_linear_solver' + + ' modulus multiplicative multiplicities myoptions nary negdistrib negsumdispflag' + + ' newline newtonepsilon newtonmaxiter nextlayerfactor niceindicespref nm nmc' + + ' noeval nolabels nonegative_lp noninteger nonscalar noun noundisp nouns np' + + ' npi nticks ntrig numer numer_pbranch obase odd oddfun opacity opproperties' + + ' opsubst optimprefix optionset orientation origin orthopoly_returns_intervals' + + ' outative outchar packagefile palette partswitch pdf_file pfeformat phiresolution' + + ' %piargs piece pivot_count_sx pivot_max_sx plot_format plot_options plot_realpart' + + ' png_file pochhammer_max_index points pointsize point_size points_joined point_type' + + ' poislim poisson poly_coefficient_ring poly_elimination_order polyfactor poly_grobner_algorithm' + + ' poly_grobner_debug poly_monomial_order poly_primary_elimination_order poly_return_term_list' + + ' poly_secondary_elimination_order poly_top_reduction_only posfun position' + + ' powerdisp pred prederror primep_number_of_tests product_use_gamma program' + + ' programmode promote_float_to_bigfloat prompt proportional_axes props psexpand' + + ' ps_file radexpand radius radsubstflag rassociative ratalgdenom ratchristof' + + ' ratdenomdivide rateinstein ratepsilon ratfac rational ratmx ratprint ratriemann' + + ' ratsimpexpons ratvarswitch ratweights ratweyl ratwtlvl real realonly redraw' + + ' refcheck resolution restart resultant ric riem rmxchar %rnum_list rombergabs' + + ' rombergit rombergmin rombergtol rootsconmode rootsepsilon run_viewer same_xy' + + ' same_xyz savedef savefactors scalar scalarmatrixp scale scale_lp setcheck' + + ' setcheckbreak setval show_edge_color show_edges show_edge_type show_edge_width' + + ' show_id show_label showtime show_vertex_color show_vertex_size show_vertex_type' + + ' show_vertices show_weight simp simplified_output simplify_products simpproduct' + + ' simpsum sinnpiflag solvedecomposes solveexplicit solvefactors solvenullwarn' + + ' solveradcan solvetrigwarn space sparse sphere spring_embedding_depth sqrtdispflag' + + ' stardisp startphi starttheta stats_numer stringdisp structures style sublis_apply_lambda' + + ' subnumsimp sumexpand sumsplitfact surface surface_hide svg_file symmetric' + + ' tab taylordepth taylor_logexpand taylor_order_coefficients taylor_truncate_polynomials' + + ' tensorkill terminal testsuite_files thetaresolution timer_devalue title tlimswitch' + + ' tr track transcompile transform transform_xy translate_fast_arrays transparent' + + ' transrun tr_array_as_ref tr_bound_function_applyp tr_file_tty_messagesp tr_float_can_branch_complex' + + ' tr_function_call_default trigexpandplus trigexpandtimes triginverses trigsign' + + ' trivial_solutions tr_numer tr_optimize_max_loop tr_semicompile tr_state_vars' + + ' tr_warn_bad_function_calls tr_warn_fexpr tr_warn_meval tr_warn_mode' + + ' tr_warn_undeclared tr_warn_undefined_variable tstep ttyoff tube_extremes' + + ' ufg ug %unitexpand unit_vectors uric uriem use_fast_arrays user_preamble' + + ' usersetunits values vect_cross verbose vertex_color vertex_coloring vertex_partition' + + ' vertex_size vertex_type view warnings weyl width windowname windowtitle wired_surface' + + ' wireframe xaxis xaxis_color xaxis_secondary xaxis_type xaxis_width xlabel' + + ' xlabel_secondary xlength xrange xrange_secondary xtics xtics_axis xtics_rotate' + + ' xtics_rotate_secondary xtics_secondary xtics_secondary_axis xu_grid x_voxel' + + ' xy_file xyplane xy_scale yaxis yaxis_color yaxis_secondary yaxis_type yaxis_width' + + ' ylabel ylabel_secondary ylength yrange yrange_secondary ytics ytics_axis' + + ' ytics_rotate ytics_rotate_secondary ytics_secondary ytics_secondary_axis' + + ' yv_grid y_voxel yx_ratio zaxis zaxis_color zaxis_type zaxis_width zeroa zerob' + + ' zerobern zeta%pi zlabel zlabel_rotate zlength zmin zn_primroot_limit zn_primroot_pretest'; + const SYMBOLS = '_ __ %|0 %%|0'; + + return { + name: 'Maxima', + keywords: { + $pattern: '[A-Za-z_%][0-9A-Za-z_%]*', + keyword: KEYWORDS, + literal: LITERALS, + built_in: BUILTIN_FUNCTIONS, + symbol: SYMBOLS + }, + contains: [ + { + className: 'comment', + begin: '/\\*', + end: '\\*/', + contains: [ 'self' ] + }, + hljs.QUOTE_STRING_MODE, + { + className: 'number', + relevance: 0, + variants: [ + { + // float number w/ exponent + // hmm, I wonder if we ought to include other exponent markers? + begin: '\\b(\\d+|\\d+\\.|\\.\\d+|\\d+\\.\\d+)[Ee][-+]?\\d+\\b' + }, + { + // bigfloat number + begin: '\\b(\\d+|\\d+\\.|\\.\\d+|\\d+\\.\\d+)[Bb][-+]?\\d+\\b', + relevance: 10 + }, + { + // float number w/out exponent + // Doesn't seem to recognize floats which start with '.' + begin: '\\b(\\.\\d+|\\d+\\.\\d+)\\b' + }, + { + // integer in base up to 36 + // Doesn't seem to recognize integers which end with '.' + begin: '\\b(\\d+|0[0-9A-Za-z]+)\\.?\\b' + } + ] + } + ], + illegal: /@/ + }; +} + +module.exports = maxima; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/mel.js b/claude-code-source/node_modules/highlight.js/lib/languages/mel.js new file mode 100644 index 00000000..6c66f673 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/mel.js @@ -0,0 +1,236 @@ +/* +Language: MEL +Description: Maya Embedded Language +Author: Shuen-Huei Guan +Website: http://www.autodesk.com/products/autodesk-maya/overview +Category: graphics +*/ + +function mel(hljs) { + return { + name: 'MEL', + keywords: + 'int float string vector matrix if else switch case default while do for in break ' + + 'continue global proc return about abs addAttr addAttributeEditorNodeHelp addDynamic ' + + 'addNewShelfTab addPP addPanelCategory addPrefixToName advanceToNextDrivenKey ' + + 'affectedNet affects aimConstraint air alias aliasAttr align alignCtx alignCurve ' + + 'alignSurface allViewFit ambientLight angle angleBetween animCone animCurveEditor ' + + 'animDisplay animView annotate appendStringArray applicationName applyAttrPreset ' + + 'applyTake arcLenDimContext arcLengthDimension arclen arrayMapper art3dPaintCtx ' + + 'artAttrCtx artAttrPaintVertexCtx artAttrSkinPaintCtx artAttrTool artBuildPaintMenu ' + + 'artFluidAttrCtx artPuttyCtx artSelectCtx artSetPaintCtx artUserPaintCtx assignCommand ' + + 'assignInputDevice assignViewportFactories attachCurve attachDeviceAttr attachSurface ' + + 'attrColorSliderGrp attrCompatibility attrControlGrp attrEnumOptionMenu ' + + 'attrEnumOptionMenuGrp attrFieldGrp attrFieldSliderGrp attrNavigationControlGrp ' + + 'attrPresetEditWin attributeExists attributeInfo attributeMenu attributeQuery ' + + 'autoKeyframe autoPlace bakeClip bakeFluidShading bakePartialHistory bakeResults ' + + 'bakeSimulation basename basenameEx batchRender bessel bevel bevelPlus binMembership ' + + 'bindSkin blend2 blendShape blendShapeEditor blendShapePanel blendTwoAttr blindDataType ' + + 'boneLattice boundary boxDollyCtx boxZoomCtx bufferCurve buildBookmarkMenu ' + + 'buildKeyframeMenu button buttonManip CBG cacheFile cacheFileCombine cacheFileMerge ' + + 'cacheFileTrack camera cameraView canCreateManip canvas capitalizeString catch ' + + 'catchQuiet ceil changeSubdivComponentDisplayLevel changeSubdivRegion channelBox ' + + 'character characterMap characterOutlineEditor characterize chdir checkBox checkBoxGrp ' + + 'checkDefaultRenderGlobals choice circle circularFillet clamp clear clearCache clip ' + + 'clipEditor clipEditorCurrentTimeCtx clipSchedule clipSchedulerOutliner clipTrimBefore ' + + 'closeCurve closeSurface cluster cmdFileOutput cmdScrollFieldExecuter ' + + 'cmdScrollFieldReporter cmdShell coarsenSubdivSelectionList collision color ' + + 'colorAtPoint colorEditor colorIndex colorIndexSliderGrp colorSliderButtonGrp ' + + 'colorSliderGrp columnLayout commandEcho commandLine commandPort compactHairSystem ' + + 'componentEditor compositingInterop computePolysetVolume condition cone confirmDialog ' + + 'connectAttr connectControl connectDynamic connectJoint connectionInfo constrain ' + + 'constrainValue constructionHistory container containsMultibyte contextInfo control ' + + 'convertFromOldLayers convertIffToPsd convertLightmap convertSolidTx convertTessellation ' + + 'convertUnit copyArray copyFlexor copyKey copySkinWeights cos cpButton cpCache ' + + 'cpClothSet cpCollision cpConstraint cpConvClothToMesh cpForces cpGetSolverAttr cpPanel ' + + 'cpProperty cpRigidCollisionFilter cpSeam cpSetEdit cpSetSolverAttr cpSolver ' + + 'cpSolverTypes cpTool cpUpdateClothUVs createDisplayLayer createDrawCtx createEditor ' + + 'createLayeredPsdFile createMotionField createNewShelf createNode createRenderLayer ' + + 'createSubdivRegion cross crossProduct ctxAbort ctxCompletion ctxEditMode ctxTraverse ' + + 'currentCtx currentTime currentTimeCtx currentUnit curve curveAddPtCtx ' + + 'curveCVCtx curveEPCtx curveEditorCtx curveIntersect curveMoveEPCtx curveOnSurface ' + + 'curveSketchCtx cutKey cycleCheck cylinder dagPose date defaultLightListCheckBox ' + + 'defaultNavigation defineDataServer defineVirtualDevice deformer deg_to_rad delete ' + + 'deleteAttr deleteShadingGroupsAndMaterials deleteShelfTab deleteUI deleteUnusedBrushes ' + + 'delrandstr detachCurve detachDeviceAttr detachSurface deviceEditor devicePanel dgInfo ' + + 'dgdirty dgeval dgtimer dimWhen directKeyCtx directionalLight dirmap dirname disable ' + + 'disconnectAttr disconnectJoint diskCache displacementToPoly displayAffected ' + + 'displayColor displayCull displayLevelOfDetail displayPref displayRGBColor ' + + 'displaySmoothness displayStats displayString displaySurface distanceDimContext ' + + 'distanceDimension doBlur dolly dollyCtx dopeSheetEditor dot dotProduct ' + + 'doubleProfileBirailSurface drag dragAttrContext draggerContext dropoffLocator ' + + 'duplicate duplicateCurve duplicateSurface dynCache dynControl dynExport dynExpression ' + + 'dynGlobals dynPaintEditor dynParticleCtx dynPref dynRelEdPanel dynRelEditor ' + + 'dynamicLoad editAttrLimits editDisplayLayerGlobals editDisplayLayerMembers ' + + 'editRenderLayerAdjustment editRenderLayerGlobals editRenderLayerMembers editor ' + + 'editorTemplate effector emit emitter enableDevice encodeString endString endsWith env ' + + 'equivalent equivalentTol erf error eval evalDeferred evalEcho event ' + + 'exactWorldBoundingBox exclusiveLightCheckBox exec executeForEachObject exists exp ' + + 'expression expressionEditorListen extendCurve extendSurface extrude fcheck fclose feof ' + + 'fflush fgetline fgetword file fileBrowserDialog fileDialog fileExtension fileInfo ' + + 'filetest filletCurve filter filterCurve filterExpand filterStudioImport ' + + 'findAllIntersections findAnimCurves findKeyframe findMenuItem findRelatedSkinCluster ' + + 'finder firstParentOf fitBspline flexor floatEq floatField floatFieldGrp floatScrollBar ' + + 'floatSlider floatSlider2 floatSliderButtonGrp floatSliderGrp floor flow fluidCacheInfo ' + + 'fluidEmitter fluidVoxelInfo flushUndo fmod fontDialog fopen formLayout format fprint ' + + 'frameLayout fread freeFormFillet frewind fromNativePath fwrite gamma gauss ' + + 'geometryConstraint getApplicationVersionAsFloat getAttr getClassification ' + + 'getDefaultBrush getFileList getFluidAttr getInputDeviceRange getMayaPanelTypes ' + + 'getModifiers getPanel getParticleAttr getPluginResource getenv getpid glRender ' + + 'glRenderEditor globalStitch gmatch goal gotoBindPose grabColor gradientControl ' + + 'gradientControlNoAttr graphDollyCtx graphSelectContext graphTrackCtx gravity grid ' + + 'gridLayout group groupObjectsByName HfAddAttractorToAS HfAssignAS HfBuildEqualMap ' + + 'HfBuildFurFiles HfBuildFurImages HfCancelAFR HfConnectASToHF HfCreateAttractor ' + + 'HfDeleteAS HfEditAS HfPerformCreateAS HfRemoveAttractorFromAS HfSelectAttached ' + + 'HfSelectAttractors HfUnAssignAS hardenPointCurve hardware hardwareRenderPanel ' + + 'headsUpDisplay headsUpMessage help helpLine hermite hide hilite hitTest hotBox hotkey ' + + 'hotkeyCheck hsv_to_rgb hudButton hudSlider hudSliderButton hwReflectionMap hwRender ' + + 'hwRenderLoad hyperGraph hyperPanel hyperShade hypot iconTextButton iconTextCheckBox ' + + 'iconTextRadioButton iconTextRadioCollection iconTextScrollList iconTextStaticLabel ' + + 'ikHandle ikHandleCtx ikHandleDisplayScale ikSolver ikSplineHandleCtx ikSystem ' + + 'ikSystemInfo ikfkDisplayMethod illustratorCurves image imfPlugins inheritTransform ' + + 'insertJoint insertJointCtx insertKeyCtx insertKnotCurve insertKnotSurface instance ' + + 'instanceable instancer intField intFieldGrp intScrollBar intSlider intSliderGrp ' + + 'interToUI internalVar intersect iprEngine isAnimCurve isConnected isDirty isParentOf ' + + 'isSameObject isTrue isValidObjectName isValidString isValidUiName isolateSelect ' + + 'itemFilter itemFilterAttr itemFilterRender itemFilterType joint jointCluster jointCtx ' + + 'jointDisplayScale jointLattice keyTangent keyframe keyframeOutliner ' + + 'keyframeRegionCurrentTimeCtx keyframeRegionDirectKeyCtx keyframeRegionDollyCtx ' + + 'keyframeRegionInsertKeyCtx keyframeRegionMoveKeyCtx keyframeRegionScaleKeyCtx ' + + 'keyframeRegionSelectKeyCtx keyframeRegionSetKeyCtx keyframeRegionTrackCtx ' + + 'keyframeStats lassoContext lattice latticeDeformKeyCtx launch launchImageEditor ' + + 'layerButton layeredShaderPort layeredTexturePort layout layoutDialog lightList ' + + 'lightListEditor lightListPanel lightlink lineIntersection linearPrecision linstep ' + + 'listAnimatable listAttr listCameras listConnections listDeviceAttachments listHistory ' + + 'listInputDeviceAxes listInputDeviceButtons listInputDevices listMenuAnnotation ' + + 'listNodeTypes listPanelCategories listRelatives listSets listTransforms ' + + 'listUnselected listerEditor loadFluid loadNewShelf loadPlugin ' + + 'loadPluginLanguageResources loadPrefObjects localizedPanelLabel lockNode loft log ' + + 'longNameOf lookThru ls lsThroughFilter lsType lsUI Mayatomr mag makeIdentity makeLive ' + + 'makePaintable makeRoll makeSingleSurface makeTubeOn makebot manipMoveContext ' + + 'manipMoveLimitsCtx manipOptions manipRotateContext manipRotateLimitsCtx ' + + 'manipScaleContext manipScaleLimitsCtx marker match max memory menu menuBarLayout ' + + 'menuEditor menuItem menuItemToShelf menuSet menuSetPref messageLine min minimizeApp ' + + 'mirrorJoint modelCurrentTimeCtx modelEditor modelPanel mouse movIn movOut move ' + + 'moveIKtoFK moveKeyCtx moveVertexAlongDirection multiProfileBirailSurface mute ' + + 'nParticle nameCommand nameField namespace namespaceInfo newPanelItems newton nodeCast ' + + 'nodeIconButton nodeOutliner nodePreset nodeType noise nonLinear normalConstraint ' + + 'normalize nurbsBoolean nurbsCopyUVSet nurbsCube nurbsEditUV nurbsPlane nurbsSelect ' + + 'nurbsSquare nurbsToPoly nurbsToPolygonsPref nurbsToSubdiv nurbsToSubdivPref ' + + 'nurbsUVSet nurbsViewDirectionVector objExists objectCenter objectLayer objectType ' + + 'objectTypeUI obsoleteProc oceanNurbsPreviewPlane offsetCurve offsetCurveOnSurface ' + + 'offsetSurface openGLExtension openMayaPref optionMenu optionMenuGrp optionVar orbit ' + + 'orbitCtx orientConstraint outlinerEditor outlinerPanel overrideModifier ' + + 'paintEffectsDisplay pairBlend palettePort paneLayout panel panelConfiguration ' + + 'panelHistory paramDimContext paramDimension paramLocator parent parentConstraint ' + + 'particle particleExists particleInstancer particleRenderInfo partition pasteKey ' + + 'pathAnimation pause pclose percent performanceOptions pfxstrokes pickWalk picture ' + + 'pixelMove planarSrf plane play playbackOptions playblast plugAttr plugNode pluginInfo ' + + 'pluginResourceUtil pointConstraint pointCurveConstraint pointLight pointMatrixMult ' + + 'pointOnCurve pointOnSurface pointPosition poleVectorConstraint polyAppend ' + + 'polyAppendFacetCtx polyAppendVertex polyAutoProjection polyAverageNormal ' + + 'polyAverageVertex polyBevel polyBlendColor polyBlindData polyBoolOp polyBridgeEdge ' + + 'polyCacheMonitor polyCheck polyChipOff polyClipboard polyCloseBorder polyCollapseEdge ' + + 'polyCollapseFacet polyColorBlindData polyColorDel polyColorPerVertex polyColorSet ' + + 'polyCompare polyCone polyCopyUV polyCrease polyCreaseCtx polyCreateFacet ' + + 'polyCreateFacetCtx polyCube polyCut polyCutCtx polyCylinder polyCylindricalProjection ' + + 'polyDelEdge polyDelFacet polyDelVertex polyDuplicateAndConnect polyDuplicateEdge ' + + 'polyEditUV polyEditUVShell polyEvaluate polyExtrudeEdge polyExtrudeFacet ' + + 'polyExtrudeVertex polyFlipEdge polyFlipUV polyForceUV polyGeoSampler polyHelix ' + + 'polyInfo polyInstallAction polyLayoutUV polyListComponentConversion polyMapCut ' + + 'polyMapDel polyMapSew polyMapSewMove polyMergeEdge polyMergeEdgeCtx polyMergeFacet ' + + 'polyMergeFacetCtx polyMergeUV polyMergeVertex polyMirrorFace polyMoveEdge ' + + 'polyMoveFacet polyMoveFacetUV polyMoveUV polyMoveVertex polyNormal polyNormalPerVertex ' + + 'polyNormalizeUV polyOptUvs polyOptions polyOutput polyPipe polyPlanarProjection ' + + 'polyPlane polyPlatonicSolid polyPoke polyPrimitive polyPrism polyProjection ' + + 'polyPyramid polyQuad polyQueryBlindData polyReduce polySelect polySelectConstraint ' + + 'polySelectConstraintMonitor polySelectCtx polySelectEditCtx polySeparate ' + + 'polySetToFaceNormal polySewEdge polyShortestPathCtx polySmooth polySoftEdge ' + + 'polySphere polySphericalProjection polySplit polySplitCtx polySplitEdge polySplitRing ' + + 'polySplitVertex polyStraightenUVBorder polySubdivideEdge polySubdivideFacet ' + + 'polyToSubdiv polyTorus polyTransfer polyTriangulate polyUVSet polyUnite polyWedgeFace ' + + 'popen popupMenu pose pow preloadRefEd print progressBar progressWindow projFileViewer ' + + 'projectCurve projectTangent projectionContext projectionManip promptDialog propModCtx ' + + 'propMove psdChannelOutliner psdEditTextureFile psdExport psdTextureFile putenv pwd ' + + 'python querySubdiv quit rad_to_deg radial radioButton radioButtonGrp radioCollection ' + + 'radioMenuItemCollection rampColorPort rand randomizeFollicles randstate rangeControl ' + + 'readTake rebuildCurve rebuildSurface recordAttr recordDevice redo reference ' + + 'referenceEdit referenceQuery refineSubdivSelectionList refresh refreshAE ' + + 'registerPluginResource rehash reloadImage removeJoint removeMultiInstance ' + + 'removePanelCategory rename renameAttr renameSelectionList renameUI render ' + + 'renderGlobalsNode renderInfo renderLayerButton renderLayerParent ' + + 'renderLayerPostProcess renderLayerUnparent renderManip renderPartition ' + + 'renderQualityNode renderSettings renderThumbnailUpdate renderWindowEditor ' + + 'renderWindowSelectContext renderer reorder reorderDeformers requires reroot ' + + 'resampleFluid resetAE resetPfxToPolyCamera resetTool resolutionNode retarget ' + + 'reverseCurve reverseSurface revolve rgb_to_hsv rigidBody rigidSolver roll rollCtx ' + + 'rootOf rot rotate rotationInterpolation roundConstantRadius rowColumnLayout rowLayout ' + + 'runTimeCommand runup sampleImage saveAllShelves saveAttrPreset saveFluid saveImage ' + + 'saveInitialState saveMenu savePrefObjects savePrefs saveShelf saveToolSettings scale ' + + 'scaleBrushBrightness scaleComponents scaleConstraint scaleKey scaleKeyCtx sceneEditor ' + + 'sceneUIReplacement scmh scriptCtx scriptEditorInfo scriptJob scriptNode scriptTable ' + + 'scriptToShelf scriptedPanel scriptedPanelType scrollField scrollLayout sculpt ' + + 'searchPathArray seed selLoadSettings select selectContext selectCurveCV selectKey ' + + 'selectKeyCtx selectKeyframeRegionCtx selectMode selectPref selectPriority selectType ' + + 'selectedNodes selectionConnection separator setAttr setAttrEnumResource ' + + 'setAttrMapping setAttrNiceNameResource setConstraintRestPosition ' + + 'setDefaultShadingGroup setDrivenKeyframe setDynamic setEditCtx setEditor setFluidAttr ' + + 'setFocus setInfinity setInputDeviceMapping setKeyCtx setKeyPath setKeyframe ' + + 'setKeyframeBlendshapeTargetWts setMenuMode setNodeNiceNameResource setNodeTypeFlag ' + + 'setParent setParticleAttr setPfxToPolyCamera setPluginResource setProject ' + + 'setStampDensity setStartupMessage setState setToolTo setUITemplate setXformManip sets ' + + 'shadingConnection shadingGeometryRelCtx shadingLightRelCtx shadingNetworkCompare ' + + 'shadingNode shapeCompare shelfButton shelfLayout shelfTabLayout shellField ' + + 'shortNameOf showHelp showHidden showManipCtx showSelectionInTitle ' + + 'showShadingGroupAttrEditor showWindow sign simplify sin singleProfileBirailSurface ' + + 'size sizeBytes skinCluster skinPercent smoothCurve smoothTangentSurface smoothstep ' + + 'snap2to2 snapKey snapMode snapTogetherCtx snapshot soft softMod softModCtx sort sound ' + + 'soundControl source spaceLocator sphere sphrand spotLight spotLightPreviewPort ' + + 'spreadSheetEditor spring sqrt squareSurface srtContext stackTrace startString ' + + 'startsWith stitchAndExplodeShell stitchSurface stitchSurfacePoints strcmp ' + + 'stringArrayCatenate stringArrayContains stringArrayCount stringArrayInsertAtIndex ' + + 'stringArrayIntersector stringArrayRemove stringArrayRemoveAtIndex ' + + 'stringArrayRemoveDuplicates stringArrayRemoveExact stringArrayToString ' + + 'stringToStringArray strip stripPrefixFromName stroke subdAutoProjection ' + + 'subdCleanTopology subdCollapse subdDuplicateAndConnect subdEditUV ' + + 'subdListComponentConversion subdMapCut subdMapSewMove subdMatchTopology subdMirror ' + + 'subdToBlind subdToPoly subdTransferUVsToCache subdiv subdivCrease ' + + 'subdivDisplaySmoothness substitute substituteAllString substituteGeometry substring ' + + 'surface surfaceSampler surfaceShaderList swatchDisplayPort switchTable symbolButton ' + + 'symbolCheckBox sysFile system tabLayout tan tangentConstraint texLatticeDeformContext ' + + 'texManipContext texMoveContext texMoveUVShellContext texRotateContext texScaleContext ' + + 'texSelectContext texSelectShortestPathCtx texSmudgeUVContext texWinToolCtx text ' + + 'textCurves textField textFieldButtonGrp textFieldGrp textManip textScrollList ' + + 'textToShelf textureDisplacePlane textureHairColor texturePlacementContext ' + + 'textureWindow threadCount threePointArcCtx timeControl timePort timerX toNativePath ' + + 'toggle toggleAxis toggleWindowVisibility tokenize tokenizeList tolerance tolower ' + + 'toolButton toolCollection toolDropped toolHasOptions toolPropertyWindow torus toupper ' + + 'trace track trackCtx transferAttributes transformCompare transformLimits translator ' + + 'trim trunc truncateFluidCache truncateHairCache tumble tumbleCtx turbulence ' + + 'twoPointArcCtx uiRes uiTemplate unassignInputDevice undo undoInfo ungroup uniform unit ' + + 'unloadPlugin untangleUV untitledFileName untrim upAxis updateAE userCtx uvLink ' + + 'uvSnapshot validateShelfName vectorize view2dToolCtx viewCamera viewClipPlane ' + + 'viewFit viewHeadOn viewLookAt viewManip viewPlace viewSet visor volumeAxis vortex ' + + 'waitCursor warning webBrowser webBrowserPrefs whatIs window windowPref wire ' + + 'wireContext workspace wrinkle wrinkleContext writeTake xbmLangPathList xform', + illegal: ' +Description: Mercury is a logic/functional programming language which combines the clarity and expressiveness of declarative programming with advanced static analysis and error detection features. +Website: https://www.mercurylang.org +*/ + +function mercury(hljs) { + const KEYWORDS = { + keyword: + 'module use_module import_module include_module end_module initialise ' + + 'mutable initialize finalize finalise interface implementation pred ' + + 'mode func type inst solver any_pred any_func is semidet det nondet ' + + 'multi erroneous failure cc_nondet cc_multi typeclass instance where ' + + 'pragma promise external trace atomic or_else require_complete_switch ' + + 'require_det require_semidet require_multi require_nondet ' + + 'require_cc_multi require_cc_nondet require_erroneous require_failure', + meta: + // pragma + 'inline no_inline type_spec source_file fact_table obsolete memo ' + + 'loop_check minimal_model terminates does_not_terminate ' + + 'check_termination promise_equivalent_clauses ' + + // preprocessor + 'foreign_proc foreign_decl foreign_code foreign_type ' + + 'foreign_import_module foreign_export_enum foreign_export ' + + 'foreign_enum may_call_mercury will_not_call_mercury thread_safe ' + + 'not_thread_safe maybe_thread_safe promise_pure promise_semipure ' + + 'tabled_for_io local untrailed trailed attach_to_io_state ' + + 'can_pass_as_mercury_type stable will_not_throw_exception ' + + 'may_modify_trail will_not_modify_trail may_duplicate ' + + 'may_not_duplicate affects_liveness does_not_affect_liveness ' + + 'doesnt_affect_liveness no_sharing unknown_sharing sharing', + built_in: + 'some all not if then else true fail false try catch catch_any ' + + 'semidet_true semidet_false semidet_fail impure_true impure semipure' + }; + + const COMMENT = hljs.COMMENT('%', '$'); + + const NUMCODE = { + className: 'number', + begin: "0'.\\|0[box][0-9a-fA-F]*" + }; + + const ATOM = hljs.inherit(hljs.APOS_STRING_MODE, { + relevance: 0 + }); + const STRING = hljs.inherit(hljs.QUOTE_STRING_MODE, { + relevance: 0 + }); + const STRING_FMT = { + className: 'subst', + begin: '\\\\[abfnrtv]\\|\\\\x[0-9a-fA-F]*\\\\\\|%[-+# *.0-9]*[dioxXucsfeEgGp]', + relevance: 0 + }; + STRING.contains = STRING.contains.slice(); // we need our own copy of contains + STRING.contains.push(STRING_FMT); + + const IMPLICATION = { + className: 'built_in', + variants: [ + { + begin: '<=>' + }, + { + begin: '<=', + relevance: 0 + }, + { + begin: '=>', + relevance: 0 + }, + { + begin: '/\\\\' + }, + { + begin: '\\\\/' + } + ] + }; + + const HEAD_BODY_CONJUNCTION = { + className: 'built_in', + variants: [ + { + begin: ':-\\|-->' + }, + { + begin: '=', + relevance: 0 + } + ] + }; + + return { + name: 'Mercury', + aliases: [ + 'm', + 'moo' + ], + keywords: KEYWORDS, + contains: [ + IMPLICATION, + HEAD_BODY_CONJUNCTION, + COMMENT, + hljs.C_BLOCK_COMMENT_MODE, + NUMCODE, + hljs.NUMBER_MODE, + ATOM, + STRING, + { // relevance booster + begin: /:-/ + }, + { // relevance booster + begin: /\.$/ + } + ] + }; +} + +module.exports = mercury; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/mipsasm.js b/claude-code-source/node_modules/highlight.js/lib/languages/mipsasm.js new file mode 100644 index 00000000..9f14ddef --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/mipsasm.js @@ -0,0 +1,109 @@ +/* +Language: MIPS Assembly +Author: Nebuleon Fumika +Description: MIPS Assembly (up to MIPS32R2) +Website: https://en.wikipedia.org/wiki/MIPS_architecture +Category: assembler +*/ + +function mipsasm(hljs) { + // local labels: %?[FB]?[AT]?\d{1,2}\w+ + return { + name: 'MIPS Assembly', + case_insensitive: true, + aliases: [ 'mips' ], + keywords: { + $pattern: '\\.?' + hljs.IDENT_RE, + meta: + // GNU preprocs + '.2byte .4byte .align .ascii .asciz .balign .byte .code .data .else .end .endif .endm .endr .equ .err .exitm .extern .global .hword .if .ifdef .ifndef .include .irp .long .macro .rept .req .section .set .skip .space .text .word .ltorg ', + built_in: + '$0 $1 $2 $3 $4 $5 $6 $7 $8 $9 $10 $11 $12 $13 $14 $15 ' + // integer registers + '$16 $17 $18 $19 $20 $21 $22 $23 $24 $25 $26 $27 $28 $29 $30 $31 ' + // integer registers + 'zero at v0 v1 a0 a1 a2 a3 a4 a5 a6 a7 ' + // integer register aliases + 't0 t1 t2 t3 t4 t5 t6 t7 t8 t9 s0 s1 s2 s3 s4 s5 s6 s7 s8 ' + // integer register aliases + 'k0 k1 gp sp fp ra ' + // integer register aliases + '$f0 $f1 $f2 $f2 $f4 $f5 $f6 $f7 $f8 $f9 $f10 $f11 $f12 $f13 $f14 $f15 ' + // floating-point registers + '$f16 $f17 $f18 $f19 $f20 $f21 $f22 $f23 $f24 $f25 $f26 $f27 $f28 $f29 $f30 $f31 ' + // floating-point registers + 'Context Random EntryLo0 EntryLo1 Context PageMask Wired EntryHi ' + // Coprocessor 0 registers + 'HWREna BadVAddr Count Compare SR IntCtl SRSCtl SRSMap Cause EPC PRId ' + // Coprocessor 0 registers + 'EBase Config Config1 Config2 Config3 LLAddr Debug DEPC DESAVE CacheErr ' + // Coprocessor 0 registers + 'ECC ErrorEPC TagLo DataLo TagHi DataHi WatchLo WatchHi PerfCtl PerfCnt ' // Coprocessor 0 registers + }, + contains: [ + { + className: 'keyword', + begin: '\\b(' + // mnemonics + // 32-bit integer instructions + 'addi?u?|andi?|b(al)?|beql?|bgez(al)?l?|bgtzl?|blezl?|bltz(al)?l?|' + + 'bnel?|cl[oz]|divu?|ext|ins|j(al)?|jalr(\\.hb)?|jr(\\.hb)?|lbu?|lhu?|' + + 'll|lui|lw[lr]?|maddu?|mfhi|mflo|movn|movz|move|msubu?|mthi|mtlo|mul|' + + 'multu?|nop|nor|ori?|rotrv?|sb|sc|se[bh]|sh|sllv?|slti?u?|srav?|' + + 'srlv?|subu?|sw[lr]?|xori?|wsbh|' + + // floating-point instructions + 'abs\\.[sd]|add\\.[sd]|alnv.ps|bc1[ft]l?|' + + 'c\\.(s?f|un|u?eq|[ou]lt|[ou]le|ngle?|seq|l[et]|ng[et])\\.[sd]|' + + '(ceil|floor|round|trunc)\\.[lw]\\.[sd]|cfc1|cvt\\.d\\.[lsw]|' + + 'cvt\\.l\\.[dsw]|cvt\\.ps\\.s|cvt\\.s\\.[dlw]|cvt\\.s\\.p[lu]|cvt\\.w\\.[dls]|' + + 'div\\.[ds]|ldx?c1|luxc1|lwx?c1|madd\\.[sd]|mfc1|mov[fntz]?\\.[ds]|' + + 'msub\\.[sd]|mth?c1|mul\\.[ds]|neg\\.[ds]|nmadd\\.[ds]|nmsub\\.[ds]|' + + 'p[lu][lu]\\.ps|recip\\.fmt|r?sqrt\\.[ds]|sdx?c1|sub\\.[ds]|suxc1|' + + 'swx?c1|' + + // system control instructions + 'break|cache|d?eret|[de]i|ehb|mfc0|mtc0|pause|prefx?|rdhwr|' + + 'rdpgpr|sdbbp|ssnop|synci?|syscall|teqi?|tgei?u?|tlb(p|r|w[ir])|' + + 'tlti?u?|tnei?|wait|wrpgpr' + + ')', + end: '\\s' + }, + // lines ending with ; or # aren't really comments, probably auto-detect fail + hljs.COMMENT('[;#](?!\\s*$)', '$'), + hljs.C_BLOCK_COMMENT_MODE, + hljs.QUOTE_STRING_MODE, + { + className: 'string', + begin: '\'', + end: '[^\\\\]\'', + relevance: 0 + }, + { + className: 'title', + begin: '\\|', + end: '\\|', + illegal: '\\n', + relevance: 0 + }, + { + className: 'number', + variants: [ + { // hex + begin: '0x[0-9a-f]+' + }, + { // bare number + begin: '\\b-?\\d+' + } + ], + relevance: 0 + }, + { + className: 'symbol', + variants: [ + { // GNU MIPS syntax + begin: '^\\s*[a-z_\\.\\$][a-z0-9_\\.\\$]+:' + }, + { // numbered local labels + begin: '^\\s*[0-9]+:' + }, + { // number local label reference (backwards, forwards) + begin: '[0-9]+[bf]' + } + ], + relevance: 0 + } + ], + // forward slashes are not allowed + illegal: /\// + }; +} + +module.exports = mipsasm; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/mizar.js b/claude-code-source/node_modules/highlight.js/lib/languages/mizar.js new file mode 100644 index 00000000..ed02c0df --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/mizar.js @@ -0,0 +1,29 @@ +/* +Language: Mizar +Description: The Mizar Language is a formal language derived from the mathematical vernacular. +Author: Kelley van Evert +Website: http://mizar.org/language/ +Category: scientific +*/ + +function mizar(hljs) { + return { + name: 'Mizar', + keywords: + 'environ vocabularies notations constructors definitions ' + + 'registrations theorems schemes requirements begin end definition ' + + 'registration cluster existence pred func defpred deffunc theorem ' + + 'proof let take assume then thus hence ex for st holds consider ' + + 'reconsider such that and in provided of as from be being by means ' + + 'equals implies iff redefine define now not or attr is mode ' + + 'suppose per cases set thesis contradiction scheme reserve struct ' + + 'correctness compatibility coherence symmetry assymetry ' + + 'reflexivity irreflexivity connectedness uniqueness commutativity ' + + 'idempotence involutiveness projectivity', + contains: [ + hljs.COMMENT('::', '$') + ] + }; +} + +module.exports = mizar; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/mojolicious.js b/claude-code-source/node_modules/highlight.js/lib/languages/mojolicious.js new file mode 100644 index 00000000..890b16ba --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/mojolicious.js @@ -0,0 +1,36 @@ +/* +Language: Mojolicious +Requires: xml.js, perl.js +Author: Dotan Dimet +Description: Mojolicious .ep (Embedded Perl) templates +Website: https://mojolicious.org +Category: template +*/ +function mojolicious(hljs) { + return { + name: 'Mojolicious', + subLanguage: 'xml', + contains: [ + { + className: 'meta', + begin: '^__(END|DATA)__$' + }, + // mojolicious line + { + begin: "^\\s*%{1,2}={0,2}", + end: '$', + subLanguage: 'perl' + }, + // mojolicious block + { + begin: "<%{1,2}={0,2}", + end: "={0,1}%>", + subLanguage: 'perl', + excludeBegin: true, + excludeEnd: true + } + ] + }; +} + +module.exports = mojolicious; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/monkey.js b/claude-code-source/node_modules/highlight.js/lib/languages/monkey.js new file mode 100644 index 00000000..2d99a153 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/monkey.js @@ -0,0 +1,89 @@ +/* +Language: Monkey +Description: Monkey2 is an easy to use, cross platform, games oriented programming language from Blitz Research. +Author: Arthur Bikmullin +Website: https://blitzresearch.itch.io/monkey2 +*/ + +function monkey(hljs) { + const NUMBER = { + className: 'number', + relevance: 0, + variants: [ + { + begin: '[$][a-fA-F0-9]+' + }, + hljs.NUMBER_MODE + ] + }; + + return { + name: 'Monkey', + case_insensitive: true, + keywords: { + keyword: 'public private property continue exit extern new try catch ' + + 'eachin not abstract final select case default const local global field ' + + 'end if then else elseif endif while wend repeat until forever for ' + + 'to step next return module inline throw import', + + built_in: 'DebugLog DebugStop Error Print ACos ACosr ASin ASinr ATan ATan2 ATan2r ATanr Abs Abs Ceil ' + + 'Clamp Clamp Cos Cosr Exp Floor Log Max Max Min Min Pow Sgn Sgn Sin Sinr Sqrt Tan Tanr Seed PI HALFPI TWOPI', + + literal: 'true false null and or shl shr mod' + }, + illegal: /\/\*/, + contains: [ + hljs.COMMENT('#rem', '#end'), + hljs.COMMENT( + "'", + '$', + { + relevance: 0 + } + ), + { + className: 'function', + beginKeywords: 'function method', + end: '[(=:]|$', + illegal: /\n/, + contains: [ hljs.UNDERSCORE_TITLE_MODE ] + }, + { + className: 'class', + beginKeywords: 'class interface', + end: '$', + contains: [ + { + beginKeywords: 'extends implements' + }, + hljs.UNDERSCORE_TITLE_MODE + ] + }, + { + className: 'built_in', + begin: '\\b(self|super)\\b' + }, + { + className: 'meta', + begin: '\\s*#', + end: '$', + keywords: { + 'meta-keyword': 'if else elseif endif end then' + } + }, + { + className: 'meta', + begin: '^\\s*strict\\b' + }, + { + beginKeywords: 'alias', + end: '=', + contains: [ hljs.UNDERSCORE_TITLE_MODE ] + }, + hljs.QUOTE_STRING_MODE, + NUMBER + ] + }; +} + +module.exports = monkey; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/moonscript.js b/claude-code-source/node_modules/highlight.js/lib/languages/moonscript.js new file mode 100644 index 00000000..fe24cd9f --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/moonscript.js @@ -0,0 +1,147 @@ +/* +Language: MoonScript +Author: Billy Quith +Description: MoonScript is a programming language that transcompiles to Lua. +Origin: coffeescript.js +Website: http://moonscript.org/ +Category: scripting +*/ + +function moonscript(hljs) { + const KEYWORDS = { + keyword: + // Moonscript keywords + 'if then not for in while do return else elseif break continue switch and or ' + + 'unless when class extends super local import export from using', + literal: + 'true false nil', + built_in: + '_G _VERSION assert collectgarbage dofile error getfenv getmetatable ipairs load ' + + 'loadfile loadstring module next pairs pcall print rawequal rawget rawset require ' + + 'select setfenv setmetatable tonumber tostring type unpack xpcall coroutine debug ' + + 'io math os package string table' + }; + const JS_IDENT_RE = '[A-Za-z$_][0-9A-Za-z$_]*'; + const SUBST = { + className: 'subst', + begin: /#\{/, + end: /\}/, + keywords: KEYWORDS + }; + const EXPRESSIONS = [ + hljs.inherit(hljs.C_NUMBER_MODE, + { + starts: { + end: '(\\s*/)?', + relevance: 0 + } + }), // a number tries to eat the following slash to prevent treating it as a regexp + { + className: 'string', + variants: [ + { + begin: /'/, + end: /'/, + contains: [ hljs.BACKSLASH_ESCAPE ] + }, + { + begin: /"/, + end: /"/, + contains: [ + hljs.BACKSLASH_ESCAPE, + SUBST + ] + } + ] + }, + { + className: 'built_in', + begin: '@__' + hljs.IDENT_RE + }, + { + begin: '@' + hljs.IDENT_RE // relevance booster on par with CoffeeScript + }, + { + begin: hljs.IDENT_RE + '\\\\' + hljs.IDENT_RE // inst\method + } + ]; + SUBST.contains = EXPRESSIONS; + + const TITLE = hljs.inherit(hljs.TITLE_MODE, { + begin: JS_IDENT_RE + }); + const POSSIBLE_PARAMS_RE = '(\\(.*\\)\\s*)?\\B[-=]>'; + const PARAMS = { + className: 'params', + begin: '\\([^\\(]', + returnBegin: true, + /* We need another contained nameless mode to not have every nested + pair of parens to be called "params" */ + contains: [ + { + begin: /\(/, + end: /\)/, + keywords: KEYWORDS, + contains: [ 'self' ].concat(EXPRESSIONS) + } + ] + }; + + return { + name: 'MoonScript', + aliases: [ 'moon' ], + keywords: KEYWORDS, + illegal: /\/\*/, + contains: EXPRESSIONS.concat([ + hljs.COMMENT('--', '$'), + { + className: 'function', // function: -> => + begin: '^\\s*' + JS_IDENT_RE + '\\s*=\\s*' + POSSIBLE_PARAMS_RE, + end: '[-=]>', + returnBegin: true, + contains: [ + TITLE, + PARAMS + ] + }, + { + begin: /[\(,:=]\s*/, // anonymous function start + relevance: 0, + contains: [ + { + className: 'function', + begin: POSSIBLE_PARAMS_RE, + end: '[-=]>', + returnBegin: true, + contains: [ PARAMS ] + } + ] + }, + { + className: 'class', + beginKeywords: 'class', + end: '$', + illegal: /[:="\[\]]/, + contains: [ + { + beginKeywords: 'extends', + endsWithParent: true, + illegal: /[:="\[\]]/, + contains: [ TITLE ] + }, + TITLE + ] + }, + { + className: 'name', // table + begin: JS_IDENT_RE + ':', + end: ':', + returnBegin: true, + returnEnd: true, + relevance: 0 + } + ]) + }; +} + +module.exports = moonscript; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/n1ql.js b/claude-code-source/node_modules/highlight.js/lib/languages/n1ql.js new file mode 100644 index 00000000..bef9523c --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/n1ql.js @@ -0,0 +1,77 @@ +/* + Language: N1QL + Author: Andres Täht + Contributors: Rene Saarsoo + Description: Couchbase query language + Website: https://www.couchbase.com/products/n1ql + */ + +function n1ql(hljs) { + return { + name: 'N1QL', + case_insensitive: true, + contains: [ + { + beginKeywords: + 'build create index delete drop explain infer|10 insert merge prepare select update upsert|10', + end: /;/, endsWithParent: true, + keywords: { + // Taken from http://developer.couchbase.com/documentation/server/current/n1ql/n1ql-language-reference/reservedwords.html + keyword: + 'all alter analyze and any array as asc begin between binary boolean break bucket build by call ' + + 'case cast cluster collate collection commit connect continue correlate cover create database ' + + 'dataset datastore declare decrement delete derived desc describe distinct do drop each element ' + + 'else end every except exclude execute exists explain fetch first flatten for force from ' + + 'function grant group gsi having if ignore ilike in include increment index infer inline inner ' + + 'insert intersect into is join key keys keyspace known last left let letting like limit lsm map ' + + 'mapping matched materialized merge minus namespace nest not number object offset on ' + + 'option or order outer over parse partition password path pool prepare primary private privilege ' + + 'procedure public raw realm reduce rename return returning revoke right role rollback satisfies ' + + 'schema select self semi set show some start statistics string system then to transaction trigger ' + + 'truncate under union unique unknown unnest unset update upsert use user using validate value ' + + 'valued values via view when where while with within work xor', + // Taken from http://developer.couchbase.com/documentation/server/4.5/n1ql/n1ql-language-reference/literals.html + literal: + 'true false null missing|5', + // Taken from http://developer.couchbase.com/documentation/server/4.5/n1ql/n1ql-language-reference/functions.html + built_in: + 'array_agg array_append array_concat array_contains array_count array_distinct array_ifnull array_length ' + + 'array_max array_min array_position array_prepend array_put array_range array_remove array_repeat array_replace ' + + 'array_reverse array_sort array_sum avg count max min sum greatest least ifmissing ifmissingornull ifnull ' + + 'missingif nullif ifinf ifnan ifnanorinf naninf neginfif posinfif clock_millis clock_str date_add_millis ' + + 'date_add_str date_diff_millis date_diff_str date_part_millis date_part_str date_trunc_millis date_trunc_str ' + + 'duration_to_str millis str_to_millis millis_to_str millis_to_utc millis_to_zone_name now_millis now_str ' + + 'str_to_duration str_to_utc str_to_zone_name decode_json encode_json encoded_size poly_length base64 base64_encode ' + + 'base64_decode meta uuid abs acos asin atan atan2 ceil cos degrees e exp ln log floor pi power radians random ' + + 'round sign sin sqrt tan trunc object_length object_names object_pairs object_inner_pairs object_values ' + + 'object_inner_values object_add object_put object_remove object_unwrap regexp_contains regexp_like regexp_position ' + + 'regexp_replace contains initcap length lower ltrim position repeat replace rtrim split substr title trim upper ' + + 'isarray isatom isboolean isnumber isobject isstring type toarray toatom toboolean tonumber toobject tostring' + }, + contains: [ + { + className: 'string', + begin: '\'', end: '\'', + contains: [hljs.BACKSLASH_ESCAPE] + }, + { + className: 'string', + begin: '"', end: '"', + contains: [hljs.BACKSLASH_ESCAPE] + }, + { + className: 'symbol', + begin: '`', end: '`', + contains: [hljs.BACKSLASH_ESCAPE], + relevance: 2 + }, + hljs.C_NUMBER_MODE, + hljs.C_BLOCK_COMMENT_MODE + ] + }, + hljs.C_BLOCK_COMMENT_MODE + ] + }; +} + +module.exports = n1ql; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/nginx.js b/claude-code-source/node_modules/highlight.js/lib/languages/nginx.js new file mode 100644 index 00000000..186e2f41 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/nginx.js @@ -0,0 +1,140 @@ +/* +Language: Nginx config +Author: Peter Leonov +Contributors: Ivan Sagalaev +Category: common, config +Website: https://www.nginx.com +*/ + +function nginx(hljs) { + const VAR = { + className: 'variable', + variants: [ + { + begin: /\$\d+/ + }, + { + begin: /\$\{/, + end: /\}/ + }, + { + begin: /[$@]/ + hljs.UNDERSCORE_IDENT_RE + } + ] + }; + const DEFAULT = { + endsWithParent: true, + keywords: { + $pattern: '[a-z/_]+', + literal: + 'on off yes no true false none blocked debug info notice warn error crit ' + + 'select break last permanent redirect kqueue rtsig epoll poll /dev/poll' + }, + relevance: 0, + illegal: '=>', + contains: [ + hljs.HASH_COMMENT_MODE, + { + className: 'string', + contains: [ + hljs.BACKSLASH_ESCAPE, + VAR + ], + variants: [ + { + begin: /"/, + end: /"/ + }, + { + begin: /'/, + end: /'/ + } + ] + }, + // this swallows entire URLs to avoid detecting numbers within + { + begin: '([a-z]+):/', + end: '\\s', + endsWithParent: true, + excludeEnd: true, + contains: [ VAR ] + }, + { + className: 'regexp', + contains: [ + hljs.BACKSLASH_ESCAPE, + VAR + ], + variants: [ + { + begin: "\\s\\^", + end: "\\s|\\{|;", + returnEnd: true + }, + // regexp locations (~, ~*) + { + begin: "~\\*?\\s+", + end: "\\s|\\{|;", + returnEnd: true + }, + // *.example.com + { + begin: "\\*(\\.[a-z\\-]+)+" + }, + // sub.example.* + { + begin: "([a-z\\-]+\\.)+\\*" + } + ] + }, + // IP + { + className: 'number', + begin: '\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}(:\\d{1,5})?\\b' + }, + // units + { + className: 'number', + begin: '\\b\\d+[kKmMgGdshdwy]*\\b', + relevance: 0 + }, + VAR + ] + }; + + return { + name: 'Nginx config', + aliases: [ 'nginxconf' ], + contains: [ + hljs.HASH_COMMENT_MODE, + { + begin: hljs.UNDERSCORE_IDENT_RE + '\\s+\\{', + returnBegin: true, + end: /\{/, + contains: [ + { + className: 'section', + begin: hljs.UNDERSCORE_IDENT_RE + } + ], + relevance: 0 + }, + { + begin: hljs.UNDERSCORE_IDENT_RE + '\\s', + end: ';|\\{', + returnBegin: true, + contains: [ + { + className: 'attribute', + begin: hljs.UNDERSCORE_IDENT_RE, + starts: DEFAULT + } + ], + relevance: 0 + } + ], + illegal: '[^\\s\\}]' + }; +} + +module.exports = nginx; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/nim.js b/claude-code-source/node_modules/highlight.js/lib/languages/nim.js new file mode 100644 index 00000000..b77dc848 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/nim.js @@ -0,0 +1,79 @@ +/* +Language: Nim +Description: Nim is a statically typed compiled systems programming language. +Website: https://nim-lang.org +Category: system +*/ + +function nim(hljs) { + return { + name: 'Nim', + keywords: { + keyword: + 'addr and as asm bind block break case cast const continue converter ' + + 'discard distinct div do elif else end enum except export finally ' + + 'for from func generic if import in include interface is isnot iterator ' + + 'let macro method mixin mod nil not notin object of or out proc ptr ' + + 'raise ref return shl shr static template try tuple type using var ' + + 'when while with without xor yield', + literal: + 'shared guarded stdin stdout stderr result true false', + built_in: + 'int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64 float ' + + 'float32 float64 bool char string cstring pointer expr stmt void ' + + 'auto any range array openarray varargs seq set clong culong cchar ' + + 'cschar cshort cint csize clonglong cfloat cdouble clongdouble ' + + 'cuchar cushort cuint culonglong cstringarray semistatic' + }, + contains: [ + { + className: 'meta', // Actually pragma + begin: /\{\./, + end: /\.\}/, + relevance: 10 + }, + { + className: 'string', + begin: /[a-zA-Z]\w*"/, + end: /"/, + contains: [ + { + begin: /""/ + } + ] + }, + { + className: 'string', + begin: /([a-zA-Z]\w*)?"""/, + end: /"""/ + }, + hljs.QUOTE_STRING_MODE, + { + className: 'type', + begin: /\b[A-Z]\w+\b/, + relevance: 0 + }, + { + className: 'number', + relevance: 0, + variants: [ + { + begin: /\b(0[xX][0-9a-fA-F][_0-9a-fA-F]*)('?[iIuU](8|16|32|64))?/ + }, + { + begin: /\b(0o[0-7][_0-7]*)('?[iIuUfF](8|16|32|64))?/ + }, + { + begin: /\b(0(b|B)[01][_01]*)('?[iIuUfF](8|16|32|64))?/ + }, + { + begin: /\b(\d[_\d]*)('?[iIuUfF](8|16|32|64))?/ + } + ] + }, + hljs.HASH_COMMENT_MODE + ] + }; +} + +module.exports = nim; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/nix.js b/claude-code-source/node_modules/highlight.js/lib/languages/nix.js new file mode 100644 index 00000000..15b945e3 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/nix.js @@ -0,0 +1,65 @@ +/* +Language: Nix +Author: Domen Kožar +Description: Nix functional language +Website: http://nixos.org/nix +*/ + +function nix(hljs) { + const NIX_KEYWORDS = { + keyword: + 'rec with let in inherit assert if else then', + literal: + 'true false or and null', + built_in: + 'import abort baseNameOf dirOf isNull builtins map removeAttrs throw ' + + 'toString derivation' + }; + const ANTIQUOTE = { + className: 'subst', + begin: /\$\{/, + end: /\}/, + keywords: NIX_KEYWORDS + }; + const ATTRS = { + begin: /[a-zA-Z0-9-_]+(\s*=)/, + returnBegin: true, + relevance: 0, + contains: [ + { + className: 'attr', + begin: /\S+/ + } + ] + }; + const STRING = { + className: 'string', + contains: [ ANTIQUOTE ], + variants: [ + { + begin: "''", + end: "''" + }, + { + begin: '"', + end: '"' + } + ] + }; + const EXPRESSIONS = [ + hljs.NUMBER_MODE, + hljs.HASH_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + STRING, + ATTRS + ]; + ANTIQUOTE.contains = EXPRESSIONS; + return { + name: 'Nix', + aliases: [ "nixos" ], + keywords: NIX_KEYWORDS, + contains: EXPRESSIONS + }; +} + +module.exports = nix; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/node-repl.js b/claude-code-source/node_modules/highlight.js/lib/languages/node-repl.js new file mode 100644 index 00000000..15e3b66d --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/node-repl.js @@ -0,0 +1,37 @@ +/* +Language: Node REPL +Requires: javascript.js +Author: Marat Nagayev +Category: scripting +*/ + +/** @type LanguageFn */ +function nodeRepl(hljs) { + return { + name: 'Node REPL', + contains: [ + { + className: 'meta', + starts: { + // a space separates the REPL prefix from the actual code + // this is purely for cleaner HTML output + end: / |$/, + starts: { + end: '$', + subLanguage: 'javascript' + } + }, + variants: [ + { + begin: /^>(?=[ ]|$)/ + }, + { + begin: /^\.\.\.(?=[ ]|$)/ + } + ] + } + ] + }; +} + +module.exports = nodeRepl; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/nsis.js b/claude-code-source/node_modules/highlight.js/lib/languages/nsis.js new file mode 100644 index 00000000..da621ba2 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/nsis.js @@ -0,0 +1,119 @@ +/* +Language: NSIS +Description: Nullsoft Scriptable Install System +Author: Jan T. Sott +Website: https://nsis.sourceforge.io/Main_Page +*/ + +function nsis(hljs) { + const CONSTANTS = { + className: 'variable', + begin: /\$(ADMINTOOLS|APPDATA|CDBURN_AREA|CMDLINE|COMMONFILES32|COMMONFILES64|COMMONFILES|COOKIES|DESKTOP|DOCUMENTS|EXEDIR|EXEFILE|EXEPATH|FAVORITES|FONTS|HISTORY|HWNDPARENT|INSTDIR|INTERNET_CACHE|LANGUAGE|LOCALAPPDATA|MUSIC|NETHOOD|OUTDIR|PICTURES|PLUGINSDIR|PRINTHOOD|PROFILE|PROGRAMFILES32|PROGRAMFILES64|PROGRAMFILES|QUICKLAUNCH|RECENT|RESOURCES_LOCALIZED|RESOURCES|SENDTO|SMPROGRAMS|SMSTARTUP|STARTMENU|SYSDIR|TEMP|TEMPLATES|VIDEOS|WINDIR)/ + }; + + const DEFINES = { + // ${defines} + className: 'variable', + begin: /\$+\{[\w.:-]+\}/ + }; + + const VARIABLES = { + // $variables + className: 'variable', + begin: /\$+\w+/, + illegal: /\(\)\{\}/ + }; + + const LANGUAGES = { + // $(language_strings) + className: 'variable', + begin: /\$+\([\w^.:-]+\)/ + }; + + const PARAMETERS = { + // command parameters + className: 'params', + begin: '(ARCHIVE|FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_NORMAL|FILE_ATTRIBUTE_OFFLINE|FILE_ATTRIBUTE_READONLY|FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_TEMPORARY|HKCR|HKCU|HKDD|HKEY_CLASSES_ROOT|HKEY_CURRENT_CONFIG|HKEY_CURRENT_USER|HKEY_DYN_DATA|HKEY_LOCAL_MACHINE|HKEY_PERFORMANCE_DATA|HKEY_USERS|HKLM|HKPD|HKU|IDABORT|IDCANCEL|IDIGNORE|IDNO|IDOK|IDRETRY|IDYES|MB_ABORTRETRYIGNORE|MB_DEFBUTTON1|MB_DEFBUTTON2|MB_DEFBUTTON3|MB_DEFBUTTON4|MB_ICONEXCLAMATION|MB_ICONINFORMATION|MB_ICONQUESTION|MB_ICONSTOP|MB_OK|MB_OKCANCEL|MB_RETRYCANCEL|MB_RIGHT|MB_RTLREADING|MB_SETFOREGROUND|MB_TOPMOST|MB_USERICON|MB_YESNO|NORMAL|OFFLINE|READONLY|SHCTX|SHELL_CONTEXT|SYSTEM|TEMPORARY)' + }; + + const COMPILER = { + // !compiler_flags + className: 'keyword', + begin: /!(addincludedir|addplugindir|appendfile|cd|define|delfile|echo|else|endif|error|execute|finalize|getdllversion|gettlbversion|if|ifdef|ifmacrodef|ifmacrondef|ifndef|include|insertmacro|macro|macroend|makensis|packhdr|searchparse|searchreplace|system|tempfile|undef|verbose|warning)/ + }; + + const METACHARS = { + // $\n, $\r, $\t, $$ + className: 'meta', + begin: /\$(\\[nrt]|\$)/ + }; + + const PLUGINS = { + // plug::ins + className: 'class', + begin: /\w+::\w+/ + }; + + const STRING = { + className: 'string', + variants: [ + { + begin: '"', + end: '"' + }, + { + begin: '\'', + end: '\'' + }, + { + begin: '`', + end: '`' + } + ], + illegal: /\n/, + contains: [ + METACHARS, + CONSTANTS, + DEFINES, + VARIABLES, + LANGUAGES + ] + }; + + return { + name: 'NSIS', + case_insensitive: false, + keywords: { + keyword: + 'Abort AddBrandingImage AddSize AllowRootDirInstall AllowSkipFiles AutoCloseWindow BGFont BGGradient BrandingText BringToFront Call CallInstDLL Caption ChangeUI CheckBitmap ClearErrors CompletedText ComponentText CopyFiles CRCCheck CreateDirectory CreateFont CreateShortCut Delete DeleteINISec DeleteINIStr DeleteRegKey DeleteRegValue DetailPrint DetailsButtonText DirText DirVar DirVerify EnableWindow EnumRegKey EnumRegValue Exch Exec ExecShell ExecShellWait ExecWait ExpandEnvStrings File FileBufSize FileClose FileErrorText FileOpen FileRead FileReadByte FileReadUTF16LE FileReadWord FileWriteUTF16LE FileSeek FileWrite FileWriteByte FileWriteWord FindClose FindFirst FindNext FindWindow FlushINI GetCurInstType GetCurrentAddress GetDlgItem GetDLLVersion GetDLLVersionLocal GetErrorLevel GetFileTime GetFileTimeLocal GetFullPathName GetFunctionAddress GetInstDirError GetKnownFolderPath GetLabelAddress GetTempFileName Goto HideWindow Icon IfAbort IfErrors IfFileExists IfRebootFlag IfRtlLanguage IfShellVarContextAll IfSilent InitPluginsDir InstallButtonText InstallColors InstallDir InstallDirRegKey InstProgressFlags InstType InstTypeGetText InstTypeSetText Int64Cmp Int64CmpU Int64Fmt IntCmp IntCmpU IntFmt IntOp IntPtrCmp IntPtrCmpU IntPtrOp IsWindow LangString LicenseBkColor LicenseData LicenseForceSelection LicenseLangString LicenseText LoadAndSetImage LoadLanguageFile LockWindow LogSet LogText ManifestDPIAware ManifestLongPathAware ManifestMaxVersionTested ManifestSupportedOS MessageBox MiscButtonText Name Nop OutFile Page PageCallbacks PEAddResource PEDllCharacteristics PERemoveResource PESubsysVer Pop Push Quit ReadEnvStr ReadINIStr ReadRegDWORD ReadRegStr Reboot RegDLL Rename RequestExecutionLevel ReserveFile Return RMDir SearchPath SectionGetFlags SectionGetInstTypes SectionGetSize SectionGetText SectionIn SectionSetFlags SectionSetInstTypes SectionSetSize SectionSetText SendMessage SetAutoClose SetBrandingImage SetCompress SetCompressor SetCompressorDictSize SetCtlColors SetCurInstType SetDatablockOptimize SetDateSave SetDetailsPrint SetDetailsView SetErrorLevel SetErrors SetFileAttributes SetFont SetOutPath SetOverwrite SetRebootFlag SetRegView SetShellVarContext SetSilent ShowInstDetails ShowUninstDetails ShowWindow SilentInstall SilentUnInstall Sleep SpaceTexts StrCmp StrCmpS StrCpy StrLen SubCaption Unicode UninstallButtonText UninstallCaption UninstallIcon UninstallSubCaption UninstallText UninstPage UnRegDLL Var VIAddVersionKey VIFileVersion VIProductVersion WindowIcon WriteINIStr WriteRegBin WriteRegDWORD WriteRegExpandStr WriteRegMultiStr WriteRegNone WriteRegStr WriteUninstaller XPStyle', + literal: + 'admin all auto both bottom bzip2 colored components current custom directory false force hide highest ifdiff ifnewer instfiles lastused leave left license listonly lzma nevershow none normal notset off on open print right show silent silentlog smooth textonly top true try un.components un.custom un.directory un.instfiles un.license uninstConfirm user Win10 Win7 Win8 WinVista zlib' + }, + contains: [ + hljs.HASH_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.COMMENT( + ';', + '$', + { + relevance: 0 + } + ), + { + className: 'function', + beginKeywords: 'Function PageEx Section SectionGroup', + end: '$' + }, + STRING, + COMPILER, + DEFINES, + VARIABLES, + LANGUAGES, + PARAMETERS, + PLUGINS, + hljs.NUMBER_MODE + ] + }; +} + +module.exports = nsis; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/objectivec.js b/claude-code-source/node_modules/highlight.js/lib/languages/objectivec.js new file mode 100644 index 00000000..18016ef9 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/objectivec.js @@ -0,0 +1,121 @@ +/* +Language: Objective-C +Author: Valerii Hiora +Contributors: Angel G. Olloqui , Matt Diephouse , Andrew Farmer , Minh Nguyễn +Website: https://developer.apple.com/documentation/objectivec +Category: common +*/ + +function objectivec(hljs) { + const API_CLASS = { + className: 'built_in', + begin: '\\b(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)\\w+' + }; + const IDENTIFIER_RE = /[a-zA-Z@][a-zA-Z0-9_]*/; + const OBJC_KEYWORDS = { + $pattern: IDENTIFIER_RE, + keyword: + 'int float while char export sizeof typedef const struct for union ' + + 'unsigned long volatile static bool mutable if do return goto void ' + + 'enum else break extern asm case short default double register explicit ' + + 'signed typename this switch continue wchar_t inline readonly assign ' + + 'readwrite self @synchronized id typeof ' + + 'nonatomic super unichar IBOutlet IBAction strong weak copy ' + + 'in out inout bycopy byref oneway __strong __weak __block __autoreleasing ' + + '@private @protected @public @try @property @end @throw @catch @finally ' + + '@autoreleasepool @synthesize @dynamic @selector @optional @required ' + + '@encode @package @import @defs @compatibility_alias ' + + '__bridge __bridge_transfer __bridge_retained __bridge_retain ' + + '__covariant __contravariant __kindof ' + + '_Nonnull _Nullable _Null_unspecified ' + + '__FUNCTION__ __PRETTY_FUNCTION__ __attribute__ ' + + 'getter setter retain unsafe_unretained ' + + 'nonnull nullable null_unspecified null_resettable class instancetype ' + + 'NS_DESIGNATED_INITIALIZER NS_UNAVAILABLE NS_REQUIRES_SUPER ' + + 'NS_RETURNS_INNER_POINTER NS_INLINE NS_AVAILABLE NS_DEPRECATED ' + + 'NS_ENUM NS_OPTIONS NS_SWIFT_UNAVAILABLE ' + + 'NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_END ' + + 'NS_REFINED_FOR_SWIFT NS_SWIFT_NAME NS_SWIFT_NOTHROW ' + + 'NS_DURING NS_HANDLER NS_ENDHANDLER NS_VALUERETURN NS_VOIDRETURN', + literal: + 'false true FALSE TRUE nil YES NO NULL', + built_in: + 'BOOL dispatch_once_t dispatch_queue_t dispatch_sync dispatch_async dispatch_once' + }; + const CLASS_KEYWORDS = { + $pattern: IDENTIFIER_RE, + keyword: '@interface @class @protocol @implementation' + }; + return { + name: 'Objective-C', + aliases: [ + 'mm', + 'objc', + 'obj-c', + 'obj-c++', + 'objective-c++' + ], + keywords: OBJC_KEYWORDS, + illegal: '/, + end: /$/, + illegal: '\\n' + }, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE + ] + }, + { + className: 'class', + begin: '(' + CLASS_KEYWORDS.keyword.split(' ').join('|') + ')\\b', + end: /(\{|$)/, + excludeEnd: true, + keywords: CLASS_KEYWORDS, + contains: [ hljs.UNDERSCORE_TITLE_MODE ] + }, + { + begin: '\\.' + hljs.UNDERSCORE_IDENT_RE, + relevance: 0 + } + ] + }; +} + +module.exports = objectivec; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/ocaml.js b/claude-code-source/node_modules/highlight.js/lib/languages/ocaml.js new file mode 100644 index 00000000..3e617bde --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/ocaml.js @@ -0,0 +1,82 @@ +/* +Language: OCaml +Author: Mehdi Dogguy +Contributors: Nicolas Braud-Santoni , Mickael Delahaye +Description: OCaml language definition. +Website: https://ocaml.org +Category: functional +*/ + +function ocaml(hljs) { + /* missing support for heredoc-like string (OCaml 4.0.2+) */ + return { + name: 'OCaml', + aliases: ['ml'], + keywords: { + $pattern: '[a-z_]\\w*!?', + keyword: + 'and as assert asr begin class constraint do done downto else end ' + + 'exception external for fun function functor if in include ' + + 'inherit! inherit initializer land lazy let lor lsl lsr lxor match method!|10 method ' + + 'mod module mutable new object of open! open or private rec sig struct ' + + 'then to try type val! val virtual when while with ' + + /* camlp4 */ + 'parser value', + built_in: + /* built-in types */ + 'array bool bytes char exn|5 float int int32 int64 list lazy_t|5 nativeint|5 string unit ' + + /* (some) types in Pervasives */ + 'in_channel out_channel ref', + literal: + 'true false' + }, + illegal: /\/\/|>>/, + contains: [ + { + className: 'literal', + begin: '\\[(\\|\\|)?\\]|\\(\\)', + relevance: 0 + }, + hljs.COMMENT( + '\\(\\*', + '\\*\\)', + { + contains: ['self'] + } + ), + { /* type variable */ + className: 'symbol', + begin: '\'[A-Za-z_](?!\')[\\w\']*' + /* the grammar is ambiguous on how 'a'b should be interpreted but not the compiler */ + }, + { /* polymorphic variant */ + className: 'type', + begin: '`[A-Z][\\w\']*' + }, + { /* module or constructor */ + className: 'type', + begin: '\\b[A-Z][\\w\']*', + relevance: 0 + }, + { /* don't color identifiers, but safely catch all identifiers with '*/ + begin: '[a-z_]\\w*\'[\\w\']*', relevance: 0 + }, + hljs.inherit(hljs.APOS_STRING_MODE, {className: 'string', relevance: 0}), + hljs.inherit(hljs.QUOTE_STRING_MODE, {illegal: null}), + { + className: 'number', + begin: + '\\b(0[xX][a-fA-F0-9_]+[Lln]?|' + + '0[oO][0-7_]+[Lln]?|' + + '0[bB][01_]+[Lln]?|' + + '[0-9][0-9_]*([Lln]|(\\.[0-9_]*)?([eE][-+]?[0-9_]+)?)?)', + relevance: 0 + }, + { + begin: /->/ // relevance booster + } + ] + } +} + +module.exports = ocaml; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/openscad.js b/claude-code-source/node_modules/highlight.js/lib/languages/openscad.js new file mode 100644 index 00000000..54708058 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/openscad.js @@ -0,0 +1,81 @@ +/* +Language: OpenSCAD +Author: Dan Panzarella +Description: OpenSCAD is a language for the 3D CAD modeling software of the same name. +Website: https://www.openscad.org +Category: scientific +*/ + +function openscad(hljs) { + const SPECIAL_VARS = { + className: 'keyword', + begin: '\\$(f[asn]|t|vp[rtd]|children)' + }; + const LITERALS = { + className: 'literal', + begin: 'false|true|PI|undef' + }; + const NUMBERS = { + className: 'number', + begin: '\\b\\d+(\\.\\d+)?(e-?\\d+)?', // adds 1e5, 1e-10 + relevance: 0 + }; + const STRING = hljs.inherit(hljs.QUOTE_STRING_MODE, { + illegal: null + }); + const PREPRO = { + className: 'meta', + keywords: { + 'meta-keyword': 'include use' + }, + begin: 'include|use <', + end: '>' + }; + const PARAMS = { + className: 'params', + begin: '\\(', + end: '\\)', + contains: [ + 'self', + NUMBERS, + STRING, + SPECIAL_VARS, + LITERALS + ] + }; + const MODIFIERS = { + begin: '[*!#%]', + relevance: 0 + }; + const FUNCTIONS = { + className: 'function', + beginKeywords: 'module function', + end: /=|\{/, + contains: [ + PARAMS, + hljs.UNDERSCORE_TITLE_MODE + ] + }; + + return { + name: 'OpenSCAD', + aliases: [ 'scad' ], + keywords: { + keyword: 'function module include use for intersection_for if else \\%', + literal: 'false true PI undef', + built_in: 'circle square polygon text sphere cube cylinder polyhedron translate rotate scale resize mirror multmatrix color offset hull minkowski union difference intersection abs sign sin cos tan acos asin atan atan2 floor round ceil ln log pow sqrt exp rands min max concat lookup str chr search version version_num norm cross parent_module echo import import_dxf dxf_linear_extrude linear_extrude rotate_extrude surface projection render children dxf_cross dxf_dim let assign' + }, + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + NUMBERS, + PREPRO, + STRING, + SPECIAL_VARS, + MODIFIERS, + FUNCTIONS + ] + }; +} + +module.exports = openscad; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/oxygene.js b/claude-code-source/node_modules/highlight.js/lib/languages/oxygene.js new file mode 100644 index 00000000..4649cf87 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/oxygene.js @@ -0,0 +1,101 @@ +/* +Language: Oxygene +Author: Carlo Kok +Description: Oxygene is built on the foundation of Object Pascal, revamped and extended to be a modern language for the twenty-first century. +Website: https://www.elementscompiler.com/elements/default.aspx +*/ + +function oxygene(hljs) { + const OXYGENE_KEYWORDS = { + $pattern: /\.?\w+/, + keyword: + 'abstract add and array as asc aspect assembly async begin break block by case class concat const copy constructor continue ' + + 'create default delegate desc distinct div do downto dynamic each else empty end ensure enum equals event except exit extension external false ' + + 'final finalize finalizer finally flags for forward from function future global group has if implementation implements implies in index inherited ' + + 'inline interface into invariants is iterator join locked locking loop matching method mod module namespace nested new nil not notify nullable of ' + + 'old on operator or order out override parallel params partial pinned private procedure property protected public queryable raise read readonly ' + + 'record reintroduce remove repeat require result reverse sealed select self sequence set shl shr skip static step soft take then to true try tuple ' + + 'type union unit unsafe until uses using var virtual raises volatile where while with write xor yield await mapped deprecated stdcall cdecl pascal ' + + 'register safecall overload library platform reference packed strict published autoreleasepool selector strong weak unretained' + }; + const CURLY_COMMENT = hljs.COMMENT( + /\{/, + /\}/, + { + relevance: 0 + } + ); + const PAREN_COMMENT = hljs.COMMENT( + '\\(\\*', + '\\*\\)', + { + relevance: 10 + } + ); + const STRING = { + className: 'string', + begin: '\'', + end: '\'', + contains: [ + { + begin: '\'\'' + } + ] + }; + const CHAR_STRING = { + className: 'string', + begin: '(#\\d+)+' + }; + const FUNCTION = { + className: 'function', + beginKeywords: 'function constructor destructor procedure method', + end: '[:;]', + keywords: 'function constructor|10 destructor|10 procedure|10 method|10', + contains: [ + hljs.TITLE_MODE, + { + className: 'params', + begin: '\\(', + end: '\\)', + keywords: OXYGENE_KEYWORDS, + contains: [ + STRING, + CHAR_STRING + ] + }, + CURLY_COMMENT, + PAREN_COMMENT + ] + }; + return { + name: 'Oxygene', + case_insensitive: true, + keywords: OXYGENE_KEYWORDS, + illegal: '("|\\$[G-Zg-z]|\\/\\*||->)', + contains: [ + CURLY_COMMENT, + PAREN_COMMENT, + hljs.C_LINE_COMMENT_MODE, + STRING, + CHAR_STRING, + hljs.NUMBER_MODE, + FUNCTION, + { + className: 'class', + begin: '=\\bclass\\b', + end: 'end;', + keywords: OXYGENE_KEYWORDS, + contains: [ + STRING, + CHAR_STRING, + CURLY_COMMENT, + PAREN_COMMENT, + hljs.C_LINE_COMMENT_MODE, + FUNCTION + ] + } + ] + }; +} + +module.exports = oxygene; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/parser3.js b/claude-code-source/node_modules/highlight.js/lib/languages/parser3.js new file mode 100644 index 00000000..708b02c4 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/parser3.js @@ -0,0 +1,57 @@ +/* +Language: Parser3 +Requires: xml.js +Author: Oleg Volchkov +Website: https://www.parser.ru/en/ +Category: template +*/ + +function parser3(hljs) { + const CURLY_SUBCOMMENT = hljs.COMMENT( + /\{/, + /\}/, + { + contains: [ 'self' ] + } + ); + return { + name: 'Parser3', + subLanguage: 'xml', + relevance: 0, + contains: [ + hljs.COMMENT('^#', '$'), + hljs.COMMENT( + /\^rem\{/, + /\}/, + { + relevance: 10, + contains: [ CURLY_SUBCOMMENT ] + } + ), + { + className: 'meta', + begin: '^@(?:BASE|USE|CLASS|OPTIONS)$', + relevance: 10 + }, + { + className: 'title', + begin: '@[\\w\\-]+\\[[\\w^;\\-]*\\](?:\\[[\\w^;\\-]*\\])?(?:.*)$' + }, + { + className: 'variable', + begin: /\$\{?[\w\-.:]+\}?/ + }, + { + className: 'keyword', + begin: /\^[\w\-.:]+/ + }, + { + className: 'number', + begin: '\\^#[0-9a-fA-F]+' + }, + hljs.C_NUMBER_MODE + ] + }; +} + +module.exports = parser3; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/perl.js b/claude-code-source/node_modules/highlight.js/lib/languages/perl.js new file mode 100644 index 00000000..ff02952b --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/perl.js @@ -0,0 +1,515 @@ +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/** + * Any of the passed expresssions may match + * + * Creates a huge this | this | that | that match + * @param {(RegExp | string)[] } args + * @returns {string} + */ +function either(...args) { + const joined = '(' + args.map((x) => source(x)).join("|") + ")"; + return joined; +} + +/* +Language: Perl +Author: Peter Leonov +Website: https://www.perl.org +Category: common +*/ + +/** @type LanguageFn */ +function perl(hljs) { + const KEYWORDS = [ + 'abs', + 'accept', + 'alarm', + 'and', + 'atan2', + 'bind', + 'binmode', + 'bless', + 'break', + 'caller', + 'chdir', + 'chmod', + 'chomp', + 'chop', + 'chown', + 'chr', + 'chroot', + 'close', + 'closedir', + 'connect', + 'continue', + 'cos', + 'crypt', + 'dbmclose', + 'dbmopen', + 'defined', + 'delete', + 'die', + 'do', + 'dump', + 'each', + 'else', + 'elsif', + 'endgrent', + 'endhostent', + 'endnetent', + 'endprotoent', + 'endpwent', + 'endservent', + 'eof', + 'eval', + 'exec', + 'exists', + 'exit', + 'exp', + 'fcntl', + 'fileno', + 'flock', + 'for', + 'foreach', + 'fork', + 'format', + 'formline', + 'getc', + 'getgrent', + 'getgrgid', + 'getgrnam', + 'gethostbyaddr', + 'gethostbyname', + 'gethostent', + 'getlogin', + 'getnetbyaddr', + 'getnetbyname', + 'getnetent', + 'getpeername', + 'getpgrp', + 'getpriority', + 'getprotobyname', + 'getprotobynumber', + 'getprotoent', + 'getpwent', + 'getpwnam', + 'getpwuid', + 'getservbyname', + 'getservbyport', + 'getservent', + 'getsockname', + 'getsockopt', + 'given', + 'glob', + 'gmtime', + 'goto', + 'grep', + 'gt', + 'hex', + 'if', + 'index', + 'int', + 'ioctl', + 'join', + 'keys', + 'kill', + 'last', + 'lc', + 'lcfirst', + 'length', + 'link', + 'listen', + 'local', + 'localtime', + 'log', + 'lstat', + 'lt', + 'ma', + 'map', + 'mkdir', + 'msgctl', + 'msgget', + 'msgrcv', + 'msgsnd', + 'my', + 'ne', + 'next', + 'no', + 'not', + 'oct', + 'open', + 'opendir', + 'or', + 'ord', + 'our', + 'pack', + 'package', + 'pipe', + 'pop', + 'pos', + 'print', + 'printf', + 'prototype', + 'push', + 'q|0', + 'qq', + 'quotemeta', + 'qw', + 'qx', + 'rand', + 'read', + 'readdir', + 'readline', + 'readlink', + 'readpipe', + 'recv', + 'redo', + 'ref', + 'rename', + 'require', + 'reset', + 'return', + 'reverse', + 'rewinddir', + 'rindex', + 'rmdir', + 'say', + 'scalar', + 'seek', + 'seekdir', + 'select', + 'semctl', + 'semget', + 'semop', + 'send', + 'setgrent', + 'sethostent', + 'setnetent', + 'setpgrp', + 'setpriority', + 'setprotoent', + 'setpwent', + 'setservent', + 'setsockopt', + 'shift', + 'shmctl', + 'shmget', + 'shmread', + 'shmwrite', + 'shutdown', + 'sin', + 'sleep', + 'socket', + 'socketpair', + 'sort', + 'splice', + 'split', + 'sprintf', + 'sqrt', + 'srand', + 'stat', + 'state', + 'study', + 'sub', + 'substr', + 'symlink', + 'syscall', + 'sysopen', + 'sysread', + 'sysseek', + 'system', + 'syswrite', + 'tell', + 'telldir', + 'tie', + 'tied', + 'time', + 'times', + 'tr', + 'truncate', + 'uc', + 'ucfirst', + 'umask', + 'undef', + 'unless', + 'unlink', + 'unpack', + 'unshift', + 'untie', + 'until', + 'use', + 'utime', + 'values', + 'vec', + 'wait', + 'waitpid', + 'wantarray', + 'warn', + 'when', + 'while', + 'write', + 'x|0', + 'xor', + 'y|0' + ]; + + // https://perldoc.perl.org/perlre#Modifiers + const REGEX_MODIFIERS = /[dualxmsipngr]{0,12}/; // aa and xx are valid, making max length 12 + const PERL_KEYWORDS = { + $pattern: /[\w.]+/, + keyword: KEYWORDS.join(" ") + }; + const SUBST = { + className: 'subst', + begin: '[$@]\\{', + end: '\\}', + keywords: PERL_KEYWORDS + }; + const METHOD = { + begin: /->\{/, + end: /\}/ + // contains defined later + }; + const VAR = { + variants: [ + { + begin: /\$\d/ + }, + { + begin: concat( + /[$%@](\^\w\b|#\w+(::\w+)*|\{\w+\}|\w+(::\w*)*)/, + // negative look-ahead tries to avoid matching patterns that are not + // Perl at all like $ident$, @ident@, etc. + `(?![A-Za-z])(?![@$%])` + ) + }, + { + begin: /[$%@][^\s\w{]/, + relevance: 0 + } + ] + }; + const STRING_CONTAINS = [ + hljs.BACKSLASH_ESCAPE, + SUBST, + VAR + ]; + const REGEX_DELIMS = [ + /!/, + /\//, + /\|/, + /\?/, + /'/, + /"/, // valid but infrequent and weird + /#/ // valid but infrequent and weird + ]; + /** + * @param {string|RegExp} prefix + * @param {string|RegExp} open + * @param {string|RegExp} close + */ + const PAIRED_DOUBLE_RE = (prefix, open, close = '\\1') => { + const middle = (close === '\\1') + ? close + : concat(close, open); + return concat( + concat("(?:", prefix, ")"), + open, + /(?:\\.|[^\\\/])*?/, + middle, + /(?:\\.|[^\\\/])*?/, + close, + REGEX_MODIFIERS + ); + }; + /** + * @param {string|RegExp} prefix + * @param {string|RegExp} open + * @param {string|RegExp} close + */ + const PAIRED_RE = (prefix, open, close) => { + return concat( + concat("(?:", prefix, ")"), + open, + /(?:\\.|[^\\\/])*?/, + close, + REGEX_MODIFIERS + ); + }; + const PERL_DEFAULT_CONTAINS = [ + VAR, + hljs.HASH_COMMENT_MODE, + hljs.COMMENT( + /^=\w/, + /=cut/, + { + endsWithParent: true + } + ), + METHOD, + { + className: 'string', + contains: STRING_CONTAINS, + variants: [ + { + begin: 'q[qwxr]?\\s*\\(', + end: '\\)', + relevance: 5 + }, + { + begin: 'q[qwxr]?\\s*\\[', + end: '\\]', + relevance: 5 + }, + { + begin: 'q[qwxr]?\\s*\\{', + end: '\\}', + relevance: 5 + }, + { + begin: 'q[qwxr]?\\s*\\|', + end: '\\|', + relevance: 5 + }, + { + begin: 'q[qwxr]?\\s*<', + end: '>', + relevance: 5 + }, + { + begin: 'qw\\s+q', + end: 'q', + relevance: 5 + }, + { + begin: '\'', + end: '\'', + contains: [ hljs.BACKSLASH_ESCAPE ] + }, + { + begin: '"', + end: '"' + }, + { + begin: '`', + end: '`', + contains: [ hljs.BACKSLASH_ESCAPE ] + }, + { + begin: /\{\w+\}/, + relevance: 0 + }, + { + begin: '-?\\w+\\s*=>', + relevance: 0 + } + ] + }, + { + className: 'number', + begin: '(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b', + relevance: 0 + }, + { // regexp container + begin: '(\\/\\/|' + hljs.RE_STARTERS_RE + '|\\b(split|return|print|reverse|grep)\\b)\\s*', + keywords: 'split return print reverse grep', + relevance: 0, + contains: [ + hljs.HASH_COMMENT_MODE, + { + className: 'regexp', + variants: [ + // allow matching common delimiters + { begin: PAIRED_DOUBLE_RE("s|tr|y", either(...REGEX_DELIMS)) }, + // and then paired delmis + { begin: PAIRED_DOUBLE_RE("s|tr|y", "\\(", "\\)") }, + { begin: PAIRED_DOUBLE_RE("s|tr|y", "\\[", "\\]") }, + { begin: PAIRED_DOUBLE_RE("s|tr|y", "\\{", "\\}") } + ], + relevance: 2 + }, + { + className: 'regexp', + variants: [ + { + // could be a comment in many languages so do not count + // as relevant + begin: /(m|qr)\/\//, + relevance: 0 + }, + // prefix is optional with /regex/ + { begin: PAIRED_RE("(?:m|qr)?", /\//, /\//)}, + // allow matching common delimiters + { begin: PAIRED_RE("m|qr", either(...REGEX_DELIMS), /\1/)}, + // allow common paired delmins + { begin: PAIRED_RE("m|qr", /\(/, /\)/)}, + { begin: PAIRED_RE("m|qr", /\[/, /\]/)}, + { begin: PAIRED_RE("m|qr", /\{/, /\}/)} + ] + } + ] + }, + { + className: 'function', + beginKeywords: 'sub', + end: '(\\s*\\(.*?\\))?[;{]', + excludeEnd: true, + relevance: 5, + contains: [ hljs.TITLE_MODE ] + }, + { + begin: '-\\w\\b', + relevance: 0 + }, + { + begin: "^__DATA__$", + end: "^__END__$", + subLanguage: 'mojolicious', + contains: [ + { + begin: "^@@.*", + end: "$", + className: "comment" + } + ] + } + ]; + SUBST.contains = PERL_DEFAULT_CONTAINS; + METHOD.contains = PERL_DEFAULT_CONTAINS; + + return { + name: 'Perl', + aliases: [ + 'pl', + 'pm' + ], + keywords: PERL_KEYWORDS, + contains: PERL_DEFAULT_CONTAINS + }; +} + +module.exports = perl; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/pf.js b/claude-code-source/node_modules/highlight.js/lib/languages/pf.js new file mode 100644 index 00000000..60689360 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/pf.js @@ -0,0 +1,59 @@ +/* +Language: Packet Filter config +Description: pf.conf — packet filter configuration file (OpenBSD) +Author: Peter Piwowarski +Website: http://man.openbsd.org/pf.conf +Category: config +*/ + +function pf(hljs) { + const MACRO = { + className: 'variable', + begin: /\$[\w\d#@][\w\d_]*/ + }; + const TABLE = { + className: 'variable', + begin: /<(?!\/)/, + end: />/ + }; + + return { + name: 'Packet Filter config', + aliases: [ 'pf.conf' ], + keywords: { + $pattern: /[a-z0-9_<>-]+/, + built_in: /* block match pass are "actions" in pf.conf(5), the rest are + * lexically similar top-level commands. + */ + 'block match pass load anchor|5 antispoof|10 set table', + keyword: + 'in out log quick on rdomain inet inet6 proto from port os to route ' + + 'allow-opts divert-packet divert-reply divert-to flags group icmp-type ' + + 'icmp6-type label once probability recieved-on rtable prio queue ' + + 'tos tag tagged user keep fragment for os drop ' + + 'af-to|10 binat-to|10 nat-to|10 rdr-to|10 bitmask least-stats random round-robin ' + + 'source-hash static-port ' + + 'dup-to reply-to route-to ' + + 'parent bandwidth default min max qlimit ' + + 'block-policy debug fingerprints hostid limit loginterface optimization ' + + 'reassemble ruleset-optimization basic none profile skip state-defaults ' + + 'state-policy timeout ' + + 'const counters persist ' + + 'no modulate synproxy state|5 floating if-bound no-sync pflow|10 sloppy ' + + 'source-track global rule max-src-nodes max-src-states max-src-conn ' + + 'max-src-conn-rate overload flush ' + + 'scrub|5 max-mss min-ttl no-df|10 random-id', + literal: + 'all any no-route self urpf-failed egress|5 unknown' + }, + contains: [ + hljs.HASH_COMMENT_MODE, + hljs.NUMBER_MODE, + hljs.QUOTE_STRING_MODE, + MACRO, + TABLE + ] + }; +} + +module.exports = pf; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/pgsql.js b/claude-code-source/node_modules/highlight.js/lib/languages/pgsql.js new file mode 100644 index 00000000..9978c2dc --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/pgsql.js @@ -0,0 +1,630 @@ +/* +Language: PostgreSQL and PL/pgSQL +Author: Egor Rogov (e.rogov@postgrespro.ru) +Website: https://www.postgresql.org/docs/11/sql.html +Description: + This language incorporates both PostgreSQL SQL dialect and PL/pgSQL language. + It is based on PostgreSQL version 11. Some notes: + - Text in double-dollar-strings is _always_ interpreted as some programming code. Text + in ordinary quotes is _never_ interpreted that way and highlighted just as a string. + - There are quite a bit "special cases". That's because many keywords are not strictly + they are keywords in some contexts and ordinary identifiers in others. Only some + of such cases are handled; you still can get some of your identifiers highlighted + wrong way. + - Function names deliberately are not highlighted. There is no way to tell function + call from other constructs, hence we can't highlight _all_ function names. And + some names highlighted while others not looks ugly. +*/ + +function pgsql(hljs) { + const COMMENT_MODE = hljs.COMMENT('--', '$'); + const UNQUOTED_IDENT = '[a-zA-Z_][a-zA-Z_0-9$]*'; + const DOLLAR_STRING = '\\$([a-zA-Z_]?|[a-zA-Z_][a-zA-Z_0-9]*)\\$'; + const LABEL = '<<\\s*' + UNQUOTED_IDENT + '\\s*>>'; + + const SQL_KW = + // https://www.postgresql.org/docs/11/static/sql-keywords-appendix.html + // https://www.postgresql.org/docs/11/static/sql-commands.html + // SQL commands (starting words) + 'ABORT ALTER ANALYZE BEGIN CALL CHECKPOINT|10 CLOSE CLUSTER COMMENT COMMIT COPY CREATE DEALLOCATE DECLARE ' + + 'DELETE DISCARD DO DROP END EXECUTE EXPLAIN FETCH GRANT IMPORT INSERT LISTEN LOAD LOCK MOVE NOTIFY ' + + 'PREPARE REASSIGN|10 REFRESH REINDEX RELEASE RESET REVOKE ROLLBACK SAVEPOINT SECURITY SELECT SET SHOW ' + + 'START TRUNCATE UNLISTEN|10 UPDATE VACUUM|10 VALUES ' + + // SQL commands (others) + 'AGGREGATE COLLATION CONVERSION|10 DATABASE DEFAULT PRIVILEGES DOMAIN TRIGGER EXTENSION FOREIGN ' + + 'WRAPPER|10 TABLE FUNCTION GROUP LANGUAGE LARGE OBJECT MATERIALIZED VIEW OPERATOR CLASS ' + + 'FAMILY POLICY PUBLICATION|10 ROLE RULE SCHEMA SEQUENCE SERVER STATISTICS SUBSCRIPTION SYSTEM ' + + 'TABLESPACE CONFIGURATION DICTIONARY PARSER TEMPLATE TYPE USER MAPPING PREPARED ACCESS ' + + 'METHOD CAST AS TRANSFORM TRANSACTION OWNED TO INTO SESSION AUTHORIZATION ' + + 'INDEX PROCEDURE ASSERTION ' + + // additional reserved key words + 'ALL ANALYSE AND ANY ARRAY ASC ASYMMETRIC|10 BOTH CASE CHECK ' + + 'COLLATE COLUMN CONCURRENTLY|10 CONSTRAINT CROSS ' + + 'DEFERRABLE RANGE ' + + 'DESC DISTINCT ELSE EXCEPT FOR FREEZE|10 FROM FULL HAVING ' + + 'ILIKE IN INITIALLY INNER INTERSECT IS ISNULL JOIN LATERAL LEADING LIKE LIMIT ' + + 'NATURAL NOT NOTNULL NULL OFFSET ON ONLY OR ORDER OUTER OVERLAPS PLACING PRIMARY ' + + 'REFERENCES RETURNING SIMILAR SOME SYMMETRIC TABLESAMPLE THEN ' + + 'TRAILING UNION UNIQUE USING VARIADIC|10 VERBOSE WHEN WHERE WINDOW WITH ' + + // some of non-reserved (which are used in clauses or as PL/pgSQL keyword) + 'BY RETURNS INOUT OUT SETOF|10 IF STRICT CURRENT CONTINUE OWNER LOCATION OVER PARTITION WITHIN ' + + 'BETWEEN ESCAPE EXTERNAL INVOKER DEFINER WORK RENAME VERSION CONNECTION CONNECT ' + + 'TABLES TEMP TEMPORARY FUNCTIONS SEQUENCES TYPES SCHEMAS OPTION CASCADE RESTRICT ADD ADMIN ' + + 'EXISTS VALID VALIDATE ENABLE DISABLE REPLICA|10 ALWAYS PASSING COLUMNS PATH ' + + 'REF VALUE OVERRIDING IMMUTABLE STABLE VOLATILE BEFORE AFTER EACH ROW PROCEDURAL ' + + 'ROUTINE NO HANDLER VALIDATOR OPTIONS STORAGE OIDS|10 WITHOUT INHERIT DEPENDS CALLED ' + + 'INPUT LEAKPROOF|10 COST ROWS NOWAIT SEARCH UNTIL ENCRYPTED|10 PASSWORD CONFLICT|10 ' + + 'INSTEAD INHERITS CHARACTERISTICS WRITE CURSOR ALSO STATEMENT SHARE EXCLUSIVE INLINE ' + + 'ISOLATION REPEATABLE READ COMMITTED SERIALIZABLE UNCOMMITTED LOCAL GLOBAL SQL PROCEDURES ' + + 'RECURSIVE SNAPSHOT ROLLUP CUBE TRUSTED|10 INCLUDE FOLLOWING PRECEDING UNBOUNDED RANGE GROUPS ' + + 'UNENCRYPTED|10 SYSID FORMAT DELIMITER HEADER QUOTE ENCODING FILTER OFF ' + + // some parameters of VACUUM/ANALYZE/EXPLAIN + 'FORCE_QUOTE FORCE_NOT_NULL FORCE_NULL COSTS BUFFERS TIMING SUMMARY DISABLE_PAGE_SKIPPING ' + + // + 'RESTART CYCLE GENERATED IDENTITY DEFERRED IMMEDIATE LEVEL LOGGED UNLOGGED ' + + 'OF NOTHING NONE EXCLUDE ATTRIBUTE ' + + // from GRANT (not keywords actually) + 'USAGE ROUTINES ' + + // actually literals, but look better this way (due to IS TRUE, IS FALSE, ISNULL etc) + 'TRUE FALSE NAN INFINITY '; + + const ROLE_ATTRS = // only those not in keywrods already + 'SUPERUSER NOSUPERUSER CREATEDB NOCREATEDB CREATEROLE NOCREATEROLE INHERIT NOINHERIT ' + + 'LOGIN NOLOGIN REPLICATION NOREPLICATION BYPASSRLS NOBYPASSRLS '; + + const PLPGSQL_KW = + 'ALIAS BEGIN CONSTANT DECLARE END EXCEPTION RETURN PERFORM|10 RAISE GET DIAGNOSTICS ' + + 'STACKED|10 FOREACH LOOP ELSIF EXIT WHILE REVERSE SLICE DEBUG LOG INFO NOTICE WARNING ASSERT ' + + 'OPEN '; + + const TYPES = + // https://www.postgresql.org/docs/11/static/datatype.html + 'BIGINT INT8 BIGSERIAL SERIAL8 BIT VARYING VARBIT BOOLEAN BOOL BOX BYTEA CHARACTER CHAR VARCHAR ' + + 'CIDR CIRCLE DATE DOUBLE PRECISION FLOAT8 FLOAT INET INTEGER INT INT4 INTERVAL JSON JSONB LINE LSEG|10 ' + + 'MACADDR MACADDR8 MONEY NUMERIC DEC DECIMAL PATH POINT POLYGON REAL FLOAT4 SMALLINT INT2 ' + + 'SMALLSERIAL|10 SERIAL2|10 SERIAL|10 SERIAL4|10 TEXT TIME ZONE TIMETZ|10 TIMESTAMP TIMESTAMPTZ|10 TSQUERY|10 TSVECTOR|10 ' + + 'TXID_SNAPSHOT|10 UUID XML NATIONAL NCHAR ' + + 'INT4RANGE|10 INT8RANGE|10 NUMRANGE|10 TSRANGE|10 TSTZRANGE|10 DATERANGE|10 ' + + // pseudotypes + 'ANYELEMENT ANYARRAY ANYNONARRAY ANYENUM ANYRANGE CSTRING INTERNAL ' + + 'RECORD PG_DDL_COMMAND VOID UNKNOWN OPAQUE REFCURSOR ' + + // spec. type + 'NAME ' + + // OID-types + 'OID REGPROC|10 REGPROCEDURE|10 REGOPER|10 REGOPERATOR|10 REGCLASS|10 REGTYPE|10 REGROLE|10 ' + + 'REGNAMESPACE|10 REGCONFIG|10 REGDICTIONARY|10 ';// + + + const TYPES_RE = + TYPES.trim() + .split(' ') + .map(function(val) { return val.split('|')[0]; }) + .join('|'); + + const SQL_BI = + 'CURRENT_TIME CURRENT_TIMESTAMP CURRENT_USER CURRENT_CATALOG|10 CURRENT_DATE LOCALTIME LOCALTIMESTAMP ' + + 'CURRENT_ROLE|10 CURRENT_SCHEMA|10 SESSION_USER PUBLIC '; + + const PLPGSQL_BI = + 'FOUND NEW OLD TG_NAME|10 TG_WHEN|10 TG_LEVEL|10 TG_OP|10 TG_RELID|10 TG_RELNAME|10 ' + + 'TG_TABLE_NAME|10 TG_TABLE_SCHEMA|10 TG_NARGS|10 TG_ARGV|10 TG_EVENT|10 TG_TAG|10 ' + + // get diagnostics + 'ROW_COUNT RESULT_OID|10 PG_CONTEXT|10 RETURNED_SQLSTATE COLUMN_NAME CONSTRAINT_NAME ' + + 'PG_DATATYPE_NAME|10 MESSAGE_TEXT TABLE_NAME SCHEMA_NAME PG_EXCEPTION_DETAIL|10 ' + + 'PG_EXCEPTION_HINT|10 PG_EXCEPTION_CONTEXT|10 '; + + const PLPGSQL_EXCEPTIONS = + // exceptions https://www.postgresql.org/docs/current/static/errcodes-appendix.html + 'SQLSTATE SQLERRM|10 ' + + 'SUCCESSFUL_COMPLETION WARNING DYNAMIC_RESULT_SETS_RETURNED IMPLICIT_ZERO_BIT_PADDING ' + + 'NULL_VALUE_ELIMINATED_IN_SET_FUNCTION PRIVILEGE_NOT_GRANTED PRIVILEGE_NOT_REVOKED ' + + 'STRING_DATA_RIGHT_TRUNCATION DEPRECATED_FEATURE NO_DATA NO_ADDITIONAL_DYNAMIC_RESULT_SETS_RETURNED ' + + 'SQL_STATEMENT_NOT_YET_COMPLETE CONNECTION_EXCEPTION CONNECTION_DOES_NOT_EXIST CONNECTION_FAILURE ' + + 'SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION SQLSERVER_REJECTED_ESTABLISHMENT_OF_SQLCONNECTION ' + + 'TRANSACTION_RESOLUTION_UNKNOWN PROTOCOL_VIOLATION TRIGGERED_ACTION_EXCEPTION FEATURE_NOT_SUPPORTED ' + + 'INVALID_TRANSACTION_INITIATION LOCATOR_EXCEPTION INVALID_LOCATOR_SPECIFICATION INVALID_GRANTOR ' + + 'INVALID_GRANT_OPERATION INVALID_ROLE_SPECIFICATION DIAGNOSTICS_EXCEPTION ' + + 'STACKED_DIAGNOSTICS_ACCESSED_WITHOUT_ACTIVE_HANDLER CASE_NOT_FOUND CARDINALITY_VIOLATION ' + + 'DATA_EXCEPTION ARRAY_SUBSCRIPT_ERROR CHARACTER_NOT_IN_REPERTOIRE DATETIME_FIELD_OVERFLOW ' + + 'DIVISION_BY_ZERO ERROR_IN_ASSIGNMENT ESCAPE_CHARACTER_CONFLICT INDICATOR_OVERFLOW ' + + 'INTERVAL_FIELD_OVERFLOW INVALID_ARGUMENT_FOR_LOGARITHM INVALID_ARGUMENT_FOR_NTILE_FUNCTION ' + + 'INVALID_ARGUMENT_FOR_NTH_VALUE_FUNCTION INVALID_ARGUMENT_FOR_POWER_FUNCTION ' + + 'INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION INVALID_CHARACTER_VALUE_FOR_CAST ' + + 'INVALID_DATETIME_FORMAT INVALID_ESCAPE_CHARACTER INVALID_ESCAPE_OCTET INVALID_ESCAPE_SEQUENCE ' + + 'NONSTANDARD_USE_OF_ESCAPE_CHARACTER INVALID_INDICATOR_PARAMETER_VALUE INVALID_PARAMETER_VALUE ' + + 'INVALID_REGULAR_EXPRESSION INVALID_ROW_COUNT_IN_LIMIT_CLAUSE ' + + 'INVALID_ROW_COUNT_IN_RESULT_OFFSET_CLAUSE INVALID_TABLESAMPLE_ARGUMENT INVALID_TABLESAMPLE_REPEAT ' + + 'INVALID_TIME_ZONE_DISPLACEMENT_VALUE INVALID_USE_OF_ESCAPE_CHARACTER MOST_SPECIFIC_TYPE_MISMATCH ' + + 'NULL_VALUE_NOT_ALLOWED NULL_VALUE_NO_INDICATOR_PARAMETER NUMERIC_VALUE_OUT_OF_RANGE ' + + 'SEQUENCE_GENERATOR_LIMIT_EXCEEDED STRING_DATA_LENGTH_MISMATCH STRING_DATA_RIGHT_TRUNCATION ' + + 'SUBSTRING_ERROR TRIM_ERROR UNTERMINATED_C_STRING ZERO_LENGTH_CHARACTER_STRING ' + + 'FLOATING_POINT_EXCEPTION INVALID_TEXT_REPRESENTATION INVALID_BINARY_REPRESENTATION ' + + 'BAD_COPY_FILE_FORMAT UNTRANSLATABLE_CHARACTER NOT_AN_XML_DOCUMENT INVALID_XML_DOCUMENT ' + + 'INVALID_XML_CONTENT INVALID_XML_COMMENT INVALID_XML_PROCESSING_INSTRUCTION ' + + 'INTEGRITY_CONSTRAINT_VIOLATION RESTRICT_VIOLATION NOT_NULL_VIOLATION FOREIGN_KEY_VIOLATION ' + + 'UNIQUE_VIOLATION CHECK_VIOLATION EXCLUSION_VIOLATION INVALID_CURSOR_STATE ' + + 'INVALID_TRANSACTION_STATE ACTIVE_SQL_TRANSACTION BRANCH_TRANSACTION_ALREADY_ACTIVE ' + + 'HELD_CURSOR_REQUIRES_SAME_ISOLATION_LEVEL INAPPROPRIATE_ACCESS_MODE_FOR_BRANCH_TRANSACTION ' + + 'INAPPROPRIATE_ISOLATION_LEVEL_FOR_BRANCH_TRANSACTION ' + + 'NO_ACTIVE_SQL_TRANSACTION_FOR_BRANCH_TRANSACTION READ_ONLY_SQL_TRANSACTION ' + + 'SCHEMA_AND_DATA_STATEMENT_MIXING_NOT_SUPPORTED NO_ACTIVE_SQL_TRANSACTION ' + + 'IN_FAILED_SQL_TRANSACTION IDLE_IN_TRANSACTION_SESSION_TIMEOUT INVALID_SQL_STATEMENT_NAME ' + + 'TRIGGERED_DATA_CHANGE_VIOLATION INVALID_AUTHORIZATION_SPECIFICATION INVALID_PASSWORD ' + + 'DEPENDENT_PRIVILEGE_DESCRIPTORS_STILL_EXIST DEPENDENT_OBJECTS_STILL_EXIST ' + + 'INVALID_TRANSACTION_TERMINATION SQL_ROUTINE_EXCEPTION FUNCTION_EXECUTED_NO_RETURN_STATEMENT ' + + 'MODIFYING_SQL_DATA_NOT_PERMITTED PROHIBITED_SQL_STATEMENT_ATTEMPTED ' + + 'READING_SQL_DATA_NOT_PERMITTED INVALID_CURSOR_NAME EXTERNAL_ROUTINE_EXCEPTION ' + + 'CONTAINING_SQL_NOT_PERMITTED MODIFYING_SQL_DATA_NOT_PERMITTED ' + + 'PROHIBITED_SQL_STATEMENT_ATTEMPTED READING_SQL_DATA_NOT_PERMITTED ' + + 'EXTERNAL_ROUTINE_INVOCATION_EXCEPTION INVALID_SQLSTATE_RETURNED NULL_VALUE_NOT_ALLOWED ' + + 'TRIGGER_PROTOCOL_VIOLATED SRF_PROTOCOL_VIOLATED EVENT_TRIGGER_PROTOCOL_VIOLATED ' + + 'SAVEPOINT_EXCEPTION INVALID_SAVEPOINT_SPECIFICATION INVALID_CATALOG_NAME ' + + 'INVALID_SCHEMA_NAME TRANSACTION_ROLLBACK TRANSACTION_INTEGRITY_CONSTRAINT_VIOLATION ' + + 'SERIALIZATION_FAILURE STATEMENT_COMPLETION_UNKNOWN DEADLOCK_DETECTED ' + + 'SYNTAX_ERROR_OR_ACCESS_RULE_VIOLATION SYNTAX_ERROR INSUFFICIENT_PRIVILEGE CANNOT_COERCE ' + + 'GROUPING_ERROR WINDOWING_ERROR INVALID_RECURSION INVALID_FOREIGN_KEY INVALID_NAME ' + + 'NAME_TOO_LONG RESERVED_NAME DATATYPE_MISMATCH INDETERMINATE_DATATYPE COLLATION_MISMATCH ' + + 'INDETERMINATE_COLLATION WRONG_OBJECT_TYPE GENERATED_ALWAYS UNDEFINED_COLUMN ' + + 'UNDEFINED_FUNCTION UNDEFINED_TABLE UNDEFINED_PARAMETER UNDEFINED_OBJECT ' + + 'DUPLICATE_COLUMN DUPLICATE_CURSOR DUPLICATE_DATABASE DUPLICATE_FUNCTION ' + + 'DUPLICATE_PREPARED_STATEMENT DUPLICATE_SCHEMA DUPLICATE_TABLE DUPLICATE_ALIAS ' + + 'DUPLICATE_OBJECT AMBIGUOUS_COLUMN AMBIGUOUS_FUNCTION AMBIGUOUS_PARAMETER AMBIGUOUS_ALIAS ' + + 'INVALID_COLUMN_REFERENCE INVALID_COLUMN_DEFINITION INVALID_CURSOR_DEFINITION ' + + 'INVALID_DATABASE_DEFINITION INVALID_FUNCTION_DEFINITION ' + + 'INVALID_PREPARED_STATEMENT_DEFINITION INVALID_SCHEMA_DEFINITION INVALID_TABLE_DEFINITION ' + + 'INVALID_OBJECT_DEFINITION WITH_CHECK_OPTION_VIOLATION INSUFFICIENT_RESOURCES DISK_FULL ' + + 'OUT_OF_MEMORY TOO_MANY_CONNECTIONS CONFIGURATION_LIMIT_EXCEEDED PROGRAM_LIMIT_EXCEEDED ' + + 'STATEMENT_TOO_COMPLEX TOO_MANY_COLUMNS TOO_MANY_ARGUMENTS OBJECT_NOT_IN_PREREQUISITE_STATE ' + + 'OBJECT_IN_USE CANT_CHANGE_RUNTIME_PARAM LOCK_NOT_AVAILABLE OPERATOR_INTERVENTION ' + + 'QUERY_CANCELED ADMIN_SHUTDOWN CRASH_SHUTDOWN CANNOT_CONNECT_NOW DATABASE_DROPPED ' + + 'SYSTEM_ERROR IO_ERROR UNDEFINED_FILE DUPLICATE_FILE SNAPSHOT_TOO_OLD CONFIG_FILE_ERROR ' + + 'LOCK_FILE_EXISTS FDW_ERROR FDW_COLUMN_NAME_NOT_FOUND FDW_DYNAMIC_PARAMETER_VALUE_NEEDED ' + + 'FDW_FUNCTION_SEQUENCE_ERROR FDW_INCONSISTENT_DESCRIPTOR_INFORMATION ' + + 'FDW_INVALID_ATTRIBUTE_VALUE FDW_INVALID_COLUMN_NAME FDW_INVALID_COLUMN_NUMBER ' + + 'FDW_INVALID_DATA_TYPE FDW_INVALID_DATA_TYPE_DESCRIPTORS ' + + 'FDW_INVALID_DESCRIPTOR_FIELD_IDENTIFIER FDW_INVALID_HANDLE FDW_INVALID_OPTION_INDEX ' + + 'FDW_INVALID_OPTION_NAME FDW_INVALID_STRING_LENGTH_OR_BUFFER_LENGTH ' + + 'FDW_INVALID_STRING_FORMAT FDW_INVALID_USE_OF_NULL_POINTER FDW_TOO_MANY_HANDLES ' + + 'FDW_OUT_OF_MEMORY FDW_NO_SCHEMAS FDW_OPTION_NAME_NOT_FOUND FDW_REPLY_HANDLE ' + + 'FDW_SCHEMA_NOT_FOUND FDW_TABLE_NOT_FOUND FDW_UNABLE_TO_CREATE_EXECUTION ' + + 'FDW_UNABLE_TO_CREATE_REPLY FDW_UNABLE_TO_ESTABLISH_CONNECTION PLPGSQL_ERROR ' + + 'RAISE_EXCEPTION NO_DATA_FOUND TOO_MANY_ROWS ASSERT_FAILURE INTERNAL_ERROR DATA_CORRUPTED ' + + 'INDEX_CORRUPTED '; + + const FUNCTIONS = + // https://www.postgresql.org/docs/11/static/functions-aggregate.html + 'ARRAY_AGG AVG BIT_AND BIT_OR BOOL_AND BOOL_OR COUNT EVERY JSON_AGG JSONB_AGG JSON_OBJECT_AGG ' + + 'JSONB_OBJECT_AGG MAX MIN MODE STRING_AGG SUM XMLAGG ' + + 'CORR COVAR_POP COVAR_SAMP REGR_AVGX REGR_AVGY REGR_COUNT REGR_INTERCEPT REGR_R2 REGR_SLOPE ' + + 'REGR_SXX REGR_SXY REGR_SYY STDDEV STDDEV_POP STDDEV_SAMP VARIANCE VAR_POP VAR_SAMP ' + + 'PERCENTILE_CONT PERCENTILE_DISC ' + + // https://www.postgresql.org/docs/11/static/functions-window.html + 'ROW_NUMBER RANK DENSE_RANK PERCENT_RANK CUME_DIST NTILE LAG LEAD FIRST_VALUE LAST_VALUE NTH_VALUE ' + + // https://www.postgresql.org/docs/11/static/functions-comparison.html + 'NUM_NONNULLS NUM_NULLS ' + + // https://www.postgresql.org/docs/11/static/functions-math.html + 'ABS CBRT CEIL CEILING DEGREES DIV EXP FLOOR LN LOG MOD PI POWER RADIANS ROUND SCALE SIGN SQRT ' + + 'TRUNC WIDTH_BUCKET ' + + 'RANDOM SETSEED ' + + 'ACOS ACOSD ASIN ASIND ATAN ATAND ATAN2 ATAN2D COS COSD COT COTD SIN SIND TAN TAND ' + + // https://www.postgresql.org/docs/11/static/functions-string.html + 'BIT_LENGTH CHAR_LENGTH CHARACTER_LENGTH LOWER OCTET_LENGTH OVERLAY POSITION SUBSTRING TREAT TRIM UPPER ' + + 'ASCII BTRIM CHR CONCAT CONCAT_WS CONVERT CONVERT_FROM CONVERT_TO DECODE ENCODE INITCAP ' + + 'LEFT LENGTH LPAD LTRIM MD5 PARSE_IDENT PG_CLIENT_ENCODING QUOTE_IDENT|10 QUOTE_LITERAL|10 ' + + 'QUOTE_NULLABLE|10 REGEXP_MATCH REGEXP_MATCHES REGEXP_REPLACE REGEXP_SPLIT_TO_ARRAY ' + + 'REGEXP_SPLIT_TO_TABLE REPEAT REPLACE REVERSE RIGHT RPAD RTRIM SPLIT_PART STRPOS SUBSTR ' + + 'TO_ASCII TO_HEX TRANSLATE ' + + // https://www.postgresql.org/docs/11/static/functions-binarystring.html + 'OCTET_LENGTH GET_BIT GET_BYTE SET_BIT SET_BYTE ' + + // https://www.postgresql.org/docs/11/static/functions-formatting.html + 'TO_CHAR TO_DATE TO_NUMBER TO_TIMESTAMP ' + + // https://www.postgresql.org/docs/11/static/functions-datetime.html + 'AGE CLOCK_TIMESTAMP|10 DATE_PART DATE_TRUNC ISFINITE JUSTIFY_DAYS JUSTIFY_HOURS JUSTIFY_INTERVAL ' + + 'MAKE_DATE MAKE_INTERVAL|10 MAKE_TIME MAKE_TIMESTAMP|10 MAKE_TIMESTAMPTZ|10 NOW STATEMENT_TIMESTAMP|10 ' + + 'TIMEOFDAY TRANSACTION_TIMESTAMP|10 ' + + // https://www.postgresql.org/docs/11/static/functions-enum.html + 'ENUM_FIRST ENUM_LAST ENUM_RANGE ' + + // https://www.postgresql.org/docs/11/static/functions-geometry.html + 'AREA CENTER DIAMETER HEIGHT ISCLOSED ISOPEN NPOINTS PCLOSE POPEN RADIUS WIDTH ' + + 'BOX BOUND_BOX CIRCLE LINE LSEG PATH POLYGON ' + + // https://www.postgresql.org/docs/11/static/functions-net.html + 'ABBREV BROADCAST HOST HOSTMASK MASKLEN NETMASK NETWORK SET_MASKLEN TEXT INET_SAME_FAMILY ' + + 'INET_MERGE MACADDR8_SET7BIT ' + + // https://www.postgresql.org/docs/11/static/functions-textsearch.html + 'ARRAY_TO_TSVECTOR GET_CURRENT_TS_CONFIG NUMNODE PLAINTO_TSQUERY PHRASETO_TSQUERY WEBSEARCH_TO_TSQUERY ' + + 'QUERYTREE SETWEIGHT STRIP TO_TSQUERY TO_TSVECTOR JSON_TO_TSVECTOR JSONB_TO_TSVECTOR TS_DELETE ' + + 'TS_FILTER TS_HEADLINE TS_RANK TS_RANK_CD TS_REWRITE TSQUERY_PHRASE TSVECTOR_TO_ARRAY ' + + 'TSVECTOR_UPDATE_TRIGGER TSVECTOR_UPDATE_TRIGGER_COLUMN ' + + // https://www.postgresql.org/docs/11/static/functions-xml.html + 'XMLCOMMENT XMLCONCAT XMLELEMENT XMLFOREST XMLPI XMLROOT ' + + 'XMLEXISTS XML_IS_WELL_FORMED XML_IS_WELL_FORMED_DOCUMENT XML_IS_WELL_FORMED_CONTENT ' + + 'XPATH XPATH_EXISTS XMLTABLE XMLNAMESPACES ' + + 'TABLE_TO_XML TABLE_TO_XMLSCHEMA TABLE_TO_XML_AND_XMLSCHEMA ' + + 'QUERY_TO_XML QUERY_TO_XMLSCHEMA QUERY_TO_XML_AND_XMLSCHEMA ' + + 'CURSOR_TO_XML CURSOR_TO_XMLSCHEMA ' + + 'SCHEMA_TO_XML SCHEMA_TO_XMLSCHEMA SCHEMA_TO_XML_AND_XMLSCHEMA ' + + 'DATABASE_TO_XML DATABASE_TO_XMLSCHEMA DATABASE_TO_XML_AND_XMLSCHEMA ' + + 'XMLATTRIBUTES ' + + // https://www.postgresql.org/docs/11/static/functions-json.html + 'TO_JSON TO_JSONB ARRAY_TO_JSON ROW_TO_JSON JSON_BUILD_ARRAY JSONB_BUILD_ARRAY JSON_BUILD_OBJECT ' + + 'JSONB_BUILD_OBJECT JSON_OBJECT JSONB_OBJECT JSON_ARRAY_LENGTH JSONB_ARRAY_LENGTH JSON_EACH ' + + 'JSONB_EACH JSON_EACH_TEXT JSONB_EACH_TEXT JSON_EXTRACT_PATH JSONB_EXTRACT_PATH ' + + 'JSON_OBJECT_KEYS JSONB_OBJECT_KEYS JSON_POPULATE_RECORD JSONB_POPULATE_RECORD JSON_POPULATE_RECORDSET ' + + 'JSONB_POPULATE_RECORDSET JSON_ARRAY_ELEMENTS JSONB_ARRAY_ELEMENTS JSON_ARRAY_ELEMENTS_TEXT ' + + 'JSONB_ARRAY_ELEMENTS_TEXT JSON_TYPEOF JSONB_TYPEOF JSON_TO_RECORD JSONB_TO_RECORD JSON_TO_RECORDSET ' + + 'JSONB_TO_RECORDSET JSON_STRIP_NULLS JSONB_STRIP_NULLS JSONB_SET JSONB_INSERT JSONB_PRETTY ' + + // https://www.postgresql.org/docs/11/static/functions-sequence.html + 'CURRVAL LASTVAL NEXTVAL SETVAL ' + + // https://www.postgresql.org/docs/11/static/functions-conditional.html + 'COALESCE NULLIF GREATEST LEAST ' + + // https://www.postgresql.org/docs/11/static/functions-array.html + 'ARRAY_APPEND ARRAY_CAT ARRAY_NDIMS ARRAY_DIMS ARRAY_FILL ARRAY_LENGTH ARRAY_LOWER ARRAY_POSITION ' + + 'ARRAY_POSITIONS ARRAY_PREPEND ARRAY_REMOVE ARRAY_REPLACE ARRAY_TO_STRING ARRAY_UPPER CARDINALITY ' + + 'STRING_TO_ARRAY UNNEST ' + + // https://www.postgresql.org/docs/11/static/functions-range.html + 'ISEMPTY LOWER_INC UPPER_INC LOWER_INF UPPER_INF RANGE_MERGE ' + + // https://www.postgresql.org/docs/11/static/functions-srf.html + 'GENERATE_SERIES GENERATE_SUBSCRIPTS ' + + // https://www.postgresql.org/docs/11/static/functions-info.html + 'CURRENT_DATABASE CURRENT_QUERY CURRENT_SCHEMA|10 CURRENT_SCHEMAS|10 INET_CLIENT_ADDR INET_CLIENT_PORT ' + + 'INET_SERVER_ADDR INET_SERVER_PORT ROW_SECURITY_ACTIVE FORMAT_TYPE ' + + 'TO_REGCLASS TO_REGPROC TO_REGPROCEDURE TO_REGOPER TO_REGOPERATOR TO_REGTYPE TO_REGNAMESPACE TO_REGROLE ' + + 'COL_DESCRIPTION OBJ_DESCRIPTION SHOBJ_DESCRIPTION ' + + 'TXID_CURRENT TXID_CURRENT_IF_ASSIGNED TXID_CURRENT_SNAPSHOT TXID_SNAPSHOT_XIP TXID_SNAPSHOT_XMAX ' + + 'TXID_SNAPSHOT_XMIN TXID_VISIBLE_IN_SNAPSHOT TXID_STATUS ' + + // https://www.postgresql.org/docs/11/static/functions-admin.html + 'CURRENT_SETTING SET_CONFIG BRIN_SUMMARIZE_NEW_VALUES BRIN_SUMMARIZE_RANGE BRIN_DESUMMARIZE_RANGE ' + + 'GIN_CLEAN_PENDING_LIST ' + + // https://www.postgresql.org/docs/11/static/functions-trigger.html + 'SUPPRESS_REDUNDANT_UPDATES_TRIGGER ' + + // ihttps://www.postgresql.org/docs/devel/static/lo-funcs.html + 'LO_FROM_BYTEA LO_PUT LO_GET LO_CREAT LO_CREATE LO_UNLINK LO_IMPORT LO_EXPORT LOREAD LOWRITE ' + + // + 'GROUPING CAST '; + + const FUNCTIONS_RE = + FUNCTIONS.trim() + .split(' ') + .map(function(val) { return val.split('|')[0]; }) + .join('|'); + + return { + name: 'PostgreSQL', + aliases: [ + 'postgres', + 'postgresql' + ], + case_insensitive: true, + keywords: { + keyword: + SQL_KW + PLPGSQL_KW + ROLE_ATTRS, + built_in: + SQL_BI + PLPGSQL_BI + PLPGSQL_EXCEPTIONS + }, + // Forbid some cunstructs from other languages to improve autodetect. In fact + // "[a-z]:" is legal (as part of array slice), but improbabal. + illegal: /:==|\W\s*\(\*|(^|\s)\$[a-z]|\{\{|[a-z]:\s*$|\.\.\.|TO:|DO:/, + contains: [ + // special handling of some words, which are reserved only in some contexts + { + className: 'keyword', + variants: [ + { + begin: /\bTEXT\s*SEARCH\b/ + }, + { + begin: /\b(PRIMARY|FOREIGN|FOR(\s+NO)?)\s+KEY\b/ + }, + { + begin: /\bPARALLEL\s+(UNSAFE|RESTRICTED|SAFE)\b/ + }, + { + begin: /\bSTORAGE\s+(PLAIN|EXTERNAL|EXTENDED|MAIN)\b/ + }, + { + begin: /\bMATCH\s+(FULL|PARTIAL|SIMPLE)\b/ + }, + { + begin: /\bNULLS\s+(FIRST|LAST)\b/ + }, + { + begin: /\bEVENT\s+TRIGGER\b/ + }, + { + begin: /\b(MAPPING|OR)\s+REPLACE\b/ + }, + { + begin: /\b(FROM|TO)\s+(PROGRAM|STDIN|STDOUT)\b/ + }, + { + begin: /\b(SHARE|EXCLUSIVE)\s+MODE\b/ + }, + { + begin: /\b(LEFT|RIGHT)\s+(OUTER\s+)?JOIN\b/ + }, + { + begin: /\b(FETCH|MOVE)\s+(NEXT|PRIOR|FIRST|LAST|ABSOLUTE|RELATIVE|FORWARD|BACKWARD)\b/ + }, + { + begin: /\bPRESERVE\s+ROWS\b/ + }, + { + begin: /\bDISCARD\s+PLANS\b/ + }, + { + begin: /\bREFERENCING\s+(OLD|NEW)\b/ + }, + { + begin: /\bSKIP\s+LOCKED\b/ + }, + { + begin: /\bGROUPING\s+SETS\b/ + }, + { + begin: /\b(BINARY|INSENSITIVE|SCROLL|NO\s+SCROLL)\s+(CURSOR|FOR)\b/ + }, + { + begin: /\b(WITH|WITHOUT)\s+HOLD\b/ + }, + { + begin: /\bWITH\s+(CASCADED|LOCAL)\s+CHECK\s+OPTION\b/ + }, + { + begin: /\bEXCLUDE\s+(TIES|NO\s+OTHERS)\b/ + }, + { + begin: /\bFORMAT\s+(TEXT|XML|JSON|YAML)\b/ + }, + { + begin: /\bSET\s+((SESSION|LOCAL)\s+)?NAMES\b/ + }, + { + begin: /\bIS\s+(NOT\s+)?UNKNOWN\b/ + }, + { + begin: /\bSECURITY\s+LABEL\b/ + }, + { + begin: /\bSTANDALONE\s+(YES|NO|NO\s+VALUE)\b/ + }, + { + begin: /\bWITH\s+(NO\s+)?DATA\b/ + }, + { + begin: /\b(FOREIGN|SET)\s+DATA\b/ + }, + { + begin: /\bSET\s+(CATALOG|CONSTRAINTS)\b/ + }, + { + begin: /\b(WITH|FOR)\s+ORDINALITY\b/ + }, + { + begin: /\bIS\s+(NOT\s+)?DOCUMENT\b/ + }, + { + begin: /\bXML\s+OPTION\s+(DOCUMENT|CONTENT)\b/ + }, + { + begin: /\b(STRIP|PRESERVE)\s+WHITESPACE\b/ + }, + { + begin: /\bNO\s+(ACTION|MAXVALUE|MINVALUE)\b/ + }, + { + begin: /\bPARTITION\s+BY\s+(RANGE|LIST|HASH)\b/ + }, + { + begin: /\bAT\s+TIME\s+ZONE\b/ + }, + { + begin: /\bGRANTED\s+BY\b/ + }, + { + begin: /\bRETURN\s+(QUERY|NEXT)\b/ + }, + { + begin: /\b(ATTACH|DETACH)\s+PARTITION\b/ + }, + { + begin: /\bFORCE\s+ROW\s+LEVEL\s+SECURITY\b/ + }, + { + begin: /\b(INCLUDING|EXCLUDING)\s+(COMMENTS|CONSTRAINTS|DEFAULTS|IDENTITY|INDEXES|STATISTICS|STORAGE|ALL)\b/ + }, + { + begin: /\bAS\s+(ASSIGNMENT|IMPLICIT|PERMISSIVE|RESTRICTIVE|ENUM|RANGE)\b/ + } + ] + }, + // functions named as keywords, followed by '(' + { + begin: /\b(FORMAT|FAMILY|VERSION)\s*\(/ + // keywords: { built_in: 'FORMAT FAMILY VERSION' } + }, + // INCLUDE ( ... ) in index_parameters in CREATE TABLE + { + begin: /\bINCLUDE\s*\(/, + keywords: 'INCLUDE' + }, + // not highlight RANGE if not in frame_clause (not 100% correct, but seems satisfactory) + { + begin: /\bRANGE(?!\s*(BETWEEN|UNBOUNDED|CURRENT|[-0-9]+))/ + }, + // disable highlighting in commands CREATE AGGREGATE/COLLATION/DATABASE/OPERTOR/TEXT SEARCH .../TYPE + // and in PL/pgSQL RAISE ... USING + { + begin: /\b(VERSION|OWNER|TEMPLATE|TABLESPACE|CONNECTION\s+LIMIT|PROCEDURE|RESTRICT|JOIN|PARSER|COPY|START|END|COLLATION|INPUT|ANALYZE|STORAGE|LIKE|DEFAULT|DELIMITER|ENCODING|COLUMN|CONSTRAINT|TABLE|SCHEMA)\s*=/ + }, + // PG_smth; HAS_some_PRIVILEGE + { + // className: 'built_in', + begin: /\b(PG_\w+?|HAS_[A-Z_]+_PRIVILEGE)\b/, + relevance: 10 + }, + // extract + { + begin: /\bEXTRACT\s*\(/, + end: /\bFROM\b/, + returnEnd: true, + keywords: { + // built_in: 'EXTRACT', + type: 'CENTURY DAY DECADE DOW DOY EPOCH HOUR ISODOW ISOYEAR MICROSECONDS ' + + 'MILLENNIUM MILLISECONDS MINUTE MONTH QUARTER SECOND TIMEZONE TIMEZONE_HOUR ' + + 'TIMEZONE_MINUTE WEEK YEAR' + } + }, + // xmlelement, xmlpi - special NAME + { + begin: /\b(XMLELEMENT|XMLPI)\s*\(\s*NAME/, + keywords: { + // built_in: 'XMLELEMENT XMLPI', + keyword: 'NAME' + } + }, + // xmlparse, xmlserialize + { + begin: /\b(XMLPARSE|XMLSERIALIZE)\s*\(\s*(DOCUMENT|CONTENT)/, + keywords: { + // built_in: 'XMLPARSE XMLSERIALIZE', + keyword: 'DOCUMENT CONTENT' + } + }, + // Sequences. We actually skip everything between CACHE|INCREMENT|MAXVALUE|MINVALUE and + // nearest following numeric constant. Without with trick we find a lot of "keywords" + // in 'avrasm' autodetection test... + { + beginKeywords: 'CACHE INCREMENT MAXVALUE MINVALUE', + end: hljs.C_NUMBER_RE, + returnEnd: true, + keywords: 'BY CACHE INCREMENT MAXVALUE MINVALUE' + }, + // WITH|WITHOUT TIME ZONE as part of datatype + { + className: 'type', + begin: /\b(WITH|WITHOUT)\s+TIME\s+ZONE\b/ + }, + // INTERVAL optional fields + { + className: 'type', + begin: /\bINTERVAL\s+(YEAR|MONTH|DAY|HOUR|MINUTE|SECOND)(\s+TO\s+(MONTH|HOUR|MINUTE|SECOND))?\b/ + }, + // Pseudo-types which allowed only as return type + { + begin: /\bRETURNS\s+(LANGUAGE_HANDLER|TRIGGER|EVENT_TRIGGER|FDW_HANDLER|INDEX_AM_HANDLER|TSM_HANDLER)\b/, + keywords: { + keyword: 'RETURNS', + type: 'LANGUAGE_HANDLER TRIGGER EVENT_TRIGGER FDW_HANDLER INDEX_AM_HANDLER TSM_HANDLER' + } + }, + // Known functions - only when followed by '(' + { + begin: '\\b(' + FUNCTIONS_RE + ')\\s*\\(' + // keywords: { built_in: FUNCTIONS } + }, + // Types + { + begin: '\\.(' + TYPES_RE + ')\\b' // prevent highlight as type, say, 'oid' in 'pgclass.oid' + }, + { + begin: '\\b(' + TYPES_RE + ')\\s+PATH\\b', // in XMLTABLE + keywords: { + keyword: 'PATH', // hopefully no one would use PATH type in XMLTABLE... + type: TYPES.replace('PATH ', '') + } + }, + { + className: 'type', + begin: '\\b(' + TYPES_RE + ')\\b' + }, + // Strings, see https://www.postgresql.org/docs/11/static/sql-syntax-lexical.html#SQL-SYNTAX-CONSTANTS + { + className: 'string', + begin: '\'', + end: '\'', + contains: [ + { + begin: '\'\'' + } + ] + }, + { + className: 'string', + begin: '(e|E|u&|U&)\'', + end: '\'', + contains: [ + { + begin: '\\\\.' + } + ], + relevance: 10 + }, + hljs.END_SAME_AS_BEGIN({ + begin: DOLLAR_STRING, + end: DOLLAR_STRING, + contains: [ + { + // actually we want them all except SQL; listed are those with known implementations + // and XML + JSON just in case + subLanguage: [ + 'pgsql', + 'perl', + 'python', + 'tcl', + 'r', + 'lua', + 'java', + 'php', + 'ruby', + 'bash', + 'scheme', + 'xml', + 'json' + ], + endsWithParent: true + } + ] + }), + // identifiers in quotes + { + begin: '"', + end: '"', + contains: [ + { + begin: '""' + } + ] + }, + // numbers + hljs.C_NUMBER_MODE, + // comments + hljs.C_BLOCK_COMMENT_MODE, + COMMENT_MODE, + // PL/pgSQL staff + // %ROWTYPE, %TYPE, $n + { + className: 'meta', + variants: [ + { // %TYPE, %ROWTYPE + begin: '%(ROW)?TYPE', + relevance: 10 + }, + { // $n + begin: '\\$\\d+' + }, + { // #compiler option + begin: '^#\\w', + end: '$' + } + ] + }, + // <> + { + className: 'symbol', + begin: LABEL, + relevance: 10 + } + ] + }; +} + +module.exports = pgsql; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/php-template.js b/claude-code-source/node_modules/highlight.js/lib/languages/php-template.js new file mode 100644 index 00000000..a3de4b27 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/php-template.js @@ -0,0 +1,54 @@ +/* +Language: PHP Template +Requires: xml.js, php.js +Author: Josh Goebel +Website: https://www.php.net +Category: common +*/ + +function phpTemplate(hljs) { + return { + name: "PHP template", + subLanguage: 'xml', + contains: [ + { + begin: /<\?(php|=)?/, + end: /\?>/, + subLanguage: 'php', + contains: [ + // We don't want the php closing tag ?> to close the PHP block when + // inside any of the following blocks: + { + begin: '/\\*', + end: '\\*/', + skip: true + }, + { + begin: 'b"', + end: '"', + skip: true + }, + { + begin: 'b\'', + end: '\'', + skip: true + }, + hljs.inherit(hljs.APOS_STRING_MODE, { + illegal: null, + className: null, + contains: null, + skip: true + }), + hljs.inherit(hljs.QUOTE_STRING_MODE, { + illegal: null, + className: null, + contains: null, + skip: true + }) + ] + } + ] + }; +} + +module.exports = phpTemplate; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/php.js b/claude-code-source/node_modules/highlight.js/lib/languages/php.js new file mode 100644 index 00000000..0004275f --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/php.js @@ -0,0 +1,204 @@ +/* +Language: PHP +Author: Victor Karamzin +Contributors: Evgeny Stepanischev , Ivan Sagalaev +Website: https://www.php.net +Category: common +*/ + +/** + * @param {HLJSApi} hljs + * @returns {LanguageDetail} + * */ +function php(hljs) { + const VARIABLE = { + className: 'variable', + begin: '\\$+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*' + + // negative look-ahead tries to avoid matching patterns that are not + // Perl at all like $ident$, @ident@, etc. + `(?![A-Za-z0-9])(?![$])` + }; + const PREPROCESSOR = { + className: 'meta', + variants: [ + { begin: /<\?php/, relevance: 10 }, // boost for obvious PHP + { begin: /<\?[=]?/ }, + { begin: /\?>/ } // end php tag + ] + }; + const SUBST = { + className: 'subst', + variants: [ + { begin: /\$\w+/ }, + { begin: /\{\$/, end: /\}/ } + ] + }; + const SINGLE_QUOTED = hljs.inherit(hljs.APOS_STRING_MODE, { + illegal: null, + }); + const DOUBLE_QUOTED = hljs.inherit(hljs.QUOTE_STRING_MODE, { + illegal: null, + contains: hljs.QUOTE_STRING_MODE.contains.concat(SUBST), + }); + const HEREDOC = hljs.END_SAME_AS_BEGIN({ + begin: /<<<[ \t]*(\w+)\n/, + end: /[ \t]*(\w+)\b/, + contains: hljs.QUOTE_STRING_MODE.contains.concat(SUBST), + }); + const STRING = { + className: 'string', + contains: [hljs.BACKSLASH_ESCAPE, PREPROCESSOR], + variants: [ + hljs.inherit(SINGLE_QUOTED, { + begin: "b'", end: "'", + }), + hljs.inherit(DOUBLE_QUOTED, { + begin: 'b"', end: '"', + }), + DOUBLE_QUOTED, + SINGLE_QUOTED, + HEREDOC + ] + }; + const NUMBER = { + className: 'number', + variants: [ + { begin: `\\b0b[01]+(?:_[01]+)*\\b` }, // Binary w/ underscore support + { begin: `\\b0o[0-7]+(?:_[0-7]+)*\\b` }, // Octals w/ underscore support + { begin: `\\b0x[\\da-f]+(?:_[\\da-f]+)*\\b` }, // Hex w/ underscore support + // Decimals w/ underscore support, with optional fragments and scientific exponent (e) suffix. + { begin: `(?:\\b\\d+(?:_\\d+)*(\\.(?:\\d+(?:_\\d+)*))?|\\B\\.\\d+)(?:e[+-]?\\d+)?` } + ], + relevance: 0 + }; + const KEYWORDS = { + keyword: + // Magic constants: + // + '__CLASS__ __DIR__ __FILE__ __FUNCTION__ __LINE__ __METHOD__ __NAMESPACE__ __TRAIT__ ' + + // Function that look like language construct or language construct that look like function: + // List of keywords that may not require parenthesis + 'die echo exit include include_once print require require_once ' + + // These are not language construct (function) but operate on the currently-executing function and can access the current symbol table + // 'compact extract func_get_arg func_get_args func_num_args get_called_class get_parent_class ' + + // Other keywords: + // + // + 'array abstract and as binary bool boolean break callable case catch class clone const continue declare ' + + 'default do double else elseif empty enddeclare endfor endforeach endif endswitch endwhile enum eval extends ' + + 'final finally float for foreach from global goto if implements instanceof insteadof int integer interface ' + + 'isset iterable list match|0 mixed new object or private protected public real return string switch throw trait ' + + 'try unset use var void while xor yield', + literal: 'false null true', + built_in: + // Standard PHP library: + // + 'Error|0 ' + // error is too common a name esp since PHP is case in-sensitive + 'AppendIterator ArgumentCountError ArithmeticError ArrayIterator ArrayObject AssertionError BadFunctionCallException BadMethodCallException CachingIterator CallbackFilterIterator CompileError Countable DirectoryIterator DivisionByZeroError DomainException EmptyIterator ErrorException Exception FilesystemIterator FilterIterator GlobIterator InfiniteIterator InvalidArgumentException IteratorIterator LengthException LimitIterator LogicException MultipleIterator NoRewindIterator OutOfBoundsException OutOfRangeException OuterIterator OverflowException ParentIterator ParseError RangeException RecursiveArrayIterator RecursiveCachingIterator RecursiveCallbackFilterIterator RecursiveDirectoryIterator RecursiveFilterIterator RecursiveIterator RecursiveIteratorIterator RecursiveRegexIterator RecursiveTreeIterator RegexIterator RuntimeException SeekableIterator SplDoublyLinkedList SplFileInfo SplFileObject SplFixedArray SplHeap SplMaxHeap SplMinHeap SplObjectStorage SplObserver SplObserver SplPriorityQueue SplQueue SplStack SplSubject SplSubject SplTempFileObject TypeError UnderflowException UnexpectedValueException UnhandledMatchError ' + + // Reserved interfaces: + // + 'ArrayAccess Closure Generator Iterator IteratorAggregate Serializable Stringable Throwable Traversable WeakReference WeakMap ' + + // Reserved classes: + // + 'Directory __PHP_Incomplete_Class parent php_user_filter self static stdClass' + }; + return { + aliases: ['php3', 'php4', 'php5', 'php6', 'php7', 'php8'], + case_insensitive: true, + keywords: KEYWORDS, + contains: [ + hljs.HASH_COMMENT_MODE, + hljs.COMMENT('//', '$', {contains: [PREPROCESSOR]}), + hljs.COMMENT( + '/\\*', + '\\*/', + { + contains: [ + { + className: 'doctag', + begin: '@[A-Za-z]+' + } + ] + } + ), + hljs.COMMENT( + '__halt_compiler.+?;', + false, + { + endsWithParent: true, + keywords: '__halt_compiler' + } + ), + PREPROCESSOR, + { + className: 'keyword', begin: /\$this\b/ + }, + VARIABLE, + { + // swallow composed identifiers to avoid parsing them as keywords + begin: /(::|->)+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/ + }, + { + className: 'function', + relevance: 0, + beginKeywords: 'fn function', end: /[;{]/, excludeEnd: true, + illegal: '[$%\\[]', + contains: [ + { + beginKeywords: 'use', + }, + hljs.UNDERSCORE_TITLE_MODE, + { + begin: '=>', // No markup, just a relevance booster + endsParent: true + }, + { + className: 'params', + begin: '\\(', end: '\\)', + excludeBegin: true, + excludeEnd: true, + keywords: KEYWORDS, + contains: [ + 'self', + VARIABLE, + hljs.C_BLOCK_COMMENT_MODE, + STRING, + NUMBER + ] + } + ] + }, + { + className: 'class', + variants: [ + { beginKeywords: "enum", illegal: /[($"]/ }, + { beginKeywords: "class interface trait", illegal: /[:($"]/ } + ], + relevance: 0, + end: /\{/, + excludeEnd: true, + contains: [ + {beginKeywords: 'extends implements'}, + hljs.UNDERSCORE_TITLE_MODE + ] + }, + { + beginKeywords: 'namespace', + relevance: 0, + end: ';', + illegal: /[.']/, + contains: [hljs.UNDERSCORE_TITLE_MODE] + }, + { + beginKeywords: 'use', + relevance: 0, + end: ';', + contains: [hljs.UNDERSCORE_TITLE_MODE] + }, + STRING, + NUMBER + ] + }; +} + +module.exports = php; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/plaintext.js b/claude-code-source/node_modules/highlight.js/lib/languages/plaintext.js new file mode 100644 index 00000000..5cb2de76 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/plaintext.js @@ -0,0 +1,19 @@ +/* +Language: Plain text +Author: Egor Rogov (e.rogov@postgrespro.ru) +Description: Plain text without any highlighting. +Category: common +*/ + +function plaintext(hljs) { + return { + name: 'Plain text', + aliases: [ + 'text', + 'txt' + ], + disableAutodetect: true + }; +} + +module.exports = plaintext; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/pony.js b/claude-code-source/node_modules/highlight.js/lib/languages/pony.js new file mode 100644 index 00000000..6bfba13e --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/pony.js @@ -0,0 +1,89 @@ +/* +Language: Pony +Author: Joe Eli McIlvain +Description: Pony is an open-source, object-oriented, actor-model, + capabilities-secure, high performance programming language. +Website: https://www.ponylang.io +*/ + +function pony(hljs) { + const KEYWORDS = { + keyword: + 'actor addressof and as be break class compile_error compile_intrinsic ' + + 'consume continue delegate digestof do else elseif embed end error ' + + 'for fun if ifdef in interface is isnt lambda let match new not object ' + + 'or primitive recover repeat return struct then trait try type until ' + + 'use var where while with xor', + meta: + 'iso val tag trn box ref', + literal: + 'this false true' + }; + + const TRIPLE_QUOTE_STRING_MODE = { + className: 'string', + begin: '"""', + end: '"""', + relevance: 10 + }; + + const QUOTE_STRING_MODE = { + className: 'string', + begin: '"', + end: '"', + contains: [ hljs.BACKSLASH_ESCAPE ] + }; + + const SINGLE_QUOTE_CHAR_MODE = { + className: 'string', + begin: '\'', + end: '\'', + contains: [ hljs.BACKSLASH_ESCAPE ], + relevance: 0 + }; + + const TYPE_NAME = { + className: 'type', + begin: '\\b_?[A-Z][\\w]*', + relevance: 0 + }; + + const PRIMED_NAME = { + begin: hljs.IDENT_RE + '\'', + relevance: 0 + }; + + const NUMBER_MODE = { + className: 'number', + begin: '(-?)(\\b0[xX][a-fA-F0-9]+|\\b0[bB][01]+|(\\b\\d+(_\\d+)?(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)', + relevance: 0 + }; + + /** + * The `FUNCTION` and `CLASS` modes were intentionally removed to simplify + * highlighting and fix cases like + * ``` + * interface Iterator[A: A] + * fun has_next(): Bool + * fun next(): A? + * ``` + * where it is valid to have a function head without a body + */ + + return { + name: 'Pony', + keywords: KEYWORDS, + contains: [ + TYPE_NAME, + TRIPLE_QUOTE_STRING_MODE, + QUOTE_STRING_MODE, + SINGLE_QUOTE_CHAR_MODE, + PRIMED_NAME, + NUMBER_MODE, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE + ] + }; +} + +module.exports = pony; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/powershell.js b/claude-code-source/node_modules/highlight.js/lib/languages/powershell.js new file mode 100644 index 00000000..46c2d4c2 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/powershell.js @@ -0,0 +1,331 @@ +/* +Language: PowerShell +Description: PowerShell is a task-based command-line shell and scripting language built on .NET. +Author: David Mohundro +Contributors: Nicholas Blumhardt , Victor Zhou , Nicolas Le Gall +Website: https://docs.microsoft.com/en-us/powershell/ +*/ + +function powershell(hljs) { + const TYPES = [ + "string", + "char", + "byte", + "int", + "long", + "bool", + "decimal", + "single", + "double", + "DateTime", + "xml", + "array", + "hashtable", + "void" + ]; + + // https://docs.microsoft.com/en-us/powershell/scripting/developer/cmdlet/approved-verbs-for-windows-powershell-commands + const VALID_VERBS = + 'Add|Clear|Close|Copy|Enter|Exit|Find|Format|Get|Hide|Join|Lock|' + + 'Move|New|Open|Optimize|Pop|Push|Redo|Remove|Rename|Reset|Resize|' + + 'Search|Select|Set|Show|Skip|Split|Step|Switch|Undo|Unlock|' + + 'Watch|Backup|Checkpoint|Compare|Compress|Convert|ConvertFrom|' + + 'ConvertTo|Dismount|Edit|Expand|Export|Group|Import|Initialize|' + + 'Limit|Merge|Mount|Out|Publish|Restore|Save|Sync|Unpublish|Update|' + + 'Approve|Assert|Build|Complete|Confirm|Deny|Deploy|Disable|Enable|Install|Invoke|' + + 'Register|Request|Restart|Resume|Start|Stop|Submit|Suspend|Uninstall|' + + 'Unregister|Wait|Debug|Measure|Ping|Repair|Resolve|Test|Trace|Connect|' + + 'Disconnect|Read|Receive|Send|Write|Block|Grant|Protect|Revoke|Unblock|' + + 'Unprotect|Use|ForEach|Sort|Tee|Where'; + + const COMPARISON_OPERATORS = + '-and|-as|-band|-bnot|-bor|-bxor|-casesensitive|-ccontains|-ceq|-cge|-cgt|' + + '-cle|-clike|-clt|-cmatch|-cne|-cnotcontains|-cnotlike|-cnotmatch|-contains|' + + '-creplace|-csplit|-eq|-exact|-f|-file|-ge|-gt|-icontains|-ieq|-ige|-igt|' + + '-ile|-ilike|-ilt|-imatch|-in|-ine|-inotcontains|-inotlike|-inotmatch|' + + '-ireplace|-is|-isnot|-isplit|-join|-le|-like|-lt|-match|-ne|-not|' + + '-notcontains|-notin|-notlike|-notmatch|-or|-regex|-replace|-shl|-shr|' + + '-split|-wildcard|-xor'; + + const KEYWORDS = { + $pattern: /-?[A-z\.\-]+\b/, + keyword: + 'if else foreach return do while until elseif begin for trap data dynamicparam ' + + 'end break throw param continue finally in switch exit filter try process catch ' + + 'hidden static parameter', + // "echo" relevance has been set to 0 to avoid auto-detect conflicts with shell transcripts + built_in: + 'ac asnp cat cd CFS chdir clc clear clhy cli clp cls clv cnsn compare copy cp ' + + 'cpi cpp curl cvpa dbp del diff dir dnsn ebp echo|0 epal epcsv epsn erase etsn exsn fc fhx ' + + 'fl ft fw gal gbp gc gcb gci gcm gcs gdr gerr ghy gi gin gjb gl gm gmo gp gps gpv group ' + + 'gsn gsnp gsv gtz gu gv gwmi h history icm iex ihy ii ipal ipcsv ipmo ipsn irm ise iwmi ' + + 'iwr kill lp ls man md measure mi mount move mp mv nal ndr ni nmo npssc nsn nv ogv oh ' + + 'popd ps pushd pwd r rbp rcjb rcsn rd rdr ren ri rjb rm rmdir rmo rni rnp rp rsn rsnp ' + + 'rujb rv rvpa rwmi sajb sal saps sasv sbp sc scb select set shcm si sl sleep sls sort sp ' + + 'spjb spps spsv start stz sujb sv swmi tee trcm type wget where wjb write' + // TODO: 'validate[A-Z]+' can't work in keywords + }; + + const TITLE_NAME_RE = /\w[\w\d]*((-)[\w\d]+)*/; + + const BACKTICK_ESCAPE = { + begin: '`[\\s\\S]', + relevance: 0 + }; + + const VAR = { + className: 'variable', + variants: [ + { + begin: /\$\B/ + }, + { + className: 'keyword', + begin: /\$this/ + }, + { + begin: /\$[\w\d][\w\d_:]*/ + } + ] + }; + + const LITERAL = { + className: 'literal', + begin: /\$(null|true|false)\b/ + }; + + const QUOTE_STRING = { + className: "string", + variants: [ + { + begin: /"/, + end: /"/ + }, + { + begin: /@"/, + end: /^"@/ + } + ], + contains: [ + BACKTICK_ESCAPE, + VAR, + { + className: 'variable', + begin: /\$[A-z]/, + end: /[^A-z]/ + } + ] + }; + + const APOS_STRING = { + className: 'string', + variants: [ + { + begin: /'/, + end: /'/ + }, + { + begin: /@'/, + end: /^'@/ + } + ] + }; + + const PS_HELPTAGS = { + className: "doctag", + variants: [ + /* no paramater help tags */ + { + begin: /\.(synopsis|description|example|inputs|outputs|notes|link|component|role|functionality)/ + }, + /* one parameter help tags */ + { + begin: /\.(parameter|forwardhelptargetname|forwardhelpcategory|remotehelprunspace|externalhelp)\s+\S+/ + } + ] + }; + + const PS_COMMENT = hljs.inherit( + hljs.COMMENT(null, null), + { + variants: [ + /* single-line comment */ + { + begin: /#/, + end: /$/ + }, + /* multi-line comment */ + { + begin: /<#/, + end: /#>/ + } + ], + contains: [ PS_HELPTAGS ] + } + ); + + const CMDLETS = { + className: 'built_in', + variants: [ + { + begin: '('.concat(VALID_VERBS, ')+(-)[\\w\\d]+') + } + ] + }; + + const PS_CLASS = { + className: 'class', + beginKeywords: 'class enum', + end: /\s*[{]/, + excludeEnd: true, + relevance: 0, + contains: [ hljs.TITLE_MODE ] + }; + + const PS_FUNCTION = { + className: 'function', + begin: /function\s+/, + end: /\s*\{|$/, + excludeEnd: true, + returnBegin: true, + relevance: 0, + contains: [ + { + begin: "function", + relevance: 0, + className: "keyword" + }, + { + className: "title", + begin: TITLE_NAME_RE, + relevance: 0 + }, + { + begin: /\(/, + end: /\)/, + className: "params", + relevance: 0, + contains: [ VAR ] + } + // CMDLETS + ] + }; + + // Using statment, plus type, plus assembly name. + const PS_USING = { + begin: /using\s/, + end: /$/, + returnBegin: true, + contains: [ + QUOTE_STRING, + APOS_STRING, + { + className: 'keyword', + begin: /(using|assembly|command|module|namespace|type)/ + } + ] + }; + + // Comperison operators & function named parameters. + const PS_ARGUMENTS = { + variants: [ + // PS literals are pretty verbose so it's a good idea to accent them a bit. + { + className: 'operator', + begin: '('.concat(COMPARISON_OPERATORS, ')\\b') + }, + { + className: 'literal', + begin: /(-)[\w\d]+/, + relevance: 0 + } + ] + }; + + const HASH_SIGNS = { + className: 'selector-tag', + begin: /@\B/, + relevance: 0 + }; + + // It's a very general rule so I'll narrow it a bit with some strict boundaries + // to avoid any possible false-positive collisions! + const PS_METHODS = { + className: 'function', + begin: /\[.*\]\s*[\w]+[ ]??\(/, + end: /$/, + returnBegin: true, + relevance: 0, + contains: [ + { + className: 'keyword', + begin: '('.concat( + KEYWORDS.keyword.toString().replace(/\s/g, '|' + ), ')\\b'), + endsParent: true, + relevance: 0 + }, + hljs.inherit(hljs.TITLE_MODE, { + endsParent: true + }) + ] + }; + + const GENTLEMANS_SET = [ + // STATIC_MEMBER, + PS_METHODS, + PS_COMMENT, + BACKTICK_ESCAPE, + hljs.NUMBER_MODE, + QUOTE_STRING, + APOS_STRING, + // PS_NEW_OBJECT_TYPE, + CMDLETS, + VAR, + LITERAL, + HASH_SIGNS + ]; + + const PS_TYPE = { + begin: /\[/, + end: /\]/, + excludeBegin: true, + excludeEnd: true, + relevance: 0, + contains: [].concat( + 'self', + GENTLEMANS_SET, + { + begin: "(" + TYPES.join("|") + ")", + className: "built_in", + relevance: 0 + }, + { + className: 'type', + begin: /[\.\w\d]+/, + relevance: 0 + } + ) + }; + + PS_METHODS.contains.unshift(PS_TYPE); + + return { + name: 'PowerShell', + aliases: [ + "ps", + "ps1" + ], + case_insensitive: true, + keywords: KEYWORDS, + contains: GENTLEMANS_SET.concat( + PS_CLASS, + PS_FUNCTION, + PS_USING, + PS_ARGUMENTS, + PS_TYPE + ) + }; +} + +module.exports = powershell; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/processing.js b/claude-code-source/node_modules/highlight.js/lib/languages/processing.js new file mode 100644 index 00000000..36903337 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/processing.js @@ -0,0 +1,58 @@ +/* +Language: Processing +Description: Processing is a flexible software sketchbook and a language for learning how to code within the context of the visual arts. +Author: Erik Paluka +Website: https://processing.org +Category: graphics +*/ + +function processing(hljs) { + return { + name: 'Processing', + keywords: { + keyword: 'BufferedReader PVector PFont PImage PGraphics HashMap boolean byte char color ' + + 'double float int long String Array FloatDict FloatList IntDict IntList JSONArray JSONObject ' + + 'Object StringDict StringList Table TableRow XML ' + + // Java keywords + 'false synchronized int abstract float private char boolean static null if const ' + + 'for true while long throw strictfp finally protected import native final return void ' + + 'enum else break transient new catch instanceof byte super volatile case assert short ' + + 'package default double public try this switch continue throws protected public private', + literal: 'P2D P3D HALF_PI PI QUARTER_PI TAU TWO_PI', + title: 'setup draw', + built_in: 'displayHeight displayWidth mouseY mouseX mousePressed pmouseX pmouseY key ' + + 'keyCode pixels focused frameCount frameRate height width ' + + 'size createGraphics beginDraw createShape loadShape PShape arc ellipse line point ' + + 'quad rect triangle bezier bezierDetail bezierPoint bezierTangent curve curveDetail curvePoint ' + + 'curveTangent curveTightness shape shapeMode beginContour beginShape bezierVertex curveVertex ' + + 'endContour endShape quadraticVertex vertex ellipseMode noSmooth rectMode smooth strokeCap ' + + 'strokeJoin strokeWeight mouseClicked mouseDragged mouseMoved mousePressed mouseReleased ' + + 'mouseWheel keyPressed keyPressedkeyReleased keyTyped print println save saveFrame day hour ' + + 'millis minute month second year background clear colorMode fill noFill noStroke stroke alpha ' + + 'blue brightness color green hue lerpColor red saturation modelX modelY modelZ screenX screenY ' + + 'screenZ ambient emissive shininess specular add createImage beginCamera camera endCamera frustum ' + + 'ortho perspective printCamera printProjection cursor frameRate noCursor exit loop noLoop popStyle ' + + 'pushStyle redraw binary boolean byte char float hex int str unbinary unhex join match matchAll nf ' + + 'nfc nfp nfs split splitTokens trim append arrayCopy concat expand reverse shorten sort splice subset ' + + 'box sphere sphereDetail createInput createReader loadBytes loadJSONArray loadJSONObject loadStrings ' + + 'loadTable loadXML open parseXML saveTable selectFolder selectInput beginRaw beginRecord createOutput ' + + 'createWriter endRaw endRecord PrintWritersaveBytes saveJSONArray saveJSONObject saveStream saveStrings ' + + 'saveXML selectOutput popMatrix printMatrix pushMatrix resetMatrix rotate rotateX rotateY rotateZ scale ' + + 'shearX shearY translate ambientLight directionalLight lightFalloff lights lightSpecular noLights normal ' + + 'pointLight spotLight image imageMode loadImage noTint requestImage tint texture textureMode textureWrap ' + + 'blend copy filter get loadPixels set updatePixels blendMode loadShader PShaderresetShader shader createFont ' + + 'loadFont text textFont textAlign textLeading textMode textSize textWidth textAscent textDescent abs ceil ' + + 'constrain dist exp floor lerp log mag map max min norm pow round sq sqrt acos asin atan atan2 cos degrees ' + + 'radians sin tan noise noiseDetail noiseSeed random randomGaussian randomSeed' + }, + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + hljs.C_NUMBER_MODE + ] + }; +} + +module.exports = processing; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/profile.js b/claude-code-source/node_modules/highlight.js/lib/languages/profile.js new file mode 100644 index 00000000..35a8fe70 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/profile.js @@ -0,0 +1,43 @@ +/* +Language: Python profiler +Description: Python profiler results +Author: Brian Beck +*/ + +function profile(hljs) { + return { + name: 'Python profiler', + contains: [ + hljs.C_NUMBER_MODE, + { + begin: '[a-zA-Z_][\\da-zA-Z_]+\\.[\\da-zA-Z_]{1,3}', + end: ':', + excludeEnd: true + }, + { + begin: '(ncalls|tottime|cumtime)', + end: '$', + keywords: 'ncalls tottime|10 cumtime|10 filename', + relevance: 10 + }, + { + begin: 'function calls', + end: '$', + contains: [ hljs.C_NUMBER_MODE ], + relevance: 10 + }, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + { + className: 'string', + begin: '\\(', + end: '\\)$', + excludeBegin: true, + excludeEnd: true, + relevance: 0 + } + ] + }; +} + +module.exports = profile; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/prolog.js b/claude-code-source/node_modules/highlight.js/lib/languages/prolog.js new file mode 100644 index 00000000..25556cdd --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/prolog.js @@ -0,0 +1,102 @@ +/* +Language: Prolog +Description: Prolog is a general purpose logic programming language associated with artificial intelligence and computational linguistics. +Author: Raivo Laanemets +Website: https://en.wikipedia.org/wiki/Prolog +*/ + +function prolog(hljs) { + const ATOM = { + + begin: /[a-z][A-Za-z0-9_]*/, + relevance: 0 + }; + + const VAR = { + + className: 'symbol', + variants: [ + { + begin: /[A-Z][a-zA-Z0-9_]*/ + }, + { + begin: /_[A-Za-z0-9_]*/ + } + ], + relevance: 0 + }; + + const PARENTED = { + + begin: /\(/, + end: /\)/, + relevance: 0 + }; + + const LIST = { + + begin: /\[/, + end: /\]/ + }; + + const LINE_COMMENT = { + + className: 'comment', + begin: /%/, + end: /$/, + contains: [ hljs.PHRASAL_WORDS_MODE ] + }; + + const BACKTICK_STRING = { + + className: 'string', + begin: /`/, + end: /`/, + contains: [ hljs.BACKSLASH_ESCAPE ] + }; + + const CHAR_CODE = { + className: 'string', // 0'a etc. + begin: /0'(\\'|.)/ + }; + + const SPACE_CODE = { + className: 'string', + begin: /0'\\s/ // 0'\s + }; + + const PRED_OP = { // relevance booster + begin: /:-/ + }; + + const inner = [ + + ATOM, + VAR, + PARENTED, + PRED_OP, + LIST, + LINE_COMMENT, + hljs.C_BLOCK_COMMENT_MODE, + hljs.QUOTE_STRING_MODE, + hljs.APOS_STRING_MODE, + BACKTICK_STRING, + CHAR_CODE, + SPACE_CODE, + hljs.C_NUMBER_MODE + ]; + + PARENTED.contains = inner; + LIST.contains = inner; + + return { + name: 'Prolog', + contains: inner.concat([ + { // relevance booster + begin: /\.$/ + } + ]) + }; +} + +module.exports = prolog; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/properties.js b/claude-code-source/node_modules/highlight.js/lib/languages/properties.js new file mode 100644 index 00000000..6ae05a44 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/properties.js @@ -0,0 +1,85 @@ +/* +Language: .properties +Contributors: Valentin Aitken , Egor Rogov +Website: https://en.wikipedia.org/wiki/.properties +Category: common, config +*/ + +function properties(hljs) { + + // whitespaces: space, tab, formfeed + var WS0 = '[ \\t\\f]*'; + var WS1 = '[ \\t\\f]+'; + // delimiter + var EQUAL_DELIM = WS0+'[:=]'+WS0; + var WS_DELIM = WS1; + var DELIM = '(' + EQUAL_DELIM + '|' + WS_DELIM + ')'; + var KEY_ALPHANUM = '([^\\\\\\W:= \\t\\f\\n]|\\\\.)+'; + var KEY_OTHER = '([^\\\\:= \\t\\f\\n]|\\\\.)+'; + + var DELIM_AND_VALUE = { + // skip DELIM + end: DELIM, + relevance: 0, + starts: { + // value: everything until end of line (again, taking into account backslashes) + className: 'string', + end: /$/, + relevance: 0, + contains: [ + { begin: '\\\\\\\\'}, + { begin: '\\\\\\n' } + ] + } + }; + + return { + name: '.properties', + case_insensitive: true, + illegal: /\S/, + contains: [ + hljs.COMMENT('^\\s*[!#]', '$'), + // key: everything until whitespace or = or : (taking into account backslashes) + // case of a "normal" key + { + returnBegin: true, + variants: [ + { begin: KEY_ALPHANUM + EQUAL_DELIM, relevance: 1 }, + { begin: KEY_ALPHANUM + WS_DELIM, relevance: 0 } + ], + contains: [ + { + className: 'attr', + begin: KEY_ALPHANUM, + endsParent: true, + relevance: 0 + } + ], + starts: DELIM_AND_VALUE + }, + // case of key containing non-alphanumeric chars => relevance = 0 + { + begin: KEY_OTHER + DELIM, + returnBegin: true, + relevance: 0, + contains: [ + { + className: 'meta', + begin: KEY_OTHER, + endsParent: true, + relevance: 0 + } + ], + starts: DELIM_AND_VALUE + }, + // case of an empty key + { + className: 'attr', + relevance: 0, + begin: KEY_OTHER + WS0 + '$' + } + ] + }; +} + +module.exports = properties; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/protobuf.js b/claude-code-source/node_modules/highlight.js/lib/languages/protobuf.js new file mode 100644 index 00000000..2ab25f19 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/protobuf.js @@ -0,0 +1,47 @@ +/* +Language: Protocol Buffers +Author: Dan Tao +Description: Protocol buffer message definition format +Website: https://developers.google.com/protocol-buffers/docs/proto3 +Category: protocols +*/ + +function protobuf(hljs) { + return { + name: 'Protocol Buffers', + keywords: { + keyword: 'package import option optional required repeated group oneof', + built_in: 'double float int32 int64 uint32 uint64 sint32 sint64 ' + + 'fixed32 fixed64 sfixed32 sfixed64 bool string bytes', + literal: 'true false' + }, + contains: [ + hljs.QUOTE_STRING_MODE, + hljs.NUMBER_MODE, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + { + className: 'class', + beginKeywords: 'message enum service', end: /\{/, + illegal: /\n/, + contains: [ + hljs.inherit(hljs.TITLE_MODE, { + starts: {endsWithParent: true, excludeEnd: true} // hack: eating everything after the first title + }) + ] + }, + { + className: 'function', + beginKeywords: 'rpc', + end: /[{;]/, excludeEnd: true, + keywords: 'rpc returns' + }, + { // match enum items (relevance) + // BLAH = ...; + begin: /^\s*[A-Z_]+(?=\s*=[^\n]+;$)/ + } + ] + }; +} + +module.exports = protobuf; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/puppet.js b/claude-code-source/node_modules/highlight.js/lib/languages/puppet.js new file mode 100644 index 00000000..026f63a1 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/puppet.js @@ -0,0 +1,147 @@ +/* +Language: Puppet +Author: Jose Molina Colmenero +Website: https://puppet.com/docs +Category: config +*/ + +function puppet(hljs) { + const PUPPET_KEYWORDS = { + keyword: + /* language keywords */ + 'and case default else elsif false if in import enherits node or true undef unless main settings $string ', + literal: + /* metaparameters */ + 'alias audit before loglevel noop require subscribe tag ' + + /* normal attributes */ + 'owner ensure group mode name|0 changes context force incl lens load_path onlyif provider returns root show_diff type_check ' + + 'en_address ip_address realname command environment hour monute month monthday special target weekday ' + + 'creates cwd ogoutput refresh refreshonly tries try_sleep umask backup checksum content ctime force ignore ' + + 'links mtime purge recurse recurselimit replace selinux_ignore_defaults selrange selrole seltype seluser source ' + + 'souirce_permissions sourceselect validate_cmd validate_replacement allowdupe attribute_membership auth_membership forcelocal gid ' + + 'ia_load_module members system host_aliases ip allowed_trunk_vlans description device_url duplex encapsulation etherchannel ' + + 'native_vlan speed principals allow_root auth_class auth_type authenticate_user k_of_n mechanisms rule session_owner shared options ' + + 'device fstype enable hasrestart directory present absent link atboot blockdevice device dump pass remounts poller_tag use ' + + 'message withpath adminfile allow_virtual allowcdrom category configfiles flavor install_options instance package_settings platform ' + + 'responsefile status uninstall_options vendor unless_system_user unless_uid binary control flags hasstatus manifest pattern restart running ' + + 'start stop allowdupe auths expiry gid groups home iterations key_membership keys managehome membership password password_max_age ' + + 'password_min_age profile_membership profiles project purge_ssh_keys role_membership roles salt shell uid baseurl cost descr enabled ' + + 'enablegroups exclude failovermethod gpgcheck gpgkey http_caching include includepkgs keepalive metadata_expire metalink mirrorlist ' + + 'priority protect proxy proxy_password proxy_username repo_gpgcheck s3_enabled skip_if_unavailable sslcacert sslclientcert sslclientkey ' + + 'sslverify mounted', + built_in: + /* core facts */ + 'architecture augeasversion blockdevices boardmanufacturer boardproductname boardserialnumber cfkey dhcp_servers ' + + 'domain ec2_ ec2_userdata facterversion filesystems ldom fqdn gid hardwareisa hardwaremodel hostname id|0 interfaces ' + + 'ipaddress ipaddress_ ipaddress6 ipaddress6_ iphostnumber is_virtual kernel kernelmajversion kernelrelease kernelversion ' + + 'kernelrelease kernelversion lsbdistcodename lsbdistdescription lsbdistid lsbdistrelease lsbmajdistrelease lsbminordistrelease ' + + 'lsbrelease macaddress macaddress_ macosx_buildversion macosx_productname macosx_productversion macosx_productverson_major ' + + 'macosx_productversion_minor manufacturer memoryfree memorysize netmask metmask_ network_ operatingsystem operatingsystemmajrelease ' + + 'operatingsystemrelease osfamily partitions path physicalprocessorcount processor processorcount productname ps puppetversion ' + + 'rubysitedir rubyversion selinux selinux_config_mode selinux_config_policy selinux_current_mode selinux_current_mode selinux_enforced ' + + 'selinux_policyversion serialnumber sp_ sshdsakey sshecdsakey sshrsakey swapencrypted swapfree swapsize timezone type uniqueid uptime ' + + 'uptime_days uptime_hours uptime_seconds uuid virtual vlans xendomains zfs_version zonenae zones zpool_version' + }; + + const COMMENT = hljs.COMMENT('#', '$'); + + const IDENT_RE = '([A-Za-z_]|::)(\\w|::)*'; + + const TITLE = hljs.inherit(hljs.TITLE_MODE, { + begin: IDENT_RE + }); + + const VARIABLE = { + className: 'variable', + begin: '\\$' + IDENT_RE + }; + + const STRING = { + className: 'string', + contains: [ + hljs.BACKSLASH_ESCAPE, + VARIABLE + ], + variants: [ + { + begin: /'/, + end: /'/ + }, + { + begin: /"/, + end: /"/ + } + ] + }; + + return { + name: 'Puppet', + aliases: [ 'pp' ], + contains: [ + COMMENT, + VARIABLE, + STRING, + { + beginKeywords: 'class', + end: '\\{|;', + illegal: /=/, + contains: [ + TITLE, + COMMENT + ] + }, + { + beginKeywords: 'define', + end: /\{/, + contains: [ + { + className: 'section', + begin: hljs.IDENT_RE, + endsParent: true + } + ] + }, + { + begin: hljs.IDENT_RE + '\\s+\\{', + returnBegin: true, + end: /\S/, + contains: [ + { + className: 'keyword', + begin: hljs.IDENT_RE + }, + { + begin: /\{/, + end: /\}/, + keywords: PUPPET_KEYWORDS, + relevance: 0, + contains: [ + STRING, + COMMENT, + { + begin: '[a-zA-Z_]+\\s*=>', + returnBegin: true, + end: '=>', + contains: [ + { + className: 'attr', + begin: hljs.IDENT_RE + } + ] + }, + { + className: 'number', + begin: '(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b', + relevance: 0 + }, + VARIABLE + ] + } + ], + relevance: 0 + } + ] + }; +} + +module.exports = puppet; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/purebasic.js b/claude-code-source/node_modules/highlight.js/lib/languages/purebasic.js new file mode 100644 index 00000000..6dd36cf9 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/purebasic.js @@ -0,0 +1,101 @@ +/* +Language: PureBASIC +Author: Tristano Ajmone +Description: Syntax highlighting for PureBASIC (v.5.00-5.60). No inline ASM highlighting. (v.1.2, May 2017) +Credits: I've taken inspiration from the PureBasic language file for GeSHi, created by Gustavo Julio Fiorenza (GuShH). +Website: https://www.purebasic.com +*/ + +// Base deafult colors in PB IDE: background: #FFFFDF; foreground: #000000; + +function purebasic(hljs) { + const STRINGS = { // PB IDE color: #0080FF (Azure Radiance) + className: 'string', + begin: '(~)?"', + end: '"', + illegal: '\\n' + }; + const CONSTANTS = { // PB IDE color: #924B72 (Cannon Pink) + // "#" + a letter or underscore + letters, digits or underscores + (optional) "$" + className: 'symbol', + begin: '#[a-zA-Z_]\\w*\\$?' + }; + + return { + name: 'PureBASIC', + aliases: [ + 'pb', + 'pbi' + ], + keywords: // PB IDE color: #006666 (Blue Stone) + Bold + // Keywords from all version of PureBASIC 5.00 upward ... + 'Align And Array As Break CallDebugger Case CompilerCase CompilerDefault ' + + 'CompilerElse CompilerElseIf CompilerEndIf CompilerEndSelect CompilerError ' + + 'CompilerIf CompilerSelect CompilerWarning Continue Data DataSection Debug ' + + 'DebugLevel Declare DeclareC DeclareCDLL DeclareDLL DeclareModule Default ' + + 'Define Dim DisableASM DisableDebugger DisableExplicit Else ElseIf EnableASM ' + + 'EnableDebugger EnableExplicit End EndDataSection EndDeclareModule EndEnumeration ' + + 'EndIf EndImport EndInterface EndMacro EndModule EndProcedure EndSelect ' + + 'EndStructure EndStructureUnion EndWith Enumeration EnumerationBinary Extends ' + + 'FakeReturn For ForEach ForEver Global Gosub Goto If Import ImportC ' + + 'IncludeBinary IncludeFile IncludePath Interface List Macro MacroExpandedCount ' + + 'Map Module NewList NewMap Next Not Or Procedure ProcedureC ' + + 'ProcedureCDLL ProcedureDLL ProcedureReturn Protected Prototype PrototypeC ReDim ' + + 'Read Repeat Restore Return Runtime Select Shared Static Step Structure ' + + 'StructureUnion Swap Threaded To UndefineMacro Until Until UnuseModule ' + + 'UseModule Wend While With XIncludeFile XOr', + contains: [ + // COMMENTS | PB IDE color: #00AAAA (Persian Green) + hljs.COMMENT(';', '$', { + relevance: 0 + }), + + { // PROCEDURES DEFINITIONS + className: 'function', + begin: '\\b(Procedure|Declare)(C|CDLL|DLL)?\\b', + end: '\\(', + excludeEnd: true, + returnBegin: true, + contains: [ + { // PROCEDURE KEYWORDS | PB IDE color: #006666 (Blue Stone) + Bold + className: 'keyword', + begin: '(Procedure|Declare)(C|CDLL|DLL)?', + excludeEnd: true + }, + { // PROCEDURE RETURN TYPE SETTING | PB IDE color: #000000 (Black) + className: 'type', + begin: '\\.\\w*' + // end: ' ', + }, + hljs.UNDERSCORE_TITLE_MODE // PROCEDURE NAME | PB IDE color: #006666 (Blue Stone) + ] + }, + STRINGS, + CONSTANTS + ] + }; +} + +/* ============================================================================== + CHANGELOG + ============================================================================== + - v.1.2 (2017-05-12) + -- BUG-FIX: Some keywords were accidentally joyned together. Now fixed. + - v.1.1 (2017-04-30) + -- Updated to PureBASIC 5.60. + -- Keywords list now built by extracting them from the PureBASIC SDK's + "SyntaxHilighting.dll" (from each PureBASIC version). Tokens from each + version are added to the list, and renamed or removed tokens are kept + for the sake of covering all versions of the language from PureBASIC + v5.00 upward. (NOTE: currently, there are no renamed or deprecated + tokens in the keywords list). For more info, see: + -- http://www.purebasic.fr/english/viewtopic.php?&p=506269 + -- https://github.com/tajmone/purebasic-archives/tree/master/syntax-highlighting/guidelines + - v.1.0 (April 2016) + -- First release + -- Keywords list taken and adapted from GuShH's (Gustavo Julio Fiorenza) + PureBasic language file for GeSHi: + -- https://github.com/easybook/geshi/blob/master/geshi/purebasic.php +*/ + +module.exports = purebasic; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/python-repl.js b/claude-code-source/node_modules/highlight.js/lib/languages/python-repl.js new file mode 100644 index 00000000..6c1ead0f --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/python-repl.js @@ -0,0 +1,36 @@ +/* +Language: Python REPL +Requires: python.js +Author: Josh Goebel +Category: common +*/ + +function pythonRepl(hljs) { + return { + aliases: [ 'pycon' ], + contains: [ + { + className: 'meta', + starts: { + // a space separates the REPL prefix from the actual code + // this is purely for cleaner HTML output + end: / |$/, + starts: { + end: '$', + subLanguage: 'python' + } + }, + variants: [ + { + begin: /^>>>(?=[ ]|$)/ + }, + { + begin: /^\.\.\.(?=[ ]|$)/ + } + ] + } + ] + }; +} + +module.exports = pythonRepl; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/python.js b/claude-code-source/node_modules/highlight.js/lib/languages/python.js new file mode 100644 index 00000000..20ce111a --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/python.js @@ -0,0 +1,446 @@ +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function lookahead(re) { + return concat('(?=', re, ')'); +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/* +Language: Python +Description: Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. +Website: https://www.python.org +Category: common +*/ + +function python(hljs) { + const RESERVED_WORDS = [ + 'and', + 'as', + 'assert', + 'async', + 'await', + 'break', + 'class', + 'continue', + 'def', + 'del', + 'elif', + 'else', + 'except', + 'finally', + 'for', + 'from', + 'global', + 'if', + 'import', + 'in', + 'is', + 'lambda', + 'nonlocal|10', + 'not', + 'or', + 'pass', + 'raise', + 'return', + 'try', + 'while', + 'with', + 'yield' + ]; + + const BUILT_INS = [ + '__import__', + 'abs', + 'all', + 'any', + 'ascii', + 'bin', + 'bool', + 'breakpoint', + 'bytearray', + 'bytes', + 'callable', + 'chr', + 'classmethod', + 'compile', + 'complex', + 'delattr', + 'dict', + 'dir', + 'divmod', + 'enumerate', + 'eval', + 'exec', + 'filter', + 'float', + 'format', + 'frozenset', + 'getattr', + 'globals', + 'hasattr', + 'hash', + 'help', + 'hex', + 'id', + 'input', + 'int', + 'isinstance', + 'issubclass', + 'iter', + 'len', + 'list', + 'locals', + 'map', + 'max', + 'memoryview', + 'min', + 'next', + 'object', + 'oct', + 'open', + 'ord', + 'pow', + 'print', + 'property', + 'range', + 'repr', + 'reversed', + 'round', + 'set', + 'setattr', + 'slice', + 'sorted', + 'staticmethod', + 'str', + 'sum', + 'super', + 'tuple', + 'type', + 'vars', + 'zip' + ]; + + const LITERALS = [ + '__debug__', + 'Ellipsis', + 'False', + 'None', + 'NotImplemented', + 'True' + ]; + + // https://docs.python.org/3/library/typing.html + // TODO: Could these be supplemented by a CamelCase matcher in certain + // contexts, leaving these remaining only for relevance hinting? + const TYPES = [ + "Any", + "Callable", + "Coroutine", + "Dict", + "List", + "Literal", + "Generic", + "Optional", + "Sequence", + "Set", + "Tuple", + "Type", + "Union" + ]; + + const KEYWORDS = { + $pattern: /[A-Za-z]\w+|__\w+__/, + keyword: RESERVED_WORDS, + built_in: BUILT_INS, + literal: LITERALS, + type: TYPES + }; + + const PROMPT = { + className: 'meta', + begin: /^(>>>|\.\.\.) / + }; + + const SUBST = { + className: 'subst', + begin: /\{/, + end: /\}/, + keywords: KEYWORDS, + illegal: /#/ + }; + + const LITERAL_BRACKET = { + begin: /\{\{/, + relevance: 0 + }; + + const STRING = { + className: 'string', + contains: [ hljs.BACKSLASH_ESCAPE ], + variants: [ + { + begin: /([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?'''/, + end: /'''/, + contains: [ + hljs.BACKSLASH_ESCAPE, + PROMPT + ], + relevance: 10 + }, + { + begin: /([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?"""/, + end: /"""/, + contains: [ + hljs.BACKSLASH_ESCAPE, + PROMPT + ], + relevance: 10 + }, + { + begin: /([fF][rR]|[rR][fF]|[fF])'''/, + end: /'''/, + contains: [ + hljs.BACKSLASH_ESCAPE, + PROMPT, + LITERAL_BRACKET, + SUBST + ] + }, + { + begin: /([fF][rR]|[rR][fF]|[fF])"""/, + end: /"""/, + contains: [ + hljs.BACKSLASH_ESCAPE, + PROMPT, + LITERAL_BRACKET, + SUBST + ] + }, + { + begin: /([uU]|[rR])'/, + end: /'/, + relevance: 10 + }, + { + begin: /([uU]|[rR])"/, + end: /"/, + relevance: 10 + }, + { + begin: /([bB]|[bB][rR]|[rR][bB])'/, + end: /'/ + }, + { + begin: /([bB]|[bB][rR]|[rR][bB])"/, + end: /"/ + }, + { + begin: /([fF][rR]|[rR][fF]|[fF])'/, + end: /'/, + contains: [ + hljs.BACKSLASH_ESCAPE, + LITERAL_BRACKET, + SUBST + ] + }, + { + begin: /([fF][rR]|[rR][fF]|[fF])"/, + end: /"/, + contains: [ + hljs.BACKSLASH_ESCAPE, + LITERAL_BRACKET, + SUBST + ] + }, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE + ] + }; + + // https://docs.python.org/3.9/reference/lexical_analysis.html#numeric-literals + const digitpart = '[0-9](_?[0-9])*'; + const pointfloat = `(\\b(${digitpart}))?\\.(${digitpart})|\\b(${digitpart})\\.`; + const NUMBER = { + className: 'number', + relevance: 0, + variants: [ + // exponentfloat, pointfloat + // https://docs.python.org/3.9/reference/lexical_analysis.html#floating-point-literals + // optionally imaginary + // https://docs.python.org/3.9/reference/lexical_analysis.html#imaginary-literals + // Note: no leading \b because floats can start with a decimal point + // and we don't want to mishandle e.g. `fn(.5)`, + // no trailing \b for pointfloat because it can end with a decimal point + // and we don't want to mishandle e.g. `0..hex()`; this should be safe + // because both MUST contain a decimal point and so cannot be confused with + // the interior part of an identifier + { + begin: `(\\b(${digitpart})|(${pointfloat}))[eE][+-]?(${digitpart})[jJ]?\\b` + }, + { + begin: `(${pointfloat})[jJ]?` + }, + + // decinteger, bininteger, octinteger, hexinteger + // https://docs.python.org/3.9/reference/lexical_analysis.html#integer-literals + // optionally "long" in Python 2 + // https://docs.python.org/2.7/reference/lexical_analysis.html#integer-and-long-integer-literals + // decinteger is optionally imaginary + // https://docs.python.org/3.9/reference/lexical_analysis.html#imaginary-literals + { + begin: '\\b([1-9](_?[0-9])*|0+(_?0)*)[lLjJ]?\\b' + }, + { + begin: '\\b0[bB](_?[01])+[lL]?\\b' + }, + { + begin: '\\b0[oO](_?[0-7])+[lL]?\\b' + }, + { + begin: '\\b0[xX](_?[0-9a-fA-F])+[lL]?\\b' + }, + + // imagnumber (digitpart-based) + // https://docs.python.org/3.9/reference/lexical_analysis.html#imaginary-literals + { + begin: `\\b(${digitpart})[jJ]\\b` + } + ] + }; + const COMMENT_TYPE = { + className: "comment", + begin: lookahead(/# type:/), + end: /$/, + keywords: KEYWORDS, + contains: [ + { // prevent keywords from coloring `type` + begin: /# type:/ + }, + // comment within a datatype comment includes no keywords + { + begin: /#/, + end: /\b\B/, + endsWithParent: true + } + ] + }; + const PARAMS = { + className: 'params', + variants: [ + // Exclude params in functions without params + { + className: "", + begin: /\(\s*\)/, + skip: true + }, + { + begin: /\(/, + end: /\)/, + excludeBegin: true, + excludeEnd: true, + keywords: KEYWORDS, + contains: [ + 'self', + PROMPT, + NUMBER, + STRING, + hljs.HASH_COMMENT_MODE + ] + } + ] + }; + SUBST.contains = [ + STRING, + NUMBER, + PROMPT + ]; + + return { + name: 'Python', + aliases: [ + 'py', + 'gyp', + 'ipython' + ], + keywords: KEYWORDS, + illegal: /(<\/|->|\?)|=>/, + contains: [ + PROMPT, + NUMBER, + { + // very common convention + begin: /\bself\b/ + }, + { + // eat "if" prior to string so that it won't accidentally be + // labeled as an f-string + beginKeywords: "if", + relevance: 0 + }, + STRING, + COMMENT_TYPE, + hljs.HASH_COMMENT_MODE, + { + variants: [ + { + className: 'function', + beginKeywords: 'def' + }, + { + className: 'class', + beginKeywords: 'class' + } + ], + end: /:/, + illegal: /[${=;\n,]/, + contains: [ + hljs.UNDERSCORE_TITLE_MODE, + PARAMS, + { + begin: /->/, + endsWithParent: true, + keywords: KEYWORDS + } + ] + }, + { + className: 'meta', + begin: /^[\t ]*@/, + end: /(?=#)|$/, + contains: [ + NUMBER, + PARAMS, + STRING + ] + } + ] + }; +} + +module.exports = python; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/q.js b/claude-code-source/node_modules/highlight.js/lib/languages/q.js new file mode 100644 index 00000000..0737415d --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/q.js @@ -0,0 +1,37 @@ +/* +Language: Q +Description: Q is a vector-based functional paradigm programming language built into the kdb+ database. + (K/Q/Kdb+ from Kx Systems) +Author: Sergey Vidyuk +Website: https://kx.com/connect-with-us/developers/ +*/ + +function q(hljs) { + const KEYWORDS = { + $pattern: /(`?)[A-Za-z0-9_]+\b/, + keyword: + 'do while select delete by update from', + literal: + '0b 1b', + built_in: + 'neg not null string reciprocal floor ceiling signum mod xbar xlog and or each scan over prior mmu lsq inv md5 ltime gtime count first var dev med cov cor all any rand sums prds mins maxs fills deltas ratios avgs differ prev next rank reverse iasc idesc asc desc msum mcount mavg mdev xrank mmin mmax xprev rotate distinct group where flip type key til get value attr cut set upsert raze union inter except cross sv vs sublist enlist read0 read1 hopen hclose hdel hsym hcount peach system ltrim rtrim trim lower upper ssr view tables views cols xcols keys xkey xcol xasc xdesc fkeys meta lj aj aj0 ij pj asof uj ww wj wj1 fby xgroup ungroup ej save load rsave rload show csv parse eval min max avg wavg wsum sin cos tan sum', + type: + '`float `double int `timestamp `timespan `datetime `time `boolean `symbol `char `byte `short `long `real `month `date `minute `second `guid' + }; + + return { + name: 'Q', + aliases: [ + 'k', + 'kdb' + ], + keywords: KEYWORDS, + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.QUOTE_STRING_MODE, + hljs.C_NUMBER_MODE + ] + }; +} + +module.exports = q; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/qml.js b/claude-code-source/node_modules/highlight.js/lib/languages/qml.js new file mode 100644 index 00000000..57b109d5 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/qml.js @@ -0,0 +1,225 @@ +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/* +Language: QML +Requires: javascript.js, xml.js +Author: John Foster +Description: Syntax highlighting for the Qt Quick QML scripting language, based mostly off + the JavaScript parser. +Website: https://doc.qt.io/qt-5/qmlapplications.html +Category: scripting +*/ + +function qml(hljs) { + const KEYWORDS = { + keyword: + 'in of on if for while finally var new function do return void else break catch ' + + 'instanceof with throw case default try this switch continue typeof delete ' + + 'let yield const export super debugger as async await import', + literal: + 'true false null undefined NaN Infinity', + built_in: + 'eval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent ' + + 'encodeURI encodeURIComponent escape unescape Object Function Boolean Error ' + + 'EvalError InternalError RangeError ReferenceError StopIteration SyntaxError ' + + 'TypeError URIError Number Math Date String RegExp Array Float32Array ' + + 'Float64Array Int16Array Int32Array Int8Array Uint16Array Uint32Array ' + + 'Uint8Array Uint8ClampedArray ArrayBuffer DataView JSON Intl arguments require ' + + 'module console window document Symbol Set Map WeakSet WeakMap Proxy Reflect ' + + 'Behavior bool color coordinate date double enumeration font geocircle georectangle ' + + 'geoshape int list matrix4x4 parent point quaternion real rect ' + + 'size string url variant vector2d vector3d vector4d ' + + 'Promise' + }; + + const QML_IDENT_RE = '[a-zA-Z_][a-zA-Z0-9\\._]*'; + + // Isolate property statements. Ends at a :, =, ;, ,, a comment or end of line. + // Use property class. + const PROPERTY = { + className: 'keyword', + begin: '\\bproperty\\b', + starts: { + className: 'string', + end: '(:|=|;|,|//|/\\*|$)', + returnEnd: true + } + }; + + // Isolate signal statements. Ends at a ) a comment or end of line. + // Use property class. + const SIGNAL = { + className: 'keyword', + begin: '\\bsignal\\b', + starts: { + className: 'string', + end: '(\\(|:|=|;|,|//|/\\*|$)', + returnEnd: true + } + }; + + // id: is special in QML. When we see id: we want to mark the id: as attribute and + // emphasize the token following. + const ID_ID = { + className: 'attribute', + begin: '\\bid\\s*:', + starts: { + className: 'string', + end: QML_IDENT_RE, + returnEnd: false + } + }; + + // Find QML object attribute. An attribute is a QML identifier followed by :. + // Unfortunately it's hard to know where it ends, as it may contain scalars, + // objects, object definitions, or javascript. The true end is either when the parent + // ends or the next attribute is detected. + const QML_ATTRIBUTE = { + begin: QML_IDENT_RE + '\\s*:', + returnBegin: true, + contains: [ + { + className: 'attribute', + begin: QML_IDENT_RE, + end: '\\s*:', + excludeEnd: true, + relevance: 0 + } + ], + relevance: 0 + }; + + // Find QML object. A QML object is a QML identifier followed by { and ends at the matching }. + // All we really care about is finding IDENT followed by { and just mark up the IDENT and ignore the {. + const QML_OBJECT = { + begin: concat(QML_IDENT_RE, /\s*\{/), + end: /\{/, + returnBegin: true, + relevance: 0, + contains: [ + hljs.inherit(hljs.TITLE_MODE, { + begin: QML_IDENT_RE + }) + ] + }; + + return { + name: 'QML', + aliases: [ 'qt' ], + case_insensitive: false, + keywords: KEYWORDS, + contains: [ + { + className: 'meta', + begin: /^\s*['"]use (strict|asm)['"]/ + }, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + { // template string + className: 'string', + begin: '`', + end: '`', + contains: [ + hljs.BACKSLASH_ESCAPE, + { + className: 'subst', + begin: '\\$\\{', + end: '\\}' + } + ] + }, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + { + className: 'number', + variants: [ + { + begin: '\\b(0[bB][01]+)' + }, + { + begin: '\\b(0[oO][0-7]+)' + }, + { + begin: hljs.C_NUMBER_RE + } + ], + relevance: 0 + }, + { // "value" container + begin: '(' + hljs.RE_STARTERS_RE + '|\\b(case|return|throw)\\b)\\s*', + keywords: 'return throw case', + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.REGEXP_MODE, + { // E4X / JSX + begin: /\s*[);\]]/, + relevance: 0, + subLanguage: 'xml' + } + ], + relevance: 0 + }, + SIGNAL, + PROPERTY, + { + className: 'function', + beginKeywords: 'function', + end: /\{/, + excludeEnd: true, + contains: [ + hljs.inherit(hljs.TITLE_MODE, { + begin: /[A-Za-z$_][0-9A-Za-z$_]*/ + }), + { + className: 'params', + begin: /\(/, + end: /\)/, + excludeBegin: true, + excludeEnd: true, + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE + ] + } + ], + illegal: /\[|%/ + }, + { + // hack: prevents detection of keywords after dots + begin: '\\.' + hljs.IDENT_RE, + relevance: 0 + }, + ID_ID, + QML_ATTRIBUTE, + QML_OBJECT + ], + illegal: /#/ + }; +} + +module.exports = qml; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/r.js b/claude-code-source/node_modules/highlight.js/lib/languages/r.js new file mode 100644 index 00000000..d6444e08 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/r.js @@ -0,0 +1,231 @@ +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function lookahead(re) { + return concat('(?=', re, ')'); +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/* +Language: R +Description: R is a free software environment for statistical computing and graphics. +Author: Joe Cheng +Contributors: Konrad Rudolph +Website: https://www.r-project.org +Category: common,scientific +*/ + +/** @type LanguageFn */ +function r(hljs) { + // Identifiers in R cannot start with `_`, but they can start with `.` if it + // is not immediately followed by a digit. + // R also supports quoted identifiers, which are near-arbitrary sequences + // delimited by backticks (`…`), which may contain escape sequences. These are + // handled in a separate mode. See `test/markup/r/names.txt` for examples. + // FIXME: Support Unicode identifiers. + const IDENT_RE = /(?:(?:[a-zA-Z]|\.[._a-zA-Z])[._a-zA-Z0-9]*)|\.(?!\d)/; + const SIMPLE_IDENT = /[a-zA-Z][a-zA-Z_0-9]*/; + + return { + name: 'R', + + // only in Haskell, not R + illegal: /->/, + keywords: { + $pattern: IDENT_RE, + keyword: + 'function if in break next repeat else for while', + literal: + 'NULL NA TRUE FALSE Inf NaN NA_integer_|10 NA_real_|10 ' + + 'NA_character_|10 NA_complex_|10', + built_in: + // Builtin constants + 'LETTERS letters month.abb month.name pi T F ' + + // Primitive functions + // These are all the functions in `base` that are implemented as a + // `.Primitive`, minus those functions that are also keywords. + 'abs acos acosh all any anyNA Arg as.call as.character ' + + 'as.complex as.double as.environment as.integer as.logical ' + + 'as.null.default as.numeric as.raw asin asinh atan atanh attr ' + + 'attributes baseenv browser c call ceiling class Conj cos cosh ' + + 'cospi cummax cummin cumprod cumsum digamma dim dimnames ' + + 'emptyenv exp expression floor forceAndCall gamma gc.time ' + + 'globalenv Im interactive invisible is.array is.atomic is.call ' + + 'is.character is.complex is.double is.environment is.expression ' + + 'is.finite is.function is.infinite is.integer is.language ' + + 'is.list is.logical is.matrix is.na is.name is.nan is.null ' + + 'is.numeric is.object is.pairlist is.raw is.recursive is.single ' + + 'is.symbol lazyLoadDBfetch length lgamma list log max min ' + + 'missing Mod names nargs nzchar oldClass on.exit pos.to.env ' + + 'proc.time prod quote range Re rep retracemem return round ' + + 'seq_along seq_len seq.int sign signif sin sinh sinpi sqrt ' + + 'standardGeneric substitute sum switch tan tanh tanpi tracemem ' + + 'trigamma trunc unclass untracemem UseMethod xtfrm', + }, + compilerExtensions: [ + // allow beforeMatch to act as a "qualifier" for the match + // the full match begin must be [beforeMatch][begin] + (mode, parent) => { + if (!mode.beforeMatch) return; + // starts conflicts with endsParent which we need to make sure the child + // rule is not matched multiple times + if (mode.starts) throw new Error("beforeMatch cannot be used with starts"); + + const originalMode = Object.assign({}, mode); + Object.keys(mode).forEach((key) => { delete mode[key]; }); + + mode.begin = concat(originalMode.beforeMatch, lookahead(originalMode.begin)); + mode.starts = { + relevance: 0, + contains: [ + Object.assign(originalMode, { endsParent: true }) + ] + }; + mode.relevance = 0; + + delete originalMode.beforeMatch; + } + ], + contains: [ + // Roxygen comments + hljs.COMMENT( + /#'/, + /$/, + { + contains: [ + { + // Handle `@examples` separately to cause all subsequent code + // until the next `@`-tag on its own line to be kept as-is, + // preventing highlighting. This code is example R code, so nested + // doctags shouldn’t be treated as such. See + // `test/markup/r/roxygen.txt` for an example. + className: 'doctag', + begin: '@examples', + starts: { + contains: [ + { begin: /\n/ }, + { + begin: /#'\s*(?=@[a-zA-Z]+)/, + endsParent: true, + }, + { + begin: /#'/, + end: /$/, + excludeBegin: true, + } + ] + } + }, + { + // Handle `@param` to highlight the parameter name following + // after. + className: 'doctag', + begin: '@param', + end: /$/, + contains: [ + { + className: 'variable', + variants: [ + { begin: IDENT_RE }, + { begin: /`(?:\\.|[^`\\])+`/ } + ], + endsParent: true + } + ] + }, + { + className: 'doctag', + begin: /@[a-zA-Z]+/ + }, + { + className: 'meta-keyword', + begin: /\\[a-zA-Z]+/, + } + ] + } + ), + + hljs.HASH_COMMENT_MODE, + + { + className: 'string', + contains: [hljs.BACKSLASH_ESCAPE], + variants: [ + hljs.END_SAME_AS_BEGIN({ begin: /[rR]"(-*)\(/, end: /\)(-*)"/ }), + hljs.END_SAME_AS_BEGIN({ begin: /[rR]"(-*)\{/, end: /\}(-*)"/ }), + hljs.END_SAME_AS_BEGIN({ begin: /[rR]"(-*)\[/, end: /\](-*)"/ }), + hljs.END_SAME_AS_BEGIN({ begin: /[rR]'(-*)\(/, end: /\)(-*)'/ }), + hljs.END_SAME_AS_BEGIN({ begin: /[rR]'(-*)\{/, end: /\}(-*)'/ }), + hljs.END_SAME_AS_BEGIN({ begin: /[rR]'(-*)\[/, end: /\](-*)'/ }), + {begin: '"', end: '"', relevance: 0}, + {begin: "'", end: "'", relevance: 0} + ], + }, + { + className: 'number', + relevance: 0, + beforeMatch: /([^a-zA-Z0-9._])/, // not part of an identifier + variants: [ + // TODO: replace with negative look-behind when available + // { begin: /(? +Category: functional +*/ +function reasonml(hljs) { + function orReValues(ops) { + return ops + .map(function(op) { + return op + .split('') + .map(function(char) { + return '\\' + char; + }) + .join(''); + }) + .join('|'); + } + + const RE_IDENT = '~?[a-z$_][0-9a-zA-Z$_]*'; + const RE_MODULE_IDENT = '`?[A-Z$_][0-9a-zA-Z$_]*'; + + const RE_PARAM_TYPEPARAM = '\'?[a-z$_][0-9a-z$_]*'; + const RE_PARAM_TYPE = '\\s*:\\s*[a-z$_][0-9a-z$_]*(\\(\\s*(' + RE_PARAM_TYPEPARAM + '\\s*(,' + RE_PARAM_TYPEPARAM + '\\s*)*)?\\))?'; + const RE_PARAM = RE_IDENT + '(' + RE_PARAM_TYPE + '){0,2}'; + const RE_OPERATOR = "(" + orReValues([ + '||', + '++', + '**', + '+.', + '*', + '/', + '*.', + '/.', + '...' + ]) + "|\\|>|&&|==|===)"; + const RE_OPERATOR_SPACED = "\\s+" + RE_OPERATOR + "\\s+"; + + const KEYWORDS = { + keyword: + 'and as asr assert begin class constraint do done downto else end exception external ' + + 'for fun function functor if in include inherit initializer ' + + 'land lazy let lor lsl lsr lxor match method mod module mutable new nonrec ' + + 'object of open or private rec sig struct then to try type val virtual when while with', + built_in: + 'array bool bytes char exn|5 float int int32 int64 list lazy_t|5 nativeint|5 ref string unit ', + literal: + 'true false' + }; + + const RE_NUMBER = '\\b(0[xX][a-fA-F0-9_]+[Lln]?|' + + '0[oO][0-7_]+[Lln]?|' + + '0[bB][01_]+[Lln]?|' + + '[0-9][0-9_]*([Lln]|(\\.[0-9_]*)?([eE][-+]?[0-9_]+)?)?)'; + + const NUMBER_MODE = { + className: 'number', + relevance: 0, + variants: [ + { + begin: RE_NUMBER + }, + { + begin: '\\(-' + RE_NUMBER + '\\)' + } + ] + }; + + const OPERATOR_MODE = { + className: 'operator', + relevance: 0, + begin: RE_OPERATOR + }; + const LIST_CONTENTS_MODES = [ + { + className: 'identifier', + relevance: 0, + begin: RE_IDENT + }, + OPERATOR_MODE, + NUMBER_MODE + ]; + + const MODULE_ACCESS_CONTENTS = [ + hljs.QUOTE_STRING_MODE, + OPERATOR_MODE, + { + className: 'module', + begin: "\\b" + RE_MODULE_IDENT, + returnBegin: true, + end: "\.", + contains: [ + { + className: 'identifier', + begin: RE_MODULE_IDENT, + relevance: 0 + } + ] + } + ]; + + const PARAMS_CONTENTS = [ + { + className: 'module', + begin: "\\b" + RE_MODULE_IDENT, + returnBegin: true, + end: "\.", + relevance: 0, + contains: [ + { + className: 'identifier', + begin: RE_MODULE_IDENT, + relevance: 0 + } + ] + } + ]; + + const PARAMS_MODE = { + begin: RE_IDENT, + end: '(,|\\n|\\))', + relevance: 0, + contains: [ + OPERATOR_MODE, + { + className: 'typing', + begin: ':', + end: '(,|\\n)', + returnBegin: true, + relevance: 0, + contains: PARAMS_CONTENTS + } + ] + }; + + const FUNCTION_BLOCK_MODE = { + className: 'function', + relevance: 0, + keywords: KEYWORDS, + variants: [ + { + begin: '\\s(\\(\\.?.*?\\)|' + RE_IDENT + ')\\s*=>', + end: '\\s*=>', + returnBegin: true, + relevance: 0, + contains: [ + { + className: 'params', + variants: [ + { + begin: RE_IDENT + }, + { + begin: RE_PARAM + }, + { + begin: /\(\s*\)/ + } + ] + } + ] + }, + { + begin: '\\s\\(\\.?[^;\\|]*\\)\\s*=>', + end: '\\s=>', + returnBegin: true, + relevance: 0, + contains: [ + { + className: 'params', + relevance: 0, + variants: [ PARAMS_MODE ] + } + ] + }, + { + begin: '\\(\\.\\s' + RE_IDENT + '\\)\\s*=>' + } + ] + }; + MODULE_ACCESS_CONTENTS.push(FUNCTION_BLOCK_MODE); + + const CONSTRUCTOR_MODE = { + className: 'constructor', + begin: RE_MODULE_IDENT + '\\(', + end: '\\)', + illegal: '\\n', + keywords: KEYWORDS, + contains: [ + hljs.QUOTE_STRING_MODE, + OPERATOR_MODE, + { + className: 'params', + begin: '\\b' + RE_IDENT + } + ] + }; + + const PATTERN_MATCH_BLOCK_MODE = { + className: 'pattern-match', + begin: '\\|', + returnBegin: true, + keywords: KEYWORDS, + end: '=>', + relevance: 0, + contains: [ + CONSTRUCTOR_MODE, + OPERATOR_MODE, + { + relevance: 0, + className: 'constructor', + begin: RE_MODULE_IDENT + } + ] + }; + + const MODULE_ACCESS_MODE = { + className: 'module-access', + keywords: KEYWORDS, + returnBegin: true, + variants: [ + { + begin: "\\b(" + RE_MODULE_IDENT + "\\.)+" + RE_IDENT + }, + { + begin: "\\b(" + RE_MODULE_IDENT + "\\.)+\\(", + end: "\\)", + returnBegin: true, + contains: [ + FUNCTION_BLOCK_MODE, + { + begin: '\\(', + end: '\\)', + skip: true + } + ].concat(MODULE_ACCESS_CONTENTS) + }, + { + begin: "\\b(" + RE_MODULE_IDENT + "\\.)+\\{", + end: /\}/ + } + ], + contains: MODULE_ACCESS_CONTENTS + }; + + PARAMS_CONTENTS.push(MODULE_ACCESS_MODE); + + return { + name: 'ReasonML', + aliases: [ 're' ], + keywords: KEYWORDS, + illegal: '(:-|:=|\\$\\{|\\+=)', + contains: [ + hljs.COMMENT('/\\*', '\\*/', { + illegal: '^(#,\\/\\/)' + }), + { + className: 'character', + begin: '\'(\\\\[^\']+|[^\'])\'', + illegal: '\\n', + relevance: 0 + }, + hljs.QUOTE_STRING_MODE, + { + className: 'literal', + begin: '\\(\\)', + relevance: 0 + }, + { + className: 'literal', + begin: '\\[\\|', + end: '\\|\\]', + relevance: 0, + contains: LIST_CONTENTS_MODES + }, + { + className: 'literal', + begin: '\\[', + end: '\\]', + relevance: 0, + contains: LIST_CONTENTS_MODES + }, + CONSTRUCTOR_MODE, + { + className: 'operator', + begin: RE_OPERATOR_SPACED, + illegal: '-->', + relevance: 0 + }, + NUMBER_MODE, + hljs.C_LINE_COMMENT_MODE, + PATTERN_MATCH_BLOCK_MODE, + FUNCTION_BLOCK_MODE, + { + className: 'module-def', + begin: "\\bmodule\\s+" + RE_IDENT + "\\s+" + RE_MODULE_IDENT + "\\s+=\\s+\\{", + end: /\}/, + returnBegin: true, + keywords: KEYWORDS, + relevance: 0, + contains: [ + { + className: 'module', + relevance: 0, + begin: RE_MODULE_IDENT + }, + { + begin: /\{/, + end: /\}/, + skip: true + } + ].concat(MODULE_ACCESS_CONTENTS) + }, + MODULE_ACCESS_MODE + ] + }; +} + +module.exports = reasonml; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/rib.js b/claude-code-source/node_modules/highlight.js/lib/languages/rib.js new file mode 100644 index 00000000..f1d0f4a4 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/rib.js @@ -0,0 +1,37 @@ +/* +Language: RenderMan RIB +Author: Konstantin Evdokimenko +Contributors: Shuen-Huei Guan +Website: https://renderman.pixar.com/resources/RenderMan_20/ribBinding.html +Category: graphics +*/ + +function rib(hljs) { + return { + name: 'RenderMan RIB', + keywords: + 'ArchiveRecord AreaLightSource Atmosphere Attribute AttributeBegin AttributeEnd Basis ' + + 'Begin Blobby Bound Clipping ClippingPlane Color ColorSamples ConcatTransform Cone ' + + 'CoordinateSystem CoordSysTransform CropWindow Curves Cylinder DepthOfField Detail ' + + 'DetailRange Disk Displacement Display End ErrorHandler Exposure Exterior Format ' + + 'FrameAspectRatio FrameBegin FrameEnd GeneralPolygon GeometricApproximation Geometry ' + + 'Hider Hyperboloid Identity Illuminate Imager Interior LightSource ' + + 'MakeCubeFaceEnvironment MakeLatLongEnvironment MakeShadow MakeTexture Matte ' + + 'MotionBegin MotionEnd NuPatch ObjectBegin ObjectEnd ObjectInstance Opacity Option ' + + 'Orientation Paraboloid Patch PatchMesh Perspective PixelFilter PixelSamples ' + + 'PixelVariance Points PointsGeneralPolygons PointsPolygons Polygon Procedural Projection ' + + 'Quantize ReadArchive RelativeDetail ReverseOrientation Rotate Scale ScreenWindow ' + + 'ShadingInterpolation ShadingRate Shutter Sides Skew SolidBegin SolidEnd Sphere ' + + 'SubdivisionMesh Surface TextureCoordinates Torus Transform TransformBegin TransformEnd ' + + 'TransformPoints Translate TrimCurve WorldBegin WorldEnd', + illegal: ' +Description: Syntax highlighting for Roboconf's DSL +Website: http://roboconf.net +Category: config +*/ + +function roboconf(hljs) { + const IDENTIFIER = '[a-zA-Z-_][^\\n{]+\\{'; + + const PROPERTY = { + className: 'attribute', + begin: /[a-zA-Z-_]+/, + end: /\s*:/, + excludeEnd: true, + starts: { + end: ';', + relevance: 0, + contains: [ + { + className: 'variable', + begin: /\.[a-zA-Z-_]+/ + }, + { + className: 'keyword', + begin: /\(optional\)/ + } + ] + } + }; + + return { + name: 'Roboconf', + aliases: [ + 'graph', + 'instances' + ], + case_insensitive: true, + keywords: 'import', + contains: [ + // Facet sections + { + begin: '^facet ' + IDENTIFIER, + end: /\}/, + keywords: 'facet', + contains: [ + PROPERTY, + hljs.HASH_COMMENT_MODE + ] + }, + + // Instance sections + { + begin: '^\\s*instance of ' + IDENTIFIER, + end: /\}/, + keywords: 'name count channels instance-data instance-state instance of', + illegal: /\S/, + contains: [ + 'self', + PROPERTY, + hljs.HASH_COMMENT_MODE + ] + }, + + // Component sections + { + begin: '^' + IDENTIFIER, + end: /\}/, + contains: [ + PROPERTY, + hljs.HASH_COMMENT_MODE + ] + }, + + // Comments + hljs.HASH_COMMENT_MODE + ] + }; +} + +module.exports = roboconf; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/routeros.js b/claude-code-source/node_modules/highlight.js/lib/languages/routeros.js new file mode 100644 index 00000000..f4a8d498 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/routeros.js @@ -0,0 +1,172 @@ +/* +Language: Microtik RouterOS script +Author: Ivan Dementev +Description: Scripting host provides a way to automate some router maintenance tasks by means of executing user-defined scripts bounded to some event occurrence +Website: https://wiki.mikrotik.com/wiki/Manual:Scripting +*/ + +// Colors from RouterOS terminal: +// green - #0E9A00 +// teal - #0C9A9A +// purple - #99069A +// light-brown - #9A9900 + +function routeros(hljs) { + const STATEMENTS = 'foreach do while for if from to step else on-error and or not in'; + + // Global commands: Every global command should start with ":" token, otherwise it will be treated as variable. + const GLOBAL_COMMANDS = 'global local beep delay put len typeof pick log time set find environment terminal error execute parse resolve toarray tobool toid toip toip6 tonum tostr totime'; + + // Common commands: Following commands available from most sub-menus: + const COMMON_COMMANDS = 'add remove enable disable set get print export edit find run debug error info warning'; + + const LITERALS = 'true false yes no nothing nil null'; + + const OBJECTS = 'traffic-flow traffic-generator firewall scheduler aaa accounting address-list address align area bandwidth-server bfd bgp bridge client clock community config connection console customer default dhcp-client dhcp-server discovery dns e-mail ethernet filter firmware gps graphing group hardware health hotspot identity igmp-proxy incoming instance interface ip ipsec ipv6 irq l2tp-server lcd ldp logging mac-server mac-winbox mangle manual mirror mme mpls nat nd neighbor network note ntp ospf ospf-v3 ovpn-server page peer pim ping policy pool port ppp pppoe-client pptp-server prefix profile proposal proxy queue radius resource rip ripng route routing screen script security-profiles server service service-port settings shares smb sms sniffer snmp snooper socks sstp-server system tool tracking type upgrade upnp user-manager users user vlan secret vrrp watchdog web-access wireless pptp pppoe lan wan layer7-protocol lease simple raw'; + + const VAR = { + className: 'variable', + variants: [ + { + begin: /\$[\w\d#@][\w\d_]*/ + }, + { + begin: /\$\{(.*?)\}/ + } + ] + }; + + const QUOTE_STRING = { + className: 'string', + begin: /"/, + end: /"/, + contains: [ + hljs.BACKSLASH_ESCAPE, + VAR, + { + className: 'variable', + begin: /\$\(/, + end: /\)/, + contains: [ hljs.BACKSLASH_ESCAPE ] + } + ] + }; + + const APOS_STRING = { + className: 'string', + begin: /'/, + end: /'/ + }; + + return { + name: 'Microtik RouterOS script', + aliases: [ + 'mikrotik' + ], + case_insensitive: true, + keywords: { + $pattern: /:?[\w-]+/, + literal: LITERALS, + keyword: STATEMENTS + ' :' + STATEMENTS.split(' ').join(' :') + ' :' + GLOBAL_COMMANDS.split(' ').join(' :') + }, + contains: [ + { // illegal syntax + variants: [ + { // -- comment + begin: /\/\*/, + end: /\*\// + }, + { // Stan comment + begin: /\/\//, + end: /$/ + }, + { // HTML tags + begin: /<\//, + end: />/ + } + ], + illegal: /./ + }, + hljs.COMMENT('^#', '$'), + QUOTE_STRING, + APOS_STRING, + VAR, + // attribute=value + { + // > is to avoid matches with => in other grammars + begin: /[\w-]+=([^\s{}[\]()>]+)/, + relevance: 0, + returnBegin: true, + contains: [ + { + className: 'attribute', + begin: /[^=]+/ + }, + { + begin: /=/, + endsWithParent: true, + relevance: 0, + contains: [ + QUOTE_STRING, + APOS_STRING, + VAR, + { + className: 'literal', + begin: '\\b(' + LITERALS.split(' ').join('|') + ')\\b' + }, + { + // Do not format unclassified values. Needed to exclude highlighting of values as built_in. + begin: /("[^"]*"|[^\s{}[\]]+)/ + } + /* + { + // IPv4 addresses and subnets + className: 'number', + variants: [ + {begin: IPADDR_wBITMASK+'(,'+IPADDR_wBITMASK+')*'}, //192.168.0.0/24,1.2.3.0/24 + {begin: IPADDR+'-'+IPADDR}, // 192.168.0.1-192.168.0.3 + {begin: IPADDR+'(,'+IPADDR+')*'}, // 192.168.0.1,192.168.0.34,192.168.24.1,192.168.0.1 + ] + }, + { + // MAC addresses and DHCP Client IDs + className: 'number', + begin: /\b(1:)?([0-9A-Fa-f]{1,2}[:-]){5}([0-9A-Fa-f]){1,2}\b/, + }, + */ + ] + } + ] + }, + { + // HEX values + className: 'number', + begin: /\*[0-9a-fA-F]+/ + }, + { + begin: '\\b(' + COMMON_COMMANDS.split(' ').join('|') + ')([\\s[(\\]|])', + returnBegin: true, + contains: [ + { + className: 'builtin-name', // 'function', + begin: /\w+/ + } + ] + }, + { + className: 'built_in', + variants: [ + { + begin: '(\\.\\./|/|\\s)((' + OBJECTS.split(' ').join('|') + ');?\\s)+' + }, + { + begin: /\.\./, + relevance: 0 + } + ] + } + ] + }; +} + +module.exports = routeros; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/rsl.js b/claude-code-source/node_modules/highlight.js/lib/languages/rsl.js new file mode 100644 index 00000000..2e1983c6 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/rsl.js @@ -0,0 +1,49 @@ +/* +Language: RenderMan RSL +Author: Konstantin Evdokimenko +Contributors: Shuen-Huei Guan +Website: https://renderman.pixar.com/resources/RenderMan_20/shadingLanguage.html +Category: graphics +*/ + +function rsl(hljs) { + return { + name: 'RenderMan RSL', + keywords: { + keyword: + 'float color point normal vector matrix while for if do return else break extern continue', + built_in: + 'abs acos ambient area asin atan atmosphere attribute calculatenormal ceil cellnoise ' + + 'clamp comp concat cos degrees depth Deriv diffuse distance Du Dv environment exp ' + + 'faceforward filterstep floor format fresnel incident length lightsource log match ' + + 'max min mod noise normalize ntransform opposite option phong pnoise pow printf ' + + 'ptlined radians random reflect refract renderinfo round setcomp setxcomp setycomp ' + + 'setzcomp shadow sign sin smoothstep specular specularbrdf spline sqrt step tan ' + + 'texture textureinfo trace transform vtransform xcomp ycomp zcomp' + }, + illegal: ' source(x)).join(""); + return joined; +} + +/* +Language: Ruby +Description: Ruby is a dynamic, open source programming language with a focus on simplicity and productivity. +Website: https://www.ruby-lang.org/ +Author: Anton Kovalyov +Contributors: Peter Leonov , Vasily Polovnyov , Loren Segal , Pascal Hurni , Cedric Sohrauer +Category: common +*/ + +function ruby(hljs) { + const RUBY_METHOD_RE = '([a-zA-Z_]\\w*[!?=]?|[-+~]@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?)'; + const RUBY_KEYWORDS = { + keyword: + 'and then defined module in return redo if BEGIN retry end for self when ' + + 'next until do begin unless END rescue else break undef not super class case ' + + 'require yield alias while ensure elsif or include attr_reader attr_writer attr_accessor ' + + '__FILE__', + built_in: 'proc lambda', + literal: + 'true false nil' + }; + const YARDOCTAG = { + className: 'doctag', + begin: '@[A-Za-z]+' + }; + const IRB_OBJECT = { + begin: '#<', + end: '>' + }; + const COMMENT_MODES = [ + hljs.COMMENT( + '#', + '$', + { + contains: [ YARDOCTAG ] + } + ), + hljs.COMMENT( + '^=begin', + '^=end', + { + contains: [ YARDOCTAG ], + relevance: 10 + } + ), + hljs.COMMENT('^__END__', '\\n$') + ]; + const SUBST = { + className: 'subst', + begin: /#\{/, + end: /\}/, + keywords: RUBY_KEYWORDS + }; + const STRING = { + className: 'string', + contains: [ + hljs.BACKSLASH_ESCAPE, + SUBST + ], + variants: [ + { + begin: /'/, + end: /'/ + }, + { + begin: /"/, + end: /"/ + }, + { + begin: /`/, + end: /`/ + }, + { + begin: /%[qQwWx]?\(/, + end: /\)/ + }, + { + begin: /%[qQwWx]?\[/, + end: /\]/ + }, + { + begin: /%[qQwWx]?\{/, + end: /\}/ + }, + { + begin: /%[qQwWx]?/ + }, + { + begin: /%[qQwWx]?\//, + end: /\// + }, + { + begin: /%[qQwWx]?%/, + end: /%/ + }, + { + begin: /%[qQwWx]?-/, + end: /-/ + }, + { + begin: /%[qQwWx]?\|/, + end: /\|/ + }, + // in the following expressions, \B in the beginning suppresses recognition of ?-sequences + // where ? is the last character of a preceding identifier, as in: `func?4` + { + begin: /\B\?(\\\d{1,3})/ + }, + { + begin: /\B\?(\\x[A-Fa-f0-9]{1,2})/ + }, + { + begin: /\B\?(\\u\{?[A-Fa-f0-9]{1,6}\}?)/ + }, + { + begin: /\B\?(\\M-\\C-|\\M-\\c|\\c\\M-|\\M-|\\C-\\M-)[\x20-\x7e]/ + }, + { + begin: /\B\?\\(c|C-)[\x20-\x7e]/ + }, + { + begin: /\B\?\\?\S/ + }, + { // heredocs + begin: /<<[-~]?'?(\w+)\n(?:[^\n]*\n)*?\s*\1\b/, + returnBegin: true, + contains: [ + { + begin: /<<[-~]?'?/ + }, + hljs.END_SAME_AS_BEGIN({ + begin: /(\w+)/, + end: /(\w+)/, + contains: [ + hljs.BACKSLASH_ESCAPE, + SUBST + ] + }) + ] + } + ] + }; + + // Ruby syntax is underdocumented, but this grammar seems to be accurate + // as of version 2.7.2 (confirmed with (irb and `Ripper.sexp(...)`) + // https://docs.ruby-lang.org/en/2.7.0/doc/syntax/literals_rdoc.html#label-Numbers + const decimal = '[1-9](_?[0-9])*|0'; + const digits = '[0-9](_?[0-9])*'; + const NUMBER = { + className: 'number', + relevance: 0, + variants: [ + // decimal integer/float, optionally exponential or rational, optionally imaginary + { + begin: `\\b(${decimal})(\\.(${digits}))?([eE][+-]?(${digits})|r)?i?\\b` + }, + + // explicit decimal/binary/octal/hexadecimal integer, + // optionally rational and/or imaginary + { + begin: "\\b0[dD][0-9](_?[0-9])*r?i?\\b" + }, + { + begin: "\\b0[bB][0-1](_?[0-1])*r?i?\\b" + }, + { + begin: "\\b0[oO][0-7](_?[0-7])*r?i?\\b" + }, + { + begin: "\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*r?i?\\b" + }, + + // 0-prefixed implicit octal integer, optionally rational and/or imaginary + { + begin: "\\b0(_?[0-7])+r?i?\\b" + } + ] + }; + + const PARAMS = { + className: 'params', + begin: '\\(', + end: '\\)', + endsParent: true, + keywords: RUBY_KEYWORDS + }; + + const RUBY_DEFAULT_CONTAINS = [ + STRING, + { + className: 'class', + beginKeywords: 'class module', + end: '$|;', + illegal: /=/, + contains: [ + hljs.inherit(hljs.TITLE_MODE, { + begin: '[A-Za-z_]\\w*(::\\w+)*(\\?|!)?' + }), + { + begin: '<\\s*', + contains: [ + { + begin: '(' + hljs.IDENT_RE + '::)?' + hljs.IDENT_RE, + // we already get points for <, we don't need poitns + // for the name also + relevance: 0 + } + ] + } + ].concat(COMMENT_MODES) + }, + { + className: 'function', + // def method_name( + // def method_name; + // def method_name (end of line) + begin: concat(/def\s+/, lookahead(RUBY_METHOD_RE + "\\s*(\\(|;|$)")), + relevance: 0, // relevance comes from kewords + keywords: "def", + end: '$|;', + contains: [ + hljs.inherit(hljs.TITLE_MODE, { + begin: RUBY_METHOD_RE + }), + PARAMS + ].concat(COMMENT_MODES) + }, + { + // swallow namespace qualifiers before symbols + begin: hljs.IDENT_RE + '::' + }, + { + className: 'symbol', + begin: hljs.UNDERSCORE_IDENT_RE + '(!|\\?)?:', + relevance: 0 + }, + { + className: 'symbol', + begin: ':(?!\\s)', + contains: [ + STRING, + { + begin: RUBY_METHOD_RE + } + ], + relevance: 0 + }, + NUMBER, + { + // negative-look forward attemps to prevent false matches like: + // @ident@ or $ident$ that might indicate this is not ruby at all + className: "variable", + begin: '(\\$\\W)|((\\$|@@?)(\\w+))(?=[^@$?])' + `(?![A-Za-z])(?![@$?'])` + }, + { + className: 'params', + begin: /\|/, + end: /\|/, + relevance: 0, // this could be a lot of things (in other languages) other than params + keywords: RUBY_KEYWORDS + }, + { // regexp container + begin: '(' + hljs.RE_STARTERS_RE + '|unless)\\s*', + keywords: 'unless', + contains: [ + { + className: 'regexp', + contains: [ + hljs.BACKSLASH_ESCAPE, + SUBST + ], + illegal: /\n/, + variants: [ + { + begin: '/', + end: '/[a-z]*' + }, + { + begin: /%r\{/, + end: /\}[a-z]*/ + }, + { + begin: '%r\\(', + end: '\\)[a-z]*' + }, + { + begin: '%r!', + end: '![a-z]*' + }, + { + begin: '%r\\[', + end: '\\][a-z]*' + } + ] + } + ].concat(IRB_OBJECT, COMMENT_MODES), + relevance: 0 + } + ].concat(IRB_OBJECT, COMMENT_MODES); + + SUBST.contains = RUBY_DEFAULT_CONTAINS; + PARAMS.contains = RUBY_DEFAULT_CONTAINS; + + // >> + // ?> + const SIMPLE_PROMPT = "[>?]>"; + // irb(main):001:0> + const DEFAULT_PROMPT = "[\\w#]+\\(\\w+\\):\\d+:\\d+>"; + const RVM_PROMPT = "(\\w+-)?\\d+\\.\\d+\\.\\d+(p\\d+)?[^\\d][^>]+>"; + + const IRB_DEFAULT = [ + { + begin: /^\s*=>/, + starts: { + end: '$', + contains: RUBY_DEFAULT_CONTAINS + } + }, + { + className: 'meta', + begin: '^(' + SIMPLE_PROMPT + "|" + DEFAULT_PROMPT + '|' + RVM_PROMPT + ')(?=[ ])', + starts: { + end: '$', + contains: RUBY_DEFAULT_CONTAINS + } + } + ]; + + COMMENT_MODES.unshift(IRB_OBJECT); + + return { + name: 'Ruby', + aliases: [ + 'rb', + 'gemspec', + 'podspec', + 'thor', + 'irb' + ], + keywords: RUBY_KEYWORDS, + illegal: /\/\*/, + contains: [ + hljs.SHEBANG({ + binary: "ruby" + }) + ] + .concat(IRB_DEFAULT) + .concat(COMMENT_MODES) + .concat(RUBY_DEFAULT_CONTAINS) + }; +} + +module.exports = ruby; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/ruleslanguage.js b/claude-code-source/node_modules/highlight.js/lib/languages/ruleslanguage.js new file mode 100644 index 00000000..f9503eaa --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/ruleslanguage.js @@ -0,0 +1,78 @@ +/* +Language: Oracle Rules Language +Author: Jason Jacobson +Description: The Oracle Utilities Rules Language is used to program the Oracle Utilities Applications acquired from LODESTAR Corporation. The products include Billing Component, LPSS, Pricing Component etc. through version 1.6.1. +Website: https://docs.oracle.com/cd/E17904_01/dev.1111/e10227/rlref.htm +Category: enterprise +*/ + +function ruleslanguage(hljs) { + return { + name: 'Oracle Rules Language', + keywords: { + keyword: + 'BILL_PERIOD BILL_START BILL_STOP RS_EFFECTIVE_START RS_EFFECTIVE_STOP RS_JURIS_CODE RS_OPCO_CODE ' + + 'INTDADDATTRIBUTE|5 INTDADDVMSG|5 INTDBLOCKOP|5 INTDBLOCKOPNA|5 INTDCLOSE|5 INTDCOUNT|5 ' + + 'INTDCOUNTSTATUSCODE|5 INTDCREATEMASK|5 INTDCREATEDAYMASK|5 INTDCREATEFACTORMASK|5 ' + + 'INTDCREATEHANDLE|5 INTDCREATEOVERRIDEDAYMASK|5 INTDCREATEOVERRIDEMASK|5 ' + + 'INTDCREATESTATUSCODEMASK|5 INTDCREATETOUPERIOD|5 INTDDELETE|5 INTDDIPTEST|5 INTDEXPORT|5 ' + + 'INTDGETERRORCODE|5 INTDGETERRORMESSAGE|5 INTDISEQUAL|5 INTDJOIN|5 INTDLOAD|5 INTDLOADACTUALCUT|5 ' + + 'INTDLOADDATES|5 INTDLOADHIST|5 INTDLOADLIST|5 INTDLOADLISTDATES|5 INTDLOADLISTENERGY|5 ' + + 'INTDLOADLISTHIST|5 INTDLOADRELATEDCHANNEL|5 INTDLOADSP|5 INTDLOADSTAGING|5 INTDLOADUOM|5 ' + + 'INTDLOADUOMDATES|5 INTDLOADUOMHIST|5 INTDLOADVERSION|5 INTDOPEN|5 INTDREADFIRST|5 INTDREADNEXT|5 ' + + 'INTDRECCOUNT|5 INTDRELEASE|5 INTDREPLACE|5 INTDROLLAVG|5 INTDROLLPEAK|5 INTDSCALAROP|5 INTDSCALE|5 ' + + 'INTDSETATTRIBUTE|5 INTDSETDSTPARTICIPANT|5 INTDSETSTRING|5 INTDSETVALUE|5 INTDSETVALUESTATUS|5 ' + + 'INTDSHIFTSTARTTIME|5 INTDSMOOTH|5 INTDSORT|5 INTDSPIKETEST|5 INTDSUBSET|5 INTDTOU|5 ' + + 'INTDTOURELEASE|5 INTDTOUVALUE|5 INTDUPDATESTATS|5 INTDVALUE|5 STDEV INTDDELETEEX|5 ' + + 'INTDLOADEXACTUAL|5 INTDLOADEXCUT|5 INTDLOADEXDATES|5 INTDLOADEX|5 INTDLOADEXRELATEDCHANNEL|5 ' + + 'INTDSAVEEX|5 MVLOAD|5 MVLOADACCT|5 MVLOADACCTDATES|5 MVLOADACCTHIST|5 MVLOADDATES|5 MVLOADHIST|5 ' + + 'MVLOADLIST|5 MVLOADLISTDATES|5 MVLOADLISTHIST|5 IF FOR NEXT DONE SELECT END CALL ABORT CLEAR CHANNEL FACTOR LIST NUMBER ' + + 'OVERRIDE SET WEEK DISTRIBUTIONNODE ELSE WHEN THEN OTHERWISE IENUM CSV INCLUDE LEAVE RIDER SAVE DELETE ' + + 'NOVALUE SECTION WARN SAVE_UPDATE DETERMINANT LABEL REPORT REVENUE EACH ' + + 'IN FROM TOTAL CHARGE BLOCK AND OR CSV_FILE RATE_CODE AUXILIARY_DEMAND ' + + 'UIDACCOUNT RS BILL_PERIOD_SELECT HOURS_PER_MONTH INTD_ERROR_STOP SEASON_SCHEDULE_NAME ' + + 'ACCOUNTFACTOR ARRAYUPPERBOUND CALLSTOREDPROC GETADOCONNECTION GETCONNECT GETDATASOURCE ' + + 'GETQUALIFIER GETUSERID HASVALUE LISTCOUNT LISTOP LISTUPDATE LISTVALUE PRORATEFACTOR RSPRORATE ' + + 'SETBINPATH SETDBMONITOR WQ_OPEN BILLINGHOURS DATE DATEFROMFLOAT DATETIMEFROMSTRING ' + + 'DATETIMETOSTRING DATETOFLOAT DAY DAYDIFF DAYNAME DBDATETIME HOUR MINUTE MONTH MONTHDIFF ' + + 'MONTHHOURS MONTHNAME ROUNDDATE SAMEWEEKDAYLASTYEAR SECOND WEEKDAY WEEKDIFF YEAR YEARDAY ' + + 'YEARSTR COMPSUM HISTCOUNT HISTMAX HISTMIN HISTMINNZ HISTVALUE MAXNRANGE MAXRANGE MINRANGE ' + + 'COMPIKVA COMPKVA COMPKVARFROMKQKW COMPLF IDATTR FLAG LF2KW LF2KWH MAXKW POWERFACTOR ' + + 'READING2USAGE AVGSEASON MAXSEASON MONTHLYMERGE SEASONVALUE SUMSEASON ACCTREADDATES ' + + 'ACCTTABLELOAD CONFIGADD CONFIGGET CREATEOBJECT CREATEREPORT EMAILCLIENT EXPBLKMDMUSAGE ' + + 'EXPMDMUSAGE EXPORT_USAGE FACTORINEFFECT GETUSERSPECIFIEDSTOP INEFFECT ISHOLIDAY RUNRATE ' + + 'SAVE_PROFILE SETREPORTTITLE USEREXIT WATFORRUNRATE TO TABLE ACOS ASIN ATAN ATAN2 BITAND CEIL ' + + 'COS COSECANT COSH COTANGENT DIVQUOT DIVREM EXP FABS FLOOR FMOD FREPM FREXPN LOG LOG10 MAX MAXN ' + + 'MIN MINNZ MODF POW ROUND ROUND2VALUE ROUNDINT SECANT SIN SINH SQROOT TAN TANH FLOAT2STRING ' + + 'FLOAT2STRINGNC INSTR LEFT LEN LTRIM MID RIGHT RTRIM STRING STRINGNC TOLOWER TOUPPER TRIM ' + + 'NUMDAYS READ_DATE STAGING', + built_in: + 'IDENTIFIER OPTIONS XML_ELEMENT XML_OP XML_ELEMENT_OF DOMDOCCREATE DOMDOCLOADFILE DOMDOCLOADXML ' + + 'DOMDOCSAVEFILE DOMDOCGETROOT DOMDOCADDPI DOMNODEGETNAME DOMNODEGETTYPE DOMNODEGETVALUE DOMNODEGETCHILDCT ' + + 'DOMNODEGETFIRSTCHILD DOMNODEGETSIBLING DOMNODECREATECHILDELEMENT DOMNODESETATTRIBUTE ' + + 'DOMNODEGETCHILDELEMENTCT DOMNODEGETFIRSTCHILDELEMENT DOMNODEGETSIBLINGELEMENT DOMNODEGETATTRIBUTECT ' + + 'DOMNODEGETATTRIBUTEI DOMNODEGETATTRIBUTEBYNAME DOMNODEGETBYNAME' + }, + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + hljs.C_NUMBER_MODE, + { + className: 'literal', + variants: [ + { // looks like #-comment + begin: '#\\s+', + relevance: 0 + }, + { + begin: '#[a-zA-Z .]+' + } + ] + } + ] + }; +} + +module.exports = ruleslanguage; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/rust.js b/claude-code-source/node_modules/highlight.js/lib/languages/rust.js new file mode 100644 index 00000000..afb2c7e0 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/rust.js @@ -0,0 +1,146 @@ +/* +Language: Rust +Author: Andrey Vlasovskikh +Contributors: Roman Shmatov , Kasper Andersen +Website: https://www.rust-lang.org +Category: common, system +*/ + +function rust(hljs) { + const NUM_SUFFIX = '([ui](8|16|32|64|128|size)|f(32|64))\?'; + const KEYWORDS = + 'abstract as async await become box break const continue crate do dyn ' + + 'else enum extern false final fn for if impl in let loop macro match mod ' + + 'move mut override priv pub ref return self Self static struct super ' + + 'trait true try type typeof unsafe unsized use virtual where while yield'; + const BUILTINS = + // functions + 'drop ' + + // types + 'i8 i16 i32 i64 i128 isize ' + + 'u8 u16 u32 u64 u128 usize ' + + 'f32 f64 ' + + 'str char bool ' + + 'Box Option Result String Vec ' + + // traits + 'Copy Send Sized Sync Drop Fn FnMut FnOnce ToOwned Clone Debug ' + + 'PartialEq PartialOrd Eq Ord AsRef AsMut Into From Default Iterator ' + + 'Extend IntoIterator DoubleEndedIterator ExactSizeIterator ' + + 'SliceConcatExt ToString ' + + // macros + 'assert! assert_eq! bitflags! bytes! cfg! col! concat! concat_idents! ' + + 'debug_assert! debug_assert_eq! env! panic! file! format! format_args! ' + + 'include_bin! include_str! line! local_data_key! module_path! ' + + 'option_env! print! println! select! stringify! try! unimplemented! ' + + 'unreachable! vec! write! writeln! macro_rules! assert_ne! debug_assert_ne!'; + return { + name: 'Rust', + aliases: [ 'rs' ], + keywords: { + $pattern: hljs.IDENT_RE + '!?', + keyword: + KEYWORDS, + literal: + 'true false Some None Ok Err', + built_in: + BUILTINS + }, + illegal: '' + } + ] + }; +} + +module.exports = rust; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/sas.js b/claude-code-source/node_modules/highlight.js/lib/languages/sas.js new file mode 100644 index 00000000..1e54ae71 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/sas.js @@ -0,0 +1,133 @@ +/* +Language: SAS +Author: Mauricio Caceres +Description: Syntax Highlighting for SAS +*/ + +function sas(hljs) { + // Data step and PROC SQL statements + const SAS_KEYWORDS = + 'do if then else end until while ' + + '' + + 'abort array attrib by call cards cards4 catname continue ' + + 'datalines datalines4 delete delim delimiter display dm drop ' + + 'endsas error file filename footnote format goto in infile ' + + 'informat input keep label leave length libname link list ' + + 'lostcard merge missing modify options output out page put ' + + 'redirect remove rename replace retain return select set skip ' + + 'startsas stop title update waitsas where window x systask ' + + '' + + 'add and alter as cascade check create delete describe ' + + 'distinct drop foreign from group having index insert into in ' + + 'key like message modify msgtype not null on or order primary ' + + 'references reset restrict select set table unique update ' + + 'validate view where'; + + // Built-in SAS functions + const SAS_FUN = + 'abs|addr|airy|arcos|arsin|atan|attrc|attrn|band|' + + 'betainv|blshift|bnot|bor|brshift|bxor|byte|cdf|ceil|' + + 'cexist|cinv|close|cnonct|collate|compbl|compound|' + + 'compress|cos|cosh|css|curobs|cv|daccdb|daccdbsl|' + + 'daccsl|daccsyd|dacctab|dairy|date|datejul|datepart|' + + 'datetime|day|dclose|depdb|depdbsl|depdbsl|depsl|' + + 'depsl|depsyd|depsyd|deptab|deptab|dequote|dhms|dif|' + + 'digamma|dim|dinfo|dnum|dopen|doptname|doptnum|dread|' + + 'dropnote|dsname|erf|erfc|exist|exp|fappend|fclose|' + + 'fcol|fdelete|fetch|fetchobs|fexist|fget|fileexist|' + + 'filename|fileref|finfo|finv|fipname|fipnamel|' + + 'fipstate|floor|fnonct|fnote|fopen|foptname|foptnum|' + + 'fpoint|fpos|fput|fread|frewind|frlen|fsep|fuzz|' + + 'fwrite|gaminv|gamma|getoption|getvarc|getvarn|hbound|' + + 'hms|hosthelp|hour|ibessel|index|indexc|indexw|input|' + + 'inputc|inputn|int|intck|intnx|intrr|irr|jbessel|' + + 'juldate|kurtosis|lag|lbound|left|length|lgamma|' + + 'libname|libref|log|log10|log2|logpdf|logpmf|logsdf|' + + 'lowcase|max|mdy|mean|min|minute|mod|month|mopen|' + + 'mort|n|netpv|nmiss|normal|note|npv|open|ordinal|' + + 'pathname|pdf|peek|peekc|pmf|point|poisson|poke|' + + 'probbeta|probbnml|probchi|probf|probgam|probhypr|' + + 'probit|probnegb|probnorm|probt|put|putc|putn|qtr|' + + 'quote|ranbin|rancau|ranexp|rangam|range|rank|rannor|' + + 'ranpoi|rantbl|rantri|ranuni|repeat|resolve|reverse|' + + 'rewind|right|round|saving|scan|sdf|second|sign|' + + 'sin|sinh|skewness|soundex|spedis|sqrt|std|stderr|' + + 'stfips|stname|stnamel|substr|sum|symget|sysget|' + + 'sysmsg|sysprod|sysrc|system|tan|tanh|time|timepart|' + + 'tinv|tnonct|today|translate|tranwrd|trigamma|' + + 'trim|trimn|trunc|uniform|upcase|uss|var|varfmt|' + + 'varinfmt|varlabel|varlen|varname|varnum|varray|' + + 'varrayx|vartype|verify|vformat|vformatd|vformatdx|' + + 'vformatn|vformatnx|vformatw|vformatwx|vformatx|' + + 'vinarray|vinarrayx|vinformat|vinformatd|vinformatdx|' + + 'vinformatn|vinformatnx|vinformatw|vinformatwx|' + + 'vinformatx|vlabel|vlabelx|vlength|vlengthx|vname|' + + 'vnamex|vtype|vtypex|weekday|year|yyq|zipfips|zipname|' + + 'zipnamel|zipstate'; + + // Built-in macro functions + const SAS_MACRO_FUN = + 'bquote|nrbquote|cmpres|qcmpres|compstor|' + + 'datatyp|display|do|else|end|eval|global|goto|' + + 'if|index|input|keydef|label|left|length|let|' + + 'local|lowcase|macro|mend|nrbquote|nrquote|' + + 'nrstr|put|qcmpres|qleft|qlowcase|qscan|' + + 'qsubstr|qsysfunc|qtrim|quote|qupcase|scan|str|' + + 'substr|superq|syscall|sysevalf|sysexec|sysfunc|' + + 'sysget|syslput|sysprod|sysrc|sysrput|then|to|' + + 'trim|unquote|until|upcase|verify|while|window'; + + return { + name: 'SAS', + case_insensitive: true, // SAS is case-insensitive + keywords: { + literal: + 'null missing _all_ _automatic_ _character_ _infile_ ' + + '_n_ _name_ _null_ _numeric_ _user_ _webout_', + meta: + SAS_KEYWORDS + }, + contains: [ + { + // Distinct highlight for proc , data, run, quit + className: 'keyword', + begin: /^\s*(proc [\w\d_]+|data|run|quit)[\s;]/ + }, + { + // Macro variables + className: 'variable', + begin: /&[a-zA-Z_&][a-zA-Z0-9_]*\.?/ + }, + { + // Special emphasis for datalines|cards + className: 'emphasis', + begin: /^\s*datalines|cards.*;/, + end: /^\s*;\s*$/ + }, + { // Built-in macro variables take precedence + className: 'built_in', + begin: '%(' + SAS_MACRO_FUN + ')' + }, + { + // User-defined macro functions highlighted after + className: 'name', + begin: /%[a-zA-Z_][a-zA-Z_0-9]*/ + }, + { + className: 'meta', + begin: '[^%](' + SAS_FUN + ')[\(]' + }, + { + className: 'string', + variants: [ + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE + ] + }, + hljs.COMMENT('\\*', ';'), + hljs.C_BLOCK_COMMENT_MODE + ] + }; +} + +module.exports = sas; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/scala.js b/claude-code-source/node_modules/highlight.js/lib/languages/scala.js new file mode 100644 index 00000000..712764a3 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/scala.js @@ -0,0 +1,140 @@ +/* +Language: Scala +Category: functional +Author: Jan Berkel +Contributors: Erik Osheim +Website: https://www.scala-lang.org +*/ + +function scala(hljs) { + const ANNOTATION = { + className: 'meta', + begin: '@[A-Za-z]+' + }; + + // used in strings for escaping/interpolation/substitution + const SUBST = { + className: 'subst', + variants: [ + { + begin: '\\$[A-Za-z0-9_]+' + }, + { + begin: /\$\{/, + end: /\}/ + } + ] + }; + + const STRING = { + className: 'string', + variants: [ + { + begin: '"""', + end: '"""' + }, + { + begin: '"', + end: '"', + illegal: '\\n', + contains: [ hljs.BACKSLASH_ESCAPE ] + }, + { + begin: '[a-z]+"', + end: '"', + illegal: '\\n', + contains: [ + hljs.BACKSLASH_ESCAPE, + SUBST + ] + }, + { + className: 'string', + begin: '[a-z]+"""', + end: '"""', + contains: [ SUBST ], + relevance: 10 + } + ] + + }; + + const SYMBOL = { + className: 'symbol', + begin: '\'\\w[\\w\\d_]*(?!\')' + }; + + const TYPE = { + className: 'type', + begin: '\\b[A-Z][A-Za-z0-9_]*', + relevance: 0 + }; + + const NAME = { + className: 'title', + begin: /[^0-9\n\t "'(),.`{}\[\]:;][^\n\t "'(),.`{}\[\]:;]+|[^0-9\n\t "'(),.`{}\[\]:;=]/, + relevance: 0 + }; + + const CLASS = { + className: 'class', + beginKeywords: 'class object trait type', + end: /[:={\[\n;]/, + excludeEnd: true, + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + { + beginKeywords: 'extends with', + relevance: 10 + }, + { + begin: /\[/, + end: /\]/, + excludeBegin: true, + excludeEnd: true, + relevance: 0, + contains: [ TYPE ] + }, + { + className: 'params', + begin: /\(/, + end: /\)/, + excludeBegin: true, + excludeEnd: true, + relevance: 0, + contains: [ TYPE ] + }, + NAME + ] + }; + + const METHOD = { + className: 'function', + beginKeywords: 'def', + end: /[:={\[(\n;]/, + excludeEnd: true, + contains: [ NAME ] + }; + + return { + name: 'Scala', + keywords: { + literal: 'true false null', + keyword: 'type yield lazy override def with val var sealed abstract private trait object if forSome for while throw finally protected extends import final return else break new catch super class case package default try this match continue throws implicit' + }, + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + STRING, + SYMBOL, + TYPE, + METHOD, + CLASS, + hljs.C_NUMBER_MODE, + ANNOTATION + ] + }; +} + +module.exports = scala; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/scheme.js b/claude-code-source/node_modules/highlight.js/lib/languages/scheme.js new file mode 100644 index 00000000..250d4b31 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/scheme.js @@ -0,0 +1,207 @@ +/* +Language: Scheme +Description: Scheme is a programming language in the Lisp family. + (keywords based on http://community.schemewiki.org/?scheme-keywords) +Author: JP Verkamp +Contributors: Ivan Sagalaev +Origin: clojure.js +Website: http://community.schemewiki.org/?what-is-scheme +Category: lisp +*/ + +function scheme(hljs) { + const SCHEME_IDENT_RE = '[^\\(\\)\\[\\]\\{\\}",\'`;#|\\\\\\s]+'; + const SCHEME_SIMPLE_NUMBER_RE = '(-|\\+)?\\d+([./]\\d+)?'; + const SCHEME_COMPLEX_NUMBER_RE = SCHEME_SIMPLE_NUMBER_RE + '[+\\-]' + SCHEME_SIMPLE_NUMBER_RE + 'i'; + const KEYWORDS = { + $pattern: SCHEME_IDENT_RE, + 'builtin-name': + 'case-lambda call/cc class define-class exit-handler field import ' + + 'inherit init-field interface let*-values let-values let/ec mixin ' + + 'opt-lambda override protect provide public rename require ' + + 'require-for-syntax syntax syntax-case syntax-error unit/sig unless ' + + 'when with-syntax and begin call-with-current-continuation ' + + 'call-with-input-file call-with-output-file case cond define ' + + 'define-syntax delay do dynamic-wind else for-each if lambda let let* ' + + 'let-syntax letrec letrec-syntax map or syntax-rules \' * + , ,@ - ... / ' + + '; < <= = => > >= ` abs acos angle append apply asin assoc assq assv atan ' + + 'boolean? caar cadr call-with-input-file call-with-output-file ' + + 'call-with-values car cdddar cddddr cdr ceiling char->integer ' + + 'char-alphabetic? char-ci<=? char-ci=? char-ci>? ' + + 'char-downcase char-lower-case? char-numeric? char-ready? char-upcase ' + + 'char-upper-case? char-whitespace? char<=? char=? char>? ' + + 'char? close-input-port close-output-port complex? cons cos ' + + 'current-input-port current-output-port denominator display eof-object? ' + + 'eq? equal? eqv? eval even? exact->inexact exact? exp expt floor ' + + 'force gcd imag-part inexact->exact inexact? input-port? integer->char ' + + 'integer? interaction-environment lcm length list list->string ' + + 'list->vector list-ref list-tail list? load log magnitude make-polar ' + + 'make-rectangular make-string make-vector max member memq memv min ' + + 'modulo negative? newline not null-environment null? number->string ' + + 'number? numerator odd? open-input-file open-output-file output-port? ' + + 'pair? peek-char port? positive? procedure? quasiquote quote quotient ' + + 'rational? rationalize read read-char real-part real? remainder reverse ' + + 'round scheme-report-environment set! set-car! set-cdr! sin sqrt string ' + + 'string->list string->number string->symbol string-append string-ci<=? ' + + 'string-ci=? string-ci>? string-copy ' + + 'string-fill! string-length string-ref string-set! string<=? string=? string>? string? substring symbol->string symbol? ' + + 'tan transcript-off transcript-on truncate values vector ' + + 'vector->list vector-fill! vector-length vector-ref vector-set! ' + + 'with-input-from-file with-output-to-file write write-char zero?' + }; + + const LITERAL = { + className: 'literal', + begin: '(#t|#f|#\\\\' + SCHEME_IDENT_RE + '|#\\\\.)' + }; + + const NUMBER = { + className: 'number', + variants: [ + { + begin: SCHEME_SIMPLE_NUMBER_RE, + relevance: 0 + }, + { + begin: SCHEME_COMPLEX_NUMBER_RE, + relevance: 0 + }, + { + begin: '#b[0-1]+(/[0-1]+)?' + }, + { + begin: '#o[0-7]+(/[0-7]+)?' + }, + { + begin: '#x[0-9a-f]+(/[0-9a-f]+)?' + } + ] + }; + + const STRING = hljs.QUOTE_STRING_MODE; + + const COMMENT_MODES = [ + hljs.COMMENT( + ';', + '$', + { + relevance: 0 + } + ), + hljs.COMMENT('#\\|', '\\|#') + ]; + + const IDENT = { + begin: SCHEME_IDENT_RE, + relevance: 0 + }; + + const QUOTED_IDENT = { + className: 'symbol', + begin: '\'' + SCHEME_IDENT_RE + }; + + const BODY = { + endsWithParent: true, + relevance: 0 + }; + + const QUOTED_LIST = { + variants: [ + { + begin: /'/ + }, + { + begin: '`' + } + ], + contains: [ + { + begin: '\\(', + end: '\\)', + contains: [ + 'self', + LITERAL, + STRING, + NUMBER, + IDENT, + QUOTED_IDENT + ] + } + ] + }; + + const NAME = { + className: 'name', + relevance: 0, + begin: SCHEME_IDENT_RE, + keywords: KEYWORDS + }; + + const LAMBDA = { + begin: /lambda/, + endsWithParent: true, + returnBegin: true, + contains: [ + NAME, + { + endsParent: true, + variants: [ + { + begin: /\(/, + end: /\)/ + }, + { + begin: /\[/, + end: /\]/ + } + ], + contains: [ IDENT ] + } + ] + }; + + const LIST = { + variants: [ + { + begin: '\\(', + end: '\\)' + }, + { + begin: '\\[', + end: '\\]' + } + ], + contains: [ + LAMBDA, + NAME, + BODY + ] + }; + + BODY.contains = [ + LITERAL, + NUMBER, + STRING, + IDENT, + QUOTED_IDENT, + QUOTED_LIST, + LIST + ].concat(COMMENT_MODES); + + return { + name: 'Scheme', + illegal: /\S/, + contains: [ + hljs.SHEBANG(), + NUMBER, + STRING, + QUOTED_IDENT, + QUOTED_LIST, + LIST + ].concat(COMMENT_MODES) + }; +} + +module.exports = scheme; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/scilab.js b/claude-code-source/node_modules/highlight.js/lib/languages/scilab.js new file mode 100644 index 00000000..f9644109 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/scilab.js @@ -0,0 +1,73 @@ +/* +Language: Scilab +Author: Sylvestre Ledru +Origin: matlab.js +Description: Scilab is a port from Matlab +Website: https://www.scilab.org +Category: scientific +*/ + +function scilab(hljs) { + const COMMON_CONTAINS = [ + hljs.C_NUMBER_MODE, + { + className: 'string', + begin: '\'|\"', + end: '\'|\"', + contains: [ hljs.BACKSLASH_ESCAPE, + { + begin: '\'\'' + } ] + } + ]; + + return { + name: 'Scilab', + aliases: [ 'sci' ], + keywords: { + $pattern: /%?\w+/, + keyword: 'abort break case clear catch continue do elseif else endfunction end for function ' + + 'global if pause return resume select try then while', + literal: + '%f %F %t %T %pi %eps %inf %nan %e %i %z %s', + built_in: // Scilab has more than 2000 functions. Just list the most commons + 'abs and acos asin atan ceil cd chdir clearglobal cosh cos cumprod deff disp error ' + + 'exec execstr exists exp eye gettext floor fprintf fread fsolve imag isdef isempty ' + + 'isinfisnan isvector lasterror length load linspace list listfiles log10 log2 log ' + + 'max min msprintf mclose mopen ones or pathconvert poly printf prod pwd rand real ' + + 'round sinh sin size gsort sprintf sqrt strcat strcmps tring sum system tanh tan ' + + 'type typename warning zeros matrix' + }, + illegal: '("|#|/\\*|\\s+/\\w+)', + contains: [ + { + className: 'function', + beginKeywords: 'function', + end: '$', + contains: [ + hljs.UNDERSCORE_TITLE_MODE, + { + className: 'params', + begin: '\\(', + end: '\\)' + } + ] + }, + // seems to be a guard against [ident]' or [ident]. + // perhaps to prevent attributes from flagging as keywords? + { + begin: '[a-zA-Z_][a-zA-Z_0-9]*[\\.\']+', + relevance: 0 + }, + { + begin: '\\[', + end: '\\][\\.\']*', + relevance: 0, + contains: COMMON_CONTAINS + }, + hljs.COMMENT('//', '$') + ].concat(COMMON_CONTAINS) + }; +} + +module.exports = scilab; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/scss.js b/claude-code-source/node_modules/highlight.js/lib/languages/scss.js new file mode 100644 index 00000000..6a5a90d6 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/scss.js @@ -0,0 +1,545 @@ +const MODES = (hljs) => { + return { + IMPORTANT: { + className: 'meta', + begin: '!important' + }, + HEXCOLOR: { + className: 'number', + begin: '#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})' + }, + ATTRIBUTE_SELECTOR_MODE: { + className: 'selector-attr', + begin: /\[/, + end: /\]/, + illegal: '$', + contains: [ + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE + ] + } + }; +}; + +const TAGS = [ + 'a', + 'abbr', + 'address', + 'article', + 'aside', + 'audio', + 'b', + 'blockquote', + 'body', + 'button', + 'canvas', + 'caption', + 'cite', + 'code', + 'dd', + 'del', + 'details', + 'dfn', + 'div', + 'dl', + 'dt', + 'em', + 'fieldset', + 'figcaption', + 'figure', + 'footer', + 'form', + 'h1', + 'h2', + 'h3', + 'h4', + 'h5', + 'h6', + 'header', + 'hgroup', + 'html', + 'i', + 'iframe', + 'img', + 'input', + 'ins', + 'kbd', + 'label', + 'legend', + 'li', + 'main', + 'mark', + 'menu', + 'nav', + 'object', + 'ol', + 'p', + 'q', + 'quote', + 'samp', + 'section', + 'span', + 'strong', + 'summary', + 'sup', + 'table', + 'tbody', + 'td', + 'textarea', + 'tfoot', + 'th', + 'thead', + 'time', + 'tr', + 'ul', + 'var', + 'video' +]; + +const MEDIA_FEATURES = [ + 'any-hover', + 'any-pointer', + 'aspect-ratio', + 'color', + 'color-gamut', + 'color-index', + 'device-aspect-ratio', + 'device-height', + 'device-width', + 'display-mode', + 'forced-colors', + 'grid', + 'height', + 'hover', + 'inverted-colors', + 'monochrome', + 'orientation', + 'overflow-block', + 'overflow-inline', + 'pointer', + 'prefers-color-scheme', + 'prefers-contrast', + 'prefers-reduced-motion', + 'prefers-reduced-transparency', + 'resolution', + 'scan', + 'scripting', + 'update', + 'width', + // TODO: find a better solution? + 'min-width', + 'max-width', + 'min-height', + 'max-height' +]; + +// https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes +const PSEUDO_CLASSES = [ + 'active', + 'any-link', + 'blank', + 'checked', + 'current', + 'default', + 'defined', + 'dir', // dir() + 'disabled', + 'drop', + 'empty', + 'enabled', + 'first', + 'first-child', + 'first-of-type', + 'fullscreen', + 'future', + 'focus', + 'focus-visible', + 'focus-within', + 'has', // has() + 'host', // host or host() + 'host-context', // host-context() + 'hover', + 'indeterminate', + 'in-range', + 'invalid', + 'is', // is() + 'lang', // lang() + 'last-child', + 'last-of-type', + 'left', + 'link', + 'local-link', + 'not', // not() + 'nth-child', // nth-child() + 'nth-col', // nth-col() + 'nth-last-child', // nth-last-child() + 'nth-last-col', // nth-last-col() + 'nth-last-of-type', //nth-last-of-type() + 'nth-of-type', //nth-of-type() + 'only-child', + 'only-of-type', + 'optional', + 'out-of-range', + 'past', + 'placeholder-shown', + 'read-only', + 'read-write', + 'required', + 'right', + 'root', + 'scope', + 'target', + 'target-within', + 'user-invalid', + 'valid', + 'visited', + 'where' // where() +]; + +// https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements +const PSEUDO_ELEMENTS = [ + 'after', + 'backdrop', + 'before', + 'cue', + 'cue-region', + 'first-letter', + 'first-line', + 'grammar-error', + 'marker', + 'part', + 'placeholder', + 'selection', + 'slotted', + 'spelling-error' +]; + +const ATTRIBUTES = [ + 'align-content', + 'align-items', + 'align-self', + 'animation', + 'animation-delay', + 'animation-direction', + 'animation-duration', + 'animation-fill-mode', + 'animation-iteration-count', + 'animation-name', + 'animation-play-state', + 'animation-timing-function', + 'auto', + 'backface-visibility', + 'background', + 'background-attachment', + 'background-clip', + 'background-color', + 'background-image', + 'background-origin', + 'background-position', + 'background-repeat', + 'background-size', + 'border', + 'border-bottom', + 'border-bottom-color', + 'border-bottom-left-radius', + 'border-bottom-right-radius', + 'border-bottom-style', + 'border-bottom-width', + 'border-collapse', + 'border-color', + 'border-image', + 'border-image-outset', + 'border-image-repeat', + 'border-image-slice', + 'border-image-source', + 'border-image-width', + 'border-left', + 'border-left-color', + 'border-left-style', + 'border-left-width', + 'border-radius', + 'border-right', + 'border-right-color', + 'border-right-style', + 'border-right-width', + 'border-spacing', + 'border-style', + 'border-top', + 'border-top-color', + 'border-top-left-radius', + 'border-top-right-radius', + 'border-top-style', + 'border-top-width', + 'border-width', + 'bottom', + 'box-decoration-break', + 'box-shadow', + 'box-sizing', + 'break-after', + 'break-before', + 'break-inside', + 'caption-side', + 'clear', + 'clip', + 'clip-path', + 'color', + 'column-count', + 'column-fill', + 'column-gap', + 'column-rule', + 'column-rule-color', + 'column-rule-style', + 'column-rule-width', + 'column-span', + 'column-width', + 'columns', + 'content', + 'counter-increment', + 'counter-reset', + 'cursor', + 'direction', + 'display', + 'empty-cells', + 'filter', + 'flex', + 'flex-basis', + 'flex-direction', + 'flex-flow', + 'flex-grow', + 'flex-shrink', + 'flex-wrap', + 'float', + 'font', + 'font-display', + 'font-family', + 'font-feature-settings', + 'font-kerning', + 'font-language-override', + 'font-size', + 'font-size-adjust', + 'font-smoothing', + 'font-stretch', + 'font-style', + 'font-variant', + 'font-variant-ligatures', + 'font-variation-settings', + 'font-weight', + 'height', + 'hyphens', + 'icon', + 'image-orientation', + 'image-rendering', + 'image-resolution', + 'ime-mode', + 'inherit', + 'initial', + 'justify-content', + 'left', + 'letter-spacing', + 'line-height', + 'list-style', + 'list-style-image', + 'list-style-position', + 'list-style-type', + 'margin', + 'margin-bottom', + 'margin-left', + 'margin-right', + 'margin-top', + 'marks', + 'mask', + 'max-height', + 'max-width', + 'min-height', + 'min-width', + 'nav-down', + 'nav-index', + 'nav-left', + 'nav-right', + 'nav-up', + 'none', + 'normal', + 'object-fit', + 'object-position', + 'opacity', + 'order', + 'orphans', + 'outline', + 'outline-color', + 'outline-offset', + 'outline-style', + 'outline-width', + 'overflow', + 'overflow-wrap', + 'overflow-x', + 'overflow-y', + 'padding', + 'padding-bottom', + 'padding-left', + 'padding-right', + 'padding-top', + 'page-break-after', + 'page-break-before', + 'page-break-inside', + 'perspective', + 'perspective-origin', + 'pointer-events', + 'position', + 'quotes', + 'resize', + 'right', + 'src', // @font-face + 'tab-size', + 'table-layout', + 'text-align', + 'text-align-last', + 'text-decoration', + 'text-decoration-color', + 'text-decoration-line', + 'text-decoration-style', + 'text-indent', + 'text-overflow', + 'text-rendering', + 'text-shadow', + 'text-transform', + 'text-underline-position', + 'top', + 'transform', + 'transform-origin', + 'transform-style', + 'transition', + 'transition-delay', + 'transition-duration', + 'transition-property', + 'transition-timing-function', + 'unicode-bidi', + 'vertical-align', + 'visibility', + 'white-space', + 'widows', + 'width', + 'word-break', + 'word-spacing', + 'word-wrap', + 'z-index' + // reverse makes sure longer attributes `font-weight` are matched fully + // instead of getting false positives on say `font` +].reverse(); + +/* +Language: SCSS +Description: Scss is an extension of the syntax of CSS. +Author: Kurt Emch +Website: https://sass-lang.com +Category: common, css +*/ + +/** @type LanguageFn */ +function scss(hljs) { + const modes = MODES(hljs); + const PSEUDO_ELEMENTS$1 = PSEUDO_ELEMENTS; + const PSEUDO_CLASSES$1 = PSEUDO_CLASSES; + + const AT_IDENTIFIER = '@[a-z-]+'; // @font-face + const AT_MODIFIERS = "and or not only"; + const IDENT_RE = '[a-zA-Z-][a-zA-Z0-9_-]*'; + const VARIABLE = { + className: 'variable', + begin: '(\\$' + IDENT_RE + ')\\b' + }; + + return { + name: 'SCSS', + case_insensitive: true, + illegal: '[=/|\']', + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + { + className: 'selector-id', + begin: '#[A-Za-z0-9_-]+', + relevance: 0 + }, + { + className: 'selector-class', + begin: '\\.[A-Za-z0-9_-]+', + relevance: 0 + }, + modes.ATTRIBUTE_SELECTOR_MODE, + { + className: 'selector-tag', + begin: '\\b(' + TAGS.join('|') + ')\\b', + // was there, before, but why? + relevance: 0 + }, + { + className: 'selector-pseudo', + begin: ':(' + PSEUDO_CLASSES$1.join('|') + ')' + }, + { + className: 'selector-pseudo', + begin: '::(' + PSEUDO_ELEMENTS$1.join('|') + ')' + }, + VARIABLE, + { // pseudo-selector params + begin: /\(/, + end: /\)/, + contains: [ hljs.CSS_NUMBER_MODE ] + }, + { + className: 'attribute', + begin: '\\b(' + ATTRIBUTES.join('|') + ')\\b' + }, + { + begin: '\\b(whitespace|wait|w-resize|visible|vertical-text|vertical-ideographic|uppercase|upper-roman|upper-alpha|underline|transparent|top|thin|thick|text|text-top|text-bottom|tb-rl|table-header-group|table-footer-group|sw-resize|super|strict|static|square|solid|small-caps|separate|se-resize|scroll|s-resize|rtl|row-resize|ridge|right|repeat|repeat-y|repeat-x|relative|progress|pointer|overline|outside|outset|oblique|nowrap|not-allowed|normal|none|nw-resize|no-repeat|no-drop|newspaper|ne-resize|n-resize|move|middle|medium|ltr|lr-tb|lowercase|lower-roman|lower-alpha|loose|list-item|line|line-through|line-edge|lighter|left|keep-all|justify|italic|inter-word|inter-ideograph|inside|inset|inline|inline-block|inherit|inactive|ideograph-space|ideograph-parenthesis|ideograph-numeric|ideograph-alpha|horizontal|hidden|help|hand|groove|fixed|ellipsis|e-resize|double|dotted|distribute|distribute-space|distribute-letter|distribute-all-lines|disc|disabled|default|decimal|dashed|crosshair|collapse|col-resize|circle|char|center|capitalize|break-word|break-all|bottom|both|bolder|bold|block|bidi-override|below|baseline|auto|always|all-scroll|absolute|table|table-cell)\\b' + }, + { + begin: ':', + end: ';', + contains: [ + VARIABLE, + modes.HEXCOLOR, + hljs.CSS_NUMBER_MODE, + hljs.QUOTE_STRING_MODE, + hljs.APOS_STRING_MODE, + modes.IMPORTANT + ] + }, + // matching these here allows us to treat them more like regular CSS + // rules so everything between the {} gets regular rule highlighting, + // which is what we want for page and font-face + { + begin: '@(page|font-face)', + lexemes: AT_IDENTIFIER, + keywords: '@page @font-face' + }, + { + begin: '@', + end: '[{;]', + returnBegin: true, + keywords: { + $pattern: /[a-z-]+/, + keyword: AT_MODIFIERS, + attribute: MEDIA_FEATURES.join(" ") + }, + contains: [ + { + begin: AT_IDENTIFIER, + className: "keyword" + }, + { + begin: /[a-z-]+(?=:)/, + className: "attribute" + }, + VARIABLE, + hljs.QUOTE_STRING_MODE, + hljs.APOS_STRING_MODE, + modes.HEXCOLOR, + hljs.CSS_NUMBER_MODE + ] + } + ] + }; +} + +module.exports = scss; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/shell.js b/claude-code-source/node_modules/highlight.js/lib/languages/shell.js new file mode 100644 index 00000000..bb2c8f74 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/shell.js @@ -0,0 +1,30 @@ +/* +Language: Shell Session +Requires: bash.js +Author: TSUYUSATO Kitsune +Category: common +Audit: 2020 +*/ + +/** @type LanguageFn */ +function shell(hljs) { + return { + name: 'Shell Session', + aliases: [ 'console' ], + contains: [ + { + className: 'meta', + // We cannot add \s (spaces) in the regular expression otherwise it will be too broad and produce unexpected result. + // For instance, in the following example, it would match "echo /path/to/home >" as a prompt: + // echo /path/to/home > t.exe + begin: /^\s{0,3}[/~\w\d[\]()@-]*[>%$#]/, + starts: { + end: /[^\\](?=\s*$)/, + subLanguage: 'bash' + } + } + ] + }; +} + +module.exports = shell; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/smali.js b/claude-code-source/node_modules/highlight.js/lib/languages/smali.js new file mode 100644 index 00000000..4e16c8a7 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/smali.js @@ -0,0 +1,135 @@ +/* +Language: Smali +Author: Dennis Titze +Description: Basic Smali highlighting +Website: https://github.com/JesusFreke/smali +*/ + +function smali(hljs) { + const smali_instr_low_prio = [ + 'add', + 'and', + 'cmp', + 'cmpg', + 'cmpl', + 'const', + 'div', + 'double', + 'float', + 'goto', + 'if', + 'int', + 'long', + 'move', + 'mul', + 'neg', + 'new', + 'nop', + 'not', + 'or', + 'rem', + 'return', + 'shl', + 'shr', + 'sput', + 'sub', + 'throw', + 'ushr', + 'xor' + ]; + const smali_instr_high_prio = [ + 'aget', + 'aput', + 'array', + 'check', + 'execute', + 'fill', + 'filled', + 'goto/16', + 'goto/32', + 'iget', + 'instance', + 'invoke', + 'iput', + 'monitor', + 'packed', + 'sget', + 'sparse' + ]; + const smali_keywords = [ + 'transient', + 'constructor', + 'abstract', + 'final', + 'synthetic', + 'public', + 'private', + 'protected', + 'static', + 'bridge', + 'system' + ]; + return { + name: 'Smali', + contains: [ + { + className: 'string', + begin: '"', + end: '"', + relevance: 0 + }, + hljs.COMMENT( + '#', + '$', + { + relevance: 0 + } + ), + { + className: 'keyword', + variants: [ + { + begin: '\\s*\\.end\\s[a-zA-Z0-9]*' + }, + { + begin: '^[ ]*\\.[a-zA-Z]*', + relevance: 0 + }, + { + begin: '\\s:[a-zA-Z_0-9]*', + relevance: 0 + }, + { + begin: '\\s(' + smali_keywords.join('|') + ')' + } + ] + }, + { + className: 'built_in', + variants: [ + { + begin: '\\s(' + smali_instr_low_prio.join('|') + ')\\s' + }, + { + begin: '\\s(' + smali_instr_low_prio.join('|') + ')((-|/)[a-zA-Z0-9]+)+\\s', + relevance: 10 + }, + { + begin: '\\s(' + smali_instr_high_prio.join('|') + ')((-|/)[a-zA-Z0-9]+)*\\s', + relevance: 10 + } + ] + }, + { + className: 'class', + begin: 'L[^\(;:\n]*;', + relevance: 0 + }, + { + begin: '[vp][0-9]+' + } + ] + }; +} + +module.exports = smali; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/smalltalk.js b/claude-code-source/node_modules/highlight.js/lib/languages/smalltalk.js new file mode 100644 index 00000000..c1d02150 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/smalltalk.js @@ -0,0 +1,63 @@ +/* +Language: Smalltalk +Description: Smalltalk is an object-oriented, dynamically typed reflective programming language. +Author: Vladimir Gubarkov +Website: https://en.wikipedia.org/wiki/Smalltalk +*/ + +function smalltalk(hljs) { + const VAR_IDENT_RE = '[a-z][a-zA-Z0-9_]*'; + const CHAR = { + className: 'string', + begin: '\\$.{1}' + }; + const SYMBOL = { + className: 'symbol', + begin: '#' + hljs.UNDERSCORE_IDENT_RE + }; + return { + name: 'Smalltalk', + aliases: [ 'st' ], + keywords: 'self super nil true false thisContext', // only 6 + contains: [ + hljs.COMMENT('"', '"'), + hljs.APOS_STRING_MODE, + { + className: 'type', + begin: '\\b[A-Z][A-Za-z0-9_]*', + relevance: 0 + }, + { + begin: VAR_IDENT_RE + ':', + relevance: 0 + }, + hljs.C_NUMBER_MODE, + SYMBOL, + CHAR, + { + // This looks more complicated than needed to avoid combinatorial + // explosion under V8. It effectively means `| var1 var2 ... |` with + // whitespace adjacent to `|` being optional. + begin: '\\|[ ]*' + VAR_IDENT_RE + '([ ]+' + VAR_IDENT_RE + ')*[ ]*\\|', + returnBegin: true, + end: /\|/, + illegal: /\S/, + contains: [ { + begin: '(\\|[ ]*)?' + VAR_IDENT_RE + } ] + }, + { + begin: '#\\(', + end: '\\)', + contains: [ + hljs.APOS_STRING_MODE, + CHAR, + hljs.C_NUMBER_MODE, + SYMBOL + ] + } + ] + }; +} + +module.exports = smalltalk; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/sml.js b/claude-code-source/node_modules/highlight.js/lib/languages/sml.js new file mode 100644 index 00000000..16b4cc18 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/sml.js @@ -0,0 +1,81 @@ +/* +Language: SML (Standard ML) +Author: Edwin Dalorzo +Description: SML language definition. +Website: https://www.smlnj.org +Origin: ocaml.js +Category: functional +*/ +function sml(hljs) { + return { + name: 'SML (Standard ML)', + aliases: [ 'ml' ], + keywords: { + $pattern: '[a-z_]\\w*!?', + keyword: + /* according to Definition of Standard ML 97 */ + 'abstype and andalso as case datatype do else end eqtype ' + + 'exception fn fun functor handle if in include infix infixr ' + + 'let local nonfix of op open orelse raise rec sharing sig ' + + 'signature struct structure then type val with withtype where while', + built_in: + /* built-in types according to basis library */ + 'array bool char exn int list option order real ref string substring vector unit word', + literal: + 'true false NONE SOME LESS EQUAL GREATER nil' + }, + illegal: /\/\/|>>/, + contains: [ + { + className: 'literal', + begin: /\[(\|\|)?\]|\(\)/, + relevance: 0 + }, + hljs.COMMENT( + '\\(\\*', + '\\*\\)', + { + contains: [ 'self' ] + } + ), + { /* type variable */ + className: 'symbol', + begin: '\'[A-Za-z_](?!\')[\\w\']*' + /* the grammar is ambiguous on how 'a'b should be interpreted but not the compiler */ + }, + { /* polymorphic variant */ + className: 'type', + begin: '`[A-Z][\\w\']*' + }, + { /* module or constructor */ + className: 'type', + begin: '\\b[A-Z][\\w\']*', + relevance: 0 + }, + { /* don't color identifiers, but safely catch all identifiers with ' */ + begin: '[a-z_]\\w*\'[\\w\']*' + }, + hljs.inherit(hljs.APOS_STRING_MODE, { + className: 'string', + relevance: 0 + }), + hljs.inherit(hljs.QUOTE_STRING_MODE, { + illegal: null + }), + { + className: 'number', + begin: + '\\b(0[xX][a-fA-F0-9_]+[Lln]?|' + + '0[oO][0-7_]+[Lln]?|' + + '0[bB][01_]+[Lln]?|' + + '[0-9][0-9_]*([Lln]|(\\.[0-9_]*)?([eE][-+]?[0-9_]+)?)?)', + relevance: 0 + }, + { + begin: /[-=]>/ // relevance booster + } + ] + }; +} + +module.exports = sml; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/sqf.js b/claude-code-source/node_modules/highlight.js/lib/languages/sqf.js new file mode 100644 index 00000000..61648266 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/sqf.js @@ -0,0 +1,448 @@ +/* +Language: SQF +Author: Søren Enevoldsen +Contributors: Marvin Saignat , Dedmen Miller +Description: Scripting language for the Arma game series +Website: https://community.bistudio.com/wiki/SQF_syntax +Category: scripting +*/ + +function sqf(hljs) { + // In SQF, a variable start with _ + const VARIABLE = { + className: 'variable', + begin: /\b_+[a-zA-Z]\w*/ + }; + + // In SQF, a function should fit myTag_fnc_myFunction pattern + // https://community.bistudio.com/wiki/Functions_Library_(Arma_3)#Adding_a_Function + const FUNCTION = { + className: 'title', + begin: /[a-zA-Z][a-zA-Z0-9]+_fnc_\w*/ + }; + + // In SQF strings, quotes matching the start are escaped by adding a consecutive. + // Example of single escaped quotes: " "" " and ' '' '. + const STRINGS = { + className: 'string', + variants: [ + { + begin: '"', + end: '"', + contains: [ { + begin: '""', + relevance: 0 + } ] + }, + { + begin: '\'', + end: '\'', + contains: [ { + begin: '\'\'', + relevance: 0 + } ] + } + ] + }; + + // list of keywords from: + // https://community.bistudio.com/wiki/PreProcessor_Commands + const PREPROCESSOR = { + className: 'meta', + begin: /#\s*[a-z]+\b/, + end: /$/, + keywords: { + 'meta-keyword': + 'define undef ifdef ifndef else endif include' + }, + contains: [ + { + begin: /\\\n/, + relevance: 0 + }, + hljs.inherit(STRINGS, { + className: 'meta-string' + }), + { + className: 'meta-string', + begin: /<[^\n>]*>/, + end: /$/, + illegal: '\\n' + }, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE + ] + }; + + return { + name: 'SQF', + case_insensitive: true, + keywords: { + keyword: + 'case catch default do else exit exitWith for forEach from if ' + + 'private switch then throw to try waitUntil while with', + built_in: + 'abs accTime acos action actionIDs actionKeys actionKeysImages actionKeysNames ' + + 'actionKeysNamesArray actionName actionParams activateAddons activatedAddons activateKey ' + + 'add3DENConnection add3DENEventHandler add3DENLayer addAction addBackpack addBackpackCargo ' + + 'addBackpackCargoGlobal addBackpackGlobal addCamShake addCuratorAddons addCuratorCameraArea ' + + 'addCuratorEditableObjects addCuratorEditingArea addCuratorPoints addEditorObject addEventHandler ' + + 'addForce addGoggles addGroupIcon addHandgunItem addHeadgear addItem addItemCargo ' + + 'addItemCargoGlobal addItemPool addItemToBackpack addItemToUniform addItemToVest addLiveStats ' + + 'addMagazine addMagazineAmmoCargo addMagazineCargo addMagazineCargoGlobal addMagazineGlobal ' + + 'addMagazinePool addMagazines addMagazineTurret addMenu addMenuItem addMissionEventHandler ' + + 'addMPEventHandler addMusicEventHandler addOwnedMine addPlayerScores addPrimaryWeaponItem ' + + 'addPublicVariableEventHandler addRating addResources addScore addScoreSide addSecondaryWeaponItem ' + + 'addSwitchableUnit addTeamMember addToRemainsCollector addTorque addUniform addVehicle addVest ' + + 'addWaypoint addWeapon addWeaponCargo addWeaponCargoGlobal addWeaponGlobal addWeaponItem ' + + 'addWeaponPool addWeaponTurret admin agent agents AGLToASL aimedAtTarget aimPos airDensityRTD ' + + 'airplaneThrottle airportSide AISFinishHeal alive all3DENEntities allAirports allControls ' + + 'allCurators allCutLayers allDead allDeadMen allDisplays allGroups allMapMarkers allMines ' + + 'allMissionObjects allow3DMode allowCrewInImmobile allowCuratorLogicIgnoreAreas allowDamage ' + + 'allowDammage allowFileOperations allowFleeing allowGetIn allowSprint allPlayers allSimpleObjects ' + + 'allSites allTurrets allUnits allUnitsUAV allVariables ammo ammoOnPylon and animate animateBay ' + + 'animateDoor animatePylon animateSource animationNames animationPhase animationSourcePhase ' + + 'animationState append apply armoryPoints arrayIntersect asin ASLToAGL ASLToATL assert ' + + 'assignAsCargo assignAsCargoIndex assignAsCommander assignAsDriver assignAsGunner assignAsTurret ' + + 'assignCurator assignedCargo assignedCommander assignedDriver assignedGunner assignedItems ' + + 'assignedTarget assignedTeam assignedVehicle assignedVehicleRole assignItem assignTeam ' + + 'assignToAirport atan atan2 atg ATLToASL attachedObject attachedObjects attachedTo attachObject ' + + 'attachTo attackEnabled backpack backpackCargo backpackContainer backpackItems backpackMagazines ' + + 'backpackSpaceFor behaviour benchmark binocular boundingBox boundingBoxReal boundingCenter ' + + 'breakOut breakTo briefingName buildingExit buildingPos buttonAction buttonSetAction cadetMode ' + + 'call callExtension camCommand camCommit camCommitPrepared camCommitted camConstuctionSetParams ' + + 'camCreate camDestroy cameraEffect cameraEffectEnableHUD cameraInterest cameraOn cameraView ' + + 'campaignConfigFile camPreload camPreloaded camPrepareBank camPrepareDir camPrepareDive ' + + 'camPrepareFocus camPrepareFov camPrepareFovRange camPreparePos camPrepareRelPos camPrepareTarget ' + + 'camSetBank camSetDir camSetDive camSetFocus camSetFov camSetFovRange camSetPos camSetRelPos ' + + 'camSetTarget camTarget camUseNVG canAdd canAddItemToBackpack canAddItemToUniform canAddItemToVest ' + + 'cancelSimpleTaskDestination canFire canMove canSlingLoad canStand canSuspend ' + + 'canTriggerDynamicSimulation canUnloadInCombat canVehicleCargo captive captiveNum cbChecked ' + + 'cbSetChecked ceil channelEnabled cheatsEnabled checkAIFeature checkVisibility className ' + + 'clearAllItemsFromBackpack clearBackpackCargo clearBackpackCargoGlobal clearGroupIcons ' + + 'clearItemCargo clearItemCargoGlobal clearItemPool clearMagazineCargo clearMagazineCargoGlobal ' + + 'clearMagazinePool clearOverlay clearRadio clearWeaponCargo clearWeaponCargoGlobal clearWeaponPool ' + + 'clientOwner closeDialog closeDisplay closeOverlay collapseObjectTree collect3DENHistory ' + + 'collectiveRTD combatMode commandArtilleryFire commandChat commander commandFire commandFollow ' + + 'commandFSM commandGetOut commandingMenu commandMove commandRadio commandStop ' + + 'commandSuppressiveFire commandTarget commandWatch comment commitOverlay compile compileFinal ' + + 'completedFSM composeText configClasses configFile configHierarchy configName configProperties ' + + 'configSourceAddonList configSourceMod configSourceModList confirmSensorTarget ' + + 'connectTerminalToUAV controlsGroupCtrl copyFromClipboard copyToClipboard copyWaypoints cos count ' + + 'countEnemy countFriendly countSide countType countUnknown create3DENComposition create3DENEntity ' + + 'createAgent createCenter createDialog createDiaryLink createDiaryRecord createDiarySubject ' + + 'createDisplay createGearDialog createGroup createGuardedPoint createLocation createMarker ' + + 'createMarkerLocal createMenu createMine createMissionDisplay createMPCampaignDisplay ' + + 'createSimpleObject createSimpleTask createSite createSoundSource createTask createTeam ' + + 'createTrigger createUnit createVehicle createVehicleCrew createVehicleLocal crew ctAddHeader ' + + 'ctAddRow ctClear ctCurSel ctData ctFindHeaderRows ctFindRowHeader ctHeaderControls ctHeaderCount ' + + 'ctRemoveHeaders ctRemoveRows ctrlActivate ctrlAddEventHandler ctrlAngle ctrlAutoScrollDelay ' + + 'ctrlAutoScrollRewind ctrlAutoScrollSpeed ctrlChecked ctrlClassName ctrlCommit ctrlCommitted ' + + 'ctrlCreate ctrlDelete ctrlEnable ctrlEnabled ctrlFade ctrlHTMLLoaded ctrlIDC ctrlIDD ' + + 'ctrlMapAnimAdd ctrlMapAnimClear ctrlMapAnimCommit ctrlMapAnimDone ctrlMapCursor ctrlMapMouseOver ' + + 'ctrlMapScale ctrlMapScreenToWorld ctrlMapWorldToScreen ctrlModel ctrlModelDirAndUp ctrlModelScale ' + + 'ctrlParent ctrlParentControlsGroup ctrlPosition ctrlRemoveAllEventHandlers ctrlRemoveEventHandler ' + + 'ctrlScale ctrlSetActiveColor ctrlSetAngle ctrlSetAutoScrollDelay ctrlSetAutoScrollRewind ' + + 'ctrlSetAutoScrollSpeed ctrlSetBackgroundColor ctrlSetChecked ctrlSetEventHandler ctrlSetFade ' + + 'ctrlSetFocus ctrlSetFont ctrlSetFontH1 ctrlSetFontH1B ctrlSetFontH2 ctrlSetFontH2B ctrlSetFontH3 ' + + 'ctrlSetFontH3B ctrlSetFontH4 ctrlSetFontH4B ctrlSetFontH5 ctrlSetFontH5B ctrlSetFontH6 ' + + 'ctrlSetFontH6B ctrlSetFontHeight ctrlSetFontHeightH1 ctrlSetFontHeightH2 ctrlSetFontHeightH3 ' + + 'ctrlSetFontHeightH4 ctrlSetFontHeightH5 ctrlSetFontHeightH6 ctrlSetFontHeightSecondary ' + + 'ctrlSetFontP ctrlSetFontPB ctrlSetFontSecondary ctrlSetForegroundColor ctrlSetModel ' + + 'ctrlSetModelDirAndUp ctrlSetModelScale ctrlSetPixelPrecision ctrlSetPosition ctrlSetScale ' + + 'ctrlSetStructuredText ctrlSetText ctrlSetTextColor ctrlSetTooltip ctrlSetTooltipColorBox ' + + 'ctrlSetTooltipColorShade ctrlSetTooltipColorText ctrlShow ctrlShown ctrlText ctrlTextHeight ' + + 'ctrlTextWidth ctrlType ctrlVisible ctRowControls ctRowCount ctSetCurSel ctSetData ' + + 'ctSetHeaderTemplate ctSetRowTemplate ctSetValue ctValue curatorAddons curatorCamera ' + + 'curatorCameraArea curatorCameraAreaCeiling curatorCoef curatorEditableObjects curatorEditingArea ' + + 'curatorEditingAreaType curatorMouseOver curatorPoints curatorRegisteredObjects curatorSelected ' + + 'curatorWaypointCost current3DENOperation currentChannel currentCommand currentMagazine ' + + 'currentMagazineDetail currentMagazineDetailTurret currentMagazineTurret currentMuzzle ' + + 'currentNamespace currentTask currentTasks currentThrowable currentVisionMode currentWaypoint ' + + 'currentWeapon currentWeaponMode currentWeaponTurret currentZeroing cursorObject cursorTarget ' + + 'customChat customRadio cutFadeOut cutObj cutRsc cutText damage date dateToNumber daytime ' + + 'deActivateKey debriefingText debugFSM debugLog deg delete3DENEntities deleteAt deleteCenter ' + + 'deleteCollection deleteEditorObject deleteGroup deleteGroupWhenEmpty deleteIdentity ' + + 'deleteLocation deleteMarker deleteMarkerLocal deleteRange deleteResources deleteSite deleteStatus ' + + 'deleteTeam deleteVehicle deleteVehicleCrew deleteWaypoint detach detectedMines ' + + 'diag_activeMissionFSMs diag_activeScripts diag_activeSQFScripts diag_activeSQSScripts ' + + 'diag_captureFrame diag_captureFrameToFile diag_captureSlowFrame diag_codePerformance ' + + 'diag_drawMode diag_enable diag_enabled diag_fps diag_fpsMin diag_frameNo diag_lightNewLoad ' + + 'diag_list diag_log diag_logSlowFrame diag_mergeConfigFile diag_recordTurretLimits ' + + 'diag_setLightNew diag_tickTime diag_toggle dialog diarySubjectExists didJIP didJIPOwner ' + + 'difficulty difficultyEnabled difficultyEnabledRTD difficultyOption direction directSay disableAI ' + + 'disableCollisionWith disableConversation disableDebriefingStats disableMapIndicators ' + + 'disableNVGEquipment disableRemoteSensors disableSerialization disableTIEquipment ' + + 'disableUAVConnectability disableUserInput displayAddEventHandler displayCtrl displayParent ' + + 'displayRemoveAllEventHandlers displayRemoveEventHandler displaySetEventHandler dissolveTeam ' + + 'distance distance2D distanceSqr distributionRegion do3DENAction doArtilleryFire doFire doFollow ' + + 'doFSM doGetOut doMove doorPhase doStop doSuppressiveFire doTarget doWatch drawArrow drawEllipse ' + + 'drawIcon drawIcon3D drawLine drawLine3D drawLink drawLocation drawPolygon drawRectangle ' + + 'drawTriangle driver drop dynamicSimulationDistance dynamicSimulationDistanceCoef ' + + 'dynamicSimulationEnabled dynamicSimulationSystemEnabled echo edit3DENMissionAttributes editObject ' + + 'editorSetEventHandler effectiveCommander emptyPositions enableAI enableAIFeature ' + + 'enableAimPrecision enableAttack enableAudioFeature enableAutoStartUpRTD enableAutoTrimRTD ' + + 'enableCamShake enableCaustics enableChannel enableCollisionWith enableCopilot ' + + 'enableDebriefingStats enableDiagLegend enableDynamicSimulation enableDynamicSimulationSystem ' + + 'enableEndDialog enableEngineArtillery enableEnvironment enableFatigue enableGunLights ' + + 'enableInfoPanelComponent enableIRLasers enableMimics enablePersonTurret enableRadio enableReload ' + + 'enableRopeAttach enableSatNormalOnDetail enableSaving enableSentences enableSimulation ' + + 'enableSimulationGlobal enableStamina enableTeamSwitch enableTraffic enableUAVConnectability ' + + 'enableUAVWaypoints enableVehicleCargo enableVehicleSensor enableWeaponDisassembly ' + + 'endLoadingScreen endMission engineOn enginesIsOnRTD enginesRpmRTD enginesTorqueRTD entities ' + + 'environmentEnabled estimatedEndServerTime estimatedTimeLeft evalObjectArgument everyBackpack ' + + 'everyContainer exec execEditorScript execFSM execVM exp expectedDestination exportJIPMessages ' + + 'eyeDirection eyePos face faction fadeMusic fadeRadio fadeSound fadeSpeech failMission ' + + 'fillWeaponsFromPool find findCover findDisplay findEditorObject findEmptyPosition ' + + 'findEmptyPositionReady findIf findNearestEnemy finishMissionInit finite fire fireAtTarget ' + + 'firstBackpack flag flagAnimationPhase flagOwner flagSide flagTexture fleeing floor flyInHeight ' + + 'flyInHeightASL fog fogForecast fogParams forceAddUniform forcedMap forceEnd forceFlagTexture ' + + 'forceFollowRoad forceMap forceRespawn forceSpeed forceWalk forceWeaponFire forceWeatherChange ' + + 'forEachMember forEachMemberAgent forEachMemberTeam forgetTarget format formation ' + + 'formationDirection formationLeader formationMembers formationPosition formationTask formatText ' + + 'formLeader freeLook fromEditor fuel fullCrew gearIDCAmmoCount gearSlotAmmoCount gearSlotData ' + + 'get3DENActionState get3DENAttribute get3DENCamera get3DENConnections get3DENEntity ' + + 'get3DENEntityID get3DENGrid get3DENIconsVisible get3DENLayerEntities get3DENLinesVisible ' + + 'get3DENMissionAttribute get3DENMouseOver get3DENSelected getAimingCoef getAllEnvSoundControllers ' + + 'getAllHitPointsDamage getAllOwnedMines getAllSoundControllers getAmmoCargo getAnimAimPrecision ' + + 'getAnimSpeedCoef getArray getArtilleryAmmo getArtilleryComputerSettings getArtilleryETA ' + + 'getAssignedCuratorLogic getAssignedCuratorUnit getBackpackCargo getBleedingRemaining ' + + 'getBurningValue getCameraViewDirection getCargoIndex getCenterOfMass getClientState ' + + 'getClientStateNumber getCompatiblePylonMagazines getConnectedUAV getContainerMaxLoad ' + + 'getCursorObjectParams getCustomAimCoef getDammage getDescription getDir getDirVisual ' + + 'getDLCAssetsUsage getDLCAssetsUsageByName getDLCs getEditorCamera getEditorMode ' + + 'getEditorObjectScope getElevationOffset getEnvSoundController getFatigue getForcedFlagTexture ' + + 'getFriend getFSMVariable getFuelCargo getGroupIcon getGroupIconParams getGroupIcons getHideFrom ' + + 'getHit getHitIndex getHitPointDamage getItemCargo getMagazineCargo getMarkerColor getMarkerPos ' + + 'getMarkerSize getMarkerType getMass getMissionConfig getMissionConfigValue getMissionDLCs ' + + 'getMissionLayerEntities getModelInfo getMousePosition getMusicPlayedTime getNumber ' + + 'getObjectArgument getObjectChildren getObjectDLC getObjectMaterials getObjectProxy ' + + 'getObjectTextures getObjectType getObjectViewDistance getOxygenRemaining getPersonUsedDLCs ' + + 'getPilotCameraDirection getPilotCameraPosition getPilotCameraRotation getPilotCameraTarget ' + + 'getPlateNumber getPlayerChannel getPlayerScores getPlayerUID getPos getPosASL getPosASLVisual ' + + 'getPosASLW getPosATL getPosATLVisual getPosVisual getPosWorld getPylonMagazines getRelDir ' + + 'getRelPos getRemoteSensorsDisabled getRepairCargo getResolution getShadowDistance getShotParents ' + + 'getSlingLoad getSoundController getSoundControllerResult getSpeed getStamina getStatValue ' + + 'getSuppression getTerrainGrid getTerrainHeightASL getText getTotalDLCUsageTime getUnitLoadout ' + + 'getUnitTrait getUserMFDText getUserMFDvalue getVariable getVehicleCargo getWeaponCargo ' + + 'getWeaponSway getWingsOrientationRTD getWingsPositionRTD getWPPos glanceAt globalChat globalRadio ' + + 'goggles goto group groupChat groupFromNetId groupIconSelectable groupIconsVisible groupId ' + + 'groupOwner groupRadio groupSelectedUnits groupSelectUnit gunner gusts halt handgunItems ' + + 'handgunMagazine handgunWeapon handsHit hasInterface hasPilotCamera hasWeapon hcAllGroups ' + + 'hcGroupParams hcLeader hcRemoveAllGroups hcRemoveGroup hcSelected hcSelectGroup hcSetGroup ' + + 'hcShowBar hcShownBar headgear hideBody hideObject hideObjectGlobal hideSelection hint hintC ' + + 'hintCadet hintSilent hmd hostMission htmlLoad HUDMovementLevels humidity image importAllGroups ' + + 'importance in inArea inAreaArray incapacitatedState inflame inflamed infoPanel ' + + 'infoPanelComponentEnabled infoPanelComponents infoPanels inGameUISetEventHandler inheritsFrom ' + + 'initAmbientLife inPolygon inputAction inRangeOfArtillery insertEditorObject intersect is3DEN ' + + 'is3DENMultiplayer isAbleToBreathe isAgent isArray isAutoHoverOn isAutonomous isAutotest ' + + 'isBleeding isBurning isClass isCollisionLightOn isCopilotEnabled isDamageAllowed isDedicated ' + + 'isDLCAvailable isEngineOn isEqualTo isEqualType isEqualTypeAll isEqualTypeAny isEqualTypeArray ' + + 'isEqualTypeParams isFilePatchingEnabled isFlashlightOn isFlatEmpty isForcedWalk isFormationLeader ' + + 'isGroupDeletedWhenEmpty isHidden isInRemainsCollector isInstructorFigureEnabled isIRLaserOn ' + + 'isKeyActive isKindOf isLaserOn isLightOn isLocalized isManualFire isMarkedForCollection ' + + 'isMultiplayer isMultiplayerSolo isNil isNull isNumber isObjectHidden isObjectRTD isOnRoad ' + + 'isPipEnabled isPlayer isRealTime isRemoteExecuted isRemoteExecutedJIP isServer isShowing3DIcons ' + + 'isSimpleObject isSprintAllowed isStaminaEnabled isSteamMission isStreamFriendlyUIEnabled isText ' + + 'isTouchingGround isTurnedOut isTutHintsEnabled isUAVConnectable isUAVConnected isUIContext ' + + 'isUniformAllowed isVehicleCargo isVehicleRadarOn isVehicleSensorEnabled isWalking ' + + 'isWeaponDeployed isWeaponRested itemCargo items itemsWithMagazines join joinAs joinAsSilent ' + + 'joinSilent joinString kbAddDatabase kbAddDatabaseTargets kbAddTopic kbHasTopic kbReact ' + + 'kbRemoveTopic kbTell kbWasSaid keyImage keyName knowsAbout land landAt landResult language ' + + 'laserTarget lbAdd lbClear lbColor lbColorRight lbCurSel lbData lbDelete lbIsSelected lbPicture ' + + 'lbPictureRight lbSelection lbSetColor lbSetColorRight lbSetCurSel lbSetData lbSetPicture ' + + 'lbSetPictureColor lbSetPictureColorDisabled lbSetPictureColorSelected lbSetPictureRight ' + + 'lbSetPictureRightColor lbSetPictureRightColorDisabled lbSetPictureRightColorSelected ' + + 'lbSetSelectColor lbSetSelectColorRight lbSetSelected lbSetText lbSetTextRight lbSetTooltip ' + + 'lbSetValue lbSize lbSort lbSortByValue lbText lbTextRight lbValue leader leaderboardDeInit ' + + 'leaderboardGetRows leaderboardInit leaderboardRequestRowsFriends leaderboardsRequestUploadScore ' + + 'leaderboardsRequestUploadScoreKeepBest leaderboardState leaveVehicle libraryCredits ' + + 'libraryDisclaimers lifeState lightAttachObject lightDetachObject lightIsOn lightnings limitSpeed ' + + 'linearConversion lineIntersects lineIntersectsObjs lineIntersectsSurfaces lineIntersectsWith ' + + 'linkItem list listObjects listRemoteTargets listVehicleSensors ln lnbAddArray lnbAddColumn ' + + 'lnbAddRow lnbClear lnbColor lnbCurSelRow lnbData lnbDeleteColumn lnbDeleteRow ' + + 'lnbGetColumnsPosition lnbPicture lnbSetColor lnbSetColumnsPos lnbSetCurSelRow lnbSetData ' + + 'lnbSetPicture lnbSetText lnbSetValue lnbSize lnbSort lnbSortByValue lnbText lnbValue load loadAbs ' + + 'loadBackpack loadFile loadGame loadIdentity loadMagazine loadOverlay loadStatus loadUniform ' + + 'loadVest local localize locationPosition lock lockCameraTo lockCargo lockDriver locked ' + + 'lockedCargo lockedDriver lockedTurret lockIdentity lockTurret lockWP log logEntities logNetwork ' + + 'logNetworkTerminate lookAt lookAtPos magazineCargo magazines magazinesAllTurrets magazinesAmmo ' + + 'magazinesAmmoCargo magazinesAmmoFull magazinesDetail magazinesDetailBackpack ' + + 'magazinesDetailUniform magazinesDetailVest magazinesTurret magazineTurretAmmo mapAnimAdd ' + + 'mapAnimClear mapAnimCommit mapAnimDone mapCenterOnCamera mapGridPosition markAsFinishedOnSteam ' + + 'markerAlpha markerBrush markerColor markerDir markerPos markerShape markerSize markerText ' + + 'markerType max members menuAction menuAdd menuChecked menuClear menuCollapse menuData menuDelete ' + + 'menuEnable menuEnabled menuExpand menuHover menuPicture menuSetAction menuSetCheck menuSetData ' + + 'menuSetPicture menuSetValue menuShortcut menuShortcutText menuSize menuSort menuText menuURL ' + + 'menuValue min mineActive mineDetectedBy missionConfigFile missionDifficulty missionName ' + + 'missionNamespace missionStart missionVersion mod modelToWorld modelToWorldVisual ' + + 'modelToWorldVisualWorld modelToWorldWorld modParams moonIntensity moonPhase morale move ' + + 'move3DENCamera moveInAny moveInCargo moveInCommander moveInDriver moveInGunner moveInTurret ' + + 'moveObjectToEnd moveOut moveTime moveTo moveToCompleted moveToFailed musicVolume name nameSound ' + + 'nearEntities nearestBuilding nearestLocation nearestLocations nearestLocationWithDubbing ' + + 'nearestObject nearestObjects nearestTerrainObjects nearObjects nearObjectsReady nearRoads ' + + 'nearSupplies nearTargets needReload netId netObjNull newOverlay nextMenuItemIndex ' + + 'nextWeatherChange nMenuItems not numberOfEnginesRTD numberToDate objectCurators objectFromNetId ' + + 'objectParent objStatus onBriefingGroup onBriefingNotes onBriefingPlan onBriefingTeamSwitch ' + + 'onCommandModeChanged onDoubleClick onEachFrame onGroupIconClick onGroupIconOverEnter ' + + 'onGroupIconOverLeave onHCGroupSelectionChanged onMapSingleClick onPlayerConnected ' + + 'onPlayerDisconnected onPreloadFinished onPreloadStarted onShowNewObject onTeamSwitch ' + + 'openCuratorInterface openDLCPage openMap openSteamApp openYoutubeVideo or orderGetIn overcast ' + + 'overcastForecast owner param params parseNumber parseSimpleArray parseText parsingNamespace ' + + 'particlesQuality pickWeaponPool pitch pixelGrid pixelGridBase pixelGridNoUIScale pixelH pixelW ' + + 'playableSlotsNumber playableUnits playAction playActionNow player playerRespawnTime playerSide ' + + 'playersNumber playGesture playMission playMove playMoveNow playMusic playScriptedMission ' + + 'playSound playSound3D position positionCameraToWorld posScreenToWorld posWorldToScreen ' + + 'ppEffectAdjust ppEffectCommit ppEffectCommitted ppEffectCreate ppEffectDestroy ppEffectEnable ' + + 'ppEffectEnabled ppEffectForceInNVG precision preloadCamera preloadObject preloadSound ' + + 'preloadTitleObj preloadTitleRsc preprocessFile preprocessFileLineNumbers primaryWeapon ' + + 'primaryWeaponItems primaryWeaponMagazine priority processDiaryLink productVersion profileName ' + + 'profileNamespace profileNameSteam progressLoadingScreen progressPosition progressSetPosition ' + + 'publicVariable publicVariableClient publicVariableServer pushBack pushBackUnique putWeaponPool ' + + 'queryItemsPool queryMagazinePool queryWeaponPool rad radioChannelAdd radioChannelCreate ' + + 'radioChannelRemove radioChannelSetCallSign radioChannelSetLabel radioVolume rain rainbow random ' + + 'rank rankId rating rectangular registeredTasks registerTask reload reloadEnabled remoteControl ' + + 'remoteExec remoteExecCall remoteExecutedOwner remove3DENConnection remove3DENEventHandler ' + + 'remove3DENLayer removeAction removeAll3DENEventHandlers removeAllActions removeAllAssignedItems ' + + 'removeAllContainers removeAllCuratorAddons removeAllCuratorCameraAreas ' + + 'removeAllCuratorEditingAreas removeAllEventHandlers removeAllHandgunItems removeAllItems ' + + 'removeAllItemsWithMagazines removeAllMissionEventHandlers removeAllMPEventHandlers ' + + 'removeAllMusicEventHandlers removeAllOwnedMines removeAllPrimaryWeaponItems removeAllWeapons ' + + 'removeBackpack removeBackpackGlobal removeCuratorAddons removeCuratorCameraArea ' + + 'removeCuratorEditableObjects removeCuratorEditingArea removeDrawIcon removeDrawLinks ' + + 'removeEventHandler removeFromRemainsCollector removeGoggles removeGroupIcon removeHandgunItem ' + + 'removeHeadgear removeItem removeItemFromBackpack removeItemFromUniform removeItemFromVest ' + + 'removeItems removeMagazine removeMagazineGlobal removeMagazines removeMagazinesTurret ' + + 'removeMagazineTurret removeMenuItem removeMissionEventHandler removeMPEventHandler ' + + 'removeMusicEventHandler removeOwnedMine removePrimaryWeaponItem removeSecondaryWeaponItem ' + + 'removeSimpleTask removeSwitchableUnit removeTeamMember removeUniform removeVest removeWeapon ' + + 'removeWeaponAttachmentCargo removeWeaponCargo removeWeaponGlobal removeWeaponTurret ' + + 'reportRemoteTarget requiredVersion resetCamShake resetSubgroupDirection resize resources ' + + 'respawnVehicle restartEditorCamera reveal revealMine reverse reversedMouseY roadAt ' + + 'roadsConnectedTo roleDescription ropeAttachedObjects ropeAttachedTo ropeAttachEnabled ' + + 'ropeAttachTo ropeCreate ropeCut ropeDestroy ropeDetach ropeEndPosition ropeLength ropes ' + + 'ropeUnwind ropeUnwound rotorsForcesRTD rotorsRpmRTD round runInitScript safeZoneH safeZoneW ' + + 'safeZoneWAbs safeZoneX safeZoneXAbs safeZoneY save3DENInventory saveGame saveIdentity ' + + 'saveJoysticks saveOverlay saveProfileNamespace saveStatus saveVar savingEnabled say say2D say3D ' + + 'scopeName score scoreSide screenshot screenToWorld scriptDone scriptName scudState ' + + 'secondaryWeapon secondaryWeaponItems secondaryWeaponMagazine select selectBestPlaces ' + + 'selectDiarySubject selectedEditorObjects selectEditorObject selectionNames selectionPosition ' + + 'selectLeader selectMax selectMin selectNoPlayer selectPlayer selectRandom selectRandomWeighted ' + + 'selectWeapon selectWeaponTurret sendAUMessage sendSimpleCommand sendTask sendTaskResult ' + + 'sendUDPMessage serverCommand serverCommandAvailable serverCommandExecutable serverName serverTime ' + + 'set set3DENAttribute set3DENAttributes set3DENGrid set3DENIconsVisible set3DENLayer ' + + 'set3DENLinesVisible set3DENLogicType set3DENMissionAttribute set3DENMissionAttributes ' + + 'set3DENModelsVisible set3DENObjectType set3DENSelected setAccTime setActualCollectiveRTD ' + + 'setAirplaneThrottle setAirportSide setAmmo setAmmoCargo setAmmoOnPylon setAnimSpeedCoef ' + + 'setAperture setApertureNew setArmoryPoints setAttributes setAutonomous setBehaviour ' + + 'setBleedingRemaining setBrakesRTD setCameraInterest setCamShakeDefParams setCamShakeParams ' + + 'setCamUseTI setCaptive setCenterOfMass setCollisionLight setCombatMode setCompassOscillation ' + + 'setConvoySeparation setCuratorCameraAreaCeiling setCuratorCoef setCuratorEditingAreaType ' + + 'setCuratorWaypointCost setCurrentChannel setCurrentTask setCurrentWaypoint setCustomAimCoef ' + + 'setCustomWeightRTD setDamage setDammage setDate setDebriefingText setDefaultCamera setDestination ' + + 'setDetailMapBlendPars setDir setDirection setDrawIcon setDriveOnPath setDropInterval ' + + 'setDynamicSimulationDistance setDynamicSimulationDistanceCoef setEditorMode setEditorObjectScope ' + + 'setEffectCondition setEngineRPMRTD setFace setFaceAnimation setFatigue setFeatureType ' + + 'setFlagAnimationPhase setFlagOwner setFlagSide setFlagTexture setFog setFormation ' + + 'setFormationTask setFormDir setFriend setFromEditor setFSMVariable setFuel setFuelCargo ' + + 'setGroupIcon setGroupIconParams setGroupIconsSelectable setGroupIconsVisible setGroupId ' + + 'setGroupIdGlobal setGroupOwner setGusts setHideBehind setHit setHitIndex setHitPointDamage ' + + 'setHorizonParallaxCoef setHUDMovementLevels setIdentity setImportance setInfoPanel setLeader ' + + 'setLightAmbient setLightAttenuation setLightBrightness setLightColor setLightDayLight ' + + 'setLightFlareMaxDistance setLightFlareSize setLightIntensity setLightnings setLightUseFlare ' + + 'setLocalWindParams setMagazineTurretAmmo setMarkerAlpha setMarkerAlphaLocal setMarkerBrush ' + + 'setMarkerBrushLocal setMarkerColor setMarkerColorLocal setMarkerDir setMarkerDirLocal ' + + 'setMarkerPos setMarkerPosLocal setMarkerShape setMarkerShapeLocal setMarkerSize ' + + 'setMarkerSizeLocal setMarkerText setMarkerTextLocal setMarkerType setMarkerTypeLocal setMass ' + + 'setMimic setMousePosition setMusicEffect setMusicEventHandler setName setNameSound ' + + 'setObjectArguments setObjectMaterial setObjectMaterialGlobal setObjectProxy setObjectTexture ' + + 'setObjectTextureGlobal setObjectViewDistance setOvercast setOwner setOxygenRemaining ' + + 'setParticleCircle setParticleClass setParticleFire setParticleParams setParticleRandom ' + + 'setPilotCameraDirection setPilotCameraRotation setPilotCameraTarget setPilotLight setPiPEffect ' + + 'setPitch setPlateNumber setPlayable setPlayerRespawnTime setPos setPosASL setPosASL2 setPosASLW ' + + 'setPosATL setPosition setPosWorld setPylonLoadOut setPylonsPriority setRadioMsg setRain ' + + 'setRainbow setRandomLip setRank setRectangular setRepairCargo setRotorBrakeRTD setShadowDistance ' + + 'setShotParents setSide setSimpleTaskAlwaysVisible setSimpleTaskCustomData ' + + 'setSimpleTaskDescription setSimpleTaskDestination setSimpleTaskTarget setSimpleTaskType ' + + 'setSimulWeatherLayers setSize setSkill setSlingLoad setSoundEffect setSpeaker setSpeech ' + + 'setSpeedMode setStamina setStaminaScheme setStatValue setSuppression setSystemOfUnits ' + + 'setTargetAge setTaskMarkerOffset setTaskResult setTaskState setTerrainGrid setText ' + + 'setTimeMultiplier setTitleEffect setTrafficDensity setTrafficDistance setTrafficGap ' + + 'setTrafficSpeed setTriggerActivation setTriggerArea setTriggerStatements setTriggerText ' + + 'setTriggerTimeout setTriggerType setType setUnconscious setUnitAbility setUnitLoadout setUnitPos ' + + 'setUnitPosWeak setUnitRank setUnitRecoilCoefficient setUnitTrait setUnloadInCombat ' + + 'setUserActionText setUserMFDText setUserMFDvalue setVariable setVectorDir setVectorDirAndUp ' + + 'setVectorUp setVehicleAmmo setVehicleAmmoDef setVehicleArmor setVehicleCargo setVehicleId ' + + 'setVehicleLock setVehiclePosition setVehicleRadar setVehicleReceiveRemoteTargets ' + + 'setVehicleReportOwnPosition setVehicleReportRemoteTargets setVehicleTIPars setVehicleVarName ' + + 'setVelocity setVelocityModelSpace setVelocityTransformation setViewDistance ' + + 'setVisibleIfTreeCollapsed setWantedRPMRTD setWaves setWaypointBehaviour setWaypointCombatMode ' + + 'setWaypointCompletionRadius setWaypointDescription setWaypointForceBehaviour setWaypointFormation ' + + 'setWaypointHousePosition setWaypointLoiterRadius setWaypointLoiterType setWaypointName ' + + 'setWaypointPosition setWaypointScript setWaypointSpeed setWaypointStatements setWaypointTimeout ' + + 'setWaypointType setWaypointVisible setWeaponReloadingTime setWind setWindDir setWindForce ' + + 'setWindStr setWingForceScaleRTD setWPPos show3DIcons showChat showCinemaBorder showCommandingMenu ' + + 'showCompass showCuratorCompass showGPS showHUD showLegend showMap shownArtilleryComputer ' + + 'shownChat shownCompass shownCuratorCompass showNewEditorObject shownGPS shownHUD shownMap ' + + 'shownPad shownRadio shownScoretable shownUAVFeed shownWarrant shownWatch showPad showRadio ' + + 'showScoretable showSubtitles showUAVFeed showWarrant showWatch showWaypoint showWaypoints side ' + + 'sideChat sideEnemy sideFriendly sideRadio simpleTasks simulationEnabled simulCloudDensity ' + + 'simulCloudOcclusion simulInClouds simulWeatherSync sin size sizeOf skill skillFinal skipTime ' + + 'sleep sliderPosition sliderRange sliderSetPosition sliderSetRange sliderSetSpeed sliderSpeed ' + + 'slingLoadAssistantShown soldierMagazines someAmmo sort soundVolume spawn speaker speed speedMode ' + + 'splitString sqrt squadParams stance startLoadingScreen step stop stopEngineRTD stopped str ' + + 'sunOrMoon supportInfo suppressFor surfaceIsWater surfaceNormal surfaceType swimInDepth ' + + 'switchableUnits switchAction switchCamera switchGesture switchLight switchMove ' + + 'synchronizedObjects synchronizedTriggers synchronizedWaypoints synchronizeObjectsAdd ' + + 'synchronizeObjectsRemove synchronizeTrigger synchronizeWaypoint systemChat systemOfUnits tan ' + + 'targetKnowledge targets targetsAggregate targetsQuery taskAlwaysVisible taskChildren ' + + 'taskCompleted taskCustomData taskDescription taskDestination taskHint taskMarkerOffset taskParent ' + + 'taskResult taskState taskType teamMember teamName teams teamSwitch teamSwitchEnabled teamType ' + + 'terminate terrainIntersect terrainIntersectASL terrainIntersectAtASL text textLog textLogFormat ' + + 'tg time timeMultiplier titleCut titleFadeOut titleObj titleRsc titleText toArray toFixed toLower ' + + 'toString toUpper triggerActivated triggerActivation triggerArea triggerAttachedVehicle ' + + 'triggerAttachObject triggerAttachVehicle triggerDynamicSimulation triggerStatements triggerText ' + + 'triggerTimeout triggerTimeoutCurrent triggerType turretLocal turretOwner turretUnit tvAdd tvClear ' + + 'tvCollapse tvCollapseAll tvCount tvCurSel tvData tvDelete tvExpand tvExpandAll tvPicture ' + + 'tvSetColor tvSetCurSel tvSetData tvSetPicture tvSetPictureColor tvSetPictureColorDisabled ' + + 'tvSetPictureColorSelected tvSetPictureRight tvSetPictureRightColor tvSetPictureRightColorDisabled ' + + 'tvSetPictureRightColorSelected tvSetText tvSetTooltip tvSetValue tvSort tvSortByValue tvText ' + + 'tvTooltip tvValue type typeName typeOf UAVControl uiNamespace uiSleep unassignCurator ' + + 'unassignItem unassignTeam unassignVehicle underwater uniform uniformContainer uniformItems ' + + 'uniformMagazines unitAddons unitAimPosition unitAimPositionVisual unitBackpack unitIsUAV unitPos ' + + 'unitReady unitRecoilCoefficient units unitsBelowHeight unlinkItem unlockAchievement ' + + 'unregisterTask updateDrawIcon updateMenuItem updateObjectTree useAISteeringComponent ' + + 'useAudioTimeForMoves userInputDisabled vectorAdd vectorCos vectorCrossProduct vectorDiff ' + + 'vectorDir vectorDirVisual vectorDistance vectorDistanceSqr vectorDotProduct vectorFromTo ' + + 'vectorMagnitude vectorMagnitudeSqr vectorModelToWorld vectorModelToWorldVisual vectorMultiply ' + + 'vectorNormalized vectorUp vectorUpVisual vectorWorldToModel vectorWorldToModelVisual vehicle ' + + 'vehicleCargoEnabled vehicleChat vehicleRadio vehicleReceiveRemoteTargets vehicleReportOwnPosition ' + + 'vehicleReportRemoteTargets vehicles vehicleVarName velocity velocityModelSpace verifySignature ' + + 'vest vestContainer vestItems vestMagazines viewDistance visibleCompass visibleGPS visibleMap ' + + 'visiblePosition visiblePositionASL visibleScoretable visibleWatch waves waypointAttachedObject ' + + 'waypointAttachedVehicle waypointAttachObject waypointAttachVehicle waypointBehaviour ' + + 'waypointCombatMode waypointCompletionRadius waypointDescription waypointForceBehaviour ' + + 'waypointFormation waypointHousePosition waypointLoiterRadius waypointLoiterType waypointName ' + + 'waypointPosition waypoints waypointScript waypointsEnabledUAV waypointShow waypointSpeed ' + + 'waypointStatements waypointTimeout waypointTimeoutCurrent waypointType waypointVisible ' + + 'weaponAccessories weaponAccessoriesCargo weaponCargo weaponDirection weaponInertia weaponLowered ' + + 'weapons weaponsItems weaponsItemsCargo weaponState weaponsTurret weightRTD WFSideText wind ', + literal: + 'blufor civilian configNull controlNull displayNull east endl false grpNull independent lineBreak ' + + 'locationNull nil objNull opfor pi resistance scriptNull sideAmbientLife sideEmpty sideLogic ' + + 'sideUnknown taskNull teamMemberNull true west' + }, + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.NUMBER_MODE, + VARIABLE, + FUNCTION, + STRINGS, + PREPROCESSOR + ], + illegal: /#|^\$ / + }; +} + +module.exports = sqf; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/sql.js b/claude-code-source/node_modules/highlight.js/lib/languages/sql.js new file mode 100644 index 00000000..18c2a43d --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/sql.js @@ -0,0 +1,699 @@ +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/** + * Any of the passed expresssions may match + * + * Creates a huge this | this | that | that match + * @param {(RegExp | string)[] } args + * @returns {string} + */ +function either(...args) { + const joined = '(' + args.map((x) => source(x)).join("|") + ")"; + return joined; +} + +/* + Language: SQL + Website: https://en.wikipedia.org/wiki/SQL + Category: common, database + */ + +function sql(hljs) { + const COMMENT_MODE = hljs.COMMENT('--', '$'); + const STRING = { + className: 'string', + variants: [ + { + begin: /'/, + end: /'/, + contains: [ + {begin: /''/ } + ] + } + ] + }; + const QUOTED_IDENTIFIER = { + begin: /"/, + end: /"/, + contains: [ { begin: /""/ } ] + }; + + const LITERALS = [ + "true", + "false", + // Not sure it's correct to call NULL literal, and clauses like IS [NOT] NULL look strange that way. + // "null", + "unknown" + ]; + + const MULTI_WORD_TYPES = [ + "double precision", + "large object", + "with timezone", + "without timezone" + ]; + + const TYPES = [ + 'bigint', + 'binary', + 'blob', + 'boolean', + 'char', + 'character', + 'clob', + 'date', + 'dec', + 'decfloat', + 'decimal', + 'float', + 'int', + 'integer', + 'interval', + 'nchar', + 'nclob', + 'national', + 'numeric', + 'real', + 'row', + 'smallint', + 'time', + 'timestamp', + 'varchar', + 'varying', // modifier (character varying) + 'varbinary' + ]; + + const NON_RESERVED_WORDS = [ + "add", + "asc", + "collation", + "desc", + "final", + "first", + "last", + "view" + ]; + + // https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#reserved-word + const RESERVED_WORDS = [ + "abs", + "acos", + "all", + "allocate", + "alter", + "and", + "any", + "are", + "array", + "array_agg", + "array_max_cardinality", + "as", + "asensitive", + "asin", + "asymmetric", + "at", + "atan", + "atomic", + "authorization", + "avg", + "begin", + "begin_frame", + "begin_partition", + "between", + "bigint", + "binary", + "blob", + "boolean", + "both", + "by", + "call", + "called", + "cardinality", + "cascaded", + "case", + "cast", + "ceil", + "ceiling", + "char", + "char_length", + "character", + "character_length", + "check", + "classifier", + "clob", + "close", + "coalesce", + "collate", + "collect", + "column", + "commit", + "condition", + "connect", + "constraint", + "contains", + "convert", + "copy", + "corr", + "corresponding", + "cos", + "cosh", + "count", + "covar_pop", + "covar_samp", + "create", + "cross", + "cube", + "cume_dist", + "current", + "current_catalog", + "current_date", + "current_default_transform_group", + "current_path", + "current_role", + "current_row", + "current_schema", + "current_time", + "current_timestamp", + "current_path", + "current_role", + "current_transform_group_for_type", + "current_user", + "cursor", + "cycle", + "date", + "day", + "deallocate", + "dec", + "decimal", + "decfloat", + "declare", + "default", + "define", + "delete", + "dense_rank", + "deref", + "describe", + "deterministic", + "disconnect", + "distinct", + "double", + "drop", + "dynamic", + "each", + "element", + "else", + "empty", + "end", + "end_frame", + "end_partition", + "end-exec", + "equals", + "escape", + "every", + "except", + "exec", + "execute", + "exists", + "exp", + "external", + "extract", + "false", + "fetch", + "filter", + "first_value", + "float", + "floor", + "for", + "foreign", + "frame_row", + "free", + "from", + "full", + "function", + "fusion", + "get", + "global", + "grant", + "group", + "grouping", + "groups", + "having", + "hold", + "hour", + "identity", + "in", + "indicator", + "initial", + "inner", + "inout", + "insensitive", + "insert", + "int", + "integer", + "intersect", + "intersection", + "interval", + "into", + "is", + "join", + "json_array", + "json_arrayagg", + "json_exists", + "json_object", + "json_objectagg", + "json_query", + "json_table", + "json_table_primitive", + "json_value", + "lag", + "language", + "large", + "last_value", + "lateral", + "lead", + "leading", + "left", + "like", + "like_regex", + "listagg", + "ln", + "local", + "localtime", + "localtimestamp", + "log", + "log10", + "lower", + "match", + "match_number", + "match_recognize", + "matches", + "max", + "member", + "merge", + "method", + "min", + "minute", + "mod", + "modifies", + "module", + "month", + "multiset", + "national", + "natural", + "nchar", + "nclob", + "new", + "no", + "none", + "normalize", + "not", + "nth_value", + "ntile", + "null", + "nullif", + "numeric", + "octet_length", + "occurrences_regex", + "of", + "offset", + "old", + "omit", + "on", + "one", + "only", + "open", + "or", + "order", + "out", + "outer", + "over", + "overlaps", + "overlay", + "parameter", + "partition", + "pattern", + "per", + "percent", + "percent_rank", + "percentile_cont", + "percentile_disc", + "period", + "portion", + "position", + "position_regex", + "power", + "precedes", + "precision", + "prepare", + "primary", + "procedure", + "ptf", + "range", + "rank", + "reads", + "real", + "recursive", + "ref", + "references", + "referencing", + "regr_avgx", + "regr_avgy", + "regr_count", + "regr_intercept", + "regr_r2", + "regr_slope", + "regr_sxx", + "regr_sxy", + "regr_syy", + "release", + "result", + "return", + "returns", + "revoke", + "right", + "rollback", + "rollup", + "row", + "row_number", + "rows", + "running", + "savepoint", + "scope", + "scroll", + "search", + "second", + "seek", + "select", + "sensitive", + "session_user", + "set", + "show", + "similar", + "sin", + "sinh", + "skip", + "smallint", + "some", + "specific", + "specifictype", + "sql", + "sqlexception", + "sqlstate", + "sqlwarning", + "sqrt", + "start", + "static", + "stddev_pop", + "stddev_samp", + "submultiset", + "subset", + "substring", + "substring_regex", + "succeeds", + "sum", + "symmetric", + "system", + "system_time", + "system_user", + "table", + "tablesample", + "tan", + "tanh", + "then", + "time", + "timestamp", + "timezone_hour", + "timezone_minute", + "to", + "trailing", + "translate", + "translate_regex", + "translation", + "treat", + "trigger", + "trim", + "trim_array", + "true", + "truncate", + "uescape", + "union", + "unique", + "unknown", + "unnest", + "update ", + "upper", + "user", + "using", + "value", + "values", + "value_of", + "var_pop", + "var_samp", + "varbinary", + "varchar", + "varying", + "versioning", + "when", + "whenever", + "where", + "width_bucket", + "window", + "with", + "within", + "without", + "year", + ]; + + // these are reserved words we have identified to be functions + // and should only be highlighted in a dispatch-like context + // ie, array_agg(...), etc. + const RESERVED_FUNCTIONS = [ + "abs", + "acos", + "array_agg", + "asin", + "atan", + "avg", + "cast", + "ceil", + "ceiling", + "coalesce", + "corr", + "cos", + "cosh", + "count", + "covar_pop", + "covar_samp", + "cume_dist", + "dense_rank", + "deref", + "element", + "exp", + "extract", + "first_value", + "floor", + "json_array", + "json_arrayagg", + "json_exists", + "json_object", + "json_objectagg", + "json_query", + "json_table", + "json_table_primitive", + "json_value", + "lag", + "last_value", + "lead", + "listagg", + "ln", + "log", + "log10", + "lower", + "max", + "min", + "mod", + "nth_value", + "ntile", + "nullif", + "percent_rank", + "percentile_cont", + "percentile_disc", + "position", + "position_regex", + "power", + "rank", + "regr_avgx", + "regr_avgy", + "regr_count", + "regr_intercept", + "regr_r2", + "regr_slope", + "regr_sxx", + "regr_sxy", + "regr_syy", + "row_number", + "sin", + "sinh", + "sqrt", + "stddev_pop", + "stddev_samp", + "substring", + "substring_regex", + "sum", + "tan", + "tanh", + "translate", + "translate_regex", + "treat", + "trim", + "trim_array", + "unnest", + "upper", + "value_of", + "var_pop", + "var_samp", + "width_bucket", + ]; + + // these functions can + const POSSIBLE_WITHOUT_PARENS = [ + "current_catalog", + "current_date", + "current_default_transform_group", + "current_path", + "current_role", + "current_schema", + "current_transform_group_for_type", + "current_user", + "session_user", + "system_time", + "system_user", + "current_time", + "localtime", + "current_timestamp", + "localtimestamp" + ]; + + // those exist to boost relevance making these very + // "SQL like" keyword combos worth +1 extra relevance + const COMBOS = [ + "create table", + "insert into", + "primary key", + "foreign key", + "not null", + "alter table", + "add constraint", + "grouping sets", + "on overflow", + "character set", + "respect nulls", + "ignore nulls", + "nulls first", + "nulls last", + "depth first", + "breadth first" + ]; + + const FUNCTIONS = RESERVED_FUNCTIONS; + + const KEYWORDS = [...RESERVED_WORDS, ...NON_RESERVED_WORDS].filter((keyword) => { + return !RESERVED_FUNCTIONS.includes(keyword); + }); + + const VARIABLE = { + className: "variable", + begin: /@[a-z0-9]+/, + }; + + const OPERATOR = { + className: "operator", + begin: /[-+*/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?/, + relevance: 0, + }; + + const FUNCTION_CALL = { + begin: concat(/\b/, either(...FUNCTIONS), /\s*\(/), + keywords: { + built_in: FUNCTIONS + } + }; + + // keywords with less than 3 letters are reduced in relevancy + function reduceRelevancy(list, {exceptions, when} = {}) { + const qualifyFn = when; + exceptions = exceptions || []; + return list.map((item) => { + if (item.match(/\|\d+$/) || exceptions.includes(item)) { + return item; + } else if (qualifyFn(item)) { + return `${item}|0`; + } else { + return item; + } + }); + } + + return { + name: 'SQL', + case_insensitive: true, + // does not include {} or HTML tags ` x.length < 3 }), + literal: LITERALS, + type: TYPES, + built_in: POSSIBLE_WITHOUT_PARENS + }, + contains: [ + { + begin: either(...COMBOS), + keywords: { + $pattern: /[\w\.]+/, + keyword: KEYWORDS.concat(COMBOS), + literal: LITERALS, + type: TYPES + }, + }, + { + className: "type", + begin: either(...MULTI_WORD_TYPES) + }, + FUNCTION_CALL, + VARIABLE, + STRING, + QUOTED_IDENTIFIER, + hljs.C_NUMBER_MODE, + hljs.C_BLOCK_COMMENT_MODE, + COMMENT_MODE, + OPERATOR + ] + }; +} + +module.exports = sql; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/sql_more.js b/claude-code-source/node_modules/highlight.js/lib/languages/sql_more.js new file mode 100644 index 00000000..a45a19ff --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/sql_more.js @@ -0,0 +1,183 @@ +/* + Language: SQL More (mix of MySQL, Oracle, etc) + Contributors: Nikolay Lisienko , Heiko August , Travis Odom , Vadimtro , Benjamin Auder + Website: https://en.wikipedia.org/wiki/SQL + Category: database + */ + +/* + +This is a preservation of the old bloated SQL grammar which includes pretty much +the kitchen sink because no one was keeping track of which keywords belong to +which databases. This is likely to be removed in the future. + +- Oracle SQL should be factored into it's own 3rd party grammar. +- MySQL should be factored out into it's own 3rd party grammar. + +*/ + +function sql_more(hljs) { + var COMMENT_MODE = hljs.COMMENT('--', '$'); + return { + name: 'SQL (more)', + aliases: ["mysql", "oracle"], + disableAutodetect: true, + case_insensitive: true, + illegal: /[<>{}*]/, + contains: [ + { + beginKeywords: + 'begin end start commit rollback savepoint lock alter create drop rename call ' + + 'delete do handler insert load replace select truncate update set show pragma grant ' + + 'merge describe use explain help declare prepare execute deallocate release ' + + 'unlock purge reset change stop analyze cache flush optimize repair kill ' + + 'install uninstall checksum restore check backup revoke comment values with', + end: /;/, endsWithParent: true, + keywords: { + $pattern: /[\w\.]+/, + keyword: + 'as abort abs absolute acc acce accep accept access accessed accessible account acos action activate add ' + + 'addtime admin administer advanced advise aes_decrypt aes_encrypt after agent aggregate ali alia alias ' + + 'all allocate allow alter always analyze ancillary and anti any anydata anydataset anyschema anytype apply ' + + 'archive archived archivelog are as asc ascii asin assembly assertion associate asynchronous at atan ' + + 'atn2 attr attri attrib attribu attribut attribute attributes audit authenticated authentication authid ' + + 'authors auto autoallocate autodblink autoextend automatic availability avg backup badfile basicfile ' + + 'before begin beginning benchmark between bfile bfile_base big bigfile bin binary_double binary_float ' + + 'binlog bit_and bit_count bit_length bit_or bit_xor bitmap blob_base block blocksize body both bound ' + + 'bucket buffer_cache buffer_pool build bulk by byte byteordermark bytes cache caching call calling cancel ' + + 'capacity cascade cascaded case cast catalog category ceil ceiling chain change changed char_base ' + + 'char_length character_length characters characterset charindex charset charsetform charsetid check ' + + 'checksum checksum_agg child choose chr chunk class cleanup clear client clob clob_base clone close ' + + 'cluster_id cluster_probability cluster_set clustering coalesce coercibility col collate collation ' + + 'collect colu colum column column_value columns columns_updated comment commit compact compatibility ' + + 'compiled complete composite_limit compound compress compute concat concat_ws concurrent confirm conn ' + + 'connec connect connect_by_iscycle connect_by_isleaf connect_by_root connect_time connection ' + + 'consider consistent constant constraint constraints constructor container content contents context ' + + 'contributors controlfile conv convert convert_tz corr corr_k corr_s corresponding corruption cos cost ' + + 'count count_big counted covar_pop covar_samp cpu_per_call cpu_per_session crc32 create creation ' + + 'critical cross cube cume_dist curdate current current_date current_time current_timestamp current_user ' + + 'cursor curtime customdatum cycle data database databases datafile datafiles datalength date_add ' + + 'date_cache date_format date_sub dateadd datediff datefromparts datename datepart datetime2fromparts ' + + 'day day_to_second dayname dayofmonth dayofweek dayofyear days db_role_change dbtimezone ddl deallocate ' + + 'declare decode decompose decrement decrypt deduplicate def defa defau defaul default defaults ' + + 'deferred defi defin define degrees delayed delegate delete delete_all delimited demand dense_rank ' + + 'depth dequeue des_decrypt des_encrypt des_key_file desc descr descri describ describe descriptor ' + + 'deterministic diagnostics difference dimension direct_load directory disable disable_all ' + + 'disallow disassociate discardfile disconnect diskgroup distinct distinctrow distribute distributed div ' + + 'do document domain dotnet double downgrade drop dumpfile duplicate duration each edition editionable ' + + 'editions element ellipsis else elsif elt empty enable enable_all enclosed encode encoding encrypt ' + + 'end end-exec endian enforced engine engines enqueue enterprise entityescaping eomonth error errors ' + + 'escaped evalname evaluate event eventdata events except exception exceptions exchange exclude excluding ' + + 'execu execut execute exempt exists exit exp expire explain explode export export_set extended extent external ' + + 'external_1 external_2 externally extract failed failed_login_attempts failover failure far fast ' + + 'feature_set feature_value fetch field fields file file_name_convert filesystem_like_logging final ' + + 'finish first first_value fixed flash_cache flashback floor flush following follows for forall force foreign ' + + 'form forma format found found_rows freelist freelists freepools fresh from from_base64 from_days ' + + 'ftp full function general generated get get_format get_lock getdate getutcdate global global_name ' + + 'globally go goto grant grants greatest group group_concat group_id grouping grouping_id groups ' + + 'gtid_subtract guarantee guard handler hash hashkeys having hea head headi headin heading heap help hex ' + + 'hierarchy high high_priority hosts hour hours http id ident_current ident_incr ident_seed identified ' + + 'identity idle_time if ifnull ignore iif ilike ilm immediate import in include including increment ' + + 'index indexes indexing indextype indicator indices inet6_aton inet6_ntoa inet_aton inet_ntoa infile ' + + 'initial initialized initially initrans inmemory inner innodb input insert install instance instantiable ' + + 'instr interface interleaved intersect into invalidate invisible is is_free_lock is_ipv4 is_ipv4_compat ' + + 'is_not is_not_null is_used_lock isdate isnull isolation iterate java join json json_exists ' + + 'keep keep_duplicates key keys kill language large last last_day last_insert_id last_value lateral lax lcase ' + + 'lead leading least leaves left len lenght length less level levels library like like2 like4 likec limit ' + + 'lines link list listagg little ln load load_file lob lobs local localtime localtimestamp locate ' + + 'locator lock locked log log10 log2 logfile logfiles logging logical logical_reads_per_call ' + + 'logoff logon logs long loop low low_priority lower lpad lrtrim ltrim main make_set makedate maketime ' + + 'managed management manual map mapping mask master master_pos_wait match matched materialized max ' + + 'maxextents maximize maxinstances maxlen maxlogfiles maxloghistory maxlogmembers maxsize maxtrans ' + + 'md5 measures median medium member memcompress memory merge microsecond mid migration min minextents ' + + 'minimum mining minus minute minutes minvalue missing mod mode model modification modify module monitoring month ' + + 'months mount move movement multiset mutex name name_const names nan national native natural nav nchar ' + + 'nclob nested never new newline next nextval no no_write_to_binlog noarchivelog noaudit nobadfile ' + + 'nocheck nocompress nocopy nocycle nodelay nodiscardfile noentityescaping noguarantee nokeep nologfile ' + + 'nomapping nomaxvalue nominimize nominvalue nomonitoring none noneditionable nonschema noorder ' + + 'nopr nopro noprom nopromp noprompt norely noresetlogs noreverse normal norowdependencies noschemacheck ' + + 'noswitch not nothing notice notnull notrim novalidate now nowait nth_value nullif nulls num numb numbe ' + + 'nvarchar nvarchar2 object ocicoll ocidate ocidatetime ociduration ociinterval ociloblocator ocinumber ' + + 'ociref ocirefcursor ocirowid ocistring ocitype oct octet_length of off offline offset oid oidindex old ' + + 'on online only opaque open operations operator optimal optimize option optionally or oracle oracle_date ' + + 'oradata ord ordaudio orddicom orddoc order ordimage ordinality ordvideo organization orlany orlvary ' + + 'out outer outfile outline output over overflow overriding package pad parallel parallel_enable ' + + 'parameters parent parse partial partition partitions pascal passing password password_grace_time ' + + 'password_lock_time password_reuse_max password_reuse_time password_verify_function patch path patindex ' + + 'pctincrease pctthreshold pctused pctversion percent percent_rank percentile_cont percentile_disc ' + + 'performance period period_add period_diff permanent physical pi pipe pipelined pivot pluggable plugin ' + + 'policy position post_transaction pow power pragma prebuilt precedes preceding precision prediction ' + + 'prediction_cost prediction_details prediction_probability prediction_set prepare present preserve ' + + 'prior priority private private_sga privileges procedural procedure procedure_analyze processlist ' + + 'profiles project prompt protection public publishingservername purge quarter query quick quiesce quota ' + + 'quotename radians raise rand range rank raw read reads readsize rebuild record records ' + + 'recover recovery recursive recycle redo reduced ref reference referenced references referencing refresh ' + + 'regexp_like register regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy ' + + 'reject rekey relational relative relaylog release release_lock relies_on relocate rely rem remainder rename ' + + 'repair repeat replace replicate replication required reset resetlogs resize resource respect restore ' + + 'restricted result result_cache resumable resume retention return returning returns reuse reverse revoke ' + + 'right rlike role roles rollback rolling rollup round row row_count rowdependencies rowid rownum rows ' + + 'rtrim rules safe salt sample save savepoint sb1 sb2 sb4 scan schema schemacheck scn scope scroll ' + + 'sdo_georaster sdo_topo_geometry search sec_to_time second seconds section securefile security seed segment select ' + + 'self semi sequence sequential serializable server servererror session session_user sessions_per_user set ' + + 'sets settings sha sha1 sha2 share shared shared_pool short show shrink shutdown si_averagecolor ' + + 'si_colorhistogram si_featurelist si_positionalcolor si_stillimage si_texture siblings sid sign sin ' + + 'size size_t sizes skip slave sleep smalldatetimefromparts smallfile snapshot some soname sort soundex ' + + 'source space sparse spfile split sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows ' + + 'sql_small_result sql_variant_property sqlcode sqldata sqlerror sqlname sqlstate sqrt square standalone ' + + 'standby start starting startup statement static statistics stats_binomial_test stats_crosstab ' + + 'stats_ks_test stats_mode stats_mw_test stats_one_way_anova stats_t_test_ stats_t_test_indep ' + + 'stats_t_test_one stats_t_test_paired stats_wsr_test status std stddev stddev_pop stddev_samp stdev ' + + 'stop storage store stored str str_to_date straight_join strcmp strict string struct stuff style subdate ' + + 'subpartition subpartitions substitutable substr substring subtime subtring_index subtype success sum ' + + 'suspend switch switchoffset switchover sync synchronous synonym sys sys_xmlagg sysasm sysaux sysdate ' + + 'sysdatetimeoffset sysdba sysoper system system_user sysutcdatetime table tables tablespace tablesample tan tdo ' + + 'template temporary terminated tertiary_weights test than then thread through tier ties time time_format ' + + 'time_zone timediff timefromparts timeout timestamp timestampadd timestampdiff timezone_abbr ' + + 'timezone_minute timezone_region to to_base64 to_date to_days to_seconds todatetimeoffset trace tracking ' + + 'transaction transactional translate translation treat trigger trigger_nestlevel triggers trim truncate ' + + 'try_cast try_convert try_parse type ub1 ub2 ub4 ucase unarchived unbounded uncompress ' + + 'under undo unhex unicode uniform uninstall union unique unix_timestamp unknown unlimited unlock unnest unpivot ' + + 'unrecoverable unsafe unsigned until untrusted unusable unused update updated upgrade upped upper upsert ' + + 'url urowid usable usage use use_stored_outlines user user_data user_resources users using utc_date ' + + 'utc_timestamp uuid uuid_short validate validate_password_strength validation valist value values var ' + + 'var_samp varcharc vari varia variab variabl variable variables variance varp varraw varrawc varray ' + + 'verify version versions view virtual visible void wait wallet warning warnings week weekday weekofyear ' + + 'wellformed when whene whenev wheneve whenever where while whitespace window with within without work wrapped ' + + 'xdb xml xmlagg xmlattributes xmlcast xmlcolattval xmlelement xmlexists xmlforest xmlindex xmlnamespaces ' + + 'xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltype xor year year_to_month years yearweek', + literal: + 'true false null unknown', + built_in: + 'array bigint binary bit blob bool boolean char character date dec decimal float int int8 integer interval number ' + + 'numeric real record serial serial8 smallint text time timestamp tinyint varchar varchar2 varying void' + }, + contains: [ + { + className: 'string', + begin: '\'', end: '\'', + contains: [{begin: '\'\''}] + }, + { + className: 'string', + begin: '"', end: '"', + contains: [{begin: '""'}] + }, + { + className: 'string', + begin: '`', end: '`' + }, + hljs.C_NUMBER_MODE, + hljs.C_BLOCK_COMMENT_MODE, + COMMENT_MODE, + hljs.HASH_COMMENT_MODE + ] + }, + hljs.C_BLOCK_COMMENT_MODE, + COMMENT_MODE, + hljs.HASH_COMMENT_MODE + ] + }; +} + +module.exports = sql_more; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/stan.js b/claude-code-source/node_modules/highlight.js/lib/languages/stan.js new file mode 100644 index 00000000..50c8bdf5 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/stan.js @@ -0,0 +1,548 @@ +/* +Language: Stan +Description: The Stan probabilistic programming language +Author: Jeffrey B. Arnold +Website: http://mc-stan.org/ +Category: scientific +*/ + +function stan(hljs) { + // variable names cannot conflict with block identifiers + const BLOCKS = [ + 'functions', + 'model', + 'data', + 'parameters', + 'quantities', + 'transformed', + 'generated' + ]; + const STATEMENTS = [ + 'for', + 'in', + 'if', + 'else', + 'while', + 'break', + 'continue', + 'return' + ]; + const SPECIAL_FUNCTIONS = [ + 'print', + 'reject', + 'increment_log_prob|10', + 'integrate_ode|10', + 'integrate_ode_rk45|10', + 'integrate_ode_bdf|10', + 'algebra_solver' + ]; + const VAR_TYPES = [ + 'int', + 'real', + 'vector', + 'ordered', + 'positive_ordered', + 'simplex', + 'unit_vector', + 'row_vector', + 'matrix', + 'cholesky_factor_corr|10', + 'cholesky_factor_cov|10', + 'corr_matrix|10', + 'cov_matrix|10', + 'void' + ]; + const FUNCTIONS = [ + 'Phi', + 'Phi_approx', + 'abs', + 'acos', + 'acosh', + 'algebra_solver', + 'append_array', + 'append_col', + 'append_row', + 'asin', + 'asinh', + 'atan', + 'atan2', + 'atanh', + 'bernoulli_cdf', + 'bernoulli_lccdf', + 'bernoulli_lcdf', + 'bernoulli_logit_lpmf', + 'bernoulli_logit_rng', + 'bernoulli_lpmf', + 'bernoulli_rng', + 'bessel_first_kind', + 'bessel_second_kind', + 'beta_binomial_cdf', + 'beta_binomial_lccdf', + 'beta_binomial_lcdf', + 'beta_binomial_lpmf', + 'beta_binomial_rng', + 'beta_cdf', + 'beta_lccdf', + 'beta_lcdf', + 'beta_lpdf', + 'beta_rng', + 'binary_log_loss', + 'binomial_cdf', + 'binomial_coefficient_log', + 'binomial_lccdf', + 'binomial_lcdf', + 'binomial_logit_lpmf', + 'binomial_lpmf', + 'binomial_rng', + 'block', + 'categorical_logit_lpmf', + 'categorical_logit_rng', + 'categorical_lpmf', + 'categorical_rng', + 'cauchy_cdf', + 'cauchy_lccdf', + 'cauchy_lcdf', + 'cauchy_lpdf', + 'cauchy_rng', + 'cbrt', + 'ceil', + 'chi_square_cdf', + 'chi_square_lccdf', + 'chi_square_lcdf', + 'chi_square_lpdf', + 'chi_square_rng', + 'cholesky_decompose', + 'choose', + 'col', + 'cols', + 'columns_dot_product', + 'columns_dot_self', + 'cos', + 'cosh', + 'cov_exp_quad', + 'crossprod', + 'csr_extract_u', + 'csr_extract_v', + 'csr_extract_w', + 'csr_matrix_times_vector', + 'csr_to_dense_matrix', + 'cumulative_sum', + 'determinant', + 'diag_matrix', + 'diag_post_multiply', + 'diag_pre_multiply', + 'diagonal', + 'digamma', + 'dims', + 'dirichlet_lpdf', + 'dirichlet_rng', + 'distance', + 'dot_product', + 'dot_self', + 'double_exponential_cdf', + 'double_exponential_lccdf', + 'double_exponential_lcdf', + 'double_exponential_lpdf', + 'double_exponential_rng', + 'e', + 'eigenvalues_sym', + 'eigenvectors_sym', + 'erf', + 'erfc', + 'exp', + 'exp2', + 'exp_mod_normal_cdf', + 'exp_mod_normal_lccdf', + 'exp_mod_normal_lcdf', + 'exp_mod_normal_lpdf', + 'exp_mod_normal_rng', + 'expm1', + 'exponential_cdf', + 'exponential_lccdf', + 'exponential_lcdf', + 'exponential_lpdf', + 'exponential_rng', + 'fabs', + 'falling_factorial', + 'fdim', + 'floor', + 'fma', + 'fmax', + 'fmin', + 'fmod', + 'frechet_cdf', + 'frechet_lccdf', + 'frechet_lcdf', + 'frechet_lpdf', + 'frechet_rng', + 'gamma_cdf', + 'gamma_lccdf', + 'gamma_lcdf', + 'gamma_lpdf', + 'gamma_p', + 'gamma_q', + 'gamma_rng', + 'gaussian_dlm_obs_lpdf', + 'get_lp', + 'gumbel_cdf', + 'gumbel_lccdf', + 'gumbel_lcdf', + 'gumbel_lpdf', + 'gumbel_rng', + 'head', + 'hypergeometric_lpmf', + 'hypergeometric_rng', + 'hypot', + 'inc_beta', + 'int_step', + 'integrate_ode', + 'integrate_ode_bdf', + 'integrate_ode_rk45', + 'inv', + 'inv_Phi', + 'inv_chi_square_cdf', + 'inv_chi_square_lccdf', + 'inv_chi_square_lcdf', + 'inv_chi_square_lpdf', + 'inv_chi_square_rng', + 'inv_cloglog', + 'inv_gamma_cdf', + 'inv_gamma_lccdf', + 'inv_gamma_lcdf', + 'inv_gamma_lpdf', + 'inv_gamma_rng', + 'inv_logit', + 'inv_sqrt', + 'inv_square', + 'inv_wishart_lpdf', + 'inv_wishart_rng', + 'inverse', + 'inverse_spd', + 'is_inf', + 'is_nan', + 'lbeta', + 'lchoose', + 'lgamma', + 'lkj_corr_cholesky_lpdf', + 'lkj_corr_cholesky_rng', + 'lkj_corr_lpdf', + 'lkj_corr_rng', + 'lmgamma', + 'lmultiply', + 'log', + 'log10', + 'log1m', + 'log1m_exp', + 'log1m_inv_logit', + 'log1p', + 'log1p_exp', + 'log2', + 'log_determinant', + 'log_diff_exp', + 'log_falling_factorial', + 'log_inv_logit', + 'log_mix', + 'log_rising_factorial', + 'log_softmax', + 'log_sum_exp', + 'logistic_cdf', + 'logistic_lccdf', + 'logistic_lcdf', + 'logistic_lpdf', + 'logistic_rng', + 'logit', + 'lognormal_cdf', + 'lognormal_lccdf', + 'lognormal_lcdf', + 'lognormal_lpdf', + 'lognormal_rng', + 'machine_precision', + 'matrix_exp', + 'max', + 'mdivide_left_spd', + 'mdivide_left_tri_low', + 'mdivide_right_spd', + 'mdivide_right_tri_low', + 'mean', + 'min', + 'modified_bessel_first_kind', + 'modified_bessel_second_kind', + 'multi_gp_cholesky_lpdf', + 'multi_gp_lpdf', + 'multi_normal_cholesky_lpdf', + 'multi_normal_cholesky_rng', + 'multi_normal_lpdf', + 'multi_normal_prec_lpdf', + 'multi_normal_rng', + 'multi_student_t_lpdf', + 'multi_student_t_rng', + 'multinomial_lpmf', + 'multinomial_rng', + 'multiply_log', + 'multiply_lower_tri_self_transpose', + 'neg_binomial_2_cdf', + 'neg_binomial_2_lccdf', + 'neg_binomial_2_lcdf', + 'neg_binomial_2_log_lpmf', + 'neg_binomial_2_log_rng', + 'neg_binomial_2_lpmf', + 'neg_binomial_2_rng', + 'neg_binomial_cdf', + 'neg_binomial_lccdf', + 'neg_binomial_lcdf', + 'neg_binomial_lpmf', + 'neg_binomial_rng', + 'negative_infinity', + 'normal_cdf', + 'normal_lccdf', + 'normal_lcdf', + 'normal_lpdf', + 'normal_rng', + 'not_a_number', + 'num_elements', + 'ordered_logistic_lpmf', + 'ordered_logistic_rng', + 'owens_t', + 'pareto_cdf', + 'pareto_lccdf', + 'pareto_lcdf', + 'pareto_lpdf', + 'pareto_rng', + 'pareto_type_2_cdf', + 'pareto_type_2_lccdf', + 'pareto_type_2_lcdf', + 'pareto_type_2_lpdf', + 'pareto_type_2_rng', + 'pi', + 'poisson_cdf', + 'poisson_lccdf', + 'poisson_lcdf', + 'poisson_log_lpmf', + 'poisson_log_rng', + 'poisson_lpmf', + 'poisson_rng', + 'positive_infinity', + 'pow', + 'print', + 'prod', + 'qr_Q', + 'qr_R', + 'quad_form', + 'quad_form_diag', + 'quad_form_sym', + 'rank', + 'rayleigh_cdf', + 'rayleigh_lccdf', + 'rayleigh_lcdf', + 'rayleigh_lpdf', + 'rayleigh_rng', + 'reject', + 'rep_array', + 'rep_matrix', + 'rep_row_vector', + 'rep_vector', + 'rising_factorial', + 'round', + 'row', + 'rows', + 'rows_dot_product', + 'rows_dot_self', + 'scaled_inv_chi_square_cdf', + 'scaled_inv_chi_square_lccdf', + 'scaled_inv_chi_square_lcdf', + 'scaled_inv_chi_square_lpdf', + 'scaled_inv_chi_square_rng', + 'sd', + 'segment', + 'sin', + 'singular_values', + 'sinh', + 'size', + 'skew_normal_cdf', + 'skew_normal_lccdf', + 'skew_normal_lcdf', + 'skew_normal_lpdf', + 'skew_normal_rng', + 'softmax', + 'sort_asc', + 'sort_desc', + 'sort_indices_asc', + 'sort_indices_desc', + 'sqrt', + 'sqrt2', + 'square', + 'squared_distance', + 'step', + 'student_t_cdf', + 'student_t_lccdf', + 'student_t_lcdf', + 'student_t_lpdf', + 'student_t_rng', + 'sub_col', + 'sub_row', + 'sum', + 'tail', + 'tan', + 'tanh', + 'target', + 'tcrossprod', + 'tgamma', + 'to_array_1d', + 'to_array_2d', + 'to_matrix', + 'to_row_vector', + 'to_vector', + 'trace', + 'trace_gen_quad_form', + 'trace_quad_form', + 'trigamma', + 'trunc', + 'uniform_cdf', + 'uniform_lccdf', + 'uniform_lcdf', + 'uniform_lpdf', + 'uniform_rng', + 'variance', + 'von_mises_lpdf', + 'von_mises_rng', + 'weibull_cdf', + 'weibull_lccdf', + 'weibull_lcdf', + 'weibull_lpdf', + 'weibull_rng', + 'wiener_lpdf', + 'wishart_lpdf', + 'wishart_rng' + ]; + const DISTRIBUTIONS = [ + 'bernoulli', + 'bernoulli_logit', + 'beta', + 'beta_binomial', + 'binomial', + 'binomial_logit', + 'categorical', + 'categorical_logit', + 'cauchy', + 'chi_square', + 'dirichlet', + 'double_exponential', + 'exp_mod_normal', + 'exponential', + 'frechet', + 'gamma', + 'gaussian_dlm_obs', + 'gumbel', + 'hypergeometric', + 'inv_chi_square', + 'inv_gamma', + 'inv_wishart', + 'lkj_corr', + 'lkj_corr_cholesky', + 'logistic', + 'lognormal', + 'multi_gp', + 'multi_gp_cholesky', + 'multi_normal', + 'multi_normal_cholesky', + 'multi_normal_prec', + 'multi_student_t', + 'multinomial', + 'neg_binomial', + 'neg_binomial_2', + 'neg_binomial_2_log', + 'normal', + 'ordered_logistic', + 'pareto', + 'pareto_type_2', + 'poisson', + 'poisson_log', + 'rayleigh', + 'scaled_inv_chi_square', + 'skew_normal', + 'student_t', + 'uniform', + 'von_mises', + 'weibull', + 'wiener', + 'wishart' + ]; + + return { + name: 'Stan', + aliases: [ 'stanfuncs' ], + keywords: { + $pattern: hljs.IDENT_RE, + title: BLOCKS, + keyword: STATEMENTS.concat(VAR_TYPES).concat(SPECIAL_FUNCTIONS), + built_in: FUNCTIONS + }, + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.COMMENT( + /#/, + /$/, + { + relevance: 0, + keywords: { + 'meta-keyword': 'include' + } + } + ), + hljs.COMMENT( + /\/\*/, + /\*\//, + { + relevance: 0, + // highlight doc strings mentioned in Stan reference + contains: [ + { + className: 'doctag', + begin: /@(return|param)/ + } + ] + } + ), + { + // hack: in range constraints, lower must follow "<" + begin: /<\s*lower\s*=/, + keywords: 'lower' + }, + { + // hack: in range constraints, upper must follow either , or < + // or + begin: /[<,]\s*upper\s*=/, + keywords: 'upper' + }, + { + className: 'keyword', + begin: /\btarget\s*\+=/, + relevance: 10 + }, + { + begin: '~\\s*(' + hljs.IDENT_RE + ')\\s*\\(', + keywords: DISTRIBUTIONS + }, + { + className: 'number', + variants: [ + { + begin: /\b\d+(?:\.\d*)?(?:[eE][+-]?\d+)?/ + }, + { + begin: /\.\d+(?:[eE][+-]?\d+)?\b/ + } + ], + relevance: 0 + }, + { + className: 'string', + begin: '"', + end: '"', + relevance: 0 + } + ] + }; +} + +module.exports = stan; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/stata.js b/claude-code-source/node_modules/highlight.js/lib/languages/stata.js new file mode 100644 index 00000000..7a9561d4 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/stata.js @@ -0,0 +1,60 @@ +/* +Language: Stata +Author: Brian Quistorff +Contributors: Drew McDonald +Description: Stata is a general-purpose statistical software package created in 1985 by StataCorp. +Website: https://en.wikipedia.org/wiki/Stata +Category: scientific +*/ + +/* + This is a fork and modification of Drew McDonald's file (https://github.com/drewmcdonald/stata-highlighting). I have also included a list of builtin commands from https://bugs.kde.org/show_bug.cgi?id=135646. +*/ + +function stata(hljs) { + return { + name: 'Stata', + aliases: [ + 'do', + 'ado' + ], + case_insensitive: true, + keywords: 'if else in foreach for forv forva forval forvalu forvalue forvalues by bys bysort xi quietly qui capture about ac ac_7 acprplot acprplot_7 adjust ado adopath adoupdate alpha ameans an ano anov anova anova_estat anova_terms anovadef aorder ap app appe appen append arch arch_dr arch_estat arch_p archlm areg areg_p args arima arima_dr arima_estat arima_p as asmprobit asmprobit_estat asmprobit_lf asmprobit_mfx__dlg asmprobit_p ass asse asser assert avplot avplot_7 avplots avplots_7 bcskew0 bgodfrey bias binreg bip0_lf biplot bipp_lf bipr_lf bipr_p biprobit bitest bitesti bitowt blogit bmemsize boot bootsamp bootstrap bootstrap_8 boxco_l boxco_p boxcox boxcox_6 boxcox_p bprobit br break brier bro brow brows browse brr brrstat bs bs_7 bsampl_w bsample bsample_7 bsqreg bstat bstat_7 bstat_8 bstrap bstrap_7 bubble bubbleplot ca ca_estat ca_p cabiplot camat canon canon_8 canon_8_p canon_estat canon_p cap caprojection capt captu captur capture cat cc cchart cchart_7 cci cd censobs_table centile cf char chdir checkdlgfiles checkestimationsample checkhlpfiles checksum chelp ci cii cl class classutil clear cli clis clist clo clog clog_lf clog_p clogi clogi_sw clogit clogit_lf clogit_p clogitp clogl_sw cloglog clonevar clslistarray cluster cluster_measures cluster_stop cluster_tree cluster_tree_8 clustermat cmdlog cnr cnre cnreg cnreg_p cnreg_sw cnsreg codebook collaps4 collapse colormult_nb colormult_nw compare compress conf confi confir confirm conren cons const constr constra constrai constrain constraint continue contract copy copyright copysource cor corc corr corr2data corr_anti corr_kmo corr_smc corre correl correla correlat correlate corrgram cou coun count cox cox_p cox_sw coxbase coxhaz coxvar cprplot cprplot_7 crc cret cretu cretur creturn cross cs cscript cscript_log csi ct ct_is ctset ctst_5 ctst_st cttost cumsp cumsp_7 cumul cusum cusum_7 cutil d|0 datasig datasign datasigna datasignat datasignatu datasignatur datasignature datetof db dbeta de dec deco decod decode deff des desc descr descri describ describe destring dfbeta dfgls dfuller di di_g dir dirstats dis discard disp disp_res disp_s displ displa display distinct do doe doed doedi doedit dotplot dotplot_7 dprobit drawnorm drop ds ds_util dstdize duplicates durbina dwstat dydx e|0 ed edi edit egen eivreg emdef en enc enco encod encode eq erase ereg ereg_lf ereg_p ereg_sw ereghet ereghet_glf ereghet_glf_sh ereghet_gp ereghet_ilf ereghet_ilf_sh ereghet_ip eret eretu eretur ereturn err erro error esize est est_cfexist est_cfname est_clickable est_expand est_hold est_table est_unhold est_unholdok estat estat_default estat_summ estat_vce_only esti estimates etodow etof etomdy ex exi exit expand expandcl fac fact facto factor factor_estat factor_p factor_pca_rotated factor_rotate factormat fcast fcast_compute fcast_graph fdades fdadesc fdadescr fdadescri fdadescrib fdadescribe fdasav fdasave fdause fh_st file open file read file close file filefilter fillin find_hlp_file findfile findit findit_7 fit fl fli flis flist for5_0 forest forestplot form forma format fpredict frac_154 frac_adj frac_chk frac_cox frac_ddp frac_dis frac_dv frac_in frac_mun frac_pp frac_pq frac_pv frac_wgt frac_xo fracgen fracplot fracplot_7 fracpoly fracpred fron_ex fron_hn fron_p fron_tn fron_tn2 frontier ftodate ftoe ftomdy ftowdate funnel funnelplot g|0 gamhet_glf gamhet_gp gamhet_ilf gamhet_ip gamma gamma_d2 gamma_p gamma_sw gammahet gdi_hexagon gdi_spokes ge gen gene gener genera generat generate genrank genstd genvmean gettoken gl gladder gladder_7 glim_l01 glim_l02 glim_l03 glim_l04 glim_l05 glim_l06 glim_l07 glim_l08 glim_l09 glim_l10 glim_l11 glim_l12 glim_lf glim_mu glim_nw1 glim_nw2 glim_nw3 glim_p glim_v1 glim_v2 glim_v3 glim_v4 glim_v5 glim_v6 glim_v7 glm glm_6 glm_p glm_sw glmpred glo glob globa global glogit glogit_8 glogit_p gmeans gnbre_lf gnbreg gnbreg_5 gnbreg_p gomp_lf gompe_sw gomper_p gompertz gompertzhet gomphet_glf gomphet_glf_sh gomphet_gp gomphet_ilf gomphet_ilf_sh gomphet_ip gphdot gphpen gphprint gprefs gprobi_p gprobit gprobit_8 gr gr7 gr_copy gr_current gr_db gr_describe gr_dir gr_draw gr_draw_replay gr_drop gr_edit gr_editviewopts gr_example gr_example2 gr_export gr_print gr_qscheme gr_query gr_read gr_rename gr_replay gr_save gr_set gr_setscheme gr_table gr_undo gr_use graph graph7 grebar greigen greigen_7 greigen_8 grmeanby grmeanby_7 gs_fileinfo gs_filetype gs_graphinfo gs_stat gsort gwood h|0 hadimvo hareg hausman haver he heck_d2 heckma_p heckman heckp_lf heckpr_p heckprob hel help hereg hetpr_lf hetpr_p hetprob hettest hexdump hilite hist hist_7 histogram hlogit hlu hmeans hotel hotelling hprobit hreg hsearch icd9 icd9_ff icd9p iis impute imtest inbase include inf infi infil infile infix inp inpu input ins insheet insp inspe inspec inspect integ inten intreg intreg_7 intreg_p intrg2_ll intrg_ll intrg_ll2 ipolate iqreg ir irf irf_create irfm iri is_svy is_svysum isid istdize ivprob_1_lf ivprob_lf ivprobit ivprobit_p ivreg ivreg_footnote ivtob_1_lf ivtob_lf ivtobit ivtobit_p jackknife jacknife jknife jknife_6 jknife_8 jkstat joinby kalarma1 kap kap_3 kapmeier kappa kapwgt kdensity kdensity_7 keep ksm ksmirnov ktau kwallis l|0 la lab labbe labbeplot labe label labelbook ladder levels levelsof leverage lfit lfit_p li lincom line linktest lis list lloghet_glf lloghet_glf_sh lloghet_gp lloghet_ilf lloghet_ilf_sh lloghet_ip llogi_sw llogis_p llogist llogistic llogistichet lnorm_lf lnorm_sw lnorma_p lnormal lnormalhet lnormhet_glf lnormhet_glf_sh lnormhet_gp lnormhet_ilf lnormhet_ilf_sh lnormhet_ip lnskew0 loadingplot loc loca local log logi logis_lf logistic logistic_p logit logit_estat logit_p loglogs logrank loneway lookfor lookup lowess lowess_7 lpredict lrecomp lroc lroc_7 lrtest ls lsens lsens_7 lsens_x lstat ltable ltable_7 ltriang lv lvr2plot lvr2plot_7 m|0 ma mac macr macro makecns man manova manova_estat manova_p manovatest mantel mark markin markout marksample mat mat_capp mat_order mat_put_rr mat_rapp mata mata_clear mata_describe mata_drop mata_matdescribe mata_matsave mata_matuse mata_memory mata_mlib mata_mosave mata_rename mata_which matalabel matcproc matlist matname matr matri matrix matrix_input__dlg matstrik mcc mcci md0_ md1_ md1debug_ md2_ md2debug_ mds mds_estat mds_p mdsconfig mdslong mdsmat mdsshepard mdytoe mdytof me_derd mean means median memory memsize menl meqparse mer merg merge meta mfp mfx mhelp mhodds minbound mixed_ll mixed_ll_reparm mkassert mkdir mkmat mkspline ml ml_5 ml_adjs ml_bhhhs ml_c_d ml_check ml_clear ml_cnt ml_debug ml_defd ml_e0 ml_e0_bfgs ml_e0_cycle ml_e0_dfp ml_e0i ml_e1 ml_e1_bfgs ml_e1_bhhh ml_e1_cycle ml_e1_dfp ml_e2 ml_e2_cycle ml_ebfg0 ml_ebfr0 ml_ebfr1 ml_ebh0q ml_ebhh0 ml_ebhr0 ml_ebr0i ml_ecr0i ml_edfp0 ml_edfr0 ml_edfr1 ml_edr0i ml_eds ml_eer0i ml_egr0i ml_elf ml_elf_bfgs ml_elf_bhhh ml_elf_cycle ml_elf_dfp ml_elfi ml_elfs ml_enr0i ml_enrr0 ml_erdu0 ml_erdu0_bfgs ml_erdu0_bhhh ml_erdu0_bhhhq ml_erdu0_cycle ml_erdu0_dfp ml_erdu0_nrbfgs ml_exde ml_footnote ml_geqnr ml_grad0 ml_graph ml_hbhhh ml_hd0 ml_hold ml_init ml_inv ml_log ml_max ml_mlout ml_mlout_8 ml_model ml_nb0 ml_opt ml_p ml_plot ml_query ml_rdgrd ml_repor ml_s_e ml_score ml_searc ml_technique ml_unhold mleval mlf_ mlmatbysum mlmatsum mlog mlogi mlogit mlogit_footnote mlogit_p mlopts mlsum mlvecsum mnl0_ mor more mov move mprobit mprobit_lf mprobit_p mrdu0_ mrdu1_ mvdecode mvencode mvreg mvreg_estat n|0 nbreg nbreg_al nbreg_lf nbreg_p nbreg_sw nestreg net newey newey_7 newey_p news nl nl_7 nl_9 nl_9_p nl_p nl_p_7 nlcom nlcom_p nlexp2 nlexp2_7 nlexp2a nlexp2a_7 nlexp3 nlexp3_7 nlgom3 nlgom3_7 nlgom4 nlgom4_7 nlinit nllog3 nllog3_7 nllog4 nllog4_7 nlog_rd nlogit nlogit_p nlogitgen nlogittree nlpred no nobreak noi nois noisi noisil noisily note notes notes_dlg nptrend numlabel numlist odbc old_ver olo olog ologi ologi_sw ologit ologit_p ologitp on one onew onewa oneway op_colnm op_comp op_diff op_inv op_str opr opro oprob oprob_sw oprobi oprobi_p oprobit oprobitp opts_exclusive order orthog orthpoly ou out outf outfi outfil outfile outs outsh outshe outshee outsheet ovtest pac pac_7 palette parse parse_dissim pause pca pca_8 pca_display pca_estat pca_p pca_rotate pcamat pchart pchart_7 pchi pchi_7 pcorr pctile pentium pergram pergram_7 permute permute_8 personal peto_st pkcollapse pkcross pkequiv pkexamine pkexamine_7 pkshape pksumm pksumm_7 pl plo plot plugin pnorm pnorm_7 poisgof poiss_lf poiss_sw poisso_p poisson poisson_estat post postclose postfile postutil pperron pr prais prais_e prais_e2 prais_p predict predictnl preserve print pro prob probi probit probit_estat probit_p proc_time procoverlay procrustes procrustes_estat procrustes_p profiler prog progr progra program prop proportion prtest prtesti pwcorr pwd q\\s qby qbys qchi qchi_7 qladder qladder_7 qnorm qnorm_7 qqplot qqplot_7 qreg qreg_c qreg_p qreg_sw qu quadchk quantile quantile_7 que quer query range ranksum ratio rchart rchart_7 rcof recast reclink recode reg reg3 reg3_p regdw regr regre regre_p2 regres regres_p regress regress_estat regriv_p remap ren rena renam rename renpfix repeat replace report reshape restore ret retu retur return rm rmdir robvar roccomp roccomp_7 roccomp_8 rocf_lf rocfit rocfit_8 rocgold rocplot rocplot_7 roctab roctab_7 rolling rologit rologit_p rot rota rotat rotate rotatemat rreg rreg_p ru run runtest rvfplot rvfplot_7 rvpplot rvpplot_7 sa safesum sample sampsi sav save savedresults saveold sc sca scal scala scalar scatter scm_mine sco scob_lf scob_p scobi_sw scobit scor score scoreplot scoreplot_help scree screeplot screeplot_help sdtest sdtesti se search separate seperate serrbar serrbar_7 serset set set_defaults sfrancia sh she shel shell shewhart shewhart_7 signestimationsample signrank signtest simul simul_7 simulate simulate_8 sktest sleep slogit slogit_d2 slogit_p smooth snapspan so sor sort spearman spikeplot spikeplot_7 spikeplt spline_x split sqreg sqreg_p sret sretu sretur sreturn ssc st st_ct st_hc st_hcd st_hcd_sh st_is st_issys st_note st_promo st_set st_show st_smpl st_subid stack statsby statsby_8 stbase stci stci_7 stcox stcox_estat stcox_fr stcox_fr_ll stcox_p stcox_sw stcoxkm stcoxkm_7 stcstat stcurv stcurve stcurve_7 stdes stem stepwise stereg stfill stgen stir stjoin stmc stmh stphplot stphplot_7 stphtest stphtest_7 stptime strate strate_7 streg streg_sw streset sts sts_7 stset stsplit stsum sttocc sttoct stvary stweib su suest suest_8 sum summ summa summar summari summariz summarize sunflower sureg survcurv survsum svar svar_p svmat svy svy_disp svy_dreg svy_est svy_est_7 svy_estat svy_get svy_gnbreg_p svy_head svy_header svy_heckman_p svy_heckprob_p svy_intreg_p svy_ivreg_p svy_logistic_p svy_logit_p svy_mlogit_p svy_nbreg_p svy_ologit_p svy_oprobit_p svy_poisson_p svy_probit_p svy_regress_p svy_sub svy_sub_7 svy_x svy_x_7 svy_x_p svydes svydes_8 svygen svygnbreg svyheckman svyheckprob svyintreg svyintreg_7 svyintrg svyivreg svylc svylog_p svylogit svymarkout svymarkout_8 svymean svymlog svymlogit svynbreg svyolog svyologit svyoprob svyoprobit svyopts svypois svypois_7 svypoisson svyprobit svyprobt svyprop svyprop_7 svyratio svyreg svyreg_p svyregress svyset svyset_7 svyset_8 svytab svytab_7 svytest svytotal sw sw_8 swcnreg swcox swereg swilk swlogis swlogit swologit swoprbt swpois swprobit swqreg swtobit swweib symmetry symmi symplot symplot_7 syntax sysdescribe sysdir sysuse szroeter ta tab tab1 tab2 tab_or tabd tabdi tabdis tabdisp tabi table tabodds tabodds_7 tabstat tabu tabul tabula tabulat tabulate te tempfile tempname tempvar tes test testnl testparm teststd tetrachoric time_it timer tis tob tobi tobit tobit_p tobit_sw token tokeni tokeniz tokenize tostring total translate translator transmap treat_ll treatr_p treatreg trim trimfill trnb_cons trnb_mean trpoiss_d2 trunc_ll truncr_p truncreg tsappend tset tsfill tsline tsline_ex tsreport tsrevar tsrline tsset tssmooth tsunab ttest ttesti tut_chk tut_wait tutorial tw tware_st two twoway twoway__fpfit_serset twoway__function_gen twoway__histogram_gen twoway__ipoint_serset twoway__ipoints_serset twoway__kdensity_gen twoway__lfit_serset twoway__normgen_gen twoway__pci_serset twoway__qfit_serset twoway__scatteri_serset twoway__sunflower_gen twoway_ksm_serset ty typ type typeof u|0 unab unabbrev unabcmd update us use uselabel var var_mkcompanion var_p varbasic varfcast vargranger varirf varirf_add varirf_cgraph varirf_create varirf_ctable varirf_describe varirf_dir varirf_drop varirf_erase varirf_graph varirf_ograph varirf_rename varirf_set varirf_table varlist varlmar varnorm varsoc varstable varstable_w varstable_w2 varwle vce vec vec_fevd vec_mkphi vec_p vec_p_w vecirf_create veclmar veclmar_w vecnorm vecnorm_w vecrank vecstable verinst vers versi versio version view viewsource vif vwls wdatetof webdescribe webseek webuse weib1_lf weib2_lf weib_lf weib_lf0 weibhet_glf weibhet_glf_sh weibhet_glfa weibhet_glfa_sh weibhet_gp weibhet_ilf weibhet_ilf_sh weibhet_ilfa weibhet_ilfa_sh weibhet_ip weibu_sw weibul_p weibull weibull_c weibull_s weibullhet wh whelp whi which whil while wilc_st wilcoxon win wind windo window winexec wntestb wntestb_7 wntestq xchart xchart_7 xcorr xcorr_7 xi xi_6 xmlsav xmlsave xmluse xpose xsh xshe xshel xshell xt_iis xt_tis xtab_p xtabond xtbin_p xtclog xtcloglog xtcloglog_8 xtcloglog_d2 xtcloglog_pa_p xtcloglog_re_p xtcnt_p xtcorr xtdata xtdes xtfront_p xtfrontier xtgee xtgee_elink xtgee_estat xtgee_makeivar xtgee_p xtgee_plink xtgls xtgls_p xthaus xthausman xtht_p xthtaylor xtile xtint_p xtintreg xtintreg_8 xtintreg_d2 xtintreg_p xtivp_1 xtivp_2 xtivreg xtline xtline_ex xtlogit xtlogit_8 xtlogit_d2 xtlogit_fe_p xtlogit_pa_p xtlogit_re_p xtmixed xtmixed_estat xtmixed_p xtnb_fe xtnb_lf xtnbreg xtnbreg_pa_p xtnbreg_refe_p xtpcse xtpcse_p xtpois xtpoisson xtpoisson_d2 xtpoisson_pa_p xtpoisson_refe_p xtpred xtprobit xtprobit_8 xtprobit_d2 xtprobit_re_p xtps_fe xtps_lf xtps_ren xtps_ren_8 xtrar_p xtrc xtrc_p xtrchh xtrefe_p xtreg xtreg_be xtreg_fe xtreg_ml xtreg_pa_p xtreg_re xtregar xtrere_p xtset xtsf_ll xtsf_llti xtsum xttab xttest0 xttobit xttobit_8 xttobit_p xttrans yx yxview__barlike_draw yxview_area_draw yxview_bar_draw yxview_dot_draw yxview_dropline_draw yxview_function_draw yxview_iarrow_draw yxview_ilabels_draw yxview_normal_draw yxview_pcarrow_draw yxview_pcbarrow_draw yxview_pccapsym_draw yxview_pcscatter_draw yxview_pcspike_draw yxview_rarea_draw yxview_rbar_draw yxview_rbarm_draw yxview_rcap_draw yxview_rcapsym_draw yxview_rconnected_draw yxview_rline_draw yxview_rscatter_draw yxview_rspike_draw yxview_spike_draw yxview_sunflower_draw zap_s zinb zinb_llf zinb_plf zip zip_llf zip_p zip_plf zt_ct_5 zt_hc_5 zt_hcd_5 zt_is_5 zt_iss_5 zt_sho_5 zt_smp_5 ztbase_5 ztcox_5 ztdes_5 ztereg_5 ztfill_5 ztgen_5 ztir_5 ztjoin_5 ztnb ztnb_p ztp ztp_p zts_5 ztset_5 ztspli_5 ztsum_5 zttoct_5 ztvary_5 ztweib_5', + contains: [ + { + className: 'symbol', + begin: /`[a-zA-Z0-9_]+'/ + }, + { + className: 'variable', + begin: /\$\{?[a-zA-Z0-9_]+\}?/ + }, + { + className: 'string', + variants: [ + { + begin: '`"[^\r\n]*?"\'' + }, + { + begin: '"[^\r\n"]*"' + } + ] + }, + + { + className: 'built_in', + variants: [ + { + begin: '\\b(abs|acos|asin|atan|atan2|atanh|ceil|cloglog|comb|cos|digamma|exp|floor|invcloglog|invlogit|ln|lnfact|lnfactorial|lngamma|log|log10|max|min|mod|reldif|round|sign|sin|sqrt|sum|tan|tanh|trigamma|trunc|betaden|Binomial|binorm|binormal|chi2|chi2tail|dgammapda|dgammapdada|dgammapdadx|dgammapdx|dgammapdxdx|F|Fden|Ftail|gammaden|gammap|ibeta|invbinomial|invchi2|invchi2tail|invF|invFtail|invgammap|invibeta|invnchi2|invnFtail|invnibeta|invnorm|invnormal|invttail|nbetaden|nchi2|nFden|nFtail|nibeta|norm|normal|normalden|normd|npnchi2|tden|ttail|uniform|abbrev|char|index|indexnot|length|lower|ltrim|match|plural|proper|real|regexm|regexr|regexs|reverse|rtrim|string|strlen|strlower|strltrim|strmatch|strofreal|strpos|strproper|strreverse|strrtrim|strtrim|strupper|subinstr|subinword|substr|trim|upper|word|wordcount|_caller|autocode|byteorder|chop|clip|cond|e|epsdouble|epsfloat|group|inlist|inrange|irecode|matrix|maxbyte|maxdouble|maxfloat|maxint|maxlong|mi|minbyte|mindouble|minfloat|minint|minlong|missing|r|recode|replay|return|s|scalar|d|date|day|dow|doy|halfyear|mdy|month|quarter|week|year|d|daily|dofd|dofh|dofm|dofq|dofw|dofy|h|halfyearly|hofd|m|mofd|monthly|q|qofd|quarterly|tin|twithin|w|weekly|wofd|y|yearly|yh|ym|yofd|yq|yw|cholesky|colnumb|colsof|corr|det|diag|diag0cnt|el|get|hadamard|I|inv|invsym|issym|issymmetric|J|matmissing|matuniform|mreldif|nullmat|rownumb|rowsof|sweep|syminv|trace|vec|vecdiag)(?=\\()' + } + ] + }, + + hljs.COMMENT('^[ \t]*\\*.*$', false), + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE + ] + }; +} + +module.exports = stata; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/step21.js b/claude-code-source/node_modules/highlight.js/lib/languages/step21.js new file mode 100644 index 00000000..09fc2ba1 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/step21.js @@ -0,0 +1,66 @@ +/* +Language: STEP Part 21 +Contributors: Adam Joseph Cook +Description: Syntax highlighter for STEP Part 21 files (ISO 10303-21). +Website: https://en.wikipedia.org/wiki/ISO_10303-21 +*/ + +function step21(hljs) { + const STEP21_IDENT_RE = '[A-Z_][A-Z0-9_.]*'; + const STEP21_KEYWORDS = { + $pattern: STEP21_IDENT_RE, + keyword: 'HEADER ENDSEC DATA' + }; + const STEP21_START = { + className: 'meta', + begin: 'ISO-10303-21;', + relevance: 10 + }; + const STEP21_CLOSE = { + className: 'meta', + begin: 'END-ISO-10303-21;', + relevance: 10 + }; + + return { + name: 'STEP Part 21', + aliases: [ + 'p21', + 'step', + 'stp' + ], + case_insensitive: true, // STEP 21 is case insensitive in theory, in practice all non-comments are capitalized. + keywords: STEP21_KEYWORDS, + contains: [ + STEP21_START, + STEP21_CLOSE, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.COMMENT('/\\*\\*!', '\\*/'), + hljs.C_NUMBER_MODE, + hljs.inherit(hljs.APOS_STRING_MODE, { + illegal: null + }), + hljs.inherit(hljs.QUOTE_STRING_MODE, { + illegal: null + }), + { + className: 'string', + begin: "'", + end: "'" + }, + { + className: 'symbol', + variants: [ + { + begin: '#', + end: '\\d+', + illegal: '\\W' + } + ] + } + ] + }; +} + +module.exports = step21; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/stylus.js b/claude-code-source/node_modules/highlight.js/lib/languages/stylus.js new file mode 100644 index 00000000..78448fc7 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/stylus.js @@ -0,0 +1,609 @@ +const MODES = (hljs) => { + return { + IMPORTANT: { + className: 'meta', + begin: '!important' + }, + HEXCOLOR: { + className: 'number', + begin: '#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})' + }, + ATTRIBUTE_SELECTOR_MODE: { + className: 'selector-attr', + begin: /\[/, + end: /\]/, + illegal: '$', + contains: [ + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE + ] + } + }; +}; + +const TAGS = [ + 'a', + 'abbr', + 'address', + 'article', + 'aside', + 'audio', + 'b', + 'blockquote', + 'body', + 'button', + 'canvas', + 'caption', + 'cite', + 'code', + 'dd', + 'del', + 'details', + 'dfn', + 'div', + 'dl', + 'dt', + 'em', + 'fieldset', + 'figcaption', + 'figure', + 'footer', + 'form', + 'h1', + 'h2', + 'h3', + 'h4', + 'h5', + 'h6', + 'header', + 'hgroup', + 'html', + 'i', + 'iframe', + 'img', + 'input', + 'ins', + 'kbd', + 'label', + 'legend', + 'li', + 'main', + 'mark', + 'menu', + 'nav', + 'object', + 'ol', + 'p', + 'q', + 'quote', + 'samp', + 'section', + 'span', + 'strong', + 'summary', + 'sup', + 'table', + 'tbody', + 'td', + 'textarea', + 'tfoot', + 'th', + 'thead', + 'time', + 'tr', + 'ul', + 'var', + 'video' +]; + +const MEDIA_FEATURES = [ + 'any-hover', + 'any-pointer', + 'aspect-ratio', + 'color', + 'color-gamut', + 'color-index', + 'device-aspect-ratio', + 'device-height', + 'device-width', + 'display-mode', + 'forced-colors', + 'grid', + 'height', + 'hover', + 'inverted-colors', + 'monochrome', + 'orientation', + 'overflow-block', + 'overflow-inline', + 'pointer', + 'prefers-color-scheme', + 'prefers-contrast', + 'prefers-reduced-motion', + 'prefers-reduced-transparency', + 'resolution', + 'scan', + 'scripting', + 'update', + 'width', + // TODO: find a better solution? + 'min-width', + 'max-width', + 'min-height', + 'max-height' +]; + +// https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes +const PSEUDO_CLASSES = [ + 'active', + 'any-link', + 'blank', + 'checked', + 'current', + 'default', + 'defined', + 'dir', // dir() + 'disabled', + 'drop', + 'empty', + 'enabled', + 'first', + 'first-child', + 'first-of-type', + 'fullscreen', + 'future', + 'focus', + 'focus-visible', + 'focus-within', + 'has', // has() + 'host', // host or host() + 'host-context', // host-context() + 'hover', + 'indeterminate', + 'in-range', + 'invalid', + 'is', // is() + 'lang', // lang() + 'last-child', + 'last-of-type', + 'left', + 'link', + 'local-link', + 'not', // not() + 'nth-child', // nth-child() + 'nth-col', // nth-col() + 'nth-last-child', // nth-last-child() + 'nth-last-col', // nth-last-col() + 'nth-last-of-type', //nth-last-of-type() + 'nth-of-type', //nth-of-type() + 'only-child', + 'only-of-type', + 'optional', + 'out-of-range', + 'past', + 'placeholder-shown', + 'read-only', + 'read-write', + 'required', + 'right', + 'root', + 'scope', + 'target', + 'target-within', + 'user-invalid', + 'valid', + 'visited', + 'where' // where() +]; + +// https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements +const PSEUDO_ELEMENTS = [ + 'after', + 'backdrop', + 'before', + 'cue', + 'cue-region', + 'first-letter', + 'first-line', + 'grammar-error', + 'marker', + 'part', + 'placeholder', + 'selection', + 'slotted', + 'spelling-error' +]; + +const ATTRIBUTES = [ + 'align-content', + 'align-items', + 'align-self', + 'animation', + 'animation-delay', + 'animation-direction', + 'animation-duration', + 'animation-fill-mode', + 'animation-iteration-count', + 'animation-name', + 'animation-play-state', + 'animation-timing-function', + 'auto', + 'backface-visibility', + 'background', + 'background-attachment', + 'background-clip', + 'background-color', + 'background-image', + 'background-origin', + 'background-position', + 'background-repeat', + 'background-size', + 'border', + 'border-bottom', + 'border-bottom-color', + 'border-bottom-left-radius', + 'border-bottom-right-radius', + 'border-bottom-style', + 'border-bottom-width', + 'border-collapse', + 'border-color', + 'border-image', + 'border-image-outset', + 'border-image-repeat', + 'border-image-slice', + 'border-image-source', + 'border-image-width', + 'border-left', + 'border-left-color', + 'border-left-style', + 'border-left-width', + 'border-radius', + 'border-right', + 'border-right-color', + 'border-right-style', + 'border-right-width', + 'border-spacing', + 'border-style', + 'border-top', + 'border-top-color', + 'border-top-left-radius', + 'border-top-right-radius', + 'border-top-style', + 'border-top-width', + 'border-width', + 'bottom', + 'box-decoration-break', + 'box-shadow', + 'box-sizing', + 'break-after', + 'break-before', + 'break-inside', + 'caption-side', + 'clear', + 'clip', + 'clip-path', + 'color', + 'column-count', + 'column-fill', + 'column-gap', + 'column-rule', + 'column-rule-color', + 'column-rule-style', + 'column-rule-width', + 'column-span', + 'column-width', + 'columns', + 'content', + 'counter-increment', + 'counter-reset', + 'cursor', + 'direction', + 'display', + 'empty-cells', + 'filter', + 'flex', + 'flex-basis', + 'flex-direction', + 'flex-flow', + 'flex-grow', + 'flex-shrink', + 'flex-wrap', + 'float', + 'font', + 'font-display', + 'font-family', + 'font-feature-settings', + 'font-kerning', + 'font-language-override', + 'font-size', + 'font-size-adjust', + 'font-smoothing', + 'font-stretch', + 'font-style', + 'font-variant', + 'font-variant-ligatures', + 'font-variation-settings', + 'font-weight', + 'height', + 'hyphens', + 'icon', + 'image-orientation', + 'image-rendering', + 'image-resolution', + 'ime-mode', + 'inherit', + 'initial', + 'justify-content', + 'left', + 'letter-spacing', + 'line-height', + 'list-style', + 'list-style-image', + 'list-style-position', + 'list-style-type', + 'margin', + 'margin-bottom', + 'margin-left', + 'margin-right', + 'margin-top', + 'marks', + 'mask', + 'max-height', + 'max-width', + 'min-height', + 'min-width', + 'nav-down', + 'nav-index', + 'nav-left', + 'nav-right', + 'nav-up', + 'none', + 'normal', + 'object-fit', + 'object-position', + 'opacity', + 'order', + 'orphans', + 'outline', + 'outline-color', + 'outline-offset', + 'outline-style', + 'outline-width', + 'overflow', + 'overflow-wrap', + 'overflow-x', + 'overflow-y', + 'padding', + 'padding-bottom', + 'padding-left', + 'padding-right', + 'padding-top', + 'page-break-after', + 'page-break-before', + 'page-break-inside', + 'perspective', + 'perspective-origin', + 'pointer-events', + 'position', + 'quotes', + 'resize', + 'right', + 'src', // @font-face + 'tab-size', + 'table-layout', + 'text-align', + 'text-align-last', + 'text-decoration', + 'text-decoration-color', + 'text-decoration-line', + 'text-decoration-style', + 'text-indent', + 'text-overflow', + 'text-rendering', + 'text-shadow', + 'text-transform', + 'text-underline-position', + 'top', + 'transform', + 'transform-origin', + 'transform-style', + 'transition', + 'transition-delay', + 'transition-duration', + 'transition-property', + 'transition-timing-function', + 'unicode-bidi', + 'vertical-align', + 'visibility', + 'white-space', + 'widows', + 'width', + 'word-break', + 'word-spacing', + 'word-wrap', + 'z-index' + // reverse makes sure longer attributes `font-weight` are matched fully + // instead of getting false positives on say `font` +].reverse(); + +/* +Language: Stylus +Author: Bryant Williams +Description: Stylus is an expressive, robust, feature-rich CSS language built for nodejs. +Website: https://github.com/stylus/stylus +Category: css +*/ + +/** @type LanguageFn */ +function stylus(hljs) { + const modes = MODES(hljs); + + const AT_MODIFIERS = "and or not only"; + const VARIABLE = { + className: 'variable', + begin: '\\$' + hljs.IDENT_RE + }; + + const AT_KEYWORDS = [ + 'charset', + 'css', + 'debug', + 'extend', + 'font-face', + 'for', + 'import', + 'include', + 'keyframes', + 'media', + 'mixin', + 'page', + 'warn', + 'while' + ]; + + const LOOKAHEAD_TAG_END = '(?=[.\\s\\n[:,(])'; + + // illegals + const ILLEGAL = [ + '\\?', + '(\\bReturn\\b)', // monkey + '(\\bEnd\\b)', // monkey + '(\\bend\\b)', // vbscript + '(\\bdef\\b)', // gradle + ';', // a whole lot of languages + '#\\s', // markdown + '\\*\\s', // markdown + '===\\s', // markdown + '\\|', + '%' // prolog + ]; + + return { + name: 'Stylus', + aliases: [ 'styl' ], + case_insensitive: false, + keywords: 'if else for in', + illegal: '(' + ILLEGAL.join('|') + ')', + contains: [ + + // strings + hljs.QUOTE_STRING_MODE, + hljs.APOS_STRING_MODE, + + // comments + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + + // hex colors + modes.HEXCOLOR, + + // class tag + { + begin: '\\.[a-zA-Z][a-zA-Z0-9_-]*' + LOOKAHEAD_TAG_END, + className: 'selector-class' + }, + + // id tag + { + begin: '#[a-zA-Z][a-zA-Z0-9_-]*' + LOOKAHEAD_TAG_END, + className: 'selector-id' + }, + + // tags + { + begin: '\\b(' + TAGS.join('|') + ')' + LOOKAHEAD_TAG_END, + className: 'selector-tag' + }, + + // psuedo selectors + { + className: 'selector-pseudo', + begin: '&?:(' + PSEUDO_CLASSES.join('|') + ')' + LOOKAHEAD_TAG_END + }, + { + className: 'selector-pseudo', + begin: '&?::(' + PSEUDO_ELEMENTS.join('|') + ')' + LOOKAHEAD_TAG_END + }, + + modes.ATTRIBUTE_SELECTOR_MODE, + + { + className: "keyword", + begin: /@media/, + starts: { + end: /[{;}]/, + keywords: { + $pattern: /[a-z-]+/, + keyword: AT_MODIFIERS, + attribute: MEDIA_FEATURES.join(" ") + }, + contains: [ hljs.CSS_NUMBER_MODE ] + } + }, + + // @ keywords + { + className: 'keyword', + begin: '\@((-(o|moz|ms|webkit)-)?(' + AT_KEYWORDS.join('|') + '))\\b' + }, + + // variables + VARIABLE, + + // dimension + hljs.CSS_NUMBER_MODE, + + // functions + // - only from beginning of line + whitespace + { + className: 'function', + begin: '^[a-zA-Z][a-zA-Z0-9_\-]*\\(.*\\)', + illegal: '[\\n]', + returnBegin: true, + contains: [ + { + className: 'title', + begin: '\\b[a-zA-Z][a-zA-Z0-9_\-]*' + }, + { + className: 'params', + begin: /\(/, + end: /\)/, + contains: [ + modes.HEXCOLOR, + VARIABLE, + hljs.APOS_STRING_MODE, + hljs.CSS_NUMBER_MODE, + hljs.QUOTE_STRING_MODE + ] + } + ] + }, + + // attributes + // - only from beginning of line + whitespace + // - must have whitespace after it + { + className: 'attribute', + begin: '\\b(' + ATTRIBUTES.join('|') + ')\\b', + starts: { + // value container + end: /;|$/, + contains: [ + modes.HEXCOLOR, + VARIABLE, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + hljs.CSS_NUMBER_MODE, + hljs.C_BLOCK_COMMENT_MODE, + modes.IMPORTANT + ], + illegal: /\./, + relevance: 0 + } + } + ] + }; +} + +module.exports = stylus; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/subunit.js b/claude-code-source/node_modules/highlight.js/lib/languages/subunit.js new file mode 100644 index 00000000..00add37b --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/subunit.js @@ -0,0 +1,51 @@ +/* +Language: SubUnit +Author: Sergey Bronnikov +Website: https://pypi.org/project/python-subunit/ +*/ + +function subunit(hljs) { + const DETAILS = { + className: 'string', + begin: '\\[\n(multipart)?', + end: '\\]\n' + }; + const TIME = { + className: 'string', + begin: '\\d{4}-\\d{2}-\\d{2}(\\s+)\\d{2}:\\d{2}:\\d{2}\.\\d+Z' + }; + const PROGRESSVALUE = { + className: 'string', + begin: '(\\+|-)\\d+' + }; + const KEYWORDS = { + className: 'keyword', + relevance: 10, + variants: [ + { + begin: '^(test|testing|success|successful|failure|error|skip|xfail|uxsuccess)(:?)\\s+(test)?' + }, + { + begin: '^progress(:?)(\\s+)?(pop|push)?' + }, + { + begin: '^tags:' + }, + { + begin: '^time:' + } + ] + }; + return { + name: 'SubUnit', + case_insensitive: true, + contains: [ + DETAILS, + TIME, + PROGRESSVALUE, + KEYWORDS + ] + }; +} + +module.exports = subunit; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/swift.js b/claude-code-source/node_modules/highlight.js/lib/languages/swift.js new file mode 100644 index 00000000..09a21989 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/swift.js @@ -0,0 +1,873 @@ +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function lookahead(re) { + return concat('(?=', re, ')'); +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/** + * Any of the passed expresssions may match + * + * Creates a huge this | this | that | that match + * @param {(RegExp | string)[] } args + * @returns {string} + */ +function either(...args) { + const joined = '(' + args.map((x) => source(x)).join("|") + ")"; + return joined; +} + +const keywordWrapper = keyword => concat( + /\b/, + keyword, + /\w$/.test(keyword) ? /\b/ : /\B/ +); + +// Keywords that require a leading dot. +const dotKeywords = [ + 'Protocol', // contextual + 'Type' // contextual +].map(keywordWrapper); + +// Keywords that may have a leading dot. +const optionalDotKeywords = [ + 'init', + 'self' +].map(keywordWrapper); + +// should register as keyword, not type +const keywordTypes = [ + 'Any', + 'Self' +]; + +// Regular keywords and literals. +const keywords = [ + // strings below will be fed into the regular `keywords` engine while regex + // will result in additional modes being created to scan for those keywords to + // avoid conflicts with other rules + 'associatedtype', + 'async', + 'await', + /as\?/, // operator + /as!/, // operator + 'as', // operator + 'break', + 'case', + 'catch', + 'class', + 'continue', + 'convenience', // contextual + 'default', + 'defer', + 'deinit', + 'didSet', // contextual + 'do', + 'dynamic', // contextual + 'else', + 'enum', + 'extension', + 'fallthrough', + /fileprivate\(set\)/, + 'fileprivate', + 'final', // contextual + 'for', + 'func', + 'get', // contextual + 'guard', + 'if', + 'import', + 'indirect', // contextual + 'infix', // contextual + /init\?/, + /init!/, + 'inout', + /internal\(set\)/, + 'internal', + 'in', + 'is', // operator + 'lazy', // contextual + 'let', + 'mutating', // contextual + 'nonmutating', // contextual + /open\(set\)/, // contextual + 'open', // contextual + 'operator', + 'optional', // contextual + 'override', // contextual + 'postfix', // contextual + 'precedencegroup', + 'prefix', // contextual + /private\(set\)/, + 'private', + 'protocol', + /public\(set\)/, + 'public', + 'repeat', + 'required', // contextual + 'rethrows', + 'return', + 'set', // contextual + 'some', // contextual + 'static', + 'struct', + 'subscript', + 'super', + 'switch', + 'throws', + 'throw', + /try\?/, // operator + /try!/, // operator + 'try', // operator + 'typealias', + /unowned\(safe\)/, // contextual + /unowned\(unsafe\)/, // contextual + 'unowned', // contextual + 'var', + 'weak', // contextual + 'where', + 'while', + 'willSet' // contextual +]; + +// NOTE: Contextual keywords are reserved only in specific contexts. +// Ideally, these should be matched using modes to avoid false positives. + +// Literals. +const literals = [ + 'false', + 'nil', + 'true' +]; + +// Keywords used in precedence groups. +const precedencegroupKeywords = [ + 'assignment', + 'associativity', + 'higherThan', + 'left', + 'lowerThan', + 'none', + 'right' +]; + +// Keywords that start with a number sign (#). +// #available is handled separately. +const numberSignKeywords = [ + '#colorLiteral', + '#column', + '#dsohandle', + '#else', + '#elseif', + '#endif', + '#error', + '#file', + '#fileID', + '#fileLiteral', + '#filePath', + '#function', + '#if', + '#imageLiteral', + '#keyPath', + '#line', + '#selector', + '#sourceLocation', + '#warn_unqualified_access', + '#warning' +]; + +// Global functions in the Standard Library. +const builtIns = [ + 'abs', + 'all', + 'any', + 'assert', + 'assertionFailure', + 'debugPrint', + 'dump', + 'fatalError', + 'getVaList', + 'isKnownUniquelyReferenced', + 'max', + 'min', + 'numericCast', + 'pointwiseMax', + 'pointwiseMin', + 'precondition', + 'preconditionFailure', + 'print', + 'readLine', + 'repeatElement', + 'sequence', + 'stride', + 'swap', + 'swift_unboxFromSwiftValueWithType', + 'transcode', + 'type', + 'unsafeBitCast', + 'unsafeDowncast', + 'withExtendedLifetime', + 'withUnsafeMutablePointer', + 'withUnsafePointer', + 'withVaList', + 'withoutActuallyEscaping', + 'zip' +]; + +// Valid first characters for operators. +const operatorHead = either( + /[/=\-+!*%<>&|^~?]/, + /[\u00A1-\u00A7]/, + /[\u00A9\u00AB]/, + /[\u00AC\u00AE]/, + /[\u00B0\u00B1]/, + /[\u00B6\u00BB\u00BF\u00D7\u00F7]/, + /[\u2016-\u2017]/, + /[\u2020-\u2027]/, + /[\u2030-\u203E]/, + /[\u2041-\u2053]/, + /[\u2055-\u205E]/, + /[\u2190-\u23FF]/, + /[\u2500-\u2775]/, + /[\u2794-\u2BFF]/, + /[\u2E00-\u2E7F]/, + /[\u3001-\u3003]/, + /[\u3008-\u3020]/, + /[\u3030]/ +); + +// Valid characters for operators. +const operatorCharacter = either( + operatorHead, + /[\u0300-\u036F]/, + /[\u1DC0-\u1DFF]/, + /[\u20D0-\u20FF]/, + /[\uFE00-\uFE0F]/, + /[\uFE20-\uFE2F]/ + // TODO: The following characters are also allowed, but the regex isn't supported yet. + // /[\u{E0100}-\u{E01EF}]/u +); + +// Valid operator. +const operator = concat(operatorHead, operatorCharacter, '*'); + +// Valid first characters for identifiers. +const identifierHead = either( + /[a-zA-Z_]/, + /[\u00A8\u00AA\u00AD\u00AF\u00B2-\u00B5\u00B7-\u00BA]/, + /[\u00BC-\u00BE\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF]/, + /[\u0100-\u02FF\u0370-\u167F\u1681-\u180D\u180F-\u1DBF]/, + /[\u1E00-\u1FFF]/, + /[\u200B-\u200D\u202A-\u202E\u203F-\u2040\u2054\u2060-\u206F]/, + /[\u2070-\u20CF\u2100-\u218F\u2460-\u24FF\u2776-\u2793]/, + /[\u2C00-\u2DFF\u2E80-\u2FFF]/, + /[\u3004-\u3007\u3021-\u302F\u3031-\u303F\u3040-\uD7FF]/, + /[\uF900-\uFD3D\uFD40-\uFDCF\uFDF0-\uFE1F\uFE30-\uFE44]/, + /[\uFE47-\uFEFE\uFF00-\uFFFD]/ // Should be /[\uFE47-\uFFFD]/, but we have to exclude FEFF. + // The following characters are also allowed, but the regexes aren't supported yet. + // /[\u{10000}-\u{1FFFD}\u{20000-\u{2FFFD}\u{30000}-\u{3FFFD}\u{40000}-\u{4FFFD}]/u, + // /[\u{50000}-\u{5FFFD}\u{60000-\u{6FFFD}\u{70000}-\u{7FFFD}\u{80000}-\u{8FFFD}]/u, + // /[\u{90000}-\u{9FFFD}\u{A0000-\u{AFFFD}\u{B0000}-\u{BFFFD}\u{C0000}-\u{CFFFD}]/u, + // /[\u{D0000}-\u{DFFFD}\u{E0000-\u{EFFFD}]/u +); + +// Valid characters for identifiers. +const identifierCharacter = either( + identifierHead, + /\d/, + /[\u0300-\u036F\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/ +); + +// Valid identifier. +const identifier = concat(identifierHead, identifierCharacter, '*'); + +// Valid type identifier. +const typeIdentifier = concat(/[A-Z]/, identifierCharacter, '*'); + +// Built-in attributes, which are highlighted as keywords. +// @available is handled separately. +const keywordAttributes = [ + 'autoclosure', + concat(/convention\(/, either('swift', 'block', 'c'), /\)/), + 'discardableResult', + 'dynamicCallable', + 'dynamicMemberLookup', + 'escaping', + 'frozen', + 'GKInspectable', + 'IBAction', + 'IBDesignable', + 'IBInspectable', + 'IBOutlet', + 'IBSegueAction', + 'inlinable', + 'main', + 'nonobjc', + 'NSApplicationMain', + 'NSCopying', + 'NSManaged', + concat(/objc\(/, identifier, /\)/), + 'objc', + 'objcMembers', + 'propertyWrapper', + 'requires_stored_property_inits', + 'testable', + 'UIApplicationMain', + 'unknown', + 'usableFromInline' +]; + +// Contextual keywords used in @available and #available. +const availabilityKeywords = [ + 'iOS', + 'iOSApplicationExtension', + 'macOS', + 'macOSApplicationExtension', + 'macCatalyst', + 'macCatalystApplicationExtension', + 'watchOS', + 'watchOSApplicationExtension', + 'tvOS', + 'tvOSApplicationExtension', + 'swift' +]; + +/* +Language: Swift +Description: Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns. +Author: Steven Van Impe +Contributors: Chris Eidhof , Nate Cook , Alexander Lichter , Richard Gibson +Website: https://swift.org +Category: common, system +*/ + +/** @type LanguageFn */ +function swift(hljs) { + const WHITESPACE = { + match: /\s+/, + relevance: 0 + }; + // https://docs.swift.org/swift-book/ReferenceManual/LexicalStructure.html#ID411 + const BLOCK_COMMENT = hljs.COMMENT( + '/\\*', + '\\*/', + { + contains: [ 'self' ] + } + ); + const COMMENTS = [ + hljs.C_LINE_COMMENT_MODE, + BLOCK_COMMENT + ]; + + // https://docs.swift.org/swift-book/ReferenceManual/LexicalStructure.html#ID413 + // https://docs.swift.org/swift-book/ReferenceManual/zzSummaryOfTheGrammar.html + const DOT_KEYWORD = { + className: 'keyword', + begin: concat(/\./, lookahead(either(...dotKeywords, ...optionalDotKeywords))), + end: either(...dotKeywords, ...optionalDotKeywords), + excludeBegin: true + }; + const KEYWORD_GUARD = { + // Consume .keyword to prevent highlighting properties and methods as keywords. + match: concat(/\./, either(...keywords)), + relevance: 0 + }; + const PLAIN_KEYWORDS = keywords + .filter(kw => typeof kw === 'string') + .concat([ "_|0" ]); // seems common, so 0 relevance + const REGEX_KEYWORDS = keywords + .filter(kw => typeof kw !== 'string') // find regex + .concat(keywordTypes) + .map(keywordWrapper); + const KEYWORD = { + variants: [ + { + className: 'keyword', + match: either(...REGEX_KEYWORDS, ...optionalDotKeywords) + } + ] + }; + // find all the regular keywords + const KEYWORDS = { + $pattern: either( + /\b\w+/, // regular keywords + /#\w+/ // number keywords + ), + keyword: PLAIN_KEYWORDS + .concat(numberSignKeywords), + literal: literals + }; + const KEYWORD_MODES = [ + DOT_KEYWORD, + KEYWORD_GUARD, + KEYWORD + ]; + + // https://github.com/apple/swift/tree/main/stdlib/public/core + const BUILT_IN_GUARD = { + // Consume .built_in to prevent highlighting properties and methods. + match: concat(/\./, either(...builtIns)), + relevance: 0 + }; + const BUILT_IN = { + className: 'built_in', + match: concat(/\b/, either(...builtIns), /(?=\()/) + }; + const BUILT_INS = [ + BUILT_IN_GUARD, + BUILT_IN + ]; + + // https://docs.swift.org/swift-book/ReferenceManual/LexicalStructure.html#ID418 + const OPERATOR_GUARD = { + // Prevent -> from being highlighting as an operator. + match: /->/, + relevance: 0 + }; + const OPERATOR = { + className: 'operator', + relevance: 0, + variants: [ + { + match: operator + }, + { + // dot-operator: only operators that start with a dot are allowed to use dots as + // characters (..., ...<, .*, etc). So there rule here is: a dot followed by one or more + // characters that may also include dots. + match: `\\.(\\.|${operatorCharacter})+` + } + ] + }; + const OPERATORS = [ + OPERATOR_GUARD, + OPERATOR + ]; + + // https://docs.swift.org/swift-book/ReferenceManual/LexicalStructure.html#grammar_numeric-literal + // TODO: Update for leading `-` after lookbehind is supported everywhere + const decimalDigits = '([0-9]_*)+'; + const hexDigits = '([0-9a-fA-F]_*)+'; + const NUMBER = { + className: 'number', + relevance: 0, + variants: [ + // decimal floating-point-literal (subsumes decimal-literal) + { + match: `\\b(${decimalDigits})(\\.(${decimalDigits}))?` + `([eE][+-]?(${decimalDigits}))?\\b` + }, + // hexadecimal floating-point-literal (subsumes hexadecimal-literal) + { + match: `\\b0x(${hexDigits})(\\.(${hexDigits}))?` + `([pP][+-]?(${decimalDigits}))?\\b` + }, + // octal-literal + { + match: /\b0o([0-7]_*)+\b/ + }, + // binary-literal + { + match: /\b0b([01]_*)+\b/ + } + ] + }; + + // https://docs.swift.org/swift-book/ReferenceManual/LexicalStructure.html#grammar_string-literal + const ESCAPED_CHARACTER = (rawDelimiter = "") => ({ + className: 'subst', + variants: [ + { + match: concat(/\\/, rawDelimiter, /[0\\tnr"']/) + }, + { + match: concat(/\\/, rawDelimiter, /u\{[0-9a-fA-F]{1,8}\}/) + } + ] + }); + const ESCAPED_NEWLINE = (rawDelimiter = "") => ({ + className: 'subst', + match: concat(/\\/, rawDelimiter, /[\t ]*(?:[\r\n]|\r\n)/) + }); + const INTERPOLATION = (rawDelimiter = "") => ({ + className: 'subst', + label: "interpol", + begin: concat(/\\/, rawDelimiter, /\(/), + end: /\)/ + }); + const MULTILINE_STRING = (rawDelimiter = "") => ({ + begin: concat(rawDelimiter, /"""/), + end: concat(/"""/, rawDelimiter), + contains: [ + ESCAPED_CHARACTER(rawDelimiter), + ESCAPED_NEWLINE(rawDelimiter), + INTERPOLATION(rawDelimiter) + ] + }); + const SINGLE_LINE_STRING = (rawDelimiter = "") => ({ + begin: concat(rawDelimiter, /"/), + end: concat(/"/, rawDelimiter), + contains: [ + ESCAPED_CHARACTER(rawDelimiter), + INTERPOLATION(rawDelimiter) + ] + }); + const STRING = { + className: 'string', + variants: [ + MULTILINE_STRING(), + MULTILINE_STRING("#"), + MULTILINE_STRING("##"), + MULTILINE_STRING("###"), + SINGLE_LINE_STRING(), + SINGLE_LINE_STRING("#"), + SINGLE_LINE_STRING("##"), + SINGLE_LINE_STRING("###") + ] + }; + + // https://docs.swift.org/swift-book/ReferenceManual/LexicalStructure.html#ID412 + const QUOTED_IDENTIFIER = { + match: concat(/`/, identifier, /`/) + }; + const IMPLICIT_PARAMETER = { + className: 'variable', + match: /\$\d+/ + }; + const PROPERTY_WRAPPER_PROJECTION = { + className: 'variable', + match: `\\$${identifierCharacter}+` + }; + const IDENTIFIERS = [ + QUOTED_IDENTIFIER, + IMPLICIT_PARAMETER, + PROPERTY_WRAPPER_PROJECTION + ]; + + // https://docs.swift.org/swift-book/ReferenceManual/Attributes.html + const AVAILABLE_ATTRIBUTE = { + match: /(@|#)available/, + className: "keyword", + starts: { + contains: [ + { + begin: /\(/, + end: /\)/, + keywords: availabilityKeywords, + contains: [ + ...OPERATORS, + NUMBER, + STRING + ] + } + ] + } + }; + const KEYWORD_ATTRIBUTE = { + className: 'keyword', + match: concat(/@/, either(...keywordAttributes)) + }; + const USER_DEFINED_ATTRIBUTE = { + className: 'meta', + match: concat(/@/, identifier) + }; + const ATTRIBUTES = [ + AVAILABLE_ATTRIBUTE, + KEYWORD_ATTRIBUTE, + USER_DEFINED_ATTRIBUTE + ]; + + // https://docs.swift.org/swift-book/ReferenceManual/Types.html + const TYPE = { + match: lookahead(/\b[A-Z]/), + relevance: 0, + contains: [ + { // Common Apple frameworks, for relevance boost + className: 'type', + match: concat(/(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)/, identifierCharacter, '+') + }, + { // Type identifier + className: 'type', + match: typeIdentifier, + relevance: 0 + }, + { // Optional type + match: /[?!]+/, + relevance: 0 + }, + { // Variadic parameter + match: /\.\.\./, + relevance: 0 + }, + { // Protocol composition + match: concat(/\s+&\s+/, lookahead(typeIdentifier)), + relevance: 0 + } + ] + }; + const GENERIC_ARGUMENTS = { + begin: //, + keywords: KEYWORDS, + contains: [ + ...COMMENTS, + ...KEYWORD_MODES, + ...ATTRIBUTES, + OPERATOR_GUARD, + TYPE + ] + }; + TYPE.contains.push(GENERIC_ARGUMENTS); + + // https://docs.swift.org/swift-book/ReferenceManual/Expressions.html#ID552 + // Prevents element names from being highlighted as keywords. + const TUPLE_ELEMENT_NAME = { + match: concat(identifier, /\s*:/), + keywords: "_|0", + relevance: 0 + }; + // Matches tuples as well as the parameter list of a function type. + const TUPLE = { + begin: /\(/, + end: /\)/, + relevance: 0, + keywords: KEYWORDS, + contains: [ + 'self', + TUPLE_ELEMENT_NAME, + ...COMMENTS, + ...KEYWORD_MODES, + ...BUILT_INS, + ...OPERATORS, + NUMBER, + STRING, + ...IDENTIFIERS, + ...ATTRIBUTES, + TYPE + ] + }; + + // https://docs.swift.org/swift-book/ReferenceManual/Declarations.html#ID362 + // Matches both the keyword func and the function title. + // Grouping these lets us differentiate between the operator function < + // and the start of the generic parameter clause (also <). + const FUNC_PLUS_TITLE = { + beginKeywords: 'func', + contains: [ + { + className: 'title', + match: either(QUOTED_IDENTIFIER.match, identifier, operator), + // Required to make sure the opening < of the generic parameter clause + // isn't parsed as a second title. + endsParent: true, + relevance: 0 + }, + WHITESPACE + ] + }; + const GENERIC_PARAMETERS = { + begin: //, + contains: [ + ...COMMENTS, + TYPE + ] + }; + const FUNCTION_PARAMETER_NAME = { + begin: either( + lookahead(concat(identifier, /\s*:/)), + lookahead(concat(identifier, /\s+/, identifier, /\s*:/)) + ), + end: /:/, + relevance: 0, + contains: [ + { + className: 'keyword', + match: /\b_\b/ + }, + { + className: 'params', + match: identifier + } + ] + }; + const FUNCTION_PARAMETERS = { + begin: /\(/, + end: /\)/, + keywords: KEYWORDS, + contains: [ + FUNCTION_PARAMETER_NAME, + ...COMMENTS, + ...KEYWORD_MODES, + ...OPERATORS, + NUMBER, + STRING, + ...ATTRIBUTES, + TYPE, + TUPLE + ], + endsParent: true, + illegal: /["']/ + }; + const FUNCTION = { + className: 'function', + match: lookahead(/\bfunc\b/), + contains: [ + FUNC_PLUS_TITLE, + GENERIC_PARAMETERS, + FUNCTION_PARAMETERS, + WHITESPACE + ], + illegal: [ + /\[/, + /%/ + ] + }; + + // https://docs.swift.org/swift-book/ReferenceManual/Declarations.html#ID375 + // https://docs.swift.org/swift-book/ReferenceManual/Declarations.html#ID379 + const INIT_SUBSCRIPT = { + className: 'function', + match: /\b(subscript|init[?!]?)\s*(?=[<(])/, + keywords: { + keyword: "subscript init init? init!", + $pattern: /\w+[?!]?/ + }, + contains: [ + GENERIC_PARAMETERS, + FUNCTION_PARAMETERS, + WHITESPACE + ], + illegal: /\[|%/ + }; + // https://docs.swift.org/swift-book/ReferenceManual/Declarations.html#ID380 + const OPERATOR_DECLARATION = { + beginKeywords: 'operator', + end: hljs.MATCH_NOTHING_RE, + contains: [ + { + className: 'title', + match: operator, + endsParent: true, + relevance: 0 + } + ] + }; + + // https://docs.swift.org/swift-book/ReferenceManual/Declarations.html#ID550 + const PRECEDENCEGROUP = { + beginKeywords: 'precedencegroup', + end: hljs.MATCH_NOTHING_RE, + contains: [ + { + className: 'title', + match: typeIdentifier, + relevance: 0 + }, + { + begin: /{/, + end: /}/, + relevance: 0, + endsParent: true, + keywords: [ + ...precedencegroupKeywords, + ...literals + ], + contains: [ TYPE ] + } + ] + }; + + // Add supported submodes to string interpolation. + for (const variant of STRING.variants) { + const interpolation = variant.contains.find(mode => mode.label === "interpol"); + // TODO: Interpolation can contain any expression, so there's room for improvement here. + interpolation.keywords = KEYWORDS; + const submodes = [ + ...KEYWORD_MODES, + ...BUILT_INS, + ...OPERATORS, + NUMBER, + STRING, + ...IDENTIFIERS + ]; + interpolation.contains = [ + ...submodes, + { + begin: /\(/, + end: /\)/, + contains: [ + 'self', + ...submodes + ] + } + ]; + } + + return { + name: 'Swift', + keywords: KEYWORDS, + contains: [ + ...COMMENTS, + FUNCTION, + INIT_SUBSCRIPT, + { + className: 'class', + beginKeywords: 'struct protocol class extension enum', + end: '\\{', + excludeEnd: true, + keywords: KEYWORDS, + contains: [ + hljs.inherit(hljs.TITLE_MODE, { + begin: /[A-Za-z$_][\u00C0-\u02B80-9A-Za-z$_]*/ + }), + ...KEYWORD_MODES + ] + }, + OPERATOR_DECLARATION, + PRECEDENCEGROUP, + { + beginKeywords: 'import', + end: /$/, + contains: [ ...COMMENTS ], + relevance: 0 + }, + ...KEYWORD_MODES, + ...BUILT_INS, + ...OPERATORS, + NUMBER, + STRING, + ...IDENTIFIERS, + ...ATTRIBUTES, + TYPE, + TUPLE + ] + }; +} + +module.exports = swift; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/taggerscript.js b/claude-code-source/node_modules/highlight.js/lib/languages/taggerscript.js new file mode 100644 index 00000000..c82ba288 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/taggerscript.js @@ -0,0 +1,52 @@ +/* +Language: Tagger Script +Author: Philipp Wolfer +Description: Syntax Highlighting for the Tagger Script as used by MusicBrainz Picard. +Website: https://picard.musicbrainz.org + */ +function taggerscript(hljs) { + const COMMENT = { + className: 'comment', + begin: /\$noop\(/, + end: /\)/, + contains: [ { + begin: /\(/, + end: /\)/, + contains: [ 'self', + { + begin: /\\./ + } ] + } ], + relevance: 10 + }; + + const FUNCTION = { + className: 'keyword', + begin: /\$(?!noop)[a-zA-Z][_a-zA-Z0-9]*/, + end: /\(/, + excludeEnd: true + }; + + const VARIABLE = { + className: 'variable', + begin: /%[_a-zA-Z0-9:]*/, + end: '%' + }; + + const ESCAPE_SEQUENCE = { + className: 'symbol', + begin: /\\./ + }; + + return { + name: 'Tagger Script', + contains: [ + COMMENT, + FUNCTION, + VARIABLE, + ESCAPE_SEQUENCE + ] + }; +} + +module.exports = taggerscript; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/tap.js b/claude-code-source/node_modules/highlight.js/lib/languages/tap.js new file mode 100644 index 00000000..c57ab402 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/tap.js @@ -0,0 +1,55 @@ +/* +Language: Test Anything Protocol +Description: TAP, the Test Anything Protocol, is a simple text-based interface between testing modules in a test harness. +Requires: yaml.js +Author: Sergey Bronnikov +Website: https://testanything.org +*/ + +function tap(hljs) { + return { + name: 'Test Anything Protocol', + case_insensitive: true, + contains: [ + hljs.HASH_COMMENT_MODE, + // version of format and total amount of testcases + { + className: 'meta', + variants: [ + { + begin: '^TAP version (\\d+)$' + }, + { + begin: '^1\\.\\.(\\d+)$' + } + ] + }, + // YAML block + { + begin: /---$/, + end: '\\.\\.\\.$', + subLanguage: 'yaml', + relevance: 0 + }, + // testcase number + { + className: 'number', + begin: ' (\\d+) ' + }, + // testcase status and description + { + className: 'symbol', + variants: [ + { + begin: '^ok' + }, + { + begin: '^not ok' + } + ] + } + ] + }; +} + +module.exports = tap; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/tcl.js b/claude-code-source/node_modules/highlight.js/lib/languages/tcl.js new file mode 100644 index 00000000..d319223a --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/tcl.js @@ -0,0 +1,115 @@ +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function optional(re) { + return concat('(', re, ')?'); +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/* +Language: Tcl +Description: Tcl is a very simple programming language. +Author: Radek Liska +Website: https://www.tcl.tk/about/language.html +*/ + +function tcl(hljs) { + const TCL_IDENT = /[a-zA-Z_][a-zA-Z0-9_]*/; + + const NUMBER = { + className: 'number', + variants: [hljs.BINARY_NUMBER_MODE, hljs.C_NUMBER_MODE] + }; + + return { + name: 'Tcl', + aliases: ['tk'], + keywords: 'after append apply array auto_execok auto_import auto_load auto_mkindex ' + + 'auto_mkindex_old auto_qualify auto_reset bgerror binary break catch cd chan clock ' + + 'close concat continue dde dict encoding eof error eval exec exit expr fblocked ' + + 'fconfigure fcopy file fileevent filename flush for foreach format gets glob global ' + + 'history http if incr info interp join lappend|10 lassign|10 lindex|10 linsert|10 list ' + + 'llength|10 load lrange|10 lrepeat|10 lreplace|10 lreverse|10 lsearch|10 lset|10 lsort|10 '+ + 'mathfunc mathop memory msgcat namespace open package parray pid pkg::create pkg_mkIndex '+ + 'platform platform::shell proc puts pwd read refchan regexp registry regsub|10 rename '+ + 'return safe scan seek set socket source split string subst switch tcl_endOfWord '+ + 'tcl_findLibrary tcl_startOfNextWord tcl_startOfPreviousWord tcl_wordBreakAfter '+ + 'tcl_wordBreakBefore tcltest tclvars tell time tm trace unknown unload unset update '+ + 'uplevel upvar variable vwait while', + contains: [ + hljs.COMMENT(';[ \\t]*#', '$'), + hljs.COMMENT('^[ \\t]*#', '$'), + { + beginKeywords: 'proc', + end: '[\\{]', + excludeEnd: true, + contains: [ + { + className: 'title', + begin: '[ \\t\\n\\r]+(::)?[a-zA-Z_]((::)?[a-zA-Z0-9_])*', + end: '[ \\t\\n\\r]', + endsWithParent: true, + excludeEnd: true + } + ] + }, + { + className: "variable", + variants: [ + { + begin: concat( + /\$/, + optional(/::/), + TCL_IDENT, + '(::', + TCL_IDENT, + ')*' + ) + }, + { + begin: '\\$\\{(::)?[a-zA-Z_]((::)?[a-zA-Z0-9_])*', + end: '\\}', + contains: [ + NUMBER + ] + } + ] + }, + { + className: 'string', + contains: [hljs.BACKSLASH_ESCAPE], + variants: [ + hljs.inherit(hljs.QUOTE_STRING_MODE, {illegal: null}) + ] + }, + NUMBER + ] + } +} + +module.exports = tcl; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/thrift.js b/claude-code-source/node_modules/highlight.js/lib/languages/thrift.js new file mode 100644 index 00000000..7d05b877 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/thrift.js @@ -0,0 +1,51 @@ +/* +Language: Thrift +Author: Oleg Efimov +Description: Thrift message definition format +Website: https://thrift.apache.org +Category: protocols +*/ + +function thrift(hljs) { + const BUILT_IN_TYPES = 'bool byte i16 i32 i64 double string binary'; + return { + name: 'Thrift', + keywords: { + keyword: + 'namespace const typedef struct enum service exception void oneway set list map required optional', + built_in: + BUILT_IN_TYPES, + literal: + 'true false' + }, + contains: [ + hljs.QUOTE_STRING_MODE, + hljs.NUMBER_MODE, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + { + className: 'class', + beginKeywords: 'struct enum service exception', + end: /\{/, + illegal: /\n/, + contains: [ + hljs.inherit(hljs.TITLE_MODE, { + // hack: eating everything after the first title + starts: { + endsWithParent: true, + excludeEnd: true + } + }) + ] + }, + { + begin: '\\b(set|list|map)\\s*<', + end: '>', + keywords: BUILT_IN_TYPES, + contains: [ 'self' ] + } + ] + }; +} + +module.exports = thrift; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/tp.js b/claude-code-source/node_modules/highlight.js/lib/languages/tp.js new file mode 100644 index 00000000..58b4d439 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/tp.js @@ -0,0 +1,95 @@ +/* +Language: TP +Author: Jay Strybis +Description: FANUC TP programming language (TPP). +*/ + +function tp(hljs) { + const TPID = { + className: 'number', + begin: '[1-9][0-9]*', /* no leading zeros */ + relevance: 0 + }; + const TPLABEL = { + className: 'symbol', + begin: ':[^\\]]+' + }; + const TPDATA = { + className: 'built_in', + begin: '(AR|P|PAYLOAD|PR|R|SR|RSR|LBL|VR|UALM|MESSAGE|UTOOL|UFRAME|TIMER|' + + 'TIMER_OVERFLOW|JOINT_MAX_SPEED|RESUME_PROG|DIAG_REC)\\[', + end: '\\]', + contains: [ + 'self', + TPID, + TPLABEL + ] + }; + const TPIO = { + className: 'built_in', + begin: '(AI|AO|DI|DO|F|RI|RO|UI|UO|GI|GO|SI|SO)\\[', + end: '\\]', + contains: [ + 'self', + TPID, + hljs.QUOTE_STRING_MODE, /* for pos section at bottom */ + TPLABEL + ] + }; + + return { + name: 'TP', + keywords: { + keyword: + 'ABORT ACC ADJUST AND AP_LD BREAK CALL CNT COL CONDITION CONFIG DA DB ' + + 'DIV DETECT ELSE END ENDFOR ERR_NUM ERROR_PROG FINE FOR GP GUARD INC ' + + 'IF JMP LINEAR_MAX_SPEED LOCK MOD MONITOR OFFSET Offset OR OVERRIDE ' + + 'PAUSE PREG PTH RT_LD RUN SELECT SKIP Skip TA TB TO TOOL_OFFSET ' + + 'Tool_Offset UF UT UFRAME_NUM UTOOL_NUM UNLOCK WAIT X Y Z W P R STRLEN ' + + 'SUBSTR FINDSTR VOFFSET PROG ATTR MN POS', + literal: + 'ON OFF max_speed LPOS JPOS ENABLE DISABLE START STOP RESET' + }, + contains: [ + TPDATA, + TPIO, + { + className: 'keyword', + begin: '/(PROG|ATTR|MN|POS|END)\\b' + }, + { + /* this is for cases like ,CALL */ + className: 'keyword', + begin: '(CALL|RUN|POINT_LOGIC|LBL)\\b' + }, + { + /* this is for cases like CNT100 where the default lexemes do not + * separate the keyword and the number */ + className: 'keyword', + begin: '\\b(ACC|CNT|Skip|Offset|PSPD|RT_LD|AP_LD|Tool_Offset)' + }, + { + /* to catch numbers that do not have a word boundary on the left */ + className: 'number', + begin: '\\d+(sec|msec|mm/sec|cm/min|inch/min|deg/sec|mm|in|cm)?\\b', + relevance: 0 + }, + hljs.COMMENT('//', '[;$]'), + hljs.COMMENT('!', '[;$]'), + hljs.COMMENT('--eg:', '$'), + hljs.QUOTE_STRING_MODE, + { + className: 'string', + begin: '\'', + end: '\'' + }, + hljs.C_NUMBER_MODE, + { + className: 'variable', + begin: '\\$[A-Za-z0-9_]+' + } + ] + }; +} + +module.exports = tp; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/twig.js b/claude-code-source/node_modules/highlight.js/lib/languages/twig.js new file mode 100644 index 00000000..216c8b16 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/twig.js @@ -0,0 +1,77 @@ +/* +Language: Twig +Requires: xml.js +Author: Luke Holder +Description: Twig is a templating language for PHP +Website: https://twig.symfony.com +Category: template +*/ + +function twig(hljs) { + var PARAMS = { + className: 'params', + begin: '\\(', end: '\\)' + }; + + var FUNCTION_NAMES = 'attribute block constant cycle date dump include ' + + 'max min parent random range source template_from_string'; + + var FUNCTIONS = { + beginKeywords: FUNCTION_NAMES, + keywords: {name: FUNCTION_NAMES}, + relevance: 0, + contains: [ + PARAMS + ] + }; + + var FILTER = { + begin: /\|[A-Za-z_]+:?/, + keywords: + 'abs batch capitalize column convert_encoding date date_modify default ' + + 'escape filter first format inky_to_html inline_css join json_encode keys last ' + + 'length lower map markdown merge nl2br number_format raw reduce replace ' + + 'reverse round slice sort spaceless split striptags title trim upper url_encode', + contains: [ + FUNCTIONS + ] + }; + + var TAGS = 'apply autoescape block deprecated do embed extends filter flush for from ' + + 'if import include macro sandbox set use verbatim with'; + + TAGS = TAGS + ' ' + TAGS.split(' ').map(function(t){return 'end' + t}).join(' '); + + return { + name: 'Twig', + aliases: ['craftcms'], + case_insensitive: true, + subLanguage: 'xml', + contains: [ + hljs.COMMENT(/\{#/, /#\}/), + { + className: 'template-tag', + begin: /\{%/, end: /%\}/, + contains: [ + { + className: 'name', + begin: /\w+/, + keywords: TAGS, + starts: { + endsWithParent: true, + contains: [FILTER, FUNCTIONS], + relevance: 0 + } + } + ] + }, + { + className: 'template-variable', + begin: /\{\{/, end: /\}\}/, + contains: ['self', FILTER, FUNCTIONS] + } + ] + }; +} + +module.exports = twig; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/typescript.js b/claude-code-source/node_modules/highlight.js/lib/languages/typescript.js new file mode 100644 index 00000000..24202814 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/typescript.js @@ -0,0 +1,697 @@ +const IDENT_RE = '[A-Za-z$_][0-9A-Za-z$_]*'; +const KEYWORDS = [ + "as", // for exports + "in", + "of", + "if", + "for", + "while", + "finally", + "var", + "new", + "function", + "do", + "return", + "void", + "else", + "break", + "catch", + "instanceof", + "with", + "throw", + "case", + "default", + "try", + "switch", + "continue", + "typeof", + "delete", + "let", + "yield", + "const", + "class", + // JS handles these with a special rule + // "get", + // "set", + "debugger", + "async", + "await", + "static", + "import", + "from", + "export", + "extends" +]; +const LITERALS = [ + "true", + "false", + "null", + "undefined", + "NaN", + "Infinity" +]; + +const TYPES = [ + "Intl", + "DataView", + "Number", + "Math", + "Date", + "String", + "RegExp", + "Object", + "Function", + "Boolean", + "Error", + "Symbol", + "Set", + "Map", + "WeakSet", + "WeakMap", + "Proxy", + "Reflect", + "JSON", + "Promise", + "Float64Array", + "Int16Array", + "Int32Array", + "Int8Array", + "Uint16Array", + "Uint32Array", + "Float32Array", + "Array", + "Uint8Array", + "Uint8ClampedArray", + "ArrayBuffer", + "BigInt64Array", + "BigUint64Array", + "BigInt" +]; + +const ERROR_TYPES = [ + "EvalError", + "InternalError", + "RangeError", + "ReferenceError", + "SyntaxError", + "TypeError", + "URIError" +]; + +const BUILT_IN_GLOBALS = [ + "setInterval", + "setTimeout", + "clearInterval", + "clearTimeout", + + "require", + "exports", + + "eval", + "isFinite", + "isNaN", + "parseFloat", + "parseInt", + "decodeURI", + "decodeURIComponent", + "encodeURI", + "encodeURIComponent", + "escape", + "unescape" +]; + +const BUILT_IN_VARIABLES = [ + "arguments", + "this", + "super", + "console", + "window", + "document", + "localStorage", + "module", + "global" // Node.js +]; + +const BUILT_INS = [].concat( + BUILT_IN_GLOBALS, + BUILT_IN_VARIABLES, + TYPES, + ERROR_TYPES +); + +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function lookahead(re) { + return concat('(?=', re, ')'); +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/* +Language: JavaScript +Description: JavaScript (JS) is a lightweight, interpreted, or just-in-time compiled programming language with first-class functions. +Category: common, scripting +Website: https://developer.mozilla.org/en-US/docs/Web/JavaScript +*/ + +/** @type LanguageFn */ +function javascript(hljs) { + /** + * Takes a string like " { + const tag = "', + end: '' + }; + const XML_TAG = { + begin: /<[A-Za-z0-9\\._:-]+/, + end: /\/[A-Za-z0-9\\._:-]+>|\/>/, + /** + * @param {RegExpMatchArray} match + * @param {CallbackResponse} response + */ + isTrulyOpeningTag: (match, response) => { + const afterMatchIndex = match[0].length + match.index; + const nextChar = match.input[afterMatchIndex]; + // nested type? + // HTML should not include another raw `<` inside a tag + // But a type might: `>`, etc. + if (nextChar === "<") { + response.ignoreMatch(); + return; + } + // + // This is now either a tag or a type. + if (nextChar === ">") { + // if we cannot find a matching closing tag, then we + // will ignore it + if (!hasClosingTag(match, { after: afterMatchIndex })) { + response.ignoreMatch(); + } + } + } + }; + const KEYWORDS$1 = { + $pattern: IDENT_RE, + keyword: KEYWORDS, + literal: LITERALS, + built_in: BUILT_INS + }; + + // https://tc39.es/ecma262/#sec-literals-numeric-literals + const decimalDigits = '[0-9](_?[0-9])*'; + const frac = `\\.(${decimalDigits})`; + // DecimalIntegerLiteral, including Annex B NonOctalDecimalIntegerLiteral + // https://tc39.es/ecma262/#sec-additional-syntax-numeric-literals + const decimalInteger = `0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*`; + const NUMBER = { + className: 'number', + variants: [ + // DecimalLiteral + { begin: `(\\b(${decimalInteger})((${frac})|\\.)?|(${frac}))` + + `[eE][+-]?(${decimalDigits})\\b` }, + { begin: `\\b(${decimalInteger})\\b((${frac})\\b|\\.)?|(${frac})\\b` }, + + // DecimalBigIntegerLiteral + { begin: `\\b(0|[1-9](_?[0-9])*)n\\b` }, + + // NonDecimalIntegerLiteral + { begin: "\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b" }, + { begin: "\\b0[bB][0-1](_?[0-1])*n?\\b" }, + { begin: "\\b0[oO][0-7](_?[0-7])*n?\\b" }, + + // LegacyOctalIntegerLiteral (does not include underscore separators) + // https://tc39.es/ecma262/#sec-additional-syntax-numeric-literals + { begin: "\\b0[0-7]+n?\\b" }, + ], + relevance: 0 + }; + + const SUBST = { + className: 'subst', + begin: '\\$\\{', + end: '\\}', + keywords: KEYWORDS$1, + contains: [] // defined later + }; + const HTML_TEMPLATE = { + begin: 'html`', + end: '', + starts: { + end: '`', + returnEnd: false, + contains: [ + hljs.BACKSLASH_ESCAPE, + SUBST + ], + subLanguage: 'xml' + } + }; + const CSS_TEMPLATE = { + begin: 'css`', + end: '', + starts: { + end: '`', + returnEnd: false, + contains: [ + hljs.BACKSLASH_ESCAPE, + SUBST + ], + subLanguage: 'css' + } + }; + const TEMPLATE_STRING = { + className: 'string', + begin: '`', + end: '`', + contains: [ + hljs.BACKSLASH_ESCAPE, + SUBST + ] + }; + const JSDOC_COMMENT = hljs.COMMENT( + /\/\*\*(?!\/)/, + '\\*/', + { + relevance: 0, + contains: [ + { + className: 'doctag', + begin: '@[A-Za-z]+', + contains: [ + { + className: 'type', + begin: '\\{', + end: '\\}', + relevance: 0 + }, + { + className: 'variable', + begin: IDENT_RE$1 + '(?=\\s*(-)|$)', + endsParent: true, + relevance: 0 + }, + // eat spaces (not newlines) so we can find + // types or variables + { + begin: /(?=[^\n])\s/, + relevance: 0 + } + ] + } + ] + } + ); + const COMMENT = { + className: "comment", + variants: [ + JSDOC_COMMENT, + hljs.C_BLOCK_COMMENT_MODE, + hljs.C_LINE_COMMENT_MODE + ] + }; + const SUBST_INTERNALS = [ + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + HTML_TEMPLATE, + CSS_TEMPLATE, + TEMPLATE_STRING, + NUMBER, + hljs.REGEXP_MODE + ]; + SUBST.contains = SUBST_INTERNALS + .concat({ + // we need to pair up {} inside our subst to prevent + // it from ending too early by matching another } + begin: /\{/, + end: /\}/, + keywords: KEYWORDS$1, + contains: [ + "self" + ].concat(SUBST_INTERNALS) + }); + const SUBST_AND_COMMENTS = [].concat(COMMENT, SUBST.contains); + const PARAMS_CONTAINS = SUBST_AND_COMMENTS.concat([ + // eat recursive parens in sub expressions + { + begin: /\(/, + end: /\)/, + keywords: KEYWORDS$1, + contains: ["self"].concat(SUBST_AND_COMMENTS) + } + ]); + const PARAMS = { + className: 'params', + begin: /\(/, + end: /\)/, + excludeBegin: true, + excludeEnd: true, + keywords: KEYWORDS$1, + contains: PARAMS_CONTAINS + }; + + return { + name: 'Javascript', + aliases: ['js', 'jsx', 'mjs', 'cjs'], + keywords: KEYWORDS$1, + // this will be extended by TypeScript + exports: { PARAMS_CONTAINS }, + illegal: /#(?![$_A-z])/, + contains: [ + hljs.SHEBANG({ + label: "shebang", + binary: "node", + relevance: 5 + }), + { + label: "use_strict", + className: 'meta', + relevance: 10, + begin: /^\s*['"]use (strict|asm)['"]/ + }, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + HTML_TEMPLATE, + CSS_TEMPLATE, + TEMPLATE_STRING, + COMMENT, + NUMBER, + { // object attr container + begin: concat(/[{,\n]\s*/, + // we need to look ahead to make sure that we actually have an + // attribute coming up so we don't steal a comma from a potential + // "value" container + // + // NOTE: this might not work how you think. We don't actually always + // enter this mode and stay. Instead it might merely match `, + // ` and then immediately end after the , because it + // fails to find any actual attrs. But this still does the job because + // it prevents the value contain rule from grabbing this instead and + // prevening this rule from firing when we actually DO have keys. + lookahead(concat( + // we also need to allow for multiple possible comments inbetween + // the first key:value pairing + /(((\/\/.*$)|(\/\*(\*[^/]|[^*])*\*\/))\s*)*/, + IDENT_RE$1 + '\\s*:'))), + relevance: 0, + contains: [ + { + className: 'attr', + begin: IDENT_RE$1 + lookahead('\\s*:'), + relevance: 0 + } + ] + }, + { // "value" container + begin: '(' + hljs.RE_STARTERS_RE + '|\\b(case|return|throw)\\b)\\s*', + keywords: 'return throw case', + contains: [ + COMMENT, + hljs.REGEXP_MODE, + { + className: 'function', + // we have to count the parens to make sure we actually have the + // correct bounding ( ) before the =>. There could be any number of + // sub-expressions inside also surrounded by parens. + begin: '(\\(' + + '[^()]*(\\(' + + '[^()]*(\\(' + + '[^()]*' + + '\\)[^()]*)*' + + '\\)[^()]*)*' + + '\\)|' + hljs.UNDERSCORE_IDENT_RE + ')\\s*=>', + returnBegin: true, + end: '\\s*=>', + contains: [ + { + className: 'params', + variants: [ + { + begin: hljs.UNDERSCORE_IDENT_RE, + relevance: 0 + }, + { + className: null, + begin: /\(\s*\)/, + skip: true + }, + { + begin: /\(/, + end: /\)/, + excludeBegin: true, + excludeEnd: true, + keywords: KEYWORDS$1, + contains: PARAMS_CONTAINS + } + ] + } + ] + }, + { // could be a comma delimited list of params to a function call + begin: /,/, relevance: 0 + }, + { + className: '', + begin: /\s/, + end: /\s*/, + skip: true + }, + { // JSX + variants: [ + { begin: FRAGMENT.begin, end: FRAGMENT.end }, + { + begin: XML_TAG.begin, + // we carefully check the opening tag to see if it truly + // is a tag and not a false positive + 'on:begin': XML_TAG.isTrulyOpeningTag, + end: XML_TAG.end + } + ], + subLanguage: 'xml', + contains: [ + { + begin: XML_TAG.begin, + end: XML_TAG.end, + skip: true, + contains: ['self'] + } + ] + } + ], + relevance: 0 + }, + { + className: 'function', + beginKeywords: 'function', + end: /[{;]/, + excludeEnd: true, + keywords: KEYWORDS$1, + contains: [ + 'self', + hljs.inherit(hljs.TITLE_MODE, { begin: IDENT_RE$1 }), + PARAMS + ], + illegal: /%/ + }, + { + // prevent this from getting swallowed up by function + // since they appear "function like" + beginKeywords: "while if switch catch for" + }, + { + className: 'function', + // we have to count the parens to make sure we actually have the correct + // bounding ( ). There could be any number of sub-expressions inside + // also surrounded by parens. + begin: hljs.UNDERSCORE_IDENT_RE + + '\\(' + // first parens + '[^()]*(\\(' + + '[^()]*(\\(' + + '[^()]*' + + '\\)[^()]*)*' + + '\\)[^()]*)*' + + '\\)\\s*\\{', // end parens + returnBegin:true, + contains: [ + PARAMS, + hljs.inherit(hljs.TITLE_MODE, { begin: IDENT_RE$1 }), + ] + }, + // hack: prevents detection of keywords in some circumstances + // .keyword() + // $keyword = x + { + variants: [ + { begin: '\\.' + IDENT_RE$1 }, + { begin: '\\$' + IDENT_RE$1 } + ], + relevance: 0 + }, + { // ES6 class + className: 'class', + beginKeywords: 'class', + end: /[{;=]/, + excludeEnd: true, + illegal: /[:"[\]]/, + contains: [ + { beginKeywords: 'extends' }, + hljs.UNDERSCORE_TITLE_MODE + ] + }, + { + begin: /\b(?=constructor)/, + end: /[{;]/, + excludeEnd: true, + contains: [ + hljs.inherit(hljs.TITLE_MODE, { begin: IDENT_RE$1 }), + 'self', + PARAMS + ] + }, + { + begin: '(get|set)\\s+(?=' + IDENT_RE$1 + '\\()', + end: /\{/, + keywords: "get set", + contains: [ + hljs.inherit(hljs.TITLE_MODE, { begin: IDENT_RE$1 }), + { begin: /\(\)/ }, // eat to avoid empty params + PARAMS + ] + }, + { + begin: /\$[(.]/ // relevance booster for a pattern common to JS libs: `$(something)` and `$.something` + } + ] + }; +} + +/* +Language: TypeScript +Author: Panu Horsmalahti +Contributors: Ike Ku +Description: TypeScript is a strict superset of JavaScript +Website: https://www.typescriptlang.org +Category: common, scripting +*/ + +/** @type LanguageFn */ +function typescript(hljs) { + const IDENT_RE$1 = IDENT_RE; + const NAMESPACE = { + beginKeywords: 'namespace', end: /\{/, excludeEnd: true + }; + const INTERFACE = { + beginKeywords: 'interface', end: /\{/, excludeEnd: true, + keywords: 'interface extends' + }; + const USE_STRICT = { + className: 'meta', + relevance: 10, + begin: /^\s*['"]use strict['"]/ + }; + const TYPES = [ + "any", + "void", + "number", + "boolean", + "string", + "object", + "never", + "enum" + ]; + const TS_SPECIFIC_KEYWORDS = [ + "type", + "namespace", + "typedef", + "interface", + "public", + "private", + "protected", + "implements", + "declare", + "abstract", + "readonly" + ]; + const KEYWORDS$1 = { + $pattern: IDENT_RE, + keyword: KEYWORDS.concat(TS_SPECIFIC_KEYWORDS), + literal: LITERALS, + built_in: BUILT_INS.concat(TYPES) + }; + const DECORATOR = { + className: 'meta', + begin: '@' + IDENT_RE$1, + }; + + const swapMode = (mode, label, replacement) => { + const indx = mode.contains.findIndex(m => m.label === label); + if (indx === -1) { throw new Error("can not find mode to replace"); } + mode.contains.splice(indx, 1, replacement); + }; + + const tsLanguage = javascript(hljs); + + // this should update anywhere keywords is used since + // it will be the same actual JS object + Object.assign(tsLanguage.keywords, KEYWORDS$1); + + tsLanguage.exports.PARAMS_CONTAINS.push(DECORATOR); + tsLanguage.contains = tsLanguage.contains.concat([ + DECORATOR, + NAMESPACE, + INTERFACE, + ]); + + // TS gets a simpler shebang rule than JS + swapMode(tsLanguage, "shebang", hljs.SHEBANG()); + // JS use strict rule purposely excludes `asm` which makes no sense + swapMode(tsLanguage, "use_strict", USE_STRICT); + + const functionDeclaration = tsLanguage.contains.find(m => m.className === "function"); + functionDeclaration.relevance = 0; // () => {} is more typical in TypeScript + + Object.assign(tsLanguage, { + name: 'TypeScript', + aliases: ['ts', 'tsx'] + }); + + return tsLanguage; +} + +module.exports = typescript; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/vala.js b/claude-code-source/node_modules/highlight.js/lib/languages/vala.js new file mode 100644 index 00000000..e3a577de --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/vala.js @@ -0,0 +1,61 @@ +/* +Language: Vala +Author: Antono Vasiljev +Description: Vala is a new programming language that aims to bring modern programming language features to GNOME developers without imposing any additional runtime requirements and without using a different ABI compared to applications and libraries written in C. +Website: https://wiki.gnome.org/Projects/Vala +*/ + +function vala(hljs) { + return { + name: 'Vala', + keywords: { + keyword: + // Value types + 'char uchar unichar int uint long ulong short ushort int8 int16 int32 int64 uint8 ' + + 'uint16 uint32 uint64 float double bool struct enum string void ' + + // Reference types + 'weak unowned owned ' + + // Modifiers + 'async signal static abstract interface override virtual delegate ' + + // Control Structures + 'if while do for foreach else switch case break default return try catch ' + + // Visibility + 'public private protected internal ' + + // Other + 'using new this get set const stdout stdin stderr var', + built_in: + 'DBus GLib CCode Gee Object Gtk Posix', + literal: + 'false true null' + }, + contains: [ + { + className: 'class', + beginKeywords: 'class interface namespace', + end: /\{/, + excludeEnd: true, + illegal: '[^,:\\n\\s\\.]', + contains: [ hljs.UNDERSCORE_TITLE_MODE ] + }, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + { + className: 'string', + begin: '"""', + end: '"""', + relevance: 5 + }, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + hljs.C_NUMBER_MODE, + { + className: 'meta', + begin: '^#', + end: '$', + relevance: 2 + } + ] + }; +} + +module.exports = vala; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/vbnet.js b/claude-code-source/node_modules/highlight.js/lib/languages/vbnet.js new file mode 100644 index 00000000..5afe2ebe --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/vbnet.js @@ -0,0 +1,214 @@ +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/** + * Any of the passed expresssions may match + * + * Creates a huge this | this | that | that match + * @param {(RegExp | string)[] } args + * @returns {string} + */ +function either(...args) { + const joined = '(' + args.map((x) => source(x)).join("|") + ")"; + return joined; +} + +/* +Language: Visual Basic .NET +Description: Visual Basic .NET (VB.NET) is a multi-paradigm, object-oriented programming language, implemented on the .NET Framework. +Authors: Poren Chiang , Jan Pilzer +Website: https://docs.microsoft.com/dotnet/visual-basic/getting-started +Category: common +*/ + +/** @type LanguageFn */ +function vbnet(hljs) { + /** + * Character Literal + * Either a single character ("a"C) or an escaped double quote (""""C). + */ + const CHARACTER = { + className: 'string', + begin: /"(""|[^/n])"C\b/ + }; + + const STRING = { + className: 'string', + begin: /"/, + end: /"/, + illegal: /\n/, + contains: [ + { + // double quote escape + begin: /""/ + } + ] + }; + + /** Date Literals consist of a date, a time, or both separated by whitespace, surrounded by # */ + const MM_DD_YYYY = /\d{1,2}\/\d{1,2}\/\d{4}/; + const YYYY_MM_DD = /\d{4}-\d{1,2}-\d{1,2}/; + const TIME_12H = /(\d|1[012])(:\d+){0,2} *(AM|PM)/; + const TIME_24H = /\d{1,2}(:\d{1,2}){1,2}/; + const DATE = { + className: 'literal', + variants: [ + { + // #YYYY-MM-DD# (ISO-Date) or #M/D/YYYY# (US-Date) + begin: concat(/# */, either(YYYY_MM_DD, MM_DD_YYYY), / *#/) + }, + { + // #H:mm[:ss]# (24h Time) + begin: concat(/# */, TIME_24H, / *#/) + }, + { + // #h[:mm[:ss]] A# (12h Time) + begin: concat(/# */, TIME_12H, / *#/) + }, + { + // date plus time + begin: concat( + /# */, + either(YYYY_MM_DD, MM_DD_YYYY), + / +/, + either(TIME_12H, TIME_24H), + / *#/ + ) + } + ] + }; + + const NUMBER = { + className: 'number', + relevance: 0, + variants: [ + { + // Float + begin: /\b\d[\d_]*((\.[\d_]+(E[+-]?[\d_]+)?)|(E[+-]?[\d_]+))[RFD@!#]?/ + }, + { + // Integer (base 10) + begin: /\b\d[\d_]*((U?[SIL])|[%&])?/ + }, + { + // Integer (base 16) + begin: /&H[\dA-F_]+((U?[SIL])|[%&])?/ + }, + { + // Integer (base 8) + begin: /&O[0-7_]+((U?[SIL])|[%&])?/ + }, + { + // Integer (base 2) + begin: /&B[01_]+((U?[SIL])|[%&])?/ + } + ] + }; + + const LABEL = { + className: 'label', + begin: /^\w+:/ + }; + + const DOC_COMMENT = hljs.COMMENT(/'''/, /$/, { + contains: [ + { + className: 'doctag', + begin: /<\/?/, + end: />/ + } + ] + }); + + const COMMENT = hljs.COMMENT(null, /$/, { + variants: [ + { + begin: /'/ + }, + { + // TODO: Use `beforeMatch:` for leading spaces + begin: /([\t ]|^)REM(?=\s)/ + } + ] + }); + + const DIRECTIVES = { + className: 'meta', + // TODO: Use `beforeMatch:` for indentation once available + begin: /[\t ]*#(const|disable|else|elseif|enable|end|externalsource|if|region)\b/, + end: /$/, + keywords: { + 'meta-keyword': + 'const disable else elseif enable end externalsource if region then' + }, + contains: [ COMMENT ] + }; + + return { + name: 'Visual Basic .NET', + aliases: [ 'vb' ], + case_insensitive: true, + classNameAliases: { + label: 'symbol' + }, + keywords: { + keyword: + 'addhandler alias aggregate ansi as async assembly auto binary by byref byval ' + /* a-b */ + 'call case catch class compare const continue custom declare default delegate dim distinct do ' + /* c-d */ + 'each equals else elseif end enum erase error event exit explicit finally for friend from function ' + /* e-f */ + 'get global goto group handles if implements imports in inherits interface into iterator ' + /* g-i */ + 'join key let lib loop me mid module mustinherit mustoverride mybase myclass ' + /* j-m */ + 'namespace narrowing new next notinheritable notoverridable ' + /* n */ + 'of off on operator option optional order overloads overridable overrides ' + /* o */ + 'paramarray partial preserve private property protected public ' + /* p */ + 'raiseevent readonly redim removehandler resume return ' + /* r */ + 'select set shadows shared skip static step stop structure strict sub synclock ' + /* s */ + 'take text then throw to try unicode until using when where while widening with withevents writeonly yield' /* t-y */, + built_in: + // Operators https://docs.microsoft.com/dotnet/visual-basic/language-reference/operators + 'addressof and andalso await directcast gettype getxmlnamespace is isfalse isnot istrue like mod nameof new not or orelse trycast typeof xor ' + + // Type Conversion Functions https://docs.microsoft.com/dotnet/visual-basic/language-reference/functions/type-conversion-functions + 'cbool cbyte cchar cdate cdbl cdec cint clng cobj csbyte cshort csng cstr cuint culng cushort', + type: + // Data types https://docs.microsoft.com/dotnet/visual-basic/language-reference/data-types + 'boolean byte char date decimal double integer long object sbyte short single string uinteger ulong ushort', + literal: 'true false nothing' + }, + illegal: + '//|\\{|\\}|endif|gosub|variant|wend|^\\$ ' /* reserved deprecated keywords */, + contains: [ + CHARACTER, + STRING, + DATE, + NUMBER, + LABEL, + DOC_COMMENT, + COMMENT, + DIRECTIVES + ] + }; +} + +module.exports = vbnet; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/vbscript-html.js b/claude-code-source/node_modules/highlight.js/lib/languages/vbscript-html.js new file mode 100644 index 00000000..24c13193 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/vbscript-html.js @@ -0,0 +1,24 @@ +/* +Language: VBScript in HTML +Requires: xml.js, vbscript.js +Author: Ivan Sagalaev +Description: "Bridge" language defining fragments of VBScript in HTML within <% .. %> +Website: https://en.wikipedia.org/wiki/VBScript +Category: scripting +*/ + +function vbscriptHtml(hljs) { + return { + name: 'VBScript in HTML', + subLanguage: 'xml', + contains: [ + { + begin: '<%', + end: '%>', + subLanguage: 'vbscript' + } + ] + }; +} + +module.exports = vbscriptHtml; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/vbscript.js b/claude-code-source/node_modules/highlight.js/lib/languages/vbscript.js new file mode 100644 index 00000000..ad09830d --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/vbscript.js @@ -0,0 +1,109 @@ +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/** + * Any of the passed expresssions may match + * + * Creates a huge this | this | that | that match + * @param {(RegExp | string)[] } args + * @returns {string} + */ +function either(...args) { + const joined = '(' + args.map((x) => source(x)).join("|") + ")"; + return joined; +} + +/* +Language: VBScript +Description: VBScript ("Microsoft Visual Basic Scripting Edition") is an Active Scripting language developed by Microsoft that is modeled on Visual Basic. +Author: Nikita Ledyaev +Contributors: Michal Gabrukiewicz +Website: https://en.wikipedia.org/wiki/VBScript +Category: scripting +*/ + +/** @type LanguageFn */ +function vbscript(hljs) { + const BUILT_IN_FUNCTIONS = ('lcase month vartype instrrev ubound setlocale getobject rgb getref string ' + + 'weekdayname rnd dateadd monthname now day minute isarray cbool round formatcurrency ' + + 'conversions csng timevalue second year space abs clng timeserial fixs len asc ' + + 'isempty maths dateserial atn timer isobject filter weekday datevalue ccur isdate ' + + 'instr datediff formatdatetime replace isnull right sgn array snumeric log cdbl hex ' + + 'chr lbound msgbox ucase getlocale cos cdate cbyte rtrim join hour oct typename trim ' + + 'strcomp int createobject loadpicture tan formatnumber mid ' + + 'split cint sin datepart ltrim sqr ' + + 'time derived eval date formatpercent exp inputbox left ascw ' + + 'chrw regexp cstr err').split(" "); + const BUILT_IN_OBJECTS = [ + "server", + "response", + "request", + // take no arguments so can be called without () + "scriptengine", + "scriptenginebuildversion", + "scriptengineminorversion", + "scriptenginemajorversion" + ]; + + const BUILT_IN_CALL = { + begin: concat(either(...BUILT_IN_FUNCTIONS), "\\s*\\("), + // relevance 0 because this is acting as a beginKeywords really + relevance:0, + keywords: { + built_in: BUILT_IN_FUNCTIONS + } + }; + + return { + name: 'VBScript', + aliases: ['vbs'], + case_insensitive: true, + keywords: { + keyword: + 'call class const dim do loop erase execute executeglobal exit for each next function ' + + 'if then else on error option explicit new private property let get public randomize ' + + 'redim rem select case set stop sub while wend with end to elseif is or xor and not ' + + 'class_initialize class_terminate default preserve in me byval byref step resume goto', + built_in: BUILT_IN_OBJECTS, + literal: + 'true false null nothing empty' + }, + illegal: '//', + contains: [ + BUILT_IN_CALL, + hljs.inherit(hljs.QUOTE_STRING_MODE, {contains: [{begin: '""'}]}), + hljs.COMMENT( + /'/, + /$/, + { + relevance: 0 + } + ), + hljs.C_NUMBER_MODE + ] + }; +} + +module.exports = vbscript; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/verilog.js b/claude-code-source/node_modules/highlight.js/lib/languages/verilog.js new file mode 100644 index 00000000..b5435ee5 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/verilog.js @@ -0,0 +1,131 @@ +/* +Language: Verilog +Author: Jon Evans +Contributors: Boone Severson +Description: Verilog is a hardware description language used in electronic design automation to describe digital and mixed-signal systems. This highlighter supports Verilog and SystemVerilog through IEEE 1800-2012. +Website: http://www.verilog.com +*/ + +function verilog(hljs) { + const SV_KEYWORDS = { + $pattern: /[\w\$]+/, + keyword: + 'accept_on alias always always_comb always_ff always_latch and assert assign ' + + 'assume automatic before begin bind bins binsof bit break buf|0 bufif0 bufif1 ' + + 'byte case casex casez cell chandle checker class clocking cmos config const ' + + 'constraint context continue cover covergroup coverpoint cross deassign default ' + + 'defparam design disable dist do edge else end endcase endchecker endclass ' + + 'endclocking endconfig endfunction endgenerate endgroup endinterface endmodule ' + + 'endpackage endprimitive endprogram endproperty endspecify endsequence endtable ' + + 'endtask enum event eventually expect export extends extern final first_match for ' + + 'force foreach forever fork forkjoin function generate|5 genvar global highz0 highz1 ' + + 'if iff ifnone ignore_bins illegal_bins implements implies import incdir include ' + + 'initial inout input inside instance int integer interconnect interface intersect ' + + 'join join_any join_none large let liblist library local localparam logic longint ' + + 'macromodule matches medium modport module nand negedge nettype new nexttime nmos ' + + 'nor noshowcancelled not notif0 notif1 or output package packed parameter pmos ' + + 'posedge primitive priority program property protected pull0 pull1 pulldown pullup ' + + 'pulsestyle_ondetect pulsestyle_onevent pure rand randc randcase randsequence rcmos ' + + 'real realtime ref reg reject_on release repeat restrict return rnmos rpmos rtran ' + + 'rtranif0 rtranif1 s_always s_eventually s_nexttime s_until s_until_with scalared ' + + 'sequence shortint shortreal showcancelled signed small soft solve specify specparam ' + + 'static string strong strong0 strong1 struct super supply0 supply1 sync_accept_on ' + + 'sync_reject_on table tagged task this throughout time timeprecision timeunit tran ' + + 'tranif0 tranif1 tri tri0 tri1 triand trior trireg type typedef union unique unique0 ' + + 'unsigned until until_with untyped use uwire var vectored virtual void wait wait_order ' + + 'wand weak weak0 weak1 while wildcard wire with within wor xnor xor', + literal: + 'null', + built_in: + '$finish $stop $exit $fatal $error $warning $info $realtime $time $printtimescale ' + + '$bitstoreal $bitstoshortreal $itor $signed $cast $bits $stime $timeformat ' + + '$realtobits $shortrealtobits $rtoi $unsigned $asserton $assertkill $assertpasson ' + + '$assertfailon $assertnonvacuouson $assertoff $assertcontrol $assertpassoff ' + + '$assertfailoff $assertvacuousoff $isunbounded $sampled $fell $changed $past_gclk ' + + '$fell_gclk $changed_gclk $rising_gclk $steady_gclk $coverage_control ' + + '$coverage_get $coverage_save $set_coverage_db_name $rose $stable $past ' + + '$rose_gclk $stable_gclk $future_gclk $falling_gclk $changing_gclk $display ' + + '$coverage_get_max $coverage_merge $get_coverage $load_coverage_db $typename ' + + '$unpacked_dimensions $left $low $increment $clog2 $ln $log10 $exp $sqrt $pow ' + + '$floor $ceil $sin $cos $tan $countbits $onehot $isunknown $fatal $warning ' + + '$dimensions $right $high $size $asin $acos $atan $atan2 $hypot $sinh $cosh ' + + '$tanh $asinh $acosh $atanh $countones $onehot0 $error $info $random ' + + '$dist_chi_square $dist_erlang $dist_exponential $dist_normal $dist_poisson ' + + '$dist_t $dist_uniform $q_initialize $q_remove $q_exam $async$and$array ' + + '$async$nand$array $async$or$array $async$nor$array $sync$and$array ' + + '$sync$nand$array $sync$or$array $sync$nor$array $q_add $q_full $psprintf ' + + '$async$and$plane $async$nand$plane $async$or$plane $async$nor$plane ' + + '$sync$and$plane $sync$nand$plane $sync$or$plane $sync$nor$plane $system ' + + '$display $displayb $displayh $displayo $strobe $strobeb $strobeh $strobeo ' + + '$write $readmemb $readmemh $writememh $value$plusargs ' + + '$dumpvars $dumpon $dumplimit $dumpports $dumpportson $dumpportslimit ' + + '$writeb $writeh $writeo $monitor $monitorb $monitorh $monitoro $writememb ' + + '$dumpfile $dumpoff $dumpall $dumpflush $dumpportsoff $dumpportsall ' + + '$dumpportsflush $fclose $fdisplay $fdisplayb $fdisplayh $fdisplayo ' + + '$fstrobe $fstrobeb $fstrobeh $fstrobeo $swrite $swriteb $swriteh ' + + '$swriteo $fscanf $fread $fseek $fflush $feof $fopen $fwrite $fwriteb ' + + '$fwriteh $fwriteo $fmonitor $fmonitorb $fmonitorh $fmonitoro $sformat ' + + '$sformatf $fgetc $ungetc $fgets $sscanf $rewind $ftell $ferror' + }; + + return { + name: 'Verilog', + aliases: [ + 'v', + 'sv', + 'svh' + ], + case_insensitive: false, + keywords: SV_KEYWORDS, + contains: [ + hljs.C_BLOCK_COMMENT_MODE, + hljs.C_LINE_COMMENT_MODE, + hljs.QUOTE_STRING_MODE, + { + className: 'number', + contains: [ hljs.BACKSLASH_ESCAPE ], + variants: [ + { + begin: '\\b((\\d+\'(b|h|o|d|B|H|O|D))[0-9xzXZa-fA-F_]+)' + }, + { + begin: '\\B((\'(b|h|o|d|B|H|O|D))[0-9xzXZa-fA-F_]+)' + }, + { + begin: '\\b([0-9_])+', + relevance: 0 + } + ] + }, + /* parameters to instances */ + { + className: 'variable', + variants: [ + { + begin: '#\\((?!parameter).+\\)' + }, + { + begin: '\\.\\w+', + relevance: 0 + } + ] + }, + { + className: 'meta', + begin: '`', + end: '$', + keywords: { + 'meta-keyword': + 'define __FILE__ ' + + '__LINE__ begin_keywords celldefine default_nettype define ' + + 'else elsif end_keywords endcelldefine endif ifdef ifndef ' + + 'include line nounconnected_drive pragma resetall timescale ' + + 'unconnected_drive undef undefineall' + }, + relevance: 0 + } + ] + }; +} + +module.exports = verilog; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/vhdl.js b/claude-code-source/node_modules/highlight.js/lib/languages/vhdl.js new file mode 100644 index 00000000..80966add --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/vhdl.js @@ -0,0 +1,71 @@ +/* +Language: VHDL +Author: Igor Kalnitsky +Contributors: Daniel C.K. Kho , Guillaume Savaton +Description: VHDL is a hardware description language used in electronic design automation to describe digital and mixed-signal systems. +Website: https://en.wikipedia.org/wiki/VHDL +*/ + +function vhdl(hljs) { + // Regular expression for VHDL numeric literals. + + // Decimal literal: + const INTEGER_RE = '\\d(_|\\d)*'; + const EXPONENT_RE = '[eE][-+]?' + INTEGER_RE; + const DECIMAL_LITERAL_RE = INTEGER_RE + '(\\.' + INTEGER_RE + ')?' + '(' + EXPONENT_RE + ')?'; + // Based literal: + const BASED_INTEGER_RE = '\\w+'; + const BASED_LITERAL_RE = INTEGER_RE + '#' + BASED_INTEGER_RE + '(\\.' + BASED_INTEGER_RE + ')?' + '#' + '(' + EXPONENT_RE + ')?'; + + const NUMBER_RE = '\\b(' + BASED_LITERAL_RE + '|' + DECIMAL_LITERAL_RE + ')'; + + return { + name: 'VHDL', + case_insensitive: true, + keywords: { + keyword: + 'abs access after alias all and architecture array assert assume assume_guarantee attribute ' + + 'begin block body buffer bus case component configuration constant context cover disconnect ' + + 'downto default else elsif end entity exit fairness file for force function generate ' + + 'generic group guarded if impure in inertial inout is label library linkage literal ' + + 'loop map mod nand new next nor not null of on open or others out package parameter port ' + + 'postponed procedure process property protected pure range record register reject ' + + 'release rem report restrict restrict_guarantee return rol ror select sequence ' + + 'severity shared signal sla sll sra srl strong subtype then to transport type ' + + 'unaffected units until use variable view vmode vprop vunit wait when while with xnor xor', + built_in: + 'boolean bit character ' + + 'integer time delay_length natural positive ' + + 'string bit_vector file_open_kind file_open_status ' + + 'std_logic std_logic_vector unsigned signed boolean_vector integer_vector ' + + 'std_ulogic std_ulogic_vector unresolved_unsigned u_unsigned unresolved_signed u_signed ' + + 'real_vector time_vector', + literal: + 'false true note warning error failure ' + // severity_level + 'line text side width' // textio + }, + illegal: /\{/, + contains: [ + hljs.C_BLOCK_COMMENT_MODE, // VHDL-2008 block commenting. + hljs.COMMENT('--', '$'), + hljs.QUOTE_STRING_MODE, + { + className: 'number', + begin: NUMBER_RE, + relevance: 0 + }, + { + className: 'string', + begin: '\'(U|X|0|1|Z|W|L|H|-)\'', + contains: [ hljs.BACKSLASH_ESCAPE ] + }, + { + className: 'symbol', + begin: '\'[A-Za-z](_?[A-Za-z0-9])*', + contains: [ hljs.BACKSLASH_ESCAPE ] + } + ] + }; +} + +module.exports = vhdl; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/vim.js b/claude-code-source/node_modules/highlight.js/lib/languages/vim.js new file mode 100644 index 00000000..13810ae8 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/vim.js @@ -0,0 +1,123 @@ +/* +Language: Vim Script +Author: Jun Yang +Description: full keyword and built-in from http://vimdoc.sourceforge.net/htmldoc/ +Website: https://www.vim.org +Category: scripting +*/ + +function vim(hljs) { + return { + name: 'Vim Script', + keywords: { + $pattern: /[!#@\w]+/, + keyword: + // express version except: ! & * < = > !! # @ @@ + 'N|0 P|0 X|0 a|0 ab abc abo al am an|0 ar arga argd arge argdo argg argl argu as au aug aun b|0 bN ba bad bd be bel bf bl bm bn bo bp br brea breaka breakd breakl bro bufdo buffers bun bw c|0 cN cNf ca cabc caddb cad caddf cal cat cb cc ccl cd ce cex cf cfir cgetb cgete cg changes chd che checkt cl cla clo cm cmapc cme cn cnew cnf cno cnorea cnoreme co col colo com comc comp con conf cope ' + + 'cp cpf cq cr cs cst cu cuna cunme cw delm deb debugg delc delf dif diffg diffo diffp diffpu diffs diffthis dig di dl dell dj dli do doautoa dp dr ds dsp e|0 ea ec echoe echoh echom echon el elsei em en endfo endf endt endw ene ex exe exi exu f|0 files filet fin fina fini fir fix fo foldc foldd folddoc foldo for fu go gr grepa gu gv ha helpf helpg helpt hi hid his ia iabc if ij il im imapc ' + + 'ime ino inorea inoreme int is isp iu iuna iunme j|0 ju k|0 keepa kee keepj lN lNf l|0 lad laddb laddf la lan lat lb lc lch lcl lcs le lefta let lex lf lfir lgetb lgete lg lgr lgrepa lh ll lla lli lmak lm lmapc lne lnew lnf ln loadk lo loc lockv lol lope lp lpf lr ls lt lu lua luad luaf lv lvimgrepa lw m|0 ma mak map mapc marks mat me menut mes mk mks mksp mkv mkvie mod mz mzf nbc nb nbs new nm nmapc nme nn nnoreme noa no noh norea noreme norm nu nun nunme ol o|0 om omapc ome on ono onoreme opt ou ounme ow p|0 ' + + 'profd prof pro promptr pc ped pe perld po popu pp pre prev ps pt ptN ptf ptj ptl ptn ptp ptr pts pu pw py3 python3 py3d py3f py pyd pyf quita qa rec red redi redr redraws reg res ret retu rew ri rightb rub rubyd rubyf rund ru rv sN san sa sal sav sb sbN sba sbf sbl sbm sbn sbp sbr scrip scripte scs se setf setg setl sf sfir sh sim sig sil sl sla sm smap smapc sme sn sni sno snor snoreme sor ' + + 'so spelld spe spelli spellr spellu spellw sp spr sre st sta startg startr star stopi stj sts sun sunm sunme sus sv sw sy synti sync tN tabN tabc tabdo tabe tabf tabfir tabl tabm tabnew ' + + 'tabn tabo tabp tabr tabs tab ta tags tc tcld tclf te tf th tj tl tm tn to tp tr try ts tu u|0 undoj undol una unh unl unlo unm unme uns up ve verb vert vim vimgrepa vi viu vie vm vmapc vme vne vn vnoreme vs vu vunme windo w|0 wN wa wh wi winc winp wn wp wq wqa ws wu wv x|0 xa xmapc xm xme xn xnoreme xu xunme y|0 z|0 ~ ' + + // full version + 'Next Print append abbreviate abclear aboveleft all amenu anoremenu args argadd argdelete argedit argglobal arglocal argument ascii autocmd augroup aunmenu buffer bNext ball badd bdelete behave belowright bfirst blast bmodified bnext botright bprevious brewind break breakadd breakdel breaklist browse bunload ' + + 'bwipeout change cNext cNfile cabbrev cabclear caddbuffer caddexpr caddfile call catch cbuffer cclose center cexpr cfile cfirst cgetbuffer cgetexpr cgetfile chdir checkpath checktime clist clast close cmap cmapclear cmenu cnext cnewer cnfile cnoremap cnoreabbrev cnoremenu copy colder colorscheme command comclear compiler continue confirm copen cprevious cpfile cquit crewind cscope cstag cunmap ' + + 'cunabbrev cunmenu cwindow delete delmarks debug debuggreedy delcommand delfunction diffupdate diffget diffoff diffpatch diffput diffsplit digraphs display deletel djump dlist doautocmd doautoall deletep drop dsearch dsplit edit earlier echo echoerr echohl echomsg else elseif emenu endif endfor ' + + 'endfunction endtry endwhile enew execute exit exusage file filetype find finally finish first fixdel fold foldclose folddoopen folddoclosed foldopen function global goto grep grepadd gui gvim hardcopy help helpfind helpgrep helptags highlight hide history insert iabbrev iabclear ijump ilist imap ' + + 'imapclear imenu inoremap inoreabbrev inoremenu intro isearch isplit iunmap iunabbrev iunmenu join jumps keepalt keepmarks keepjumps lNext lNfile list laddexpr laddbuffer laddfile last language later lbuffer lcd lchdir lclose lcscope left leftabove lexpr lfile lfirst lgetbuffer lgetexpr lgetfile lgrep lgrepadd lhelpgrep llast llist lmake lmap lmapclear lnext lnewer lnfile lnoremap loadkeymap loadview ' + + 'lockmarks lockvar lolder lopen lprevious lpfile lrewind ltag lunmap luado luafile lvimgrep lvimgrepadd lwindow move mark make mapclear match menu menutranslate messages mkexrc mksession mkspell mkvimrc mkview mode mzscheme mzfile nbclose nbkey nbsart next nmap nmapclear nmenu nnoremap ' + + 'nnoremenu noautocmd noremap nohlsearch noreabbrev noremenu normal number nunmap nunmenu oldfiles open omap omapclear omenu only onoremap onoremenu options ounmap ounmenu ownsyntax print profdel profile promptfind promptrepl pclose pedit perl perldo pop popup ppop preserve previous psearch ptag ptNext ' + + 'ptfirst ptjump ptlast ptnext ptprevious ptrewind ptselect put pwd py3do py3file python pydo pyfile quit quitall qall read recover redo redir redraw redrawstatus registers resize retab return rewind right rightbelow ruby rubydo rubyfile rundo runtime rviminfo substitute sNext sandbox sargument sall saveas sbuffer sbNext sball sbfirst sblast sbmodified sbnext sbprevious sbrewind scriptnames scriptencoding ' + + 'scscope set setfiletype setglobal setlocal sfind sfirst shell simalt sign silent sleep slast smagic smapclear smenu snext sniff snomagic snoremap snoremenu sort source spelldump spellgood spellinfo spellrepall spellundo spellwrong split sprevious srewind stop stag startgreplace startreplace ' + + 'startinsert stopinsert stjump stselect sunhide sunmap sunmenu suspend sview swapname syntax syntime syncbind tNext tabNext tabclose tabedit tabfind tabfirst tablast tabmove tabnext tabonly tabprevious tabrewind tag tcl tcldo tclfile tearoff tfirst throw tjump tlast tmenu tnext topleft tprevious ' + 'trewind tselect tunmenu undo undojoin undolist unabbreviate unhide unlet unlockvar unmap unmenu unsilent update vglobal version verbose vertical vimgrep vimgrepadd visual viusage view vmap vmapclear vmenu vnew ' + + 'vnoremap vnoremenu vsplit vunmap vunmenu write wNext wall while winsize wincmd winpos wnext wprevious wqall wsverb wundo wviminfo xit xall xmapclear xmap xmenu xnoremap xnoremenu xunmap xunmenu yank', + built_in: // built in func + 'synIDtrans atan2 range matcharg did_filetype asin feedkeys xor argv ' + + 'complete_check add getwinposx getqflist getwinposy screencol ' + + 'clearmatches empty extend getcmdpos mzeval garbagecollect setreg ' + + 'ceil sqrt diff_hlID inputsecret get getfperm getpid filewritable ' + + 'shiftwidth max sinh isdirectory synID system inputrestore winline ' + + 'atan visualmode inputlist tabpagewinnr round getregtype mapcheck ' + + 'hasmapto histdel argidx findfile sha256 exists toupper getcmdline ' + + 'taglist string getmatches bufnr strftime winwidth bufexists ' + + 'strtrans tabpagebuflist setcmdpos remote_read printf setloclist ' + + 'getpos getline bufwinnr float2nr len getcmdtype diff_filler luaeval ' + + 'resolve libcallnr foldclosedend reverse filter has_key bufname ' + + 'str2float strlen setline getcharmod setbufvar index searchpos ' + + 'shellescape undofile foldclosed setqflist buflisted strchars str2nr ' + + 'virtcol floor remove undotree remote_expr winheight gettabwinvar ' + + 'reltime cursor tabpagenr finddir localtime acos getloclist search ' + + 'tanh matchend rename gettabvar strdisplaywidth type abs py3eval ' + + 'setwinvar tolower wildmenumode log10 spellsuggest bufloaded ' + + 'synconcealed nextnonblank server2client complete settabwinvar ' + + 'executable input wincol setmatches getftype hlID inputsave ' + + 'searchpair or screenrow line settabvar histadd deepcopy strpart ' + + 'remote_peek and eval getftime submatch screenchar winsaveview ' + + 'matchadd mkdir screenattr getfontname libcall reltimestr getfsize ' + + 'winnr invert pow getbufline byte2line soundfold repeat fnameescape ' + + 'tagfiles sin strwidth spellbadword trunc maparg log lispindent ' + + 'hostname setpos globpath remote_foreground getchar synIDattr ' + + 'fnamemodify cscope_connection stridx winbufnr indent min ' + + 'complete_add nr2char searchpairpos inputdialog values matchlist ' + + 'items hlexists strridx browsedir expand fmod pathshorten line2byte ' + + 'argc count getwinvar glob foldtextresult getreg foreground cosh ' + + 'matchdelete has char2nr simplify histget searchdecl iconv ' + + 'winrestcmd pumvisible writefile foldlevel haslocaldir keys cos ' + + 'matchstr foldtext histnr tan tempname getcwd byteidx getbufvar ' + + 'islocked escape eventhandler remote_send serverlist winrestview ' + + 'synstack pyeval prevnonblank readfile cindent filereadable changenr ' + + 'exp' + }, + illegal: /;/, + contains: [ + hljs.NUMBER_MODE, + { + className: 'string', + begin: '\'', + end: '\'', + illegal: '\\n' + }, + + /* + A double quote can start either a string or a line comment. Strings are + ended before the end of a line by another double quote and can contain + escaped double-quotes and post-escaped line breaks. + + Also, any double quote at the beginning of a line is a comment but we + don't handle that properly at the moment: any double quote inside will + turn them into a string. Handling it properly will require a smarter + parser. + */ + { + className: 'string', + begin: /"(\\"|\n\\|[^"\n])*"/ + }, + hljs.COMMENT('"', '$'), + + { + className: 'variable', + begin: /[bwtglsav]:[\w\d_]*/ + }, + { + className: 'function', + beginKeywords: 'function function!', + end: '$', + relevance: 0, + contains: [ + hljs.TITLE_MODE, + { + className: 'params', + begin: '\\(', + end: '\\)' + } + ] + }, + { + className: 'symbol', + begin: /<[\w-]+>/ + } + ] + }; +} + +module.exports = vim; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/x86asm.js b/claude-code-source/node_modules/highlight.js/lib/languages/x86asm.js new file mode 100644 index 00000000..8736cf09 --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/x86asm.js @@ -0,0 +1,163 @@ +/* +Language: Intel x86 Assembly +Author: innocenat +Description: x86 assembly language using Intel's mnemonic and NASM syntax +Website: https://en.wikipedia.org/wiki/X86_assembly_language +Category: assembler +*/ + +function x86asm(hljs) { + return { + name: 'Intel x86 Assembly', + case_insensitive: true, + keywords: { + $pattern: '[.%]?' + hljs.IDENT_RE, + keyword: + 'lock rep repe repz repne repnz xaquire xrelease bnd nobnd ' + + 'aaa aad aam aas adc add and arpl bb0_reset bb1_reset bound bsf bsr bswap bt btc btr bts call cbw cdq cdqe clc cld cli clts cmc cmp cmpsb cmpsd cmpsq cmpsw cmpxchg cmpxchg486 cmpxchg8b cmpxchg16b cpuid cpu_read cpu_write cqo cwd cwde daa das dec div dmint emms enter equ f2xm1 fabs fadd faddp fbld fbstp fchs fclex fcmovb fcmovbe fcmove fcmovnb fcmovnbe fcmovne fcmovnu fcmovu fcom fcomi fcomip fcomp fcompp fcos fdecstp fdisi fdiv fdivp fdivr fdivrp femms feni ffree ffreep fiadd ficom ficomp fidiv fidivr fild fimul fincstp finit fist fistp fisttp fisub fisubr fld fld1 fldcw fldenv fldl2e fldl2t fldlg2 fldln2 fldpi fldz fmul fmulp fnclex fndisi fneni fninit fnop fnsave fnstcw fnstenv fnstsw fpatan fprem fprem1 fptan frndint frstor fsave fscale fsetpm fsin fsincos fsqrt fst fstcw fstenv fstp fstsw fsub fsubp fsubr fsubrp ftst fucom fucomi fucomip fucomp fucompp fxam fxch fxtract fyl2x fyl2xp1 hlt ibts icebp idiv imul in inc incbin insb insd insw int int01 int1 int03 int3 into invd invpcid invlpg invlpga iret iretd iretq iretw jcxz jecxz jrcxz jmp jmpe lahf lar lds lea leave les lfence lfs lgdt lgs lidt lldt lmsw loadall loadall286 lodsb lodsd lodsq lodsw loop loope loopne loopnz loopz lsl lss ltr mfence monitor mov movd movq movsb movsd movsq movsw movsx movsxd movzx mul mwait neg nop not or out outsb outsd outsw packssdw packsswb packuswb paddb paddd paddsb paddsiw paddsw paddusb paddusw paddw pand pandn pause paveb pavgusb pcmpeqb pcmpeqd pcmpeqw pcmpgtb pcmpgtd pcmpgtw pdistib pf2id pfacc pfadd pfcmpeq pfcmpge pfcmpgt pfmax pfmin pfmul pfrcp pfrcpit1 pfrcpit2 pfrsqit1 pfrsqrt pfsub pfsubr pi2fd pmachriw pmaddwd pmagw pmulhriw pmulhrwa pmulhrwc pmulhw pmullw pmvgezb pmvlzb pmvnzb pmvzb pop popa popad popaw popf popfd popfq popfw por prefetch prefetchw pslld psllq psllw psrad psraw psrld psrlq psrlw psubb psubd psubsb psubsiw psubsw psubusb psubusw psubw punpckhbw punpckhdq punpckhwd punpcklbw punpckldq punpcklwd push pusha pushad pushaw pushf pushfd pushfq pushfw pxor rcl rcr rdshr rdmsr rdpmc rdtsc rdtscp ret retf retn rol ror rdm rsdc rsldt rsm rsts sahf sal salc sar sbb scasb scasd scasq scasw sfence sgdt shl shld shr shrd sidt sldt skinit smi smint smintold smsw stc std sti stosb stosd stosq stosw str sub svdc svldt svts swapgs syscall sysenter sysexit sysret test ud0 ud1 ud2b ud2 ud2a umov verr verw fwait wbinvd wrshr wrmsr xadd xbts xchg xlatb xlat xor cmove cmovz cmovne cmovnz cmova cmovnbe cmovae cmovnb cmovb cmovnae cmovbe cmovna cmovg cmovnle cmovge cmovnl cmovl cmovnge cmovle cmovng cmovc cmovnc cmovo cmovno cmovs cmovns cmovp cmovpe cmovnp cmovpo je jz jne jnz ja jnbe jae jnb jb jnae jbe jna jg jnle jge jnl jl jnge jle jng jc jnc jo jno js jns jpo jnp jpe jp sete setz setne setnz seta setnbe setae setnb setnc setb setnae setcset setbe setna setg setnle setge setnl setl setnge setle setng sets setns seto setno setpe setp setpo setnp addps addss andnps andps cmpeqps cmpeqss cmpleps cmpless cmpltps cmpltss cmpneqps cmpneqss cmpnleps cmpnless cmpnltps cmpnltss cmpordps cmpordss cmpunordps cmpunordss cmpps cmpss comiss cvtpi2ps cvtps2pi cvtsi2ss cvtss2si cvttps2pi cvttss2si divps divss ldmxcsr maxps maxss minps minss movaps movhps movlhps movlps movhlps movmskps movntps movss movups mulps mulss orps rcpps rcpss rsqrtps rsqrtss shufps sqrtps sqrtss stmxcsr subps subss ucomiss unpckhps unpcklps xorps fxrstor fxrstor64 fxsave fxsave64 xgetbv xsetbv xsave xsave64 xsaveopt xsaveopt64 xrstor xrstor64 prefetchnta prefetcht0 prefetcht1 prefetcht2 maskmovq movntq pavgb pavgw pextrw pinsrw pmaxsw pmaxub pminsw pminub pmovmskb pmulhuw psadbw pshufw pf2iw pfnacc pfpnacc pi2fw pswapd maskmovdqu clflush movntdq movnti movntpd movdqa movdqu movdq2q movq2dq paddq pmuludq pshufd pshufhw pshuflw pslldq psrldq psubq punpckhqdq punpcklqdq addpd addsd andnpd andpd cmpeqpd cmpeqsd cmplepd cmplesd cmpltpd cmpltsd cmpneqpd cmpneqsd cmpnlepd cmpnlesd cmpnltpd cmpnltsd cmpordpd cmpordsd cmpunordpd cmpunordsd cmppd comisd cvtdq2pd cvtdq2ps cvtpd2dq cvtpd2pi cvtpd2ps cvtpi2pd cvtps2dq cvtps2pd cvtsd2si cvtsd2ss cvtsi2sd cvtss2sd cvttpd2pi cvttpd2dq cvttps2dq cvttsd2si divpd divsd maxpd maxsd minpd minsd movapd movhpd movlpd movmskpd movupd mulpd mulsd orpd shufpd sqrtpd sqrtsd subpd subsd ucomisd unpckhpd unpcklpd xorpd addsubpd addsubps haddpd haddps hsubpd hsubps lddqu movddup movshdup movsldup clgi stgi vmcall vmclear vmfunc vmlaunch vmload vmmcall vmptrld vmptrst vmread vmresume vmrun vmsave vmwrite vmxoff vmxon invept invvpid pabsb pabsw pabsd palignr phaddw phaddd phaddsw phsubw phsubd phsubsw pmaddubsw pmulhrsw pshufb psignb psignw psignd extrq insertq movntsd movntss lzcnt blendpd blendps blendvpd blendvps dppd dpps extractps insertps movntdqa mpsadbw packusdw pblendvb pblendw pcmpeqq pextrb pextrd pextrq phminposuw pinsrb pinsrd pinsrq pmaxsb pmaxsd pmaxud pmaxuw pminsb pminsd pminud pminuw pmovsxbw pmovsxbd pmovsxbq pmovsxwd pmovsxwq pmovsxdq pmovzxbw pmovzxbd pmovzxbq pmovzxwd pmovzxwq pmovzxdq pmuldq pmulld ptest roundpd roundps roundsd roundss crc32 pcmpestri pcmpestrm pcmpistri pcmpistrm pcmpgtq popcnt getsec pfrcpv pfrsqrtv movbe aesenc aesenclast aesdec aesdeclast aesimc aeskeygenassist vaesenc vaesenclast vaesdec vaesdeclast vaesimc vaeskeygenassist vaddpd vaddps vaddsd vaddss vaddsubpd vaddsubps vandpd vandps vandnpd vandnps vblendpd vblendps vblendvpd vblendvps vbroadcastss vbroadcastsd vbroadcastf128 vcmpeq_ospd vcmpeqpd vcmplt_ospd vcmpltpd vcmple_ospd vcmplepd vcmpunord_qpd vcmpunordpd vcmpneq_uqpd vcmpneqpd vcmpnlt_uspd vcmpnltpd vcmpnle_uspd vcmpnlepd vcmpord_qpd vcmpordpd vcmpeq_uqpd vcmpnge_uspd vcmpngepd vcmpngt_uspd vcmpngtpd vcmpfalse_oqpd vcmpfalsepd vcmpneq_oqpd vcmpge_ospd vcmpgepd vcmpgt_ospd vcmpgtpd vcmptrue_uqpd vcmptruepd vcmplt_oqpd vcmple_oqpd vcmpunord_spd vcmpneq_uspd vcmpnlt_uqpd vcmpnle_uqpd vcmpord_spd vcmpeq_uspd vcmpnge_uqpd vcmpngt_uqpd vcmpfalse_ospd vcmpneq_ospd vcmpge_oqpd vcmpgt_oqpd vcmptrue_uspd vcmppd vcmpeq_osps vcmpeqps vcmplt_osps vcmpltps vcmple_osps vcmpleps vcmpunord_qps vcmpunordps vcmpneq_uqps vcmpneqps vcmpnlt_usps vcmpnltps vcmpnle_usps vcmpnleps vcmpord_qps vcmpordps vcmpeq_uqps vcmpnge_usps vcmpngeps vcmpngt_usps vcmpngtps vcmpfalse_oqps vcmpfalseps vcmpneq_oqps vcmpge_osps vcmpgeps vcmpgt_osps vcmpgtps vcmptrue_uqps vcmptrueps vcmplt_oqps vcmple_oqps vcmpunord_sps vcmpneq_usps vcmpnlt_uqps vcmpnle_uqps vcmpord_sps vcmpeq_usps vcmpnge_uqps vcmpngt_uqps vcmpfalse_osps vcmpneq_osps vcmpge_oqps vcmpgt_oqps vcmptrue_usps vcmpps vcmpeq_ossd vcmpeqsd vcmplt_ossd vcmpltsd vcmple_ossd vcmplesd vcmpunord_qsd vcmpunordsd vcmpneq_uqsd vcmpneqsd vcmpnlt_ussd vcmpnltsd vcmpnle_ussd vcmpnlesd vcmpord_qsd vcmpordsd vcmpeq_uqsd vcmpnge_ussd vcmpngesd vcmpngt_ussd vcmpngtsd vcmpfalse_oqsd vcmpfalsesd vcmpneq_oqsd vcmpge_ossd vcmpgesd vcmpgt_ossd vcmpgtsd vcmptrue_uqsd vcmptruesd vcmplt_oqsd vcmple_oqsd vcmpunord_ssd vcmpneq_ussd vcmpnlt_uqsd vcmpnle_uqsd vcmpord_ssd vcmpeq_ussd vcmpnge_uqsd vcmpngt_uqsd vcmpfalse_ossd vcmpneq_ossd vcmpge_oqsd vcmpgt_oqsd vcmptrue_ussd vcmpsd vcmpeq_osss vcmpeqss vcmplt_osss vcmpltss vcmple_osss vcmpless vcmpunord_qss vcmpunordss vcmpneq_uqss vcmpneqss vcmpnlt_usss vcmpnltss vcmpnle_usss vcmpnless vcmpord_qss vcmpordss vcmpeq_uqss vcmpnge_usss vcmpngess vcmpngt_usss vcmpngtss vcmpfalse_oqss vcmpfalsess vcmpneq_oqss vcmpge_osss vcmpgess vcmpgt_osss vcmpgtss vcmptrue_uqss vcmptruess vcmplt_oqss vcmple_oqss vcmpunord_sss vcmpneq_usss vcmpnlt_uqss vcmpnle_uqss vcmpord_sss vcmpeq_usss vcmpnge_uqss vcmpngt_uqss vcmpfalse_osss vcmpneq_osss vcmpge_oqss vcmpgt_oqss vcmptrue_usss vcmpss vcomisd vcomiss vcvtdq2pd vcvtdq2ps vcvtpd2dq vcvtpd2ps vcvtps2dq vcvtps2pd vcvtsd2si vcvtsd2ss vcvtsi2sd vcvtsi2ss vcvtss2sd vcvtss2si vcvttpd2dq vcvttps2dq vcvttsd2si vcvttss2si vdivpd vdivps vdivsd vdivss vdppd vdpps vextractf128 vextractps vhaddpd vhaddps vhsubpd vhsubps vinsertf128 vinsertps vlddqu vldqqu vldmxcsr vmaskmovdqu vmaskmovps vmaskmovpd vmaxpd vmaxps vmaxsd vmaxss vminpd vminps vminsd vminss vmovapd vmovaps vmovd vmovq vmovddup vmovdqa vmovqqa vmovdqu vmovqqu vmovhlps vmovhpd vmovhps vmovlhps vmovlpd vmovlps vmovmskpd vmovmskps vmovntdq vmovntqq vmovntdqa vmovntpd vmovntps vmovsd vmovshdup vmovsldup vmovss vmovupd vmovups vmpsadbw vmulpd vmulps vmulsd vmulss vorpd vorps vpabsb vpabsw vpabsd vpacksswb vpackssdw vpackuswb vpackusdw vpaddb vpaddw vpaddd vpaddq vpaddsb vpaddsw vpaddusb vpaddusw vpalignr vpand vpandn vpavgb vpavgw vpblendvb vpblendw vpcmpestri vpcmpestrm vpcmpistri vpcmpistrm vpcmpeqb vpcmpeqw vpcmpeqd vpcmpeqq vpcmpgtb vpcmpgtw vpcmpgtd vpcmpgtq vpermilpd vpermilps vperm2f128 vpextrb vpextrw vpextrd vpextrq vphaddw vphaddd vphaddsw vphminposuw vphsubw vphsubd vphsubsw vpinsrb vpinsrw vpinsrd vpinsrq vpmaddwd vpmaddubsw vpmaxsb vpmaxsw vpmaxsd vpmaxub vpmaxuw vpmaxud vpminsb vpminsw vpminsd vpminub vpminuw vpminud vpmovmskb vpmovsxbw vpmovsxbd vpmovsxbq vpmovsxwd vpmovsxwq vpmovsxdq vpmovzxbw vpmovzxbd vpmovzxbq vpmovzxwd vpmovzxwq vpmovzxdq vpmulhuw vpmulhrsw vpmulhw vpmullw vpmulld vpmuludq vpmuldq vpor vpsadbw vpshufb vpshufd vpshufhw vpshuflw vpsignb vpsignw vpsignd vpslldq vpsrldq vpsllw vpslld vpsllq vpsraw vpsrad vpsrlw vpsrld vpsrlq vptest vpsubb vpsubw vpsubd vpsubq vpsubsb vpsubsw vpsubusb vpsubusw vpunpckhbw vpunpckhwd vpunpckhdq vpunpckhqdq vpunpcklbw vpunpcklwd vpunpckldq vpunpcklqdq vpxor vrcpps vrcpss vrsqrtps vrsqrtss vroundpd vroundps vroundsd vroundss vshufpd vshufps vsqrtpd vsqrtps vsqrtsd vsqrtss vstmxcsr vsubpd vsubps vsubsd vsubss vtestps vtestpd vucomisd vucomiss vunpckhpd vunpckhps vunpcklpd vunpcklps vxorpd vxorps vzeroall vzeroupper pclmullqlqdq pclmulhqlqdq pclmullqhqdq pclmulhqhqdq pclmulqdq vpclmullqlqdq vpclmulhqlqdq vpclmullqhqdq vpclmulhqhqdq vpclmulqdq vfmadd132ps vfmadd132pd vfmadd312ps vfmadd312pd vfmadd213ps vfmadd213pd vfmadd123ps vfmadd123pd vfmadd231ps vfmadd231pd vfmadd321ps vfmadd321pd vfmaddsub132ps vfmaddsub132pd vfmaddsub312ps vfmaddsub312pd vfmaddsub213ps vfmaddsub213pd vfmaddsub123ps vfmaddsub123pd vfmaddsub231ps vfmaddsub231pd vfmaddsub321ps vfmaddsub321pd vfmsub132ps vfmsub132pd vfmsub312ps vfmsub312pd vfmsub213ps vfmsub213pd vfmsub123ps vfmsub123pd vfmsub231ps vfmsub231pd vfmsub321ps vfmsub321pd vfmsubadd132ps vfmsubadd132pd vfmsubadd312ps vfmsubadd312pd vfmsubadd213ps vfmsubadd213pd vfmsubadd123ps vfmsubadd123pd vfmsubadd231ps vfmsubadd231pd vfmsubadd321ps vfmsubadd321pd vfnmadd132ps vfnmadd132pd vfnmadd312ps vfnmadd312pd vfnmadd213ps vfnmadd213pd vfnmadd123ps vfnmadd123pd vfnmadd231ps vfnmadd231pd vfnmadd321ps vfnmadd321pd vfnmsub132ps vfnmsub132pd vfnmsub312ps vfnmsub312pd vfnmsub213ps vfnmsub213pd vfnmsub123ps vfnmsub123pd vfnmsub231ps vfnmsub231pd vfnmsub321ps vfnmsub321pd vfmadd132ss vfmadd132sd vfmadd312ss vfmadd312sd vfmadd213ss vfmadd213sd vfmadd123ss vfmadd123sd vfmadd231ss vfmadd231sd vfmadd321ss vfmadd321sd vfmsub132ss vfmsub132sd vfmsub312ss vfmsub312sd vfmsub213ss vfmsub213sd vfmsub123ss vfmsub123sd vfmsub231ss vfmsub231sd vfmsub321ss vfmsub321sd vfnmadd132ss vfnmadd132sd vfnmadd312ss vfnmadd312sd vfnmadd213ss vfnmadd213sd vfnmadd123ss vfnmadd123sd vfnmadd231ss vfnmadd231sd vfnmadd321ss vfnmadd321sd vfnmsub132ss vfnmsub132sd vfnmsub312ss vfnmsub312sd vfnmsub213ss vfnmsub213sd vfnmsub123ss vfnmsub123sd vfnmsub231ss vfnmsub231sd vfnmsub321ss vfnmsub321sd rdfsbase rdgsbase rdrand wrfsbase wrgsbase vcvtph2ps vcvtps2ph adcx adox rdseed clac stac xstore xcryptecb xcryptcbc xcryptctr xcryptcfb xcryptofb montmul xsha1 xsha256 llwpcb slwpcb lwpval lwpins vfmaddpd vfmaddps vfmaddsd vfmaddss vfmaddsubpd vfmaddsubps vfmsubaddpd vfmsubaddps vfmsubpd vfmsubps vfmsubsd vfmsubss vfnmaddpd vfnmaddps vfnmaddsd vfnmaddss vfnmsubpd vfnmsubps vfnmsubsd vfnmsubss vfrczpd vfrczps vfrczsd vfrczss vpcmov vpcomb vpcomd vpcomq vpcomub vpcomud vpcomuq vpcomuw vpcomw vphaddbd vphaddbq vphaddbw vphadddq vphaddubd vphaddubq vphaddubw vphaddudq vphadduwd vphadduwq vphaddwd vphaddwq vphsubbw vphsubdq vphsubwd vpmacsdd vpmacsdqh vpmacsdql vpmacssdd vpmacssdqh vpmacssdql vpmacsswd vpmacssww vpmacswd vpmacsww vpmadcsswd vpmadcswd vpperm vprotb vprotd vprotq vprotw vpshab vpshad vpshaq vpshaw vpshlb vpshld vpshlq vpshlw vbroadcasti128 vpblendd vpbroadcastb vpbroadcastw vpbroadcastd vpbroadcastq vpermd vpermpd vpermps vpermq vperm2i128 vextracti128 vinserti128 vpmaskmovd vpmaskmovq vpsllvd vpsllvq vpsravd vpsrlvd vpsrlvq vgatherdpd vgatherqpd vgatherdps vgatherqps vpgatherdd vpgatherqd vpgatherdq vpgatherqq xabort xbegin xend xtest andn bextr blci blcic blsi blsic blcfill blsfill blcmsk blsmsk blsr blcs bzhi mulx pdep pext rorx sarx shlx shrx tzcnt tzmsk t1mskc valignd valignq vblendmpd vblendmps vbroadcastf32x4 vbroadcastf64x4 vbroadcasti32x4 vbroadcasti64x4 vcompresspd vcompressps vcvtpd2udq vcvtps2udq vcvtsd2usi vcvtss2usi vcvttpd2udq vcvttps2udq vcvttsd2usi vcvttss2usi vcvtudq2pd vcvtudq2ps vcvtusi2sd vcvtusi2ss vexpandpd vexpandps vextractf32x4 vextractf64x4 vextracti32x4 vextracti64x4 vfixupimmpd vfixupimmps vfixupimmsd vfixupimmss vgetexppd vgetexpps vgetexpsd vgetexpss vgetmantpd vgetmantps vgetmantsd vgetmantss vinsertf32x4 vinsertf64x4 vinserti32x4 vinserti64x4 vmovdqa32 vmovdqa64 vmovdqu32 vmovdqu64 vpabsq vpandd vpandnd vpandnq vpandq vpblendmd vpblendmq vpcmpltd vpcmpled vpcmpneqd vpcmpnltd vpcmpnled vpcmpd vpcmpltq vpcmpleq vpcmpneqq vpcmpnltq vpcmpnleq vpcmpq vpcmpequd vpcmpltud vpcmpleud vpcmpnequd vpcmpnltud vpcmpnleud vpcmpud vpcmpequq vpcmpltuq vpcmpleuq vpcmpnequq vpcmpnltuq vpcmpnleuq vpcmpuq vpcompressd vpcompressq vpermi2d vpermi2pd vpermi2ps vpermi2q vpermt2d vpermt2pd vpermt2ps vpermt2q vpexpandd vpexpandq vpmaxsq vpmaxuq vpminsq vpminuq vpmovdb vpmovdw vpmovqb vpmovqd vpmovqw vpmovsdb vpmovsdw vpmovsqb vpmovsqd vpmovsqw vpmovusdb vpmovusdw vpmovusqb vpmovusqd vpmovusqw vpord vporq vprold vprolq vprolvd vprolvq vprord vprorq vprorvd vprorvq vpscatterdd vpscatterdq vpscatterqd vpscatterqq vpsraq vpsravq vpternlogd vpternlogq vptestmd vptestmq vptestnmd vptestnmq vpxord vpxorq vrcp14pd vrcp14ps vrcp14sd vrcp14ss vrndscalepd vrndscaleps vrndscalesd vrndscaless vrsqrt14pd vrsqrt14ps vrsqrt14sd vrsqrt14ss vscalefpd vscalefps vscalefsd vscalefss vscatterdpd vscatterdps vscatterqpd vscatterqps vshuff32x4 vshuff64x2 vshufi32x4 vshufi64x2 kandnw kandw kmovw knotw kortestw korw kshiftlw kshiftrw kunpckbw kxnorw kxorw vpbroadcastmb2q vpbroadcastmw2d vpconflictd vpconflictq vplzcntd vplzcntq vexp2pd vexp2ps vrcp28pd vrcp28ps vrcp28sd vrcp28ss vrsqrt28pd vrsqrt28ps vrsqrt28sd vrsqrt28ss vgatherpf0dpd vgatherpf0dps vgatherpf0qpd vgatherpf0qps vgatherpf1dpd vgatherpf1dps vgatherpf1qpd vgatherpf1qps vscatterpf0dpd vscatterpf0dps vscatterpf0qpd vscatterpf0qps vscatterpf1dpd vscatterpf1dps vscatterpf1qpd vscatterpf1qps prefetchwt1 bndmk bndcl bndcu bndcn bndmov bndldx bndstx sha1rnds4 sha1nexte sha1msg1 sha1msg2 sha256rnds2 sha256msg1 sha256msg2 hint_nop0 hint_nop1 hint_nop2 hint_nop3 hint_nop4 hint_nop5 hint_nop6 hint_nop7 hint_nop8 hint_nop9 hint_nop10 hint_nop11 hint_nop12 hint_nop13 hint_nop14 hint_nop15 hint_nop16 hint_nop17 hint_nop18 hint_nop19 hint_nop20 hint_nop21 hint_nop22 hint_nop23 hint_nop24 hint_nop25 hint_nop26 hint_nop27 hint_nop28 hint_nop29 hint_nop30 hint_nop31 hint_nop32 hint_nop33 hint_nop34 hint_nop35 hint_nop36 hint_nop37 hint_nop38 hint_nop39 hint_nop40 hint_nop41 hint_nop42 hint_nop43 hint_nop44 hint_nop45 hint_nop46 hint_nop47 hint_nop48 hint_nop49 hint_nop50 hint_nop51 hint_nop52 hint_nop53 hint_nop54 hint_nop55 hint_nop56 hint_nop57 hint_nop58 hint_nop59 hint_nop60 hint_nop61 hint_nop62 hint_nop63', + built_in: + // Instruction pointer + 'ip eip rip ' + + // 8-bit registers + 'al ah bl bh cl ch dl dh sil dil bpl spl r8b r9b r10b r11b r12b r13b r14b r15b ' + + // 16-bit registers + 'ax bx cx dx si di bp sp r8w r9w r10w r11w r12w r13w r14w r15w ' + + // 32-bit registers + 'eax ebx ecx edx esi edi ebp esp eip r8d r9d r10d r11d r12d r13d r14d r15d ' + + // 64-bit registers + 'rax rbx rcx rdx rsi rdi rbp rsp r8 r9 r10 r11 r12 r13 r14 r15 ' + + // Segment registers + 'cs ds es fs gs ss ' + + // Floating point stack registers + 'st st0 st1 st2 st3 st4 st5 st6 st7 ' + + // MMX Registers + 'mm0 mm1 mm2 mm3 mm4 mm5 mm6 mm7 ' + + // SSE registers + 'xmm0 xmm1 xmm2 xmm3 xmm4 xmm5 xmm6 xmm7 xmm8 xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15 ' + + 'xmm16 xmm17 xmm18 xmm19 xmm20 xmm21 xmm22 xmm23 xmm24 xmm25 xmm26 xmm27 xmm28 xmm29 xmm30 xmm31 ' + + // AVX registers + 'ymm0 ymm1 ymm2 ymm3 ymm4 ymm5 ymm6 ymm7 ymm8 ymm9 ymm10 ymm11 ymm12 ymm13 ymm14 ymm15 ' + + 'ymm16 ymm17 ymm18 ymm19 ymm20 ymm21 ymm22 ymm23 ymm24 ymm25 ymm26 ymm27 ymm28 ymm29 ymm30 ymm31 ' + + // AVX-512F registers + 'zmm0 zmm1 zmm2 zmm3 zmm4 zmm5 zmm6 zmm7 zmm8 zmm9 zmm10 zmm11 zmm12 zmm13 zmm14 zmm15 ' + + 'zmm16 zmm17 zmm18 zmm19 zmm20 zmm21 zmm22 zmm23 zmm24 zmm25 zmm26 zmm27 zmm28 zmm29 zmm30 zmm31 ' + + // AVX-512F mask registers + 'k0 k1 k2 k3 k4 k5 k6 k7 ' + + // Bound (MPX) register + 'bnd0 bnd1 bnd2 bnd3 ' + + // Special register + 'cr0 cr1 cr2 cr3 cr4 cr8 dr0 dr1 dr2 dr3 dr8 tr3 tr4 tr5 tr6 tr7 ' + + // NASM altreg package + 'r0 r1 r2 r3 r4 r5 r6 r7 r0b r1b r2b r3b r4b r5b r6b r7b ' + + 'r0w r1w r2w r3w r4w r5w r6w r7w r0d r1d r2d r3d r4d r5d r6d r7d ' + + 'r0h r1h r2h r3h ' + + 'r0l r1l r2l r3l r4l r5l r6l r7l r8l r9l r10l r11l r12l r13l r14l r15l ' + + + 'db dw dd dq dt ddq do dy dz ' + + 'resb resw resd resq rest resdq reso resy resz ' + + 'incbin equ times ' + + 'byte word dword qword nosplit rel abs seg wrt strict near far a32 ptr', + + meta: + '%define %xdefine %+ %undef %defstr %deftok %assign %strcat %strlen %substr %rotate %elif %else %endif ' + + '%if %ifmacro %ifctx %ifidn %ifidni %ifid %ifnum %ifstr %iftoken %ifempty %ifenv %error %warning %fatal %rep ' + + '%endrep %include %push %pop %repl %pathsearch %depend %use %arg %stacksize %local %line %comment %endcomment ' + + '.nolist ' + + '__FILE__ __LINE__ __SECT__ __BITS__ __OUTPUT_FORMAT__ __DATE__ __TIME__ __DATE_NUM__ __TIME_NUM__ ' + + '__UTC_DATE__ __UTC_TIME__ __UTC_DATE_NUM__ __UTC_TIME_NUM__ __PASS__ struc endstruc istruc at iend ' + + 'align alignb sectalign daz nodaz up down zero default option assume public ' + + + 'bits use16 use32 use64 default section segment absolute extern global common cpu float ' + + '__utf16__ __utf16le__ __utf16be__ __utf32__ __utf32le__ __utf32be__ ' + + '__float8__ __float16__ __float32__ __float64__ __float80m__ __float80e__ __float128l__ __float128h__ ' + + '__Infinity__ __QNaN__ __SNaN__ Inf NaN QNaN SNaN float8 float16 float32 float64 float80m float80e ' + + 'float128l float128h __FLOAT_DAZ__ __FLOAT_ROUND__ __FLOAT__' + }, + contains: [ + hljs.COMMENT( + ';', + '$', + { + relevance: 0 + } + ), + { + className: 'number', + variants: [ + // Float number and x87 BCD + { + begin: '\\b(?:([0-9][0-9_]*)?\\.[0-9_]*(?:[eE][+-]?[0-9_]+)?|' + + '(0[Xx])?[0-9][0-9_]*(\\.[0-9_]*)?(?:[pP](?:[+-]?[0-9_]+)?)?)\\b', + relevance: 0 + }, + + // Hex number in $ + { + begin: '\\$[0-9][0-9A-Fa-f]*', + relevance: 0 + }, + + // Number in H,D,T,Q,O,B,Y suffix + { + begin: '\\b(?:[0-9A-Fa-f][0-9A-Fa-f_]*[Hh]|[0-9][0-9_]*[DdTt]?|[0-7][0-7_]*[QqOo]|[0-1][0-1_]*[BbYy])\\b' + }, + + // Number in X,D,T,Q,O,B,Y prefix + { + begin: '\\b(?:0[Xx][0-9A-Fa-f_]+|0[DdTt][0-9_]+|0[QqOo][0-7_]+|0[BbYy][0-1_]+)\\b' + } + ] + }, + // Double quote string + hljs.QUOTE_STRING_MODE, + { + className: 'string', + variants: [ + // Single-quoted string + { + begin: '\'', + end: '[^\\\\]\'' + }, + // Backquoted string + { + begin: '`', + end: '[^\\\\]`' + } + ], + relevance: 0 + }, + { + className: 'symbol', + variants: [ + // Global label and local label + { + begin: '^\\s*[A-Za-z._?][A-Za-z0-9_$#@~.?]*(:|\\s+label)' + }, + // Macro-local label + { + begin: '^\\s*%%[A-Za-z0-9_$#@~.?]*:' + } + ], + relevance: 0 + }, + // Macro parameter + { + className: 'subst', + begin: '%[0-9]+', + relevance: 0 + }, + // Macro parameter + { + className: 'subst', + begin: '%!\S+', + relevance: 0 + }, + { + className: 'meta', + begin: /^\s*\.[\w_-]+/ + } + ] + }; +} + +module.exports = x86asm; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/xl.js b/claude-code-source/node_modules/highlight.js/lib/languages/xl.js new file mode 100644 index 00000000..270741db --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/xl.js @@ -0,0 +1,92 @@ +/* +Language: XL +Author: Christophe de Dinechin +Description: An extensible programming language, based on parse tree rewriting +Website: http://xlr.sf.net +*/ + +function xl(hljs) { + const BUILTIN_MODULES = + 'ObjectLoader Animate MovieCredits Slides Filters Shading Materials LensFlare Mapping VLCAudioVideo ' + + 'StereoDecoder PointCloud NetworkAccess RemoteControl RegExp ChromaKey Snowfall NodeJS Speech Charts'; + + const XL_KEYWORDS = { + $pattern: /[a-zA-Z][a-zA-Z0-9_?]*/, + keyword: + 'if then else do while until for loop import with is as where when by data constant ' + + 'integer real text name boolean symbol infix prefix postfix block tree', + literal: + 'true false nil', + built_in: + 'in mod rem and or xor not abs sign floor ceil sqrt sin cos tan asin ' + + 'acos atan exp expm1 log log2 log10 log1p pi at text_length text_range ' + + 'text_find text_replace contains page slide basic_slide title_slide ' + + 'title subtitle fade_in fade_out fade_at clear_color color line_color ' + + 'line_width texture_wrap texture_transform texture scale_?x scale_?y ' + + 'scale_?z? translate_?x translate_?y translate_?z? rotate_?x rotate_?y ' + + 'rotate_?z? rectangle circle ellipse sphere path line_to move_to ' + + 'quad_to curve_to theme background contents locally time mouse_?x ' + + 'mouse_?y mouse_buttons ' + + BUILTIN_MODULES + }; + + const DOUBLE_QUOTE_TEXT = { + className: 'string', + begin: '"', + end: '"', + illegal: '\\n' + }; + const SINGLE_QUOTE_TEXT = { + className: 'string', + begin: '\'', + end: '\'', + illegal: '\\n' + }; + const LONG_TEXT = { + className: 'string', + begin: '<<', + end: '>>' + }; + const BASED_NUMBER = { + className: 'number', + begin: '[0-9]+#[0-9A-Z_]+(\\.[0-9-A-Z_]+)?#?([Ee][+-]?[0-9]+)?' + }; + const IMPORT = { + beginKeywords: 'import', + end: '$', + keywords: XL_KEYWORDS, + contains: [ DOUBLE_QUOTE_TEXT ] + }; + const FUNCTION_DEFINITION = { + className: 'function', + begin: /[a-z][^\n]*->/, + returnBegin: true, + end: /->/, + contains: [ + hljs.inherit(hljs.TITLE_MODE, { + starts: { + endsWithParent: true, + keywords: XL_KEYWORDS + } + }) + ] + }; + return { + name: 'XL', + aliases: [ 'tao' ], + keywords: XL_KEYWORDS, + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + DOUBLE_QUOTE_TEXT, + SINGLE_QUOTE_TEXT, + LONG_TEXT, + FUNCTION_DEFINITION, + IMPORT, + BASED_NUMBER, + hljs.NUMBER_MODE + ] + }; +} + +module.exports = xl; diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/xml.js b/claude-code-source/node_modules/highlight.js/lib/languages/xml.js new file mode 100644 index 00000000..1c81810d --- /dev/null +++ b/claude-code-source/node_modules/highlight.js/lib/languages/xml.js @@ -0,0 +1,287 @@ +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function lookahead(re) { + return concat('(?=', re, ')'); +} + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function optional(re) { + return concat('(', re, ')?'); +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/** + * Any of the passed expresssions may match + * + * Creates a huge this | this | that | that match + * @param {(RegExp | string)[] } args + * @returns {string} + */ +function either(...args) { + const joined = '(' + args.map((x) => source(x)).join("|") + ")"; + return joined; +} + +/* +Language: HTML, XML +Website: https://www.w3.org/XML/ +Category: common +Audit: 2020 +*/ + +/** @type LanguageFn */ +function xml(hljs) { + // Element names can contain letters, digits, hyphens, underscores, and periods + const TAG_NAME_RE = concat(/[A-Z_]/, optional(/[A-Z0-9_.-]*:/), /[A-Z0-9_.-]*/); + const XML_IDENT_RE = /[A-Za-z0-9._:-]+/; + const XML_ENTITIES = { + className: 'symbol', + begin: /&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/ + }; + const XML_META_KEYWORDS = { + begin: /\s/, + contains: [ + { + className: 'meta-keyword', + begin: /#?[a-z_][a-z1-9_-]+/, + illegal: /\n/ + } + ] + }; + const XML_META_PAR_KEYWORDS = hljs.inherit(XML_META_KEYWORDS, { + begin: /\(/, + end: /\)/ + }); + const APOS_META_STRING_MODE = hljs.inherit(hljs.APOS_STRING_MODE, { + className: 'meta-string' + }); + const QUOTE_META_STRING_MODE = hljs.inherit(hljs.QUOTE_STRING_MODE, { + className: 'meta-string' + }); + const TAG_INTERNALS = { + endsWithParent: true, + illegal: /`]+/ + } + ] + } + ] + } + ] + }; + return { + name: 'HTML, XML', + aliases: [ + 'html', + 'xhtml', + 'rss', + 'atom', + 'xjb', + 'xsd', + 'xsl', + 'plist', + 'wsf', + 'svg' + ], + case_insensitive: true, + contains: [ + { + className: 'meta', + begin: //, + relevance: 10, + contains: [ + XML_META_KEYWORDS, + QUOTE_META_STRING_MODE, + APOS_META_STRING_MODE, + XML_META_PAR_KEYWORDS, + { + begin: /\[/, + end: /\]/, + contains: [ + { + className: 'meta', + begin: //, + contains: [ + XML_META_KEYWORDS, + XML_META_PAR_KEYWORDS, + QUOTE_META_STRING_MODE, + APOS_META_STRING_MODE + ] + } + ] + } + ] + }, + hljs.COMMENT( + //, + { + relevance: 10 + } + ), + { + begin: //, + relevance: 10 + }, + XML_ENTITIES, + { + className: 'meta', + begin: /<\?xml/, + end: /\?>/, + relevance: 10 + }, + { + className: 'tag', + /* + The lookahead pattern (?=...) ensures that 'begin' only matches + ')/, + end: />/, + keywords: { + name: 'style' + }, + contains: [ TAG_INTERNALS ], + starts: { + end: /<\/style>/, + returnEnd: true, + subLanguage: [ + 'css', + 'xml' + ] + } + }, + { + className: 'tag', + // See the comment in the