From 72cb15ba3fd1ebc4bc61f3f54f59e4678fe22af8 Mon Sep 17 00:00:00 2001 From: stack72 Date: Wed, 17 Mar 2021 15:19:38 +0000 Subject: [PATCH] chore(dist): Update dist [automated commit] --- dist/index.js | 84 ++++++++++++++++++++++++++++++++++------------- dist/index.js.map | 2 +- 2 files changed, 62 insertions(+), 24 deletions(-) diff --git a/dist/index.js b/dist/index.js index ead48e7b..8ebf588b 100644 --- a/dist/index.js +++ b/dist/index.js @@ -107355,33 +107355,79 @@ var core = __nccwpck_require__(2186); var automation = __nccwpck_require__(5883); // EXTERNAL MODULE: ./node_modules/runtypes/lib/index.js var lib = __nccwpck_require__(5568); +// CONCATENATED MODULE: ./src/libs/utils.ts +/* eslint @typescript-eslint/explicit-module-boundary-types: 0 */ +function invariant(condition, message) { + if (!condition) { + throw new Error(message); + } +} +function parseArray(input) { + return parseUndefined(input) + ? input.split(/\r?\n/).reduce((acc, line) => acc + .concat(line.split(',')) + .filter((pat) => pat) + .map((pat) => pat.trim()), []) + : undefined; +} +function parseUndefined(input) { + return input === undefined || input === '' ? undefined : input; +} +function parseBoolean(input) { + return parseUndefined(input) ? input === 'true' : undefined; +} +function parseNumber(input) { + return parseUndefined(input) ? Number(input) : undefined; +} + // CONCATENATED MODULE: ./src/config.ts + const command = lib.Union(lib.Literal('up'), lib.Literal('update'), lib.Literal('refresh'), lib.Literal('destroy'), lib.Literal('preview')); +const options = lib.Partial({ + parallel: lib.Number, + message: lib.String, + expectNoChanges: lib.Boolean, + diff: lib.Boolean, + replace: lib.Array(lib.String), + target: lib.Array(lib.String), + targetDependents: lib.Boolean, +}); const config = lib.Record({ + // Required options command: command, stackName: lib.String, workDir: lib.String, - cloudUrl: lib.String.Or(lib.Undefined), - githubToken: lib.String.Or(lib.Undefined), commentOnPr: lib.Boolean, - args: lib.String.Or(lib.Undefined), - upsert: lib.Boolean.Or(lib.Undefined), -}); + options: options, +}) + .And(lib.Partial({ + // Optional options + cloudUrl: lib.String, + githubToken: lib.String, + upsert: lib.Boolean, +})); function makeConfig() { return (0,tslib.__awaiter)(this, void 0, void 0, function* () { - const [command, ...args] = (0,core.getInput)('command', { required: true }).split(' '); return config.check({ - command, + command: (0,core.getInput)('command', { required: true }), stackName: (0,core.getInput)('stack-name', { required: true }), workDir: (0,core.getInput)('work-dir') || './', cloudUrl: (0,core.getInput)('cloud-url'), githubToken: (0,core.getInput)('github-token'), - commentOnPr: (0,core.getInput)('comment-on-pr') === 'true' ? true : false, - args: (0,core.getInput)('args') || args.join(' '), - upsert: (0,core.getInput)('upsert') === 'true' ? true : false, + commentOnPr: parseBoolean((0,core.getInput)('comment-on-pr')), + upsert: parseBoolean((0,core.getInput)('upsert')), + options: { + parallel: parseNumber((0,core.getInput)('parallel')), + message: (0,core.getInput)('message'), + expectNoChanges: parseBoolean((0,core.getInput)('expect-no-changes')), + diff: parseBoolean((0,core.getInput)('diff')), + replace: parseArray((0,core.getInput)('replace')), + target: parseArray((0,core.getInput)('target')), + targetDependents: parseBoolean((0,core.getInput)('target-dependents')), + }, }); }); } @@ -107399,14 +107445,6 @@ const environmentVariables = dist.cleanEnv(process.env, { // EXTERNAL MODULE: ./node_modules/@actions/github/lib/github.js var github = __nccwpck_require__(5438); -// CONCATENATED MODULE: ./src/libs/utils.ts -/* eslint @typescript-eslint/explicit-module-boundary-types: 0 */ -function invariant(condition, message) { - if (!condition) { - throw new Error(message); - } -} - // CONCATENATED MODULE: ./src/libs/pr.ts @@ -107501,12 +107539,12 @@ const main = () => (0,tslib.__awaiter)(void 0, void 0, void 0, function* () { core.info(msg); }; const actions = { - up: () => stack.up({ onOutput }).then((r) => r.stdout), - update: () => stack.up({ onOutput }).then((r) => r.stdout), - refresh: () => stack.refresh({ onOutput }).then((r) => r.stdout), - destroy: () => stack.destroy({ onOutput }).then((r) => r.stdout), + up: () => stack.up(Object.assign({ onOutput }, config.options)).then((r) => r.stdout), + update: () => stack.up(Object.assign({ onOutput }, config.options)).then((r) => r.stdout), + refresh: () => stack.refresh(Object.assign({ onOutput }, config.options)).then((r) => r.stdout), + destroy: () => stack.destroy(Object.assign({ onOutput }, config.options)).then((r) => r.stdout), preview: () => (0,tslib.__awaiter)(void 0, void 0, void 0, function* () { - const { stdout, stderr } = yield stack.preview(); + const { stdout, stderr } = yield stack.preview(config.options); onOutput(stdout); onOutput(stderr); return stdout; diff --git a/dist/index.js.map b/dist/index.js.map index 3d2a2709..3c82f800 100644 --- a/dist/index.js.map +++ b/dist/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","sources":["../webpack://pulumi-github-action/./node_modules/@actions/core/lib/command.js","../webpack://pulumi-github-action/./node_modules/@actions/core/lib/core.js","../webpack://pulumi-github-action/./node_modules/@actions/core/lib/file-command.js","../webpack://pulumi-github-action/./node_modules/@actions/core/lib/utils.js","../webpack://pulumi-github-action/./node_modules/@actions/exec/lib/exec.js","../webpack://pulumi-github-action/./node_modules/@actions/exec/lib/toolrunner.js","../webpack://pulumi-github-action/./node_modules/@actions/github/lib/context.js","../webpack://pulumi-github-action/./node_modules/@actions/github/lib/github.js","../webpack://pulumi-github-action/./node_modules/@actions/github/lib/internal/utils.js","../webpack://pulumi-github-action/./node_modules/@actions/github/lib/utils.js","../webpack://pulumi-github-action/./node_modules/@actions/http-client/index.js","../webpack://pulumi-github-action/./node_modules/@actions/http-client/proxy.js","../webpack://pulumi-github-action/./node_modules/@actions/io/lib/io-util.js","../webpack://pulumi-github-action/./node_modules/@actions/io/lib/io.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/backoff-timeout.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/call-credentials-filter.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/call-credentials.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/call-stream.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/call.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/channel-credentials.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/channel-options.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/channel.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/client-interceptors.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/client.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/compression-filter.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/constants.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/deadline-filter.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/experimental.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/filter-stack.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/filter.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/http_proxy.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/index.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/load-balancer-child-handler.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/load-balancer-pick-first.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/load-balancer-round-robin.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/load-balancer.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/logging.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/make-client.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/max-message-size-filter.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/metadata.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/picker.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/resolver-dns.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/resolver-uds.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/resolver.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/resolving-load-balancer.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/server-call.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/server-credentials.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/server.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/service-config.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/status-builder.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/stream-decoder.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/subchannel-pool.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/subchannel.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/tls-helpers.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/build/src/uri-parser.js","../webpack://pulumi-github-action/./node_modules/@grpc/grpc-js/node_modules/semver/semver.js","../webpack://pulumi-github-action/./node_modules/@octokit/auth-token/dist-node/index.js","../webpack://pulumi-github-action/./node_modules/@octokit/core/dist-node/index.js","../webpack://pulumi-github-action/./node_modules/@octokit/endpoint/dist-node/index.js","../webpack://pulumi-github-action/./node_modules/@octokit/endpoint/node_modules/is-plain-object/dist/is-plain-object.js","../webpack://pulumi-github-action/./node_modules/@octokit/graphql/dist-node/index.js","../webpack://pulumi-github-action/./node_modules/@octokit/plugin-paginate-rest/dist-node/index.js","../webpack://pulumi-github-action/./node_modules/@octokit/plugin-rest-endpoint-methods/dist-node/index.js","../webpack://pulumi-github-action/./node_modules/@octokit/request-error/dist-node/index.js","../webpack://pulumi-github-action/./node_modules/@octokit/request/dist-node/index.js","../webpack://pulumi-github-action/./node_modules/@octokit/request/node_modules/is-plain-object/dist/is-plain-object.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/asset/archive.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/asset/asset.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/asset/index.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/config.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/dynamic/index.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/errors.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/index.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/iterable/index.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/log/index.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/metadata.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/node_modules/semver/semver.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/node_modules/source-map-support/register.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/node_modules/source-map-support/source-map-support.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/node_modules/source-map/lib/array-set.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/node_modules/source-map/lib/base64-vlq.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/node_modules/source-map/lib/base64.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/node_modules/source-map/lib/binary-search.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/node_modules/source-map/lib/mapping-list.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/node_modules/source-map/lib/quick-sort.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/node_modules/source-map/lib/source-map-consumer.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/node_modules/source-map/lib/source-map-generator.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/node_modules/source-map/lib/source-node.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/node_modules/source-map/lib/util.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/node_modules/source-map/source-map.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/output.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/proto/engine_grpc_pb.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/proto/engine_pb.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/proto/language_grpc_pb.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/proto/language_pb.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/proto/plugin_pb.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/proto/provider_grpc_pb.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/proto/provider_pb.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/proto/resource_grpc_pb.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/proto/resource_pb.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/proto/status_pb.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/provider/index.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/provider/server.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/resource.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/runtime/asyncIterableUtil.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/runtime/closure/codePaths.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/runtime/closure/createClosure.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/runtime/closure/parseFunction.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/runtime/closure/rewriteSuper.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/runtime/closure/serializeClosure.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/runtime/closure/utils.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/runtime/closure/v8.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/runtime/closure/v8Hooks.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/runtime/closure/v8_v10andLower.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/runtime/closure/v8_v11andHigher.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/runtime/config.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/runtime/debuggable.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/runtime/index.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/runtime/invoke.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/runtime/mocks.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/runtime/resource.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/runtime/rpc.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/runtime/settings.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/runtime/stack.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/stackReference.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/utils.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/x/automation/cmd.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/x/automation/errors.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/x/automation/index.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/x/automation/localWorkspace.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/x/automation/server.js","../webpack://pulumi-github-action/./node_modules/@pulumi/pulumi/x/automation/stack.js","../webpack://pulumi-github-action/./node_modules/@pulumi/query/asyncQueryable.js","../webpack://pulumi-github-action/./node_modules/@pulumi/query/base.js","../webpack://pulumi-github-action/./node_modules/@pulumi/query/index.js","../webpack://pulumi-github-action/./node_modules/@pulumi/query/interfaces.js","../webpack://pulumi-github-action/./node_modules/@pulumi/query/operators.js","../webpack://pulumi-github-action/./node_modules/@pulumi/query/sources.js","../webpack://pulumi-github-action/./node_modules/@pulumi/query/util.js","../webpack://pulumi-github-action/./node_modules/agent-base/dist/src/index.js","../webpack://pulumi-github-action/./node_modules/agent-base/dist/src/promisify.js","../webpack://pulumi-github-action/./node_modules/asap/asap.js","../webpack://pulumi-github-action/./node_modules/asap/raw.js","../webpack://pulumi-github-action/./node_modules/balanced-match/index.js","../webpack://pulumi-github-action/./node_modules/base64-js/index.js","../webpack://pulumi-github-action/./node_modules/before-after-hook/index.js","../webpack://pulumi-github-action/./node_modules/before-after-hook/lib/add.js","../webpack://pulumi-github-action/./node_modules/before-after-hook/lib/register.js","../webpack://pulumi-github-action/./node_modules/before-after-hook/lib/remove.js","../webpack://pulumi-github-action/./node_modules/bignumber.js/bignumber.js","../webpack://pulumi-github-action/./node_modules/brace-expansion/index.js","../webpack://pulumi-github-action/./node_modules/buffer-equal-constant-time/index.js","../webpack://pulumi-github-action/./node_modules/call-bind/callBound.js","../webpack://pulumi-github-action/./node_modules/call-bind/index.js","../webpack://pulumi-github-action/./node_modules/concat-map/index.js","../webpack://pulumi-github-action/./node_modules/debug/src/browser.js","../webpack://pulumi-github-action/./node_modules/debug/src/common.js","../webpack://pulumi-github-action/./node_modules/debug/src/index.js","../webpack://pulumi-github-action/./node_modules/debug/src/node.js","../webpack://pulumi-github-action/./node_modules/debuglog/debuglog.js","../webpack://pulumi-github-action/./node_modules/define-properties/index.js","../webpack://pulumi-github-action/./node_modules/deprecation/dist-node/index.js","../webpack://pulumi-github-action/./node_modules/dezalgo/dezalgo.js","../webpack://pulumi-github-action/./node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js","../webpack://pulumi-github-action/./node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js","../webpack://pulumi-github-action/./node_modules/envalid/dist/envalid.cjs.development.js","../webpack://pulumi-github-action/./node_modules/envalid/dist/envalid.cjs.production.min.js","../webpack://pulumi-github-action/./node_modules/envalid/dist/index.js","../webpack://pulumi-github-action/./node_modules/es-abstract/2020/CreateDataProperty.js","../webpack://pulumi-github-action/./node_modules/es-abstract/2020/FromPropertyDescriptor.js","../webpack://pulumi-github-action/./node_modules/es-abstract/2020/IsArray.js","../webpack://pulumi-github-action/./node_modules/es-abstract/2020/IsCallable.js","../webpack://pulumi-github-action/./node_modules/es-abstract/2020/IsDataDescriptor.js","../webpack://pulumi-github-action/./node_modules/es-abstract/2020/IsExtensible.js","../webpack://pulumi-github-action/./node_modules/es-abstract/2020/IsPropertyKey.js","../webpack://pulumi-github-action/./node_modules/es-abstract/2020/IsRegExp.js","../webpack://pulumi-github-action/./node_modules/es-abstract/2020/OrdinaryGetOwnProperty.js","../webpack://pulumi-github-action/./node_modules/es-abstract/2020/RequireObjectCoercible.js","../webpack://pulumi-github-action/./node_modules/es-abstract/2020/SameValue.js","../webpack://pulumi-github-action/./node_modules/es-abstract/2020/ToBoolean.js","../webpack://pulumi-github-action/./node_modules/es-abstract/2020/ToObject.js","../webpack://pulumi-github-action/./node_modules/es-abstract/2020/ToPropertyDescriptor.js","../webpack://pulumi-github-action/./node_modules/es-abstract/2020/Type.js","../webpack://pulumi-github-action/./node_modules/es-abstract/5/CheckObjectCoercible.js","../webpack://pulumi-github-action/./node_modules/es-abstract/5/Type.js","../webpack://pulumi-github-action/./node_modules/es-abstract/helpers/DefineOwnProperty.js","../webpack://pulumi-github-action/./node_modules/es-abstract/helpers/assertRecord.js","../webpack://pulumi-github-action/./node_modules/es-abstract/helpers/getOwnPropertyDescriptor.js","../webpack://pulumi-github-action/./node_modules/es-abstract/helpers/isNaN.js","../webpack://pulumi-github-action/./node_modules/es-abstract/helpers/isPrimitive.js","../webpack://pulumi-github-action/./node_modules/extend/index.js","../webpack://pulumi-github-action/./node_modules/fast-text-encoding/text.min.js","../webpack://pulumi-github-action/./node_modules/fs.realpath/index.js","../webpack://pulumi-github-action/./node_modules/fs.realpath/old.js","../webpack://pulumi-github-action/./node_modules/function-bind/implementation.js","../webpack://pulumi-github-action/./node_modules/function-bind/index.js","../webpack://pulumi-github-action/./node_modules/gaxios/build/src/common.js","../webpack://pulumi-github-action/./node_modules/gaxios/build/src/gaxios.js","../webpack://pulumi-github-action/./node_modules/gaxios/build/src/index.js","../webpack://pulumi-github-action/./node_modules/gaxios/build/src/retry.js","../webpack://pulumi-github-action/./node_modules/gcp-metadata/build/src/index.js","../webpack://pulumi-github-action/./node_modules/get-intrinsic/index.js","../webpack://pulumi-github-action/./node_modules/glob/common.js","../webpack://pulumi-github-action/./node_modules/glob/glob.js","../webpack://pulumi-github-action/./node_modules/glob/sync.js","../webpack://pulumi-github-action/./node_modules/google-auth-library/build/src/auth/authclient.js","../webpack://pulumi-github-action/./node_modules/google-auth-library/build/src/auth/computeclient.js","../webpack://pulumi-github-action/./node_modules/google-auth-library/build/src/auth/envDetect.js","../webpack://pulumi-github-action/./node_modules/google-auth-library/build/src/auth/googleauth.js","../webpack://pulumi-github-action/./node_modules/google-auth-library/build/src/auth/iam.js","../webpack://pulumi-github-action/./node_modules/google-auth-library/build/src/auth/idtokenclient.js","../webpack://pulumi-github-action/./node_modules/google-auth-library/build/src/auth/jwtaccess.js","../webpack://pulumi-github-action/./node_modules/google-auth-library/build/src/auth/jwtclient.js","../webpack://pulumi-github-action/./node_modules/google-auth-library/build/src/auth/loginticket.js","../webpack://pulumi-github-action/./node_modules/google-auth-library/build/src/auth/oauth2client.js","../webpack://pulumi-github-action/./node_modules/google-auth-library/build/src/auth/refreshclient.js","../webpack://pulumi-github-action/./node_modules/google-auth-library/build/src/crypto/browser/crypto.js","../webpack://pulumi-github-action/./node_modules/google-auth-library/build/src/crypto/crypto.js","../webpack://pulumi-github-action/./node_modules/google-auth-library/build/src/crypto/node/crypto.js","../webpack://pulumi-github-action/./node_modules/google-auth-library/build/src/index.js","../webpack://pulumi-github-action/./node_modules/google-auth-library/build/src/options.js","../webpack://pulumi-github-action/./node_modules/google-auth-library/build/src/transporters.js","../webpack://pulumi-github-action/./node_modules/google-auth-library/node_modules/arrify/index.js","../webpack://pulumi-github-action/./node_modules/google-p12-pem/build/src/index.js","../webpack://pulumi-github-action/./node_modules/google-protobuf/google-protobuf.js","../webpack://pulumi-github-action/./node_modules/google-protobuf/google/protobuf/any_pb.js","../webpack://pulumi-github-action/./node_modules/google-protobuf/google/protobuf/empty_pb.js","../webpack://pulumi-github-action/./node_modules/google-protobuf/google/protobuf/struct_pb.js","../webpack://pulumi-github-action/./node_modules/graceful-fs/clone.js","../webpack://pulumi-github-action/./node_modules/graceful-fs/graceful-fs.js","../webpack://pulumi-github-action/./node_modules/graceful-fs/legacy-streams.js","../webpack://pulumi-github-action/./node_modules/graceful-fs/polyfills.js","../webpack://pulumi-github-action/./node_modules/gtoken/build/src/index.js","../webpack://pulumi-github-action/./node_modules/has-flag/index.js","../webpack://pulumi-github-action/./node_modules/has-symbols/index.js","../webpack://pulumi-github-action/./node_modules/has-symbols/shams.js","../webpack://pulumi-github-action/./node_modules/has/src/index.js","../webpack://pulumi-github-action/./node_modules/hosted-git-info/git-host-info.js","../webpack://pulumi-github-action/./node_modules/hosted-git-info/git-host.js","../webpack://pulumi-github-action/./node_modules/hosted-git-info/index.js","../webpack://pulumi-github-action/./node_modules/https-proxy-agent/dist/agent.js","../webpack://pulumi-github-action/./node_modules/https-proxy-agent/dist/index.js","../webpack://pulumi-github-action/./node_modules/https-proxy-agent/dist/parse-proxy-response.js","../webpack://pulumi-github-action/./node_modules/inflight/inflight.js","../webpack://pulumi-github-action/./node_modules/inherits/inherits.js","../webpack://pulumi-github-action/./node_modules/inherits/inherits_browser.js","../webpack://pulumi-github-action/./node_modules/is-callable/index.js","../webpack://pulumi-github-action/./node_modules/is-regex/index.js","../webpack://pulumi-github-action/./node_modules/is-stream/index.js","../webpack://pulumi-github-action/./node_modules/js-yaml/index.js","../webpack://pulumi-github-action/./node_modules/js-yaml/lib/js-yaml.js","../webpack://pulumi-github-action/./node_modules/js-yaml/lib/js-yaml/common.js","../webpack://pulumi-github-action/./node_modules/js-yaml/lib/js-yaml/dumper.js","../webpack://pulumi-github-action/./node_modules/js-yaml/lib/js-yaml/exception.js","../webpack://pulumi-github-action/./node_modules/js-yaml/lib/js-yaml/loader.js","../webpack://pulumi-github-action/./node_modules/js-yaml/lib/js-yaml/mark.js","../webpack://pulumi-github-action/./node_modules/js-yaml/lib/js-yaml/schema.js","../webpack://pulumi-github-action/./node_modules/js-yaml/lib/js-yaml/schema/core.js","../webpack://pulumi-github-action/./node_modules/js-yaml/lib/js-yaml/schema/default_full.js","../webpack://pulumi-github-action/./node_modules/js-yaml/lib/js-yaml/schema/default_safe.js","../webpack://pulumi-github-action/./node_modules/js-yaml/lib/js-yaml/schema/failsafe.js","../webpack://pulumi-github-action/./node_modules/js-yaml/lib/js-yaml/schema/json.js","../webpack://pulumi-github-action/./node_modules/js-yaml/lib/js-yaml/type.js","../webpack://pulumi-github-action/./node_modules/js-yaml/lib/js-yaml/type/binary.js","../webpack://pulumi-github-action/./node_modules/js-yaml/lib/js-yaml/type/bool.js","../webpack://pulumi-github-action/./node_modules/js-yaml/lib/js-yaml/type/float.js","../webpack://pulumi-github-action/./node_modules/js-yaml/lib/js-yaml/type/int.js","../webpack://pulumi-github-action/./node_modules/js-yaml/lib/js-yaml/type/js/function.js","../webpack://pulumi-github-action/./node_modules/js-yaml/lib/js-yaml/type/js/regexp.js","../webpack://pulumi-github-action/./node_modules/js-yaml/lib/js-yaml/type/js/undefined.js","../webpack://pulumi-github-action/./node_modules/js-yaml/lib/js-yaml/type/map.js","../webpack://pulumi-github-action/./node_modules/js-yaml/lib/js-yaml/type/merge.js","../webpack://pulumi-github-action/./node_modules/js-yaml/lib/js-yaml/type/null.js","../webpack://pulumi-github-action/./node_modules/js-yaml/lib/js-yaml/type/omap.js","../webpack://pulumi-github-action/./node_modules/js-yaml/lib/js-yaml/type/pairs.js","../webpack://pulumi-github-action/./node_modules/js-yaml/lib/js-yaml/type/seq.js","../webpack://pulumi-github-action/./node_modules/js-yaml/lib/js-yaml/type/set.js","../webpack://pulumi-github-action/./node_modules/js-yaml/lib/js-yaml/type/str.js","../webpack://pulumi-github-action/./node_modules/js-yaml/lib/js-yaml/type/timestamp.js","../webpack://pulumi-github-action/./node_modules/json-bigint/index.js","../webpack://pulumi-github-action/./node_modules/json-bigint/lib/parse.js","../webpack://pulumi-github-action/./node_modules/json-bigint/lib/stringify.js","../webpack://pulumi-github-action/./node_modules/json-parse-even-better-errors/index.js","../webpack://pulumi-github-action/./node_modules/jwa/index.js","../webpack://pulumi-github-action/./node_modules/jws/index.js","../webpack://pulumi-github-action/./node_modules/jws/lib/data-stream.js","../webpack://pulumi-github-action/./node_modules/jws/lib/sign-stream.js","../webpack://pulumi-github-action/./node_modules/jws/lib/tostring.js","../webpack://pulumi-github-action/./node_modules/jws/lib/verify-stream.js","../webpack://pulumi-github-action/./node_modules/lru-cache/index.js","../webpack://pulumi-github-action/./node_modules/minimatch/minimatch.js","../webpack://pulumi-github-action/./node_modules/ms/index.js","../webpack://pulumi-github-action/./node_modules/node-fetch/lib/index.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/aes.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/aesCipherSuites.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/asn1-validator.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/asn1.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/baseN.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/cipher.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/cipherModes.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/debug.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/des.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/ed25519.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/forge.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/hmac.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/index.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/jsbn.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/kem.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/log.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/md.all.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/md.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/md5.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/mgf.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/mgf1.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/oids.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/pbe.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/pbkdf2.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/pem.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/pkcs1.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/pkcs12.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/pkcs7.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/pkcs7asn1.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/pki.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/prime.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/prng.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/pss.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/random.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/rc2.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/rsa.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/sha1.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/sha256.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/sha512.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/ssh.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/task.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/tls.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/util.js","../webpack://pulumi-github-action/./node_modules/node-forge/lib/x509.js","../webpack://pulumi-github-action/./node_modules/normalize-package-data/lib/extract_description.js","../webpack://pulumi-github-action/./node_modules/normalize-package-data/lib/fixer.js","../webpack://pulumi-github-action/./node_modules/normalize-package-data/lib/make_warning.js","../webpack://pulumi-github-action/./node_modules/normalize-package-data/lib/normalize.js","../webpack://pulumi-github-action/./node_modules/normalize-package-data/node_modules/resolve/index.js","../webpack://pulumi-github-action/./node_modules/normalize-package-data/node_modules/resolve/lib/async.js","../webpack://pulumi-github-action/./node_modules/normalize-package-data/node_modules/resolve/lib/caller.js","../webpack://pulumi-github-action/./node_modules/normalize-package-data/node_modules/resolve/lib/core.js","../webpack://pulumi-github-action/./node_modules/normalize-package-data/node_modules/resolve/lib/is-core.js","../webpack://pulumi-github-action/./node_modules/normalize-package-data/node_modules/resolve/lib/node-modules-paths.js","../webpack://pulumi-github-action/./node_modules/normalize-package-data/node_modules/resolve/lib/normalize-options.js","../webpack://pulumi-github-action/./node_modules/normalize-package-data/node_modules/resolve/lib/sync.js","../webpack://pulumi-github-action/./node_modules/normalize-package-data/node_modules/semver/semver.js","../webpack://pulumi-github-action/./node_modules/npm-normalize-package-bin/index.js","../webpack://pulumi-github-action/./node_modules/object-keys/implementation.js","../webpack://pulumi-github-action/./node_modules/object-keys/index.js","../webpack://pulumi-github-action/./node_modules/object-keys/isArguments.js","../webpack://pulumi-github-action/./node_modules/object.getownpropertydescriptors/implementation.js","../webpack://pulumi-github-action/./node_modules/object.getownpropertydescriptors/index.js","../webpack://pulumi-github-action/./node_modules/object.getownpropertydescriptors/polyfill.js","../webpack://pulumi-github-action/./node_modules/object.getownpropertydescriptors/shim.js","../webpack://pulumi-github-action/./node_modules/once/once.js","../webpack://pulumi-github-action/./node_modules/path-is-absolute/index.js","../webpack://pulumi-github-action/./node_modules/path-parse/index.js","../webpack://pulumi-github-action/./node_modules/read-package-json/read-json.js","../webpack://pulumi-github-action/./node_modules/read-package-tree/realpath.js","../webpack://pulumi-github-action/./node_modules/read-package-tree/rpt.js","../webpack://pulumi-github-action/./node_modules/readdir-scoped-modules/readdir.js","../webpack://pulumi-github-action/./node_modules/require-from-string/index.js","../webpack://pulumi-github-action/./node_modules/runtypes/lib/asynccontract.js","../webpack://pulumi-github-action/./node_modules/runtypes/lib/contract.js","../webpack://pulumi-github-action/./node_modules/runtypes/lib/decorator.js","../webpack://pulumi-github-action/./node_modules/runtypes/lib/errors.js","../webpack://pulumi-github-action/./node_modules/runtypes/lib/index.js","../webpack://pulumi-github-action/./node_modules/runtypes/lib/match.js","../webpack://pulumi-github-action/./node_modules/runtypes/lib/reflect.js","../webpack://pulumi-github-action/./node_modules/runtypes/lib/result.js","../webpack://pulumi-github-action/./node_modules/runtypes/lib/runtype.js","../webpack://pulumi-github-action/./node_modules/runtypes/lib/show.js","../webpack://pulumi-github-action/./node_modules/runtypes/lib/types/array.js","../webpack://pulumi-github-action/./node_modules/runtypes/lib/types/boolean.js","../webpack://pulumi-github-action/./node_modules/runtypes/lib/types/brand.js","../webpack://pulumi-github-action/./node_modules/runtypes/lib/types/constraint.js","../webpack://pulumi-github-action/./node_modules/runtypes/lib/types/dictionary.js","../webpack://pulumi-github-action/./node_modules/runtypes/lib/types/function.js","../webpack://pulumi-github-action/./node_modules/runtypes/lib/types/instanceof.js","../webpack://pulumi-github-action/./node_modules/runtypes/lib/types/intersect.js","../webpack://pulumi-github-action/./node_modules/runtypes/lib/types/lazy.js","../webpack://pulumi-github-action/./node_modules/runtypes/lib/types/literal.js","../webpack://pulumi-github-action/./node_modules/runtypes/lib/types/never.js","../webpack://pulumi-github-action/./node_modules/runtypes/lib/types/number.js","../webpack://pulumi-github-action/./node_modules/runtypes/lib/types/record.js","../webpack://pulumi-github-action/./node_modules/runtypes/lib/types/string.js","../webpack://pulumi-github-action/./node_modules/runtypes/lib/types/symbol.js","../webpack://pulumi-github-action/./node_modules/runtypes/lib/types/tuple.js","../webpack://pulumi-github-action/./node_modules/runtypes/lib/types/union.js","../webpack://pulumi-github-action/./node_modules/runtypes/lib/types/unknown.js","../webpack://pulumi-github-action/./node_modules/runtypes/lib/types/void.js","../webpack://pulumi-github-action/./node_modules/runtypes/lib/util.js","../webpack://pulumi-github-action/./node_modules/safe-buffer/index.js","../webpack://pulumi-github-action/./node_modules/spdx-correct/index.js","../webpack://pulumi-github-action/./node_modules/spdx-expression-parse/index.js","../webpack://pulumi-github-action/./node_modules/spdx-expression-parse/parse.js","../webpack://pulumi-github-action/./node_modules/spdx-expression-parse/scan.js","../webpack://pulumi-github-action/./node_modules/supports-color/index.js","../webpack://pulumi-github-action/./node_modules/tslib/tslib.js","../webpack://pulumi-github-action/./node_modules/tunnel/index.js","../webpack://pulumi-github-action/./node_modules/tunnel/lib/tunnel.js","../webpack://pulumi-github-action/./node_modules/universal-user-agent/dist-node/index.js","../webpack://pulumi-github-action/./node_modules/upath/build/code/upath.js","../webpack://pulumi-github-action/./node_modules/util-promisify/index.js","../webpack://pulumi-github-action/./node_modules/validate-npm-package-license/index.js","../webpack://pulumi-github-action/./node_modules/wrappy/wrappy.js","../webpack://pulumi-github-action/./node_modules/yallist/iterator.js","../webpack://pulumi-github-action/./node_modules/yallist/yallist.js","../webpack://pulumi-github-action/./src/config.ts","../webpack://pulumi-github-action/./src/libs/envs.ts","../webpack://pulumi-github-action/./src/libs/utils.ts","../webpack://pulumi-github-action/./src/libs/pr.ts","../webpack://pulumi-github-action/./src/libs/exec.ts","../webpack://pulumi-github-action/./src/libs/pulumi-cli.ts","../webpack://pulumi-github-action/./src/main.ts","../webpack://pulumi-github-action/./node_modules/@vercel/ncc/dist/ncc/@@notfound.js","../webpack://pulumi-github-action/external \"assert\"","../webpack://pulumi-github-action/external \"buffer\"","../webpack://pulumi-github-action/external \"child_process\"","../webpack://pulumi-github-action/external \"constants\"","../webpack://pulumi-github-action/external \"crypto\"","../webpack://pulumi-github-action/external \"dns\"","../webpack://pulumi-github-action/external \"domain\"","../webpack://pulumi-github-action/external \"events\"","../webpack://pulumi-github-action/external \"fs\"","../webpack://pulumi-github-action/external \"http\"","../webpack://pulumi-github-action/external \"http2\"","../webpack://pulumi-github-action/external \"https\"","../webpack://pulumi-github-action/external \"inspector\"","../webpack://pulumi-github-action/external \"module\"","../webpack://pulumi-github-action/external \"net\"","../webpack://pulumi-github-action/external \"os\"","../webpack://pulumi-github-action/external \"path\"","../webpack://pulumi-github-action/external \"querystring\"","../webpack://pulumi-github-action/external \"stream\"","../webpack://pulumi-github-action/external \"timers\"","../webpack://pulumi-github-action/external \"tls\"","../webpack://pulumi-github-action/external \"tty\"","../webpack://pulumi-github-action/external \"typescript\"","../webpack://pulumi-github-action/external \"url\"","../webpack://pulumi-github-action/external \"util\"","../webpack://pulumi-github-action/external \"v8\"","../webpack://pulumi-github-action/external \"zlib\"","../webpack://pulumi-github-action/webpack/bootstrap","../webpack://pulumi-github-action/webpack/runtime/make namespace object","../webpack://pulumi-github-action/webpack/runtime/node module decorator","../webpack://pulumi-github-action/webpack/runtime/compat","../webpack://pulumi-github-action/webpack/startup"],"sourcesContent":["\"use strict\";\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst os = __importStar(require(\"os\"));\nconst utils_1 = require(\"./utils\");\n/**\n * Commands\n *\n * Command Format:\n * ::name key=value,key=value::message\n *\n * Examples:\n * ::warning::This is the message\n * ::set-env name=MY_VAR::some value\n */\nfunction issueCommand(command, properties, message) {\n const cmd = new Command(command, properties, message);\n process.stdout.write(cmd.toString() + os.EOL);\n}\nexports.issueCommand = issueCommand;\nfunction issue(name, message = '') {\n issueCommand(name, {}, message);\n}\nexports.issue = issue;\nconst CMD_STRING = '::';\nclass Command {\n constructor(command, properties, message) {\n if (!command) {\n command = 'missing.command';\n }\n this.command = command;\n this.properties = properties;\n this.message = message;\n }\n toString() {\n let cmdStr = CMD_STRING + this.command;\n if (this.properties && Object.keys(this.properties).length > 0) {\n cmdStr += ' ';\n let first = true;\n for (const key in this.properties) {\n if (this.properties.hasOwnProperty(key)) {\n const val = this.properties[key];\n if (val) {\n if (first) {\n first = false;\n }\n else {\n cmdStr += ',';\n }\n cmdStr += `${key}=${escapeProperty(val)}`;\n }\n }\n }\n }\n cmdStr += `${CMD_STRING}${escapeData(this.message)}`;\n return cmdStr;\n }\n}\nfunction escapeData(s) {\n return utils_1.toCommandValue(s)\n .replace(/%/g, '%25')\n .replace(/\\r/g, '%0D')\n .replace(/\\n/g, '%0A');\n}\nfunction escapeProperty(s) {\n return utils_1.toCommandValue(s)\n .replace(/%/g, '%25')\n .replace(/\\r/g, '%0D')\n .replace(/\\n/g, '%0A')\n .replace(/:/g, '%3A')\n .replace(/,/g, '%2C');\n}\n//# sourceMappingURL=command.js.map","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst command_1 = require(\"./command\");\nconst file_command_1 = require(\"./file-command\");\nconst utils_1 = require(\"./utils\");\nconst os = __importStar(require(\"os\"));\nconst path = __importStar(require(\"path\"));\n/**\n * The code to exit an action\n */\nvar ExitCode;\n(function (ExitCode) {\n /**\n * A code indicating that the action was successful\n */\n ExitCode[ExitCode[\"Success\"] = 0] = \"Success\";\n /**\n * A code indicating that the action was a failure\n */\n ExitCode[ExitCode[\"Failure\"] = 1] = \"Failure\";\n})(ExitCode = exports.ExitCode || (exports.ExitCode = {}));\n//-----------------------------------------------------------------------\n// Variables\n//-----------------------------------------------------------------------\n/**\n * Sets env variable for this action and future actions in the job\n * @param name the name of the variable to set\n * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction exportVariable(name, val) {\n const convertedVal = utils_1.toCommandValue(val);\n process.env[name] = convertedVal;\n const filePath = process.env['GITHUB_ENV'] || '';\n if (filePath) {\n const delimiter = '_GitHubActionsFileCommandDelimeter_';\n const commandValue = `${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}`;\n file_command_1.issueCommand('ENV', commandValue);\n }\n else {\n command_1.issueCommand('set-env', { name }, convertedVal);\n }\n}\nexports.exportVariable = exportVariable;\n/**\n * Registers a secret which will get masked from logs\n * @param secret value of the secret\n */\nfunction setSecret(secret) {\n command_1.issueCommand('add-mask', {}, secret);\n}\nexports.setSecret = setSecret;\n/**\n * Prepends inputPath to the PATH (for this action and future actions)\n * @param inputPath\n */\nfunction addPath(inputPath) {\n const filePath = process.env['GITHUB_PATH'] || '';\n if (filePath) {\n file_command_1.issueCommand('PATH', inputPath);\n }\n else {\n command_1.issueCommand('add-path', {}, inputPath);\n }\n process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`;\n}\nexports.addPath = addPath;\n/**\n * Gets the value of an input. The value is also trimmed.\n *\n * @param name name of the input to get\n * @param options optional. See InputOptions.\n * @returns string\n */\nfunction getInput(name, options) {\n const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || '';\n if (options && options.required && !val) {\n throw new Error(`Input required and not supplied: ${name}`);\n }\n return val.trim();\n}\nexports.getInput = getInput;\n/**\n * Sets the value of an output.\n *\n * @param name name of the output to set\n * @param value value to store. Non-string values will be converted to a string via JSON.stringify\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction setOutput(name, value) {\n command_1.issueCommand('set-output', { name }, value);\n}\nexports.setOutput = setOutput;\n/**\n * Enables or disables the echoing of commands into stdout for the rest of the step.\n * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set.\n *\n */\nfunction setCommandEcho(enabled) {\n command_1.issue('echo', enabled ? 'on' : 'off');\n}\nexports.setCommandEcho = setCommandEcho;\n//-----------------------------------------------------------------------\n// Results\n//-----------------------------------------------------------------------\n/**\n * Sets the action status to failed.\n * When the action exits it will be with an exit code of 1\n * @param message add error issue message\n */\nfunction setFailed(message) {\n process.exitCode = ExitCode.Failure;\n error(message);\n}\nexports.setFailed = setFailed;\n//-----------------------------------------------------------------------\n// Logging Commands\n//-----------------------------------------------------------------------\n/**\n * Gets whether Actions Step Debug is on or not\n */\nfunction isDebug() {\n return process.env['RUNNER_DEBUG'] === '1';\n}\nexports.isDebug = isDebug;\n/**\n * Writes debug message to user log\n * @param message debug message\n */\nfunction debug(message) {\n command_1.issueCommand('debug', {}, message);\n}\nexports.debug = debug;\n/**\n * Adds an error issue\n * @param message error issue message. Errors will be converted to string via toString()\n */\nfunction error(message) {\n command_1.issue('error', message instanceof Error ? message.toString() : message);\n}\nexports.error = error;\n/**\n * Adds an warning issue\n * @param message warning issue message. Errors will be converted to string via toString()\n */\nfunction warning(message) {\n command_1.issue('warning', message instanceof Error ? message.toString() : message);\n}\nexports.warning = warning;\n/**\n * Writes info to log with console.log.\n * @param message info message\n */\nfunction info(message) {\n process.stdout.write(message + os.EOL);\n}\nexports.info = info;\n/**\n * Begin an output group.\n *\n * Output until the next `groupEnd` will be foldable in this group\n *\n * @param name The name of the output group\n */\nfunction startGroup(name) {\n command_1.issue('group', name);\n}\nexports.startGroup = startGroup;\n/**\n * End an output group.\n */\nfunction endGroup() {\n command_1.issue('endgroup');\n}\nexports.endGroup = endGroup;\n/**\n * Wrap an asynchronous function call in a group.\n *\n * Returns the same type as the function itself.\n *\n * @param name The name of the group\n * @param fn The function to wrap in the group\n */\nfunction group(name, fn) {\n return __awaiter(this, void 0, void 0, function* () {\n startGroup(name);\n let result;\n try {\n result = yield fn();\n }\n finally {\n endGroup();\n }\n return result;\n });\n}\nexports.group = group;\n//-----------------------------------------------------------------------\n// Wrapper action state\n//-----------------------------------------------------------------------\n/**\n * Saves state for current action, the state can only be retrieved by this action's post job execution.\n *\n * @param name name of the state to store\n * @param value value to store. Non-string values will be converted to a string via JSON.stringify\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction saveState(name, value) {\n command_1.issueCommand('save-state', { name }, value);\n}\nexports.saveState = saveState;\n/**\n * Gets the value of an state set by this action's main execution.\n *\n * @param name name of the state to get\n * @returns string\n */\nfunction getState(name) {\n return process.env[`STATE_${name}`] || '';\n}\nexports.getState = getState;\n//# sourceMappingURL=core.js.map","\"use strict\";\n// For internal use, subject to change.\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n// We use any as a valid input type\n/* eslint-disable @typescript-eslint/no-explicit-any */\nconst fs = __importStar(require(\"fs\"));\nconst os = __importStar(require(\"os\"));\nconst utils_1 = require(\"./utils\");\nfunction issueCommand(command, message) {\n const filePath = process.env[`GITHUB_${command}`];\n if (!filePath) {\n throw new Error(`Unable to find environment variable for file command ${command}`);\n }\n if (!fs.existsSync(filePath)) {\n throw new Error(`Missing file at path: ${filePath}`);\n }\n fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, {\n encoding: 'utf8'\n });\n}\nexports.issueCommand = issueCommand;\n//# sourceMappingURL=file-command.js.map","\"use strict\";\n// We use any as a valid input type\n/* eslint-disable @typescript-eslint/no-explicit-any */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Sanitizes an input into a string so it can be passed into issueCommand safely\n * @param input input to sanitize into a string\n */\nfunction toCommandValue(input) {\n if (input === null || input === undefined) {\n return '';\n }\n else if (typeof input === 'string' || input instanceof String) {\n return input;\n }\n return JSON.stringify(input);\n}\nexports.toCommandValue = toCommandValue;\n//# sourceMappingURL=utils.js.map","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tr = __importStar(require(\"./toolrunner\"));\n/**\n * Exec a command.\n * Output will be streamed to the live console.\n * Returns promise with return code\n *\n * @param commandLine command to execute (can include additional args). Must be correctly escaped.\n * @param args optional arguments for tool. Escaping is handled by the lib.\n * @param options optional exec options. See ExecOptions\n * @returns Promise exit code\n */\nfunction exec(commandLine, args, options) {\n return __awaiter(this, void 0, void 0, function* () {\n const commandArgs = tr.argStringToArray(commandLine);\n if (commandArgs.length === 0) {\n throw new Error(`Parameter 'commandLine' cannot be null or empty.`);\n }\n // Path to tool to execute should be first arg\n const toolPath = commandArgs[0];\n args = commandArgs.slice(1).concat(args || []);\n const runner = new tr.ToolRunner(toolPath, args, options);\n return runner.exec();\n });\n}\nexports.exec = exec;\n//# sourceMappingURL=exec.js.map","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst os = __importStar(require(\"os\"));\nconst events = __importStar(require(\"events\"));\nconst child = __importStar(require(\"child_process\"));\nconst path = __importStar(require(\"path\"));\nconst io = __importStar(require(\"@actions/io\"));\nconst ioUtil = __importStar(require(\"@actions/io/lib/io-util\"));\n/* eslint-disable @typescript-eslint/unbound-method */\nconst IS_WINDOWS = process.platform === 'win32';\n/*\n * Class for running command line tools. Handles quoting and arg parsing in a platform agnostic way.\n */\nclass ToolRunner extends events.EventEmitter {\n constructor(toolPath, args, options) {\n super();\n if (!toolPath) {\n throw new Error(\"Parameter 'toolPath' cannot be null or empty.\");\n }\n this.toolPath = toolPath;\n this.args = args || [];\n this.options = options || {};\n }\n _debug(message) {\n if (this.options.listeners && this.options.listeners.debug) {\n this.options.listeners.debug(message);\n }\n }\n _getCommandString(options, noPrefix) {\n const toolPath = this._getSpawnFileName();\n const args = this._getSpawnArgs(options);\n let cmd = noPrefix ? '' : '[command]'; // omit prefix when piped to a second tool\n if (IS_WINDOWS) {\n // Windows + cmd file\n if (this._isCmdFile()) {\n cmd += toolPath;\n for (const a of args) {\n cmd += ` ${a}`;\n }\n }\n // Windows + verbatim\n else if (options.windowsVerbatimArguments) {\n cmd += `\"${toolPath}\"`;\n for (const a of args) {\n cmd += ` ${a}`;\n }\n }\n // Windows (regular)\n else {\n cmd += this._windowsQuoteCmdArg(toolPath);\n for (const a of args) {\n cmd += ` ${this._windowsQuoteCmdArg(a)}`;\n }\n }\n }\n else {\n // OSX/Linux - this can likely be improved with some form of quoting.\n // creating processes on Unix is fundamentally different than Windows.\n // on Unix, execvp() takes an arg array.\n cmd += toolPath;\n for (const a of args) {\n cmd += ` ${a}`;\n }\n }\n return cmd;\n }\n _processLineBuffer(data, strBuffer, onLine) {\n try {\n let s = strBuffer + data.toString();\n let n = s.indexOf(os.EOL);\n while (n > -1) {\n const line = s.substring(0, n);\n onLine(line);\n // the rest of the string ...\n s = s.substring(n + os.EOL.length);\n n = s.indexOf(os.EOL);\n }\n strBuffer = s;\n }\n catch (err) {\n // streaming lines to console is best effort. Don't fail a build.\n this._debug(`error processing line. Failed with error ${err}`);\n }\n }\n _getSpawnFileName() {\n if (IS_WINDOWS) {\n if (this._isCmdFile()) {\n return process.env['COMSPEC'] || 'cmd.exe';\n }\n }\n return this.toolPath;\n }\n _getSpawnArgs(options) {\n if (IS_WINDOWS) {\n if (this._isCmdFile()) {\n let argline = `/D /S /C \"${this._windowsQuoteCmdArg(this.toolPath)}`;\n for (const a of this.args) {\n argline += ' ';\n argline += options.windowsVerbatimArguments\n ? a\n : this._windowsQuoteCmdArg(a);\n }\n argline += '\"';\n return [argline];\n }\n }\n return this.args;\n }\n _endsWith(str, end) {\n return str.endsWith(end);\n }\n _isCmdFile() {\n const upperToolPath = this.toolPath.toUpperCase();\n return (this._endsWith(upperToolPath, '.CMD') ||\n this._endsWith(upperToolPath, '.BAT'));\n }\n _windowsQuoteCmdArg(arg) {\n // for .exe, apply the normal quoting rules that libuv applies\n if (!this._isCmdFile()) {\n return this._uvQuoteCmdArg(arg);\n }\n // otherwise apply quoting rules specific to the cmd.exe command line parser.\n // the libuv rules are generic and are not designed specifically for cmd.exe\n // command line parser.\n //\n // for a detailed description of the cmd.exe command line parser, refer to\n // http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912\n // need quotes for empty arg\n if (!arg) {\n return '\"\"';\n }\n // determine whether the arg needs to be quoted\n const cmdSpecialChars = [\n ' ',\n '\\t',\n '&',\n '(',\n ')',\n '[',\n ']',\n '{',\n '}',\n '^',\n '=',\n ';',\n '!',\n \"'\",\n '+',\n ',',\n '`',\n '~',\n '|',\n '<',\n '>',\n '\"'\n ];\n let needsQuotes = false;\n for (const char of arg) {\n if (cmdSpecialChars.some(x => x === char)) {\n needsQuotes = true;\n break;\n }\n }\n // short-circuit if quotes not needed\n if (!needsQuotes) {\n return arg;\n }\n // the following quoting rules are very similar to the rules that by libuv applies.\n //\n // 1) wrap the string in quotes\n //\n // 2) double-up quotes - i.e. \" => \"\"\n //\n // this is different from the libuv quoting rules. libuv replaces \" with \\\", which unfortunately\n // doesn't work well with a cmd.exe command line.\n //\n // note, replacing \" with \"\" also works well if the arg is passed to a downstream .NET console app.\n // for example, the command line:\n // foo.exe \"myarg:\"\"my val\"\"\"\n // is parsed by a .NET console app into an arg array:\n // [ \"myarg:\\\"my val\\\"\" ]\n // which is the same end result when applying libuv quoting rules. although the actual\n // command line from libuv quoting rules would look like:\n // foo.exe \"myarg:\\\"my val\\\"\"\n //\n // 3) double-up slashes that precede a quote,\n // e.g. hello \\world => \"hello \\world\"\n // hello\\\"world => \"hello\\\\\"\"world\"\n // hello\\\\\"world => \"hello\\\\\\\\\"\"world\"\n // hello world\\ => \"hello world\\\\\"\n //\n // technically this is not required for a cmd.exe command line, or the batch argument parser.\n // the reasons for including this as a .cmd quoting rule are:\n //\n // a) this is optimized for the scenario where the argument is passed from the .cmd file to an\n // external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule.\n //\n // b) it's what we've been doing previously (by deferring to node default behavior) and we\n // haven't heard any complaints about that aspect.\n //\n // note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be\n // escaped when used on the command line directly - even though within a .cmd file % can be escaped\n // by using %%.\n //\n // the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts\n // the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing.\n //\n // one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would\n // often work, since it is unlikely that var^ would exist, and the ^ character is removed when the\n // variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args\n // to an external program.\n //\n // an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file.\n // % can be escaped within a .cmd file.\n let reverse = '\"';\n let quoteHit = true;\n for (let i = arg.length; i > 0; i--) {\n // walk the string in reverse\n reverse += arg[i - 1];\n if (quoteHit && arg[i - 1] === '\\\\') {\n reverse += '\\\\'; // double the slash\n }\n else if (arg[i - 1] === '\"') {\n quoteHit = true;\n reverse += '\"'; // double the quote\n }\n else {\n quoteHit = false;\n }\n }\n reverse += '\"';\n return reverse\n .split('')\n .reverse()\n .join('');\n }\n _uvQuoteCmdArg(arg) {\n // Tool runner wraps child_process.spawn() and needs to apply the same quoting as\n // Node in certain cases where the undocumented spawn option windowsVerbatimArguments\n // is used.\n //\n // Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV,\n // see https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details),\n // pasting copyright notice from Node within this function:\n //\n // Copyright Joyent, Inc. and other Node contributors. All rights reserved.\n //\n // Permission is hereby granted, free of charge, to any person obtaining a copy\n // of this software and associated documentation files (the \"Software\"), to\n // deal in the Software without restriction, including without limitation the\n // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n // sell copies of the Software, and to permit persons to whom the Software is\n // furnished to do so, subject to the following conditions:\n //\n // The above copyright notice and this permission notice shall be included in\n // all copies or substantial portions of the Software.\n //\n // THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n // IN THE SOFTWARE.\n if (!arg) {\n // Need double quotation for empty argument\n return '\"\"';\n }\n if (!arg.includes(' ') && !arg.includes('\\t') && !arg.includes('\"')) {\n // No quotation needed\n return arg;\n }\n if (!arg.includes('\"') && !arg.includes('\\\\')) {\n // No embedded double quotes or backslashes, so I can just wrap\n // quote marks around the whole thing.\n return `\"${arg}\"`;\n }\n // Expected input/output:\n // input : hello\"world\n // output: \"hello\\\"world\"\n // input : hello\"\"world\n // output: \"hello\\\"\\\"world\"\n // input : hello\\world\n // output: hello\\world\n // input : hello\\\\world\n // output: hello\\\\world\n // input : hello\\\"world\n // output: \"hello\\\\\\\"world\"\n // input : hello\\\\\"world\n // output: \"hello\\\\\\\\\\\"world\"\n // input : hello world\\\n // output: \"hello world\\\\\" - note the comment in libuv actually reads \"hello world\\\"\n // but it appears the comment is wrong, it should be \"hello world\\\\\"\n let reverse = '\"';\n let quoteHit = true;\n for (let i = arg.length; i > 0; i--) {\n // walk the string in reverse\n reverse += arg[i - 1];\n if (quoteHit && arg[i - 1] === '\\\\') {\n reverse += '\\\\';\n }\n else if (arg[i - 1] === '\"') {\n quoteHit = true;\n reverse += '\\\\';\n }\n else {\n quoteHit = false;\n }\n }\n reverse += '\"';\n return reverse\n .split('')\n .reverse()\n .join('');\n }\n _cloneExecOptions(options) {\n options = options || {};\n const result = {\n cwd: options.cwd || process.cwd(),\n env: options.env || process.env,\n silent: options.silent || false,\n windowsVerbatimArguments: options.windowsVerbatimArguments || false,\n failOnStdErr: options.failOnStdErr || false,\n ignoreReturnCode: options.ignoreReturnCode || false,\n delay: options.delay || 10000\n };\n result.outStream = options.outStream || process.stdout;\n result.errStream = options.errStream || process.stderr;\n return result;\n }\n _getSpawnOptions(options, toolPath) {\n options = options || {};\n const result = {};\n result.cwd = options.cwd;\n result.env = options.env;\n result['windowsVerbatimArguments'] =\n options.windowsVerbatimArguments || this._isCmdFile();\n if (options.windowsVerbatimArguments) {\n result.argv0 = `\"${toolPath}\"`;\n }\n return result;\n }\n /**\n * Exec a tool.\n * Output will be streamed to the live console.\n * Returns promise with return code\n *\n * @param tool path to tool to exec\n * @param options optional exec options. See ExecOptions\n * @returns number\n */\n exec() {\n return __awaiter(this, void 0, void 0, function* () {\n // root the tool path if it is unrooted and contains relative pathing\n if (!ioUtil.isRooted(this.toolPath) &&\n (this.toolPath.includes('/') ||\n (IS_WINDOWS && this.toolPath.includes('\\\\')))) {\n // prefer options.cwd if it is specified, however options.cwd may also need to be rooted\n this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath);\n }\n // if the tool is only a file name, then resolve it from the PATH\n // otherwise verify it exists (add extension on Windows if necessary)\n this.toolPath = yield io.which(this.toolPath, true);\n return new Promise((resolve, reject) => {\n this._debug(`exec tool: ${this.toolPath}`);\n this._debug('arguments:');\n for (const arg of this.args) {\n this._debug(` ${arg}`);\n }\n const optionsNonNull = this._cloneExecOptions(this.options);\n if (!optionsNonNull.silent && optionsNonNull.outStream) {\n optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL);\n }\n const state = new ExecState(optionsNonNull, this.toolPath);\n state.on('debug', (message) => {\n this._debug(message);\n });\n const fileName = this._getSpawnFileName();\n const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName));\n const stdbuffer = '';\n if (cp.stdout) {\n cp.stdout.on('data', (data) => {\n if (this.options.listeners && this.options.listeners.stdout) {\n this.options.listeners.stdout(data);\n }\n if (!optionsNonNull.silent && optionsNonNull.outStream) {\n optionsNonNull.outStream.write(data);\n }\n this._processLineBuffer(data, stdbuffer, (line) => {\n if (this.options.listeners && this.options.listeners.stdline) {\n this.options.listeners.stdline(line);\n }\n });\n });\n }\n const errbuffer = '';\n if (cp.stderr) {\n cp.stderr.on('data', (data) => {\n state.processStderr = true;\n if (this.options.listeners && this.options.listeners.stderr) {\n this.options.listeners.stderr(data);\n }\n if (!optionsNonNull.silent &&\n optionsNonNull.errStream &&\n optionsNonNull.outStream) {\n const s = optionsNonNull.failOnStdErr\n ? optionsNonNull.errStream\n : optionsNonNull.outStream;\n s.write(data);\n }\n this._processLineBuffer(data, errbuffer, (line) => {\n if (this.options.listeners && this.options.listeners.errline) {\n this.options.listeners.errline(line);\n }\n });\n });\n }\n cp.on('error', (err) => {\n state.processError = err.message;\n state.processExited = true;\n state.processClosed = true;\n state.CheckComplete();\n });\n cp.on('exit', (code) => {\n state.processExitCode = code;\n state.processExited = true;\n this._debug(`Exit code ${code} received from tool '${this.toolPath}'`);\n state.CheckComplete();\n });\n cp.on('close', (code) => {\n state.processExitCode = code;\n state.processExited = true;\n state.processClosed = true;\n this._debug(`STDIO streams have closed for tool '${this.toolPath}'`);\n state.CheckComplete();\n });\n state.on('done', (error, exitCode) => {\n if (stdbuffer.length > 0) {\n this.emit('stdline', stdbuffer);\n }\n if (errbuffer.length > 0) {\n this.emit('errline', errbuffer);\n }\n cp.removeAllListeners();\n if (error) {\n reject(error);\n }\n else {\n resolve(exitCode);\n }\n });\n if (this.options.input) {\n if (!cp.stdin) {\n throw new Error('child process missing stdin');\n }\n cp.stdin.end(this.options.input);\n }\n });\n });\n }\n}\nexports.ToolRunner = ToolRunner;\n/**\n * Convert an arg string to an array of args. Handles escaping\n *\n * @param argString string of arguments\n * @returns string[] array of arguments\n */\nfunction argStringToArray(argString) {\n const args = [];\n let inQuotes = false;\n let escaped = false;\n let arg = '';\n function append(c) {\n // we only escape double quotes.\n if (escaped && c !== '\"') {\n arg += '\\\\';\n }\n arg += c;\n escaped = false;\n }\n for (let i = 0; i < argString.length; i++) {\n const c = argString.charAt(i);\n if (c === '\"') {\n if (!escaped) {\n inQuotes = !inQuotes;\n }\n else {\n append(c);\n }\n continue;\n }\n if (c === '\\\\' && escaped) {\n append(c);\n continue;\n }\n if (c === '\\\\' && inQuotes) {\n escaped = true;\n continue;\n }\n if (c === ' ' && !inQuotes) {\n if (arg.length > 0) {\n args.push(arg);\n arg = '';\n }\n continue;\n }\n append(c);\n }\n if (arg.length > 0) {\n args.push(arg.trim());\n }\n return args;\n}\nexports.argStringToArray = argStringToArray;\nclass ExecState extends events.EventEmitter {\n constructor(options, toolPath) {\n super();\n this.processClosed = false; // tracks whether the process has exited and stdio is closed\n this.processError = '';\n this.processExitCode = 0;\n this.processExited = false; // tracks whether the process has exited\n this.processStderr = false; // tracks whether stderr was written to\n this.delay = 10000; // 10 seconds\n this.done = false;\n this.timeout = null;\n if (!toolPath) {\n throw new Error('toolPath must not be empty');\n }\n this.options = options;\n this.toolPath = toolPath;\n if (options.delay) {\n this.delay = options.delay;\n }\n }\n CheckComplete() {\n if (this.done) {\n return;\n }\n if (this.processClosed) {\n this._setResult();\n }\n else if (this.processExited) {\n this.timeout = setTimeout(ExecState.HandleTimeout, this.delay, this);\n }\n }\n _debug(message) {\n this.emit('debug', message);\n }\n _setResult() {\n // determine whether there is an error\n let error;\n if (this.processExited) {\n if (this.processError) {\n error = new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`);\n }\n else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) {\n error = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`);\n }\n else if (this.processStderr && this.options.failOnStdErr) {\n error = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`);\n }\n }\n // clear the timeout\n if (this.timeout) {\n clearTimeout(this.timeout);\n this.timeout = null;\n }\n this.done = true;\n this.emit('done', error, this.processExitCode);\n }\n static HandleTimeout(state) {\n if (state.done) {\n return;\n }\n if (!state.processClosed && state.processExited) {\n const message = `The STDIO streams did not close within ${state.delay /\n 1000} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`;\n state._debug(message);\n }\n state._setResult();\n }\n}\n//# sourceMappingURL=toolrunner.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Context = void 0;\nconst fs_1 = require(\"fs\");\nconst os_1 = require(\"os\");\nclass Context {\n /**\n * Hydrate the context from the environment\n */\n constructor() {\n this.payload = {};\n if (process.env.GITHUB_EVENT_PATH) {\n if (fs_1.existsSync(process.env.GITHUB_EVENT_PATH)) {\n this.payload = JSON.parse(fs_1.readFileSync(process.env.GITHUB_EVENT_PATH, { encoding: 'utf8' }));\n }\n else {\n const path = process.env.GITHUB_EVENT_PATH;\n process.stdout.write(`GITHUB_EVENT_PATH ${path} does not exist${os_1.EOL}`);\n }\n }\n this.eventName = process.env.GITHUB_EVENT_NAME;\n this.sha = process.env.GITHUB_SHA;\n this.ref = process.env.GITHUB_REF;\n this.workflow = process.env.GITHUB_WORKFLOW;\n this.action = process.env.GITHUB_ACTION;\n this.actor = process.env.GITHUB_ACTOR;\n this.job = process.env.GITHUB_JOB;\n this.runNumber = parseInt(process.env.GITHUB_RUN_NUMBER, 10);\n this.runId = parseInt(process.env.GITHUB_RUN_ID, 10);\n }\n get issue() {\n const payload = this.payload;\n return Object.assign(Object.assign({}, this.repo), { number: (payload.issue || payload.pull_request || payload).number });\n }\n get repo() {\n if (process.env.GITHUB_REPOSITORY) {\n const [owner, repo] = process.env.GITHUB_REPOSITORY.split('/');\n return { owner, repo };\n }\n if (this.payload.repository) {\n return {\n owner: this.payload.repository.owner.login,\n repo: this.payload.repository.name\n };\n }\n throw new Error(\"context.repo requires a GITHUB_REPOSITORY environment variable like 'owner/repo'\");\n }\n}\nexports.Context = Context;\n//# sourceMappingURL=context.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getOctokit = exports.context = void 0;\nconst Context = __importStar(require(\"./context\"));\nconst utils_1 = require(\"./utils\");\nexports.context = new Context.Context();\n/**\n * Returns a hydrated octokit ready to use for GitHub Actions\n *\n * @param token the repo PAT or GITHUB_TOKEN\n * @param options other options to set\n */\nfunction getOctokit(token, options) {\n return new utils_1.GitHub(utils_1.getOctokitOptions(token, options));\n}\nexports.getOctokit = getOctokit;\n//# sourceMappingURL=github.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getApiBaseUrl = exports.getProxyAgent = exports.getAuthString = void 0;\nconst httpClient = __importStar(require(\"@actions/http-client\"));\nfunction getAuthString(token, options) {\n if (!token && !options.auth) {\n throw new Error('Parameter token or opts.auth is required');\n }\n else if (token && options.auth) {\n throw new Error('Parameters token and opts.auth may not both be specified');\n }\n return typeof options.auth === 'string' ? options.auth : `token ${token}`;\n}\nexports.getAuthString = getAuthString;\nfunction getProxyAgent(destinationUrl) {\n const hc = new httpClient.HttpClient();\n return hc.getAgent(destinationUrl);\n}\nexports.getProxyAgent = getProxyAgent;\nfunction getApiBaseUrl() {\n return process.env['GITHUB_API_URL'] || 'https://api.github.com';\n}\nexports.getApiBaseUrl = getApiBaseUrl;\n//# sourceMappingURL=utils.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getOctokitOptions = exports.GitHub = exports.context = void 0;\nconst Context = __importStar(require(\"./context\"));\nconst Utils = __importStar(require(\"./internal/utils\"));\n// octokit + plugins\nconst core_1 = require(\"@octokit/core\");\nconst plugin_rest_endpoint_methods_1 = require(\"@octokit/plugin-rest-endpoint-methods\");\nconst plugin_paginate_rest_1 = require(\"@octokit/plugin-paginate-rest\");\nexports.context = new Context.Context();\nconst baseUrl = Utils.getApiBaseUrl();\nconst defaults = {\n baseUrl,\n request: {\n agent: Utils.getProxyAgent(baseUrl)\n }\n};\nexports.GitHub = core_1.Octokit.plugin(plugin_rest_endpoint_methods_1.restEndpointMethods, plugin_paginate_rest_1.paginateRest).defaults(defaults);\n/**\n * Convience function to correctly format Octokit Options to pass into the constructor.\n *\n * @param token the repo PAT or GITHUB_TOKEN\n * @param options other options to set\n */\nfunction getOctokitOptions(token, options) {\n const opts = Object.assign({}, options || {}); // Shallow clone - don't mutate the object provided by the caller\n // Auth\n const auth = Utils.getAuthString(token, opts);\n if (auth) {\n opts.auth = auth;\n }\n return opts;\n}\nexports.getOctokitOptions = getOctokitOptions;\n//# sourceMappingURL=utils.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst http = require(\"http\");\nconst https = require(\"https\");\nconst pm = require(\"./proxy\");\nlet tunnel;\nvar HttpCodes;\n(function (HttpCodes) {\n HttpCodes[HttpCodes[\"OK\"] = 200] = \"OK\";\n HttpCodes[HttpCodes[\"MultipleChoices\"] = 300] = \"MultipleChoices\";\n HttpCodes[HttpCodes[\"MovedPermanently\"] = 301] = \"MovedPermanently\";\n HttpCodes[HttpCodes[\"ResourceMoved\"] = 302] = \"ResourceMoved\";\n HttpCodes[HttpCodes[\"SeeOther\"] = 303] = \"SeeOther\";\n HttpCodes[HttpCodes[\"NotModified\"] = 304] = \"NotModified\";\n HttpCodes[HttpCodes[\"UseProxy\"] = 305] = \"UseProxy\";\n HttpCodes[HttpCodes[\"SwitchProxy\"] = 306] = \"SwitchProxy\";\n HttpCodes[HttpCodes[\"TemporaryRedirect\"] = 307] = \"TemporaryRedirect\";\n HttpCodes[HttpCodes[\"PermanentRedirect\"] = 308] = \"PermanentRedirect\";\n HttpCodes[HttpCodes[\"BadRequest\"] = 400] = \"BadRequest\";\n HttpCodes[HttpCodes[\"Unauthorized\"] = 401] = \"Unauthorized\";\n HttpCodes[HttpCodes[\"PaymentRequired\"] = 402] = \"PaymentRequired\";\n HttpCodes[HttpCodes[\"Forbidden\"] = 403] = \"Forbidden\";\n HttpCodes[HttpCodes[\"NotFound\"] = 404] = \"NotFound\";\n HttpCodes[HttpCodes[\"MethodNotAllowed\"] = 405] = \"MethodNotAllowed\";\n HttpCodes[HttpCodes[\"NotAcceptable\"] = 406] = \"NotAcceptable\";\n HttpCodes[HttpCodes[\"ProxyAuthenticationRequired\"] = 407] = \"ProxyAuthenticationRequired\";\n HttpCodes[HttpCodes[\"RequestTimeout\"] = 408] = \"RequestTimeout\";\n HttpCodes[HttpCodes[\"Conflict\"] = 409] = \"Conflict\";\n HttpCodes[HttpCodes[\"Gone\"] = 410] = \"Gone\";\n HttpCodes[HttpCodes[\"TooManyRequests\"] = 429] = \"TooManyRequests\";\n HttpCodes[HttpCodes[\"InternalServerError\"] = 500] = \"InternalServerError\";\n HttpCodes[HttpCodes[\"NotImplemented\"] = 501] = \"NotImplemented\";\n HttpCodes[HttpCodes[\"BadGateway\"] = 502] = \"BadGateway\";\n HttpCodes[HttpCodes[\"ServiceUnavailable\"] = 503] = \"ServiceUnavailable\";\n HttpCodes[HttpCodes[\"GatewayTimeout\"] = 504] = \"GatewayTimeout\";\n})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {}));\nvar Headers;\n(function (Headers) {\n Headers[\"Accept\"] = \"accept\";\n Headers[\"ContentType\"] = \"content-type\";\n})(Headers = exports.Headers || (exports.Headers = {}));\nvar MediaTypes;\n(function (MediaTypes) {\n MediaTypes[\"ApplicationJson\"] = \"application/json\";\n})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {}));\n/**\n * Returns the proxy URL, depending upon the supplied url and proxy environment variables.\n * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com\n */\nfunction getProxyUrl(serverUrl) {\n let proxyUrl = pm.getProxyUrl(new URL(serverUrl));\n return proxyUrl ? proxyUrl.href : '';\n}\nexports.getProxyUrl = getProxyUrl;\nconst HttpRedirectCodes = [\n HttpCodes.MovedPermanently,\n HttpCodes.ResourceMoved,\n HttpCodes.SeeOther,\n HttpCodes.TemporaryRedirect,\n HttpCodes.PermanentRedirect\n];\nconst HttpResponseRetryCodes = [\n HttpCodes.BadGateway,\n HttpCodes.ServiceUnavailable,\n HttpCodes.GatewayTimeout\n];\nconst RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD'];\nconst ExponentialBackoffCeiling = 10;\nconst ExponentialBackoffTimeSlice = 5;\nclass HttpClientError extends Error {\n constructor(message, statusCode) {\n super(message);\n this.name = 'HttpClientError';\n this.statusCode = statusCode;\n Object.setPrototypeOf(this, HttpClientError.prototype);\n }\n}\nexports.HttpClientError = HttpClientError;\nclass HttpClientResponse {\n constructor(message) {\n this.message = message;\n }\n readBody() {\n return new Promise(async (resolve, reject) => {\n let output = Buffer.alloc(0);\n this.message.on('data', (chunk) => {\n output = Buffer.concat([output, chunk]);\n });\n this.message.on('end', () => {\n resolve(output.toString());\n });\n });\n }\n}\nexports.HttpClientResponse = HttpClientResponse;\nfunction isHttps(requestUrl) {\n let parsedUrl = new URL(requestUrl);\n return parsedUrl.protocol === 'https:';\n}\nexports.isHttps = isHttps;\nclass HttpClient {\n constructor(userAgent, handlers, requestOptions) {\n this._ignoreSslError = false;\n this._allowRedirects = true;\n this._allowRedirectDowngrade = false;\n this._maxRedirects = 50;\n this._allowRetries = false;\n this._maxRetries = 1;\n this._keepAlive = false;\n this._disposed = false;\n this.userAgent = userAgent;\n this.handlers = handlers || [];\n this.requestOptions = requestOptions;\n if (requestOptions) {\n if (requestOptions.ignoreSslError != null) {\n this._ignoreSslError = requestOptions.ignoreSslError;\n }\n this._socketTimeout = requestOptions.socketTimeout;\n if (requestOptions.allowRedirects != null) {\n this._allowRedirects = requestOptions.allowRedirects;\n }\n if (requestOptions.allowRedirectDowngrade != null) {\n this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade;\n }\n if (requestOptions.maxRedirects != null) {\n this._maxRedirects = Math.max(requestOptions.maxRedirects, 0);\n }\n if (requestOptions.keepAlive != null) {\n this._keepAlive = requestOptions.keepAlive;\n }\n if (requestOptions.allowRetries != null) {\n this._allowRetries = requestOptions.allowRetries;\n }\n if (requestOptions.maxRetries != null) {\n this._maxRetries = requestOptions.maxRetries;\n }\n }\n }\n options(requestUrl, additionalHeaders) {\n return this.request('OPTIONS', requestUrl, null, additionalHeaders || {});\n }\n get(requestUrl, additionalHeaders) {\n return this.request('GET', requestUrl, null, additionalHeaders || {});\n }\n del(requestUrl, additionalHeaders) {\n return this.request('DELETE', requestUrl, null, additionalHeaders || {});\n }\n post(requestUrl, data, additionalHeaders) {\n return this.request('POST', requestUrl, data, additionalHeaders || {});\n }\n patch(requestUrl, data, additionalHeaders) {\n return this.request('PATCH', requestUrl, data, additionalHeaders || {});\n }\n put(requestUrl, data, additionalHeaders) {\n return this.request('PUT', requestUrl, data, additionalHeaders || {});\n }\n head(requestUrl, additionalHeaders) {\n return this.request('HEAD', requestUrl, null, additionalHeaders || {});\n }\n sendStream(verb, requestUrl, stream, additionalHeaders) {\n return this.request(verb, requestUrl, stream, additionalHeaders);\n }\n /**\n * Gets a typed object from an endpoint\n * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise\n */\n async getJson(requestUrl, additionalHeaders = {}) {\n additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);\n let res = await this.get(requestUrl, additionalHeaders);\n return this._processResponse(res, this.requestOptions);\n }\n async postJson(requestUrl, obj, additionalHeaders = {}) {\n let data = JSON.stringify(obj, null, 2);\n additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);\n additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);\n let res = await this.post(requestUrl, data, additionalHeaders);\n return this._processResponse(res, this.requestOptions);\n }\n async putJson(requestUrl, obj, additionalHeaders = {}) {\n let data = JSON.stringify(obj, null, 2);\n additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);\n additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);\n let res = await this.put(requestUrl, data, additionalHeaders);\n return this._processResponse(res, this.requestOptions);\n }\n async patchJson(requestUrl, obj, additionalHeaders = {}) {\n let data = JSON.stringify(obj, null, 2);\n additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);\n additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);\n let res = await this.patch(requestUrl, data, additionalHeaders);\n return this._processResponse(res, this.requestOptions);\n }\n /**\n * Makes a raw http request.\n * All other methods such as get, post, patch, and request ultimately call this.\n * Prefer get, del, post and patch\n */\n async request(verb, requestUrl, data, headers) {\n if (this._disposed) {\n throw new Error('Client has already been disposed.');\n }\n let parsedUrl = new URL(requestUrl);\n let info = this._prepareRequest(verb, parsedUrl, headers);\n // Only perform retries on reads since writes may not be idempotent.\n let maxTries = this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1\n ? this._maxRetries + 1\n : 1;\n let numTries = 0;\n let response;\n while (numTries < maxTries) {\n response = await this.requestRaw(info, data);\n // Check if it's an authentication challenge\n if (response &&\n response.message &&\n response.message.statusCode === HttpCodes.Unauthorized) {\n let authenticationHandler;\n for (let i = 0; i < this.handlers.length; i++) {\n if (this.handlers[i].canHandleAuthentication(response)) {\n authenticationHandler = this.handlers[i];\n break;\n }\n }\n if (authenticationHandler) {\n return authenticationHandler.handleAuthentication(this, info, data);\n }\n else {\n // We have received an unauthorized response but have no handlers to handle it.\n // Let the response return to the caller.\n return response;\n }\n }\n let redirectsRemaining = this._maxRedirects;\n while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1 &&\n this._allowRedirects &&\n redirectsRemaining > 0) {\n const redirectUrl = response.message.headers['location'];\n if (!redirectUrl) {\n // if there's no location to redirect to, we won't\n break;\n }\n let parsedRedirectUrl = new URL(redirectUrl);\n if (parsedUrl.protocol == 'https:' &&\n parsedUrl.protocol != parsedRedirectUrl.protocol &&\n !this._allowRedirectDowngrade) {\n throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.');\n }\n // we need to finish reading the response before reassigning response\n // which will leak the open socket.\n await response.readBody();\n // strip authorization header if redirected to a different hostname\n if (parsedRedirectUrl.hostname !== parsedUrl.hostname) {\n for (let header in headers) {\n // header names are case insensitive\n if (header.toLowerCase() === 'authorization') {\n delete headers[header];\n }\n }\n }\n // let's make the request with the new redirectUrl\n info = this._prepareRequest(verb, parsedRedirectUrl, headers);\n response = await this.requestRaw(info, data);\n redirectsRemaining--;\n }\n if (HttpResponseRetryCodes.indexOf(response.message.statusCode) == -1) {\n // If not a retry code, return immediately instead of retrying\n return response;\n }\n numTries += 1;\n if (numTries < maxTries) {\n await response.readBody();\n await this._performExponentialBackoff(numTries);\n }\n }\n return response;\n }\n /**\n * Needs to be called if keepAlive is set to true in request options.\n */\n dispose() {\n if (this._agent) {\n this._agent.destroy();\n }\n this._disposed = true;\n }\n /**\n * Raw request.\n * @param info\n * @param data\n */\n requestRaw(info, data) {\n return new Promise((resolve, reject) => {\n let callbackForResult = function (err, res) {\n if (err) {\n reject(err);\n }\n resolve(res);\n };\n this.requestRawWithCallback(info, data, callbackForResult);\n });\n }\n /**\n * Raw request with callback.\n * @param info\n * @param data\n * @param onResult\n */\n requestRawWithCallback(info, data, onResult) {\n let socket;\n if (typeof data === 'string') {\n info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8');\n }\n let callbackCalled = false;\n let handleResult = (err, res) => {\n if (!callbackCalled) {\n callbackCalled = true;\n onResult(err, res);\n }\n };\n let req = info.httpModule.request(info.options, (msg) => {\n let res = new HttpClientResponse(msg);\n handleResult(null, res);\n });\n req.on('socket', sock => {\n socket = sock;\n });\n // If we ever get disconnected, we want the socket to timeout eventually\n req.setTimeout(this._socketTimeout || 3 * 60000, () => {\n if (socket) {\n socket.end();\n }\n handleResult(new Error('Request timeout: ' + info.options.path), null);\n });\n req.on('error', function (err) {\n // err has statusCode property\n // res should have headers\n handleResult(err, null);\n });\n if (data && typeof data === 'string') {\n req.write(data, 'utf8');\n }\n if (data && typeof data !== 'string') {\n data.on('close', function () {\n req.end();\n });\n data.pipe(req);\n }\n else {\n req.end();\n }\n }\n /**\n * Gets an http agent. This function is useful when you need an http agent that handles\n * routing through a proxy server - depending upon the url and proxy environment variables.\n * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com\n */\n getAgent(serverUrl) {\n let parsedUrl = new URL(serverUrl);\n return this._getAgent(parsedUrl);\n }\n _prepareRequest(method, requestUrl, headers) {\n const info = {};\n info.parsedUrl = requestUrl;\n const usingSsl = info.parsedUrl.protocol === 'https:';\n info.httpModule = usingSsl ? https : http;\n const defaultPort = usingSsl ? 443 : 80;\n info.options = {};\n info.options.host = info.parsedUrl.hostname;\n info.options.port = info.parsedUrl.port\n ? parseInt(info.parsedUrl.port)\n : defaultPort;\n info.options.path =\n (info.parsedUrl.pathname || '') + (info.parsedUrl.search || '');\n info.options.method = method;\n info.options.headers = this._mergeHeaders(headers);\n if (this.userAgent != null) {\n info.options.headers['user-agent'] = this.userAgent;\n }\n info.options.agent = this._getAgent(info.parsedUrl);\n // gives handlers an opportunity to participate\n if (this.handlers) {\n this.handlers.forEach(handler => {\n handler.prepareRequest(info.options);\n });\n }\n return info;\n }\n _mergeHeaders(headers) {\n const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {});\n if (this.requestOptions && this.requestOptions.headers) {\n return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers));\n }\n return lowercaseKeys(headers || {});\n }\n _getExistingOrDefaultHeader(additionalHeaders, header, _default) {\n const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {});\n let clientHeader;\n if (this.requestOptions && this.requestOptions.headers) {\n clientHeader = lowercaseKeys(this.requestOptions.headers)[header];\n }\n return additionalHeaders[header] || clientHeader || _default;\n }\n _getAgent(parsedUrl) {\n let agent;\n let proxyUrl = pm.getProxyUrl(parsedUrl);\n let useProxy = proxyUrl && proxyUrl.hostname;\n if (this._keepAlive && useProxy) {\n agent = this._proxyAgent;\n }\n if (this._keepAlive && !useProxy) {\n agent = this._agent;\n }\n // if agent is already assigned use that agent.\n if (!!agent) {\n return agent;\n }\n const usingSsl = parsedUrl.protocol === 'https:';\n let maxSockets = 100;\n if (!!this.requestOptions) {\n maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets;\n }\n if (useProxy) {\n // If using proxy, need tunnel\n if (!tunnel) {\n tunnel = require('tunnel');\n }\n const agentOptions = {\n maxSockets: maxSockets,\n keepAlive: this._keepAlive,\n proxy: {\n proxyAuth: `${proxyUrl.username}:${proxyUrl.password}`,\n host: proxyUrl.hostname,\n port: proxyUrl.port\n }\n };\n let tunnelAgent;\n const overHttps = proxyUrl.protocol === 'https:';\n if (usingSsl) {\n tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp;\n }\n else {\n tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp;\n }\n agent = tunnelAgent(agentOptions);\n this._proxyAgent = agent;\n }\n // if reusing agent across request and tunneling agent isn't assigned create a new agent\n if (this._keepAlive && !agent) {\n const options = { keepAlive: this._keepAlive, maxSockets: maxSockets };\n agent = usingSsl ? new https.Agent(options) : new http.Agent(options);\n this._agent = agent;\n }\n // if not using private agent and tunnel agent isn't setup then use global agent\n if (!agent) {\n agent = usingSsl ? https.globalAgent : http.globalAgent;\n }\n if (usingSsl && this._ignoreSslError) {\n // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process\n // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options\n // we have to cast it to any and change it directly\n agent.options = Object.assign(agent.options || {}, {\n rejectUnauthorized: false\n });\n }\n return agent;\n }\n _performExponentialBackoff(retryNumber) {\n retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);\n const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber);\n return new Promise(resolve => setTimeout(() => resolve(), ms));\n }\n static dateTimeDeserializer(key, value) {\n if (typeof value === 'string') {\n let a = new Date(value);\n if (!isNaN(a.valueOf())) {\n return a;\n }\n }\n return value;\n }\n async _processResponse(res, options) {\n return new Promise(async (resolve, reject) => {\n const statusCode = res.message.statusCode;\n const response = {\n statusCode: statusCode,\n result: null,\n headers: {}\n };\n // not found leads to null obj returned\n if (statusCode == HttpCodes.NotFound) {\n resolve(response);\n }\n let obj;\n let contents;\n // get the result from the body\n try {\n contents = await res.readBody();\n if (contents && contents.length > 0) {\n if (options && options.deserializeDates) {\n obj = JSON.parse(contents, HttpClient.dateTimeDeserializer);\n }\n else {\n obj = JSON.parse(contents);\n }\n response.result = obj;\n }\n response.headers = res.message.headers;\n }\n catch (err) {\n // Invalid resource (contents not json); leaving result obj null\n }\n // note that 3xx redirects are handled by the http layer.\n if (statusCode > 299) {\n let msg;\n // if exception/error in body, attempt to get better error\n if (obj && obj.message) {\n msg = obj.message;\n }\n else if (contents && contents.length > 0) {\n // it may be the case that the exception is in the body message as string\n msg = contents;\n }\n else {\n msg = 'Failed request: (' + statusCode + ')';\n }\n let err = new HttpClientError(msg, statusCode);\n err.result = response.result;\n reject(err);\n }\n else {\n resolve(response);\n }\n });\n }\n}\nexports.HttpClient = HttpClient;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nfunction getProxyUrl(reqUrl) {\n let usingSsl = reqUrl.protocol === 'https:';\n let proxyUrl;\n if (checkBypass(reqUrl)) {\n return proxyUrl;\n }\n let proxyVar;\n if (usingSsl) {\n proxyVar = process.env['https_proxy'] || process.env['HTTPS_PROXY'];\n }\n else {\n proxyVar = process.env['http_proxy'] || process.env['HTTP_PROXY'];\n }\n if (proxyVar) {\n proxyUrl = new URL(proxyVar);\n }\n return proxyUrl;\n}\nexports.getProxyUrl = getProxyUrl;\nfunction checkBypass(reqUrl) {\n if (!reqUrl.hostname) {\n return false;\n }\n let noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || '';\n if (!noProxy) {\n return false;\n }\n // Determine the request port\n let reqPort;\n if (reqUrl.port) {\n reqPort = Number(reqUrl.port);\n }\n else if (reqUrl.protocol === 'http:') {\n reqPort = 80;\n }\n else if (reqUrl.protocol === 'https:') {\n reqPort = 443;\n }\n // Format the request hostname and hostname with port\n let upperReqHosts = [reqUrl.hostname.toUpperCase()];\n if (typeof reqPort === 'number') {\n upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`);\n }\n // Compare request host against noproxy\n for (let upperNoProxyItem of noProxy\n .split(',')\n .map(x => x.trim().toUpperCase())\n .filter(x => x)) {\n if (upperReqHosts.some(x => x === upperNoProxyItem)) {\n return true;\n }\n }\n return false;\n}\nexports.checkBypass = checkBypass;\n","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar _a;\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst assert_1 = require(\"assert\");\nconst fs = require(\"fs\");\nconst path = require(\"path\");\n_a = fs.promises, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink;\nexports.IS_WINDOWS = process.platform === 'win32';\nfunction exists(fsPath) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n yield exports.stat(fsPath);\n }\n catch (err) {\n if (err.code === 'ENOENT') {\n return false;\n }\n throw err;\n }\n return true;\n });\n}\nexports.exists = exists;\nfunction isDirectory(fsPath, useStat = false) {\n return __awaiter(this, void 0, void 0, function* () {\n const stats = useStat ? yield exports.stat(fsPath) : yield exports.lstat(fsPath);\n return stats.isDirectory();\n });\n}\nexports.isDirectory = isDirectory;\n/**\n * On OSX/Linux, true if path starts with '/'. On Windows, true for paths like:\n * \\, \\hello, \\\\hello\\share, C:, and C:\\hello (and corresponding alternate separator cases).\n */\nfunction isRooted(p) {\n p = normalizeSeparators(p);\n if (!p) {\n throw new Error('isRooted() parameter \"p\" cannot be empty');\n }\n if (exports.IS_WINDOWS) {\n return (p.startsWith('\\\\') || /^[A-Z]:/i.test(p) // e.g. \\ or \\hello or \\\\hello\n ); // e.g. C: or C:\\hello\n }\n return p.startsWith('/');\n}\nexports.isRooted = isRooted;\n/**\n * Recursively create a directory at `fsPath`.\n *\n * This implementation is optimistic, meaning it attempts to create the full\n * path first, and backs up the path stack from there.\n *\n * @param fsPath The path to create\n * @param maxDepth The maximum recursion depth\n * @param depth The current recursion depth\n */\nfunction mkdirP(fsPath, maxDepth = 1000, depth = 1) {\n return __awaiter(this, void 0, void 0, function* () {\n assert_1.ok(fsPath, 'a path argument must be provided');\n fsPath = path.resolve(fsPath);\n if (depth >= maxDepth)\n return exports.mkdir(fsPath);\n try {\n yield exports.mkdir(fsPath);\n return;\n }\n catch (err) {\n switch (err.code) {\n case 'ENOENT': {\n yield mkdirP(path.dirname(fsPath), maxDepth, depth + 1);\n yield exports.mkdir(fsPath);\n return;\n }\n default: {\n let stats;\n try {\n stats = yield exports.stat(fsPath);\n }\n catch (err2) {\n throw err;\n }\n if (!stats.isDirectory())\n throw err;\n }\n }\n }\n });\n}\nexports.mkdirP = mkdirP;\n/**\n * Best effort attempt to determine whether a file exists and is executable.\n * @param filePath file path to check\n * @param extensions additional file extensions to try\n * @return if file exists and is executable, returns the file path. otherwise empty string.\n */\nfunction tryGetExecutablePath(filePath, extensions) {\n return __awaiter(this, void 0, void 0, function* () {\n let stats = undefined;\n try {\n // test file exists\n stats = yield exports.stat(filePath);\n }\n catch (err) {\n if (err.code !== 'ENOENT') {\n // eslint-disable-next-line no-console\n console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`);\n }\n }\n if (stats && stats.isFile()) {\n if (exports.IS_WINDOWS) {\n // on Windows, test for valid extension\n const upperExt = path.extname(filePath).toUpperCase();\n if (extensions.some(validExt => validExt.toUpperCase() === upperExt)) {\n return filePath;\n }\n }\n else {\n if (isUnixExecutable(stats)) {\n return filePath;\n }\n }\n }\n // try each extension\n const originalFilePath = filePath;\n for (const extension of extensions) {\n filePath = originalFilePath + extension;\n stats = undefined;\n try {\n stats = yield exports.stat(filePath);\n }\n catch (err) {\n if (err.code !== 'ENOENT') {\n // eslint-disable-next-line no-console\n console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`);\n }\n }\n if (stats && stats.isFile()) {\n if (exports.IS_WINDOWS) {\n // preserve the case of the actual file (since an extension was appended)\n try {\n const directory = path.dirname(filePath);\n const upperName = path.basename(filePath).toUpperCase();\n for (const actualName of yield exports.readdir(directory)) {\n if (upperName === actualName.toUpperCase()) {\n filePath = path.join(directory, actualName);\n break;\n }\n }\n }\n catch (err) {\n // eslint-disable-next-line no-console\n console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`);\n }\n return filePath;\n }\n else {\n if (isUnixExecutable(stats)) {\n return filePath;\n }\n }\n }\n }\n return '';\n });\n}\nexports.tryGetExecutablePath = tryGetExecutablePath;\nfunction normalizeSeparators(p) {\n p = p || '';\n if (exports.IS_WINDOWS) {\n // convert slashes on Windows\n p = p.replace(/\\//g, '\\\\');\n // remove redundant slashes\n return p.replace(/\\\\\\\\+/g, '\\\\');\n }\n // remove redundant slashes\n return p.replace(/\\/\\/+/g, '/');\n}\n// on Mac/Linux, test the execute bit\n// R W X R W X R W X\n// 256 128 64 32 16 8 4 2 1\nfunction isUnixExecutable(stats) {\n return ((stats.mode & 1) > 0 ||\n ((stats.mode & 8) > 0 && stats.gid === process.getgid()) ||\n ((stats.mode & 64) > 0 && stats.uid === process.getuid()));\n}\n//# sourceMappingURL=io-util.js.map","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst childProcess = require(\"child_process\");\nconst path = require(\"path\");\nconst util_1 = require(\"util\");\nconst ioUtil = require(\"./io-util\");\nconst exec = util_1.promisify(childProcess.exec);\n/**\n * Copies a file or folder.\n * Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js\n *\n * @param source source path\n * @param dest destination path\n * @param options optional. See CopyOptions.\n */\nfunction cp(source, dest, options = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n const { force, recursive } = readCopyOptions(options);\n const destStat = (yield ioUtil.exists(dest)) ? yield ioUtil.stat(dest) : null;\n // Dest is an existing file, but not forcing\n if (destStat && destStat.isFile() && !force) {\n return;\n }\n // If dest is an existing directory, should copy inside.\n const newDest = destStat && destStat.isDirectory()\n ? path.join(dest, path.basename(source))\n : dest;\n if (!(yield ioUtil.exists(source))) {\n throw new Error(`no such file or directory: ${source}`);\n }\n const sourceStat = yield ioUtil.stat(source);\n if (sourceStat.isDirectory()) {\n if (!recursive) {\n throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`);\n }\n else {\n yield cpDirRecursive(source, newDest, 0, force);\n }\n }\n else {\n if (path.relative(source, newDest) === '') {\n // a file cannot be copied to itself\n throw new Error(`'${newDest}' and '${source}' are the same file`);\n }\n yield copyFile(source, newDest, force);\n }\n });\n}\nexports.cp = cp;\n/**\n * Moves a path.\n *\n * @param source source path\n * @param dest destination path\n * @param options optional. See MoveOptions.\n */\nfunction mv(source, dest, options = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n if (yield ioUtil.exists(dest)) {\n let destExists = true;\n if (yield ioUtil.isDirectory(dest)) {\n // If dest is directory copy src into dest\n dest = path.join(dest, path.basename(source));\n destExists = yield ioUtil.exists(dest);\n }\n if (destExists) {\n if (options.force == null || options.force) {\n yield rmRF(dest);\n }\n else {\n throw new Error('Destination already exists');\n }\n }\n }\n yield mkdirP(path.dirname(dest));\n yield ioUtil.rename(source, dest);\n });\n}\nexports.mv = mv;\n/**\n * Remove a path recursively with force\n *\n * @param inputPath path to remove\n */\nfunction rmRF(inputPath) {\n return __awaiter(this, void 0, void 0, function* () {\n if (ioUtil.IS_WINDOWS) {\n // Node doesn't provide a delete operation, only an unlink function. This means that if the file is being used by another\n // program (e.g. antivirus), it won't be deleted. To address this, we shell out the work to rd/del.\n try {\n if (yield ioUtil.isDirectory(inputPath, true)) {\n yield exec(`rd /s /q \"${inputPath}\"`);\n }\n else {\n yield exec(`del /f /a \"${inputPath}\"`);\n }\n }\n catch (err) {\n // if you try to delete a file that doesn't exist, desired result is achieved\n // other errors are valid\n if (err.code !== 'ENOENT')\n throw err;\n }\n // Shelling out fails to remove a symlink folder with missing source, this unlink catches that\n try {\n yield ioUtil.unlink(inputPath);\n }\n catch (err) {\n // if you try to delete a file that doesn't exist, desired result is achieved\n // other errors are valid\n if (err.code !== 'ENOENT')\n throw err;\n }\n }\n else {\n let isDir = false;\n try {\n isDir = yield ioUtil.isDirectory(inputPath);\n }\n catch (err) {\n // if you try to delete a file that doesn't exist, desired result is achieved\n // other errors are valid\n if (err.code !== 'ENOENT')\n throw err;\n return;\n }\n if (isDir) {\n yield exec(`rm -rf \"${inputPath}\"`);\n }\n else {\n yield ioUtil.unlink(inputPath);\n }\n }\n });\n}\nexports.rmRF = rmRF;\n/**\n * Make a directory. Creates the full path with folders in between\n * Will throw if it fails\n *\n * @param fsPath path to create\n * @returns Promise\n */\nfunction mkdirP(fsPath) {\n return __awaiter(this, void 0, void 0, function* () {\n yield ioUtil.mkdirP(fsPath);\n });\n}\nexports.mkdirP = mkdirP;\n/**\n * Returns path of a tool had the tool actually been invoked. Resolves via paths.\n * If you check and the tool does not exist, it will throw.\n *\n * @param tool name of the tool\n * @param check whether to check if tool exists\n * @returns Promise path to tool\n */\nfunction which(tool, check) {\n return __awaiter(this, void 0, void 0, function* () {\n if (!tool) {\n throw new Error(\"parameter 'tool' is required\");\n }\n // recursive when check=true\n if (check) {\n const result = yield which(tool, false);\n if (!result) {\n if (ioUtil.IS_WINDOWS) {\n throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`);\n }\n else {\n throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`);\n }\n }\n }\n try {\n // build the list of extensions to try\n const extensions = [];\n if (ioUtil.IS_WINDOWS && process.env.PATHEXT) {\n for (const extension of process.env.PATHEXT.split(path.delimiter)) {\n if (extension) {\n extensions.push(extension);\n }\n }\n }\n // if it's rooted, return it if exists. otherwise return empty.\n if (ioUtil.isRooted(tool)) {\n const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions);\n if (filePath) {\n return filePath;\n }\n return '';\n }\n // if any path separators, return empty\n if (tool.includes('/') || (ioUtil.IS_WINDOWS && tool.includes('\\\\'))) {\n return '';\n }\n // build the list of directories\n //\n // Note, technically \"where\" checks the current directory on Windows. From a toolkit perspective,\n // it feels like we should not do this. Checking the current directory seems like more of a use\n // case of a shell, and the which() function exposed by the toolkit should strive for consistency\n // across platforms.\n const directories = [];\n if (process.env.PATH) {\n for (const p of process.env.PATH.split(path.delimiter)) {\n if (p) {\n directories.push(p);\n }\n }\n }\n // return the first match\n for (const directory of directories) {\n const filePath = yield ioUtil.tryGetExecutablePath(directory + path.sep + tool, extensions);\n if (filePath) {\n return filePath;\n }\n }\n return '';\n }\n catch (err) {\n throw new Error(`which failed with message ${err.message}`);\n }\n });\n}\nexports.which = which;\nfunction readCopyOptions(options) {\n const force = options.force == null ? true : options.force;\n const recursive = Boolean(options.recursive);\n return { force, recursive };\n}\nfunction cpDirRecursive(sourceDir, destDir, currentDepth, force) {\n return __awaiter(this, void 0, void 0, function* () {\n // Ensure there is not a run away recursive copy\n if (currentDepth >= 255)\n return;\n currentDepth++;\n yield mkdirP(destDir);\n const files = yield ioUtil.readdir(sourceDir);\n for (const fileName of files) {\n const srcFile = `${sourceDir}/${fileName}`;\n const destFile = `${destDir}/${fileName}`;\n const srcFileStat = yield ioUtil.lstat(srcFile);\n if (srcFileStat.isDirectory()) {\n // Recurse\n yield cpDirRecursive(srcFile, destFile, currentDepth, force);\n }\n else {\n yield copyFile(srcFile, destFile, force);\n }\n }\n // Change the mode for the newly created directory\n yield ioUtil.chmod(destDir, (yield ioUtil.stat(sourceDir)).mode);\n });\n}\n// Buffered file copy\nfunction copyFile(srcFile, destFile, force) {\n return __awaiter(this, void 0, void 0, function* () {\n if ((yield ioUtil.lstat(srcFile)).isSymbolicLink()) {\n // unlink/re-link it\n try {\n yield ioUtil.lstat(destFile);\n yield ioUtil.unlink(destFile);\n }\n catch (e) {\n // Try to override file permission\n if (e.code === 'EPERM') {\n yield ioUtil.chmod(destFile, '0666');\n yield ioUtil.unlink(destFile);\n }\n // other errors = it doesn't exist, no work to do\n }\n // Copy over symlink\n const symlinkFull = yield ioUtil.readlink(srcFile);\n yield ioUtil.symlink(symlinkFull, destFile, ioUtil.IS_WINDOWS ? 'junction' : null);\n }\n else if (!(yield ioUtil.exists(destFile)) || force) {\n yield ioUtil.copyFile(srcFile, destFile);\n }\n });\n}\n//# sourceMappingURL=io.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.BackoffTimeout = void 0;\nconst INITIAL_BACKOFF_MS = 1000;\nconst BACKOFF_MULTIPLIER = 1.6;\nconst MAX_BACKOFF_MS = 120000;\nconst BACKOFF_JITTER = 0.2;\n/**\n * Get a number uniformly at random in the range [min, max)\n * @param min\n * @param max\n */\nfunction uniformRandom(min, max) {\n return Math.random() * (max - min) + min;\n}\nclass BackoffTimeout {\n constructor(callback, options) {\n this.callback = callback;\n this.initialDelay = INITIAL_BACKOFF_MS;\n this.multiplier = BACKOFF_MULTIPLIER;\n this.maxDelay = MAX_BACKOFF_MS;\n this.jitter = BACKOFF_JITTER;\n this.running = false;\n this.hasRef = true;\n if (options) {\n if (options.initialDelay) {\n this.initialDelay = options.initialDelay;\n }\n if (options.multiplier) {\n this.multiplier = options.multiplier;\n }\n if (options.jitter) {\n this.jitter = options.jitter;\n }\n if (options.maxDelay) {\n this.maxDelay = options.maxDelay;\n }\n }\n this.nextDelay = this.initialDelay;\n this.timerId = setTimeout(() => { }, 0);\n clearTimeout(this.timerId);\n }\n /**\n * Call the callback after the current amount of delay time\n */\n runOnce() {\n this.running = true;\n this.timerId = setTimeout(() => {\n this.callback();\n this.running = false;\n }, this.nextDelay);\n if (!this.hasRef) {\n this.timerId.unref();\n }\n const nextBackoff = Math.min(this.nextDelay * this.multiplier, this.maxDelay);\n const jitterMagnitude = nextBackoff * this.jitter;\n this.nextDelay =\n nextBackoff + uniformRandom(-jitterMagnitude, jitterMagnitude);\n }\n /**\n * Stop the timer. The callback will not be called until `runOnce` is called\n * again.\n */\n stop() {\n clearTimeout(this.timerId);\n this.running = false;\n }\n /**\n * Reset the delay time to its initial value.\n */\n reset() {\n this.nextDelay = this.initialDelay;\n }\n isRunning() {\n return this.running;\n }\n ref() {\n this.hasRef = true;\n this.timerId.ref();\n }\n unref() {\n this.hasRef = false;\n this.timerId.unref();\n }\n}\nexports.BackoffTimeout = BackoffTimeout;\n//# sourceMappingURL=backoff-timeout.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CallCredentialsFilterFactory = exports.CallCredentialsFilter = void 0;\nconst filter_1 = require(\"./filter\");\nconst constants_1 = require(\"./constants\");\nconst uri_parser_1 = require(\"./uri-parser\");\nclass CallCredentialsFilter extends filter_1.BaseFilter {\n constructor(channel, stream) {\n var _a, _b;\n super();\n this.channel = channel;\n this.stream = stream;\n this.channel = channel;\n this.stream = stream;\n const splitPath = stream.getMethod().split('/');\n let serviceName = '';\n /* The standard path format is \"/{serviceName}/{methodName}\", so if we split\n * by '/', the first item should be empty and the second should be the\n * service name */\n if (splitPath.length >= 2) {\n serviceName = splitPath[1];\n }\n const hostname = (_b = (_a = uri_parser_1.splitHostPort(stream.getHost())) === null || _a === void 0 ? void 0 : _a.host) !== null && _b !== void 0 ? _b : 'localhost';\n /* Currently, call credentials are only allowed on HTTPS connections, so we\n * can assume that the scheme is \"https\" */\n this.serviceUrl = `https://${hostname}/${serviceName}`;\n }\n async sendMetadata(metadata) {\n const credentials = this.stream.getCredentials();\n const credsMetadata = credentials.generateMetadata({\n service_url: this.serviceUrl,\n });\n const resultMetadata = await metadata;\n try {\n resultMetadata.merge(await credsMetadata);\n }\n catch (error) {\n this.stream.cancelWithStatus(constants_1.Status.UNAUTHENTICATED, `Failed to retrieve auth metadata with error: ${error.message}`);\n return Promise.reject('Failed to retrieve auth metadata');\n }\n if (resultMetadata.get('authorization').length > 1) {\n this.stream.cancelWithStatus(constants_1.Status.INTERNAL, '\"authorization\" metadata cannot have multiple values');\n return Promise.reject('\"authorization\" metadata cannot have multiple values');\n }\n return resultMetadata;\n }\n}\nexports.CallCredentialsFilter = CallCredentialsFilter;\nclass CallCredentialsFilterFactory {\n constructor(channel) {\n this.channel = channel;\n this.channel = channel;\n }\n createFilter(callStream) {\n return new CallCredentialsFilter(this.channel, callStream);\n }\n}\nexports.CallCredentialsFilterFactory = CallCredentialsFilterFactory;\n//# sourceMappingURL=call-credentials-filter.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CallCredentials = void 0;\nconst metadata_1 = require(\"./metadata\");\nfunction isCurrentOauth2Client(client) {\n return ('getRequestHeaders' in client &&\n typeof client.getRequestHeaders === 'function');\n}\n/**\n * A class that represents a generic method of adding authentication-related\n * metadata on a per-request basis.\n */\nclass CallCredentials {\n /**\n * Creates a new CallCredentials object from a given function that generates\n * Metadata objects.\n * @param metadataGenerator A function that accepts a set of options, and\n * generates a Metadata object based on these options, which is passed back\n * to the caller via a supplied (err, metadata) callback.\n */\n static createFromMetadataGenerator(metadataGenerator) {\n return new SingleCallCredentials(metadataGenerator);\n }\n /**\n * Create a gRPC credential from a Google credential object.\n * @param googleCredentials The authentication client to use.\n * @return The resulting CallCredentials object.\n */\n static createFromGoogleCredential(googleCredentials) {\n return CallCredentials.createFromMetadataGenerator((options, callback) => {\n let getHeaders;\n if (isCurrentOauth2Client(googleCredentials)) {\n getHeaders = googleCredentials.getRequestHeaders(options.service_url);\n }\n else {\n getHeaders = new Promise((resolve, reject) => {\n googleCredentials.getRequestMetadata(options.service_url, (err, headers) => {\n if (err) {\n reject(err);\n return;\n }\n resolve(headers);\n });\n });\n }\n getHeaders.then((headers) => {\n const metadata = new metadata_1.Metadata();\n for (const key of Object.keys(headers)) {\n metadata.add(key, headers[key]);\n }\n callback(null, metadata);\n }, (err) => {\n callback(err);\n });\n });\n }\n static createEmpty() {\n return new EmptyCallCredentials();\n }\n}\nexports.CallCredentials = CallCredentials;\nclass ComposedCallCredentials extends CallCredentials {\n constructor(creds) {\n super();\n this.creds = creds;\n }\n async generateMetadata(options) {\n const base = new metadata_1.Metadata();\n const generated = await Promise.all(this.creds.map((cred) => cred.generateMetadata(options)));\n for (const gen of generated) {\n base.merge(gen);\n }\n return base;\n }\n compose(other) {\n return new ComposedCallCredentials(this.creds.concat([other]));\n }\n _equals(other) {\n if (this === other) {\n return true;\n }\n if (other instanceof ComposedCallCredentials) {\n return this.creds.every((value, index) => value._equals(other.creds[index]));\n }\n else {\n return false;\n }\n }\n}\nclass SingleCallCredentials extends CallCredentials {\n constructor(metadataGenerator) {\n super();\n this.metadataGenerator = metadataGenerator;\n }\n generateMetadata(options) {\n return new Promise((resolve, reject) => {\n this.metadataGenerator(options, (err, metadata) => {\n if (metadata !== undefined) {\n resolve(metadata);\n }\n else {\n reject(err);\n }\n });\n });\n }\n compose(other) {\n return new ComposedCallCredentials([this, other]);\n }\n _equals(other) {\n if (this === other) {\n return true;\n }\n if (other instanceof SingleCallCredentials) {\n return this.metadataGenerator === other.metadataGenerator;\n }\n else {\n return false;\n }\n }\n}\nclass EmptyCallCredentials extends CallCredentials {\n generateMetadata(options) {\n return Promise.resolve(new metadata_1.Metadata());\n }\n compose(other) {\n return other;\n }\n _equals(other) {\n return other instanceof EmptyCallCredentials;\n }\n}\n//# sourceMappingURL=call-credentials.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Http2CallStream = exports.InterceptingListenerImpl = exports.isInterceptingListener = void 0;\nconst http2 = require(\"http2\");\nconst constants_1 = require(\"./constants\");\nconst filter_stack_1 = require(\"./filter-stack\");\nconst metadata_1 = require(\"./metadata\");\nconst stream_decoder_1 = require(\"./stream-decoder\");\nconst logging = require(\"./logging\");\nconst constants_2 = require(\"./constants\");\nconst TRACER_NAME = 'call_stream';\nconst { HTTP2_HEADER_STATUS, HTTP2_HEADER_CONTENT_TYPE, NGHTTP2_CANCEL, } = http2.constants;\nfunction isInterceptingListener(listener) {\n return (listener.onReceiveMetadata !== undefined &&\n listener.onReceiveMetadata.length === 1);\n}\nexports.isInterceptingListener = isInterceptingListener;\nclass InterceptingListenerImpl {\n constructor(listener, nextListener) {\n this.listener = listener;\n this.nextListener = nextListener;\n this.processingMessage = false;\n this.pendingStatus = null;\n }\n onReceiveMetadata(metadata) {\n this.listener.onReceiveMetadata(metadata, (metadata) => {\n this.nextListener.onReceiveMetadata(metadata);\n });\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n onReceiveMessage(message) {\n /* If this listener processes messages asynchronously, the last message may\n * be reordered with respect to the status */\n this.processingMessage = true;\n this.listener.onReceiveMessage(message, (msg) => {\n this.processingMessage = false;\n this.nextListener.onReceiveMessage(msg);\n if (this.pendingStatus) {\n this.nextListener.onReceiveStatus(this.pendingStatus);\n }\n });\n }\n onReceiveStatus(status) {\n this.listener.onReceiveStatus(status, (processedStatus) => {\n if (this.processingMessage) {\n this.pendingStatus = processedStatus;\n }\n else {\n this.nextListener.onReceiveStatus(processedStatus);\n }\n });\n }\n}\nexports.InterceptingListenerImpl = InterceptingListenerImpl;\nclass Http2CallStream {\n constructor(methodName, channel, options, filterStackFactory, channelCallCredentials, callNumber) {\n this.methodName = methodName;\n this.channel = channel;\n this.options = options;\n this.channelCallCredentials = channelCallCredentials;\n this.callNumber = callNumber;\n this.http2Stream = null;\n this.pendingRead = false;\n this.isWriteFilterPending = false;\n this.pendingWrite = null;\n this.pendingWriteCallback = null;\n this.writesClosed = false;\n this.decoder = new stream_decoder_1.StreamDecoder();\n this.isReadFilterPending = false;\n this.canPush = false;\n /**\n * Indicates that an 'end' event has come from the http2 stream, so there\n * will be no more data events.\n */\n this.readsClosed = false;\n this.statusOutput = false;\n this.unpushedReadMessages = [];\n this.unfilteredReadMessages = [];\n // Status code mapped from :status. To be used if grpc-status is not received\n this.mappedStatusCode = constants_1.Status.UNKNOWN;\n // This is populated (non-null) if and only if the call has ended\n this.finalStatus = null;\n this.subchannel = null;\n this.listener = null;\n this.internalErrorMessage = null;\n this.filterStack = filterStackFactory.createFilter(this);\n this.credentials = channelCallCredentials;\n this.disconnectListener = () => {\n this.endCall({\n code: constants_1.Status.UNAVAILABLE,\n details: 'Connection dropped',\n metadata: new metadata_1.Metadata(),\n });\n };\n if (this.options.parentCall && this.options.flags & constants_1.Propagate.CANCELLATION) {\n this.options.parentCall.on('cancelled', () => {\n this.cancelWithStatus(constants_1.Status.CANCELLED, 'Cancelled by parent call');\n });\n }\n }\n outputStatus() {\n /* Precondition: this.finalStatus !== null */\n if (!this.statusOutput) {\n this.statusOutput = true;\n const filteredStatus = this.filterStack.receiveTrailers(this.finalStatus);\n /* We delay the actual action of bubbling up the status to insulate the\n * cleanup code in this class from any errors that may be thrown in the\n * upper layers as a result of bubbling up the status. In particular,\n * if the status is not OK, the \"error\" event may be emitted\n * synchronously at the top level, which will result in a thrown error if\n * the user does not handle that event. */\n process.nextTick(() => {\n var _a;\n (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onReceiveStatus(filteredStatus);\n });\n if (this.subchannel) {\n this.subchannel.callUnref();\n this.subchannel.removeDisconnectListener(this.disconnectListener);\n }\n }\n }\n trace(text) {\n logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, '[' + this.callNumber + '] ' + text);\n }\n /**\n * On first call, emits a 'status' event with the given StatusObject.\n * Subsequent calls are no-ops.\n * @param status The status of the call.\n */\n endCall(status) {\n /* If the status is OK and a new status comes in (e.g. from a\n * deserialization failure), that new status takes priority */\n if (this.finalStatus === null || this.finalStatus.code === constants_1.Status.OK) {\n this.trace('ended with status: code=' +\n status.code +\n ' details=\"' +\n status.details +\n '\"');\n this.finalStatus = status;\n this.maybeOutputStatus();\n }\n this.destroyHttp2Stream();\n }\n maybeOutputStatus() {\n if (this.finalStatus !== null) {\n /* The combination check of readsClosed and that the two message buffer\n * arrays are empty checks that there all incoming data has been fully\n * processed */\n if (this.finalStatus.code !== constants_1.Status.OK ||\n (this.readsClosed &&\n this.unpushedReadMessages.length === 0 &&\n this.unfilteredReadMessages.length === 0 &&\n !this.isReadFilterPending)) {\n this.outputStatus();\n }\n }\n }\n push(message) {\n this.trace('pushing to reader message of length ' +\n (message instanceof Buffer ? message.length : null));\n this.canPush = false;\n process.nextTick(() => {\n var _a;\n /* If we have already output the status any later messages should be\n * ignored, and can cause out-of-order operation errors higher up in the\n * stack. Checking as late as possible here to avoid any race conditions.\n */\n if (this.statusOutput) {\n return;\n }\n (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onReceiveMessage(message);\n this.maybeOutputStatus();\n });\n }\n handleFilterError(error) {\n this.cancelWithStatus(constants_1.Status.INTERNAL, error.message);\n }\n handleFilteredRead(message) {\n /* If we the call has already ended with an error, we don't want to do\n * anything with this message. Dropping it on the floor is correct\n * behavior */\n if (this.finalStatus !== null && this.finalStatus.code !== constants_1.Status.OK) {\n this.maybeOutputStatus();\n return;\n }\n this.isReadFilterPending = false;\n if (this.canPush) {\n this.http2Stream.pause();\n this.push(message);\n }\n else {\n this.trace('unpushedReadMessages.push message of length ' + message.length);\n this.unpushedReadMessages.push(message);\n }\n if (this.unfilteredReadMessages.length > 0) {\n /* nextMessage is guaranteed not to be undefined because\n unfilteredReadMessages is non-empty */\n const nextMessage = this.unfilteredReadMessages.shift();\n this.filterReceivedMessage(nextMessage);\n }\n }\n filterReceivedMessage(framedMessage) {\n /* If we the call has already ended with an error, we don't want to do\n * anything with this message. Dropping it on the floor is correct\n * behavior */\n if (this.finalStatus !== null && this.finalStatus.code !== constants_1.Status.OK) {\n this.maybeOutputStatus();\n return;\n }\n this.trace('filterReceivedMessage of length ' + framedMessage.length);\n this.isReadFilterPending = true;\n this.filterStack\n .receiveMessage(Promise.resolve(framedMessage))\n .then(this.handleFilteredRead.bind(this), this.handleFilterError.bind(this));\n }\n tryPush(messageBytes) {\n if (this.isReadFilterPending) {\n this.trace('unfilteredReadMessages.push message of length ' +\n (messageBytes && messageBytes.length));\n this.unfilteredReadMessages.push(messageBytes);\n }\n else {\n this.filterReceivedMessage(messageBytes);\n }\n }\n handleTrailers(headers) {\n let headersString = '';\n for (const header of Object.keys(headers)) {\n headersString += '\\t\\t' + header + ': ' + headers[header] + '\\n';\n }\n this.trace('Received server trailers:\\n' + headersString);\n let metadata;\n try {\n metadata = metadata_1.Metadata.fromHttp2Headers(headers);\n }\n catch (e) {\n metadata = new metadata_1.Metadata();\n }\n const metadataMap = metadata.getMap();\n let code = this.mappedStatusCode;\n if (code === constants_1.Status.UNKNOWN &&\n typeof metadataMap['grpc-status'] === 'string') {\n const receivedStatus = Number(metadataMap['grpc-status']);\n if (receivedStatus in constants_1.Status) {\n code = receivedStatus;\n this.trace('received status code ' + receivedStatus + ' from server');\n }\n metadata.remove('grpc-status');\n }\n let details = '';\n if (typeof metadataMap['grpc-message'] === 'string') {\n details = decodeURI(metadataMap['grpc-message']);\n metadata.remove('grpc-message');\n this.trace('received status details string \"' + details + '\" from server');\n }\n const status = { code, details, metadata };\n let finalStatus;\n try {\n // Attempt to assign final status.\n finalStatus = this.filterStack.receiveTrailers(status);\n }\n catch (error) {\n // This is a no-op if the call was already ended when handling headers.\n this.endCall({\n code: constants_1.Status.INTERNAL,\n details: 'Failed to process received status',\n metadata: new metadata_1.Metadata(),\n });\n return;\n }\n // This is a no-op if the call was already ended when handling headers.\n this.endCall(finalStatus);\n }\n attachHttp2Stream(stream, subchannel, extraFilterFactory) {\n if (extraFilterFactory !== undefined) {\n this.filterStack = new filter_stack_1.FilterStack([\n this.filterStack,\n extraFilterFactory.createFilter(this),\n ]);\n }\n if (this.finalStatus !== null) {\n stream.close(NGHTTP2_CANCEL);\n }\n else {\n this.trace('attachHttp2Stream from subchannel ' + subchannel.getAddress());\n this.http2Stream = stream;\n this.subchannel = subchannel;\n subchannel.addDisconnectListener(this.disconnectListener);\n subchannel.callRef();\n stream.on('response', (headers, flags) => {\n var _a;\n let headersString = '';\n for (const header of Object.keys(headers)) {\n headersString += '\\t\\t' + header + ': ' + headers[header] + '\\n';\n }\n this.trace('Received server headers:\\n' + headersString);\n switch (headers[':status']) {\n // TODO(murgatroid99): handle 100 and 101\n case 400:\n this.mappedStatusCode = constants_1.Status.INTERNAL;\n break;\n case 401:\n this.mappedStatusCode = constants_1.Status.UNAUTHENTICATED;\n break;\n case 403:\n this.mappedStatusCode = constants_1.Status.PERMISSION_DENIED;\n break;\n case 404:\n this.mappedStatusCode = constants_1.Status.UNIMPLEMENTED;\n break;\n case 429:\n case 502:\n case 503:\n case 504:\n this.mappedStatusCode = constants_1.Status.UNAVAILABLE;\n break;\n default:\n this.mappedStatusCode = constants_1.Status.UNKNOWN;\n }\n if (flags & http2.constants.NGHTTP2_FLAG_END_STREAM) {\n this.handleTrailers(headers);\n }\n else {\n let metadata;\n try {\n metadata = metadata_1.Metadata.fromHttp2Headers(headers);\n }\n catch (error) {\n this.endCall({\n code: constants_1.Status.UNKNOWN,\n details: error.message,\n metadata: new metadata_1.Metadata(),\n });\n return;\n }\n try {\n const finalMetadata = this.filterStack.receiveMetadata(metadata);\n (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onReceiveMetadata(finalMetadata);\n }\n catch (error) {\n this.endCall({\n code: constants_1.Status.UNKNOWN,\n details: error.message,\n metadata: new metadata_1.Metadata(),\n });\n }\n }\n });\n stream.on('trailers', this.handleTrailers.bind(this));\n stream.on('data', (data) => {\n this.trace('receive HTTP/2 data frame of length ' + data.length);\n const messages = this.decoder.write(data);\n for (const message of messages) {\n this.trace('parsed message of length ' + message.length);\n this.tryPush(message);\n }\n });\n stream.on('end', () => {\n this.readsClosed = true;\n this.maybeOutputStatus();\n });\n stream.on('close', () => {\n /* Use process.next tick to ensure that this code happens after any\n * \"error\" event that may be emitted at about the same time, so that\n * we can bubble up the error message from that event. */\n process.nextTick(() => {\n var _a;\n this.trace('HTTP/2 stream closed with code ' + stream.rstCode);\n /* If we have a final status with an OK status code, that means that\n * we have received all of the messages and we have processed the\n * trailers and the call completed successfully, so it doesn't matter\n * how the stream ends after that */\n if (((_a = this.finalStatus) === null || _a === void 0 ? void 0 : _a.code) === constants_1.Status.OK) {\n return;\n }\n let code;\n let details = '';\n switch (stream.rstCode) {\n case http2.constants.NGHTTP2_NO_ERROR:\n /* If we get a NO_ERROR code and we already have a status, the\n * stream completed properly and we just haven't fully processed\n * it yet */\n if (this.finalStatus !== null) {\n return;\n }\n code = constants_1.Status.INTERNAL;\n details = `Received RST_STREAM with code ${stream.rstCode}`;\n break;\n case http2.constants.NGHTTP2_REFUSED_STREAM:\n code = constants_1.Status.UNAVAILABLE;\n details = 'Stream refused by server';\n break;\n case http2.constants.NGHTTP2_CANCEL:\n code = constants_1.Status.CANCELLED;\n details = 'Call cancelled';\n break;\n case http2.constants.NGHTTP2_ENHANCE_YOUR_CALM:\n code = constants_1.Status.RESOURCE_EXHAUSTED;\n details = 'Bandwidth exhausted';\n break;\n case http2.constants.NGHTTP2_INADEQUATE_SECURITY:\n code = constants_1.Status.PERMISSION_DENIED;\n details = 'Protocol not secure enough';\n break;\n case http2.constants.NGHTTP2_INTERNAL_ERROR:\n code = constants_1.Status.INTERNAL;\n if (this.internalErrorMessage === null) {\n /* This error code was previously handled in the default case, and\n * there are several instances of it online, so I wanted to\n * preserve the original error message so that people find existing\n * information in searches, but also include the more recognizable\n * \"Internal server error\" message. */\n details = `Received RST_STREAM with code ${stream.rstCode} (Internal server error)`;\n }\n else {\n /* The \"Received RST_STREAM with code ...\" error is preserved\n * here for continuity with errors reported online, but the\n * error message at the end will probably be more relevant in\n * most cases. */\n details = `Received RST_STREAM with code ${stream.rstCode} triggered by internal client error: ${this.internalErrorMessage}`;\n }\n break;\n default:\n code = constants_1.Status.INTERNAL;\n details = `Received RST_STREAM with code ${stream.rstCode}`;\n }\n // This is a no-op if trailers were received at all.\n // This is OK, because status codes emitted here correspond to more\n // catastrophic issues that prevent us from receiving trailers in the\n // first place.\n this.endCall({ code, details, metadata: new metadata_1.Metadata() });\n });\n });\n stream.on('error', (err) => {\n /* We need an error handler here to stop \"Uncaught Error\" exceptions\n * from bubbling up. However, errors here should all correspond to\n * \"close\" events, where we will handle the error more granularly */\n /* Specifically looking for stream errors that were *not* constructed\n * from a RST_STREAM response here:\n * https://github.com/nodejs/node/blob/8b8620d580314050175983402dfddf2674e8e22a/lib/internal/http2/core.js#L2267\n */\n if (err.code !== 'ERR_HTTP2_STREAM_ERROR') {\n this.internalErrorMessage = err.message;\n }\n });\n if (!this.pendingRead) {\n stream.pause();\n }\n if (this.pendingWrite) {\n if (!this.pendingWriteCallback) {\n throw new Error('Invalid state in write handling code');\n }\n this.trace('sending data chunk of length ' +\n this.pendingWrite.length +\n ' (deferred)');\n stream.write(this.pendingWrite, this.pendingWriteCallback);\n }\n this.maybeCloseWrites();\n }\n }\n start(metadata, listener) {\n this.trace('Sending metadata');\n this.listener = listener;\n this.channel._startCallStream(this, metadata);\n }\n destroyHttp2Stream() {\n var _a;\n // The http2 stream could already have been destroyed if cancelWithStatus\n // is called in response to an internal http2 error.\n if (this.http2Stream !== null && !this.http2Stream.destroyed) {\n /* If the call has ended with an OK status, communicate that when closing\n * the stream, partly to avoid a situation in which we detect an error\n * RST_STREAM as a result after we have the status */\n let code;\n if (((_a = this.finalStatus) === null || _a === void 0 ? void 0 : _a.code) === constants_1.Status.OK) {\n code = http2.constants.NGHTTP2_NO_ERROR;\n }\n else {\n code = http2.constants.NGHTTP2_CANCEL;\n }\n this.trace('close http2 stream with code ' + code);\n this.http2Stream.close(code);\n }\n }\n cancelWithStatus(status, details) {\n this.trace('cancelWithStatus code: ' + status + ' details: \"' + details + '\"');\n this.endCall({ code: status, details, metadata: new metadata_1.Metadata() });\n }\n getDeadline() {\n if (this.options.parentCall && this.options.flags & constants_1.Propagate.DEADLINE) {\n const parentDeadline = this.options.parentCall.getDeadline();\n const selfDeadline = this.options.deadline;\n const parentDeadlineMsecs = parentDeadline instanceof Date ? parentDeadline.getTime() : parentDeadline;\n const selfDeadlineMsecs = selfDeadline instanceof Date ? selfDeadline.getTime() : selfDeadline;\n return Math.min(parentDeadlineMsecs, selfDeadlineMsecs);\n }\n else {\n return this.options.deadline;\n }\n }\n getCredentials() {\n return this.credentials;\n }\n setCredentials(credentials) {\n this.credentials = this.channelCallCredentials.compose(credentials);\n }\n getStatus() {\n return this.finalStatus;\n }\n getPeer() {\n var _a, _b;\n return (_b = (_a = this.subchannel) === null || _a === void 0 ? void 0 : _a.getAddress()) !== null && _b !== void 0 ? _b : this.channel.getTarget();\n }\n getMethod() {\n return this.methodName;\n }\n getHost() {\n return this.options.host;\n }\n startRead() {\n /* If the stream has ended with an error, we should not emit any more\n * messages and we should communicate that the stream has ended */\n if (this.finalStatus !== null && this.finalStatus.code !== constants_1.Status.OK) {\n this.readsClosed = true;\n this.maybeOutputStatus();\n return;\n }\n this.canPush = true;\n if (this.http2Stream === null) {\n this.pendingRead = true;\n }\n else {\n if (this.unpushedReadMessages.length > 0) {\n const nextMessage = this.unpushedReadMessages.shift();\n this.push(nextMessage);\n return;\n }\n /* Only resume reading from the http2Stream if we don't have any pending\n * messages to emit */\n this.http2Stream.resume();\n }\n }\n maybeCloseWrites() {\n if (this.writesClosed &&\n !this.isWriteFilterPending &&\n this.http2Stream !== null) {\n this.trace('calling end() on HTTP/2 stream');\n this.http2Stream.end();\n }\n }\n sendMessageWithContext(context, message) {\n var _a;\n this.trace('write() called with message of length ' + message.length);\n const writeObj = {\n message,\n flags: context.flags,\n };\n const cb = (_a = context.callback) !== null && _a !== void 0 ? _a : (() => { });\n this.isWriteFilterPending = true;\n this.filterStack.sendMessage(Promise.resolve(writeObj)).then((message) => {\n this.isWriteFilterPending = false;\n if (this.http2Stream === null) {\n this.trace('deferring writing data chunk of length ' + message.message.length);\n this.pendingWrite = message.message;\n this.pendingWriteCallback = cb;\n }\n else {\n this.trace('sending data chunk of length ' + message.message.length);\n this.http2Stream.write(message.message, cb);\n this.maybeCloseWrites();\n }\n }, this.handleFilterError.bind(this));\n }\n halfClose() {\n this.trace('end() called');\n this.writesClosed = true;\n this.maybeCloseWrites();\n }\n}\nexports.Http2CallStream = Http2CallStream;\n//# sourceMappingURL=call-stream.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ClientDuplexStreamImpl = exports.ClientWritableStreamImpl = exports.ClientReadableStreamImpl = exports.ClientUnaryCallImpl = exports.callErrorFromStatus = void 0;\nconst events_1 = require(\"events\");\nconst stream_1 = require(\"stream\");\nconst constants_1 = require(\"./constants\");\n/**\n * Construct a ServiceError from a StatusObject. This function exists primarily\n * as an attempt to make the error stack trace clearly communicate that the\n * error is not necessarily a problem in gRPC itself.\n * @param status\n */\nfunction callErrorFromStatus(status) {\n const message = `${status.code} ${constants_1.Status[status.code]}: ${status.details}`;\n return Object.assign(new Error(message), status);\n}\nexports.callErrorFromStatus = callErrorFromStatus;\nclass ClientUnaryCallImpl extends events_1.EventEmitter {\n constructor() {\n super();\n }\n cancel() {\n var _a;\n (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, 'Cancelled on client');\n }\n getPeer() {\n var _a, _b;\n return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : 'unknown';\n }\n}\nexports.ClientUnaryCallImpl = ClientUnaryCallImpl;\nclass ClientReadableStreamImpl extends stream_1.Readable {\n constructor(deserialize) {\n super({ objectMode: true });\n this.deserialize = deserialize;\n }\n cancel() {\n var _a;\n (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, 'Cancelled on client');\n }\n getPeer() {\n var _a, _b;\n return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : 'unknown';\n }\n _read(_size) {\n var _a;\n (_a = this.call) === null || _a === void 0 ? void 0 : _a.startRead();\n }\n}\nexports.ClientReadableStreamImpl = ClientReadableStreamImpl;\nclass ClientWritableStreamImpl extends stream_1.Writable {\n constructor(serialize) {\n super({ objectMode: true });\n this.serialize = serialize;\n }\n cancel() {\n var _a;\n (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, 'Cancelled on client');\n }\n getPeer() {\n var _a, _b;\n return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : 'unknown';\n }\n _write(chunk, encoding, cb) {\n var _a;\n const context = {\n callback: cb,\n };\n const flags = Number(encoding);\n if (!Number.isNaN(flags)) {\n context.flags = flags;\n }\n (_a = this.call) === null || _a === void 0 ? void 0 : _a.sendMessageWithContext(context, chunk);\n }\n _final(cb) {\n var _a;\n (_a = this.call) === null || _a === void 0 ? void 0 : _a.halfClose();\n cb();\n }\n}\nexports.ClientWritableStreamImpl = ClientWritableStreamImpl;\nclass ClientDuplexStreamImpl extends stream_1.Duplex {\n constructor(serialize, deserialize) {\n super({ objectMode: true });\n this.serialize = serialize;\n this.deserialize = deserialize;\n }\n cancel() {\n var _a;\n (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, 'Cancelled on client');\n }\n getPeer() {\n var _a, _b;\n return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : 'unknown';\n }\n _read(_size) {\n var _a;\n (_a = this.call) === null || _a === void 0 ? void 0 : _a.startRead();\n }\n _write(chunk, encoding, cb) {\n var _a;\n const context = {\n callback: cb,\n };\n const flags = Number(encoding);\n if (!Number.isNaN(flags)) {\n context.flags = flags;\n }\n (_a = this.call) === null || _a === void 0 ? void 0 : _a.sendMessageWithContext(context, chunk);\n }\n _final(cb) {\n var _a;\n (_a = this.call) === null || _a === void 0 ? void 0 : _a.halfClose();\n cb();\n }\n}\nexports.ClientDuplexStreamImpl = ClientDuplexStreamImpl;\n//# sourceMappingURL=call.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.createGoogleDefaultCredentials = exports.ChannelCredentials = void 0;\nconst tls_1 = require(\"tls\");\nconst call_credentials_1 = require(\"./call-credentials\");\nconst tls_helpers_1 = require(\"./tls-helpers\");\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction verifyIsBufferOrNull(obj, friendlyName) {\n if (obj && !(obj instanceof Buffer)) {\n throw new TypeError(`${friendlyName}, if provided, must be a Buffer.`);\n }\n}\nfunction bufferOrNullEqual(buf1, buf2) {\n if (buf1 === null && buf2 === null) {\n return true;\n }\n else {\n return buf1 !== null && buf2 !== null && buf1.equals(buf2);\n }\n}\n/**\n * A class that contains credentials for communicating over a channel, as well\n * as a set of per-call credentials, which are applied to every method call made\n * over a channel initialized with an instance of this class.\n */\nclass ChannelCredentials {\n constructor(callCredentials) {\n this.callCredentials = callCredentials || call_credentials_1.CallCredentials.createEmpty();\n }\n /**\n * Gets the set of per-call credentials associated with this instance.\n */\n _getCallCredentials() {\n return this.callCredentials;\n }\n /**\n * Return a new ChannelCredentials instance with a given set of credentials.\n * The resulting instance can be used to construct a Channel that communicates\n * over TLS.\n * @param rootCerts The root certificate data.\n * @param privateKey The client certificate private key, if available.\n * @param certChain The client certificate key chain, if available.\n */\n static createSsl(rootCerts, privateKey, certChain, verifyOptions) {\n verifyIsBufferOrNull(rootCerts, 'Root certificate');\n verifyIsBufferOrNull(privateKey, 'Private key');\n verifyIsBufferOrNull(certChain, 'Certificate chain');\n if (privateKey && !certChain) {\n throw new Error('Private key must be given with accompanying certificate chain');\n }\n if (!privateKey && certChain) {\n throw new Error('Certificate chain must be given with accompanying private key');\n }\n return new SecureChannelCredentialsImpl(rootCerts || tls_helpers_1.getDefaultRootsData(), privateKey || null, certChain || null, verifyOptions || {});\n }\n /**\n * Return a new ChannelCredentials instance with no credentials.\n */\n static createInsecure() {\n return new InsecureChannelCredentialsImpl();\n }\n}\nexports.ChannelCredentials = ChannelCredentials;\nclass InsecureChannelCredentialsImpl extends ChannelCredentials {\n constructor(callCredentials) {\n super(callCredentials);\n }\n compose(callCredentials) {\n throw new Error('Cannot compose insecure credentials');\n }\n _getConnectionOptions() {\n return null;\n }\n _isSecure() {\n return false;\n }\n _equals(other) {\n return other instanceof InsecureChannelCredentialsImpl;\n }\n}\nclass SecureChannelCredentialsImpl extends ChannelCredentials {\n constructor(rootCerts, privateKey, certChain, verifyOptions) {\n super();\n this.rootCerts = rootCerts;\n this.privateKey = privateKey;\n this.certChain = certChain;\n this.verifyOptions = verifyOptions;\n const secureContext = tls_1.createSecureContext({\n ca: rootCerts || undefined,\n key: privateKey || undefined,\n cert: certChain || undefined,\n ciphers: tls_helpers_1.CIPHER_SUITES,\n });\n this.connectionOptions = { secureContext };\n if (verifyOptions && verifyOptions.checkServerIdentity) {\n this.connectionOptions.checkServerIdentity = (host, cert) => {\n return verifyOptions.checkServerIdentity(host, { raw: cert.raw });\n };\n }\n }\n compose(callCredentials) {\n const combinedCallCredentials = this.callCredentials.compose(callCredentials);\n return new ComposedChannelCredentialsImpl(this, combinedCallCredentials);\n }\n _getConnectionOptions() {\n // Copy to prevent callers from mutating this.connectionOptions\n return Object.assign({}, this.connectionOptions);\n }\n _isSecure() {\n return true;\n }\n _equals(other) {\n if (this === other) {\n return true;\n }\n if (other instanceof SecureChannelCredentialsImpl) {\n if (!bufferOrNullEqual(this.rootCerts, other.rootCerts)) {\n return false;\n }\n if (!bufferOrNullEqual(this.privateKey, other.privateKey)) {\n return false;\n }\n if (!bufferOrNullEqual(this.certChain, other.certChain)) {\n return false;\n }\n return (this.verifyOptions.checkServerIdentity ===\n other.verifyOptions.checkServerIdentity);\n }\n else {\n return false;\n }\n }\n}\nclass ComposedChannelCredentialsImpl extends ChannelCredentials {\n constructor(channelCredentials, callCreds) {\n super(callCreds);\n this.channelCredentials = channelCredentials;\n }\n compose(callCredentials) {\n const combinedCallCredentials = this.callCredentials.compose(callCredentials);\n return new ComposedChannelCredentialsImpl(this.channelCredentials, combinedCallCredentials);\n }\n _getConnectionOptions() {\n return this.channelCredentials._getConnectionOptions();\n }\n _isSecure() {\n return true;\n }\n _equals(other) {\n if (this === other) {\n return true;\n }\n if (other instanceof ComposedChannelCredentialsImpl) {\n return (this.channelCredentials._equals(other.channelCredentials) &&\n this.callCredentials._equals(other.callCredentials));\n }\n else {\n return false;\n }\n }\n}\nfunction createGoogleDefaultCredentials() {\n const GoogleAuth = require('google-auth-library')\n .GoogleAuth;\n const sslCreds = ChannelCredentials.createSsl();\n const googleAuthCreds = call_credentials_1.CallCredentials.createFromGoogleCredential(new GoogleAuth());\n return sslCreds.compose(googleAuthCreds);\n}\nexports.createGoogleDefaultCredentials = createGoogleDefaultCredentials;\n//# sourceMappingURL=channel-credentials.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.channelOptionsEqual = exports.recognizedOptions = void 0;\n/**\n * This is for checking provided options at runtime. This is an object for\n * easier membership checking.\n */\nexports.recognizedOptions = {\n 'grpc.ssl_target_name_override': true,\n 'grpc.primary_user_agent': true,\n 'grpc.secondary_user_agent': true,\n 'grpc.default_authority': true,\n 'grpc.keepalive_time_ms': true,\n 'grpc.keepalive_timeout_ms': true,\n 'grpc.keepalive_permit_without_calls': true,\n 'grpc.service_config': true,\n 'grpc.max_concurrent_streams': true,\n 'grpc.initial_reconnect_backoff_ms': true,\n 'grpc.max_reconnect_backoff_ms': true,\n 'grpc.use_local_subchannel_pool': true,\n 'grpc.max_send_message_length': true,\n 'grpc.max_receive_message_length': true,\n 'grpc.enable_http_proxy': true,\n};\nfunction channelOptionsEqual(options1, options2) {\n const keys1 = Object.keys(options1).sort();\n const keys2 = Object.keys(options2).sort();\n if (keys1.length !== keys2.length) {\n return false;\n }\n for (let i = 0; i < keys1.length; i += 1) {\n if (keys1[i] !== keys2[i]) {\n return false;\n }\n if (options1[keys1[i]] !== options2[keys2[i]]) {\n return false;\n }\n }\n return true;\n}\nexports.channelOptionsEqual = channelOptionsEqual;\n//# sourceMappingURL=channel-options.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ChannelImplementation = exports.ConnectivityState = void 0;\nconst call_stream_1 = require(\"./call-stream\");\nconst channel_credentials_1 = require(\"./channel-credentials\");\nconst resolving_load_balancer_1 = require(\"./resolving-load-balancer\");\nconst subchannel_pool_1 = require(\"./subchannel-pool\");\nconst picker_1 = require(\"./picker\");\nconst constants_1 = require(\"./constants\");\nconst filter_stack_1 = require(\"./filter-stack\");\nconst call_credentials_filter_1 = require(\"./call-credentials-filter\");\nconst deadline_filter_1 = require(\"./deadline-filter\");\nconst compression_filter_1 = require(\"./compression-filter\");\nconst resolver_1 = require(\"./resolver\");\nconst logging_1 = require(\"./logging\");\nconst max_message_size_filter_1 = require(\"./max-message-size-filter\");\nconst http_proxy_1 = require(\"./http_proxy\");\nconst uri_parser_1 = require(\"./uri-parser\");\nvar ConnectivityState;\n(function (ConnectivityState) {\n ConnectivityState[ConnectivityState[\"IDLE\"] = 0] = \"IDLE\";\n ConnectivityState[ConnectivityState[\"CONNECTING\"] = 1] = \"CONNECTING\";\n ConnectivityState[ConnectivityState[\"READY\"] = 2] = \"READY\";\n ConnectivityState[ConnectivityState[\"TRANSIENT_FAILURE\"] = 3] = \"TRANSIENT_FAILURE\";\n ConnectivityState[ConnectivityState[\"SHUTDOWN\"] = 4] = \"SHUTDOWN\";\n})(ConnectivityState = exports.ConnectivityState || (exports.ConnectivityState = {}));\n/**\n * See https://nodejs.org/api/timers.html#timers_setinterval_callback_delay_args\n */\nconst MAX_TIMEOUT_TIME = 2147483647;\nlet nextCallNumber = 0;\nfunction getNewCallNumber() {\n const callNumber = nextCallNumber;\n nextCallNumber += 1;\n if (nextCallNumber >= Number.MAX_SAFE_INTEGER) {\n nextCallNumber = 0;\n }\n return callNumber;\n}\nclass ChannelImplementation {\n constructor(target, credentials, options) {\n var _a, _b, _c;\n this.credentials = credentials;\n this.options = options;\n this.connectivityState = ConnectivityState.IDLE;\n this.currentPicker = new picker_1.UnavailablePicker();\n this.pickQueue = [];\n this.connectivityStateWatchers = [];\n if (typeof target !== 'string') {\n throw new TypeError('Channel target must be a string');\n }\n if (!(credentials instanceof channel_credentials_1.ChannelCredentials)) {\n throw new TypeError('Channel credentials must be a ChannelCredentials object');\n }\n if (options) {\n if (typeof options !== 'object' ||\n !Object.values(options).every((value) => typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'undefined')) {\n throw new TypeError('Channel options must be an object with string or number values');\n }\n }\n const originalTargetUri = uri_parser_1.parseUri(target);\n if (originalTargetUri === null) {\n throw new Error(`Could not parse target name \"${target}\"`);\n }\n /* This ensures that the target has a scheme that is registered with the\n * resolver */\n const defaultSchemeMapResult = resolver_1.mapUriDefaultScheme(originalTargetUri);\n if (defaultSchemeMapResult === null) {\n throw new Error(`Could not find a default scheme for target name \"${target}\"`);\n }\n this.callRefTimer = setInterval(() => { }, MAX_TIMEOUT_TIME);\n (_b = (_a = this.callRefTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a);\n if (this.options['grpc.default_authority']) {\n this.defaultAuthority = this.options['grpc.default_authority'];\n }\n else {\n this.defaultAuthority = resolver_1.getDefaultAuthority(defaultSchemeMapResult);\n }\n const proxyMapResult = http_proxy_1.mapProxyName(defaultSchemeMapResult, options);\n this.target = proxyMapResult.target;\n this.options = Object.assign({}, this.options, proxyMapResult.extraOptions);\n /* The global boolean parameter to getSubchannelPool has the inverse meaning to what\n * the grpc.use_local_subchannel_pool channel option means. */\n this.subchannelPool = subchannel_pool_1.getSubchannelPool(((_c = options['grpc.use_local_subchannel_pool']) !== null && _c !== void 0 ? _c : 0) === 0);\n const channelControlHelper = {\n createSubchannel: (subchannelAddress, subchannelArgs) => {\n return this.subchannelPool.getOrCreateSubchannel(this.target, subchannelAddress, Object.assign({}, this.options, subchannelArgs), this.credentials);\n },\n updateState: (connectivityState, picker) => {\n var _a, _b;\n this.currentPicker = picker;\n const queueCopy = this.pickQueue.slice();\n (_b = (_a = this.callRefTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a);\n this.pickQueue = [];\n for (const { callStream, callMetadata } of queueCopy) {\n this.tryPick(callStream, callMetadata);\n }\n this.updateState(connectivityState);\n },\n requestReresolution: () => {\n // This should never be called.\n throw new Error('Resolving load balancer should never call requestReresolution');\n },\n };\n this.resolvingLoadBalancer = new resolving_load_balancer_1.ResolvingLoadBalancer(this.target, channelControlHelper, options);\n this.filterStackFactory = new filter_stack_1.FilterStackFactory([\n new call_credentials_filter_1.CallCredentialsFilterFactory(this),\n new deadline_filter_1.DeadlineFilterFactory(this),\n new max_message_size_filter_1.MaxMessageSizeFilterFactory(this.options),\n new compression_filter_1.CompressionFilterFactory(this),\n ]);\n }\n pushPick(callStream, callMetadata) {\n var _a, _b;\n (_b = (_a = this.callRefTimer).ref) === null || _b === void 0 ? void 0 : _b.call(_a);\n this.pickQueue.push({ callStream, callMetadata });\n }\n /**\n * Check the picker output for the given call and corresponding metadata,\n * and take any relevant actions. Should not be called while iterating\n * over pickQueue.\n * @param callStream\n * @param callMetadata\n */\n tryPick(callStream, callMetadata) {\n var _a, _b, _c;\n const pickResult = this.currentPicker.pick({ metadata: callMetadata });\n logging_1.trace(constants_1.LogVerbosity.DEBUG, 'channel', 'Pick result: ' +\n picker_1.PickResultType[pickResult.pickResultType] +\n ' subchannel: ' + ((_a = pickResult.subchannel) === null || _a === void 0 ? void 0 : _a.getAddress()) +\n ' status: ' + ((_b = pickResult.status) === null || _b === void 0 ? void 0 : _b.code) +\n ' ' + ((_c = pickResult.status) === null || _c === void 0 ? void 0 : _c.details));\n switch (pickResult.pickResultType) {\n case picker_1.PickResultType.COMPLETE:\n if (pickResult.subchannel === null) {\n callStream.cancelWithStatus(constants_1.Status.UNAVAILABLE, 'Request dropped by load balancing policy');\n // End the call with an error\n }\n else {\n /* If the subchannel is not in the READY state, that indicates a bug\n * somewhere in the load balancer or picker. So, we log an error and\n * queue the pick to be tried again later. */\n if (pickResult.subchannel.getConnectivityState() !==\n ConnectivityState.READY) {\n logging_1.log(constants_1.LogVerbosity.ERROR, 'Error: COMPLETE pick result subchannel ' +\n pickResult.subchannel.getAddress() +\n ' has state ' +\n ConnectivityState[pickResult.subchannel.getConnectivityState()]);\n this.pushPick(callStream, callMetadata);\n break;\n }\n /* We need to clone the callMetadata here because the transparent\n * retry code in the promise resolution handler use the same\n * callMetadata object, so it needs to stay unmodified */\n callStream.filterStack\n .sendMetadata(Promise.resolve(callMetadata.clone()))\n .then((finalMetadata) => {\n var _a, _b;\n const subchannelState = pickResult.subchannel.getConnectivityState();\n if (subchannelState === ConnectivityState.READY) {\n try {\n pickResult.subchannel.startCallStream(finalMetadata, callStream, (_a = pickResult.extraFilterFactory) !== null && _a !== void 0 ? _a : undefined);\n /* If we reach this point, the call stream has started\n * successfully */\n (_b = pickResult.onCallStarted) === null || _b === void 0 ? void 0 : _b.call(pickResult);\n }\n catch (error) {\n if (error.code ===\n 'ERR_HTTP2_GOAWAY_SESSION') {\n /* An error here indicates that something went wrong with\n * the picked subchannel's http2 stream right before we\n * tried to start the stream. We are handling a promise\n * result here, so this is asynchronous with respect to the\n * original tryPick call, so calling it again is not\n * recursive. We call tryPick immediately instead of\n * queueing this pick again because handling the queue is\n * triggered by state changes, and we want to immediately\n * check if the state has already changed since the\n * previous tryPick call. We do this instead of cancelling\n * the stream because the correct behavior may be\n * re-queueing instead, based on the logic in the rest of\n * tryPick */\n logging_1.trace(constants_1.LogVerbosity.INFO, 'channel', 'Failed to start call on picked subchannel ' +\n pickResult.subchannel.getAddress() +\n ' with error ' +\n error.message +\n '. Retrying pick');\n this.tryPick(callStream, callMetadata);\n }\n else {\n logging_1.trace(constants_1.LogVerbosity.INFO, 'channel', 'Failed to start call on picked subchanel ' +\n pickResult.subchannel.getAddress() +\n ' with error ' +\n error.message +\n '. Ending call');\n callStream.cancelWithStatus(constants_1.Status.INTERNAL, `Failed to start HTTP/2 stream with error: ${error.message}`);\n }\n }\n }\n else {\n /* The logic for doing this here is the same as in the catch\n * block above */\n logging_1.trace(constants_1.LogVerbosity.INFO, 'channel', 'Picked subchannel ' +\n pickResult.subchannel.getAddress() +\n ' has state ' +\n ConnectivityState[subchannelState] +\n ' after metadata filters. Retrying pick');\n this.tryPick(callStream, callMetadata);\n }\n }, (error) => {\n // We assume the error code isn't 0 (Status.OK)\n callStream.cancelWithStatus((typeof error.code === 'number') ? error.code : constants_1.Status.UNKNOWN, `Getting metadata from plugin failed with error: ${error.message}`);\n });\n }\n break;\n case picker_1.PickResultType.QUEUE:\n this.pushPick(callStream, callMetadata);\n break;\n case picker_1.PickResultType.TRANSIENT_FAILURE:\n if (callMetadata.getOptions().waitForReady) {\n this.pushPick(callStream, callMetadata);\n }\n else {\n callStream.cancelWithStatus(pickResult.status.code, pickResult.status.details);\n }\n break;\n case picker_1.PickResultType.DROP:\n callStream.cancelWithStatus(pickResult.status.code, pickResult.status.details);\n break;\n default:\n throw new Error(`Invalid state: unknown pickResultType ${pickResult.pickResultType}`);\n }\n }\n removeConnectivityStateWatcher(watcherObject) {\n const watcherIndex = this.connectivityStateWatchers.findIndex((value) => value === watcherObject);\n if (watcherIndex >= 0) {\n this.connectivityStateWatchers.splice(watcherIndex, 1);\n }\n }\n updateState(newState) {\n logging_1.trace(constants_1.LogVerbosity.DEBUG, 'connectivity_state', uri_parser_1.uriToString(this.target) +\n ' ' +\n ConnectivityState[this.connectivityState] +\n ' -> ' +\n ConnectivityState[newState]);\n this.connectivityState = newState;\n const watchersCopy = this.connectivityStateWatchers.slice();\n for (const watcherObject of watchersCopy) {\n if (newState !== watcherObject.currentState) {\n if (watcherObject.timer) {\n clearTimeout(watcherObject.timer);\n }\n this.removeConnectivityStateWatcher(watcherObject);\n watcherObject.callback();\n }\n }\n }\n _startCallStream(stream, metadata) {\n this.tryPick(stream, metadata.clone());\n }\n close() {\n this.resolvingLoadBalancer.destroy();\n this.updateState(ConnectivityState.SHUTDOWN);\n clearInterval(this.callRefTimer);\n this.subchannelPool.unrefUnusedSubchannels();\n }\n getTarget() {\n return uri_parser_1.uriToString(this.target);\n }\n getConnectivityState(tryToConnect) {\n const connectivityState = this.connectivityState;\n if (tryToConnect) {\n this.resolvingLoadBalancer.exitIdle();\n }\n return connectivityState;\n }\n watchConnectivityState(currentState, deadline, callback) {\n let timer = null;\n if (deadline !== Infinity) {\n const deadlineDate = deadline instanceof Date ? deadline : new Date(deadline);\n const now = new Date();\n if (deadline === -Infinity || deadlineDate <= now) {\n process.nextTick(callback, new Error('Deadline passed without connectivity state change'));\n return;\n }\n timer = setTimeout(() => {\n this.removeConnectivityStateWatcher(watcherObject);\n callback(new Error('Deadline passed without connectivity state change'));\n }, deadlineDate.getTime() - now.getTime());\n }\n const watcherObject = {\n currentState,\n callback,\n timer\n };\n this.connectivityStateWatchers.push(watcherObject);\n }\n createCall(method, deadline, host, parentCall, propagateFlags) {\n if (typeof method !== 'string') {\n throw new TypeError('Channel#createCall: method must be a string');\n }\n if (!(typeof deadline === 'number' || deadline instanceof Date)) {\n throw new TypeError('Channel#createCall: deadline must be a number or Date');\n }\n if (this.connectivityState === ConnectivityState.SHUTDOWN) {\n throw new Error('Channel has been shut down');\n }\n const callNumber = getNewCallNumber();\n logging_1.trace(constants_1.LogVerbosity.DEBUG, 'channel', uri_parser_1.uriToString(this.target) +\n ' createCall [' +\n callNumber +\n '] method=\"' +\n method +\n '\", deadline=' +\n deadline);\n const finalOptions = {\n deadline: deadline,\n flags: propagateFlags !== null && propagateFlags !== void 0 ? propagateFlags : constants_1.Propagate.DEFAULTS,\n host: host !== null && host !== void 0 ? host : this.defaultAuthority,\n parentCall: parentCall,\n };\n const stream = new call_stream_1.Http2CallStream(method, this, finalOptions, this.filterStackFactory, this.credentials._getCallCredentials(), callNumber);\n return stream;\n }\n}\nexports.ChannelImplementation = ChannelImplementation;\n//# sourceMappingURL=channel.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getInterceptingCall = exports.InterceptingCall = exports.RequesterBuilder = exports.ListenerBuilder = exports.InterceptorConfigurationError = void 0;\nconst metadata_1 = require(\"./metadata\");\nconst call_stream_1 = require(\"./call-stream\");\nconst constants_1 = require(\"./constants\");\n/**\n * Error class associated with passing both interceptors and interceptor\n * providers to a client constructor or as call options.\n */\nclass InterceptorConfigurationError extends Error {\n constructor(message) {\n super(message);\n this.name = 'InterceptorConfigurationError';\n Error.captureStackTrace(this, InterceptorConfigurationError);\n }\n}\nexports.InterceptorConfigurationError = InterceptorConfigurationError;\nclass ListenerBuilder {\n constructor() {\n this.metadata = undefined;\n this.message = undefined;\n this.status = undefined;\n }\n withOnReceiveMetadata(onReceiveMetadata) {\n this.metadata = onReceiveMetadata;\n return this;\n }\n withOnReceiveMessage(onReceiveMessage) {\n this.message = onReceiveMessage;\n return this;\n }\n withOnReceiveStatus(onReceiveStatus) {\n this.status = onReceiveStatus;\n return this;\n }\n build() {\n return {\n onReceiveMetadata: this.metadata,\n onReceiveMessage: this.message,\n onReceiveStatus: this.status,\n };\n }\n}\nexports.ListenerBuilder = ListenerBuilder;\nclass RequesterBuilder {\n constructor() {\n this.start = undefined;\n this.message = undefined;\n this.halfClose = undefined;\n this.cancel = undefined;\n }\n withStart(start) {\n this.start = start;\n return this;\n }\n withSendMessage(sendMessage) {\n this.message = sendMessage;\n return this;\n }\n withHalfClose(halfClose) {\n this.halfClose = halfClose;\n return this;\n }\n withCancel(cancel) {\n this.cancel = cancel;\n return this;\n }\n build() {\n return {\n start: this.start,\n sendMessage: this.message,\n halfClose: this.halfClose,\n cancel: this.cancel,\n };\n }\n}\nexports.RequesterBuilder = RequesterBuilder;\n/**\n * A Listener with a default pass-through implementation of each method. Used\n * for filling out Listeners with some methods omitted.\n */\nconst defaultListener = {\n onReceiveMetadata: (metadata, next) => {\n next(metadata);\n },\n onReceiveMessage: (message, next) => {\n next(message);\n },\n onReceiveStatus: (status, next) => {\n next(status);\n },\n};\n/**\n * A Requester with a default pass-through implementation of each method. Used\n * for filling out Requesters with some methods omitted.\n */\nconst defaultRequester = {\n start: (metadata, listener, next) => {\n next(metadata, listener);\n },\n sendMessage: (message, next) => {\n next(message);\n },\n halfClose: (next) => {\n next();\n },\n cancel: (next) => {\n next();\n },\n};\nclass InterceptingCall {\n constructor(nextCall, requester) {\n var _a, _b, _c, _d;\n this.nextCall = nextCall;\n /**\n * Indicates that a message has been passed to the listener's onReceiveMessage\n * method it has not been passed to the corresponding next callback\n */\n this.processingMessage = false;\n /**\n * Indicates that a status was received but could not be propagated because\n * a message was still being processed.\n */\n this.pendingHalfClose = false;\n if (requester) {\n this.requester = {\n start: (_a = requester.start) !== null && _a !== void 0 ? _a : defaultRequester.start,\n sendMessage: (_b = requester.sendMessage) !== null && _b !== void 0 ? _b : defaultRequester.sendMessage,\n halfClose: (_c = requester.halfClose) !== null && _c !== void 0 ? _c : defaultRequester.halfClose,\n cancel: (_d = requester.cancel) !== null && _d !== void 0 ? _d : defaultRequester.cancel,\n };\n }\n else {\n this.requester = defaultRequester;\n }\n }\n cancelWithStatus(status, details) {\n this.requester.cancel(() => {\n this.nextCall.cancelWithStatus(status, details);\n });\n }\n getPeer() {\n return this.nextCall.getPeer();\n }\n start(metadata, interceptingListener) {\n var _a, _b, _c, _d, _e, _f;\n const fullInterceptingListener = {\n onReceiveMetadata: (_b = (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMetadata) === null || _a === void 0 ? void 0 : _a.bind(interceptingListener)) !== null && _b !== void 0 ? _b : ((metadata) => { }),\n onReceiveMessage: (_d = (_c = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMessage) === null || _c === void 0 ? void 0 : _c.bind(interceptingListener)) !== null && _d !== void 0 ? _d : ((message) => { }),\n onReceiveStatus: (_f = (_e = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveStatus) === null || _e === void 0 ? void 0 : _e.bind(interceptingListener)) !== null && _f !== void 0 ? _f : ((status) => { }),\n };\n this.requester.start(metadata, fullInterceptingListener, (md, listener) => {\n var _a, _b, _c;\n let finalInterceptingListener;\n if (call_stream_1.isInterceptingListener(listener)) {\n finalInterceptingListener = listener;\n }\n else {\n const fullListener = {\n onReceiveMetadata: (_a = listener.onReceiveMetadata) !== null && _a !== void 0 ? _a : defaultListener.onReceiveMetadata,\n onReceiveMessage: (_b = listener.onReceiveMessage) !== null && _b !== void 0 ? _b : defaultListener.onReceiveMessage,\n onReceiveStatus: (_c = listener.onReceiveStatus) !== null && _c !== void 0 ? _c : defaultListener.onReceiveStatus,\n };\n finalInterceptingListener = new call_stream_1.InterceptingListenerImpl(fullListener, fullInterceptingListener);\n }\n this.nextCall.start(md, finalInterceptingListener);\n });\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n sendMessageWithContext(context, message) {\n this.processingMessage = true;\n this.requester.sendMessage(message, (finalMessage) => {\n this.processingMessage = false;\n this.nextCall.sendMessageWithContext(context, finalMessage);\n if (this.pendingHalfClose) {\n this.nextCall.halfClose();\n }\n });\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n sendMessage(message) {\n this.sendMessageWithContext({}, message);\n }\n startRead() {\n this.nextCall.startRead();\n }\n halfClose() {\n this.requester.halfClose(() => {\n if (this.processingMessage) {\n this.pendingHalfClose = true;\n }\n else {\n this.nextCall.halfClose();\n }\n });\n }\n setCredentials(credentials) {\n this.nextCall.setCredentials(credentials);\n }\n}\nexports.InterceptingCall = InterceptingCall;\nfunction getCall(channel, path, options) {\n var _a, _b;\n const deadline = (_a = options.deadline) !== null && _a !== void 0 ? _a : Infinity;\n const host = options.host;\n const parent = (_b = options.parent) !== null && _b !== void 0 ? _b : null;\n const propagateFlags = options.propagate_flags;\n const credentials = options.credentials;\n const call = channel.createCall(path, deadline, host, parent, propagateFlags);\n if (credentials) {\n call.setCredentials(credentials);\n }\n return call;\n}\n/**\n * InterceptingCall implementation that directly owns the underlying Call\n * object and handles serialization and deseraizliation.\n */\nclass BaseInterceptingCall {\n constructor(call, \n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n methodDefinition) {\n this.call = call;\n this.methodDefinition = methodDefinition;\n }\n cancelWithStatus(status, details) {\n this.call.cancelWithStatus(status, details);\n }\n getPeer() {\n return this.call.getPeer();\n }\n setCredentials(credentials) {\n this.call.setCredentials(credentials);\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n sendMessageWithContext(context, message) {\n let serialized;\n try {\n serialized = this.methodDefinition.requestSerialize(message);\n }\n catch (e) {\n this.call.cancelWithStatus(constants_1.Status.INTERNAL, `Request message serialization failure: ${e.message}`);\n return;\n }\n this.call.sendMessageWithContext(context, serialized);\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n sendMessage(message) {\n this.sendMessageWithContext({}, message);\n }\n start(metadata, interceptingListener) {\n let readError = null;\n this.call.start(metadata, {\n onReceiveMetadata: (metadata) => {\n var _a;\n (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMetadata) === null || _a === void 0 ? void 0 : _a.call(interceptingListener, metadata);\n },\n onReceiveMessage: (message) => {\n var _a;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let deserialized;\n try {\n deserialized = this.methodDefinition.responseDeserialize(message);\n }\n catch (e) {\n readError = {\n code: constants_1.Status.INTERNAL,\n details: `Response message parsing error: ${e.message}`,\n metadata: new metadata_1.Metadata(),\n };\n this.call.cancelWithStatus(readError.code, readError.details);\n return;\n }\n (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMessage) === null || _a === void 0 ? void 0 : _a.call(interceptingListener, deserialized);\n },\n onReceiveStatus: (status) => {\n var _a, _b;\n if (readError) {\n (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveStatus) === null || _a === void 0 ? void 0 : _a.call(interceptingListener, readError);\n }\n else {\n (_b = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveStatus) === null || _b === void 0 ? void 0 : _b.call(interceptingListener, status);\n }\n },\n });\n }\n startRead() {\n this.call.startRead();\n }\n halfClose() {\n this.call.halfClose();\n }\n}\n/**\n * BaseInterceptingCall with special-cased behavior for methods with unary\n * responses.\n */\nclass BaseUnaryInterceptingCall extends BaseInterceptingCall {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor(call, methodDefinition) {\n super(call, methodDefinition);\n }\n start(metadata, listener) {\n var _a, _b;\n let receivedMessage = false;\n const wrapperListener = {\n onReceiveMetadata: (_b = (_a = listener === null || listener === void 0 ? void 0 : listener.onReceiveMetadata) === null || _a === void 0 ? void 0 : _a.bind(listener)) !== null && _b !== void 0 ? _b : ((metadata) => { }),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n onReceiveMessage: (message) => {\n var _a;\n receivedMessage = true;\n (_a = listener === null || listener === void 0 ? void 0 : listener.onReceiveMessage) === null || _a === void 0 ? void 0 : _a.call(listener, message);\n },\n onReceiveStatus: (status) => {\n var _a, _b;\n if (!receivedMessage) {\n (_a = listener === null || listener === void 0 ? void 0 : listener.onReceiveMessage) === null || _a === void 0 ? void 0 : _a.call(listener, null);\n }\n (_b = listener === null || listener === void 0 ? void 0 : listener.onReceiveStatus) === null || _b === void 0 ? void 0 : _b.call(listener, status);\n },\n };\n super.start(metadata, wrapperListener);\n this.call.startRead();\n }\n}\n/**\n * BaseInterceptingCall with special-cased behavior for methods with streaming\n * responses.\n */\nclass BaseStreamingInterceptingCall extends BaseInterceptingCall {\n}\nfunction getBottomInterceptingCall(channel, options, \n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nmethodDefinition) {\n const call = getCall(channel, methodDefinition.path, options);\n if (methodDefinition.responseStream) {\n return new BaseStreamingInterceptingCall(call, methodDefinition);\n }\n else {\n return new BaseUnaryInterceptingCall(call, methodDefinition);\n }\n}\nfunction getInterceptingCall(interceptorArgs, \n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nmethodDefinition, options, channel) {\n if (interceptorArgs.clientInterceptors.length > 0 &&\n interceptorArgs.clientInterceptorProviders.length > 0) {\n throw new InterceptorConfigurationError('Both interceptors and interceptor_providers were passed as options ' +\n 'to the client constructor. Only one of these is allowed.');\n }\n if (interceptorArgs.callInterceptors.length > 0 &&\n interceptorArgs.callInterceptorProviders.length > 0) {\n throw new InterceptorConfigurationError('Both interceptors and interceptor_providers were passed as call ' +\n 'options. Only one of these is allowed.');\n }\n let interceptors = [];\n // Interceptors passed to the call override interceptors passed to the client constructor\n if (interceptorArgs.callInterceptors.length > 0 ||\n interceptorArgs.callInterceptorProviders.length > 0) {\n interceptors = []\n .concat(interceptorArgs.callInterceptors, interceptorArgs.callInterceptorProviders.map((provider) => provider(methodDefinition)))\n .filter((interceptor) => interceptor);\n // Filter out falsy values when providers return nothing\n }\n else {\n interceptors = []\n .concat(interceptorArgs.clientInterceptors, interceptorArgs.clientInterceptorProviders.map((provider) => provider(methodDefinition)))\n .filter((interceptor) => interceptor);\n // Filter out falsy values when providers return nothing\n }\n const interceptorOptions = Object.assign({}, options, {\n method_definition: methodDefinition,\n });\n /* For each interceptor in the list, the nextCall function passed to it is\n * based on the next interceptor in the list, using a nextCall function\n * constructed with the following interceptor in the list, and so on. The\n * initialValue, which is effectively at the end of the list, is a nextCall\n * function that invokes getBottomInterceptingCall, the result of which\n * handles (de)serialization and also gets the underlying call from the\n * channel. */\n const getCall = interceptors.reduceRight((nextCall, nextInterceptor) => {\n return (currentOptions) => nextInterceptor(currentOptions, nextCall);\n }, (finalOptions) => getBottomInterceptingCall(channel, finalOptions, methodDefinition));\n return getCall(interceptorOptions);\n}\nexports.getInterceptingCall = getInterceptingCall;\n//# sourceMappingURL=client-interceptors.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Client = void 0;\nconst call_1 = require(\"./call\");\nconst channel_1 = require(\"./channel\");\nconst constants_1 = require(\"./constants\");\nconst metadata_1 = require(\"./metadata\");\nconst client_interceptors_1 = require(\"./client-interceptors\");\nconst CHANNEL_SYMBOL = Symbol();\nconst INTERCEPTOR_SYMBOL = Symbol();\nconst INTERCEPTOR_PROVIDER_SYMBOL = Symbol();\nconst CALL_INVOCATION_TRANSFORMER_SYMBOL = Symbol();\n/**\n * A generic gRPC client. Primarily useful as a base class for all generated\n * clients.\n */\nclass Client {\n constructor(address, credentials, options = {}) {\n var _a, _b;\n options = Object.assign({}, options);\n this[INTERCEPTOR_SYMBOL] = (_a = options.interceptors) !== null && _a !== void 0 ? _a : [];\n delete options.interceptors;\n this[INTERCEPTOR_PROVIDER_SYMBOL] = (_b = options.interceptor_providers) !== null && _b !== void 0 ? _b : [];\n delete options.interceptor_providers;\n if (this[INTERCEPTOR_SYMBOL].length > 0 &&\n this[INTERCEPTOR_PROVIDER_SYMBOL].length > 0) {\n throw new Error('Both interceptors and interceptor_providers were passed as options ' +\n 'to the client constructor. Only one of these is allowed.');\n }\n this[CALL_INVOCATION_TRANSFORMER_SYMBOL] =\n options.callInvocationTransformer;\n delete options.callInvocationTransformer;\n if (options.channelOverride) {\n this[CHANNEL_SYMBOL] = options.channelOverride;\n }\n else if (options.channelFactoryOverride) {\n const channelFactoryOverride = options.channelFactoryOverride;\n delete options.channelFactoryOverride;\n this[CHANNEL_SYMBOL] = channelFactoryOverride(address, credentials, options);\n }\n else {\n this[CHANNEL_SYMBOL] = new channel_1.ChannelImplementation(address, credentials, options);\n }\n }\n close() {\n this[CHANNEL_SYMBOL].close();\n }\n getChannel() {\n return this[CHANNEL_SYMBOL];\n }\n waitForReady(deadline, callback) {\n const checkState = (err) => {\n if (err) {\n callback(new Error('Failed to connect before the deadline'));\n return;\n }\n let newState;\n try {\n newState = this[CHANNEL_SYMBOL].getConnectivityState(true);\n }\n catch (e) {\n callback(new Error('The channel has been closed'));\n return;\n }\n if (newState === channel_1.ConnectivityState.READY) {\n callback();\n }\n else {\n try {\n this[CHANNEL_SYMBOL].watchConnectivityState(newState, deadline, checkState);\n }\n catch (e) {\n callback(new Error('The channel has been closed'));\n }\n }\n };\n setImmediate(checkState);\n }\n checkOptionalUnaryResponseArguments(arg1, arg2, arg3) {\n if (arg1 instanceof Function) {\n return { metadata: new metadata_1.Metadata(), options: {}, callback: arg1 };\n }\n else if (arg2 instanceof Function) {\n if (arg1 instanceof metadata_1.Metadata) {\n return { metadata: arg1, options: {}, callback: arg2 };\n }\n else {\n return { metadata: new metadata_1.Metadata(), options: arg1, callback: arg2 };\n }\n }\n else {\n if (!(arg1 instanceof metadata_1.Metadata &&\n arg2 instanceof Object &&\n arg3 instanceof Function)) {\n throw new Error('Incorrect arguments passed');\n }\n return { metadata: arg1, options: arg2, callback: arg3 };\n }\n }\n makeUnaryRequest(method, serialize, deserialize, argument, metadata, options, callback) {\n var _a, _b;\n const checkedArguments = this.checkOptionalUnaryResponseArguments(metadata, options, callback);\n const methodDefinition = {\n path: method,\n requestStream: false,\n responseStream: false,\n requestSerialize: serialize,\n responseDeserialize: deserialize,\n };\n let callProperties = {\n argument: argument,\n metadata: checkedArguments.metadata,\n call: new call_1.ClientUnaryCallImpl(),\n channel: this[CHANNEL_SYMBOL],\n methodDefinition: methodDefinition,\n callOptions: checkedArguments.options,\n callback: checkedArguments.callback,\n };\n if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) {\n callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties);\n }\n const emitter = callProperties.call;\n const interceptorArgs = {\n clientInterceptors: this[INTERCEPTOR_SYMBOL],\n clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL],\n callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [],\n callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : [],\n };\n const call = client_interceptors_1.getInterceptingCall(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel);\n /* This needs to happen before the emitter is used. Unfortunately we can't\n * enforce this with the type system. We need to construct this emitter\n * before calling the CallInvocationTransformer, and we need to create the\n * call after that. */\n emitter.call = call;\n if (callProperties.callOptions.credentials) {\n call.setCredentials(callProperties.callOptions.credentials);\n }\n let responseMessage = null;\n let receivedStatus = false;\n call.start(callProperties.metadata, {\n onReceiveMetadata: (metadata) => {\n emitter.emit('metadata', metadata);\n },\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n onReceiveMessage(message) {\n if (responseMessage !== null) {\n call.cancelWithStatus(constants_1.Status.INTERNAL, 'Too many responses received');\n }\n responseMessage = message;\n },\n onReceiveStatus(status) {\n if (receivedStatus) {\n return;\n }\n receivedStatus = true;\n if (status.code === constants_1.Status.OK) {\n callProperties.callback(null, responseMessage);\n }\n else {\n callProperties.callback(call_1.callErrorFromStatus(status));\n }\n emitter.emit('status', status);\n },\n });\n call.sendMessage(argument);\n call.halfClose();\n return emitter;\n }\n makeClientStreamRequest(method, serialize, deserialize, metadata, options, callback) {\n var _a, _b;\n const checkedArguments = this.checkOptionalUnaryResponseArguments(metadata, options, callback);\n const methodDefinition = {\n path: method,\n requestStream: true,\n responseStream: false,\n requestSerialize: serialize,\n responseDeserialize: deserialize,\n };\n let callProperties = {\n metadata: checkedArguments.metadata,\n call: new call_1.ClientWritableStreamImpl(serialize),\n channel: this[CHANNEL_SYMBOL],\n methodDefinition: methodDefinition,\n callOptions: checkedArguments.options,\n callback: checkedArguments.callback,\n };\n if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) {\n callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties);\n }\n const emitter = callProperties.call;\n const interceptorArgs = {\n clientInterceptors: this[INTERCEPTOR_SYMBOL],\n clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL],\n callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [],\n callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : [],\n };\n const call = client_interceptors_1.getInterceptingCall(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel);\n /* This needs to happen before the emitter is used. Unfortunately we can't\n * enforce this with the type system. We need to construct this emitter\n * before calling the CallInvocationTransformer, and we need to create the\n * call after that. */\n emitter.call = call;\n if (callProperties.callOptions.credentials) {\n call.setCredentials(callProperties.callOptions.credentials);\n }\n let responseMessage = null;\n let receivedStatus = false;\n call.start(callProperties.metadata, {\n onReceiveMetadata: (metadata) => {\n emitter.emit('metadata', metadata);\n },\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n onReceiveMessage(message) {\n if (responseMessage !== null) {\n call.cancelWithStatus(constants_1.Status.INTERNAL, 'Too many responses received');\n }\n responseMessage = message;\n },\n onReceiveStatus(status) {\n if (receivedStatus) {\n return;\n }\n receivedStatus = true;\n if (status.code === constants_1.Status.OK) {\n callProperties.callback(null, responseMessage);\n }\n else {\n callProperties.callback(call_1.callErrorFromStatus(status));\n }\n emitter.emit('status', status);\n },\n });\n return emitter;\n }\n checkMetadataAndOptions(arg1, arg2) {\n let metadata;\n let options;\n if (arg1 instanceof metadata_1.Metadata) {\n metadata = arg1;\n if (arg2) {\n options = arg2;\n }\n else {\n options = {};\n }\n }\n else {\n if (arg1) {\n options = arg1;\n }\n else {\n options = {};\n }\n metadata = new metadata_1.Metadata();\n }\n return { metadata, options };\n }\n makeServerStreamRequest(method, serialize, deserialize, argument, metadata, options) {\n var _a, _b;\n const checkedArguments = this.checkMetadataAndOptions(metadata, options);\n const methodDefinition = {\n path: method,\n requestStream: false,\n responseStream: true,\n requestSerialize: serialize,\n responseDeserialize: deserialize,\n };\n let callProperties = {\n argument: argument,\n metadata: checkedArguments.metadata,\n call: new call_1.ClientReadableStreamImpl(deserialize),\n channel: this[CHANNEL_SYMBOL],\n methodDefinition: methodDefinition,\n callOptions: checkedArguments.options,\n };\n if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) {\n callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties);\n }\n const stream = callProperties.call;\n const interceptorArgs = {\n clientInterceptors: this[INTERCEPTOR_SYMBOL],\n clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL],\n callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [],\n callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : [],\n };\n const call = client_interceptors_1.getInterceptingCall(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel);\n /* This needs to happen before the emitter is used. Unfortunately we can't\n * enforce this with the type system. We need to construct this emitter\n * before calling the CallInvocationTransformer, and we need to create the\n * call after that. */\n stream.call = call;\n if (callProperties.callOptions.credentials) {\n call.setCredentials(callProperties.callOptions.credentials);\n }\n let receivedStatus = false;\n call.start(callProperties.metadata, {\n onReceiveMetadata(metadata) {\n stream.emit('metadata', metadata);\n },\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n onReceiveMessage(message) {\n stream.push(message);\n },\n onReceiveStatus(status) {\n if (receivedStatus) {\n return;\n }\n receivedStatus = true;\n stream.push(null);\n if (status.code !== constants_1.Status.OK) {\n stream.emit('error', call_1.callErrorFromStatus(status));\n }\n stream.emit('status', status);\n },\n });\n call.sendMessage(argument);\n call.halfClose();\n return stream;\n }\n makeBidiStreamRequest(method, serialize, deserialize, metadata, options) {\n var _a, _b;\n const checkedArguments = this.checkMetadataAndOptions(metadata, options);\n const methodDefinition = {\n path: method,\n requestStream: true,\n responseStream: true,\n requestSerialize: serialize,\n responseDeserialize: deserialize,\n };\n let callProperties = {\n metadata: checkedArguments.metadata,\n call: new call_1.ClientDuplexStreamImpl(serialize, deserialize),\n channel: this[CHANNEL_SYMBOL],\n methodDefinition: methodDefinition,\n callOptions: checkedArguments.options,\n };\n if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) {\n callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties);\n }\n const stream = callProperties.call;\n const interceptorArgs = {\n clientInterceptors: this[INTERCEPTOR_SYMBOL],\n clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL],\n callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [],\n callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : [],\n };\n const call = client_interceptors_1.getInterceptingCall(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel);\n /* This needs to happen before the emitter is used. Unfortunately we can't\n * enforce this with the type system. We need to construct this emitter\n * before calling the CallInvocationTransformer, and we need to create the\n * call after that. */\n stream.call = call;\n if (callProperties.callOptions.credentials) {\n call.setCredentials(callProperties.callOptions.credentials);\n }\n let receivedStatus = false;\n call.start(callProperties.metadata, {\n onReceiveMetadata(metadata) {\n stream.emit('metadata', metadata);\n },\n onReceiveMessage(message) {\n stream.push(message);\n },\n onReceiveStatus(status) {\n if (receivedStatus) {\n return;\n }\n receivedStatus = true;\n stream.push(null);\n if (status.code !== constants_1.Status.OK) {\n stream.emit('error', call_1.callErrorFromStatus(status));\n }\n stream.emit('status', status);\n },\n });\n return stream;\n }\n}\nexports.Client = Client;\n//# sourceMappingURL=client.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CompressionFilterFactory = exports.CompressionFilter = void 0;\nconst zlib = require(\"zlib\");\nconst filter_1 = require(\"./filter\");\nclass CompressionHandler {\n /**\n * @param message Raw uncompressed message bytes\n * @param compress Indicates whether the message should be compressed\n * @return Framed message, compressed if applicable\n */\n async writeMessage(message, compress) {\n let messageBuffer = message;\n if (compress) {\n messageBuffer = await this.compressMessage(messageBuffer);\n }\n const output = Buffer.allocUnsafe(messageBuffer.length + 5);\n output.writeUInt8(compress ? 1 : 0, 0);\n output.writeUInt32BE(messageBuffer.length, 1);\n messageBuffer.copy(output, 5);\n return output;\n }\n /**\n * @param data Framed message, possibly compressed\n * @return Uncompressed message\n */\n async readMessage(data) {\n const compressed = data.readUInt8(0) === 1;\n let messageBuffer = data.slice(5);\n if (compressed) {\n messageBuffer = await this.decompressMessage(messageBuffer);\n }\n return messageBuffer;\n }\n}\nclass IdentityHandler extends CompressionHandler {\n async compressMessage(message) {\n return message;\n }\n async writeMessage(message, compress) {\n const output = Buffer.allocUnsafe(message.length + 5);\n /* With \"identity\" compression, messages should always be marked as\n * uncompressed */\n output.writeUInt8(0, 0);\n output.writeUInt32BE(message.length, 1);\n message.copy(output, 5);\n return output;\n }\n decompressMessage(message) {\n return Promise.reject(new Error('Received compressed message but \"grpc-encoding\" header was identity'));\n }\n}\nclass DeflateHandler extends CompressionHandler {\n compressMessage(message) {\n return new Promise((resolve, reject) => {\n zlib.deflate(message, (err, output) => {\n if (err) {\n reject(err);\n }\n else {\n resolve(output);\n }\n });\n });\n }\n decompressMessage(message) {\n return new Promise((resolve, reject) => {\n zlib.inflate(message, (err, output) => {\n if (err) {\n reject(err);\n }\n else {\n resolve(output);\n }\n });\n });\n }\n}\nclass GzipHandler extends CompressionHandler {\n compressMessage(message) {\n return new Promise((resolve, reject) => {\n zlib.gzip(message, (err, output) => {\n if (err) {\n reject(err);\n }\n else {\n resolve(output);\n }\n });\n });\n }\n decompressMessage(message) {\n return new Promise((resolve, reject) => {\n zlib.unzip(message, (err, output) => {\n if (err) {\n reject(err);\n }\n else {\n resolve(output);\n }\n });\n });\n }\n}\nclass UnknownHandler extends CompressionHandler {\n constructor(compressionName) {\n super();\n this.compressionName = compressionName;\n }\n compressMessage(message) {\n return Promise.reject(new Error(`Received message compressed with unsupported compression method ${this.compressionName}`));\n }\n decompressMessage(message) {\n // This should be unreachable\n return Promise.reject(new Error(`Compression method not supported: ${this.compressionName}`));\n }\n}\nfunction getCompressionHandler(compressionName) {\n switch (compressionName) {\n case 'identity':\n return new IdentityHandler();\n case 'deflate':\n return new DeflateHandler();\n case 'gzip':\n return new GzipHandler();\n default:\n return new UnknownHandler(compressionName);\n }\n}\nclass CompressionFilter extends filter_1.BaseFilter {\n constructor() {\n super(...arguments);\n this.sendCompression = new IdentityHandler();\n this.receiveCompression = new IdentityHandler();\n }\n async sendMetadata(metadata) {\n const headers = await metadata;\n headers.set('grpc-accept-encoding', 'identity,deflate,gzip');\n headers.set('accept-encoding', 'identity,gzip');\n return headers;\n }\n receiveMetadata(metadata) {\n const receiveEncoding = metadata.get('grpc-encoding');\n if (receiveEncoding.length > 0) {\n const encoding = receiveEncoding[0];\n if (typeof encoding === 'string') {\n this.receiveCompression = getCompressionHandler(encoding);\n }\n }\n metadata.remove('grpc-encoding');\n metadata.remove('grpc-accept-encoding');\n return metadata;\n }\n async sendMessage(message) {\n /* This filter is special. The input message is the bare message bytes,\n * and the output is a framed and possibly compressed message. For this\n * reason, this filter should be at the bottom of the filter stack */\n const resolvedMessage = await message;\n const compress = resolvedMessage.flags === undefined\n ? false\n : (resolvedMessage.flags & 2 /* NoCompress */) === 0;\n return {\n message: await this.sendCompression.writeMessage(resolvedMessage.message, compress),\n flags: resolvedMessage.flags,\n };\n }\n async receiveMessage(message) {\n /* This filter is also special. The input message is framed and possibly\n * compressed, and the output message is deframed and uncompressed. So\n * this is another reason that this filter should be at the bottom of the\n * filter stack. */\n return this.receiveCompression.readMessage(await message);\n }\n}\nexports.CompressionFilter = CompressionFilter;\nclass CompressionFilterFactory {\n constructor(channel) {\n this.channel = channel;\n }\n createFilter(callStream) {\n return new CompressionFilter();\n }\n}\nexports.CompressionFilterFactory = CompressionFilterFactory;\n//# sourceMappingURL=compression-filter.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH = exports.DEFAULT_MAX_SEND_MESSAGE_LENGTH = exports.Propagate = exports.LogVerbosity = exports.Status = void 0;\nvar Status;\n(function (Status) {\n Status[Status[\"OK\"] = 0] = \"OK\";\n Status[Status[\"CANCELLED\"] = 1] = \"CANCELLED\";\n Status[Status[\"UNKNOWN\"] = 2] = \"UNKNOWN\";\n Status[Status[\"INVALID_ARGUMENT\"] = 3] = \"INVALID_ARGUMENT\";\n Status[Status[\"DEADLINE_EXCEEDED\"] = 4] = \"DEADLINE_EXCEEDED\";\n Status[Status[\"NOT_FOUND\"] = 5] = \"NOT_FOUND\";\n Status[Status[\"ALREADY_EXISTS\"] = 6] = \"ALREADY_EXISTS\";\n Status[Status[\"PERMISSION_DENIED\"] = 7] = \"PERMISSION_DENIED\";\n Status[Status[\"RESOURCE_EXHAUSTED\"] = 8] = \"RESOURCE_EXHAUSTED\";\n Status[Status[\"FAILED_PRECONDITION\"] = 9] = \"FAILED_PRECONDITION\";\n Status[Status[\"ABORTED\"] = 10] = \"ABORTED\";\n Status[Status[\"OUT_OF_RANGE\"] = 11] = \"OUT_OF_RANGE\";\n Status[Status[\"UNIMPLEMENTED\"] = 12] = \"UNIMPLEMENTED\";\n Status[Status[\"INTERNAL\"] = 13] = \"INTERNAL\";\n Status[Status[\"UNAVAILABLE\"] = 14] = \"UNAVAILABLE\";\n Status[Status[\"DATA_LOSS\"] = 15] = \"DATA_LOSS\";\n Status[Status[\"UNAUTHENTICATED\"] = 16] = \"UNAUTHENTICATED\";\n})(Status = exports.Status || (exports.Status = {}));\nvar LogVerbosity;\n(function (LogVerbosity) {\n LogVerbosity[LogVerbosity[\"DEBUG\"] = 0] = \"DEBUG\";\n LogVerbosity[LogVerbosity[\"INFO\"] = 1] = \"INFO\";\n LogVerbosity[LogVerbosity[\"ERROR\"] = 2] = \"ERROR\";\n})(LogVerbosity = exports.LogVerbosity || (exports.LogVerbosity = {}));\n/**\n * NOTE: This enum is not currently used in any implemented API in this\n * library. It is included only for type parity with the other implementation.\n */\nvar Propagate;\n(function (Propagate) {\n Propagate[Propagate[\"DEADLINE\"] = 1] = \"DEADLINE\";\n Propagate[Propagate[\"CENSUS_STATS_CONTEXT\"] = 2] = \"CENSUS_STATS_CONTEXT\";\n Propagate[Propagate[\"CENSUS_TRACING_CONTEXT\"] = 4] = \"CENSUS_TRACING_CONTEXT\";\n Propagate[Propagate[\"CANCELLATION\"] = 8] = \"CANCELLATION\";\n // https://github.com/grpc/grpc/blob/master/include/grpc/impl/codegen/propagation_bits.h#L43\n Propagate[Propagate[\"DEFAULTS\"] = 65535] = \"DEFAULTS\";\n})(Propagate = exports.Propagate || (exports.Propagate = {}));\n// -1 means unlimited\nexports.DEFAULT_MAX_SEND_MESSAGE_LENGTH = -1;\n// 4 MB default\nexports.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH = 4 * 1024 * 1024;\n//# sourceMappingURL=constants.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DeadlineFilterFactory = exports.DeadlineFilter = void 0;\nconst constants_1 = require(\"./constants\");\nconst filter_1 = require(\"./filter\");\nconst units = [\n ['m', 1],\n ['S', 1000],\n ['M', 60 * 1000],\n ['H', 60 * 60 * 1000],\n];\nfunction getDeadline(deadline) {\n const now = new Date().getTime();\n const timeoutMs = Math.max(deadline - now, 0);\n for (const [unit, factor] of units) {\n const amount = timeoutMs / factor;\n if (amount < 1e8) {\n return String(Math.ceil(amount)) + unit;\n }\n }\n throw new Error('Deadline is too far in the future');\n}\nclass DeadlineFilter extends filter_1.BaseFilter {\n constructor(channel, callStream) {\n var _a, _b;\n super();\n this.channel = channel;\n this.callStream = callStream;\n this.timer = null;\n const callDeadline = callStream.getDeadline();\n if (callDeadline instanceof Date) {\n this.deadline = callDeadline.getTime();\n }\n else {\n this.deadline = callDeadline;\n }\n const now = new Date().getTime();\n let timeout = this.deadline - now;\n if (timeout <= 0) {\n process.nextTick(() => {\n callStream.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, 'Deadline exceeded');\n });\n }\n else if (this.deadline !== Infinity) {\n this.timer = setTimeout(() => {\n callStream.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, 'Deadline exceeded');\n }, timeout);\n (_b = (_a = this.timer).unref) === null || _b === void 0 ? void 0 : _b.call(_a);\n }\n }\n async sendMetadata(metadata) {\n if (this.deadline === Infinity) {\n return metadata;\n }\n /* The input metadata promise depends on the original channel.connect()\n * promise, so when it is complete that implies that the channel is\n * connected */\n const finalMetadata = await metadata;\n const timeoutString = getDeadline(this.deadline);\n finalMetadata.set('grpc-timeout', timeoutString);\n return finalMetadata;\n }\n receiveTrailers(status) {\n if (this.timer) {\n clearTimeout(this.timer);\n }\n return status;\n }\n}\nexports.DeadlineFilter = DeadlineFilter;\nclass DeadlineFilterFactory {\n constructor(channel) {\n this.channel = channel;\n }\n createFilter(callStream) {\n return new DeadlineFilter(this.channel, callStream);\n }\n}\nexports.DeadlineFilterFactory = DeadlineFilterFactory;\n//# sourceMappingURL=deadline-filter.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar logging_1 = require(\"./logging\");\nObject.defineProperty(exports, \"trace\", { enumerable: true, get: function () { return logging_1.trace; } });\nvar resolver_1 = require(\"./resolver\");\nObject.defineProperty(exports, \"registerResolver\", { enumerable: true, get: function () { return resolver_1.registerResolver; } });\nvar uri_parser_1 = require(\"./uri-parser\");\nObject.defineProperty(exports, \"uriToString\", { enumerable: true, get: function () { return uri_parser_1.uriToString; } });\nvar channel_credentials_1 = require(\"./channel-credentials\");\nObject.defineProperty(exports, \"createGoogleDefaultCredentials\", { enumerable: true, get: function () { return channel_credentials_1.createGoogleDefaultCredentials; } });\nvar backoff_timeout_1 = require(\"./backoff-timeout\");\nObject.defineProperty(exports, \"BackoffTimeout\", { enumerable: true, get: function () { return backoff_timeout_1.BackoffTimeout; } });\nvar load_balancer_1 = require(\"./load-balancer\");\nObject.defineProperty(exports, \"registerLoadBalancerType\", { enumerable: true, get: function () { return load_balancer_1.registerLoadBalancerType; } });\nObject.defineProperty(exports, \"getFirstUsableConfig\", { enumerable: true, get: function () { return load_balancer_1.getFirstUsableConfig; } });\nObject.defineProperty(exports, \"validateLoadBalancingConfig\", { enumerable: true, get: function () { return load_balancer_1.validateLoadBalancingConfig; } });\nvar subchannel_1 = require(\"./subchannel\");\nObject.defineProperty(exports, \"subchannelAddressToString\", { enumerable: true, get: function () { return subchannel_1.subchannelAddressToString; } });\nvar load_balancer_child_handler_1 = require(\"./load-balancer-child-handler\");\nObject.defineProperty(exports, \"ChildLoadBalancerHandler\", { enumerable: true, get: function () { return load_balancer_child_handler_1.ChildLoadBalancerHandler; } });\nvar picker_1 = require(\"./picker\");\nObject.defineProperty(exports, \"UnavailablePicker\", { enumerable: true, get: function () { return picker_1.UnavailablePicker; } });\nObject.defineProperty(exports, \"QueuePicker\", { enumerable: true, get: function () { return picker_1.QueuePicker; } });\nObject.defineProperty(exports, \"PickResultType\", { enumerable: true, get: function () { return picker_1.PickResultType; } });\nvar filter_1 = require(\"./filter\");\nObject.defineProperty(exports, \"BaseFilter\", { enumerable: true, get: function () { return filter_1.BaseFilter; } });\nvar filter_stack_1 = require(\"./filter-stack\");\nObject.defineProperty(exports, \"FilterStackFactory\", { enumerable: true, get: function () { return filter_stack_1.FilterStackFactory; } });\n//# sourceMappingURL=experimental.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.FilterStackFactory = exports.FilterStack = void 0;\nclass FilterStack {\n constructor(filters) {\n this.filters = filters;\n }\n sendMetadata(metadata) {\n let result = metadata;\n for (let i = 0; i < this.filters.length; i++) {\n result = this.filters[i].sendMetadata(result);\n }\n return result;\n }\n receiveMetadata(metadata) {\n let result = metadata;\n for (let i = this.filters.length - 1; i >= 0; i--) {\n result = this.filters[i].receiveMetadata(result);\n }\n return result;\n }\n sendMessage(message) {\n let result = message;\n for (let i = 0; i < this.filters.length; i++) {\n result = this.filters[i].sendMessage(result);\n }\n return result;\n }\n receiveMessage(message) {\n let result = message;\n for (let i = this.filters.length - 1; i >= 0; i--) {\n result = this.filters[i].receiveMessage(result);\n }\n return result;\n }\n receiveTrailers(status) {\n let result = status;\n for (let i = this.filters.length - 1; i >= 0; i--) {\n result = this.filters[i].receiveTrailers(result);\n }\n return result;\n }\n}\nexports.FilterStack = FilterStack;\nclass FilterStackFactory {\n constructor(factories) {\n this.factories = factories;\n }\n createFilter(callStream) {\n return new FilterStack(this.factories.map((factory) => factory.createFilter(callStream)));\n }\n}\nexports.FilterStackFactory = FilterStackFactory;\n//# sourceMappingURL=filter-stack.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.BaseFilter = void 0;\nclass BaseFilter {\n async sendMetadata(metadata) {\n return metadata;\n }\n receiveMetadata(metadata) {\n return metadata;\n }\n async sendMessage(message) {\n return message;\n }\n async receiveMessage(message) {\n return message;\n }\n receiveTrailers(status) {\n return status;\n }\n}\nexports.BaseFilter = BaseFilter;\n//# sourceMappingURL=filter.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getProxiedConnection = exports.mapProxyName = void 0;\nconst logging_1 = require(\"./logging\");\nconst constants_1 = require(\"./constants\");\nconst resolver_1 = require(\"./resolver\");\nconst http = require(\"http\");\nconst tls = require(\"tls\");\nconst logging = require(\"./logging\");\nconst subchannel_1 = require(\"./subchannel\");\nconst uri_parser_1 = require(\"./uri-parser\");\nconst url_1 = require(\"url\");\nconst TRACER_NAME = 'proxy';\nfunction trace(text) {\n logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text);\n}\nfunction getProxyInfo() {\n let proxyEnv = '';\n let envVar = '';\n /* Prefer using 'grpc_proxy'. Fallback on 'http_proxy' if it is not set.\n * Also prefer using 'https_proxy' with fallback on 'http_proxy'. The\n * fallback behavior can be removed if there's a demand for it.\n */\n if (process.env.grpc_proxy) {\n envVar = 'grpc_proxy';\n proxyEnv = process.env.grpc_proxy;\n }\n else if (process.env.https_proxy) {\n envVar = 'https_proxy';\n proxyEnv = process.env.https_proxy;\n }\n else if (process.env.http_proxy) {\n envVar = 'http_proxy';\n proxyEnv = process.env.http_proxy;\n }\n else {\n return {};\n }\n let proxyUrl;\n try {\n proxyUrl = new url_1.URL(proxyEnv);\n }\n catch (e) {\n logging_1.log(constants_1.LogVerbosity.ERROR, `cannot parse value of \"${envVar}\" env var`);\n return {};\n }\n if (proxyUrl.protocol !== 'http:') {\n logging_1.log(constants_1.LogVerbosity.ERROR, `\"${proxyUrl.protocol}\" scheme not supported in proxy URI`);\n return {};\n }\n let userCred = null;\n if (proxyUrl.username) {\n if (proxyUrl.password) {\n logging_1.log(constants_1.LogVerbosity.INFO, 'userinfo found in proxy URI');\n userCred = `${proxyUrl.username}:${proxyUrl.password}`;\n }\n else {\n userCred = proxyUrl.username;\n }\n }\n const hostname = proxyUrl.hostname;\n let port = proxyUrl.port;\n /* The proxy URL uses the scheme \"http:\", which has a default port number of\n * 80. We need to set that explicitly here if it is omitted because otherwise\n * it will use gRPC's default port 443. */\n if (port === '') {\n port = '80';\n }\n const result = {\n address: `${hostname}:${port}`\n };\n if (userCred) {\n result.creds = userCred;\n }\n trace('Proxy server ' + result.address + ' set by environment variable ' + envVar);\n return result;\n}\nfunction getNoProxyHostList() {\n /* Prefer using 'no_grpc_proxy'. Fallback on 'no_proxy' if it is not set. */\n let noProxyStr = process.env.no_grpc_proxy;\n let envVar = 'no_grpc_proxy';\n if (!noProxyStr) {\n noProxyStr = process.env.no_proxy;\n envVar = 'no_proxy';\n }\n if (noProxyStr) {\n trace('No proxy server list set by environment variable ' + envVar);\n return noProxyStr.split(',');\n }\n else {\n return [];\n }\n}\nfunction mapProxyName(target, options) {\n var _a;\n const noProxyResult = {\n target: target,\n extraOptions: {},\n };\n if (((_a = options['grpc.enable_http_proxy']) !== null && _a !== void 0 ? _a : 1) === 0) {\n return noProxyResult;\n }\n const proxyInfo = getProxyInfo();\n if (!proxyInfo.address) {\n return noProxyResult;\n }\n const hostPort = uri_parser_1.splitHostPort(target.path);\n if (!hostPort) {\n return noProxyResult;\n }\n const serverHost = hostPort.host;\n for (const host of getNoProxyHostList()) {\n if (host === serverHost) {\n trace('Not using proxy for target in no_proxy list: ' + uri_parser_1.uriToString(target));\n return noProxyResult;\n }\n }\n const extraOptions = {\n 'grpc.http_connect_target': uri_parser_1.uriToString(target),\n };\n if (proxyInfo.creds) {\n extraOptions['grpc.http_connect_creds'] = proxyInfo.creds;\n }\n return {\n target: {\n scheme: 'dns',\n path: proxyInfo.address,\n },\n extraOptions: extraOptions,\n };\n}\nexports.mapProxyName = mapProxyName;\nfunction getProxiedConnection(address, channelOptions, connectionOptions) {\n if (!('grpc.http_connect_target' in channelOptions)) {\n return Promise.resolve({});\n }\n const realTarget = channelOptions['grpc.http_connect_target'];\n const parsedTarget = uri_parser_1.parseUri(realTarget);\n if (parsedTarget === null) {\n return Promise.resolve({});\n }\n const options = {\n method: 'CONNECT',\n path: parsedTarget.path,\n };\n // Connect to the subchannel address as a proxy\n if (subchannel_1.isTcpSubchannelAddress(address)) {\n options.host = address.host;\n options.port = address.port;\n }\n else {\n options.socketPath = address.path;\n }\n if ('grpc.http_connect_creds' in channelOptions) {\n options.headers = {\n 'Proxy-Authorization': 'Basic ' +\n Buffer.from(channelOptions['grpc.http_connect_creds']).toString('base64'),\n };\n }\n const proxyAddressString = subchannel_1.subchannelAddressToString(address);\n trace('Using proxy ' + proxyAddressString + ' to connect to ' + options.path);\n return new Promise((resolve, reject) => {\n const request = http.request(options);\n request.once('connect', (res, socket, head) => {\n var _a;\n request.removeAllListeners();\n socket.removeAllListeners();\n if (res.statusCode === 200) {\n trace('Successfully connected to ' +\n options.path +\n ' through proxy ' +\n proxyAddressString);\n if ('secureContext' in connectionOptions) {\n /* The proxy is connecting to a TLS server, so upgrade this socket\n * connection to a TLS connection.\n * This is a workaround for https://github.com/nodejs/node/issues/32922\n * See https://github.com/grpc/grpc-node/pull/1369 for more info. */\n const targetPath = resolver_1.getDefaultAuthority(parsedTarget);\n const hostPort = uri_parser_1.splitHostPort(targetPath);\n const remoteHost = (_a = hostPort === null || hostPort === void 0 ? void 0 : hostPort.host) !== null && _a !== void 0 ? _a : targetPath;\n const cts = tls.connect(Object.assign({ host: remoteHost, servername: remoteHost, socket: socket }, connectionOptions), () => {\n trace('Successfully established a TLS connection to ' +\n options.path +\n ' through proxy ' +\n proxyAddressString);\n resolve({ socket: cts, realTarget: parsedTarget });\n });\n cts.on('error', () => {\n reject();\n });\n }\n else {\n resolve({\n socket,\n realTarget: parsedTarget,\n });\n }\n }\n else {\n logging_1.log(constants_1.LogVerbosity.ERROR, 'Failed to connect to ' +\n options.path +\n ' through proxy ' +\n proxyAddressString +\n ' with status ' +\n res.statusCode);\n reject();\n }\n });\n request.once('error', (err) => {\n request.removeAllListeners();\n logging_1.log(constants_1.LogVerbosity.ERROR, 'Failed to connect to proxy ' +\n proxyAddressString +\n ' with error ' +\n err.message);\n reject();\n });\n request.end();\n });\n}\nexports.getProxiedConnection = getProxiedConnection;\n//# sourceMappingURL=http_proxy.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.experimental = exports.StatusBuilder = exports.getClientChannel = exports.ServerCredentials = exports.Server = exports.setLogVerbosity = exports.setLogger = exports.load = exports.loadObject = exports.CallCredentials = exports.ChannelCredentials = exports.waitForClientReady = exports.closeClient = exports.Channel = exports.makeGenericClientConstructor = exports.makeClientConstructor = exports.loadPackageDefinition = exports.Client = exports.propagate = exports.connectivityState = exports.status = exports.logVerbosity = exports.Metadata = exports.credentials = void 0;\nconst semver = require(\"semver\");\nconst call_credentials_1 = require(\"./call-credentials\");\nObject.defineProperty(exports, \"CallCredentials\", { enumerable: true, get: function () { return call_credentials_1.CallCredentials; } });\nconst channel_1 = require(\"./channel\");\nObject.defineProperty(exports, \"connectivityState\", { enumerable: true, get: function () { return channel_1.ConnectivityState; } });\nObject.defineProperty(exports, \"Channel\", { enumerable: true, get: function () { return channel_1.ChannelImplementation; } });\nconst channel_credentials_1 = require(\"./channel-credentials\");\nObject.defineProperty(exports, \"ChannelCredentials\", { enumerable: true, get: function () { return channel_credentials_1.ChannelCredentials; } });\nconst client_1 = require(\"./client\");\nObject.defineProperty(exports, \"Client\", { enumerable: true, get: function () { return client_1.Client; } });\nconst constants_1 = require(\"./constants\");\nObject.defineProperty(exports, \"logVerbosity\", { enumerable: true, get: function () { return constants_1.LogVerbosity; } });\nObject.defineProperty(exports, \"status\", { enumerable: true, get: function () { return constants_1.Status; } });\nObject.defineProperty(exports, \"propagate\", { enumerable: true, get: function () { return constants_1.Propagate; } });\nconst logging = require(\"./logging\");\nconst make_client_1 = require(\"./make-client\");\nObject.defineProperty(exports, \"loadPackageDefinition\", { enumerable: true, get: function () { return make_client_1.loadPackageDefinition; } });\nObject.defineProperty(exports, \"makeClientConstructor\", { enumerable: true, get: function () { return make_client_1.makeClientConstructor; } });\nObject.defineProperty(exports, \"makeGenericClientConstructor\", { enumerable: true, get: function () { return make_client_1.makeClientConstructor; } });\nconst metadata_1 = require(\"./metadata\");\nObject.defineProperty(exports, \"Metadata\", { enumerable: true, get: function () { return metadata_1.Metadata; } });\nconst server_1 = require(\"./server\");\nObject.defineProperty(exports, \"Server\", { enumerable: true, get: function () { return server_1.Server; } });\nconst server_credentials_1 = require(\"./server-credentials\");\nObject.defineProperty(exports, \"ServerCredentials\", { enumerable: true, get: function () { return server_credentials_1.ServerCredentials; } });\nconst status_builder_1 = require(\"./status-builder\");\nObject.defineProperty(exports, \"StatusBuilder\", { enumerable: true, get: function () { return status_builder_1.StatusBuilder; } });\nconst supportedNodeVersions = require('../../package.json').engines.node;\nif (!semver.satisfies(process.version, supportedNodeVersions)) {\n throw new Error(`@grpc/grpc-js only works on Node ${supportedNodeVersions}`);\n}\n/**** Client Credentials ****/\n// Using assign only copies enumerable properties, which is what we want\nexports.credentials = {\n /**\n * Combine a ChannelCredentials with any number of CallCredentials into a\n * single ChannelCredentials object.\n * @param channelCredentials The ChannelCredentials object.\n * @param callCredentials Any number of CallCredentials objects.\n * @return The resulting ChannelCredentials object.\n */\n combineChannelCredentials: (channelCredentials, ...callCredentials) => {\n return callCredentials.reduce((acc, other) => acc.compose(other), channelCredentials);\n },\n /**\n * Combine any number of CallCredentials into a single CallCredentials\n * object.\n * @param first The first CallCredentials object.\n * @param additional Any number of additional CallCredentials objects.\n * @return The resulting CallCredentials object.\n */\n combineCallCredentials: (first, ...additional) => {\n return additional.reduce((acc, other) => acc.compose(other), first);\n },\n // from channel-credentials.ts\n createInsecure: channel_credentials_1.ChannelCredentials.createInsecure,\n createSsl: channel_credentials_1.ChannelCredentials.createSsl,\n // from call-credentials.ts\n createFromMetadataGenerator: call_credentials_1.CallCredentials.createFromMetadataGenerator,\n createFromGoogleCredential: call_credentials_1.CallCredentials.createFromGoogleCredential,\n createEmpty: call_credentials_1.CallCredentials.createEmpty,\n};\n/**\n * Close a Client object.\n * @param client The client to close.\n */\nexports.closeClient = (client) => client.close();\nexports.waitForClientReady = (client, deadline, callback) => client.waitForReady(deadline, callback);\n/* eslint-enable @typescript-eslint/no-explicit-any */\n/**** Unimplemented function stubs ****/\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexports.loadObject = (value, options) => {\n throw new Error('Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead');\n};\nexports.load = (filename, format, options) => {\n throw new Error('Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead');\n};\nexports.setLogger = (logger) => {\n logging.setLogger(logger);\n};\nexports.setLogVerbosity = (verbosity) => {\n logging.setLoggerVerbosity(verbosity);\n};\nexports.getClientChannel = (client) => {\n return client_1.Client.prototype.getChannel.call(client);\n};\nvar client_interceptors_1 = require(\"./client-interceptors\");\nObject.defineProperty(exports, \"ListenerBuilder\", { enumerable: true, get: function () { return client_interceptors_1.ListenerBuilder; } });\nObject.defineProperty(exports, \"RequesterBuilder\", { enumerable: true, get: function () { return client_interceptors_1.RequesterBuilder; } });\nObject.defineProperty(exports, \"InterceptingCall\", { enumerable: true, get: function () { return client_interceptors_1.InterceptingCall; } });\nObject.defineProperty(exports, \"InterceptorConfigurationError\", { enumerable: true, get: function () { return client_interceptors_1.InterceptorConfigurationError; } });\nconst experimental = require(\"./experimental\");\nexports.experimental = experimental;\nconst resolver = require(\"./resolver\");\nconst load_balancer = require(\"./load-balancer\");\n(() => {\n resolver.registerAll();\n load_balancer.registerAll();\n})();\n//# sourceMappingURL=index.js.map","\"use strict\";\n/*\n * Copyright 2020 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ChildLoadBalancerHandler = void 0;\nconst load_balancer_1 = require(\"./load-balancer\");\nconst channel_1 = require(\"./channel\");\nconst TYPE_NAME = 'child_load_balancer_helper';\nclass ChildLoadBalancerHandler {\n constructor(channelControlHelper) {\n this.channelControlHelper = channelControlHelper;\n this.currentChild = null;\n this.pendingChild = null;\n this.ChildPolicyHelper = class {\n constructor(parent) {\n this.parent = parent;\n this.child = null;\n }\n createSubchannel(subchannelAddress, subchannelArgs) {\n return this.parent.channelControlHelper.createSubchannel(subchannelAddress, subchannelArgs);\n }\n updateState(connectivityState, picker) {\n var _a;\n if (this.calledByPendingChild()) {\n if (connectivityState !== channel_1.ConnectivityState.READY) {\n return;\n }\n (_a = this.parent.currentChild) === null || _a === void 0 ? void 0 : _a.destroy();\n this.parent.currentChild = this.parent.pendingChild;\n this.parent.pendingChild = null;\n }\n else if (!this.calledByCurrentChild()) {\n return;\n }\n this.parent.channelControlHelper.updateState(connectivityState, picker);\n }\n requestReresolution() {\n var _a;\n const latestChild = (_a = this.parent.pendingChild) !== null && _a !== void 0 ? _a : this.parent.currentChild;\n if (this.child === latestChild) {\n this.parent.channelControlHelper.requestReresolution();\n }\n }\n setChild(newChild) {\n this.child = newChild;\n }\n calledByPendingChild() {\n return this.child === this.parent.pendingChild;\n }\n calledByCurrentChild() {\n return this.child === this.parent.currentChild;\n }\n };\n }\n /**\n * Prerequisites: lbConfig !== null and lbConfig.name is registered\n * @param addressList\n * @param lbConfig\n * @param attributes\n */\n updateAddressList(addressList, lbConfig, attributes) {\n let childToUpdate;\n if (this.currentChild === null ||\n this.currentChild.getTypeName() !== lbConfig.getLoadBalancerName()) {\n const newHelper = new this.ChildPolicyHelper(this);\n const newChild = load_balancer_1.createLoadBalancer(lbConfig, newHelper);\n newHelper.setChild(newChild);\n if (this.currentChild === null) {\n this.currentChild = newChild;\n childToUpdate = this.currentChild;\n }\n else {\n if (this.pendingChild) {\n this.pendingChild.destroy();\n }\n this.pendingChild = newChild;\n childToUpdate = this.pendingChild;\n }\n }\n else {\n if (this.pendingChild === null) {\n childToUpdate = this.currentChild;\n }\n else {\n childToUpdate = this.pendingChild;\n }\n }\n childToUpdate.updateAddressList(addressList, lbConfig, attributes);\n }\n exitIdle() {\n if (this.currentChild) {\n this.currentChild.resetBackoff();\n if (this.pendingChild) {\n this.pendingChild.resetBackoff();\n }\n }\n }\n resetBackoff() {\n if (this.currentChild) {\n this.currentChild.resetBackoff();\n if (this.pendingChild) {\n this.pendingChild.resetBackoff();\n }\n }\n }\n destroy() {\n if (this.currentChild) {\n this.currentChild.destroy();\n this.currentChild = null;\n }\n if (this.pendingChild) {\n this.pendingChild.destroy();\n this.pendingChild = null;\n }\n }\n getTypeName() {\n return TYPE_NAME;\n }\n}\nexports.ChildLoadBalancerHandler = ChildLoadBalancerHandler;\n//# sourceMappingURL=load-balancer-child-handler.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.setup = exports.PickFirstLoadBalancer = exports.PickFirstLoadBalancingConfig = void 0;\nconst load_balancer_1 = require(\"./load-balancer\");\nconst channel_1 = require(\"./channel\");\nconst picker_1 = require(\"./picker\");\nconst subchannel_1 = require(\"./subchannel\");\nconst logging = require(\"./logging\");\nconst constants_1 = require(\"./constants\");\nconst TRACER_NAME = 'pick_first';\nfunction trace(text) {\n logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text);\n}\nconst TYPE_NAME = 'pick_first';\n/**\n * Delay after starting a connection on a subchannel before starting a\n * connection on the next subchannel in the list, for Happy Eyeballs algorithm.\n */\nconst CONNECTION_DELAY_INTERVAL_MS = 250;\nclass PickFirstLoadBalancingConfig {\n getLoadBalancerName() {\n return TYPE_NAME;\n }\n constructor() { }\n toJsonObject() {\n return {\n [TYPE_NAME]: {}\n };\n }\n static createFromJson(obj) {\n return new PickFirstLoadBalancingConfig();\n }\n}\nexports.PickFirstLoadBalancingConfig = PickFirstLoadBalancingConfig;\n/**\n * Picker for a `PickFirstLoadBalancer` in the READY state. Always returns the\n * picked subchannel.\n */\nclass PickFirstPicker {\n constructor(subchannel) {\n this.subchannel = subchannel;\n }\n pick(pickArgs) {\n return {\n pickResultType: picker_1.PickResultType.COMPLETE,\n subchannel: this.subchannel,\n status: null,\n extraFilterFactory: null,\n onCallStarted: null,\n };\n }\n}\nclass PickFirstLoadBalancer {\n /**\n * Load balancer that attempts to connect to each backend in the address list\n * in order, and picks the first one that connects, using it for every\n * request.\n * @param channelControlHelper `ChannelControlHelper` instance provided by\n * this load balancer's owner.\n */\n constructor(channelControlHelper) {\n this.channelControlHelper = channelControlHelper;\n /**\n * The list of backend addresses most recently passed to `updateAddressList`.\n */\n this.latestAddressList = [];\n /**\n * The list of subchannels this load balancer is currently attempting to\n * connect to.\n */\n this.subchannels = [];\n /**\n * The current connectivity state of the load balancer.\n */\n this.currentState = channel_1.ConnectivityState.IDLE;\n /**\n * The index within the `subchannels` array of the subchannel with the most\n * recently started connection attempt.\n */\n this.currentSubchannelIndex = 0;\n /**\n * The currently picked subchannel used for making calls. Populated if\n * and only if the load balancer's current state is READY. In that case,\n * the subchannel's current state is also READY.\n */\n this.currentPick = null;\n this.triedAllSubchannels = false;\n this.subchannelStateCounts = {\n [channel_1.ConnectivityState.CONNECTING]: 0,\n [channel_1.ConnectivityState.IDLE]: 0,\n [channel_1.ConnectivityState.READY]: 0,\n [channel_1.ConnectivityState.SHUTDOWN]: 0,\n [channel_1.ConnectivityState.TRANSIENT_FAILURE]: 0,\n };\n this.subchannelStateListener = (subchannel, previousState, newState) => {\n this.subchannelStateCounts[previousState] -= 1;\n this.subchannelStateCounts[newState] += 1;\n /* If the subchannel we most recently attempted to start connecting\n * to goes into TRANSIENT_FAILURE, immediately try to start\n * connecting to the next one instead of waiting for the connection\n * delay timer. */\n if (subchannel === this.subchannels[this.currentSubchannelIndex] &&\n newState === channel_1.ConnectivityState.TRANSIENT_FAILURE) {\n this.startNextSubchannelConnecting();\n }\n if (newState === channel_1.ConnectivityState.READY) {\n this.pickSubchannel(subchannel);\n return;\n }\n else {\n if (this.triedAllSubchannels &&\n this.subchannelStateCounts[channel_1.ConnectivityState.IDLE] ===\n this.subchannels.length) {\n /* If all of the subchannels are IDLE we should go back to a\n * basic IDLE state where there is no subchannel list to avoid\n * holding unused resources */\n this.resetSubchannelList();\n this.updateState(channel_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this));\n return;\n }\n if (this.currentPick === null) {\n if (this.triedAllSubchannels) {\n let newLBState;\n if (this.subchannelStateCounts[channel_1.ConnectivityState.CONNECTING] > 0) {\n newLBState = channel_1.ConnectivityState.CONNECTING;\n }\n else if (this.subchannelStateCounts[channel_1.ConnectivityState.TRANSIENT_FAILURE] >\n 0) {\n newLBState = channel_1.ConnectivityState.TRANSIENT_FAILURE;\n }\n else {\n newLBState = channel_1.ConnectivityState.IDLE;\n }\n if (newLBState !== this.currentState) {\n if (newLBState === channel_1.ConnectivityState.TRANSIENT_FAILURE) {\n this.updateState(newLBState, new picker_1.UnavailablePicker());\n }\n else {\n this.updateState(newLBState, new picker_1.QueuePicker(this));\n }\n }\n }\n else {\n this.updateState(channel_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this));\n }\n }\n }\n };\n this.pickedSubchannelStateListener = (subchannel, previousState, newState) => {\n if (newState !== channel_1.ConnectivityState.READY) {\n this.currentPick = null;\n subchannel.unref();\n subchannel.removeConnectivityStateListener(this.pickedSubchannelStateListener);\n if (this.subchannels.length > 0) {\n if (this.triedAllSubchannels) {\n let newLBState;\n if (this.subchannelStateCounts[channel_1.ConnectivityState.CONNECTING] > 0) {\n newLBState = channel_1.ConnectivityState.CONNECTING;\n }\n else if (this.subchannelStateCounts[channel_1.ConnectivityState.TRANSIENT_FAILURE] >\n 0) {\n newLBState = channel_1.ConnectivityState.TRANSIENT_FAILURE;\n }\n else {\n newLBState = channel_1.ConnectivityState.IDLE;\n }\n if (newLBState === channel_1.ConnectivityState.TRANSIENT_FAILURE) {\n this.updateState(newLBState, new picker_1.UnavailablePicker());\n }\n else {\n this.updateState(newLBState, new picker_1.QueuePicker(this));\n }\n }\n else {\n this.updateState(channel_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this));\n }\n }\n else {\n /* We don't need to backoff here because this only happens if a\n * subchannel successfully connects then disconnects, so it will not\n * create a loop of attempting to connect to an unreachable backend\n */\n this.updateState(channel_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this));\n }\n }\n };\n this.connectionDelayTimeout = setTimeout(() => { }, 0);\n clearTimeout(this.connectionDelayTimeout);\n }\n startNextSubchannelConnecting() {\n if (this.triedAllSubchannels) {\n return;\n }\n for (const [index, subchannel] of this.subchannels.entries()) {\n if (index > this.currentSubchannelIndex) {\n const subchannelState = subchannel.getConnectivityState();\n if (subchannelState === channel_1.ConnectivityState.IDLE ||\n subchannelState === channel_1.ConnectivityState.CONNECTING) {\n this.startConnecting(index);\n return;\n }\n }\n }\n this.triedAllSubchannels = true;\n }\n /**\n * Have a single subchannel in the `subchannels` list start connecting.\n * @param subchannelIndex The index into the `subchannels` list.\n */\n startConnecting(subchannelIndex) {\n clearTimeout(this.connectionDelayTimeout);\n this.currentSubchannelIndex = subchannelIndex;\n if (this.subchannels[subchannelIndex].getConnectivityState() ===\n channel_1.ConnectivityState.IDLE) {\n trace('Start connecting to subchannel with address ' +\n this.subchannels[subchannelIndex].getAddress());\n process.nextTick(() => {\n this.subchannels[subchannelIndex].startConnecting();\n });\n }\n this.connectionDelayTimeout = setTimeout(() => {\n this.startNextSubchannelConnecting();\n }, CONNECTION_DELAY_INTERVAL_MS);\n }\n pickSubchannel(subchannel) {\n trace('Pick subchannel with address ' + subchannel.getAddress());\n if (this.currentPick !== null) {\n this.currentPick.unref();\n this.currentPick.removeConnectivityStateListener(this.pickedSubchannelStateListener);\n }\n this.currentPick = subchannel;\n this.updateState(channel_1.ConnectivityState.READY, new PickFirstPicker(subchannel));\n subchannel.addConnectivityStateListener(this.pickedSubchannelStateListener);\n subchannel.ref();\n this.resetSubchannelList();\n clearTimeout(this.connectionDelayTimeout);\n }\n updateState(newState, picker) {\n trace(channel_1.ConnectivityState[this.currentState] +\n ' -> ' +\n channel_1.ConnectivityState[newState]);\n this.currentState = newState;\n this.channelControlHelper.updateState(newState, picker);\n }\n resetSubchannelList() {\n for (const subchannel of this.subchannels) {\n subchannel.removeConnectivityStateListener(this.subchannelStateListener);\n subchannel.unref();\n }\n this.currentSubchannelIndex = 0;\n this.subchannelStateCounts = {\n [channel_1.ConnectivityState.CONNECTING]: 0,\n [channel_1.ConnectivityState.IDLE]: 0,\n [channel_1.ConnectivityState.READY]: 0,\n [channel_1.ConnectivityState.SHUTDOWN]: 0,\n [channel_1.ConnectivityState.TRANSIENT_FAILURE]: 0,\n };\n this.subchannels = [];\n this.triedAllSubchannels = false;\n }\n /**\n * Start connecting to the address list most recently passed to\n * `updateAddressList`.\n */\n connectToAddressList() {\n this.resetSubchannelList();\n trace('Connect to address list ' +\n this.latestAddressList.map((address) => subchannel_1.subchannelAddressToString(address)));\n this.subchannels = this.latestAddressList.map((address) => this.channelControlHelper.createSubchannel(address, {}));\n for (const subchannel of this.subchannels) {\n subchannel.ref();\n }\n for (const subchannel of this.subchannels) {\n subchannel.addConnectivityStateListener(this.subchannelStateListener);\n this.subchannelStateCounts[subchannel.getConnectivityState()] += 1;\n if (subchannel.getConnectivityState() === channel_1.ConnectivityState.READY) {\n this.pickSubchannel(subchannel);\n this.resetSubchannelList();\n return;\n }\n }\n for (const [index, subchannel] of this.subchannels.entries()) {\n const subchannelState = subchannel.getConnectivityState();\n if (subchannelState === channel_1.ConnectivityState.IDLE ||\n subchannelState === channel_1.ConnectivityState.CONNECTING) {\n this.startConnecting(index);\n if (this.currentPick === null) {\n this.updateState(channel_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this));\n }\n return;\n }\n }\n // If the code reaches this point, every subchannel must be in TRANSIENT_FAILURE\n if (this.currentPick === null) {\n this.updateState(channel_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker());\n }\n }\n updateAddressList(addressList, lbConfig) {\n // lbConfig has no useful information for pick first load balancing\n /* To avoid unnecessary churn, we only do something with this address list\n * if we're not currently trying to establish a connection, or if the new\n * address list is different from the existing one */\n if (this.subchannels.length === 0 ||\n !this.latestAddressList.every((value, index) => addressList[index] === value)) {\n this.latestAddressList = addressList;\n this.connectToAddressList();\n }\n }\n exitIdle() {\n for (const subchannel of this.subchannels) {\n subchannel.startConnecting();\n }\n if (this.currentState === channel_1.ConnectivityState.IDLE) {\n if (this.latestAddressList.length > 0) {\n this.connectToAddressList();\n }\n }\n if (this.currentState === channel_1.ConnectivityState.IDLE ||\n this.triedAllSubchannels) {\n this.channelControlHelper.requestReresolution();\n }\n }\n resetBackoff() {\n /* The pick first load balancer does not have a connection backoff, so this\n * does nothing */\n }\n destroy() {\n this.resetSubchannelList();\n if (this.currentPick !== null) {\n this.currentPick.unref();\n this.currentPick.removeConnectivityStateListener(this.pickedSubchannelStateListener);\n }\n }\n getTypeName() {\n return TYPE_NAME;\n }\n}\nexports.PickFirstLoadBalancer = PickFirstLoadBalancer;\nfunction setup() {\n load_balancer_1.registerLoadBalancerType(TYPE_NAME, PickFirstLoadBalancer, PickFirstLoadBalancingConfig);\n}\nexports.setup = setup;\n//# sourceMappingURL=load-balancer-pick-first.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.setup = exports.RoundRobinLoadBalancer = void 0;\nconst load_balancer_1 = require(\"./load-balancer\");\nconst channel_1 = require(\"./channel\");\nconst picker_1 = require(\"./picker\");\nconst subchannel_1 = require(\"./subchannel\");\nconst logging = require(\"./logging\");\nconst constants_1 = require(\"./constants\");\nconst TRACER_NAME = 'round_robin';\nfunction trace(text) {\n logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text);\n}\nconst TYPE_NAME = 'round_robin';\nclass RoundRobinLoadBalancingConfig {\n getLoadBalancerName() {\n return TYPE_NAME;\n }\n constructor() { }\n toJsonObject() {\n return {\n [TYPE_NAME]: {}\n };\n }\n static createFromJson(obj) {\n return new RoundRobinLoadBalancingConfig();\n }\n}\nclass RoundRobinPicker {\n constructor(subchannelList, nextIndex = 0) {\n this.subchannelList = subchannelList;\n this.nextIndex = nextIndex;\n }\n pick(pickArgs) {\n const pickedSubchannel = this.subchannelList[this.nextIndex];\n this.nextIndex = (this.nextIndex + 1) % this.subchannelList.length;\n return {\n pickResultType: picker_1.PickResultType.COMPLETE,\n subchannel: pickedSubchannel,\n status: null,\n extraFilterFactory: null,\n onCallStarted: null,\n };\n }\n /**\n * Check what the next subchannel returned would be. Used by the load\n * balancer implementation to preserve this part of the picker state if\n * possible when a subchannel connects or disconnects.\n */\n peekNextSubchannel() {\n return this.subchannelList[this.nextIndex];\n }\n}\nclass RoundRobinLoadBalancer {\n constructor(channelControlHelper) {\n this.channelControlHelper = channelControlHelper;\n this.subchannels = [];\n this.currentState = channel_1.ConnectivityState.IDLE;\n this.currentReadyPicker = null;\n this.subchannelStateCounts = {\n [channel_1.ConnectivityState.CONNECTING]: 0,\n [channel_1.ConnectivityState.IDLE]: 0,\n [channel_1.ConnectivityState.READY]: 0,\n [channel_1.ConnectivityState.SHUTDOWN]: 0,\n [channel_1.ConnectivityState.TRANSIENT_FAILURE]: 0,\n };\n this.subchannelStateListener = (subchannel, previousState, newState) => {\n this.subchannelStateCounts[previousState] -= 1;\n this.subchannelStateCounts[newState] += 1;\n this.calculateAndUpdateState();\n if (newState === channel_1.ConnectivityState.TRANSIENT_FAILURE ||\n newState === channel_1.ConnectivityState.IDLE) {\n this.channelControlHelper.requestReresolution();\n subchannel.startConnecting();\n }\n };\n }\n calculateAndUpdateState() {\n if (this.subchannelStateCounts[channel_1.ConnectivityState.READY] > 0) {\n const readySubchannels = this.subchannels.filter((subchannel) => subchannel.getConnectivityState() === channel_1.ConnectivityState.READY);\n let index = 0;\n if (this.currentReadyPicker !== null) {\n index = readySubchannels.indexOf(this.currentReadyPicker.peekNextSubchannel());\n if (index < 0) {\n index = 0;\n }\n }\n this.updateState(channel_1.ConnectivityState.READY, new RoundRobinPicker(readySubchannels, index));\n }\n else if (this.subchannelStateCounts[channel_1.ConnectivityState.CONNECTING] > 0) {\n this.updateState(channel_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this));\n }\n else if (this.subchannelStateCounts[channel_1.ConnectivityState.TRANSIENT_FAILURE] > 0) {\n this.updateState(channel_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker());\n }\n else {\n this.updateState(channel_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this));\n }\n }\n updateState(newState, picker) {\n trace(channel_1.ConnectivityState[this.currentState] +\n ' -> ' +\n channel_1.ConnectivityState[newState]);\n if (newState === channel_1.ConnectivityState.READY) {\n this.currentReadyPicker = picker;\n }\n else {\n this.currentReadyPicker = null;\n }\n this.currentState = newState;\n this.channelControlHelper.updateState(newState, picker);\n }\n resetSubchannelList() {\n for (const subchannel of this.subchannels) {\n subchannel.removeConnectivityStateListener(this.subchannelStateListener);\n subchannel.unref();\n }\n this.subchannelStateCounts = {\n [channel_1.ConnectivityState.CONNECTING]: 0,\n [channel_1.ConnectivityState.IDLE]: 0,\n [channel_1.ConnectivityState.READY]: 0,\n [channel_1.ConnectivityState.SHUTDOWN]: 0,\n [channel_1.ConnectivityState.TRANSIENT_FAILURE]: 0,\n };\n this.subchannels = [];\n }\n updateAddressList(addressList, lbConfig) {\n this.resetSubchannelList();\n trace('Connect to address list ' +\n addressList.map((address) => subchannel_1.subchannelAddressToString(address)));\n this.subchannels = addressList.map((address) => this.channelControlHelper.createSubchannel(address, {}));\n for (const subchannel of this.subchannels) {\n subchannel.ref();\n subchannel.addConnectivityStateListener(this.subchannelStateListener);\n const subchannelState = subchannel.getConnectivityState();\n this.subchannelStateCounts[subchannelState] += 1;\n if (subchannelState === channel_1.ConnectivityState.IDLE ||\n subchannelState === channel_1.ConnectivityState.TRANSIENT_FAILURE) {\n subchannel.startConnecting();\n }\n }\n this.calculateAndUpdateState();\n }\n exitIdle() {\n for (const subchannel of this.subchannels) {\n subchannel.startConnecting();\n }\n }\n resetBackoff() {\n /* The pick first load balancer does not have a connection backoff, so this\n * does nothing */\n }\n destroy() {\n this.resetSubchannelList();\n }\n getTypeName() {\n return TYPE_NAME;\n }\n}\nexports.RoundRobinLoadBalancer = RoundRobinLoadBalancer;\nfunction setup() {\n load_balancer_1.registerLoadBalancerType(TYPE_NAME, RoundRobinLoadBalancer, RoundRobinLoadBalancingConfig);\n}\nexports.setup = setup;\n//# sourceMappingURL=load-balancer-round-robin.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.registerAll = exports.validateLoadBalancingConfig = exports.getFirstUsableConfig = exports.isLoadBalancerNameRegistered = exports.createLoadBalancer = exports.registerLoadBalancerType = void 0;\nconst load_balancer_pick_first = require(\"./load-balancer-pick-first\");\nconst load_balancer_round_robin = require(\"./load-balancer-round-robin\");\nconst registeredLoadBalancerTypes = {};\nfunction registerLoadBalancerType(typeName, loadBalancerType, loadBalancingConfigType) {\n registeredLoadBalancerTypes[typeName] = {\n LoadBalancer: loadBalancerType,\n LoadBalancingConfig: loadBalancingConfigType\n };\n}\nexports.registerLoadBalancerType = registerLoadBalancerType;\nfunction createLoadBalancer(config, channelControlHelper) {\n const typeName = config.getLoadBalancerName();\n if (typeName in registeredLoadBalancerTypes) {\n return new registeredLoadBalancerTypes[typeName].LoadBalancer(channelControlHelper);\n }\n else {\n return null;\n }\n}\nexports.createLoadBalancer = createLoadBalancer;\nfunction isLoadBalancerNameRegistered(typeName) {\n return typeName in registeredLoadBalancerTypes;\n}\nexports.isLoadBalancerNameRegistered = isLoadBalancerNameRegistered;\nfunction getFirstUsableConfig(configs, defaultPickFirst = false) {\n for (const config of configs) {\n if (config.getLoadBalancerName() in registeredLoadBalancerTypes) {\n return config;\n }\n }\n if (defaultPickFirst) {\n return new load_balancer_pick_first.PickFirstLoadBalancingConfig();\n }\n else {\n return null;\n }\n}\nexports.getFirstUsableConfig = getFirstUsableConfig;\nfunction validateLoadBalancingConfig(obj) {\n if (!(obj !== null && (typeof obj === 'object'))) {\n throw new Error('Load balancing config must be an object');\n }\n const keys = Object.keys(obj);\n if (keys.length !== 1) {\n throw new Error('Provided load balancing config has multiple conflicting entries');\n }\n const typeName = keys[0];\n if (typeName in registeredLoadBalancerTypes) {\n return registeredLoadBalancerTypes[typeName].LoadBalancingConfig.createFromJson(obj[typeName]);\n }\n else {\n throw new Error(`Unrecognized load balancing config name ${typeName}`);\n }\n}\nexports.validateLoadBalancingConfig = validateLoadBalancingConfig;\nfunction registerAll() {\n load_balancer_pick_first.setup();\n load_balancer_round_robin.setup();\n}\nexports.registerAll = registerAll;\n//# sourceMappingURL=load-balancer.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nvar _a, _b, _c, _d;\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.trace = exports.log = exports.setLoggerVerbosity = exports.setLogger = exports.getLogger = void 0;\nconst constants_1 = require(\"./constants\");\nlet _logger = console;\nlet _logVerbosity = constants_1.LogVerbosity.ERROR;\nconst verbosityString = (_b = (_a = process.env.GRPC_NODE_VERBOSITY) !== null && _a !== void 0 ? _a : process.env.GRPC_VERBOSITY) !== null && _b !== void 0 ? _b : '';\nswitch (verbosityString) {\n case 'DEBUG':\n _logVerbosity = constants_1.LogVerbosity.DEBUG;\n break;\n case 'INFO':\n _logVerbosity = constants_1.LogVerbosity.INFO;\n break;\n case 'ERROR':\n _logVerbosity = constants_1.LogVerbosity.ERROR;\n break;\n default:\n // Ignore any other values\n}\nexports.getLogger = () => {\n return _logger;\n};\nexports.setLogger = (logger) => {\n _logger = logger;\n};\nexports.setLoggerVerbosity = (verbosity) => {\n _logVerbosity = verbosity;\n};\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexports.log = (severity, ...args) => {\n if (severity >= _logVerbosity && typeof _logger.error === 'function') {\n _logger.error(...args);\n }\n};\nconst tracersString = (_d = (_c = process.env.GRPC_NODE_TRACE) !== null && _c !== void 0 ? _c : process.env.GRPC_TRACE) !== null && _d !== void 0 ? _d : '';\nconst enabledTracers = tracersString.split(',');\nconst allEnabled = enabledTracers.includes('all');\nfunction trace(severity, tracer, text) {\n if (allEnabled || enabledTracers.includes(tracer)) {\n exports.log(severity, new Date().toISOString() + ' | ' + tracer + ' | ' + text);\n }\n}\nexports.trace = trace;\n//# sourceMappingURL=logging.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.loadPackageDefinition = exports.makeClientConstructor = void 0;\nconst client_1 = require(\"./client\");\n/**\n * Map with short names for each of the requester maker functions. Used in\n * makeClientConstructor\n * @private\n */\nconst requesterFuncs = {\n unary: client_1.Client.prototype.makeUnaryRequest,\n server_stream: client_1.Client.prototype.makeServerStreamRequest,\n client_stream: client_1.Client.prototype.makeClientStreamRequest,\n bidi: client_1.Client.prototype.makeBidiStreamRequest,\n};\n/**\n * Returns true, if given key is included in the blacklisted\n * keys.\n * @param key key for check, string.\n */\nfunction isPrototypePolluted(key) {\n return ['__proto__', 'prototype', 'constructor'].includes(key);\n}\n/**\n * Creates a constructor for a client with the given methods, as specified in\n * the methods argument. The resulting class will have an instance method for\n * each method in the service, which is a partial application of one of the\n * [Client]{@link grpc.Client} request methods, depending on `requestSerialize`\n * and `responseSerialize`, with the `method`, `serialize`, and `deserialize`\n * arguments predefined.\n * @param methods An object mapping method names to\n * method attributes\n * @param serviceName The fully qualified name of the service\n * @param classOptions An options object.\n * @return New client constructor, which is a subclass of\n * {@link grpc.Client}, and has the same arguments as that constructor.\n */\nfunction makeClientConstructor(methods, serviceName, classOptions) {\n if (!classOptions) {\n classOptions = {};\n }\n class ServiceClientImpl extends client_1.Client {\n }\n Object.keys(methods).forEach((name) => {\n if (isPrototypePolluted(name)) {\n return;\n }\n const attrs = methods[name];\n let methodType;\n // TODO(murgatroid99): Verify that we don't need this anymore\n if (typeof name === 'string' && name.charAt(0) === '$') {\n throw new Error('Method names cannot start with $');\n }\n if (attrs.requestStream) {\n if (attrs.responseStream) {\n methodType = 'bidi';\n }\n else {\n methodType = 'client_stream';\n }\n }\n else {\n if (attrs.responseStream) {\n methodType = 'server_stream';\n }\n else {\n methodType = 'unary';\n }\n }\n const serialize = attrs.requestSerialize;\n const deserialize = attrs.responseDeserialize;\n const methodFunc = partial(requesterFuncs[methodType], attrs.path, serialize, deserialize);\n ServiceClientImpl.prototype[name] = methodFunc;\n // Associate all provided attributes with the method\n Object.assign(ServiceClientImpl.prototype[name], attrs);\n if (attrs.originalName && !isPrototypePolluted(attrs.originalName)) {\n ServiceClientImpl.prototype[attrs.originalName] =\n ServiceClientImpl.prototype[name];\n }\n });\n ServiceClientImpl.service = methods;\n return ServiceClientImpl;\n}\nexports.makeClientConstructor = makeClientConstructor;\nfunction partial(fn, path, serialize, deserialize) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (...args) {\n return fn.call(this, path, serialize, deserialize, ...args);\n };\n}\nfunction isProtobufTypeDefinition(obj) {\n return 'format' in obj;\n}\n/**\n * Load a gRPC package definition as a gRPC object hierarchy.\n * @param packageDef The package definition object.\n * @return The resulting gRPC object.\n */\nfunction loadPackageDefinition(packageDef) {\n const result = {};\n for (const serviceFqn in packageDef) {\n if (Object.prototype.hasOwnProperty.call(packageDef, serviceFqn)) {\n const service = packageDef[serviceFqn];\n const nameComponents = serviceFqn.split('.');\n if (nameComponents.some((comp) => isPrototypePolluted(comp))) {\n continue;\n }\n const serviceName = nameComponents[nameComponents.length - 1];\n let current = result;\n for (const packageName of nameComponents.slice(0, -1)) {\n if (!current[packageName]) {\n current[packageName] = {};\n }\n current = current[packageName];\n }\n if (isProtobufTypeDefinition(service)) {\n current[serviceName] = service;\n }\n else {\n current[serviceName] = makeClientConstructor(service, serviceName, {});\n }\n }\n }\n return result;\n}\nexports.loadPackageDefinition = loadPackageDefinition;\n//# sourceMappingURL=make-client.js.map","\"use strict\";\n/*\n * Copyright 2020 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.MaxMessageSizeFilterFactory = exports.MaxMessageSizeFilter = void 0;\nconst filter_1 = require(\"./filter\");\nconst constants_1 = require(\"./constants\");\nclass MaxMessageSizeFilter extends filter_1.BaseFilter {\n constructor(options, callStream) {\n super();\n this.options = options;\n this.callStream = callStream;\n this.maxSendMessageSize = constants_1.DEFAULT_MAX_SEND_MESSAGE_LENGTH;\n this.maxReceiveMessageSize = constants_1.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH;\n if ('grpc.max_send_message_length' in options) {\n this.maxSendMessageSize = options['grpc.max_send_message_length'];\n }\n if ('grpc.max_receive_message_length' in options) {\n this.maxReceiveMessageSize = options['grpc.max_receive_message_length'];\n }\n }\n async sendMessage(message) {\n /* A configured size of -1 means that there is no limit, so skip the check\n * entirely */\n if (this.maxSendMessageSize === -1) {\n return message;\n }\n else {\n const concreteMessage = await message;\n if (concreteMessage.message.length > this.maxSendMessageSize) {\n this.callStream.cancelWithStatus(constants_1.Status.RESOURCE_EXHAUSTED, `Sent message larger than max (${concreteMessage.message.length} vs. ${this.maxSendMessageSize})`);\n return Promise.reject('Message too large');\n }\n else {\n return concreteMessage;\n }\n }\n }\n async receiveMessage(message) {\n /* A configured size of -1 means that there is no limit, so skip the check\n * entirely */\n if (this.maxReceiveMessageSize === -1) {\n return message;\n }\n else {\n const concreteMessage = await message;\n if (concreteMessage.length > this.maxReceiveMessageSize) {\n this.callStream.cancelWithStatus(constants_1.Status.RESOURCE_EXHAUSTED, `Received message larger than max (${concreteMessage.length} vs. ${this.maxReceiveMessageSize})`);\n return Promise.reject('Message too large');\n }\n else {\n return concreteMessage;\n }\n }\n }\n}\nexports.MaxMessageSizeFilter = MaxMessageSizeFilter;\nclass MaxMessageSizeFilterFactory {\n constructor(options) {\n this.options = options;\n }\n createFilter(callStream) {\n return new MaxMessageSizeFilter(this.options, callStream);\n }\n}\nexports.MaxMessageSizeFilterFactory = MaxMessageSizeFilterFactory;\n//# sourceMappingURL=max-message-size-filter.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Metadata = void 0;\nconst logging_1 = require(\"./logging\");\nconst constants_1 = require(\"./constants\");\nconst LEGAL_KEY_REGEX = /^[0-9a-z_.-]+$/;\nconst LEGAL_NON_BINARY_VALUE_REGEX = /^[ -~]*$/;\nfunction isLegalKey(key) {\n return LEGAL_KEY_REGEX.test(key);\n}\nfunction isLegalNonBinaryValue(value) {\n return LEGAL_NON_BINARY_VALUE_REGEX.test(value);\n}\nfunction isBinaryKey(key) {\n return key.endsWith('-bin');\n}\nfunction isCustomMetadata(key) {\n return !key.startsWith('grpc-');\n}\nfunction normalizeKey(key) {\n return key.toLowerCase();\n}\nfunction validate(key, value) {\n if (!isLegalKey(key)) {\n throw new Error('Metadata key \"' + key + '\" contains illegal characters');\n }\n if (value !== null && value !== undefined) {\n if (isBinaryKey(key)) {\n if (!(value instanceof Buffer)) {\n throw new Error(\"keys that end with '-bin' must have Buffer values\");\n }\n }\n else {\n if (value instanceof Buffer) {\n throw new Error(\"keys that don't end with '-bin' must have String values\");\n }\n if (!isLegalNonBinaryValue(value)) {\n throw new Error('Metadata string value \"' + value + '\" contains illegal characters');\n }\n }\n }\n}\n/**\n * A class for storing metadata. Keys are normalized to lowercase ASCII.\n */\nclass Metadata {\n constructor(options) {\n this.internalRepr = new Map();\n if (options === undefined) {\n this.options = {};\n }\n else {\n this.options = options;\n }\n }\n /**\n * Sets the given value for the given key by replacing any other values\n * associated with that key. Normalizes the key.\n * @param key The key to whose value should be set.\n * @param value The value to set. Must be a buffer if and only\n * if the normalized key ends with '-bin'.\n */\n set(key, value) {\n key = normalizeKey(key);\n validate(key, value);\n this.internalRepr.set(key, [value]);\n }\n /**\n * Adds the given value for the given key by appending to a list of previous\n * values associated with that key. Normalizes the key.\n * @param key The key for which a new value should be appended.\n * @param value The value to add. Must be a buffer if and only\n * if the normalized key ends with '-bin'.\n */\n add(key, value) {\n key = normalizeKey(key);\n validate(key, value);\n const existingValue = this.internalRepr.get(key);\n if (existingValue === undefined) {\n this.internalRepr.set(key, [value]);\n }\n else {\n existingValue.push(value);\n }\n }\n /**\n * Removes the given key and any associated values. Normalizes the key.\n * @param key The key whose values should be removed.\n */\n remove(key) {\n key = normalizeKey(key);\n validate(key);\n this.internalRepr.delete(key);\n }\n /**\n * Gets a list of all values associated with the key. Normalizes the key.\n * @param key The key whose value should be retrieved.\n * @return A list of values associated with the given key.\n */\n get(key) {\n key = normalizeKey(key);\n validate(key);\n return this.internalRepr.get(key) || [];\n }\n /**\n * Gets a plain object mapping each key to the first value associated with it.\n * This reflects the most common way that people will want to see metadata.\n * @return A key/value mapping of the metadata.\n */\n getMap() {\n const result = {};\n this.internalRepr.forEach((values, key) => {\n if (values.length > 0) {\n const v = values[0];\n result[key] = v instanceof Buffer ? v.slice() : v;\n }\n });\n return result;\n }\n /**\n * Clones the metadata object.\n * @return The newly cloned object.\n */\n clone() {\n const newMetadata = new Metadata(this.options);\n const newInternalRepr = newMetadata.internalRepr;\n this.internalRepr.forEach((value, key) => {\n const clonedValue = value.map((v) => {\n if (v instanceof Buffer) {\n return Buffer.from(v);\n }\n else {\n return v;\n }\n });\n newInternalRepr.set(key, clonedValue);\n });\n return newMetadata;\n }\n /**\n * Merges all key-value pairs from a given Metadata object into this one.\n * If both this object and the given object have values in the same key,\n * values from the other Metadata object will be appended to this object's\n * values.\n * @param other A Metadata object.\n */\n merge(other) {\n other.internalRepr.forEach((values, key) => {\n const mergedValue = (this.internalRepr.get(key) || []).concat(values);\n this.internalRepr.set(key, mergedValue);\n });\n }\n setOptions(options) {\n this.options = options;\n }\n getOptions() {\n return this.options;\n }\n /**\n * Creates an OutgoingHttpHeaders object that can be used with the http2 API.\n */\n toHttp2Headers() {\n // NOTE: Node <8.9 formats http2 headers incorrectly.\n const result = {};\n this.internalRepr.forEach((values, key) => {\n // We assume that the user's interaction with this object is limited to\n // through its public API (i.e. keys and values are already validated).\n result[key] = values.map((value) => {\n if (value instanceof Buffer) {\n return value.toString('base64');\n }\n else {\n return value;\n }\n });\n });\n return result;\n }\n // For compatibility with the other Metadata implementation\n _getCoreRepresentation() {\n return this.internalRepr;\n }\n /**\n * Returns a new Metadata object based fields in a given IncomingHttpHeaders\n * object.\n * @param headers An IncomingHttpHeaders object.\n */\n static fromHttp2Headers(headers) {\n const result = new Metadata();\n Object.keys(headers).forEach((key) => {\n // Reserved headers (beginning with `:`) are not valid keys.\n if (key.charAt(0) === ':') {\n return;\n }\n const values = headers[key];\n try {\n if (isBinaryKey(key)) {\n if (Array.isArray(values)) {\n values.forEach((value) => {\n result.add(key, Buffer.from(value, 'base64'));\n });\n }\n else if (values !== undefined) {\n if (isCustomMetadata(key)) {\n values.split(',').forEach((v) => {\n result.add(key, Buffer.from(v.trim(), 'base64'));\n });\n }\n else {\n result.add(key, Buffer.from(values, 'base64'));\n }\n }\n }\n else {\n if (Array.isArray(values)) {\n values.forEach((value) => {\n result.add(key, value);\n });\n }\n else if (values !== undefined) {\n result.add(key, values);\n }\n }\n }\n catch (error) {\n const message = `Failed to add metadata entry ${key}: ${values}. ${error.message}. For more information see https://github.com/grpc/grpc-node/issues/1173`;\n logging_1.log(constants_1.LogVerbosity.ERROR, message);\n }\n });\n return result;\n }\n}\nexports.Metadata = Metadata;\n//# sourceMappingURL=metadata.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.QueuePicker = exports.UnavailablePicker = exports.PickResultType = void 0;\nconst metadata_1 = require(\"./metadata\");\nconst constants_1 = require(\"./constants\");\nvar PickResultType;\n(function (PickResultType) {\n PickResultType[PickResultType[\"COMPLETE\"] = 0] = \"COMPLETE\";\n PickResultType[PickResultType[\"QUEUE\"] = 1] = \"QUEUE\";\n PickResultType[PickResultType[\"TRANSIENT_FAILURE\"] = 2] = \"TRANSIENT_FAILURE\";\n PickResultType[PickResultType[\"DROP\"] = 3] = \"DROP\";\n})(PickResultType = exports.PickResultType || (exports.PickResultType = {}));\n/**\n * A standard picker representing a load balancer in the TRANSIENT_FAILURE\n * state. Always responds to every pick request with an UNAVAILABLE status.\n */\nclass UnavailablePicker {\n constructor(status) {\n if (status !== undefined) {\n this.status = status;\n }\n else {\n this.status = {\n code: constants_1.Status.UNAVAILABLE,\n details: 'No connection established',\n metadata: new metadata_1.Metadata(),\n };\n }\n }\n pick(pickArgs) {\n return {\n pickResultType: PickResultType.TRANSIENT_FAILURE,\n subchannel: null,\n status: this.status,\n extraFilterFactory: null,\n onCallStarted: null,\n };\n }\n}\nexports.UnavailablePicker = UnavailablePicker;\n/**\n * A standard picker representing a load balancer in the IDLE or CONNECTING\n * state. Always responds to every pick request with a QUEUE pick result\n * indicating that the pick should be tried again with the next `Picker`. Also\n * reports back to the load balancer that a connection should be established\n * once any pick is attempted.\n */\nclass QueuePicker {\n // Constructed with a load balancer. Calls exitIdle on it the first time pick is called\n constructor(loadBalancer) {\n this.loadBalancer = loadBalancer;\n this.calledExitIdle = false;\n }\n pick(pickArgs) {\n if (!this.calledExitIdle) {\n process.nextTick(() => {\n this.loadBalancer.exitIdle();\n });\n this.calledExitIdle = true;\n }\n return {\n pickResultType: PickResultType.QUEUE,\n subchannel: null,\n status: null,\n extraFilterFactory: null,\n onCallStarted: null,\n };\n }\n}\nexports.QueuePicker = QueuePicker;\n//# sourceMappingURL=picker.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.setup = void 0;\nconst resolver_1 = require(\"./resolver\");\nconst dns = require(\"dns\");\nconst util = require(\"util\");\nconst service_config_1 = require(\"./service-config\");\nconst constants_1 = require(\"./constants\");\nconst metadata_1 = require(\"./metadata\");\nconst logging = require(\"./logging\");\nconst constants_2 = require(\"./constants\");\nconst uri_parser_1 = require(\"./uri-parser\");\nconst net_1 = require(\"net\");\nconst TRACER_NAME = 'dns_resolver';\nfunction trace(text) {\n logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, text);\n}\n/**\n * The default TCP port to connect to if not explicitly specified in the target.\n */\nconst DEFAULT_PORT = 443;\nconst resolveTxtPromise = util.promisify(dns.resolveTxt);\nconst dnsLookupPromise = util.promisify(dns.lookup);\n/**\n * Merge any number of arrays into a single alternating array\n * @param arrays\n */\nfunction mergeArrays(...arrays) {\n const result = [];\n for (let i = 0; i <\n Math.max.apply(null, arrays.map((array) => array.length)); i++) {\n for (const array of arrays) {\n if (i < array.length) {\n result.push(array[i]);\n }\n }\n }\n return result;\n}\n/**\n * Resolver implementation that handles DNS names and IP addresses.\n */\nclass DnsResolver {\n constructor(target, listener, channelOptions) {\n var _a, _b;\n this.target = target;\n this.listener = listener;\n this.pendingLookupPromise = null;\n this.pendingTxtPromise = null;\n this.latestLookupResult = null;\n this.latestServiceConfig = null;\n this.latestServiceConfigError = null;\n trace('Resolver constructed for target ' + uri_parser_1.uriToString(target));\n const hostPort = uri_parser_1.splitHostPort(target.path);\n if (hostPort === null) {\n this.ipResult = null;\n this.dnsHostname = null;\n this.port = null;\n }\n else {\n if (net_1.isIPv4(hostPort.host) || net_1.isIPv6(hostPort.host)) {\n this.ipResult = [\n {\n host: hostPort.host,\n port: (_a = hostPort.port) !== null && _a !== void 0 ? _a : DEFAULT_PORT,\n },\n ];\n this.dnsHostname = null;\n this.port = null;\n }\n else {\n this.ipResult = null;\n this.dnsHostname = hostPort.host;\n this.port = (_b = hostPort.port) !== null && _b !== void 0 ? _b : DEFAULT_PORT;\n }\n }\n this.percentage = Math.random() * 100;\n this.defaultResolutionError = {\n code: constants_1.Status.UNAVAILABLE,\n details: `Name resolution failed for target ${uri_parser_1.uriToString(this.target)}`,\n metadata: new metadata_1.Metadata(),\n };\n }\n /**\n * If the target is an IP address, just provide that address as a result.\n * Otherwise, initiate A, AAAA, and TXT lookups\n */\n startResolution() {\n if (this.ipResult !== null) {\n trace('Returning IP address for target ' + uri_parser_1.uriToString(this.target));\n setImmediate(() => {\n this.listener.onSuccessfulResolution(this.ipResult, null, null, {});\n });\n return;\n }\n if (this.dnsHostname === null) {\n setImmediate(() => {\n this.listener.onError({\n code: constants_1.Status.UNAVAILABLE,\n details: `Failed to parse DNS address ${uri_parser_1.uriToString(this.target)}`,\n metadata: new metadata_1.Metadata(),\n });\n });\n }\n else {\n /* We clear out latestLookupResult here to ensure that it contains the\n * latest result since the last time we started resolving. That way, the\n * TXT resolution handler can use it, but only if it finishes second. We\n * don't clear out any previous service config results because it's\n * better to use a service config that's slightly out of date than to\n * revert to an effectively blank one. */\n this.latestLookupResult = null;\n const hostname = this.dnsHostname;\n /* We lookup both address families here and then split them up later\n * because when looking up a single family, dns.lookup outputs an error\n * if the name exists but there are no records for that family, and that\n * error is indistinguishable from other kinds of errors */\n this.pendingLookupPromise = dnsLookupPromise(hostname, { all: true });\n this.pendingLookupPromise.then((addressList) => {\n this.pendingLookupPromise = null;\n const ip4Addresses = addressList.filter((addr) => addr.family === 4);\n const ip6Addresses = addressList.filter((addr) => addr.family === 6);\n this.latestLookupResult = mergeArrays(ip6Addresses, ip4Addresses).map((addr) => ({ host: addr.address, port: +this.port }));\n const allAddressesString = '[' +\n this.latestLookupResult\n .map((addr) => addr.host + ':' + addr.port)\n .join(',') +\n ']';\n trace('Resolved addresses for target ' +\n uri_parser_1.uriToString(this.target) +\n ': ' +\n allAddressesString);\n if (this.latestLookupResult.length === 0) {\n this.listener.onError(this.defaultResolutionError);\n return;\n }\n /* If the TXT lookup has not yet finished, both of the last two\n * arguments will be null, which is the equivalent of getting an\n * empty TXT response. When the TXT lookup does finish, its handler\n * can update the service config by using the same address list */\n this.listener.onSuccessfulResolution(this.latestLookupResult, this.latestServiceConfig, this.latestServiceConfigError, {});\n }, (err) => {\n trace('Resolution error for target ' +\n uri_parser_1.uriToString(this.target) +\n ': ' +\n err.message);\n this.pendingLookupPromise = null;\n this.listener.onError(this.defaultResolutionError);\n });\n /* If there already is a still-pending TXT resolution, we can just use\n * that result when it comes in */\n if (this.pendingTxtPromise === null) {\n /* We handle the TXT query promise differently than the others because\n * the name resolution attempt as a whole is a success even if the TXT\n * lookup fails */\n this.pendingTxtPromise = resolveTxtPromise(hostname);\n this.pendingTxtPromise.then((txtRecord) => {\n this.pendingTxtPromise = null;\n try {\n this.latestServiceConfig = service_config_1.extractAndSelectServiceConfig(txtRecord, this.percentage);\n }\n catch (err) {\n this.latestServiceConfigError = {\n code: constants_1.Status.UNAVAILABLE,\n details: 'Parsing service config failed',\n metadata: new metadata_1.Metadata(),\n };\n }\n if (this.latestLookupResult !== null) {\n /* We rely here on the assumption that calling this function with\n * identical parameters will be essentialy idempotent, and calling\n * it with the same address list and a different service config\n * should result in a fast and seamless switchover. */\n this.listener.onSuccessfulResolution(this.latestLookupResult, this.latestServiceConfig, this.latestServiceConfigError, {});\n }\n }, (err) => {\n /* If TXT lookup fails we should do nothing, which means that we\n * continue to use the result of the most recent successful lookup,\n * or the default null config object if there has never been a\n * successful lookup. We do not set the latestServiceConfigError\n * here because that is specifically used for response validation\n * errors. We still need to handle this error so that it does not\n * bubble up as an unhandled promise rejection. */\n });\n }\n }\n }\n updateResolution() {\n trace('Resolution update requested for target ' + uri_parser_1.uriToString(this.target));\n if (this.pendingLookupPromise === null) {\n this.startResolution();\n }\n }\n destroy() {\n /* Do nothing. There is not a practical way to cancel in-flight DNS\n * requests, and after this function is called we can expect that\n * updateResolution will not be called again. */\n }\n /**\n * Get the default authority for the given target. For IP targets, that is\n * the IP address. For DNS targets, it is the hostname.\n * @param target\n */\n static getDefaultAuthority(target) {\n return target.path;\n }\n}\n/**\n * Set up the DNS resolver class by registering it as the handler for the\n * \"dns:\" prefix and as the default resolver.\n */\nfunction setup() {\n resolver_1.registerResolver('dns', DnsResolver);\n resolver_1.registerDefaultScheme('dns');\n}\nexports.setup = setup;\n//# sourceMappingURL=resolver-dns.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.setup = void 0;\nconst resolver_1 = require(\"./resolver\");\nclass UdsResolver {\n constructor(target, listener, channelOptions) {\n this.listener = listener;\n this.addresses = [];\n let path;\n if (target.authority === '') {\n path = '/' + target.path;\n }\n else {\n path = target.path;\n }\n this.addresses = [{ path }];\n }\n updateResolution() {\n process.nextTick(this.listener.onSuccessfulResolution, this.addresses, null, null, {});\n }\n destroy() {\n // This resolver owns no resources, so we do nothing here.\n }\n static getDefaultAuthority(target) {\n return 'localhost';\n }\n}\nfunction setup() {\n resolver_1.registerResolver('unix', UdsResolver);\n}\nexports.setup = setup;\n//# sourceMappingURL=resolver-uds.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.registerAll = exports.mapUriDefaultScheme = exports.getDefaultAuthority = exports.createResolver = exports.registerDefaultScheme = exports.registerResolver = void 0;\nconst resolver_dns = require(\"./resolver-dns\");\nconst resolver_uds = require(\"./resolver-uds\");\nconst uri_parser_1 = require(\"./uri-parser\");\nconst registeredResolvers = {};\nlet defaultScheme = null;\n/**\n * Register a resolver class to handle target names prefixed with the `prefix`\n * string. This prefix should correspond to a URI scheme name listed in the\n * [gRPC Name Resolution document](https://github.com/grpc/grpc/blob/master/doc/naming.md)\n * @param prefix\n * @param resolverClass\n */\nfunction registerResolver(scheme, resolverClass) {\n registeredResolvers[scheme] = resolverClass;\n}\nexports.registerResolver = registerResolver;\n/**\n * Register a default resolver to handle target names that do not start with\n * any registered prefix.\n * @param resolverClass\n */\nfunction registerDefaultScheme(scheme) {\n defaultScheme = scheme;\n}\nexports.registerDefaultScheme = registerDefaultScheme;\n/**\n * Create a name resolver for the specified target, if possible. Throws an\n * error if no such name resolver can be created.\n * @param target\n * @param listener\n */\nfunction createResolver(target, listener, options) {\n if (target.scheme !== undefined && target.scheme in registeredResolvers) {\n return new registeredResolvers[target.scheme](target, listener, options);\n }\n else {\n throw new Error(`No resolver could be created for target ${uri_parser_1.uriToString(target)}`);\n }\n}\nexports.createResolver = createResolver;\n/**\n * Get the default authority for the specified target, if possible. Throws an\n * error if no registered name resolver can parse that target string.\n * @param target\n */\nfunction getDefaultAuthority(target) {\n if (target.scheme !== undefined && target.scheme in registeredResolvers) {\n return registeredResolvers[target.scheme].getDefaultAuthority(target);\n }\n else {\n throw new Error(`Invalid target ${uri_parser_1.uriToString(target)}`);\n }\n}\nexports.getDefaultAuthority = getDefaultAuthority;\nfunction mapUriDefaultScheme(target) {\n if (target.scheme === undefined || !(target.scheme in registeredResolvers)) {\n if (defaultScheme !== null) {\n return {\n scheme: defaultScheme,\n authority: undefined,\n path: uri_parser_1.uriToString(target),\n };\n }\n else {\n return null;\n }\n }\n return target;\n}\nexports.mapUriDefaultScheme = mapUriDefaultScheme;\nfunction registerAll() {\n resolver_dns.setup();\n resolver_uds.setup();\n}\nexports.registerAll = registerAll;\n//# sourceMappingURL=resolver.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ResolvingLoadBalancer = void 0;\nconst load_balancer_1 = require(\"./load-balancer\");\nconst service_config_1 = require(\"./service-config\");\nconst channel_1 = require(\"./channel\");\nconst resolver_1 = require(\"./resolver\");\nconst picker_1 = require(\"./picker\");\nconst backoff_timeout_1 = require(\"./backoff-timeout\");\nconst constants_1 = require(\"./constants\");\nconst metadata_1 = require(\"./metadata\");\nconst logging = require(\"./logging\");\nconst constants_2 = require(\"./constants\");\nconst uri_parser_1 = require(\"./uri-parser\");\nconst load_balancer_child_handler_1 = require(\"./load-balancer-child-handler\");\nconst TRACER_NAME = 'resolving_load_balancer';\nfunction trace(text) {\n logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, text);\n}\nconst DEFAULT_LOAD_BALANCER_NAME = 'pick_first';\nclass ResolvingLoadBalancer {\n /**\n * Wrapper class that behaves like a `LoadBalancer` and also handles name\n * resolution internally.\n * @param target The address of the backend to connect to.\n * @param channelControlHelper `ChannelControlHelper` instance provided by\n * this load balancer's owner.\n * @param defaultServiceConfig The default service configuration to be used\n * if none is provided by the name resolver. A `null` value indicates\n * that the default behavior should be the default unconfigured behavior.\n * In practice, that means using the \"pick first\" load balancer\n * implmentation\n */\n constructor(target, channelControlHelper, channelOptions) {\n this.target = target;\n this.channelControlHelper = channelControlHelper;\n this.channelOptions = channelOptions;\n this.latestChildState = channel_1.ConnectivityState.IDLE;\n this.latestChildPicker = new picker_1.QueuePicker(this);\n /**\n * This resolving load balancer's current connectivity state.\n */\n this.currentState = channel_1.ConnectivityState.IDLE;\n /**\n * The service config object from the last successful resolution, if\n * available. A value of null indicates that we have not yet received a valid\n * service config from the resolver.\n */\n this.previousServiceConfig = null;\n /**\n * Indicates whether we should attempt to resolve again after the backoff\n * timer runs out.\n */\n this.continueResolving = false;\n if (channelOptions['grpc.service_config']) {\n this.defaultServiceConfig = service_config_1.validateServiceConfig(JSON.parse(channelOptions['grpc.service_config']));\n }\n else {\n this.defaultServiceConfig = {\n loadBalancingConfig: [],\n methodConfig: [],\n };\n }\n this.updateState(channel_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this));\n this.childLoadBalancer = new load_balancer_child_handler_1.ChildLoadBalancerHandler({\n createSubchannel: channelControlHelper.createSubchannel.bind(channelControlHelper),\n requestReresolution: () => {\n /* If the backoffTimeout is running, we're still backing off from\n * making resolve requests, so we shouldn't make another one here.\n * In that case, the backoff timer callback will call\n * updateResolution */\n if (this.backoffTimeout.isRunning()) {\n this.continueResolving = true;\n }\n else {\n this.updateResolution();\n }\n },\n updateState: (newState, picker) => {\n this.latestChildState = newState;\n this.latestChildPicker = picker;\n this.updateState(newState, picker);\n },\n });\n this.innerResolver = resolver_1.createResolver(target, {\n onSuccessfulResolution: (addressList, serviceConfig, serviceConfigError, attributes) => {\n var _a;\n let workingServiceConfig = null;\n /* This first group of conditionals implements the algorithm described\n * in https://github.com/grpc/proposal/blob/master/A21-service-config-error-handling.md\n * in the section called \"Behavior on receiving a new gRPC Config\".\n */\n if (serviceConfig === null) {\n // Step 4 and 5\n if (serviceConfigError === null) {\n // Step 5\n this.previousServiceConfig = null;\n workingServiceConfig = this.defaultServiceConfig;\n }\n else {\n // Step 4\n if (this.previousServiceConfig === null) {\n // Step 4.ii\n this.handleResolutionFailure(serviceConfigError);\n }\n else {\n // Step 4.i\n workingServiceConfig = this.previousServiceConfig;\n }\n }\n }\n else {\n // Step 3\n workingServiceConfig = serviceConfig;\n this.previousServiceConfig = serviceConfig;\n }\n const workingConfigList = (_a = workingServiceConfig === null || workingServiceConfig === void 0 ? void 0 : workingServiceConfig.loadBalancingConfig) !== null && _a !== void 0 ? _a : [];\n const loadBalancingConfig = load_balancer_1.getFirstUsableConfig(workingConfigList, true);\n if (loadBalancingConfig === null) {\n // There were load balancing configs but none are supported. This counts as a resolution failure\n this.handleResolutionFailure({\n code: constants_1.Status.UNAVAILABLE,\n details: 'All load balancer options in service config are not compatible',\n metadata: new metadata_1.Metadata(),\n });\n return;\n }\n this.childLoadBalancer.updateAddressList(addressList, loadBalancingConfig, attributes);\n },\n onError: (error) => {\n this.handleResolutionFailure(error);\n },\n }, channelOptions);\n this.backoffTimeout = new backoff_timeout_1.BackoffTimeout(() => {\n if (this.continueResolving) {\n this.updateResolution();\n this.continueResolving = false;\n }\n else {\n this.updateState(this.latestChildState, this.latestChildPicker);\n }\n });\n this.backoffTimeout.unref();\n }\n updateResolution() {\n this.innerResolver.updateResolution();\n if (this.currentState === channel_1.ConnectivityState.IDLE) {\n this.updateState(channel_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this));\n }\n }\n updateState(connectivityState, picker) {\n trace(uri_parser_1.uriToString(this.target) +\n ' ' +\n channel_1.ConnectivityState[this.currentState] +\n ' -> ' +\n channel_1.ConnectivityState[connectivityState]);\n // Ensure that this.exitIdle() is called by the picker\n if (connectivityState === channel_1.ConnectivityState.IDLE) {\n picker = new picker_1.QueuePicker(this);\n }\n this.currentState = connectivityState;\n this.channelControlHelper.updateState(connectivityState, picker);\n }\n handleResolutionFailure(error) {\n if (this.latestChildState === channel_1.ConnectivityState.IDLE) {\n this.updateState(channel_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(error));\n }\n this.backoffTimeout.runOnce();\n }\n exitIdle() {\n this.childLoadBalancer.exitIdle();\n if (this.currentState === channel_1.ConnectivityState.IDLE) {\n if (this.backoffTimeout.isRunning()) {\n this.continueResolving = true;\n }\n else {\n this.updateResolution();\n }\n this.updateState(channel_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this));\n }\n }\n updateAddressList(addressList, lbConfig) {\n throw new Error('updateAddressList not supported on ResolvingLoadBalancer');\n }\n resetBackoff() {\n this.backoffTimeout.reset();\n this.childLoadBalancer.resetBackoff();\n }\n destroy() {\n this.childLoadBalancer.destroy();\n this.innerResolver.destroy();\n this.updateState(channel_1.ConnectivityState.SHUTDOWN, new picker_1.UnavailablePicker());\n }\n getTypeName() {\n return 'resolving_load_balancer';\n }\n}\nexports.ResolvingLoadBalancer = ResolvingLoadBalancer;\n//# sourceMappingURL=resolving-load-balancer.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Http2ServerCallStream = exports.ServerDuplexStreamImpl = exports.ServerWritableStreamImpl = exports.ServerReadableStreamImpl = exports.ServerUnaryCallImpl = void 0;\nconst events_1 = require(\"events\");\nconst http2 = require(\"http2\");\nconst stream_1 = require(\"stream\");\nconst constants_1 = require(\"./constants\");\nconst metadata_1 = require(\"./metadata\");\nconst stream_decoder_1 = require(\"./stream-decoder\");\nconst logging = require(\"./logging\");\nconst TRACER_NAME = 'server_call';\nfunction trace(text) {\n logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text);\n}\nconst GRPC_ACCEPT_ENCODING_HEADER = 'grpc-accept-encoding';\nconst GRPC_ENCODING_HEADER = 'grpc-encoding';\nconst GRPC_MESSAGE_HEADER = 'grpc-message';\nconst GRPC_STATUS_HEADER = 'grpc-status';\nconst GRPC_TIMEOUT_HEADER = 'grpc-timeout';\nconst DEADLINE_REGEX = /(\\d{1,8})\\s*([HMSmun])/;\nconst deadlineUnitsToMs = {\n H: 3600000,\n M: 60000,\n S: 1000,\n m: 1,\n u: 0.001,\n n: 0.000001,\n};\nconst defaultResponseHeaders = {\n // TODO(cjihrig): Remove these encoding headers from the default response\n // once compression is integrated.\n [GRPC_ACCEPT_ENCODING_HEADER]: 'identity',\n [GRPC_ENCODING_HEADER]: 'identity',\n [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_OK,\n [http2.constants.HTTP2_HEADER_CONTENT_TYPE]: 'application/grpc+proto',\n};\nconst defaultResponseOptions = {\n waitForTrailers: true,\n};\nclass ServerUnaryCallImpl extends events_1.EventEmitter {\n constructor(call, metadata, request) {\n super();\n this.call = call;\n this.metadata = metadata;\n this.request = request;\n this.cancelled = false;\n this.call.setupSurfaceCall(this);\n }\n getPeer() {\n return this.call.getPeer();\n }\n sendMetadata(responseMetadata) {\n this.call.sendMetadata(responseMetadata);\n }\n getDeadline() {\n return this.call.getDeadline();\n }\n}\nexports.ServerUnaryCallImpl = ServerUnaryCallImpl;\nclass ServerReadableStreamImpl extends stream_1.Readable {\n constructor(call, metadata, deserialize) {\n super({ objectMode: true });\n this.call = call;\n this.metadata = metadata;\n this.deserialize = deserialize;\n this.cancelled = false;\n this.call.setupSurfaceCall(this);\n this.call.setupReadable(this);\n }\n _read(size) {\n if (!this.call.consumeUnpushedMessages(this)) {\n return;\n }\n this.call.resume();\n }\n getPeer() {\n return this.call.getPeer();\n }\n sendMetadata(responseMetadata) {\n this.call.sendMetadata(responseMetadata);\n }\n getDeadline() {\n return this.call.getDeadline();\n }\n}\nexports.ServerReadableStreamImpl = ServerReadableStreamImpl;\nclass ServerWritableStreamImpl extends stream_1.Writable {\n constructor(call, metadata, serialize, request) {\n super({ objectMode: true });\n this.call = call;\n this.metadata = metadata;\n this.serialize = serialize;\n this.request = request;\n this.cancelled = false;\n this.trailingMetadata = new metadata_1.Metadata();\n this.call.setupSurfaceCall(this);\n this.on('error', (err) => {\n this.call.sendError(err);\n this.end();\n });\n }\n getPeer() {\n return this.call.getPeer();\n }\n sendMetadata(responseMetadata) {\n this.call.sendMetadata(responseMetadata);\n }\n getDeadline() {\n return this.call.getDeadline();\n }\n _write(chunk, encoding, \n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n callback) {\n try {\n const response = this.call.serializeMessage(chunk);\n if (!this.call.write(response)) {\n this.call.once('drain', callback);\n return;\n }\n }\n catch (err) {\n err.code = constants_1.Status.INTERNAL;\n this.emit('error', err);\n }\n callback();\n }\n _final(callback) {\n this.call.sendStatus({\n code: constants_1.Status.OK,\n details: 'OK',\n metadata: this.trailingMetadata,\n });\n callback(null);\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n end(metadata) {\n if (metadata) {\n this.trailingMetadata = metadata;\n }\n super.end();\n }\n}\nexports.ServerWritableStreamImpl = ServerWritableStreamImpl;\nclass ServerDuplexStreamImpl extends stream_1.Duplex {\n constructor(call, metadata, serialize, deserialize) {\n super({ objectMode: true });\n this.call = call;\n this.metadata = metadata;\n this.serialize = serialize;\n this.deserialize = deserialize;\n this.cancelled = false;\n this.trailingMetadata = new metadata_1.Metadata();\n this.call.setupSurfaceCall(this);\n this.call.setupReadable(this);\n this.on('error', (err) => {\n this.call.sendError(err);\n this.end();\n });\n }\n getPeer() {\n return this.call.getPeer();\n }\n sendMetadata(responseMetadata) {\n this.call.sendMetadata(responseMetadata);\n }\n getDeadline() {\n return this.call.getDeadline();\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n end(metadata) {\n if (metadata) {\n this.trailingMetadata = metadata;\n }\n super.end();\n }\n}\nexports.ServerDuplexStreamImpl = ServerDuplexStreamImpl;\nServerDuplexStreamImpl.prototype._read =\n ServerReadableStreamImpl.prototype._read;\nServerDuplexStreamImpl.prototype._write =\n ServerWritableStreamImpl.prototype._write;\nServerDuplexStreamImpl.prototype._final =\n ServerWritableStreamImpl.prototype._final;\nServerDuplexStreamImpl.prototype.end = ServerWritableStreamImpl.prototype.end;\n// Internal class that wraps the HTTP2 request.\nclass Http2ServerCallStream extends events_1.EventEmitter {\n constructor(stream, handler, options) {\n super();\n this.stream = stream;\n this.handler = handler;\n this.options = options;\n this.cancelled = false;\n this.deadlineTimer = setTimeout(() => { }, 0);\n this.deadline = Infinity;\n this.wantTrailers = false;\n this.metadataSent = false;\n this.canPush = false;\n this.isPushPending = false;\n this.bufferedMessages = [];\n this.messagesToPush = [];\n this.maxSendMessageSize = constants_1.DEFAULT_MAX_SEND_MESSAGE_LENGTH;\n this.maxReceiveMessageSize = constants_1.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH;\n this.stream.once('error', (err) => {\n /* We need an error handler to avoid uncaught error event exceptions, but\n * there is nothing we can reasonably do here. Any error event should\n * have a corresponding close event, which handles emitting the cancelled\n * event. And the stream is now in a bad state, so we can't reasonably\n * expect to be able to send an error over it. */\n });\n this.stream.once('close', () => {\n var _a;\n trace('Request to method ' + ((_a = this.handler) === null || _a === void 0 ? void 0 : _a.path) +\n ' stream closed with rstCode ' +\n this.stream.rstCode);\n this.cancelled = true;\n this.emit('cancelled', 'cancelled');\n });\n this.stream.on('drain', () => {\n this.emit('drain');\n });\n if ('grpc.max_send_message_length' in options) {\n this.maxSendMessageSize = options['grpc.max_send_message_length'];\n }\n if ('grpc.max_receive_message_length' in options) {\n this.maxReceiveMessageSize = options['grpc.max_receive_message_length'];\n }\n // Clear noop timer\n clearTimeout(this.deadlineTimer);\n }\n checkCancelled() {\n /* In some cases the stream can become destroyed before the close event\n * fires. That creates a race condition that this check works around */\n if (this.stream.destroyed) {\n this.cancelled = true;\n }\n return this.cancelled;\n }\n sendMetadata(customMetadata) {\n if (this.checkCancelled()) {\n return;\n }\n if (this.metadataSent) {\n return;\n }\n this.metadataSent = true;\n const custom = customMetadata ? customMetadata.toHttp2Headers() : null;\n // TODO(cjihrig): Include compression headers.\n const headers = Object.assign({}, defaultResponseHeaders, custom);\n this.stream.respond(headers, defaultResponseOptions);\n }\n receiveMetadata(headers) {\n const metadata = metadata_1.Metadata.fromHttp2Headers(headers);\n // TODO(cjihrig): Receive compression metadata.\n const timeoutHeader = metadata.get(GRPC_TIMEOUT_HEADER);\n if (timeoutHeader.length > 0) {\n const match = timeoutHeader[0].toString().match(DEADLINE_REGEX);\n if (match === null) {\n const err = new Error('Invalid deadline');\n err.code = constants_1.Status.OUT_OF_RANGE;\n this.sendError(err);\n return;\n }\n const timeout = (+match[1] * deadlineUnitsToMs[match[2]]) | 0;\n const now = new Date();\n this.deadline = now.setMilliseconds(now.getMilliseconds() + timeout);\n this.deadlineTimer = setTimeout(handleExpiredDeadline, timeout, this);\n metadata.remove(GRPC_TIMEOUT_HEADER);\n }\n // Remove several headers that should not be propagated to the application\n metadata.remove(http2.constants.HTTP2_HEADER_ACCEPT_ENCODING);\n metadata.remove(http2.constants.HTTP2_HEADER_TE);\n metadata.remove(http2.constants.HTTP2_HEADER_CONTENT_TYPE);\n metadata.remove('grpc-encoding');\n metadata.remove('grpc-accept-encoding');\n return metadata;\n }\n receiveUnaryMessage() {\n return new Promise((resolve, reject) => {\n const stream = this.stream;\n const chunks = [];\n let totalLength = 0;\n stream.on('data', (data) => {\n chunks.push(data);\n totalLength += data.byteLength;\n });\n stream.once('end', async () => {\n try {\n const requestBytes = Buffer.concat(chunks, totalLength);\n if (this.maxReceiveMessageSize !== -1 &&\n requestBytes.length > this.maxReceiveMessageSize) {\n this.sendError({\n code: constants_1.Status.RESOURCE_EXHAUSTED,\n details: `Received message larger than max (${requestBytes.length} vs. ${this.maxReceiveMessageSize})`,\n });\n resolve();\n }\n resolve(this.deserializeMessage(requestBytes));\n }\n catch (err) {\n err.code = constants_1.Status.INTERNAL;\n this.sendError(err);\n resolve();\n }\n });\n });\n }\n serializeMessage(value) {\n const messageBuffer = this.handler.serialize(value);\n // TODO(cjihrig): Call compression aware serializeMessage().\n const byteLength = messageBuffer.byteLength;\n const output = Buffer.allocUnsafe(byteLength + 5);\n output.writeUInt8(0, 0);\n output.writeUInt32BE(byteLength, 1);\n messageBuffer.copy(output, 5);\n return output;\n }\n deserializeMessage(bytes) {\n // TODO(cjihrig): Call compression aware deserializeMessage().\n const receivedMessage = bytes.slice(5);\n return this.handler.deserialize(receivedMessage);\n }\n async sendUnaryMessage(err, value, metadata, flags) {\n if (this.checkCancelled()) {\n return;\n }\n if (!metadata) {\n metadata = new metadata_1.Metadata();\n }\n if (err) {\n if (!Object.prototype.hasOwnProperty.call(err, 'metadata')) {\n err.metadata = metadata;\n }\n this.sendError(err);\n return;\n }\n try {\n const response = this.serializeMessage(value);\n this.write(response);\n this.sendStatus({ code: constants_1.Status.OK, details: 'OK', metadata });\n }\n catch (err) {\n err.code = constants_1.Status.INTERNAL;\n this.sendError(err);\n }\n }\n sendStatus(statusObj) {\n var _a;\n if (this.checkCancelled()) {\n return;\n }\n trace('Request to method ' + ((_a = this.handler) === null || _a === void 0 ? void 0 : _a.path) +\n ' ended with status code: ' +\n constants_1.Status[statusObj.code] +\n ' details: ' +\n statusObj.details);\n clearTimeout(this.deadlineTimer);\n if (!this.wantTrailers) {\n this.wantTrailers = true;\n this.stream.once('wantTrailers', () => {\n const trailersToSend = Object.assign({\n [GRPC_STATUS_HEADER]: statusObj.code,\n [GRPC_MESSAGE_HEADER]: encodeURI(statusObj.details),\n }, statusObj.metadata.toHttp2Headers());\n this.stream.sendTrailers(trailersToSend);\n });\n this.sendMetadata();\n this.stream.end();\n }\n }\n sendError(error) {\n if (this.checkCancelled()) {\n return;\n }\n const status = {\n code: constants_1.Status.UNKNOWN,\n details: 'message' in error ? error.message : 'Unknown Error',\n metadata: 'metadata' in error && error.metadata !== undefined\n ? error.metadata\n : new metadata_1.Metadata(),\n };\n if ('code' in error &&\n typeof error.code === 'number' &&\n Number.isInteger(error.code)) {\n status.code = error.code;\n if ('details' in error && typeof error.details === 'string') {\n status.details = error.details;\n }\n }\n this.sendStatus(status);\n }\n write(chunk) {\n if (this.checkCancelled()) {\n return;\n }\n if (this.maxSendMessageSize !== -1 &&\n chunk.length > this.maxSendMessageSize) {\n this.sendError({\n code: constants_1.Status.RESOURCE_EXHAUSTED,\n details: `Sent message larger than max (${chunk.length} vs. ${this.maxSendMessageSize})`,\n });\n return;\n }\n this.sendMetadata();\n return this.stream.write(chunk);\n }\n resume() {\n this.stream.resume();\n }\n setupSurfaceCall(call) {\n this.once('cancelled', (reason) => {\n call.cancelled = true;\n call.emit('cancelled', reason);\n });\n }\n setupReadable(readable) {\n const decoder = new stream_decoder_1.StreamDecoder();\n this.stream.on('data', async (data) => {\n const messages = decoder.write(data);\n for (const message of messages) {\n if (this.maxReceiveMessageSize !== -1 &&\n message.length > this.maxReceiveMessageSize) {\n this.sendError({\n code: constants_1.Status.RESOURCE_EXHAUSTED,\n details: `Received message larger than max (${message.length} vs. ${this.maxReceiveMessageSize})`,\n });\n return;\n }\n this.pushOrBufferMessage(readable, message);\n }\n });\n this.stream.once('end', () => {\n this.pushOrBufferMessage(readable, null);\n });\n }\n consumeUnpushedMessages(readable) {\n this.canPush = true;\n while (this.messagesToPush.length > 0) {\n const nextMessage = this.messagesToPush.shift();\n const canPush = readable.push(nextMessage);\n if (nextMessage === null || canPush === false) {\n this.canPush = false;\n break;\n }\n }\n return this.canPush;\n }\n pushOrBufferMessage(readable, messageBytes) {\n if (this.isPushPending) {\n this.bufferedMessages.push(messageBytes);\n }\n else {\n this.pushMessage(readable, messageBytes);\n }\n }\n async pushMessage(readable, messageBytes) {\n if (messageBytes === null) {\n if (this.canPush) {\n readable.push(null);\n }\n else {\n this.messagesToPush.push(null);\n }\n return;\n }\n this.isPushPending = true;\n try {\n const deserialized = await this.deserializeMessage(messageBytes);\n if (this.canPush) {\n if (!readable.push(deserialized)) {\n this.canPush = false;\n this.stream.pause();\n }\n }\n else {\n this.messagesToPush.push(deserialized);\n }\n }\n catch (error) {\n // Ignore any remaining messages when errors occur.\n this.bufferedMessages.length = 0;\n if (!('code' in error &&\n typeof error.code === 'number' &&\n Number.isInteger(error.code) &&\n error.code >= constants_1.Status.OK &&\n error.code <= constants_1.Status.UNAUTHENTICATED)) {\n // The error code is not a valid gRPC code so its being overwritten.\n error.code = constants_1.Status.INTERNAL;\n }\n readable.emit('error', error);\n }\n this.isPushPending = false;\n if (this.bufferedMessages.length > 0) {\n this.pushMessage(readable, this.bufferedMessages.shift());\n }\n }\n getPeer() {\n const socket = this.stream.session.socket;\n if (socket.remoteAddress) {\n if (socket.remotePort) {\n return `${socket.remoteAddress}:${socket.remotePort}`;\n }\n else {\n return socket.remoteAddress;\n }\n }\n else {\n return 'unknown';\n }\n }\n getDeadline() {\n return this.deadline;\n }\n}\nexports.Http2ServerCallStream = Http2ServerCallStream;\nfunction handleExpiredDeadline(call) {\n const err = new Error('Deadline exceeded');\n err.code = constants_1.Status.DEADLINE_EXCEEDED;\n call.sendError(err);\n call.cancelled = true;\n call.emit('cancelled', 'deadline');\n}\n//# sourceMappingURL=server-call.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ServerCredentials = void 0;\nconst tls_helpers_1 = require(\"./tls-helpers\");\nclass ServerCredentials {\n static createInsecure() {\n return new InsecureServerCredentials();\n }\n static createSsl(rootCerts, keyCertPairs, checkClientCertificate = false) {\n if (rootCerts !== null && !Buffer.isBuffer(rootCerts)) {\n throw new TypeError('rootCerts must be null or a Buffer');\n }\n if (!Array.isArray(keyCertPairs)) {\n throw new TypeError('keyCertPairs must be an array');\n }\n if (typeof checkClientCertificate !== 'boolean') {\n throw new TypeError('checkClientCertificate must be a boolean');\n }\n const cert = [];\n const key = [];\n for (let i = 0; i < keyCertPairs.length; i++) {\n const pair = keyCertPairs[i];\n if (pair === null || typeof pair !== 'object') {\n throw new TypeError(`keyCertPair[${i}] must be an object`);\n }\n if (!Buffer.isBuffer(pair.private_key)) {\n throw new TypeError(`keyCertPair[${i}].private_key must be a Buffer`);\n }\n if (!Buffer.isBuffer(pair.cert_chain)) {\n throw new TypeError(`keyCertPair[${i}].cert_chain must be a Buffer`);\n }\n cert.push(pair.cert_chain);\n key.push(pair.private_key);\n }\n return new SecureServerCredentials({\n ca: rootCerts || tls_helpers_1.getDefaultRootsData() || undefined,\n cert,\n key,\n requestCert: checkClientCertificate,\n ciphers: tls_helpers_1.CIPHER_SUITES,\n });\n }\n}\nexports.ServerCredentials = ServerCredentials;\nclass InsecureServerCredentials extends ServerCredentials {\n _isSecure() {\n return false;\n }\n _getSettings() {\n return null;\n }\n}\nclass SecureServerCredentials extends ServerCredentials {\n constructor(options) {\n super();\n this.options = options;\n }\n _isSecure() {\n return true;\n }\n _getSettings() {\n return this.options;\n }\n}\n//# sourceMappingURL=server-credentials.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Server = void 0;\nconst http2 = require(\"http2\");\nconst constants_1 = require(\"./constants\");\nconst metadata_1 = require(\"./metadata\");\nconst server_call_1 = require(\"./server-call\");\nconst resolver_1 = require(\"./resolver\");\nconst logging = require(\"./logging\");\nconst subchannel_1 = require(\"./subchannel\");\nconst uri_parser_1 = require(\"./uri-parser\");\nconst TRACER_NAME = 'server';\nfunction trace(text) {\n logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text);\n}\nfunction noop() { }\nfunction getUnimplementedStatusResponse(methodName) {\n return {\n code: constants_1.Status.UNIMPLEMENTED,\n details: `The server does not implement the method ${methodName}`,\n metadata: new metadata_1.Metadata(),\n };\n}\nfunction getDefaultHandler(handlerType, methodName) {\n const unimplementedStatusResponse = getUnimplementedStatusResponse(methodName);\n switch (handlerType) {\n case 'unary':\n return (call, callback) => {\n callback(unimplementedStatusResponse, null);\n };\n case 'clientStream':\n return (call, callback) => {\n callback(unimplementedStatusResponse, null);\n };\n case 'serverStream':\n return (call) => {\n call.emit('error', unimplementedStatusResponse);\n };\n case 'bidi':\n return (call) => {\n call.emit('error', unimplementedStatusResponse);\n };\n default:\n throw new Error(`Invalid handlerType ${handlerType}`);\n }\n}\nclass Server {\n constructor(options) {\n this.http2ServerList = [];\n this.handlers = new Map();\n this.sessions = new Set();\n this.started = false;\n this.options = options !== null && options !== void 0 ? options : {};\n }\n addProtoService() {\n throw new Error('Not implemented. Use addService() instead');\n }\n addService(service, implementation) {\n if (service === null ||\n typeof service !== 'object' ||\n implementation === null ||\n typeof implementation !== 'object') {\n throw new Error('addService() requires two objects as arguments');\n }\n const serviceKeys = Object.keys(service);\n if (serviceKeys.length === 0) {\n throw new Error('Cannot add an empty service to a server');\n }\n serviceKeys.forEach((name) => {\n const attrs = service[name];\n let methodType;\n if (attrs.requestStream) {\n if (attrs.responseStream) {\n methodType = 'bidi';\n }\n else {\n methodType = 'clientStream';\n }\n }\n else {\n if (attrs.responseStream) {\n methodType = 'serverStream';\n }\n else {\n methodType = 'unary';\n }\n }\n let implFn = implementation[name];\n let impl;\n if (implFn === undefined && typeof attrs.originalName === 'string') {\n implFn = implementation[attrs.originalName];\n }\n if (implFn !== undefined) {\n impl = implFn.bind(implementation);\n }\n else {\n impl = getDefaultHandler(methodType, name);\n }\n const success = this.register(attrs.path, impl, attrs.responseSerialize, attrs.requestDeserialize, methodType);\n if (success === false) {\n throw new Error(`Method handler for ${attrs.path} already provided.`);\n }\n });\n }\n removeService(service) {\n if (service === null ||\n typeof service !== 'object') {\n throw new Error('removeService() requires object as argument');\n }\n const serviceKeys = Object.keys(service);\n serviceKeys.forEach((name) => {\n const attrs = service[name];\n this.unregister(attrs.path);\n });\n }\n bind(port, creds) {\n throw new Error('Not implemented. Use bindAsync() instead');\n }\n bindAsync(port, creds, callback) {\n if (this.started === true) {\n throw new Error('server is already started');\n }\n if (typeof port !== 'string') {\n throw new TypeError('port must be a string');\n }\n if (creds === null || typeof creds !== 'object') {\n throw new TypeError('creds must be an object');\n }\n if (typeof callback !== 'function') {\n throw new TypeError('callback must be a function');\n }\n const initialPortUri = uri_parser_1.parseUri(port);\n if (initialPortUri === null) {\n throw new Error(`Could not parse port \"${port}\"`);\n }\n const portUri = resolver_1.mapUriDefaultScheme(initialPortUri);\n if (portUri === null) {\n throw new Error(`Could not get a default scheme for port \"${port}\"`);\n }\n const serverOptions = {\n maxSendHeaderBlockLength: Number.MAX_SAFE_INTEGER\n };\n if ('grpc.max_concurrent_streams' in this.options) {\n serverOptions.settings = {\n maxConcurrentStreams: this.options['grpc.max_concurrent_streams'],\n };\n }\n const setupServer = () => {\n let http2Server;\n if (creds._isSecure()) {\n const secureServerOptions = Object.assign(serverOptions, creds._getSettings());\n http2Server = http2.createSecureServer(secureServerOptions);\n }\n else {\n http2Server = http2.createServer(serverOptions);\n }\n http2Server.setTimeout(0, noop);\n this._setupHandlers(http2Server);\n return http2Server;\n };\n const bindSpecificPort = (addressList, portNum, previousCount) => {\n if (addressList.length === 0) {\n return Promise.resolve({ port: portNum, count: previousCount });\n }\n return Promise.all(addressList.map((address) => {\n trace('Attempting to bind ' + subchannel_1.subchannelAddressToString(address));\n let addr;\n if (subchannel_1.isTcpSubchannelAddress(address)) {\n addr = {\n host: address.host,\n port: portNum,\n };\n }\n else {\n addr = address;\n }\n const http2Server = setupServer();\n return new Promise((resolve, reject) => {\n function onError(err) {\n resolve(err);\n }\n http2Server.once('error', onError);\n http2Server.listen(addr, () => {\n trace('Successfully bound ' + subchannel_1.subchannelAddressToString(address));\n this.http2ServerList.push(http2Server);\n const boundAddress = http2Server.address();\n if (typeof boundAddress === 'string') {\n resolve(portNum);\n }\n else {\n resolve(boundAddress.port);\n }\n http2Server.removeListener('error', onError);\n });\n });\n })).then((results) => {\n let count = 0;\n for (const result of results) {\n if (typeof result === 'number') {\n count += 1;\n if (result !== portNum) {\n throw new Error('Invalid state: multiple port numbers added from single address');\n }\n }\n }\n return {\n port: portNum,\n count: count + previousCount,\n };\n });\n };\n const bindWildcardPort = (addressList) => {\n if (addressList.length === 0) {\n return Promise.resolve({ port: 0, count: 0 });\n }\n const address = addressList[0];\n const http2Server = setupServer();\n return new Promise((resolve, reject) => {\n function onError(err) {\n resolve(bindWildcardPort(addressList.slice(1)));\n }\n http2Server.once('error', onError);\n http2Server.listen(address, () => {\n this.http2ServerList.push(http2Server);\n resolve(bindSpecificPort(addressList.slice(1), http2Server.address().port, 1));\n http2Server.removeListener('error', onError);\n });\n });\n };\n const resolverListener = {\n onSuccessfulResolution: (addressList, serviceConfig, serviceConfigError) => {\n // We only want one resolution result. Discard all future results\n resolverListener.onSuccessfulResolution = () => { };\n if (addressList.length === 0) {\n callback(new Error(`No addresses resolved for port ${port}`), 0);\n return;\n }\n let bindResultPromise;\n if (subchannel_1.isTcpSubchannelAddress(addressList[0])) {\n if (addressList[0].port === 0) {\n bindResultPromise = bindWildcardPort(addressList);\n }\n else {\n bindResultPromise = bindSpecificPort(addressList, addressList[0].port, 0);\n }\n }\n else {\n // Use an arbitrary non-zero port for non-TCP addresses\n bindResultPromise = bindSpecificPort(addressList, 1, 0);\n }\n bindResultPromise.then((bindResult) => {\n if (bindResult.count === 0) {\n const errorString = `No address added out of total ${addressList.length} resolved`;\n logging.log(constants_1.LogVerbosity.ERROR, errorString);\n callback(new Error(errorString), 0);\n }\n else {\n if (bindResult.count < addressList.length) {\n logging.log(constants_1.LogVerbosity.INFO, `WARNING Only ${bindResult.count} addresses added out of total ${addressList.length} resolved`);\n }\n callback(null, bindResult.port);\n }\n }, (error) => {\n const errorString = `No address added out of total ${addressList.length} resolved`;\n logging.log(constants_1.LogVerbosity.ERROR, errorString);\n callback(new Error(errorString), 0);\n });\n },\n onError: (error) => {\n callback(new Error(error.details), 0);\n },\n };\n const resolver = resolver_1.createResolver(portUri, resolverListener, this.options);\n resolver.updateResolution();\n }\n forceShutdown() {\n // Close the server if it is still running.\n for (const http2Server of this.http2ServerList) {\n if (http2Server.listening) {\n http2Server.close();\n }\n }\n this.started = false;\n // Always destroy any available sessions. It's possible that one or more\n // tryShutdown() calls are in progress. Don't wait on them to finish.\n this.sessions.forEach((session) => {\n // Cast NGHTTP2_CANCEL to any because TypeScript doesn't seem to\n // recognize destroy(code) as a valid signature.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n session.destroy(http2.constants.NGHTTP2_CANCEL);\n });\n this.sessions.clear();\n }\n register(name, handler, serialize, deserialize, type) {\n if (this.handlers.has(name)) {\n return false;\n }\n this.handlers.set(name, {\n func: handler,\n serialize,\n deserialize,\n type,\n path: name,\n });\n return true;\n }\n unregister(name) {\n return this.handlers.delete(name);\n }\n start() {\n if (this.http2ServerList.length === 0 ||\n this.http2ServerList.every((http2Server) => http2Server.listening !== true)) {\n throw new Error('server must be bound in order to start');\n }\n if (this.started === true) {\n throw new Error('server is already started');\n }\n this.started = true;\n }\n tryShutdown(callback) {\n let pendingChecks = 0;\n function maybeCallback() {\n pendingChecks--;\n if (pendingChecks === 0) {\n callback();\n }\n }\n // Close the server if necessary.\n this.started = false;\n for (const http2Server of this.http2ServerList) {\n if (http2Server.listening) {\n pendingChecks++;\n http2Server.close(maybeCallback);\n }\n }\n this.sessions.forEach((session) => {\n if (!session.closed) {\n pendingChecks += 1;\n session.close(maybeCallback);\n }\n });\n if (pendingChecks === 0) {\n callback();\n }\n }\n addHttp2Port() {\n throw new Error('Not yet implemented');\n }\n _setupHandlers(http2Server) {\n if (http2Server === null) {\n return;\n }\n http2Server.on('stream', (stream, headers) => {\n const contentType = headers[http2.constants.HTTP2_HEADER_CONTENT_TYPE];\n if (typeof contentType !== 'string' ||\n !contentType.startsWith('application/grpc')) {\n stream.respond({\n [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE,\n }, { endStream: true });\n return;\n }\n try {\n const path = headers[http2.constants.HTTP2_HEADER_PATH];\n const serverAddress = http2Server.address();\n let serverAddressString = 'null';\n if (serverAddress) {\n if (typeof serverAddress === 'string') {\n serverAddressString = serverAddress;\n }\n else {\n serverAddressString =\n serverAddress.address + ':' + serverAddress.port;\n }\n }\n trace('Received call to method ' +\n path +\n ' at address ' +\n serverAddressString);\n const handler = this.handlers.get(path);\n if (handler === undefined) {\n trace('No handler registered for method ' +\n path +\n '. Sending UNIMPLEMENTED status.');\n throw getUnimplementedStatusResponse(path);\n }\n const call = new server_call_1.Http2ServerCallStream(stream, handler, this.options);\n const metadata = call.receiveMetadata(headers);\n switch (handler.type) {\n case 'unary':\n handleUnary(call, handler, metadata);\n break;\n case 'clientStream':\n handleClientStreaming(call, handler, metadata);\n break;\n case 'serverStream':\n handleServerStreaming(call, handler, metadata);\n break;\n case 'bidi':\n handleBidiStreaming(call, handler, metadata);\n break;\n default:\n throw new Error(`Unknown handler type: ${handler.type}`);\n }\n }\n catch (err) {\n const call = new server_call_1.Http2ServerCallStream(stream, null, this.options);\n if (err.code === undefined) {\n err.code = constants_1.Status.INTERNAL;\n }\n call.sendError(err);\n }\n });\n http2Server.on('session', (session) => {\n if (!this.started) {\n session.destroy();\n return;\n }\n this.sessions.add(session);\n session.on('close', () => {\n this.sessions.delete(session);\n });\n });\n }\n}\nexports.Server = Server;\nasync function handleUnary(call, handler, metadata) {\n const request = await call.receiveUnaryMessage();\n if (request === undefined || call.cancelled) {\n return;\n }\n const emitter = new server_call_1.ServerUnaryCallImpl(call, metadata, request);\n handler.func(emitter, (err, value, trailer, flags) => {\n call.sendUnaryMessage(err, value, trailer, flags);\n });\n}\nfunction handleClientStreaming(call, handler, metadata) {\n const stream = new server_call_1.ServerReadableStreamImpl(call, metadata, handler.deserialize);\n function respond(err, value, trailer, flags) {\n stream.destroy();\n call.sendUnaryMessage(err, value, trailer, flags);\n }\n if (call.cancelled) {\n return;\n }\n stream.on('error', respond);\n handler.func(stream, respond);\n}\nasync function handleServerStreaming(call, handler, metadata) {\n const request = await call.receiveUnaryMessage();\n if (request === undefined || call.cancelled) {\n return;\n }\n const stream = new server_call_1.ServerWritableStreamImpl(call, metadata, handler.serialize, request);\n handler.func(stream);\n}\nfunction handleBidiStreaming(call, handler, metadata) {\n const stream = new server_call_1.ServerDuplexStreamImpl(call, metadata, handler.serialize, handler.deserialize);\n if (call.cancelled) {\n return;\n }\n handler.func(stream);\n}\n//# sourceMappingURL=server.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.extractAndSelectServiceConfig = exports.validateServiceConfig = void 0;\n/* This file implements gRFC A2 and the service config spec:\n * https://github.com/grpc/proposal/blob/master/A2-service-configs-in-dns.md\n * https://github.com/grpc/grpc/blob/master/doc/service_config.md. Each\n * function here takes an object with unknown structure and returns its\n * specific object type if the input has the right structure, and throws an\n * error otherwise. */\n/* The any type is purposely used here. All functions validate their input at\n * runtime */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nconst os = require(\"os\");\nconst load_balancer_1 = require(\"./load-balancer\");\n/**\n * Recognizes a number with up to 9 digits after the decimal point, followed by\n * an \"s\", representing a number of seconds.\n */\nconst TIMEOUT_REGEX = /^\\d+(\\.\\d{1,9})?s$/;\n/**\n * Client language name used for determining whether this client matches a\n * `ServiceConfigCanaryConfig`'s `clientLanguage` list.\n */\nconst CLIENT_LANGUAGE_STRING = 'node';\nfunction validateName(obj) {\n if (!('service' in obj) || typeof obj.service !== 'string') {\n throw new Error('Invalid method config name: invalid service');\n }\n const result = {\n service: obj.service,\n };\n if ('method' in obj) {\n if (typeof obj.method === 'string') {\n result.method = obj.method;\n }\n else {\n throw new Error('Invalid method config name: invalid method');\n }\n }\n return result;\n}\nfunction validateMethodConfig(obj) {\n const result = {\n name: [],\n };\n if (!('name' in obj) || !Array.isArray(obj.name)) {\n throw new Error('Invalid method config: invalid name array');\n }\n for (const name of obj.name) {\n result.name.push(validateName(name));\n }\n if ('waitForReady' in obj) {\n if (typeof obj.waitForReady !== 'boolean') {\n throw new Error('Invalid method config: invalid waitForReady');\n }\n result.waitForReady = obj.waitForReady;\n }\n if ('timeout' in obj) {\n if (!(typeof obj.timeout === 'string') ||\n !TIMEOUT_REGEX.test(obj.timeout)) {\n throw new Error('Invalid method config: invalid timeout');\n }\n result.timeout = obj.timeout;\n }\n if ('maxRequestBytes' in obj) {\n if (typeof obj.maxRequestBytes !== 'number') {\n throw new Error('Invalid method config: invalid maxRequestBytes');\n }\n result.maxRequestBytes = obj.maxRequestBytes;\n }\n if ('maxResponseBytes' in obj) {\n if (typeof obj.maxResponseBytes !== 'number') {\n throw new Error('Invalid method config: invalid maxRequestBytes');\n }\n result.maxResponseBytes = obj.maxResponseBytes;\n }\n return result;\n}\nfunction validateServiceConfig(obj) {\n const result = {\n loadBalancingConfig: [],\n methodConfig: [],\n };\n if ('loadBalancingPolicy' in obj) {\n if (typeof obj.loadBalancingPolicy === 'string') {\n result.loadBalancingPolicy = obj.loadBalancingPolicy;\n }\n else {\n throw new Error('Invalid service config: invalid loadBalancingPolicy');\n }\n }\n if ('loadBalancingConfig' in obj) {\n if (Array.isArray(obj.loadBalancingConfig)) {\n for (const config of obj.loadBalancingConfig) {\n result.loadBalancingConfig.push(load_balancer_1.validateLoadBalancingConfig(config));\n }\n }\n else {\n throw new Error('Invalid service config: invalid loadBalancingConfig');\n }\n }\n if ('methodConfig' in obj) {\n if (Array.isArray(obj.methodConfig)) {\n for (const methodConfig of obj.methodConfig) {\n result.methodConfig.push(validateMethodConfig(methodConfig));\n }\n }\n }\n // Validate method name uniqueness\n const seenMethodNames = [];\n for (const methodConfig of result.methodConfig) {\n for (const name of methodConfig.name) {\n for (const seenName of seenMethodNames) {\n if (name.service === seenName.service &&\n name.method === seenName.method) {\n throw new Error(`Invalid service config: duplicate name ${name.service}/${name.method}`);\n }\n }\n seenMethodNames.push(name);\n }\n }\n return result;\n}\nexports.validateServiceConfig = validateServiceConfig;\nfunction validateCanaryConfig(obj) {\n if (!('serviceConfig' in obj)) {\n throw new Error('Invalid service config choice: missing service config');\n }\n const result = {\n serviceConfig: validateServiceConfig(obj.serviceConfig),\n };\n if ('clientLanguage' in obj) {\n if (Array.isArray(obj.clientLanguage)) {\n result.clientLanguage = [];\n for (const lang of obj.clientLanguage) {\n if (typeof lang === 'string') {\n result.clientLanguage.push(lang);\n }\n else {\n throw new Error('Invalid service config choice: invalid clientLanguage');\n }\n }\n }\n else {\n throw new Error('Invalid service config choice: invalid clientLanguage');\n }\n }\n if ('clientHostname' in obj) {\n if (Array.isArray(obj.clientHostname)) {\n result.clientHostname = [];\n for (const lang of obj.clientHostname) {\n if (typeof lang === 'string') {\n result.clientHostname.push(lang);\n }\n else {\n throw new Error('Invalid service config choice: invalid clientHostname');\n }\n }\n }\n else {\n throw new Error('Invalid service config choice: invalid clientHostname');\n }\n }\n if ('percentage' in obj) {\n if (typeof obj.percentage === 'number' &&\n 0 <= obj.percentage &&\n obj.percentage <= 100) {\n result.percentage = obj.percentage;\n }\n else {\n throw new Error('Invalid service config choice: invalid percentage');\n }\n }\n // Validate that no unexpected fields are present\n const allowedFields = [\n 'clientLanguage',\n 'percentage',\n 'clientHostname',\n 'serviceConfig',\n ];\n for (const field in obj) {\n if (!allowedFields.includes(field)) {\n throw new Error(`Invalid service config choice: unexpected field ${field}`);\n }\n }\n return result;\n}\nfunction validateAndSelectCanaryConfig(obj, percentage) {\n if (!Array.isArray(obj)) {\n throw new Error('Invalid service config list');\n }\n for (const config of obj) {\n const validatedConfig = validateCanaryConfig(config);\n /* For each field, we check if it is present, then only discard the\n * config if the field value does not match the current client */\n if (typeof validatedConfig.percentage === 'number' &&\n percentage > validatedConfig.percentage) {\n continue;\n }\n if (Array.isArray(validatedConfig.clientHostname)) {\n let hostnameMatched = false;\n for (const hostname of validatedConfig.clientHostname) {\n if (hostname === os.hostname()) {\n hostnameMatched = true;\n }\n }\n if (!hostnameMatched) {\n continue;\n }\n }\n if (Array.isArray(validatedConfig.clientLanguage)) {\n let languageMatched = false;\n for (const language of validatedConfig.clientLanguage) {\n if (language === CLIENT_LANGUAGE_STRING) {\n languageMatched = true;\n }\n }\n if (!languageMatched) {\n continue;\n }\n }\n return validatedConfig.serviceConfig;\n }\n throw new Error('No matching service config found');\n}\n/**\n * Find the \"grpc_config\" record among the TXT records, parse its value as JSON, validate its contents,\n * and select a service config with selection fields that all match this client. Most of these steps\n * can fail with an error; the caller must handle any errors thrown this way.\n * @param txtRecord The TXT record array that is output from a successful call to dns.resolveTxt\n * @param percentage A number chosen from the range [0, 100) that is used to select which config to use\n * @return The service configuration to use, given the percentage value, or null if the service config\n * data has a valid format but none of the options match the current client.\n */\nfunction extractAndSelectServiceConfig(txtRecord, percentage) {\n for (const record of txtRecord) {\n if (record.length > 0 && record[0].startsWith('grpc_config=')) {\n /* Treat the list of strings in this record as a single string and remove\n * \"grpc_config=\" from the beginning. The rest should be a JSON string */\n const recordString = record.join('').substring('grpc_config='.length);\n const recordJson = JSON.parse(recordString);\n return validateAndSelectCanaryConfig(recordJson, percentage);\n }\n }\n return null;\n}\nexports.extractAndSelectServiceConfig = extractAndSelectServiceConfig;\n//# sourceMappingURL=service-config.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.StatusBuilder = void 0;\n/**\n * A builder for gRPC status objects.\n */\nclass StatusBuilder {\n constructor() {\n this.code = null;\n this.details = null;\n this.metadata = null;\n }\n /**\n * Adds a status code to the builder.\n */\n withCode(code) {\n this.code = code;\n return this;\n }\n /**\n * Adds details to the builder.\n */\n withDetails(details) {\n this.details = details;\n return this;\n }\n /**\n * Adds metadata to the builder.\n */\n withMetadata(metadata) {\n this.metadata = metadata;\n return this;\n }\n /**\n * Builds the status object.\n */\n build() {\n const status = {};\n if (this.code !== null) {\n status.code = this.code;\n }\n if (this.details !== null) {\n status.details = this.details;\n }\n if (this.metadata !== null) {\n status.metadata = this.metadata;\n }\n return status;\n }\n}\nexports.StatusBuilder = StatusBuilder;\n//# sourceMappingURL=status-builder.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.StreamDecoder = void 0;\nvar ReadState;\n(function (ReadState) {\n ReadState[ReadState[\"NO_DATA\"] = 0] = \"NO_DATA\";\n ReadState[ReadState[\"READING_SIZE\"] = 1] = \"READING_SIZE\";\n ReadState[ReadState[\"READING_MESSAGE\"] = 2] = \"READING_MESSAGE\";\n})(ReadState || (ReadState = {}));\nclass StreamDecoder {\n constructor() {\n this.readState = ReadState.NO_DATA;\n this.readCompressFlag = Buffer.alloc(1);\n this.readPartialSize = Buffer.alloc(4);\n this.readSizeRemaining = 4;\n this.readMessageSize = 0;\n this.readPartialMessage = [];\n this.readMessageRemaining = 0;\n }\n write(data) {\n let readHead = 0;\n let toRead;\n const result = [];\n while (readHead < data.length) {\n switch (this.readState) {\n case ReadState.NO_DATA:\n this.readCompressFlag = data.slice(readHead, readHead + 1);\n readHead += 1;\n this.readState = ReadState.READING_SIZE;\n this.readPartialSize.fill(0);\n this.readSizeRemaining = 4;\n this.readMessageSize = 0;\n this.readMessageRemaining = 0;\n this.readPartialMessage = [];\n break;\n case ReadState.READING_SIZE:\n toRead = Math.min(data.length - readHead, this.readSizeRemaining);\n data.copy(this.readPartialSize, 4 - this.readSizeRemaining, readHead, readHead + toRead);\n this.readSizeRemaining -= toRead;\n readHead += toRead;\n // readSizeRemaining >=0 here\n if (this.readSizeRemaining === 0) {\n this.readMessageSize = this.readPartialSize.readUInt32BE(0);\n this.readMessageRemaining = this.readMessageSize;\n if (this.readMessageRemaining > 0) {\n this.readState = ReadState.READING_MESSAGE;\n }\n else {\n const message = Buffer.concat([this.readCompressFlag, this.readPartialSize], 5);\n this.readState = ReadState.NO_DATA;\n result.push(message);\n }\n }\n break;\n case ReadState.READING_MESSAGE:\n toRead = Math.min(data.length - readHead, this.readMessageRemaining);\n this.readPartialMessage.push(data.slice(readHead, readHead + toRead));\n this.readMessageRemaining -= toRead;\n readHead += toRead;\n // readMessageRemaining >=0 here\n if (this.readMessageRemaining === 0) {\n // At this point, we have read a full message\n const framedMessageBuffers = [\n this.readCompressFlag,\n this.readPartialSize,\n ].concat(this.readPartialMessage);\n const framedMessage = Buffer.concat(framedMessageBuffers, this.readMessageSize + 5);\n this.readState = ReadState.NO_DATA;\n result.push(framedMessage);\n }\n break;\n default:\n throw new Error('Unexpected read state');\n }\n }\n return result;\n }\n}\nexports.StreamDecoder = StreamDecoder;\n//# sourceMappingURL=stream-decoder.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getSubchannelPool = exports.SubchannelPool = void 0;\nconst channel_options_1 = require(\"./channel-options\");\nconst subchannel_1 = require(\"./subchannel\");\nconst uri_parser_1 = require(\"./uri-parser\");\n// 10 seconds in milliseconds. This value is arbitrary.\n/**\n * The amount of time in between checks for dropping subchannels that have no\n * other references\n */\nconst REF_CHECK_INTERVAL = 10000;\nclass SubchannelPool {\n /**\n * A pool of subchannels use for making connections. Subchannels with the\n * exact same parameters will be reused.\n * @param global If true, this is the global subchannel pool. Otherwise, it\n * is the pool for a single channel.\n */\n constructor(global) {\n this.global = global;\n this.pool = Object.create(null);\n /**\n * A timer of a task performing a periodic subchannel cleanup.\n */\n this.cleanupTimer = null;\n }\n /**\n * Unrefs all unused subchannels and cancels the cleanup task if all\n * subchannels have been unrefed.\n */\n unrefUnusedSubchannels() {\n let allSubchannelsUnrefed = true;\n /* These objects are created with Object.create(null), so they do not\n * have a prototype, which means that for (... in ...) loops over them\n * do not need to be filtered */\n // eslint-disable-disable-next-line:forin\n for (const channelTarget in this.pool) {\n const subchannelObjArray = this.pool[channelTarget];\n const refedSubchannels = subchannelObjArray.filter((value) => !value.subchannel.unrefIfOneRef());\n if (refedSubchannels.length > 0) {\n allSubchannelsUnrefed = false;\n }\n /* For each subchannel in the pool, try to unref it if it has\n * exactly one ref (which is the ref from the pool itself). If that\n * does happen, remove the subchannel from the pool */\n this.pool[channelTarget] = refedSubchannels;\n }\n /* Currently we do not delete keys with empty values. If that results\n * in significant memory usage we should change it. */\n // Cancel the cleanup task if all subchannels have been unrefed.\n if (allSubchannelsUnrefed && this.cleanupTimer !== null) {\n clearInterval(this.cleanupTimer);\n this.cleanupTimer = null;\n }\n }\n /**\n * Ensures that the cleanup task is spawned.\n */\n ensureCleanupTask() {\n var _a, _b;\n if (this.global && this.cleanupTimer === null) {\n this.cleanupTimer = setInterval(() => {\n this.unrefUnusedSubchannels();\n }, REF_CHECK_INTERVAL);\n // Unref because this timer should not keep the event loop running.\n // Call unref only if it exists to address electron/electron#21162\n (_b = (_a = this.cleanupTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a);\n }\n }\n /**\n * Get a subchannel if one already exists with exactly matching parameters.\n * Otherwise, create and save a subchannel with those parameters.\n * @param channelTarget\n * @param subchannelTarget\n * @param channelArguments\n * @param channelCredentials\n */\n getOrCreateSubchannel(channelTargetUri, subchannelTarget, channelArguments, channelCredentials) {\n this.ensureCleanupTask();\n const channelTarget = uri_parser_1.uriToString(channelTargetUri);\n if (channelTarget in this.pool) {\n const subchannelObjArray = this.pool[channelTarget];\n for (const subchannelObj of subchannelObjArray) {\n if (subchannel_1.subchannelAddressEqual(subchannelTarget, subchannelObj.subchannelAddress) &&\n channel_options_1.channelOptionsEqual(channelArguments, subchannelObj.channelArguments) &&\n channelCredentials._equals(subchannelObj.channelCredentials)) {\n return subchannelObj.subchannel;\n }\n }\n }\n // If we get here, no matching subchannel was found\n const subchannel = new subchannel_1.Subchannel(channelTargetUri, subchannelTarget, channelArguments, channelCredentials);\n if (!(channelTarget in this.pool)) {\n this.pool[channelTarget] = [];\n }\n this.pool[channelTarget].push({\n subchannelAddress: subchannelTarget,\n channelArguments,\n channelCredentials,\n subchannel,\n });\n if (this.global) {\n subchannel.ref();\n }\n return subchannel;\n }\n}\nexports.SubchannelPool = SubchannelPool;\nconst globalSubchannelPool = new SubchannelPool(true);\n/**\n * Get either the global subchannel pool, or a new subchannel pool.\n * @param global\n */\nfunction getSubchannelPool(global) {\n if (global) {\n return globalSubchannelPool;\n }\n else {\n return new SubchannelPool(false);\n }\n}\nexports.getSubchannelPool = getSubchannelPool;\n//# sourceMappingURL=subchannel-pool.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Subchannel = exports.subchannelAddressToString = exports.subchannelAddressEqual = exports.isTcpSubchannelAddress = void 0;\nconst http2 = require(\"http2\");\nconst tls_1 = require(\"tls\");\nconst channel_1 = require(\"./channel\");\nconst backoff_timeout_1 = require(\"./backoff-timeout\");\nconst resolver_1 = require(\"./resolver\");\nconst logging = require(\"./logging\");\nconst constants_1 = require(\"./constants\");\nconst http_proxy_1 = require(\"./http_proxy\");\nconst net = require(\"net\");\nconst uri_parser_1 = require(\"./uri-parser\");\nconst clientVersion = require('../../package.json').version;\nconst TRACER_NAME = 'subchannel';\nfunction trace(text) {\n logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text);\n}\nfunction refTrace(text) {\n logging.trace(constants_1.LogVerbosity.DEBUG, 'subchannel_refcount', text);\n}\nconst MIN_CONNECT_TIMEOUT_MS = 20000;\nconst INITIAL_BACKOFF_MS = 1000;\nconst BACKOFF_MULTIPLIER = 1.6;\nconst MAX_BACKOFF_MS = 120000;\nconst BACKOFF_JITTER = 0.2;\n/* setInterval and setTimeout only accept signed 32 bit integers. JS doesn't\n * have a constant for the max signed 32 bit integer, so this is a simple way\n * to calculate it */\nconst KEEPALIVE_MAX_TIME_MS = ~(1 << 31);\nconst KEEPALIVE_TIMEOUT_MS = 20000;\nconst { HTTP2_HEADER_AUTHORITY, HTTP2_HEADER_CONTENT_TYPE, HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_TE, HTTP2_HEADER_USER_AGENT, } = http2.constants;\n/**\n * Get a number uniformly at random in the range [min, max)\n * @param min\n * @param max\n */\nfunction uniformRandom(min, max) {\n return Math.random() * (max - min) + min;\n}\nconst tooManyPingsData = Buffer.from('too_many_pings', 'ascii');\nfunction isTcpSubchannelAddress(address) {\n return 'port' in address;\n}\nexports.isTcpSubchannelAddress = isTcpSubchannelAddress;\nfunction subchannelAddressEqual(address1, address2) {\n if (isTcpSubchannelAddress(address1)) {\n return (isTcpSubchannelAddress(address2) &&\n address1.host === address2.host &&\n address1.port === address2.port);\n }\n else {\n return !isTcpSubchannelAddress(address2) && address1.path === address2.path;\n }\n}\nexports.subchannelAddressEqual = subchannelAddressEqual;\nfunction subchannelAddressToString(address) {\n if (isTcpSubchannelAddress(address)) {\n return address.host + ':' + address.port;\n }\n else {\n return address.path;\n }\n}\nexports.subchannelAddressToString = subchannelAddressToString;\nclass Subchannel {\n /**\n * A class representing a connection to a single backend.\n * @param channelTarget The target string for the channel as a whole\n * @param subchannelAddress The address for the backend that this subchannel\n * will connect to\n * @param options The channel options, plus any specific subchannel options\n * for this subchannel\n * @param credentials The channel credentials used to establish this\n * connection\n */\n constructor(channelTarget, subchannelAddress, options, credentials) {\n this.channelTarget = channelTarget;\n this.subchannelAddress = subchannelAddress;\n this.options = options;\n this.credentials = credentials;\n /**\n * The subchannel's current connectivity state. Invariant: `session` === `null`\n * if and only if `connectivityState` is IDLE or TRANSIENT_FAILURE.\n */\n this.connectivityState = channel_1.ConnectivityState.IDLE;\n /**\n * The underlying http2 session used to make requests.\n */\n this.session = null;\n /**\n * Indicates that the subchannel should transition from TRANSIENT_FAILURE to\n * CONNECTING instead of IDLE when the backoff timeout ends.\n */\n this.continueConnecting = false;\n /**\n * A list of listener functions that will be called whenever the connectivity\n * state changes. Will be modified by `addConnectivityStateListener` and\n * `removeConnectivityStateListener`\n */\n this.stateListeners = [];\n /**\n * A list of listener functions that will be called when the underlying\n * socket disconnects. Used for ending active calls with an UNAVAILABLE\n * status.\n */\n this.disconnectListeners = [];\n /**\n * The amount of time in between sending pings\n */\n this.keepaliveTimeMs = KEEPALIVE_MAX_TIME_MS;\n /**\n * The amount of time to wait for an acknowledgement after sending a ping\n */\n this.keepaliveTimeoutMs = KEEPALIVE_TIMEOUT_MS;\n /**\n * Indicates whether keepalive pings should be sent without any active calls\n */\n this.keepaliveWithoutCalls = false;\n /**\n * Tracks calls with references to this subchannel\n */\n this.callRefcount = 0;\n /**\n * Tracks channels and subchannel pools with references to this subchannel\n */\n this.refcount = 0;\n // Build user-agent string.\n this.userAgent = [\n options['grpc.primary_user_agent'],\n `grpc-node-js/${clientVersion}`,\n options['grpc.secondary_user_agent'],\n ]\n .filter((e) => e)\n .join(' '); // remove falsey values first\n if ('grpc.keepalive_time_ms' in options) {\n this.keepaliveTimeMs = options['grpc.keepalive_time_ms'];\n }\n if ('grpc.keepalive_timeout_ms' in options) {\n this.keepaliveTimeoutMs = options['grpc.keepalive_timeout_ms'];\n }\n if ('grpc.keepalive_permit_without_calls' in options) {\n this.keepaliveWithoutCalls = options['grpc.keepalive_permit_without_calls'] === 1;\n }\n else {\n this.keepaliveWithoutCalls = false;\n }\n this.keepaliveIntervalId = setTimeout(() => { }, 0);\n clearTimeout(this.keepaliveIntervalId);\n this.keepaliveTimeoutId = setTimeout(() => { }, 0);\n clearTimeout(this.keepaliveTimeoutId);\n const backoffOptions = {\n initialDelay: options['grpc.initial_reconnect_backoff_ms'],\n maxDelay: options['grpc.max_reconnect_backoff_ms'],\n };\n this.backoffTimeout = new backoff_timeout_1.BackoffTimeout(() => {\n this.handleBackoffTimer();\n }, backoffOptions);\n this.subchannelAddressString = subchannelAddressToString(subchannelAddress);\n }\n handleBackoffTimer() {\n if (this.continueConnecting) {\n this.transitionToState([channel_1.ConnectivityState.TRANSIENT_FAILURE], channel_1.ConnectivityState.CONNECTING);\n }\n else {\n this.transitionToState([channel_1.ConnectivityState.TRANSIENT_FAILURE], channel_1.ConnectivityState.IDLE);\n }\n }\n /**\n * Start a backoff timer with the current nextBackoff timeout\n */\n startBackoff() {\n this.backoffTimeout.runOnce();\n }\n stopBackoff() {\n this.backoffTimeout.stop();\n this.backoffTimeout.reset();\n }\n sendPing() {\n logging.trace(constants_1.LogVerbosity.DEBUG, 'keepalive', 'Sending ping to ' + this.subchannelAddressString);\n this.keepaliveTimeoutId = setTimeout(() => {\n this.transitionToState([channel_1.ConnectivityState.READY], channel_1.ConnectivityState.IDLE);\n }, this.keepaliveTimeoutMs);\n this.session.ping((err, duration, payload) => {\n clearTimeout(this.keepaliveTimeoutId);\n });\n }\n startKeepalivePings() {\n this.keepaliveIntervalId = setInterval(() => {\n this.sendPing();\n }, this.keepaliveTimeMs);\n /* Don't send a ping immediately because whatever caused us to start\n * sending pings should also involve some network activity. */\n }\n stopKeepalivePings() {\n clearInterval(this.keepaliveIntervalId);\n clearTimeout(this.keepaliveTimeoutId);\n }\n createSession(proxyConnectionResult) {\n var _a, _b, _c;\n const targetAuthority = resolver_1.getDefaultAuthority((_a = proxyConnectionResult.realTarget) !== null && _a !== void 0 ? _a : this.channelTarget);\n let connectionOptions = this.credentials._getConnectionOptions() || {};\n connectionOptions.maxSendHeaderBlockLength = Number.MAX_SAFE_INTEGER;\n let addressScheme = 'http://';\n if ('secureContext' in connectionOptions) {\n addressScheme = 'https://';\n // If provided, the value of grpc.ssl_target_name_override should be used\n // to override the target hostname when checking server identity.\n // This option is used for testing only.\n if (this.options['grpc.ssl_target_name_override']) {\n const sslTargetNameOverride = this.options['grpc.ssl_target_name_override'];\n connectionOptions.checkServerIdentity = (host, cert) => {\n return tls_1.checkServerIdentity(sslTargetNameOverride, cert);\n };\n connectionOptions.servername = sslTargetNameOverride;\n }\n else {\n const authorityHostname = (_c = (_b = uri_parser_1.splitHostPort(targetAuthority)) === null || _b === void 0 ? void 0 : _b.host) !== null && _c !== void 0 ? _c : 'localhost';\n // We want to always set servername to support SNI\n connectionOptions.servername = authorityHostname;\n }\n if (proxyConnectionResult.socket) {\n /* This is part of the workaround for\n * https://github.com/nodejs/node/issues/32922. Without that bug,\n * proxyConnectionResult.socket would always be a plaintext socket and\n * this would say\n * connectionOptions.socket = proxyConnectionResult.socket; */\n connectionOptions.createConnection = (authority, option) => {\n return proxyConnectionResult.socket;\n };\n }\n }\n else {\n /* In all but the most recent versions of Node, http2.connect does not use\n * the options when establishing plaintext connections, so we need to\n * establish that connection explicitly. */\n connectionOptions.createConnection = (authority, option) => {\n if (proxyConnectionResult.socket) {\n return proxyConnectionResult.socket;\n }\n else {\n /* net.NetConnectOpts is declared in a way that is more restrictive\n * than what net.connect will actually accept, so we use the type\n * assertion to work around that. */\n return net.connect(this.subchannelAddress);\n }\n };\n }\n connectionOptions = Object.assign(Object.assign({}, connectionOptions), this.subchannelAddress);\n /* http2.connect uses the options here:\n * https://github.com/nodejs/node/blob/70c32a6d190e2b5d7b9ff9d5b6a459d14e8b7d59/lib/internal/http2/core.js#L3028-L3036\n * The spread operator overides earlier values with later ones, so any port\n * or host values in the options will be used rather than any values extracted\n * from the first argument. In addition, the path overrides the host and port,\n * as documented for plaintext connections here:\n * https://nodejs.org/api/net.html#net_socket_connect_options_connectlistener\n * and for TLS connections here:\n * https://nodejs.org/api/tls.html#tls_tls_connect_options_callback. In\n * earlier versions of Node, http2.connect passes these options to\n * tls.connect but not net.connect, so in the insecure case we still need\n * to set the createConnection option above to create the connection\n * explicitly. We cannot do that in the TLS case because http2.connect\n * passes necessary additional options to tls.connect.\n * The first argument just needs to be parseable as a URL and the scheme\n * determines whether the connection will be established over TLS or not.\n */\n const session = http2.connect(addressScheme + targetAuthority, connectionOptions);\n this.session = session;\n session.unref();\n /* For all of these events, check if the session at the time of the event\n * is the same one currently attached to this subchannel, to ensure that\n * old events from previous connection attempts cannot cause invalid state\n * transitions. */\n session.once('connect', () => {\n if (this.session === session) {\n this.transitionToState([channel_1.ConnectivityState.CONNECTING], channel_1.ConnectivityState.READY);\n }\n });\n session.once('close', () => {\n if (this.session === session) {\n this.transitionToState([channel_1.ConnectivityState.CONNECTING], channel_1.ConnectivityState.TRANSIENT_FAILURE);\n /* Transitioning directly to IDLE here should be OK because we are not\n * doing any backoff, because a connection was established at some\n * point */\n this.transitionToState([channel_1.ConnectivityState.READY], channel_1.ConnectivityState.IDLE);\n }\n });\n session.once('goaway', (errorCode, lastStreamID, opaqueData) => {\n if (this.session === session) {\n /* See the last paragraph of\n * https://github.com/grpc/proposal/blob/master/A8-client-side-keepalive.md#basic-keepalive */\n if (errorCode === http2.constants.NGHTTP2_ENHANCE_YOUR_CALM &&\n opaqueData.equals(tooManyPingsData)) {\n this.keepaliveTimeMs = Math.min(2 * this.keepaliveTimeMs, KEEPALIVE_MAX_TIME_MS);\n logging.log(constants_1.LogVerbosity.ERROR, `Connection to ${uri_parser_1.uriToString(this.channelTarget)} at ${this.subchannelAddressString} rejected by server because of excess pings. Increasing ping interval to ${this.keepaliveTimeMs} ms`);\n }\n trace(this.subchannelAddressString +\n ' connection closed by GOAWAY with code ' +\n errorCode);\n this.transitionToState([channel_1.ConnectivityState.CONNECTING, channel_1.ConnectivityState.READY], channel_1.ConnectivityState.IDLE);\n }\n });\n session.once('error', (error) => {\n /* Do nothing here. Any error should also trigger a close event, which is\n * where we want to handle that. */\n trace(this.subchannelAddressString +\n ' connection closed with error ' +\n error.message);\n });\n }\n startConnectingInternal() {\n var _a, _b;\n /* Pass connection options through to the proxy so that it's able to\n * upgrade it's connection to support tls if needed.\n * This is a workaround for https://github.com/nodejs/node/issues/32922\n * See https://github.com/grpc/grpc-node/pull/1369 for more info. */\n const connectionOptions = this.credentials._getConnectionOptions() || {};\n if ('secureContext' in connectionOptions) {\n connectionOptions.ALPNProtocols = ['h2'];\n // If provided, the value of grpc.ssl_target_name_override should be used\n // to override the target hostname when checking server identity.\n // This option is used for testing only.\n if (this.options['grpc.ssl_target_name_override']) {\n const sslTargetNameOverride = this.options['grpc.ssl_target_name_override'];\n connectionOptions.checkServerIdentity = (host, cert) => {\n return tls_1.checkServerIdentity(sslTargetNameOverride, cert);\n };\n connectionOptions.servername = sslTargetNameOverride;\n }\n else {\n if ('grpc.http_connect_target' in this.options) {\n /* This is more or less how servername will be set in createSession\n * if a connection is successfully established through the proxy.\n * If the proxy is not used, these connectionOptions are discarded\n * anyway */\n const targetPath = resolver_1.getDefaultAuthority((_a = uri_parser_1.parseUri(this.options['grpc.http_connect_target'])) !== null && _a !== void 0 ? _a : {\n path: 'localhost',\n });\n const hostPort = uri_parser_1.splitHostPort(targetPath);\n connectionOptions.servername = (_b = hostPort === null || hostPort === void 0 ? void 0 : hostPort.host) !== null && _b !== void 0 ? _b : targetPath;\n }\n }\n }\n http_proxy_1.getProxiedConnection(this.subchannelAddress, this.options, connectionOptions).then((result) => {\n this.createSession(result);\n }, (reason) => {\n this.transitionToState([channel_1.ConnectivityState.CONNECTING], channel_1.ConnectivityState.TRANSIENT_FAILURE);\n });\n }\n /**\n * Initiate a state transition from any element of oldStates to the new\n * state. If the current connectivityState is not in oldStates, do nothing.\n * @param oldStates The set of states to transition from\n * @param newState The state to transition to\n * @returns True if the state changed, false otherwise\n */\n transitionToState(oldStates, newState) {\n if (oldStates.indexOf(this.connectivityState) === -1) {\n return false;\n }\n trace(this.subchannelAddressString +\n ' ' +\n channel_1.ConnectivityState[this.connectivityState] +\n ' -> ' +\n channel_1.ConnectivityState[newState]);\n const previousState = this.connectivityState;\n this.connectivityState = newState;\n switch (newState) {\n case channel_1.ConnectivityState.READY:\n this.stopBackoff();\n this.session.socket.once('close', () => {\n for (const listener of this.disconnectListeners) {\n listener();\n }\n });\n if (this.keepaliveWithoutCalls) {\n this.startKeepalivePings();\n }\n break;\n case channel_1.ConnectivityState.CONNECTING:\n this.startBackoff();\n this.startConnectingInternal();\n this.continueConnecting = false;\n break;\n case channel_1.ConnectivityState.TRANSIENT_FAILURE:\n if (this.session) {\n this.session.close();\n }\n this.session = null;\n this.stopKeepalivePings();\n /* If the backoff timer has already ended by the time we get to the\n * TRANSIENT_FAILURE state, we want to immediately transition out of\n * TRANSIENT_FAILURE as though the backoff timer is ending right now */\n if (!this.backoffTimeout.isRunning()) {\n process.nextTick(() => {\n this.handleBackoffTimer();\n });\n }\n break;\n case channel_1.ConnectivityState.IDLE:\n if (this.session) {\n this.session.close();\n }\n this.session = null;\n this.stopKeepalivePings();\n break;\n default:\n throw new Error(`Invalid state: unknown ConnectivityState ${newState}`);\n }\n /* We use a shallow copy of the stateListeners array in case a listener\n * is removed during this iteration */\n for (const listener of [...this.stateListeners]) {\n listener(this, previousState, newState);\n }\n return true;\n }\n /**\n * Check if the subchannel associated with zero calls and with zero channels.\n * If so, shut it down.\n */\n checkBothRefcounts() {\n /* If no calls, channels, or subchannel pools have any more references to\n * this subchannel, we can be sure it will never be used again. */\n if (this.callRefcount === 0 && this.refcount === 0) {\n this.transitionToState([\n channel_1.ConnectivityState.CONNECTING,\n channel_1.ConnectivityState.IDLE,\n channel_1.ConnectivityState.READY,\n ], channel_1.ConnectivityState.TRANSIENT_FAILURE);\n }\n }\n callRef() {\n refTrace(this.subchannelAddressString +\n ' callRefcount ' +\n this.callRefcount +\n ' -> ' +\n (this.callRefcount + 1));\n if (this.callRefcount === 0) {\n if (this.session) {\n this.session.ref();\n }\n this.backoffTimeout.ref();\n if (!this.keepaliveWithoutCalls) {\n this.startKeepalivePings();\n }\n }\n this.callRefcount += 1;\n }\n callUnref() {\n refTrace(this.subchannelAddressString +\n ' callRefcount ' +\n this.callRefcount +\n ' -> ' +\n (this.callRefcount - 1));\n this.callRefcount -= 1;\n if (this.callRefcount === 0) {\n if (this.session) {\n this.session.unref();\n }\n this.backoffTimeout.unref();\n if (!this.keepaliveWithoutCalls) {\n this.stopKeepalivePings();\n }\n this.checkBothRefcounts();\n }\n }\n ref() {\n refTrace(this.subchannelAddressString +\n ' refcount ' +\n this.refcount +\n ' -> ' +\n (this.refcount + 1));\n this.refcount += 1;\n }\n unref() {\n refTrace(this.subchannelAddressString +\n ' refcount ' +\n this.refcount +\n ' -> ' +\n (this.refcount - 1));\n this.refcount -= 1;\n this.checkBothRefcounts();\n }\n unrefIfOneRef() {\n if (this.refcount === 1) {\n this.unref();\n return true;\n }\n return false;\n }\n /**\n * Start a stream on the current session with the given `metadata` as headers\n * and then attach it to the `callStream`. Must only be called if the\n * subchannel's current connectivity state is READY.\n * @param metadata\n * @param callStream\n */\n startCallStream(metadata, callStream, extraFilterFactory) {\n const headers = metadata.toHttp2Headers();\n headers[HTTP2_HEADER_AUTHORITY] = callStream.getHost();\n headers[HTTP2_HEADER_USER_AGENT] = this.userAgent;\n headers[HTTP2_HEADER_CONTENT_TYPE] = 'application/grpc';\n headers[HTTP2_HEADER_METHOD] = 'POST';\n headers[HTTP2_HEADER_PATH] = callStream.getMethod();\n headers[HTTP2_HEADER_TE] = 'trailers';\n let http2Stream;\n /* In theory, if an error is thrown by session.request because session has\n * become unusable (e.g. because it has received a goaway), this subchannel\n * should soon see the corresponding close or goaway event anyway and leave\n * READY. But we have seen reports that this does not happen\n * (https://github.com/googleapis/nodejs-firestore/issues/1023#issuecomment-653204096)\n * so for defense in depth, we just discard the session when we see an\n * error here.\n */\n try {\n http2Stream = this.session.request(headers);\n }\n catch (e) {\n this.transitionToState([channel_1.ConnectivityState.READY], channel_1.ConnectivityState.TRANSIENT_FAILURE);\n throw e;\n }\n let headersString = '';\n for (const header of Object.keys(headers)) {\n headersString += '\\t\\t' + header + ': ' + headers[header] + '\\n';\n }\n logging.trace(constants_1.LogVerbosity.DEBUG, 'call_stream', 'Starting stream on subchannel ' + this.subchannelAddressString + ' with headers\\n' + headersString);\n callStream.attachHttp2Stream(http2Stream, this, extraFilterFactory);\n }\n /**\n * If the subchannel is currently IDLE, start connecting and switch to the\n * CONNECTING state. If the subchannel is current in TRANSIENT_FAILURE,\n * the next time it would transition to IDLE, start connecting again instead.\n * Otherwise, do nothing.\n */\n startConnecting() {\n /* First, try to transition from IDLE to connecting. If that doesn't happen\n * because the state is not currently IDLE, check if it is\n * TRANSIENT_FAILURE, and if so indicate that it should go back to\n * connecting after the backoff timer ends. Otherwise do nothing */\n if (!this.transitionToState([channel_1.ConnectivityState.IDLE], channel_1.ConnectivityState.CONNECTING)) {\n if (this.connectivityState === channel_1.ConnectivityState.TRANSIENT_FAILURE) {\n this.continueConnecting = true;\n }\n }\n }\n /**\n * Get the subchannel's current connectivity state.\n */\n getConnectivityState() {\n return this.connectivityState;\n }\n /**\n * Add a listener function to be called whenever the subchannel's\n * connectivity state changes.\n * @param listener\n */\n addConnectivityStateListener(listener) {\n this.stateListeners.push(listener);\n }\n /**\n * Remove a listener previously added with `addConnectivityStateListener`\n * @param listener A reference to a function previously passed to\n * `addConnectivityStateListener`\n */\n removeConnectivityStateListener(listener) {\n const listenerIndex = this.stateListeners.indexOf(listener);\n if (listenerIndex > -1) {\n this.stateListeners.splice(listenerIndex, 1);\n }\n }\n addDisconnectListener(listener) {\n this.disconnectListeners.push(listener);\n }\n removeDisconnectListener(listener) {\n const listenerIndex = this.disconnectListeners.indexOf(listener);\n if (listenerIndex > -1) {\n this.disconnectListeners.splice(listenerIndex, 1);\n }\n }\n /**\n * Reset the backoff timeout, and immediately start connecting if in backoff.\n */\n resetBackoff() {\n this.backoffTimeout.reset();\n this.transitionToState([channel_1.ConnectivityState.TRANSIENT_FAILURE], channel_1.ConnectivityState.CONNECTING);\n }\n getAddress() {\n return this.subchannelAddressString;\n }\n}\nexports.Subchannel = Subchannel;\n//# sourceMappingURL=subchannel.js.map","\"use strict\";\n/*\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getDefaultRootsData = exports.CIPHER_SUITES = void 0;\nconst fs = require(\"fs\");\nexports.CIPHER_SUITES = process.env.GRPC_SSL_CIPHER_SUITES;\nconst DEFAULT_ROOTS_FILE_PATH = process.env.GRPC_DEFAULT_SSL_ROOTS_FILE_PATH;\nlet defaultRootsData = null;\nfunction getDefaultRootsData() {\n if (DEFAULT_ROOTS_FILE_PATH) {\n if (defaultRootsData === null) {\n defaultRootsData = fs.readFileSync(DEFAULT_ROOTS_FILE_PATH);\n }\n return defaultRootsData;\n }\n return null;\n}\nexports.getDefaultRootsData = getDefaultRootsData;\n//# sourceMappingURL=tls-helpers.js.map","\"use strict\";\n/*\n * Copyright 2020 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.uriToString = exports.splitHostPort = exports.parseUri = void 0;\n/*\n * The groups correspond to URI parts as follows:\n * 1. scheme\n * 2. authority\n * 3. path\n */\nconst URI_REGEX = /^(?:([A-Za-z0-9+.-]+):)?(?:\\/\\/([^/]*)\\/)?(.+)$/;\nfunction parseUri(uriString) {\n const parsedUri = URI_REGEX.exec(uriString);\n if (parsedUri === null) {\n return null;\n }\n return {\n scheme: parsedUri[1],\n authority: parsedUri[2],\n path: parsedUri[3],\n };\n}\nexports.parseUri = parseUri;\nconst NUMBER_REGEX = /^\\d+$/;\nfunction splitHostPort(path) {\n if (path.startsWith('[')) {\n const hostEnd = path.indexOf(']');\n if (hostEnd === -1) {\n return null;\n }\n const host = path.substring(1, hostEnd);\n /* Only an IPv6 address should be in bracketed notation, and an IPv6\n * address should have at least one colon */\n if (host.indexOf(':') === -1) {\n return null;\n }\n if (path.length > hostEnd + 1) {\n if (path[hostEnd + 1] === ':') {\n const portString = path.substring(hostEnd + 2);\n if (NUMBER_REGEX.test(portString)) {\n return {\n host: host,\n port: +portString,\n };\n }\n else {\n return null;\n }\n }\n else {\n return null;\n }\n }\n else {\n return {\n host,\n };\n }\n }\n else {\n const splitPath = path.split(':');\n /* Exactly one colon means that this is host:port. Zero colons means that\n * there is no port. And multiple colons means that this is a bare IPv6\n * address with no port */\n if (splitPath.length === 2) {\n if (NUMBER_REGEX.test(splitPath[1])) {\n return {\n host: splitPath[0],\n port: +splitPath[1],\n };\n }\n else {\n return null;\n }\n }\n else {\n return {\n host: path,\n };\n }\n }\n}\nexports.splitHostPort = splitHostPort;\nfunction uriToString(uri) {\n let result = '';\n if (uri.scheme !== undefined) {\n result += uri.scheme + ':';\n }\n if (uri.authority !== undefined) {\n result += '//' + uri.authority + '/';\n }\n result += uri.path;\n return result;\n}\nexports.uriToString = uriToString;\n//# sourceMappingURL=uri-parser.js.map","exports = module.exports = SemVer\n\nvar debug\n/* istanbul ignore next */\nif (typeof process === 'object' &&\n process.env &&\n process.env.NODE_DEBUG &&\n /\\bsemver\\b/i.test(process.env.NODE_DEBUG)) {\n debug = function () {\n var args = Array.prototype.slice.call(arguments, 0)\n args.unshift('SEMVER')\n console.log.apply(console, args)\n }\n} else {\n debug = function () {}\n}\n\n// Note: this is the semver.org version of the spec that it implements\n// Not necessarily the package version of this code.\nexports.SEMVER_SPEC_VERSION = '2.0.0'\n\nvar MAX_LENGTH = 256\nvar MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||\n /* istanbul ignore next */ 9007199254740991\n\n// Max safe segment length for coercion.\nvar MAX_SAFE_COMPONENT_LENGTH = 16\n\n// The actual regexps go on exports.re\nvar re = exports.re = []\nvar src = exports.src = []\nvar t = exports.tokens = {}\nvar R = 0\n\nfunction tok (n) {\n t[n] = R++\n}\n\n// The following Regular Expressions can be used for tokenizing,\n// validating, and parsing SemVer version strings.\n\n// ## Numeric Identifier\n// A single `0`, or a non-zero digit followed by zero or more digits.\n\ntok('NUMERICIDENTIFIER')\nsrc[t.NUMERICIDENTIFIER] = '0|[1-9]\\\\d*'\ntok('NUMERICIDENTIFIERLOOSE')\nsrc[t.NUMERICIDENTIFIERLOOSE] = '[0-9]+'\n\n// ## Non-numeric Identifier\n// Zero or more digits, followed by a letter or hyphen, and then zero or\n// more letters, digits, or hyphens.\n\ntok('NONNUMERICIDENTIFIER')\nsrc[t.NONNUMERICIDENTIFIER] = '\\\\d*[a-zA-Z-][a-zA-Z0-9-]*'\n\n// ## Main Version\n// Three dot-separated numeric identifiers.\n\ntok('MAINVERSION')\nsrc[t.MAINVERSION] = '(' + src[t.NUMERICIDENTIFIER] + ')\\\\.' +\n '(' + src[t.NUMERICIDENTIFIER] + ')\\\\.' +\n '(' + src[t.NUMERICIDENTIFIER] + ')'\n\ntok('MAINVERSIONLOOSE')\nsrc[t.MAINVERSIONLOOSE] = '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\\\.' +\n '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\\\.' +\n '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')'\n\n// ## Pre-release Version Identifier\n// A numeric identifier, or a non-numeric identifier.\n\ntok('PRERELEASEIDENTIFIER')\nsrc[t.PRERELEASEIDENTIFIER] = '(?:' + src[t.NUMERICIDENTIFIER] +\n '|' + src[t.NONNUMERICIDENTIFIER] + ')'\n\ntok('PRERELEASEIDENTIFIERLOOSE')\nsrc[t.PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[t.NUMERICIDENTIFIERLOOSE] +\n '|' + src[t.NONNUMERICIDENTIFIER] + ')'\n\n// ## Pre-release Version\n// Hyphen, followed by one or more dot-separated pre-release version\n// identifiers.\n\ntok('PRERELEASE')\nsrc[t.PRERELEASE] = '(?:-(' + src[t.PRERELEASEIDENTIFIER] +\n '(?:\\\\.' + src[t.PRERELEASEIDENTIFIER] + ')*))'\n\ntok('PRERELEASELOOSE')\nsrc[t.PRERELEASELOOSE] = '(?:-?(' + src[t.PRERELEASEIDENTIFIERLOOSE] +\n '(?:\\\\.' + src[t.PRERELEASEIDENTIFIERLOOSE] + ')*))'\n\n// ## Build Metadata Identifier\n// Any combination of digits, letters, or hyphens.\n\ntok('BUILDIDENTIFIER')\nsrc[t.BUILDIDENTIFIER] = '[0-9A-Za-z-]+'\n\n// ## Build Metadata\n// Plus sign, followed by one or more period-separated build metadata\n// identifiers.\n\ntok('BUILD')\nsrc[t.BUILD] = '(?:\\\\+(' + src[t.BUILDIDENTIFIER] +\n '(?:\\\\.' + src[t.BUILDIDENTIFIER] + ')*))'\n\n// ## Full Version String\n// A main version, followed optionally by a pre-release version and\n// build metadata.\n\n// Note that the only major, minor, patch, and pre-release sections of\n// the version string are capturing groups. The build metadata is not a\n// capturing group, because it should not ever be used in version\n// comparison.\n\ntok('FULL')\ntok('FULLPLAIN')\nsrc[t.FULLPLAIN] = 'v?' + src[t.MAINVERSION] +\n src[t.PRERELEASE] + '?' +\n src[t.BUILD] + '?'\n\nsrc[t.FULL] = '^' + src[t.FULLPLAIN] + '$'\n\n// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.\n// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty\n// common in the npm registry.\ntok('LOOSEPLAIN')\nsrc[t.LOOSEPLAIN] = '[v=\\\\s]*' + src[t.MAINVERSIONLOOSE] +\n src[t.PRERELEASELOOSE] + '?' +\n src[t.BUILD] + '?'\n\ntok('LOOSE')\nsrc[t.LOOSE] = '^' + src[t.LOOSEPLAIN] + '$'\n\ntok('GTLT')\nsrc[t.GTLT] = '((?:<|>)?=?)'\n\n// Something like \"2.*\" or \"1.2.x\".\n// Note that \"x.x\" is a valid xRange identifer, meaning \"any version\"\n// Only the first item is strictly required.\ntok('XRANGEIDENTIFIERLOOSE')\nsrc[t.XRANGEIDENTIFIERLOOSE] = src[t.NUMERICIDENTIFIERLOOSE] + '|x|X|\\\\*'\ntok('XRANGEIDENTIFIER')\nsrc[t.XRANGEIDENTIFIER] = src[t.NUMERICIDENTIFIER] + '|x|X|\\\\*'\n\ntok('XRANGEPLAIN')\nsrc[t.XRANGEPLAIN] = '[v=\\\\s]*(' + src[t.XRANGEIDENTIFIER] + ')' +\n '(?:\\\\.(' + src[t.XRANGEIDENTIFIER] + ')' +\n '(?:\\\\.(' + src[t.XRANGEIDENTIFIER] + ')' +\n '(?:' + src[t.PRERELEASE] + ')?' +\n src[t.BUILD] + '?' +\n ')?)?'\n\ntok('XRANGEPLAINLOOSE')\nsrc[t.XRANGEPLAINLOOSE] = '[v=\\\\s]*(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' +\n '(?:\\\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' +\n '(?:\\\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' +\n '(?:' + src[t.PRERELEASELOOSE] + ')?' +\n src[t.BUILD] + '?' +\n ')?)?'\n\ntok('XRANGE')\nsrc[t.XRANGE] = '^' + src[t.GTLT] + '\\\\s*' + src[t.XRANGEPLAIN] + '$'\ntok('XRANGELOOSE')\nsrc[t.XRANGELOOSE] = '^' + src[t.GTLT] + '\\\\s*' + src[t.XRANGEPLAINLOOSE] + '$'\n\n// Coercion.\n// Extract anything that could conceivably be a part of a valid semver\ntok('COERCE')\nsrc[t.COERCE] = '(^|[^\\\\d])' +\n '(\\\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' +\n '(?:\\\\.(\\\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' +\n '(?:\\\\.(\\\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' +\n '(?:$|[^\\\\d])'\ntok('COERCERTL')\nre[t.COERCERTL] = new RegExp(src[t.COERCE], 'g')\n\n// Tilde ranges.\n// Meaning is \"reasonably at or greater than\"\ntok('LONETILDE')\nsrc[t.LONETILDE] = '(?:~>?)'\n\ntok('TILDETRIM')\nsrc[t.TILDETRIM] = '(\\\\s*)' + src[t.LONETILDE] + '\\\\s+'\nre[t.TILDETRIM] = new RegExp(src[t.TILDETRIM], 'g')\nvar tildeTrimReplace = '$1~'\n\ntok('TILDE')\nsrc[t.TILDE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAIN] + '$'\ntok('TILDELOOSE')\nsrc[t.TILDELOOSE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAINLOOSE] + '$'\n\n// Caret ranges.\n// Meaning is \"at least and backwards compatible with\"\ntok('LONECARET')\nsrc[t.LONECARET] = '(?:\\\\^)'\n\ntok('CARETTRIM')\nsrc[t.CARETTRIM] = '(\\\\s*)' + src[t.LONECARET] + '\\\\s+'\nre[t.CARETTRIM] = new RegExp(src[t.CARETTRIM], 'g')\nvar caretTrimReplace = '$1^'\n\ntok('CARET')\nsrc[t.CARET] = '^' + src[t.LONECARET] + src[t.XRANGEPLAIN] + '$'\ntok('CARETLOOSE')\nsrc[t.CARETLOOSE] = '^' + src[t.LONECARET] + src[t.XRANGEPLAINLOOSE] + '$'\n\n// A simple gt/lt/eq thing, or just \"\" to indicate \"any version\"\ntok('COMPARATORLOOSE')\nsrc[t.COMPARATORLOOSE] = '^' + src[t.GTLT] + '\\\\s*(' + src[t.LOOSEPLAIN] + ')$|^$'\ntok('COMPARATOR')\nsrc[t.COMPARATOR] = '^' + src[t.GTLT] + '\\\\s*(' + src[t.FULLPLAIN] + ')$|^$'\n\n// An expression to strip any whitespace between the gtlt and the thing\n// it modifies, so that `> 1.2.3` ==> `>1.2.3`\ntok('COMPARATORTRIM')\nsrc[t.COMPARATORTRIM] = '(\\\\s*)' + src[t.GTLT] +\n '\\\\s*(' + src[t.LOOSEPLAIN] + '|' + src[t.XRANGEPLAIN] + ')'\n\n// this one has to use the /g flag\nre[t.COMPARATORTRIM] = new RegExp(src[t.COMPARATORTRIM], 'g')\nvar comparatorTrimReplace = '$1$2$3'\n\n// Something like `1.2.3 - 1.2.4`\n// Note that these all use the loose form, because they'll be\n// checked against either the strict or loose comparator form\n// later.\ntok('HYPHENRANGE')\nsrc[t.HYPHENRANGE] = '^\\\\s*(' + src[t.XRANGEPLAIN] + ')' +\n '\\\\s+-\\\\s+' +\n '(' + src[t.XRANGEPLAIN] + ')' +\n '\\\\s*$'\n\ntok('HYPHENRANGELOOSE')\nsrc[t.HYPHENRANGELOOSE] = '^\\\\s*(' + src[t.XRANGEPLAINLOOSE] + ')' +\n '\\\\s+-\\\\s+' +\n '(' + src[t.XRANGEPLAINLOOSE] + ')' +\n '\\\\s*$'\n\n// Star ranges basically just allow anything at all.\ntok('STAR')\nsrc[t.STAR] = '(<|>)?=?\\\\s*\\\\*'\n\n// Compile to actual regexp objects.\n// All are flag-free, unless they were created above with a flag.\nfor (var i = 0; i < R; i++) {\n debug(i, src[i])\n if (!re[i]) {\n re[i] = new RegExp(src[i])\n }\n}\n\nexports.parse = parse\nfunction parse (version, options) {\n if (!options || typeof options !== 'object') {\n options = {\n loose: !!options,\n includePrerelease: false\n }\n }\n\n if (version instanceof SemVer) {\n return version\n }\n\n if (typeof version !== 'string') {\n return null\n }\n\n if (version.length > MAX_LENGTH) {\n return null\n }\n\n var r = options.loose ? re[t.LOOSE] : re[t.FULL]\n if (!r.test(version)) {\n return null\n }\n\n try {\n return new SemVer(version, options)\n } catch (er) {\n return null\n }\n}\n\nexports.valid = valid\nfunction valid (version, options) {\n var v = parse(version, options)\n return v ? v.version : null\n}\n\nexports.clean = clean\nfunction clean (version, options) {\n var s = parse(version.trim().replace(/^[=v]+/, ''), options)\n return s ? s.version : null\n}\n\nexports.SemVer = SemVer\n\nfunction SemVer (version, options) {\n if (!options || typeof options !== 'object') {\n options = {\n loose: !!options,\n includePrerelease: false\n }\n }\n if (version instanceof SemVer) {\n if (version.loose === options.loose) {\n return version\n } else {\n version = version.version\n }\n } else if (typeof version !== 'string') {\n throw new TypeError('Invalid Version: ' + version)\n }\n\n if (version.length > MAX_LENGTH) {\n throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters')\n }\n\n if (!(this instanceof SemVer)) {\n return new SemVer(version, options)\n }\n\n debug('SemVer', version, options)\n this.options = options\n this.loose = !!options.loose\n\n var m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])\n\n if (!m) {\n throw new TypeError('Invalid Version: ' + version)\n }\n\n this.raw = version\n\n // these are actually numbers\n this.major = +m[1]\n this.minor = +m[2]\n this.patch = +m[3]\n\n if (this.major > MAX_SAFE_INTEGER || this.major < 0) {\n throw new TypeError('Invalid major version')\n }\n\n if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {\n throw new TypeError('Invalid minor version')\n }\n\n if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {\n throw new TypeError('Invalid patch version')\n }\n\n // numberify any prerelease numeric ids\n if (!m[4]) {\n this.prerelease = []\n } else {\n this.prerelease = m[4].split('.').map(function (id) {\n if (/^[0-9]+$/.test(id)) {\n var num = +id\n if (num >= 0 && num < MAX_SAFE_INTEGER) {\n return num\n }\n }\n return id\n })\n }\n\n this.build = m[5] ? m[5].split('.') : []\n this.format()\n}\n\nSemVer.prototype.format = function () {\n this.version = this.major + '.' + this.minor + '.' + this.patch\n if (this.prerelease.length) {\n this.version += '-' + this.prerelease.join('.')\n }\n return this.version\n}\n\nSemVer.prototype.toString = function () {\n return this.version\n}\n\nSemVer.prototype.compare = function (other) {\n debug('SemVer.compare', this.version, this.options, other)\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n return this.compareMain(other) || this.comparePre(other)\n}\n\nSemVer.prototype.compareMain = function (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n return compareIdentifiers(this.major, other.major) ||\n compareIdentifiers(this.minor, other.minor) ||\n compareIdentifiers(this.patch, other.patch)\n}\n\nSemVer.prototype.comparePre = function (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n // NOT having a prerelease is > having one\n if (this.prerelease.length && !other.prerelease.length) {\n return -1\n } else if (!this.prerelease.length && other.prerelease.length) {\n return 1\n } else if (!this.prerelease.length && !other.prerelease.length) {\n return 0\n }\n\n var i = 0\n do {\n var a = this.prerelease[i]\n var b = other.prerelease[i]\n debug('prerelease compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n}\n\nSemVer.prototype.compareBuild = function (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n var i = 0\n do {\n var a = this.build[i]\n var b = other.build[i]\n debug('prerelease compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n}\n\n// preminor will bump the version up to the next minor release, and immediately\n// down to pre-release. premajor and prepatch work the same way.\nSemVer.prototype.inc = function (release, identifier) {\n switch (release) {\n case 'premajor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor = 0\n this.major++\n this.inc('pre', identifier)\n break\n case 'preminor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor++\n this.inc('pre', identifier)\n break\n case 'prepatch':\n // If this is already a prerelease, it will bump to the next version\n // drop any prereleases that might already exist, since they are not\n // relevant at this point.\n this.prerelease.length = 0\n this.inc('patch', identifier)\n this.inc('pre', identifier)\n break\n // If the input is a non-prerelease version, this acts the same as\n // prepatch.\n case 'prerelease':\n if (this.prerelease.length === 0) {\n this.inc('patch', identifier)\n }\n this.inc('pre', identifier)\n break\n\n case 'major':\n // If this is a pre-major version, bump up to the same major version.\n // Otherwise increment major.\n // 1.0.0-5 bumps to 1.0.0\n // 1.1.0 bumps to 2.0.0\n if (this.minor !== 0 ||\n this.patch !== 0 ||\n this.prerelease.length === 0) {\n this.major++\n }\n this.minor = 0\n this.patch = 0\n this.prerelease = []\n break\n case 'minor':\n // If this is a pre-minor version, bump up to the same minor version.\n // Otherwise increment minor.\n // 1.2.0-5 bumps to 1.2.0\n // 1.2.1 bumps to 1.3.0\n if (this.patch !== 0 || this.prerelease.length === 0) {\n this.minor++\n }\n this.patch = 0\n this.prerelease = []\n break\n case 'patch':\n // If this is not a pre-release version, it will increment the patch.\n // If it is a pre-release it will bump up to the same patch version.\n // 1.2.0-5 patches to 1.2.0\n // 1.2.0 patches to 1.2.1\n if (this.prerelease.length === 0) {\n this.patch++\n }\n this.prerelease = []\n break\n // This probably shouldn't be used publicly.\n // 1.0.0 \"pre\" would become 1.0.0-0 which is the wrong direction.\n case 'pre':\n if (this.prerelease.length === 0) {\n this.prerelease = [0]\n } else {\n var i = this.prerelease.length\n while (--i >= 0) {\n if (typeof this.prerelease[i] === 'number') {\n this.prerelease[i]++\n i = -2\n }\n }\n if (i === -1) {\n // didn't increment anything\n this.prerelease.push(0)\n }\n }\n if (identifier) {\n // 1.2.0-beta.1 bumps to 1.2.0-beta.2,\n // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0\n if (this.prerelease[0] === identifier) {\n if (isNaN(this.prerelease[1])) {\n this.prerelease = [identifier, 0]\n }\n } else {\n this.prerelease = [identifier, 0]\n }\n }\n break\n\n default:\n throw new Error('invalid increment argument: ' + release)\n }\n this.format()\n this.raw = this.version\n return this\n}\n\nexports.inc = inc\nfunction inc (version, release, loose, identifier) {\n if (typeof (loose) === 'string') {\n identifier = loose\n loose = undefined\n }\n\n try {\n return new SemVer(version, loose).inc(release, identifier).version\n } catch (er) {\n return null\n }\n}\n\nexports.diff = diff\nfunction diff (version1, version2) {\n if (eq(version1, version2)) {\n return null\n } else {\n var v1 = parse(version1)\n var v2 = parse(version2)\n var prefix = ''\n if (v1.prerelease.length || v2.prerelease.length) {\n prefix = 'pre'\n var defaultResult = 'prerelease'\n }\n for (var key in v1) {\n if (key === 'major' || key === 'minor' || key === 'patch') {\n if (v1[key] !== v2[key]) {\n return prefix + key\n }\n }\n }\n return defaultResult // may be undefined\n }\n}\n\nexports.compareIdentifiers = compareIdentifiers\n\nvar numeric = /^[0-9]+$/\nfunction compareIdentifiers (a, b) {\n var anum = numeric.test(a)\n var bnum = numeric.test(b)\n\n if (anum && bnum) {\n a = +a\n b = +b\n }\n\n return a === b ? 0\n : (anum && !bnum) ? -1\n : (bnum && !anum) ? 1\n : a < b ? -1\n : 1\n}\n\nexports.rcompareIdentifiers = rcompareIdentifiers\nfunction rcompareIdentifiers (a, b) {\n return compareIdentifiers(b, a)\n}\n\nexports.major = major\nfunction major (a, loose) {\n return new SemVer(a, loose).major\n}\n\nexports.minor = minor\nfunction minor (a, loose) {\n return new SemVer(a, loose).minor\n}\n\nexports.patch = patch\nfunction patch (a, loose) {\n return new SemVer(a, loose).patch\n}\n\nexports.compare = compare\nfunction compare (a, b, loose) {\n return new SemVer(a, loose).compare(new SemVer(b, loose))\n}\n\nexports.compareLoose = compareLoose\nfunction compareLoose (a, b) {\n return compare(a, b, true)\n}\n\nexports.compareBuild = compareBuild\nfunction compareBuild (a, b, loose) {\n var versionA = new SemVer(a, loose)\n var versionB = new SemVer(b, loose)\n return versionA.compare(versionB) || versionA.compareBuild(versionB)\n}\n\nexports.rcompare = rcompare\nfunction rcompare (a, b, loose) {\n return compare(b, a, loose)\n}\n\nexports.sort = sort\nfunction sort (list, loose) {\n return list.sort(function (a, b) {\n return exports.compareBuild(a, b, loose)\n })\n}\n\nexports.rsort = rsort\nfunction rsort (list, loose) {\n return list.sort(function (a, b) {\n return exports.compareBuild(b, a, loose)\n })\n}\n\nexports.gt = gt\nfunction gt (a, b, loose) {\n return compare(a, b, loose) > 0\n}\n\nexports.lt = lt\nfunction lt (a, b, loose) {\n return compare(a, b, loose) < 0\n}\n\nexports.eq = eq\nfunction eq (a, b, loose) {\n return compare(a, b, loose) === 0\n}\n\nexports.neq = neq\nfunction neq (a, b, loose) {\n return compare(a, b, loose) !== 0\n}\n\nexports.gte = gte\nfunction gte (a, b, loose) {\n return compare(a, b, loose) >= 0\n}\n\nexports.lte = lte\nfunction lte (a, b, loose) {\n return compare(a, b, loose) <= 0\n}\n\nexports.cmp = cmp\nfunction cmp (a, op, b, loose) {\n switch (op) {\n case '===':\n if (typeof a === 'object')\n a = a.version\n if (typeof b === 'object')\n b = b.version\n return a === b\n\n case '!==':\n if (typeof a === 'object')\n a = a.version\n if (typeof b === 'object')\n b = b.version\n return a !== b\n\n case '':\n case '=':\n case '==':\n return eq(a, b, loose)\n\n case '!=':\n return neq(a, b, loose)\n\n case '>':\n return gt(a, b, loose)\n\n case '>=':\n return gte(a, b, loose)\n\n case '<':\n return lt(a, b, loose)\n\n case '<=':\n return lte(a, b, loose)\n\n default:\n throw new TypeError('Invalid operator: ' + op)\n }\n}\n\nexports.Comparator = Comparator\nfunction Comparator (comp, options) {\n if (!options || typeof options !== 'object') {\n options = {\n loose: !!options,\n includePrerelease: false\n }\n }\n\n if (comp instanceof Comparator) {\n if (comp.loose === !!options.loose) {\n return comp\n } else {\n comp = comp.value\n }\n }\n\n if (!(this instanceof Comparator)) {\n return new Comparator(comp, options)\n }\n\n debug('comparator', comp, options)\n this.options = options\n this.loose = !!options.loose\n this.parse(comp)\n\n if (this.semver === ANY) {\n this.value = ''\n } else {\n this.value = this.operator + this.semver.version\n }\n\n debug('comp', this)\n}\n\nvar ANY = {}\nComparator.prototype.parse = function (comp) {\n var r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]\n var m = comp.match(r)\n\n if (!m) {\n throw new TypeError('Invalid comparator: ' + comp)\n }\n\n this.operator = m[1] !== undefined ? m[1] : ''\n if (this.operator === '=') {\n this.operator = ''\n }\n\n // if it literally is just '>' or '' then allow anything.\n if (!m[2]) {\n this.semver = ANY\n } else {\n this.semver = new SemVer(m[2], this.options.loose)\n }\n}\n\nComparator.prototype.toString = function () {\n return this.value\n}\n\nComparator.prototype.test = function (version) {\n debug('Comparator.test', version, this.options.loose)\n\n if (this.semver === ANY || version === ANY) {\n return true\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n return cmp(version, this.operator, this.semver, this.options)\n}\n\nComparator.prototype.intersects = function (comp, options) {\n if (!(comp instanceof Comparator)) {\n throw new TypeError('a Comparator is required')\n }\n\n if (!options || typeof options !== 'object') {\n options = {\n loose: !!options,\n includePrerelease: false\n }\n }\n\n var rangeTmp\n\n if (this.operator === '') {\n if (this.value === '') {\n return true\n }\n rangeTmp = new Range(comp.value, options)\n return satisfies(this.value, rangeTmp, options)\n } else if (comp.operator === '') {\n if (comp.value === '') {\n return true\n }\n rangeTmp = new Range(this.value, options)\n return satisfies(comp.semver, rangeTmp, options)\n }\n\n var sameDirectionIncreasing =\n (this.operator === '>=' || this.operator === '>') &&\n (comp.operator === '>=' || comp.operator === '>')\n var sameDirectionDecreasing =\n (this.operator === '<=' || this.operator === '<') &&\n (comp.operator === '<=' || comp.operator === '<')\n var sameSemVer = this.semver.version === comp.semver.version\n var differentDirectionsInclusive =\n (this.operator === '>=' || this.operator === '<=') &&\n (comp.operator === '>=' || comp.operator === '<=')\n var oppositeDirectionsLessThan =\n cmp(this.semver, '<', comp.semver, options) &&\n ((this.operator === '>=' || this.operator === '>') &&\n (comp.operator === '<=' || comp.operator === '<'))\n var oppositeDirectionsGreaterThan =\n cmp(this.semver, '>', comp.semver, options) &&\n ((this.operator === '<=' || this.operator === '<') &&\n (comp.operator === '>=' || comp.operator === '>'))\n\n return sameDirectionIncreasing || sameDirectionDecreasing ||\n (sameSemVer && differentDirectionsInclusive) ||\n oppositeDirectionsLessThan || oppositeDirectionsGreaterThan\n}\n\nexports.Range = Range\nfunction Range (range, options) {\n if (!options || typeof options !== 'object') {\n options = {\n loose: !!options,\n includePrerelease: false\n }\n }\n\n if (range instanceof Range) {\n if (range.loose === !!options.loose &&\n range.includePrerelease === !!options.includePrerelease) {\n return range\n } else {\n return new Range(range.raw, options)\n }\n }\n\n if (range instanceof Comparator) {\n return new Range(range.value, options)\n }\n\n if (!(this instanceof Range)) {\n return new Range(range, options)\n }\n\n this.options = options\n this.loose = !!options.loose\n this.includePrerelease = !!options.includePrerelease\n\n // First, split based on boolean or ||\n this.raw = range\n this.set = range.split(/\\s*\\|\\|\\s*/).map(function (range) {\n return this.parseRange(range.trim())\n }, this).filter(function (c) {\n // throw out any that are not relevant for whatever reason\n return c.length\n })\n\n if (!this.set.length) {\n throw new TypeError('Invalid SemVer Range: ' + range)\n }\n\n this.format()\n}\n\nRange.prototype.format = function () {\n this.range = this.set.map(function (comps) {\n return comps.join(' ').trim()\n }).join('||').trim()\n return this.range\n}\n\nRange.prototype.toString = function () {\n return this.range\n}\n\nRange.prototype.parseRange = function (range) {\n var loose = this.options.loose\n range = range.trim()\n // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`\n var hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]\n range = range.replace(hr, hyphenReplace)\n debug('hyphen replace', range)\n // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`\n range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)\n debug('comparator trim', range, re[t.COMPARATORTRIM])\n\n // `~ 1.2.3` => `~1.2.3`\n range = range.replace(re[t.TILDETRIM], tildeTrimReplace)\n\n // `^ 1.2.3` => `^1.2.3`\n range = range.replace(re[t.CARETTRIM], caretTrimReplace)\n\n // normalize spaces\n range = range.split(/\\s+/).join(' ')\n\n // At this point, the range is completely trimmed and\n // ready to be split into comparators.\n\n var compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]\n var set = range.split(' ').map(function (comp) {\n return parseComparator(comp, this.options)\n }, this).join(' ').split(/\\s+/)\n if (this.options.loose) {\n // in loose mode, throw out any that are not valid comparators\n set = set.filter(function (comp) {\n return !!comp.match(compRe)\n })\n }\n set = set.map(function (comp) {\n return new Comparator(comp, this.options)\n }, this)\n\n return set\n}\n\nRange.prototype.intersects = function (range, options) {\n if (!(range instanceof Range)) {\n throw new TypeError('a Range is required')\n }\n\n return this.set.some(function (thisComparators) {\n return (\n isSatisfiable(thisComparators, options) &&\n range.set.some(function (rangeComparators) {\n return (\n isSatisfiable(rangeComparators, options) &&\n thisComparators.every(function (thisComparator) {\n return rangeComparators.every(function (rangeComparator) {\n return thisComparator.intersects(rangeComparator, options)\n })\n })\n )\n })\n )\n })\n}\n\n// take a set of comparators and determine whether there\n// exists a version which can satisfy it\nfunction isSatisfiable (comparators, options) {\n var result = true\n var remainingComparators = comparators.slice()\n var testComparator = remainingComparators.pop()\n\n while (result && remainingComparators.length) {\n result = remainingComparators.every(function (otherComparator) {\n return testComparator.intersects(otherComparator, options)\n })\n\n testComparator = remainingComparators.pop()\n }\n\n return result\n}\n\n// Mostly just for testing and legacy API reasons\nexports.toComparators = toComparators\nfunction toComparators (range, options) {\n return new Range(range, options).set.map(function (comp) {\n return comp.map(function (c) {\n return c.value\n }).join(' ').trim().split(' ')\n })\n}\n\n// comprised of xranges, tildes, stars, and gtlt's at this point.\n// already replaced the hyphen ranges\n// turn into a set of JUST comparators.\nfunction parseComparator (comp, options) {\n debug('comp', comp, options)\n comp = replaceCarets(comp, options)\n debug('caret', comp)\n comp = replaceTildes(comp, options)\n debug('tildes', comp)\n comp = replaceXRanges(comp, options)\n debug('xrange', comp)\n comp = replaceStars(comp, options)\n debug('stars', comp)\n return comp\n}\n\nfunction isX (id) {\n return !id || id.toLowerCase() === 'x' || id === '*'\n}\n\n// ~, ~> --> * (any, kinda silly)\n// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0\n// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0\n// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0\n// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0\n// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0\nfunction replaceTildes (comp, options) {\n return comp.trim().split(/\\s+/).map(function (comp) {\n return replaceTilde(comp, options)\n }).join(' ')\n}\n\nfunction replaceTilde (comp, options) {\n var r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]\n return comp.replace(r, function (_, M, m, p, pr) {\n debug('tilde', comp, _, M, m, p, pr)\n var ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'\n } else if (isX(p)) {\n // ~1.2 == >=1.2.0 <1.3.0\n ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'\n } else if (pr) {\n debug('replaceTilde pr', pr)\n ret = '>=' + M + '.' + m + '.' + p + '-' + pr +\n ' <' + M + '.' + (+m + 1) + '.0'\n } else {\n // ~1.2.3 == >=1.2.3 <1.3.0\n ret = '>=' + M + '.' + m + '.' + p +\n ' <' + M + '.' + (+m + 1) + '.0'\n }\n\n debug('tilde return', ret)\n return ret\n })\n}\n\n// ^ --> * (any, kinda silly)\n// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0\n// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0\n// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0\n// ^1.2.3 --> >=1.2.3 <2.0.0\n// ^1.2.0 --> >=1.2.0 <2.0.0\nfunction replaceCarets (comp, options) {\n return comp.trim().split(/\\s+/).map(function (comp) {\n return replaceCaret(comp, options)\n }).join(' ')\n}\n\nfunction replaceCaret (comp, options) {\n debug('caret', comp, options)\n var r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]\n return comp.replace(r, function (_, M, m, p, pr) {\n debug('caret', comp, _, M, m, p, pr)\n var ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'\n } else if (isX(p)) {\n if (M === '0') {\n ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'\n } else {\n ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0'\n }\n } else if (pr) {\n debug('replaceCaret pr', pr)\n if (M === '0') {\n if (m === '0') {\n ret = '>=' + M + '.' + m + '.' + p + '-' + pr +\n ' <' + M + '.' + m + '.' + (+p + 1)\n } else {\n ret = '>=' + M + '.' + m + '.' + p + '-' + pr +\n ' <' + M + '.' + (+m + 1) + '.0'\n }\n } else {\n ret = '>=' + M + '.' + m + '.' + p + '-' + pr +\n ' <' + (+M + 1) + '.0.0'\n }\n } else {\n debug('no pr')\n if (M === '0') {\n if (m === '0') {\n ret = '>=' + M + '.' + m + '.' + p +\n ' <' + M + '.' + m + '.' + (+p + 1)\n } else {\n ret = '>=' + M + '.' + m + '.' + p +\n ' <' + M + '.' + (+m + 1) + '.0'\n }\n } else {\n ret = '>=' + M + '.' + m + '.' + p +\n ' <' + (+M + 1) + '.0.0'\n }\n }\n\n debug('caret return', ret)\n return ret\n })\n}\n\nfunction replaceXRanges (comp, options) {\n debug('replaceXRanges', comp, options)\n return comp.split(/\\s+/).map(function (comp) {\n return replaceXRange(comp, options)\n }).join(' ')\n}\n\nfunction replaceXRange (comp, options) {\n comp = comp.trim()\n var r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]\n return comp.replace(r, function (ret, gtlt, M, m, p, pr) {\n debug('xRange', comp, ret, gtlt, M, m, p, pr)\n var xM = isX(M)\n var xm = xM || isX(m)\n var xp = xm || isX(p)\n var anyX = xp\n\n if (gtlt === '=' && anyX) {\n gtlt = ''\n }\n\n // if we're including prereleases in the match, then we need\n // to fix this to -0, the lowest possible prerelease value\n pr = options.includePrerelease ? '-0' : ''\n\n if (xM) {\n if (gtlt === '>' || gtlt === '<') {\n // nothing is allowed\n ret = '<0.0.0-0'\n } else {\n // nothing is forbidden\n ret = '*'\n }\n } else if (gtlt && anyX) {\n // we know patch is an x, because we have any x at all.\n // replace X with 0\n if (xm) {\n m = 0\n }\n p = 0\n\n if (gtlt === '>') {\n // >1 => >=2.0.0\n // >1.2 => >=1.3.0\n // >1.2.3 => >= 1.2.4\n gtlt = '>='\n if (xm) {\n M = +M + 1\n m = 0\n p = 0\n } else {\n m = +m + 1\n p = 0\n }\n } else if (gtlt === '<=') {\n // <=0.7.x is actually <0.8.0, since any 0.7.x should\n // pass. Similarly, <=7.x is actually <8.0.0, etc.\n gtlt = '<'\n if (xm) {\n M = +M + 1\n } else {\n m = +m + 1\n }\n }\n\n ret = gtlt + M + '.' + m + '.' + p + pr\n } else if (xm) {\n ret = '>=' + M + '.0.0' + pr + ' <' + (+M + 1) + '.0.0' + pr\n } else if (xp) {\n ret = '>=' + M + '.' + m + '.0' + pr +\n ' <' + M + '.' + (+m + 1) + '.0' + pr\n }\n\n debug('xRange return', ret)\n\n return ret\n })\n}\n\n// Because * is AND-ed with everything else in the comparator,\n// and '' means \"any version\", just remove the *s entirely.\nfunction replaceStars (comp, options) {\n debug('replaceStars', comp, options)\n // Looseness is ignored here. star is always as loose as it gets!\n return comp.trim().replace(re[t.STAR], '')\n}\n\n// This function is passed to string.replace(re[t.HYPHENRANGE])\n// M, m, patch, prerelease, build\n// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5\n// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do\n// 1.2 - 3.4 => >=1.2.0 <3.5.0\nfunction hyphenReplace ($0,\n from, fM, fm, fp, fpr, fb,\n to, tM, tm, tp, tpr, tb) {\n if (isX(fM)) {\n from = ''\n } else if (isX(fm)) {\n from = '>=' + fM + '.0.0'\n } else if (isX(fp)) {\n from = '>=' + fM + '.' + fm + '.0'\n } else {\n from = '>=' + from\n }\n\n if (isX(tM)) {\n to = ''\n } else if (isX(tm)) {\n to = '<' + (+tM + 1) + '.0.0'\n } else if (isX(tp)) {\n to = '<' + tM + '.' + (+tm + 1) + '.0'\n } else if (tpr) {\n to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr\n } else {\n to = '<=' + to\n }\n\n return (from + ' ' + to).trim()\n}\n\n// if ANY of the sets match ALL of its comparators, then pass\nRange.prototype.test = function (version) {\n if (!version) {\n return false\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n for (var i = 0; i < this.set.length; i++) {\n if (testSet(this.set[i], version, this.options)) {\n return true\n }\n }\n return false\n}\n\nfunction testSet (set, version, options) {\n for (var i = 0; i < set.length; i++) {\n if (!set[i].test(version)) {\n return false\n }\n }\n\n if (version.prerelease.length && !options.includePrerelease) {\n // Find the set of versions that are allowed to have prereleases\n // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0\n // That should allow `1.2.3-pr.2` to pass.\n // However, `1.2.4-alpha.notready` should NOT be allowed,\n // even though it's within the range set by the comparators.\n for (i = 0; i < set.length; i++) {\n debug(set[i].semver)\n if (set[i].semver === ANY) {\n continue\n }\n\n if (set[i].semver.prerelease.length > 0) {\n var allowed = set[i].semver\n if (allowed.major === version.major &&\n allowed.minor === version.minor &&\n allowed.patch === version.patch) {\n return true\n }\n }\n }\n\n // Version has a -pre, but it's not one of the ones we like.\n return false\n }\n\n return true\n}\n\nexports.satisfies = satisfies\nfunction satisfies (version, range, options) {\n try {\n range = new Range(range, options)\n } catch (er) {\n return false\n }\n return range.test(version)\n}\n\nexports.maxSatisfying = maxSatisfying\nfunction maxSatisfying (versions, range, options) {\n var max = null\n var maxSV = null\n try {\n var rangeObj = new Range(range, options)\n } catch (er) {\n return null\n }\n versions.forEach(function (v) {\n if (rangeObj.test(v)) {\n // satisfies(v, range, options)\n if (!max || maxSV.compare(v) === -1) {\n // compare(max, v, true)\n max = v\n maxSV = new SemVer(max, options)\n }\n }\n })\n return max\n}\n\nexports.minSatisfying = minSatisfying\nfunction minSatisfying (versions, range, options) {\n var min = null\n var minSV = null\n try {\n var rangeObj = new Range(range, options)\n } catch (er) {\n return null\n }\n versions.forEach(function (v) {\n if (rangeObj.test(v)) {\n // satisfies(v, range, options)\n if (!min || minSV.compare(v) === 1) {\n // compare(min, v, true)\n min = v\n minSV = new SemVer(min, options)\n }\n }\n })\n return min\n}\n\nexports.minVersion = minVersion\nfunction minVersion (range, loose) {\n range = new Range(range, loose)\n\n var minver = new SemVer('0.0.0')\n if (range.test(minver)) {\n return minver\n }\n\n minver = new SemVer('0.0.0-0')\n if (range.test(minver)) {\n return minver\n }\n\n minver = null\n for (var i = 0; i < range.set.length; ++i) {\n var comparators = range.set[i]\n\n comparators.forEach(function (comparator) {\n // Clone to avoid manipulating the comparator's semver object.\n var compver = new SemVer(comparator.semver.version)\n switch (comparator.operator) {\n case '>':\n if (compver.prerelease.length === 0) {\n compver.patch++\n } else {\n compver.prerelease.push(0)\n }\n compver.raw = compver.format()\n /* fallthrough */\n case '':\n case '>=':\n if (!minver || gt(minver, compver)) {\n minver = compver\n }\n break\n case '<':\n case '<=':\n /* Ignore maximum versions */\n break\n /* istanbul ignore next */\n default:\n throw new Error('Unexpected operation: ' + comparator.operator)\n }\n })\n }\n\n if (minver && range.test(minver)) {\n return minver\n }\n\n return null\n}\n\nexports.validRange = validRange\nfunction validRange (range, options) {\n try {\n // Return '*' instead of '' so that truthiness works.\n // This will throw if it's invalid anyway\n return new Range(range, options).range || '*'\n } catch (er) {\n return null\n }\n}\n\n// Determine if version is less than all the versions possible in the range\nexports.ltr = ltr\nfunction ltr (version, range, options) {\n return outside(version, range, '<', options)\n}\n\n// Determine if version is greater than all the versions possible in the range.\nexports.gtr = gtr\nfunction gtr (version, range, options) {\n return outside(version, range, '>', options)\n}\n\nexports.outside = outside\nfunction outside (version, range, hilo, options) {\n version = new SemVer(version, options)\n range = new Range(range, options)\n\n var gtfn, ltefn, ltfn, comp, ecomp\n switch (hilo) {\n case '>':\n gtfn = gt\n ltefn = lte\n ltfn = lt\n comp = '>'\n ecomp = '>='\n break\n case '<':\n gtfn = lt\n ltefn = gte\n ltfn = gt\n comp = '<'\n ecomp = '<='\n break\n default:\n throw new TypeError('Must provide a hilo val of \"<\" or \">\"')\n }\n\n // If it satisifes the range it is not outside\n if (satisfies(version, range, options)) {\n return false\n }\n\n // From now on, variable terms are as if we're in \"gtr\" mode.\n // but note that everything is flipped for the \"ltr\" function.\n\n for (var i = 0; i < range.set.length; ++i) {\n var comparators = range.set[i]\n\n var high = null\n var low = null\n\n comparators.forEach(function (comparator) {\n if (comparator.semver === ANY) {\n comparator = new Comparator('>=0.0.0')\n }\n high = high || comparator\n low = low || comparator\n if (gtfn(comparator.semver, high.semver, options)) {\n high = comparator\n } else if (ltfn(comparator.semver, low.semver, options)) {\n low = comparator\n }\n })\n\n // If the edge version comparator has a operator then our version\n // isn't outside it\n if (high.operator === comp || high.operator === ecomp) {\n return false\n }\n\n // If the lowest version comparator has an operator and our version\n // is less than it then it isn't higher than the range\n if ((!low.operator || low.operator === comp) &&\n ltefn(version, low.semver)) {\n return false\n } else if (low.operator === ecomp && ltfn(version, low.semver)) {\n return false\n }\n }\n return true\n}\n\nexports.prerelease = prerelease\nfunction prerelease (version, options) {\n var parsed = parse(version, options)\n return (parsed && parsed.prerelease.length) ? parsed.prerelease : null\n}\n\nexports.intersects = intersects\nfunction intersects (r1, r2, options) {\n r1 = new Range(r1, options)\n r2 = new Range(r2, options)\n return r1.intersects(r2)\n}\n\nexports.coerce = coerce\nfunction coerce (version, options) {\n if (version instanceof SemVer) {\n return version\n }\n\n if (typeof version === 'number') {\n version = String(version)\n }\n\n if (typeof version !== 'string') {\n return null\n }\n\n options = options || {}\n\n var match = null\n if (!options.rtl) {\n match = version.match(re[t.COERCE])\n } else {\n // Find the right-most coercible string that does not share\n // a terminus with a more left-ward coercible string.\n // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'\n //\n // Walk through the string checking with a /g regexp\n // Manually set the index so as to pick up overlapping matches.\n // Stop when we get a match that ends at the string end, since no\n // coercible string can be more right-ward without the same terminus.\n var next\n while ((next = re[t.COERCERTL].exec(version)) &&\n (!match || match.index + match[0].length !== version.length)\n ) {\n if (!match ||\n next.index + next[0].length !== match.index + match[0].length) {\n match = next\n }\n re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length\n }\n // leave it in a clean state\n re[t.COERCERTL].lastIndex = -1\n }\n\n if (match === null) {\n return null\n }\n\n return parse(match[2] +\n '.' + (match[3] || '0') +\n '.' + (match[4] || '0'), options)\n}\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nasync function auth(token) {\n const tokenType = token.split(/\\./).length === 3 ? \"app\" : /^v\\d+\\./.test(token) ? \"installation\" : \"oauth\";\n return {\n type: \"token\",\n token: token,\n tokenType\n };\n}\n\n/**\n * Prefix token for usage in the Authorization header\n *\n * @param token OAuth token or JSON Web Token\n */\nfunction withAuthorizationPrefix(token) {\n if (token.split(/\\./).length === 3) {\n return `bearer ${token}`;\n }\n\n return `token ${token}`;\n}\n\nasync function hook(token, request, route, parameters) {\n const endpoint = request.endpoint.merge(route, parameters);\n endpoint.headers.authorization = withAuthorizationPrefix(token);\n return request(endpoint);\n}\n\nconst createTokenAuth = function createTokenAuth(token) {\n if (!token) {\n throw new Error(\"[@octokit/auth-token] No token passed to createTokenAuth\");\n }\n\n if (typeof token !== \"string\") {\n throw new Error(\"[@octokit/auth-token] Token passed to createTokenAuth is not a string\");\n }\n\n token = token.replace(/^(token|bearer) +/i, \"\");\n return Object.assign(auth.bind(null, token), {\n hook: hook.bind(null, token)\n });\n};\n\nexports.createTokenAuth = createTokenAuth;\n//# sourceMappingURL=index.js.map\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nvar universalUserAgent = require('universal-user-agent');\nvar beforeAfterHook = require('before-after-hook');\nvar request = require('@octokit/request');\nvar graphql = require('@octokit/graphql');\nvar authToken = require('@octokit/auth-token');\n\nfunction _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n\n return target;\n}\n\nfunction _objectWithoutProperties(source, excluded) {\n if (source == null) return {};\n\n var target = _objectWithoutPropertiesLoose(source, excluded);\n\n var key, i;\n\n if (Object.getOwnPropertySymbols) {\n var sourceSymbolKeys = Object.getOwnPropertySymbols(source);\n\n for (i = 0; i < sourceSymbolKeys.length; i++) {\n key = sourceSymbolKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;\n target[key] = source[key];\n }\n }\n\n return target;\n}\n\nconst VERSION = \"3.2.5\";\n\nclass Octokit {\n constructor(options = {}) {\n const hook = new beforeAfterHook.Collection();\n const requestDefaults = {\n baseUrl: request.request.endpoint.DEFAULTS.baseUrl,\n headers: {},\n request: Object.assign({}, options.request, {\n hook: hook.bind(null, \"request\")\n }),\n mediaType: {\n previews: [],\n format: \"\"\n }\n }; // prepend default user agent with `options.userAgent` if set\n\n requestDefaults.headers[\"user-agent\"] = [options.userAgent, `octokit-core.js/${VERSION} ${universalUserAgent.getUserAgent()}`].filter(Boolean).join(\" \");\n\n if (options.baseUrl) {\n requestDefaults.baseUrl = options.baseUrl;\n }\n\n if (options.previews) {\n requestDefaults.mediaType.previews = options.previews;\n }\n\n if (options.timeZone) {\n requestDefaults.headers[\"time-zone\"] = options.timeZone;\n }\n\n this.request = request.request.defaults(requestDefaults);\n this.graphql = graphql.withCustomRequest(this.request).defaults(requestDefaults);\n this.log = Object.assign({\n debug: () => {},\n info: () => {},\n warn: console.warn.bind(console),\n error: console.error.bind(console)\n }, options.log);\n this.hook = hook; // (1) If neither `options.authStrategy` nor `options.auth` are set, the `octokit` instance\n // is unauthenticated. The `this.auth()` method is a no-op and no request hook is registered.\n // (2) If only `options.auth` is set, use the default token authentication strategy.\n // (3) If `options.authStrategy` is set then use it and pass in `options.auth`. Always pass own request as many strategies accept a custom request instance.\n // TODO: type `options.auth` based on `options.authStrategy`.\n\n if (!options.authStrategy) {\n if (!options.auth) {\n // (1)\n this.auth = async () => ({\n type: \"unauthenticated\"\n });\n } else {\n // (2)\n const auth = authToken.createTokenAuth(options.auth); // @ts-ignore ¯\\_(ツ)_/¯\n\n hook.wrap(\"request\", auth.hook);\n this.auth = auth;\n }\n } else {\n const {\n authStrategy\n } = options,\n otherOptions = _objectWithoutProperties(options, [\"authStrategy\"]);\n\n const auth = authStrategy(Object.assign({\n request: this.request,\n log: this.log,\n // we pass the current octokit instance as well as its constructor options\n // to allow for authentication strategies that return a new octokit instance\n // that shares the same internal state as the current one. The original\n // requirement for this was the \"event-octokit\" authentication strategy\n // of https://github.com/probot/octokit-auth-probot.\n octokit: this,\n octokitOptions: otherOptions\n }, options.auth)); // @ts-ignore ¯\\_(ツ)_/¯\n\n hook.wrap(\"request\", auth.hook);\n this.auth = auth;\n } // apply plugins\n // https://stackoverflow.com/a/16345172\n\n\n const classConstructor = this.constructor;\n classConstructor.plugins.forEach(plugin => {\n Object.assign(this, plugin(this, options));\n });\n }\n\n static defaults(defaults) {\n const OctokitWithDefaults = class extends this {\n constructor(...args) {\n const options = args[0] || {};\n\n if (typeof defaults === \"function\") {\n super(defaults(options));\n return;\n }\n\n super(Object.assign({}, defaults, options, options.userAgent && defaults.userAgent ? {\n userAgent: `${options.userAgent} ${defaults.userAgent}`\n } : null));\n }\n\n };\n return OctokitWithDefaults;\n }\n /**\n * Attach a plugin (or many) to your Octokit instance.\n *\n * @example\n * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...)\n */\n\n\n static plugin(...newPlugins) {\n var _a;\n\n const currentPlugins = this.plugins;\n const NewOctokit = (_a = class extends this {}, _a.plugins = currentPlugins.concat(newPlugins.filter(plugin => !currentPlugins.includes(plugin))), _a);\n return NewOctokit;\n }\n\n}\nOctokit.VERSION = VERSION;\nOctokit.plugins = [];\n\nexports.Octokit = Octokit;\n//# sourceMappingURL=index.js.map\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nvar isPlainObject = require('is-plain-object');\nvar universalUserAgent = require('universal-user-agent');\n\nfunction lowercaseKeys(object) {\n if (!object) {\n return {};\n }\n\n return Object.keys(object).reduce((newObj, key) => {\n newObj[key.toLowerCase()] = object[key];\n return newObj;\n }, {});\n}\n\nfunction mergeDeep(defaults, options) {\n const result = Object.assign({}, defaults);\n Object.keys(options).forEach(key => {\n if (isPlainObject.isPlainObject(options[key])) {\n if (!(key in defaults)) Object.assign(result, {\n [key]: options[key]\n });else result[key] = mergeDeep(defaults[key], options[key]);\n } else {\n Object.assign(result, {\n [key]: options[key]\n });\n }\n });\n return result;\n}\n\nfunction removeUndefinedProperties(obj) {\n for (const key in obj) {\n if (obj[key] === undefined) {\n delete obj[key];\n }\n }\n\n return obj;\n}\n\nfunction merge(defaults, route, options) {\n if (typeof route === \"string\") {\n let [method, url] = route.split(\" \");\n options = Object.assign(url ? {\n method,\n url\n } : {\n url: method\n }, options);\n } else {\n options = Object.assign({}, route);\n } // lowercase header names before merging with defaults to avoid duplicates\n\n\n options.headers = lowercaseKeys(options.headers); // remove properties with undefined values before merging\n\n removeUndefinedProperties(options);\n removeUndefinedProperties(options.headers);\n const mergedOptions = mergeDeep(defaults || {}, options); // mediaType.previews arrays are merged, instead of overwritten\n\n if (defaults && defaults.mediaType.previews.length) {\n mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(preview => !mergedOptions.mediaType.previews.includes(preview)).concat(mergedOptions.mediaType.previews);\n }\n\n mergedOptions.mediaType.previews = mergedOptions.mediaType.previews.map(preview => preview.replace(/-preview/, \"\"));\n return mergedOptions;\n}\n\nfunction addQueryParameters(url, parameters) {\n const separator = /\\?/.test(url) ? \"&\" : \"?\";\n const names = Object.keys(parameters);\n\n if (names.length === 0) {\n return url;\n }\n\n return url + separator + names.map(name => {\n if (name === \"q\") {\n return \"q=\" + parameters.q.split(\"+\").map(encodeURIComponent).join(\"+\");\n }\n\n return `${name}=${encodeURIComponent(parameters[name])}`;\n }).join(\"&\");\n}\n\nconst urlVariableRegex = /\\{[^}]+\\}/g;\n\nfunction removeNonChars(variableName) {\n return variableName.replace(/^\\W+|\\W+$/g, \"\").split(/,/);\n}\n\nfunction extractUrlVariableNames(url) {\n const matches = url.match(urlVariableRegex);\n\n if (!matches) {\n return [];\n }\n\n return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []);\n}\n\nfunction omit(object, keysToOmit) {\n return Object.keys(object).filter(option => !keysToOmit.includes(option)).reduce((obj, key) => {\n obj[key] = object[key];\n return obj;\n }, {});\n}\n\n// Based on https://github.com/bramstein/url-template, licensed under BSD\n// TODO: create separate package.\n//\n// Copyright (c) 2012-2014, Bram Stein\n// All rights reserved.\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n// 1. Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n// 3. The name of the author may not be used to endorse or promote products\n// derived from this software without specific prior written permission.\n// THIS SOFTWARE IS PROVIDED BY THE AUTHOR \"AS IS\" AND ANY EXPRESS OR IMPLIED\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n// EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\n// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n/* istanbul ignore file */\nfunction encodeReserved(str) {\n return str.split(/(%[0-9A-Fa-f]{2})/g).map(function (part) {\n if (!/%[0-9A-Fa-f]/.test(part)) {\n part = encodeURI(part).replace(/%5B/g, \"[\").replace(/%5D/g, \"]\");\n }\n\n return part;\n }).join(\"\");\n}\n\nfunction encodeUnreserved(str) {\n return encodeURIComponent(str).replace(/[!'()*]/g, function (c) {\n return \"%\" + c.charCodeAt(0).toString(16).toUpperCase();\n });\n}\n\nfunction encodeValue(operator, value, key) {\n value = operator === \"+\" || operator === \"#\" ? encodeReserved(value) : encodeUnreserved(value);\n\n if (key) {\n return encodeUnreserved(key) + \"=\" + value;\n } else {\n return value;\n }\n}\n\nfunction isDefined(value) {\n return value !== undefined && value !== null;\n}\n\nfunction isKeyOperator(operator) {\n return operator === \";\" || operator === \"&\" || operator === \"?\";\n}\n\nfunction getValues(context, operator, key, modifier) {\n var value = context[key],\n result = [];\n\n if (isDefined(value) && value !== \"\") {\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n value = value.toString();\n\n if (modifier && modifier !== \"*\") {\n value = value.substring(0, parseInt(modifier, 10));\n }\n\n result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : \"\"));\n } else {\n if (modifier === \"*\") {\n if (Array.isArray(value)) {\n value.filter(isDefined).forEach(function (value) {\n result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : \"\"));\n });\n } else {\n Object.keys(value).forEach(function (k) {\n if (isDefined(value[k])) {\n result.push(encodeValue(operator, value[k], k));\n }\n });\n }\n } else {\n const tmp = [];\n\n if (Array.isArray(value)) {\n value.filter(isDefined).forEach(function (value) {\n tmp.push(encodeValue(operator, value));\n });\n } else {\n Object.keys(value).forEach(function (k) {\n if (isDefined(value[k])) {\n tmp.push(encodeUnreserved(k));\n tmp.push(encodeValue(operator, value[k].toString()));\n }\n });\n }\n\n if (isKeyOperator(operator)) {\n result.push(encodeUnreserved(key) + \"=\" + tmp.join(\",\"));\n } else if (tmp.length !== 0) {\n result.push(tmp.join(\",\"));\n }\n }\n }\n } else {\n if (operator === \";\") {\n if (isDefined(value)) {\n result.push(encodeUnreserved(key));\n }\n } else if (value === \"\" && (operator === \"&\" || operator === \"?\")) {\n result.push(encodeUnreserved(key) + \"=\");\n } else if (value === \"\") {\n result.push(\"\");\n }\n }\n\n return result;\n}\n\nfunction parseUrl(template) {\n return {\n expand: expand.bind(null, template)\n };\n}\n\nfunction expand(template, context) {\n var operators = [\"+\", \"#\", \".\", \"/\", \";\", \"?\", \"&\"];\n return template.replace(/\\{([^\\{\\}]+)\\}|([^\\{\\}]+)/g, function (_, expression, literal) {\n if (expression) {\n let operator = \"\";\n const values = [];\n\n if (operators.indexOf(expression.charAt(0)) !== -1) {\n operator = expression.charAt(0);\n expression = expression.substr(1);\n }\n\n expression.split(/,/g).forEach(function (variable) {\n var tmp = /([^:\\*]*)(?::(\\d+)|(\\*))?/.exec(variable);\n values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3]));\n });\n\n if (operator && operator !== \"+\") {\n var separator = \",\";\n\n if (operator === \"?\") {\n separator = \"&\";\n } else if (operator !== \"#\") {\n separator = operator;\n }\n\n return (values.length !== 0 ? operator : \"\") + values.join(separator);\n } else {\n return values.join(\",\");\n }\n } else {\n return encodeReserved(literal);\n }\n });\n}\n\nfunction parse(options) {\n // https://fetch.spec.whatwg.org/#methods\n let method = options.method.toUpperCase(); // replace :varname with {varname} to make it RFC 6570 compatible\n\n let url = (options.url || \"/\").replace(/:([a-z]\\w+)/g, \"{$1}\");\n let headers = Object.assign({}, options.headers);\n let body;\n let parameters = omit(options, [\"method\", \"baseUrl\", \"url\", \"headers\", \"request\", \"mediaType\"]); // extract variable names from URL to calculate remaining variables later\n\n const urlVariableNames = extractUrlVariableNames(url);\n url = parseUrl(url).expand(parameters);\n\n if (!/^http/.test(url)) {\n url = options.baseUrl + url;\n }\n\n const omittedParameters = Object.keys(options).filter(option => urlVariableNames.includes(option)).concat(\"baseUrl\");\n const remainingParameters = omit(parameters, omittedParameters);\n const isBinaryRequest = /application\\/octet-stream/i.test(headers.accept);\n\n if (!isBinaryRequest) {\n if (options.mediaType.format) {\n // e.g. application/vnd.github.v3+json => application/vnd.github.v3.raw\n headers.accept = headers.accept.split(/,/).map(preview => preview.replace(/application\\/vnd(\\.\\w+)(\\.v3)?(\\.\\w+)?(\\+json)?$/, `application/vnd$1$2.${options.mediaType.format}`)).join(\",\");\n }\n\n if (options.mediaType.previews.length) {\n const previewsFromAcceptHeader = headers.accept.match(/[\\w-]+(?=-preview)/g) || [];\n headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map(preview => {\n const format = options.mediaType.format ? `.${options.mediaType.format}` : \"+json\";\n return `application/vnd.github.${preview}-preview${format}`;\n }).join(\",\");\n }\n } // for GET/HEAD requests, set URL query parameters from remaining parameters\n // for PATCH/POST/PUT/DELETE requests, set request body from remaining parameters\n\n\n if ([\"GET\", \"HEAD\"].includes(method)) {\n url = addQueryParameters(url, remainingParameters);\n } else {\n if (\"data\" in remainingParameters) {\n body = remainingParameters.data;\n } else {\n if (Object.keys(remainingParameters).length) {\n body = remainingParameters;\n } else {\n headers[\"content-length\"] = 0;\n }\n }\n } // default content-type for JSON if body is set\n\n\n if (!headers[\"content-type\"] && typeof body !== \"undefined\") {\n headers[\"content-type\"] = \"application/json; charset=utf-8\";\n } // GitHub expects 'content-length: 0' header for PUT/PATCH requests without body.\n // fetch does not allow to set `content-length` header, but we can set body to an empty string\n\n\n if ([\"PATCH\", \"PUT\"].includes(method) && typeof body === \"undefined\") {\n body = \"\";\n } // Only return body/request keys if present\n\n\n return Object.assign({\n method,\n url,\n headers\n }, typeof body !== \"undefined\" ? {\n body\n } : null, options.request ? {\n request: options.request\n } : null);\n}\n\nfunction endpointWithDefaults(defaults, route, options) {\n return parse(merge(defaults, route, options));\n}\n\nfunction withDefaults(oldDefaults, newDefaults) {\n const DEFAULTS = merge(oldDefaults, newDefaults);\n const endpoint = endpointWithDefaults.bind(null, DEFAULTS);\n return Object.assign(endpoint, {\n DEFAULTS,\n defaults: withDefaults.bind(null, DEFAULTS),\n merge: merge.bind(null, DEFAULTS),\n parse\n });\n}\n\nconst VERSION = \"6.0.11\";\n\nconst userAgent = `octokit-endpoint.js/${VERSION} ${universalUserAgent.getUserAgent()}`; // DEFAULTS has all properties set that EndpointOptions has, except url.\n// So we use RequestParameters and add method as additional required property.\n\nconst DEFAULTS = {\n method: \"GET\",\n baseUrl: \"https://api.github.com\",\n headers: {\n accept: \"application/vnd.github.v3+json\",\n \"user-agent\": userAgent\n },\n mediaType: {\n format: \"\",\n previews: []\n }\n};\n\nconst endpoint = withDefaults(null, DEFAULTS);\n\nexports.endpoint = endpoint;\n//# sourceMappingURL=index.js.map\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\n/*!\n * is-plain-object \n *\n * Copyright (c) 2014-2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\nfunction isObject(o) {\n return Object.prototype.toString.call(o) === '[object Object]';\n}\n\nfunction isPlainObject(o) {\n var ctor,prot;\n\n if (isObject(o) === false) return false;\n\n // If has modified constructor\n ctor = o.constructor;\n if (ctor === undefined) return true;\n\n // If has modified prototype\n prot = ctor.prototype;\n if (isObject(prot) === false) return false;\n\n // If constructor does not have an Object-specific method\n if (prot.hasOwnProperty('isPrototypeOf') === false) {\n return false;\n }\n\n // Most likely a plain Object\n return true;\n}\n\nexports.isPlainObject = isPlainObject;\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nvar request = require('@octokit/request');\nvar universalUserAgent = require('universal-user-agent');\n\nconst VERSION = \"4.6.0\";\n\nclass GraphqlError extends Error {\n constructor(request, response) {\n const message = response.data.errors[0].message;\n super(message);\n Object.assign(this, response.data);\n Object.assign(this, {\n headers: response.headers\n });\n this.name = \"GraphqlError\";\n this.request = request; // Maintains proper stack trace (only available on V8)\n\n /* istanbul ignore next */\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n\n}\n\nconst NON_VARIABLE_OPTIONS = [\"method\", \"baseUrl\", \"url\", \"headers\", \"request\", \"query\", \"mediaType\"];\nconst GHES_V3_SUFFIX_REGEX = /\\/api\\/v3\\/?$/;\nfunction graphql(request, query, options) {\n if (typeof query === \"string\" && options && \"query\" in options) {\n return Promise.reject(new Error(`[@octokit/graphql] \"query\" cannot be used as variable name`));\n }\n\n const parsedOptions = typeof query === \"string\" ? Object.assign({\n query\n }, options) : query;\n const requestOptions = Object.keys(parsedOptions).reduce((result, key) => {\n if (NON_VARIABLE_OPTIONS.includes(key)) {\n result[key] = parsedOptions[key];\n return result;\n }\n\n if (!result.variables) {\n result.variables = {};\n }\n\n result.variables[key] = parsedOptions[key];\n return result;\n }, {}); // workaround for GitHub Enterprise baseUrl set with /api/v3 suffix\n // https://github.com/octokit/auth-app.js/issues/111#issuecomment-657610451\n\n const baseUrl = parsedOptions.baseUrl || request.endpoint.DEFAULTS.baseUrl;\n\n if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) {\n requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, \"/api/graphql\");\n }\n\n return request(requestOptions).then(response => {\n if (response.data.errors) {\n const headers = {};\n\n for (const key of Object.keys(response.headers)) {\n headers[key] = response.headers[key];\n }\n\n throw new GraphqlError(requestOptions, {\n headers,\n data: response.data\n });\n }\n\n return response.data.data;\n });\n}\n\nfunction withDefaults(request$1, newDefaults) {\n const newRequest = request$1.defaults(newDefaults);\n\n const newApi = (query, options) => {\n return graphql(newRequest, query, options);\n };\n\n return Object.assign(newApi, {\n defaults: withDefaults.bind(null, newRequest),\n endpoint: request.request.endpoint\n });\n}\n\nconst graphql$1 = withDefaults(request.request, {\n headers: {\n \"user-agent\": `octokit-graphql.js/${VERSION} ${universalUserAgent.getUserAgent()}`\n },\n method: \"POST\",\n url: \"/graphql\"\n});\nfunction withCustomRequest(customRequest) {\n return withDefaults(customRequest, {\n method: \"POST\",\n url: \"/graphql\"\n });\n}\n\nexports.graphql = graphql$1;\nexports.withCustomRequest = withCustomRequest;\n//# sourceMappingURL=index.js.map\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nconst VERSION = \"2.9.1\";\n\n/**\n * Some “list” response that can be paginated have a different response structure\n *\n * They have a `total_count` key in the response (search also has `incomplete_results`,\n * /installation/repositories also has `repository_selection`), as well as a key with\n * the list of the items which name varies from endpoint to endpoint.\n *\n * Octokit normalizes these responses so that paginated results are always returned following\n * the same structure. One challenge is that if the list response has only one page, no Link\n * header is provided, so this header alone is not sufficient to check wether a response is\n * paginated or not.\n *\n * We check if a \"total_count\" key is present in the response data, but also make sure that\n * a \"url\" property is not, as the \"Get the combined status for a specific ref\" endpoint would\n * otherwise match: https://developer.github.com/v3/repos/statuses/#get-the-combined-status-for-a-specific-ref\n */\nfunction normalizePaginatedListResponse(response) {\n const responseNeedsNormalization = \"total_count\" in response.data && !(\"url\" in response.data);\n if (!responseNeedsNormalization) return response; // keep the additional properties intact as there is currently no other way\n // to retrieve the same information.\n\n const incompleteResults = response.data.incomplete_results;\n const repositorySelection = response.data.repository_selection;\n const totalCount = response.data.total_count;\n delete response.data.incomplete_results;\n delete response.data.repository_selection;\n delete response.data.total_count;\n const namespaceKey = Object.keys(response.data)[0];\n const data = response.data[namespaceKey];\n response.data = data;\n\n if (typeof incompleteResults !== \"undefined\") {\n response.data.incomplete_results = incompleteResults;\n }\n\n if (typeof repositorySelection !== \"undefined\") {\n response.data.repository_selection = repositorySelection;\n }\n\n response.data.total_count = totalCount;\n return response;\n}\n\nfunction iterator(octokit, route, parameters) {\n const options = typeof route === \"function\" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters);\n const requestMethod = typeof route === \"function\" ? route : octokit.request;\n const method = options.method;\n const headers = options.headers;\n let url = options.url;\n return {\n [Symbol.asyncIterator]: () => ({\n async next() {\n if (!url) return {\n done: true\n };\n const response = await requestMethod({\n method,\n url,\n headers\n });\n const normalizedResponse = normalizePaginatedListResponse(response); // `response.headers.link` format:\n // '; rel=\"next\", ; rel=\"last\"'\n // sets `url` to undefined if \"next\" URL is not present or `link` header is not set\n\n url = ((normalizedResponse.headers.link || \"\").match(/<([^>]+)>;\\s*rel=\"next\"/) || [])[1];\n return {\n value: normalizedResponse\n };\n }\n\n })\n };\n}\n\nfunction paginate(octokit, route, parameters, mapFn) {\n if (typeof parameters === \"function\") {\n mapFn = parameters;\n parameters = undefined;\n }\n\n return gather(octokit, [], iterator(octokit, route, parameters)[Symbol.asyncIterator](), mapFn);\n}\n\nfunction gather(octokit, results, iterator, mapFn) {\n return iterator.next().then(result => {\n if (result.done) {\n return results;\n }\n\n let earlyExit = false;\n\n function done() {\n earlyExit = true;\n }\n\n results = results.concat(mapFn ? mapFn(result.value, done) : result.value.data);\n\n if (earlyExit) {\n return results;\n }\n\n return gather(octokit, results, iterator, mapFn);\n });\n}\n\nconst composePaginateRest = Object.assign(paginate, {\n iterator\n});\n\n/**\n * @param octokit Octokit instance\n * @param options Options passed to Octokit constructor\n */\n\nfunction paginateRest(octokit) {\n return {\n paginate: Object.assign(paginate.bind(null, octokit), {\n iterator: iterator.bind(null, octokit)\n })\n };\n}\npaginateRest.VERSION = VERSION;\n\nexports.composePaginateRest = composePaginateRest;\nexports.paginateRest = paginateRest;\n//# sourceMappingURL=index.js.map\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nconst Endpoints = {\n actions: {\n addSelectedRepoToOrgSecret: [\"PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}\"],\n cancelWorkflowRun: [\"POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel\"],\n createOrUpdateOrgSecret: [\"PUT /orgs/{org}/actions/secrets/{secret_name}\"],\n createOrUpdateRepoSecret: [\"PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}\"],\n createRegistrationTokenForOrg: [\"POST /orgs/{org}/actions/runners/registration-token\"],\n createRegistrationTokenForRepo: [\"POST /repos/{owner}/{repo}/actions/runners/registration-token\"],\n createRemoveTokenForOrg: [\"POST /orgs/{org}/actions/runners/remove-token\"],\n createRemoveTokenForRepo: [\"POST /repos/{owner}/{repo}/actions/runners/remove-token\"],\n createWorkflowDispatch: [\"POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches\"],\n deleteArtifact: [\"DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}\"],\n deleteOrgSecret: [\"DELETE /orgs/{org}/actions/secrets/{secret_name}\"],\n deleteRepoSecret: [\"DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}\"],\n deleteSelfHostedRunnerFromOrg: [\"DELETE /orgs/{org}/actions/runners/{runner_id}\"],\n deleteSelfHostedRunnerFromRepo: [\"DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}\"],\n deleteWorkflowRun: [\"DELETE /repos/{owner}/{repo}/actions/runs/{run_id}\"],\n deleteWorkflowRunLogs: [\"DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs\"],\n disableSelectedRepositoryGithubActionsOrganization: [\"DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}\"],\n disableWorkflow: [\"PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable\"],\n downloadArtifact: [\"GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}\"],\n downloadJobLogsForWorkflowRun: [\"GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs\"],\n downloadWorkflowRunLogs: [\"GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs\"],\n enableSelectedRepositoryGithubActionsOrganization: [\"PUT /orgs/{org}/actions/permissions/repositories/{repository_id}\"],\n enableWorkflow: [\"PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable\"],\n getAllowedActionsOrganization: [\"GET /orgs/{org}/actions/permissions/selected-actions\"],\n getAllowedActionsRepository: [\"GET /repos/{owner}/{repo}/actions/permissions/selected-actions\"],\n getArtifact: [\"GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}\"],\n getGithubActionsPermissionsOrganization: [\"GET /orgs/{org}/actions/permissions\"],\n getGithubActionsPermissionsRepository: [\"GET /repos/{owner}/{repo}/actions/permissions\"],\n getJobForWorkflowRun: [\"GET /repos/{owner}/{repo}/actions/jobs/{job_id}\"],\n getOrgPublicKey: [\"GET /orgs/{org}/actions/secrets/public-key\"],\n getOrgSecret: [\"GET /orgs/{org}/actions/secrets/{secret_name}\"],\n getRepoPermissions: [\"GET /repos/{owner}/{repo}/actions/permissions\", {}, {\n renamed: [\"actions\", \"getGithubActionsPermissionsRepository\"]\n }],\n getRepoPublicKey: [\"GET /repos/{owner}/{repo}/actions/secrets/public-key\"],\n getRepoSecret: [\"GET /repos/{owner}/{repo}/actions/secrets/{secret_name}\"],\n getSelfHostedRunnerForOrg: [\"GET /orgs/{org}/actions/runners/{runner_id}\"],\n getSelfHostedRunnerForRepo: [\"GET /repos/{owner}/{repo}/actions/runners/{runner_id}\"],\n getWorkflow: [\"GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}\"],\n getWorkflowRun: [\"GET /repos/{owner}/{repo}/actions/runs/{run_id}\"],\n getWorkflowRunUsage: [\"GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing\"],\n getWorkflowUsage: [\"GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing\"],\n listArtifactsForRepo: [\"GET /repos/{owner}/{repo}/actions/artifacts\"],\n listJobsForWorkflowRun: [\"GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs\"],\n listOrgSecrets: [\"GET /orgs/{org}/actions/secrets\"],\n listRepoSecrets: [\"GET /repos/{owner}/{repo}/actions/secrets\"],\n listRepoWorkflows: [\"GET /repos/{owner}/{repo}/actions/workflows\"],\n listRunnerApplicationsForOrg: [\"GET /orgs/{org}/actions/runners/downloads\"],\n listRunnerApplicationsForRepo: [\"GET /repos/{owner}/{repo}/actions/runners/downloads\"],\n listSelectedReposForOrgSecret: [\"GET /orgs/{org}/actions/secrets/{secret_name}/repositories\"],\n listSelectedRepositoriesEnabledGithubActionsOrganization: [\"GET /orgs/{org}/actions/permissions/repositories\"],\n listSelfHostedRunnersForOrg: [\"GET /orgs/{org}/actions/runners\"],\n listSelfHostedRunnersForRepo: [\"GET /repos/{owner}/{repo}/actions/runners\"],\n listWorkflowRunArtifacts: [\"GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts\"],\n listWorkflowRuns: [\"GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs\"],\n listWorkflowRunsForRepo: [\"GET /repos/{owner}/{repo}/actions/runs\"],\n reRunWorkflow: [\"POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun\"],\n removeSelectedRepoFromOrgSecret: [\"DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}\"],\n setAllowedActionsOrganization: [\"PUT /orgs/{org}/actions/permissions/selected-actions\"],\n setAllowedActionsRepository: [\"PUT /repos/{owner}/{repo}/actions/permissions/selected-actions\"],\n setGithubActionsPermissionsOrganization: [\"PUT /orgs/{org}/actions/permissions\"],\n setGithubActionsPermissionsRepository: [\"PUT /repos/{owner}/{repo}/actions/permissions\"],\n setSelectedReposForOrgSecret: [\"PUT /orgs/{org}/actions/secrets/{secret_name}/repositories\"],\n setSelectedRepositoriesEnabledGithubActionsOrganization: [\"PUT /orgs/{org}/actions/permissions/repositories\"]\n },\n activity: {\n checkRepoIsStarredByAuthenticatedUser: [\"GET /user/starred/{owner}/{repo}\"],\n deleteRepoSubscription: [\"DELETE /repos/{owner}/{repo}/subscription\"],\n deleteThreadSubscription: [\"DELETE /notifications/threads/{thread_id}/subscription\"],\n getFeeds: [\"GET /feeds\"],\n getRepoSubscription: [\"GET /repos/{owner}/{repo}/subscription\"],\n getThread: [\"GET /notifications/threads/{thread_id}\"],\n getThreadSubscriptionForAuthenticatedUser: [\"GET /notifications/threads/{thread_id}/subscription\"],\n listEventsForAuthenticatedUser: [\"GET /users/{username}/events\"],\n listNotificationsForAuthenticatedUser: [\"GET /notifications\"],\n listOrgEventsForAuthenticatedUser: [\"GET /users/{username}/events/orgs/{org}\"],\n listPublicEvents: [\"GET /events\"],\n listPublicEventsForRepoNetwork: [\"GET /networks/{owner}/{repo}/events\"],\n listPublicEventsForUser: [\"GET /users/{username}/events/public\"],\n listPublicOrgEvents: [\"GET /orgs/{org}/events\"],\n listReceivedEventsForUser: [\"GET /users/{username}/received_events\"],\n listReceivedPublicEventsForUser: [\"GET /users/{username}/received_events/public\"],\n listRepoEvents: [\"GET /repos/{owner}/{repo}/events\"],\n listRepoNotificationsForAuthenticatedUser: [\"GET /repos/{owner}/{repo}/notifications\"],\n listReposStarredByAuthenticatedUser: [\"GET /user/starred\"],\n listReposStarredByUser: [\"GET /users/{username}/starred\"],\n listReposWatchedByUser: [\"GET /users/{username}/subscriptions\"],\n listStargazersForRepo: [\"GET /repos/{owner}/{repo}/stargazers\"],\n listWatchedReposForAuthenticatedUser: [\"GET /user/subscriptions\"],\n listWatchersForRepo: [\"GET /repos/{owner}/{repo}/subscribers\"],\n markNotificationsAsRead: [\"PUT /notifications\"],\n markRepoNotificationsAsRead: [\"PUT /repos/{owner}/{repo}/notifications\"],\n markThreadAsRead: [\"PATCH /notifications/threads/{thread_id}\"],\n setRepoSubscription: [\"PUT /repos/{owner}/{repo}/subscription\"],\n setThreadSubscription: [\"PUT /notifications/threads/{thread_id}/subscription\"],\n starRepoForAuthenticatedUser: [\"PUT /user/starred/{owner}/{repo}\"],\n unstarRepoForAuthenticatedUser: [\"DELETE /user/starred/{owner}/{repo}\"]\n },\n apps: {\n addRepoToInstallation: [\"PUT /user/installations/{installation_id}/repositories/{repository_id}\"],\n checkToken: [\"POST /applications/{client_id}/token\"],\n createContentAttachment: [\"POST /content_references/{content_reference_id}/attachments\", {\n mediaType: {\n previews: [\"corsair\"]\n }\n }],\n createFromManifest: [\"POST /app-manifests/{code}/conversions\"],\n createInstallationAccessToken: [\"POST /app/installations/{installation_id}/access_tokens\"],\n deleteAuthorization: [\"DELETE /applications/{client_id}/grant\"],\n deleteInstallation: [\"DELETE /app/installations/{installation_id}\"],\n deleteToken: [\"DELETE /applications/{client_id}/token\"],\n getAuthenticated: [\"GET /app\"],\n getBySlug: [\"GET /apps/{app_slug}\"],\n getInstallation: [\"GET /app/installations/{installation_id}\"],\n getOrgInstallation: [\"GET /orgs/{org}/installation\"],\n getRepoInstallation: [\"GET /repos/{owner}/{repo}/installation\"],\n getSubscriptionPlanForAccount: [\"GET /marketplace_listing/accounts/{account_id}\"],\n getSubscriptionPlanForAccountStubbed: [\"GET /marketplace_listing/stubbed/accounts/{account_id}\"],\n getUserInstallation: [\"GET /users/{username}/installation\"],\n getWebhookConfigForApp: [\"GET /app/hook/config\"],\n listAccountsForPlan: [\"GET /marketplace_listing/plans/{plan_id}/accounts\"],\n listAccountsForPlanStubbed: [\"GET /marketplace_listing/stubbed/plans/{plan_id}/accounts\"],\n listInstallationReposForAuthenticatedUser: [\"GET /user/installations/{installation_id}/repositories\"],\n listInstallations: [\"GET /app/installations\"],\n listInstallationsForAuthenticatedUser: [\"GET /user/installations\"],\n listPlans: [\"GET /marketplace_listing/plans\"],\n listPlansStubbed: [\"GET /marketplace_listing/stubbed/plans\"],\n listReposAccessibleToInstallation: [\"GET /installation/repositories\"],\n listSubscriptionsForAuthenticatedUser: [\"GET /user/marketplace_purchases\"],\n listSubscriptionsForAuthenticatedUserStubbed: [\"GET /user/marketplace_purchases/stubbed\"],\n removeRepoFromInstallation: [\"DELETE /user/installations/{installation_id}/repositories/{repository_id}\"],\n resetToken: [\"PATCH /applications/{client_id}/token\"],\n revokeInstallationAccessToken: [\"DELETE /installation/token\"],\n scopeToken: [\"POST /applications/{client_id}/token/scoped\"],\n suspendInstallation: [\"PUT /app/installations/{installation_id}/suspended\"],\n unsuspendInstallation: [\"DELETE /app/installations/{installation_id}/suspended\"],\n updateWebhookConfigForApp: [\"PATCH /app/hook/config\"]\n },\n billing: {\n getGithubActionsBillingOrg: [\"GET /orgs/{org}/settings/billing/actions\"],\n getGithubActionsBillingUser: [\"GET /users/{username}/settings/billing/actions\"],\n getGithubPackagesBillingOrg: [\"GET /orgs/{org}/settings/billing/packages\"],\n getGithubPackagesBillingUser: [\"GET /users/{username}/settings/billing/packages\"],\n getSharedStorageBillingOrg: [\"GET /orgs/{org}/settings/billing/shared-storage\"],\n getSharedStorageBillingUser: [\"GET /users/{username}/settings/billing/shared-storage\"]\n },\n checks: {\n create: [\"POST /repos/{owner}/{repo}/check-runs\"],\n createSuite: [\"POST /repos/{owner}/{repo}/check-suites\"],\n get: [\"GET /repos/{owner}/{repo}/check-runs/{check_run_id}\"],\n getSuite: [\"GET /repos/{owner}/{repo}/check-suites/{check_suite_id}\"],\n listAnnotations: [\"GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations\"],\n listForRef: [\"GET /repos/{owner}/{repo}/commits/{ref}/check-runs\"],\n listForSuite: [\"GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs\"],\n listSuitesForRef: [\"GET /repos/{owner}/{repo}/commits/{ref}/check-suites\"],\n rerequestSuite: [\"POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest\"],\n setSuitesPreferences: [\"PATCH /repos/{owner}/{repo}/check-suites/preferences\"],\n update: [\"PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}\"]\n },\n codeScanning: {\n getAlert: [\"GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}\", {}, {\n renamedParameters: {\n alert_id: \"alert_number\"\n }\n }],\n listAlertsForRepo: [\"GET /repos/{owner}/{repo}/code-scanning/alerts\"],\n listRecentAnalyses: [\"GET /repos/{owner}/{repo}/code-scanning/analyses\"],\n updateAlert: [\"PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}\"],\n uploadSarif: [\"POST /repos/{owner}/{repo}/code-scanning/sarifs\"]\n },\n codesOfConduct: {\n getAllCodesOfConduct: [\"GET /codes_of_conduct\", {\n mediaType: {\n previews: [\"scarlet-witch\"]\n }\n }],\n getConductCode: [\"GET /codes_of_conduct/{key}\", {\n mediaType: {\n previews: [\"scarlet-witch\"]\n }\n }],\n getForRepo: [\"GET /repos/{owner}/{repo}/community/code_of_conduct\", {\n mediaType: {\n previews: [\"scarlet-witch\"]\n }\n }]\n },\n emojis: {\n get: [\"GET /emojis\"]\n },\n enterpriseAdmin: {\n disableSelectedOrganizationGithubActionsEnterprise: [\"DELETE /enterprises/{enterprise}/actions/permissions/organizations/{org_id}\"],\n enableSelectedOrganizationGithubActionsEnterprise: [\"PUT /enterprises/{enterprise}/actions/permissions/organizations/{org_id}\"],\n getAllowedActionsEnterprise: [\"GET /enterprises/{enterprise}/actions/permissions/selected-actions\"],\n getGithubActionsPermissionsEnterprise: [\"GET /enterprises/{enterprise}/actions/permissions\"],\n listSelectedOrganizationsEnabledGithubActionsEnterprise: [\"GET /enterprises/{enterprise}/actions/permissions/organizations\"],\n setAllowedActionsEnterprise: [\"PUT /enterprises/{enterprise}/actions/permissions/selected-actions\"],\n setGithubActionsPermissionsEnterprise: [\"PUT /enterprises/{enterprise}/actions/permissions\"],\n setSelectedOrganizationsEnabledGithubActionsEnterprise: [\"PUT /enterprises/{enterprise}/actions/permissions/organizations\"]\n },\n gists: {\n checkIsStarred: [\"GET /gists/{gist_id}/star\"],\n create: [\"POST /gists\"],\n createComment: [\"POST /gists/{gist_id}/comments\"],\n delete: [\"DELETE /gists/{gist_id}\"],\n deleteComment: [\"DELETE /gists/{gist_id}/comments/{comment_id}\"],\n fork: [\"POST /gists/{gist_id}/forks\"],\n get: [\"GET /gists/{gist_id}\"],\n getComment: [\"GET /gists/{gist_id}/comments/{comment_id}\"],\n getRevision: [\"GET /gists/{gist_id}/{sha}\"],\n list: [\"GET /gists\"],\n listComments: [\"GET /gists/{gist_id}/comments\"],\n listCommits: [\"GET /gists/{gist_id}/commits\"],\n listForUser: [\"GET /users/{username}/gists\"],\n listForks: [\"GET /gists/{gist_id}/forks\"],\n listPublic: [\"GET /gists/public\"],\n listStarred: [\"GET /gists/starred\"],\n star: [\"PUT /gists/{gist_id}/star\"],\n unstar: [\"DELETE /gists/{gist_id}/star\"],\n update: [\"PATCH /gists/{gist_id}\"],\n updateComment: [\"PATCH /gists/{gist_id}/comments/{comment_id}\"]\n },\n git: {\n createBlob: [\"POST /repos/{owner}/{repo}/git/blobs\"],\n createCommit: [\"POST /repos/{owner}/{repo}/git/commits\"],\n createRef: [\"POST /repos/{owner}/{repo}/git/refs\"],\n createTag: [\"POST /repos/{owner}/{repo}/git/tags\"],\n createTree: [\"POST /repos/{owner}/{repo}/git/trees\"],\n deleteRef: [\"DELETE /repos/{owner}/{repo}/git/refs/{ref}\"],\n getBlob: [\"GET /repos/{owner}/{repo}/git/blobs/{file_sha}\"],\n getCommit: [\"GET /repos/{owner}/{repo}/git/commits/{commit_sha}\"],\n getRef: [\"GET /repos/{owner}/{repo}/git/ref/{ref}\"],\n getTag: [\"GET /repos/{owner}/{repo}/git/tags/{tag_sha}\"],\n getTree: [\"GET /repos/{owner}/{repo}/git/trees/{tree_sha}\"],\n listMatchingRefs: [\"GET /repos/{owner}/{repo}/git/matching-refs/{ref}\"],\n updateRef: [\"PATCH /repos/{owner}/{repo}/git/refs/{ref}\"]\n },\n gitignore: {\n getAllTemplates: [\"GET /gitignore/templates\"],\n getTemplate: [\"GET /gitignore/templates/{name}\"]\n },\n interactions: {\n getRestrictionsForAuthenticatedUser: [\"GET /user/interaction-limits\"],\n getRestrictionsForOrg: [\"GET /orgs/{org}/interaction-limits\"],\n getRestrictionsForRepo: [\"GET /repos/{owner}/{repo}/interaction-limits\"],\n getRestrictionsForYourPublicRepos: [\"GET /user/interaction-limits\", {}, {\n renamed: [\"interactions\", \"getRestrictionsForAuthenticatedUser\"]\n }],\n removeRestrictionsForAuthenticatedUser: [\"DELETE /user/interaction-limits\"],\n removeRestrictionsForOrg: [\"DELETE /orgs/{org}/interaction-limits\"],\n removeRestrictionsForRepo: [\"DELETE /repos/{owner}/{repo}/interaction-limits\"],\n removeRestrictionsForYourPublicRepos: [\"DELETE /user/interaction-limits\", {}, {\n renamed: [\"interactions\", \"removeRestrictionsForAuthenticatedUser\"]\n }],\n setRestrictionsForAuthenticatedUser: [\"PUT /user/interaction-limits\"],\n setRestrictionsForOrg: [\"PUT /orgs/{org}/interaction-limits\"],\n setRestrictionsForRepo: [\"PUT /repos/{owner}/{repo}/interaction-limits\"],\n setRestrictionsForYourPublicRepos: [\"PUT /user/interaction-limits\", {}, {\n renamed: [\"interactions\", \"setRestrictionsForAuthenticatedUser\"]\n }]\n },\n issues: {\n addAssignees: [\"POST /repos/{owner}/{repo}/issues/{issue_number}/assignees\"],\n addLabels: [\"POST /repos/{owner}/{repo}/issues/{issue_number}/labels\"],\n checkUserCanBeAssigned: [\"GET /repos/{owner}/{repo}/assignees/{assignee}\"],\n create: [\"POST /repos/{owner}/{repo}/issues\"],\n createComment: [\"POST /repos/{owner}/{repo}/issues/{issue_number}/comments\"],\n createLabel: [\"POST /repos/{owner}/{repo}/labels\"],\n createMilestone: [\"POST /repos/{owner}/{repo}/milestones\"],\n deleteComment: [\"DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}\"],\n deleteLabel: [\"DELETE /repos/{owner}/{repo}/labels/{name}\"],\n deleteMilestone: [\"DELETE /repos/{owner}/{repo}/milestones/{milestone_number}\"],\n get: [\"GET /repos/{owner}/{repo}/issues/{issue_number}\"],\n getComment: [\"GET /repos/{owner}/{repo}/issues/comments/{comment_id}\"],\n getEvent: [\"GET /repos/{owner}/{repo}/issues/events/{event_id}\"],\n getLabel: [\"GET /repos/{owner}/{repo}/labels/{name}\"],\n getMilestone: [\"GET /repos/{owner}/{repo}/milestones/{milestone_number}\"],\n list: [\"GET /issues\"],\n listAssignees: [\"GET /repos/{owner}/{repo}/assignees\"],\n listComments: [\"GET /repos/{owner}/{repo}/issues/{issue_number}/comments\"],\n listCommentsForRepo: [\"GET /repos/{owner}/{repo}/issues/comments\"],\n listEvents: [\"GET /repos/{owner}/{repo}/issues/{issue_number}/events\"],\n listEventsForRepo: [\"GET /repos/{owner}/{repo}/issues/events\"],\n listEventsForTimeline: [\"GET /repos/{owner}/{repo}/issues/{issue_number}/timeline\", {\n mediaType: {\n previews: [\"mockingbird\"]\n }\n }],\n listForAuthenticatedUser: [\"GET /user/issues\"],\n listForOrg: [\"GET /orgs/{org}/issues\"],\n listForRepo: [\"GET /repos/{owner}/{repo}/issues\"],\n listLabelsForMilestone: [\"GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels\"],\n listLabelsForRepo: [\"GET /repos/{owner}/{repo}/labels\"],\n listLabelsOnIssue: [\"GET /repos/{owner}/{repo}/issues/{issue_number}/labels\"],\n listMilestones: [\"GET /repos/{owner}/{repo}/milestones\"],\n lock: [\"PUT /repos/{owner}/{repo}/issues/{issue_number}/lock\"],\n removeAllLabels: [\"DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels\"],\n removeAssignees: [\"DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees\"],\n removeLabel: [\"DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}\"],\n setLabels: [\"PUT /repos/{owner}/{repo}/issues/{issue_number}/labels\"],\n unlock: [\"DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock\"],\n update: [\"PATCH /repos/{owner}/{repo}/issues/{issue_number}\"],\n updateComment: [\"PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}\"],\n updateLabel: [\"PATCH /repos/{owner}/{repo}/labels/{name}\"],\n updateMilestone: [\"PATCH /repos/{owner}/{repo}/milestones/{milestone_number}\"]\n },\n licenses: {\n get: [\"GET /licenses/{license}\"],\n getAllCommonlyUsed: [\"GET /licenses\"],\n getForRepo: [\"GET /repos/{owner}/{repo}/license\"]\n },\n markdown: {\n render: [\"POST /markdown\"],\n renderRaw: [\"POST /markdown/raw\", {\n headers: {\n \"content-type\": \"text/plain; charset=utf-8\"\n }\n }]\n },\n meta: {\n get: [\"GET /meta\"],\n getOctocat: [\"GET /octocat\"],\n getZen: [\"GET /zen\"],\n root: [\"GET /\"]\n },\n migrations: {\n cancelImport: [\"DELETE /repos/{owner}/{repo}/import\"],\n deleteArchiveForAuthenticatedUser: [\"DELETE /user/migrations/{migration_id}/archive\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n deleteArchiveForOrg: [\"DELETE /orgs/{org}/migrations/{migration_id}/archive\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n downloadArchiveForOrg: [\"GET /orgs/{org}/migrations/{migration_id}/archive\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n getArchiveForAuthenticatedUser: [\"GET /user/migrations/{migration_id}/archive\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n getCommitAuthors: [\"GET /repos/{owner}/{repo}/import/authors\"],\n getImportStatus: [\"GET /repos/{owner}/{repo}/import\"],\n getLargeFiles: [\"GET /repos/{owner}/{repo}/import/large_files\"],\n getStatusForAuthenticatedUser: [\"GET /user/migrations/{migration_id}\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n getStatusForOrg: [\"GET /orgs/{org}/migrations/{migration_id}\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n listForAuthenticatedUser: [\"GET /user/migrations\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n listForOrg: [\"GET /orgs/{org}/migrations\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n listReposForOrg: [\"GET /orgs/{org}/migrations/{migration_id}/repositories\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n listReposForUser: [\"GET /user/migrations/{migration_id}/repositories\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n mapCommitAuthor: [\"PATCH /repos/{owner}/{repo}/import/authors/{author_id}\"],\n setLfsPreference: [\"PATCH /repos/{owner}/{repo}/import/lfs\"],\n startForAuthenticatedUser: [\"POST /user/migrations\"],\n startForOrg: [\"POST /orgs/{org}/migrations\"],\n startImport: [\"PUT /repos/{owner}/{repo}/import\"],\n unlockRepoForAuthenticatedUser: [\"DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n unlockRepoForOrg: [\"DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n updateImport: [\"PATCH /repos/{owner}/{repo}/import\"]\n },\n orgs: {\n blockUser: [\"PUT /orgs/{org}/blocks/{username}\"],\n cancelInvitation: [\"DELETE /orgs/{org}/invitations/{invitation_id}\"],\n checkBlockedUser: [\"GET /orgs/{org}/blocks/{username}\"],\n checkMembershipForUser: [\"GET /orgs/{org}/members/{username}\"],\n checkPublicMembershipForUser: [\"GET /orgs/{org}/public_members/{username}\"],\n convertMemberToOutsideCollaborator: [\"PUT /orgs/{org}/outside_collaborators/{username}\"],\n createInvitation: [\"POST /orgs/{org}/invitations\"],\n createWebhook: [\"POST /orgs/{org}/hooks\"],\n deleteWebhook: [\"DELETE /orgs/{org}/hooks/{hook_id}\"],\n get: [\"GET /orgs/{org}\"],\n getMembershipForAuthenticatedUser: [\"GET /user/memberships/orgs/{org}\"],\n getMembershipForUser: [\"GET /orgs/{org}/memberships/{username}\"],\n getWebhook: [\"GET /orgs/{org}/hooks/{hook_id}\"],\n getWebhookConfigForOrg: [\"GET /orgs/{org}/hooks/{hook_id}/config\"],\n list: [\"GET /organizations\"],\n listAppInstallations: [\"GET /orgs/{org}/installations\"],\n listBlockedUsers: [\"GET /orgs/{org}/blocks\"],\n listFailedInvitations: [\"GET /orgs/{org}/failed_invitations\"],\n listForAuthenticatedUser: [\"GET /user/orgs\"],\n listForUser: [\"GET /users/{username}/orgs\"],\n listInvitationTeams: [\"GET /orgs/{org}/invitations/{invitation_id}/teams\"],\n listMembers: [\"GET /orgs/{org}/members\"],\n listMembershipsForAuthenticatedUser: [\"GET /user/memberships/orgs\"],\n listOutsideCollaborators: [\"GET /orgs/{org}/outside_collaborators\"],\n listPendingInvitations: [\"GET /orgs/{org}/invitations\"],\n listPublicMembers: [\"GET /orgs/{org}/public_members\"],\n listWebhooks: [\"GET /orgs/{org}/hooks\"],\n pingWebhook: [\"POST /orgs/{org}/hooks/{hook_id}/pings\"],\n removeMember: [\"DELETE /orgs/{org}/members/{username}\"],\n removeMembershipForUser: [\"DELETE /orgs/{org}/memberships/{username}\"],\n removeOutsideCollaborator: [\"DELETE /orgs/{org}/outside_collaborators/{username}\"],\n removePublicMembershipForAuthenticatedUser: [\"DELETE /orgs/{org}/public_members/{username}\"],\n setMembershipForUser: [\"PUT /orgs/{org}/memberships/{username}\"],\n setPublicMembershipForAuthenticatedUser: [\"PUT /orgs/{org}/public_members/{username}\"],\n unblockUser: [\"DELETE /orgs/{org}/blocks/{username}\"],\n update: [\"PATCH /orgs/{org}\"],\n updateMembershipForAuthenticatedUser: [\"PATCH /user/memberships/orgs/{org}\"],\n updateWebhook: [\"PATCH /orgs/{org}/hooks/{hook_id}\"],\n updateWebhookConfigForOrg: [\"PATCH /orgs/{org}/hooks/{hook_id}/config\"]\n },\n projects: {\n addCollaborator: [\"PUT /projects/{project_id}/collaborators/{username}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n createCard: [\"POST /projects/columns/{column_id}/cards\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n createColumn: [\"POST /projects/{project_id}/columns\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n createForAuthenticatedUser: [\"POST /user/projects\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n createForOrg: [\"POST /orgs/{org}/projects\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n createForRepo: [\"POST /repos/{owner}/{repo}/projects\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n delete: [\"DELETE /projects/{project_id}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n deleteCard: [\"DELETE /projects/columns/cards/{card_id}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n deleteColumn: [\"DELETE /projects/columns/{column_id}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n get: [\"GET /projects/{project_id}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n getCard: [\"GET /projects/columns/cards/{card_id}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n getColumn: [\"GET /projects/columns/{column_id}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n getPermissionForUser: [\"GET /projects/{project_id}/collaborators/{username}/permission\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n listCards: [\"GET /projects/columns/{column_id}/cards\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n listCollaborators: [\"GET /projects/{project_id}/collaborators\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n listColumns: [\"GET /projects/{project_id}/columns\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n listForOrg: [\"GET /orgs/{org}/projects\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n listForRepo: [\"GET /repos/{owner}/{repo}/projects\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n listForUser: [\"GET /users/{username}/projects\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n moveCard: [\"POST /projects/columns/cards/{card_id}/moves\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n moveColumn: [\"POST /projects/columns/{column_id}/moves\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n removeCollaborator: [\"DELETE /projects/{project_id}/collaborators/{username}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n update: [\"PATCH /projects/{project_id}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n updateCard: [\"PATCH /projects/columns/cards/{card_id}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n updateColumn: [\"PATCH /projects/columns/{column_id}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }]\n },\n pulls: {\n checkIfMerged: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/merge\"],\n create: [\"POST /repos/{owner}/{repo}/pulls\"],\n createReplyForReviewComment: [\"POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies\"],\n createReview: [\"POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews\"],\n createReviewComment: [\"POST /repos/{owner}/{repo}/pulls/{pull_number}/comments\"],\n deletePendingReview: [\"DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}\"],\n deleteReviewComment: [\"DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}\"],\n dismissReview: [\"PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals\"],\n get: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}\"],\n getReview: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}\"],\n getReviewComment: [\"GET /repos/{owner}/{repo}/pulls/comments/{comment_id}\"],\n list: [\"GET /repos/{owner}/{repo}/pulls\"],\n listCommentsForReview: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments\"],\n listCommits: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/commits\"],\n listFiles: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/files\"],\n listRequestedReviewers: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers\"],\n listReviewComments: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/comments\"],\n listReviewCommentsForRepo: [\"GET /repos/{owner}/{repo}/pulls/comments\"],\n listReviews: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews\"],\n merge: [\"PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge\"],\n removeRequestedReviewers: [\"DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers\"],\n requestReviewers: [\"POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers\"],\n submitReview: [\"POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events\"],\n update: [\"PATCH /repos/{owner}/{repo}/pulls/{pull_number}\"],\n updateBranch: [\"PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch\", {\n mediaType: {\n previews: [\"lydian\"]\n }\n }],\n updateReview: [\"PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}\"],\n updateReviewComment: [\"PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}\"]\n },\n rateLimit: {\n get: [\"GET /rate_limit\"]\n },\n reactions: {\n createForCommitComment: [\"POST /repos/{owner}/{repo}/comments/{comment_id}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n createForIssue: [\"POST /repos/{owner}/{repo}/issues/{issue_number}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n createForIssueComment: [\"POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n createForPullRequestReviewComment: [\"POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n createForTeamDiscussionCommentInOrg: [\"POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n createForTeamDiscussionInOrg: [\"POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n deleteForCommitComment: [\"DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n deleteForIssue: [\"DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n deleteForIssueComment: [\"DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n deleteForPullRequestComment: [\"DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n deleteForTeamDiscussion: [\"DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n deleteForTeamDiscussionComment: [\"DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n deleteLegacy: [\"DELETE /reactions/{reaction_id}\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }, {\n deprecated: \"octokit.reactions.deleteLegacy() is deprecated, see https://docs.github.com/v3/reactions/#delete-a-reaction-legacy\"\n }],\n listForCommitComment: [\"GET /repos/{owner}/{repo}/comments/{comment_id}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n listForIssue: [\"GET /repos/{owner}/{repo}/issues/{issue_number}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n listForIssueComment: [\"GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n listForPullRequestReviewComment: [\"GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n listForTeamDiscussionCommentInOrg: [\"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n listForTeamDiscussionInOrg: [\"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }]\n },\n repos: {\n acceptInvitation: [\"PATCH /user/repository_invitations/{invitation_id}\"],\n addAppAccessRestrictions: [\"POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps\", {}, {\n mapToData: \"apps\"\n }],\n addCollaborator: [\"PUT /repos/{owner}/{repo}/collaborators/{username}\"],\n addStatusCheckContexts: [\"POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts\", {}, {\n mapToData: \"contexts\"\n }],\n addTeamAccessRestrictions: [\"POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams\", {}, {\n mapToData: \"teams\"\n }],\n addUserAccessRestrictions: [\"POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users\", {}, {\n mapToData: \"users\"\n }],\n checkCollaborator: [\"GET /repos/{owner}/{repo}/collaborators/{username}\"],\n checkVulnerabilityAlerts: [\"GET /repos/{owner}/{repo}/vulnerability-alerts\", {\n mediaType: {\n previews: [\"dorian\"]\n }\n }],\n compareCommits: [\"GET /repos/{owner}/{repo}/compare/{base}...{head}\"],\n createCommitComment: [\"POST /repos/{owner}/{repo}/commits/{commit_sha}/comments\"],\n createCommitSignatureProtection: [\"POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures\", {\n mediaType: {\n previews: [\"zzzax\"]\n }\n }],\n createCommitStatus: [\"POST /repos/{owner}/{repo}/statuses/{sha}\"],\n createDeployKey: [\"POST /repos/{owner}/{repo}/keys\"],\n createDeployment: [\"POST /repos/{owner}/{repo}/deployments\"],\n createDeploymentStatus: [\"POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses\"],\n createDispatchEvent: [\"POST /repos/{owner}/{repo}/dispatches\"],\n createForAuthenticatedUser: [\"POST /user/repos\"],\n createFork: [\"POST /repos/{owner}/{repo}/forks\"],\n createInOrg: [\"POST /orgs/{org}/repos\"],\n createOrUpdateFileContents: [\"PUT /repos/{owner}/{repo}/contents/{path}\"],\n createPagesSite: [\"POST /repos/{owner}/{repo}/pages\", {\n mediaType: {\n previews: [\"switcheroo\"]\n }\n }],\n createRelease: [\"POST /repos/{owner}/{repo}/releases\"],\n createUsingTemplate: [\"POST /repos/{template_owner}/{template_repo}/generate\", {\n mediaType: {\n previews: [\"baptiste\"]\n }\n }],\n createWebhook: [\"POST /repos/{owner}/{repo}/hooks\"],\n declineInvitation: [\"DELETE /user/repository_invitations/{invitation_id}\"],\n delete: [\"DELETE /repos/{owner}/{repo}\"],\n deleteAccessRestrictions: [\"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions\"],\n deleteAdminBranchProtection: [\"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins\"],\n deleteBranchProtection: [\"DELETE /repos/{owner}/{repo}/branches/{branch}/protection\"],\n deleteCommitComment: [\"DELETE /repos/{owner}/{repo}/comments/{comment_id}\"],\n deleteCommitSignatureProtection: [\"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures\", {\n mediaType: {\n previews: [\"zzzax\"]\n }\n }],\n deleteDeployKey: [\"DELETE /repos/{owner}/{repo}/keys/{key_id}\"],\n deleteDeployment: [\"DELETE /repos/{owner}/{repo}/deployments/{deployment_id}\"],\n deleteFile: [\"DELETE /repos/{owner}/{repo}/contents/{path}\"],\n deleteInvitation: [\"DELETE /repos/{owner}/{repo}/invitations/{invitation_id}\"],\n deletePagesSite: [\"DELETE /repos/{owner}/{repo}/pages\", {\n mediaType: {\n previews: [\"switcheroo\"]\n }\n }],\n deletePullRequestReviewProtection: [\"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews\"],\n deleteRelease: [\"DELETE /repos/{owner}/{repo}/releases/{release_id}\"],\n deleteReleaseAsset: [\"DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}\"],\n deleteWebhook: [\"DELETE /repos/{owner}/{repo}/hooks/{hook_id}\"],\n disableAutomatedSecurityFixes: [\"DELETE /repos/{owner}/{repo}/automated-security-fixes\", {\n mediaType: {\n previews: [\"london\"]\n }\n }],\n disableVulnerabilityAlerts: [\"DELETE /repos/{owner}/{repo}/vulnerability-alerts\", {\n mediaType: {\n previews: [\"dorian\"]\n }\n }],\n downloadArchive: [\"GET /repos/{owner}/{repo}/zipball/{ref}\", {}, {\n renamed: [\"repos\", \"downloadZipballArchive\"]\n }],\n downloadTarballArchive: [\"GET /repos/{owner}/{repo}/tarball/{ref}\"],\n downloadZipballArchive: [\"GET /repos/{owner}/{repo}/zipball/{ref}\"],\n enableAutomatedSecurityFixes: [\"PUT /repos/{owner}/{repo}/automated-security-fixes\", {\n mediaType: {\n previews: [\"london\"]\n }\n }],\n enableVulnerabilityAlerts: [\"PUT /repos/{owner}/{repo}/vulnerability-alerts\", {\n mediaType: {\n previews: [\"dorian\"]\n }\n }],\n get: [\"GET /repos/{owner}/{repo}\"],\n getAccessRestrictions: [\"GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions\"],\n getAdminBranchProtection: [\"GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins\"],\n getAllStatusCheckContexts: [\"GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts\"],\n getAllTopics: [\"GET /repos/{owner}/{repo}/topics\", {\n mediaType: {\n previews: [\"mercy\"]\n }\n }],\n getAppsWithAccessToProtectedBranch: [\"GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps\"],\n getBranch: [\"GET /repos/{owner}/{repo}/branches/{branch}\"],\n getBranchProtection: [\"GET /repos/{owner}/{repo}/branches/{branch}/protection\"],\n getClones: [\"GET /repos/{owner}/{repo}/traffic/clones\"],\n getCodeFrequencyStats: [\"GET /repos/{owner}/{repo}/stats/code_frequency\"],\n getCollaboratorPermissionLevel: [\"GET /repos/{owner}/{repo}/collaborators/{username}/permission\"],\n getCombinedStatusForRef: [\"GET /repos/{owner}/{repo}/commits/{ref}/status\"],\n getCommit: [\"GET /repos/{owner}/{repo}/commits/{ref}\"],\n getCommitActivityStats: [\"GET /repos/{owner}/{repo}/stats/commit_activity\"],\n getCommitComment: [\"GET /repos/{owner}/{repo}/comments/{comment_id}\"],\n getCommitSignatureProtection: [\"GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures\", {\n mediaType: {\n previews: [\"zzzax\"]\n }\n }],\n getCommunityProfileMetrics: [\"GET /repos/{owner}/{repo}/community/profile\"],\n getContent: [\"GET /repos/{owner}/{repo}/contents/{path}\"],\n getContributorsStats: [\"GET /repos/{owner}/{repo}/stats/contributors\"],\n getDeployKey: [\"GET /repos/{owner}/{repo}/keys/{key_id}\"],\n getDeployment: [\"GET /repos/{owner}/{repo}/deployments/{deployment_id}\"],\n getDeploymentStatus: [\"GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}\"],\n getLatestPagesBuild: [\"GET /repos/{owner}/{repo}/pages/builds/latest\"],\n getLatestRelease: [\"GET /repos/{owner}/{repo}/releases/latest\"],\n getPages: [\"GET /repos/{owner}/{repo}/pages\"],\n getPagesBuild: [\"GET /repos/{owner}/{repo}/pages/builds/{build_id}\"],\n getParticipationStats: [\"GET /repos/{owner}/{repo}/stats/participation\"],\n getPullRequestReviewProtection: [\"GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews\"],\n getPunchCardStats: [\"GET /repos/{owner}/{repo}/stats/punch_card\"],\n getReadme: [\"GET /repos/{owner}/{repo}/readme\"],\n getRelease: [\"GET /repos/{owner}/{repo}/releases/{release_id}\"],\n getReleaseAsset: [\"GET /repos/{owner}/{repo}/releases/assets/{asset_id}\"],\n getReleaseByTag: [\"GET /repos/{owner}/{repo}/releases/tags/{tag}\"],\n getStatusChecksProtection: [\"GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks\"],\n getTeamsWithAccessToProtectedBranch: [\"GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams\"],\n getTopPaths: [\"GET /repos/{owner}/{repo}/traffic/popular/paths\"],\n getTopReferrers: [\"GET /repos/{owner}/{repo}/traffic/popular/referrers\"],\n getUsersWithAccessToProtectedBranch: [\"GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users\"],\n getViews: [\"GET /repos/{owner}/{repo}/traffic/views\"],\n getWebhook: [\"GET /repos/{owner}/{repo}/hooks/{hook_id}\"],\n getWebhookConfigForRepo: [\"GET /repos/{owner}/{repo}/hooks/{hook_id}/config\"],\n listBranches: [\"GET /repos/{owner}/{repo}/branches\"],\n listBranchesForHeadCommit: [\"GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head\", {\n mediaType: {\n previews: [\"groot\"]\n }\n }],\n listCollaborators: [\"GET /repos/{owner}/{repo}/collaborators\"],\n listCommentsForCommit: [\"GET /repos/{owner}/{repo}/commits/{commit_sha}/comments\"],\n listCommitCommentsForRepo: [\"GET /repos/{owner}/{repo}/comments\"],\n listCommitStatusesForRef: [\"GET /repos/{owner}/{repo}/commits/{ref}/statuses\"],\n listCommits: [\"GET /repos/{owner}/{repo}/commits\"],\n listContributors: [\"GET /repos/{owner}/{repo}/contributors\"],\n listDeployKeys: [\"GET /repos/{owner}/{repo}/keys\"],\n listDeploymentStatuses: [\"GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses\"],\n listDeployments: [\"GET /repos/{owner}/{repo}/deployments\"],\n listForAuthenticatedUser: [\"GET /user/repos\"],\n listForOrg: [\"GET /orgs/{org}/repos\"],\n listForUser: [\"GET /users/{username}/repos\"],\n listForks: [\"GET /repos/{owner}/{repo}/forks\"],\n listInvitations: [\"GET /repos/{owner}/{repo}/invitations\"],\n listInvitationsForAuthenticatedUser: [\"GET /user/repository_invitations\"],\n listLanguages: [\"GET /repos/{owner}/{repo}/languages\"],\n listPagesBuilds: [\"GET /repos/{owner}/{repo}/pages/builds\"],\n listPublic: [\"GET /repositories\"],\n listPullRequestsAssociatedWithCommit: [\"GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls\", {\n mediaType: {\n previews: [\"groot\"]\n }\n }],\n listReleaseAssets: [\"GET /repos/{owner}/{repo}/releases/{release_id}/assets\"],\n listReleases: [\"GET /repos/{owner}/{repo}/releases\"],\n listTags: [\"GET /repos/{owner}/{repo}/tags\"],\n listTeams: [\"GET /repos/{owner}/{repo}/teams\"],\n listWebhooks: [\"GET /repos/{owner}/{repo}/hooks\"],\n merge: [\"POST /repos/{owner}/{repo}/merges\"],\n pingWebhook: [\"POST /repos/{owner}/{repo}/hooks/{hook_id}/pings\"],\n removeAppAccessRestrictions: [\"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps\", {}, {\n mapToData: \"apps\"\n }],\n removeCollaborator: [\"DELETE /repos/{owner}/{repo}/collaborators/{username}\"],\n removeStatusCheckContexts: [\"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts\", {}, {\n mapToData: \"contexts\"\n }],\n removeStatusCheckProtection: [\"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks\"],\n removeTeamAccessRestrictions: [\"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams\", {}, {\n mapToData: \"teams\"\n }],\n removeUserAccessRestrictions: [\"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users\", {}, {\n mapToData: \"users\"\n }],\n renameBranch: [\"POST /repos/{owner}/{repo}/branches/{branch}/rename\"],\n replaceAllTopics: [\"PUT /repos/{owner}/{repo}/topics\", {\n mediaType: {\n previews: [\"mercy\"]\n }\n }],\n requestPagesBuild: [\"POST /repos/{owner}/{repo}/pages/builds\"],\n setAdminBranchProtection: [\"POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins\"],\n setAppAccessRestrictions: [\"PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps\", {}, {\n mapToData: \"apps\"\n }],\n setStatusCheckContexts: [\"PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts\", {}, {\n mapToData: \"contexts\"\n }],\n setTeamAccessRestrictions: [\"PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams\", {}, {\n mapToData: \"teams\"\n }],\n setUserAccessRestrictions: [\"PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users\", {}, {\n mapToData: \"users\"\n }],\n testPushWebhook: [\"POST /repos/{owner}/{repo}/hooks/{hook_id}/tests\"],\n transfer: [\"POST /repos/{owner}/{repo}/transfer\"],\n update: [\"PATCH /repos/{owner}/{repo}\"],\n updateBranchProtection: [\"PUT /repos/{owner}/{repo}/branches/{branch}/protection\"],\n updateCommitComment: [\"PATCH /repos/{owner}/{repo}/comments/{comment_id}\"],\n updateInformationAboutPagesSite: [\"PUT /repos/{owner}/{repo}/pages\"],\n updateInvitation: [\"PATCH /repos/{owner}/{repo}/invitations/{invitation_id}\"],\n updatePullRequestReviewProtection: [\"PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews\"],\n updateRelease: [\"PATCH /repos/{owner}/{repo}/releases/{release_id}\"],\n updateReleaseAsset: [\"PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}\"],\n updateStatusCheckPotection: [\"PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks\", {}, {\n renamed: [\"repos\", \"updateStatusCheckProtection\"]\n }],\n updateStatusCheckProtection: [\"PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks\"],\n updateWebhook: [\"PATCH /repos/{owner}/{repo}/hooks/{hook_id}\"],\n updateWebhookConfigForRepo: [\"PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config\"],\n uploadReleaseAsset: [\"POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}\", {\n baseUrl: \"https://uploads.github.com\"\n }]\n },\n search: {\n code: [\"GET /search/code\"],\n commits: [\"GET /search/commits\", {\n mediaType: {\n previews: [\"cloak\"]\n }\n }],\n issuesAndPullRequests: [\"GET /search/issues\"],\n labels: [\"GET /search/labels\"],\n repos: [\"GET /search/repositories\"],\n topics: [\"GET /search/topics\", {\n mediaType: {\n previews: [\"mercy\"]\n }\n }],\n users: [\"GET /search/users\"]\n },\n secretScanning: {\n getAlert: [\"GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}\"],\n listAlertsForRepo: [\"GET /repos/{owner}/{repo}/secret-scanning/alerts\"],\n updateAlert: [\"PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}\"]\n },\n teams: {\n addOrUpdateMembershipForUserInOrg: [\"PUT /orgs/{org}/teams/{team_slug}/memberships/{username}\"],\n addOrUpdateProjectPermissionsInOrg: [\"PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n addOrUpdateRepoPermissionsInOrg: [\"PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}\"],\n checkPermissionsForProjectInOrg: [\"GET /orgs/{org}/teams/{team_slug}/projects/{project_id}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n checkPermissionsForRepoInOrg: [\"GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}\"],\n create: [\"POST /orgs/{org}/teams\"],\n createDiscussionCommentInOrg: [\"POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments\"],\n createDiscussionInOrg: [\"POST /orgs/{org}/teams/{team_slug}/discussions\"],\n deleteDiscussionCommentInOrg: [\"DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}\"],\n deleteDiscussionInOrg: [\"DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}\"],\n deleteInOrg: [\"DELETE /orgs/{org}/teams/{team_slug}\"],\n getByName: [\"GET /orgs/{org}/teams/{team_slug}\"],\n getDiscussionCommentInOrg: [\"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}\"],\n getDiscussionInOrg: [\"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}\"],\n getMembershipForUserInOrg: [\"GET /orgs/{org}/teams/{team_slug}/memberships/{username}\"],\n list: [\"GET /orgs/{org}/teams\"],\n listChildInOrg: [\"GET /orgs/{org}/teams/{team_slug}/teams\"],\n listDiscussionCommentsInOrg: [\"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments\"],\n listDiscussionsInOrg: [\"GET /orgs/{org}/teams/{team_slug}/discussions\"],\n listForAuthenticatedUser: [\"GET /user/teams\"],\n listMembersInOrg: [\"GET /orgs/{org}/teams/{team_slug}/members\"],\n listPendingInvitationsInOrg: [\"GET /orgs/{org}/teams/{team_slug}/invitations\"],\n listProjectsInOrg: [\"GET /orgs/{org}/teams/{team_slug}/projects\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n listReposInOrg: [\"GET /orgs/{org}/teams/{team_slug}/repos\"],\n removeMembershipForUserInOrg: [\"DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}\"],\n removeProjectInOrg: [\"DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}\"],\n removeRepoInOrg: [\"DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}\"],\n updateDiscussionCommentInOrg: [\"PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}\"],\n updateDiscussionInOrg: [\"PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}\"],\n updateInOrg: [\"PATCH /orgs/{org}/teams/{team_slug}\"]\n },\n users: {\n addEmailForAuthenticated: [\"POST /user/emails\"],\n block: [\"PUT /user/blocks/{username}\"],\n checkBlocked: [\"GET /user/blocks/{username}\"],\n checkFollowingForUser: [\"GET /users/{username}/following/{target_user}\"],\n checkPersonIsFollowedByAuthenticated: [\"GET /user/following/{username}\"],\n createGpgKeyForAuthenticated: [\"POST /user/gpg_keys\"],\n createPublicSshKeyForAuthenticated: [\"POST /user/keys\"],\n deleteEmailForAuthenticated: [\"DELETE /user/emails\"],\n deleteGpgKeyForAuthenticated: [\"DELETE /user/gpg_keys/{gpg_key_id}\"],\n deletePublicSshKeyForAuthenticated: [\"DELETE /user/keys/{key_id}\"],\n follow: [\"PUT /user/following/{username}\"],\n getAuthenticated: [\"GET /user\"],\n getByUsername: [\"GET /users/{username}\"],\n getContextForUser: [\"GET /users/{username}/hovercard\"],\n getGpgKeyForAuthenticated: [\"GET /user/gpg_keys/{gpg_key_id}\"],\n getPublicSshKeyForAuthenticated: [\"GET /user/keys/{key_id}\"],\n list: [\"GET /users\"],\n listBlockedByAuthenticated: [\"GET /user/blocks\"],\n listEmailsForAuthenticated: [\"GET /user/emails\"],\n listFollowedByAuthenticated: [\"GET /user/following\"],\n listFollowersForAuthenticatedUser: [\"GET /user/followers\"],\n listFollowersForUser: [\"GET /users/{username}/followers\"],\n listFollowingForUser: [\"GET /users/{username}/following\"],\n listGpgKeysForAuthenticated: [\"GET /user/gpg_keys\"],\n listGpgKeysForUser: [\"GET /users/{username}/gpg_keys\"],\n listPublicEmailsForAuthenticated: [\"GET /user/public_emails\"],\n listPublicKeysForUser: [\"GET /users/{username}/keys\"],\n listPublicSshKeysForAuthenticated: [\"GET /user/keys\"],\n setPrimaryEmailVisibilityForAuthenticated: [\"PATCH /user/email/visibility\"],\n unblock: [\"DELETE /user/blocks/{username}\"],\n unfollow: [\"DELETE /user/following/{username}\"],\n updateAuthenticated: [\"PATCH /user\"]\n }\n};\n\nconst VERSION = \"4.10.1\";\n\nfunction endpointsToMethods(octokit, endpointsMap) {\n const newMethods = {};\n\n for (const [scope, endpoints] of Object.entries(endpointsMap)) {\n for (const [methodName, endpoint] of Object.entries(endpoints)) {\n const [route, defaults, decorations] = endpoint;\n const [method, url] = route.split(/ /);\n const endpointDefaults = Object.assign({\n method,\n url\n }, defaults);\n\n if (!newMethods[scope]) {\n newMethods[scope] = {};\n }\n\n const scopeMethods = newMethods[scope];\n\n if (decorations) {\n scopeMethods[methodName] = decorate(octokit, scope, methodName, endpointDefaults, decorations);\n continue;\n }\n\n scopeMethods[methodName] = octokit.request.defaults(endpointDefaults);\n }\n }\n\n return newMethods;\n}\n\nfunction decorate(octokit, scope, methodName, defaults, decorations) {\n const requestWithDefaults = octokit.request.defaults(defaults);\n /* istanbul ignore next */\n\n function withDecorations(...args) {\n // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488\n let options = requestWithDefaults.endpoint.merge(...args); // There are currently no other decorations than `.mapToData`\n\n if (decorations.mapToData) {\n options = Object.assign({}, options, {\n data: options[decorations.mapToData],\n [decorations.mapToData]: undefined\n });\n return requestWithDefaults(options);\n }\n\n if (decorations.renamed) {\n const [newScope, newMethodName] = decorations.renamed;\n octokit.log.warn(`octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()`);\n }\n\n if (decorations.deprecated) {\n octokit.log.warn(decorations.deprecated);\n }\n\n if (decorations.renamedParameters) {\n // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488\n const options = requestWithDefaults.endpoint.merge(...args);\n\n for (const [name, alias] of Object.entries(decorations.renamedParameters)) {\n if (name in options) {\n octokit.log.warn(`\"${name}\" parameter is deprecated for \"octokit.${scope}.${methodName}()\". Use \"${alias}\" instead`);\n\n if (!(alias in options)) {\n options[alias] = options[name];\n }\n\n delete options[name];\n }\n }\n\n return requestWithDefaults(options);\n } // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488\n\n\n return requestWithDefaults(...args);\n }\n\n return Object.assign(withDecorations, requestWithDefaults);\n}\n\n/**\n * This plugin is a 1:1 copy of internal @octokit/rest plugins. The primary\n * goal is to rebuild @octokit/rest on top of @octokit/core. Once that is\n * done, we will remove the registerEndpoints methods and return the methods\n * directly as with the other plugins. At that point we will also remove the\n * legacy workarounds and deprecations.\n *\n * See the plan at\n * https://github.com/octokit/plugin-rest-endpoint-methods.js/pull/1\n */\n\nfunction restEndpointMethods(octokit) {\n return endpointsToMethods(octokit, Endpoints);\n}\nrestEndpointMethods.VERSION = VERSION;\n\nexports.restEndpointMethods = restEndpointMethods;\n//# sourceMappingURL=index.js.map\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nfunction _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }\n\nvar deprecation = require('deprecation');\nvar once = _interopDefault(require('once'));\n\nconst logOnce = once(deprecation => console.warn(deprecation));\n/**\n * Error with extra properties to help with debugging\n */\n\nclass RequestError extends Error {\n constructor(message, statusCode, options) {\n super(message); // Maintains proper stack trace (only available on V8)\n\n /* istanbul ignore next */\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n\n this.name = \"HttpError\";\n this.status = statusCode;\n Object.defineProperty(this, \"code\", {\n get() {\n logOnce(new deprecation.Deprecation(\"[@octokit/request-error] `error.code` is deprecated, use `error.status`.\"));\n return statusCode;\n }\n\n });\n this.headers = options.headers || {}; // redact request credentials without mutating original request options\n\n const requestCopy = Object.assign({}, options.request);\n\n if (options.request.headers.authorization) {\n requestCopy.headers = Object.assign({}, options.request.headers, {\n authorization: options.request.headers.authorization.replace(/ .*$/, \" [REDACTED]\")\n });\n }\n\n requestCopy.url = requestCopy.url // client_id & client_secret can be passed as URL query parameters to increase rate limit\n // see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications\n .replace(/\\bclient_secret=\\w+/g, \"client_secret=[REDACTED]\") // OAuth tokens can be passed as URL query parameters, although it is not recommended\n // see https://developer.github.com/v3/#oauth2-token-sent-in-a-header\n .replace(/\\baccess_token=\\w+/g, \"access_token=[REDACTED]\");\n this.request = requestCopy;\n }\n\n}\n\nexports.RequestError = RequestError;\n//# sourceMappingURL=index.js.map\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nfunction _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }\n\nvar endpoint = require('@octokit/endpoint');\nvar universalUserAgent = require('universal-user-agent');\nvar isPlainObject = require('is-plain-object');\nvar nodeFetch = _interopDefault(require('node-fetch'));\nvar requestError = require('@octokit/request-error');\n\nconst VERSION = \"5.4.14\";\n\nfunction getBufferResponse(response) {\n return response.arrayBuffer();\n}\n\nfunction fetchWrapper(requestOptions) {\n if (isPlainObject.isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) {\n requestOptions.body = JSON.stringify(requestOptions.body);\n }\n\n let headers = {};\n let status;\n let url;\n const fetch = requestOptions.request && requestOptions.request.fetch || nodeFetch;\n return fetch(requestOptions.url, Object.assign({\n method: requestOptions.method,\n body: requestOptions.body,\n headers: requestOptions.headers,\n redirect: requestOptions.redirect\n }, requestOptions.request)).then(response => {\n url = response.url;\n status = response.status;\n\n for (const keyAndValue of response.headers) {\n headers[keyAndValue[0]] = keyAndValue[1];\n }\n\n if (status === 204 || status === 205) {\n return;\n } // GitHub API returns 200 for HEAD requests\n\n\n if (requestOptions.method === \"HEAD\") {\n if (status < 400) {\n return;\n }\n\n throw new requestError.RequestError(response.statusText, status, {\n headers,\n request: requestOptions\n });\n }\n\n if (status === 304) {\n throw new requestError.RequestError(\"Not modified\", status, {\n headers,\n request: requestOptions\n });\n }\n\n if (status >= 400) {\n return response.text().then(message => {\n const error = new requestError.RequestError(message, status, {\n headers,\n request: requestOptions\n });\n\n try {\n let responseBody = JSON.parse(error.message);\n Object.assign(error, responseBody);\n let errors = responseBody.errors; // Assumption `errors` would always be in Array format\n\n error.message = error.message + \": \" + errors.map(JSON.stringify).join(\", \");\n } catch (e) {// ignore, see octokit/rest.js#684\n }\n\n throw error;\n });\n }\n\n const contentType = response.headers.get(\"content-type\");\n\n if (/application\\/json/.test(contentType)) {\n return response.json();\n }\n\n if (!contentType || /^text\\/|charset=utf-8$/.test(contentType)) {\n return response.text();\n }\n\n return getBufferResponse(response);\n }).then(data => {\n return {\n status,\n url,\n headers,\n data\n };\n }).catch(error => {\n if (error instanceof requestError.RequestError) {\n throw error;\n }\n\n throw new requestError.RequestError(error.message, 500, {\n headers,\n request: requestOptions\n });\n });\n}\n\nfunction withDefaults(oldEndpoint, newDefaults) {\n const endpoint = oldEndpoint.defaults(newDefaults);\n\n const newApi = function (route, parameters) {\n const endpointOptions = endpoint.merge(route, parameters);\n\n if (!endpointOptions.request || !endpointOptions.request.hook) {\n return fetchWrapper(endpoint.parse(endpointOptions));\n }\n\n const request = (route, parameters) => {\n return fetchWrapper(endpoint.parse(endpoint.merge(route, parameters)));\n };\n\n Object.assign(request, {\n endpoint,\n defaults: withDefaults.bind(null, endpoint)\n });\n return endpointOptions.request.hook(request, endpointOptions);\n };\n\n return Object.assign(newApi, {\n endpoint,\n defaults: withDefaults.bind(null, endpoint)\n });\n}\n\nconst request = withDefaults(endpoint.endpoint, {\n headers: {\n \"user-agent\": `octokit-request.js/${VERSION} ${universalUserAgent.getUserAgent()}`\n }\n});\n\nexports.request = request;\n//# sourceMappingURL=index.js.map\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\n/*!\n * is-plain-object \n *\n * Copyright (c) 2014-2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\nfunction isObject(o) {\n return Object.prototype.toString.call(o) === '[object Object]';\n}\n\nfunction isPlainObject(o) {\n var ctor,prot;\n\n if (isObject(o) === false) return false;\n\n // If has modified constructor\n ctor = o.constructor;\n if (ctor === undefined) return true;\n\n // If has modified prototype\n prot = ctor.prototype;\n if (isObject(prot) === false) return false;\n\n // If constructor does not have an Object-specific method\n if (prot.hasOwnProperty('isPrototypeOf') === false) {\n return false;\n }\n\n // Most likely a plain Object\n return true;\n}\n\nexports.isPlainObject = isPlainObject;\n","\"use strict\";\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst utils = require(\"../utils\");\n/**\n * An Archive represents a collection of named assets.\n */\nclass Archive {\n constructor() {\n /**\n * A private field to help with RTTI that works in SxS scenarios.\n * @internal\n */\n // tslint:disable-next-line:variable-name\n this.__pulumiArchive = true;\n }\n /**\n * Returns true if the given object is an instance of an Archive. This is designed to work even when\n * multiple copies of the Pulumi SDK have been loaded into the same process.\n */\n static isInstance(obj) {\n return utils.isInstance(obj, \"__pulumiArchive\");\n }\n}\nexports.Archive = Archive;\n/**\n * An AssetArchive is an archive created from an in-memory collection of named assets or other archives.\n */\nclass AssetArchive extends Archive {\n constructor(assets) {\n super();\n this.assets = Promise.resolve(assets);\n }\n}\nexports.AssetArchive = AssetArchive;\n/**\n * A FileArchive is a file-based archive, or a collection of file-based assets. This can be a raw directory or a\n * single archive file in one of the supported formats (.tar, .tar.gz, or .zip).\n */\nclass FileArchive extends Archive {\n constructor(path) {\n super();\n this.path = Promise.resolve(path);\n }\n}\nexports.FileArchive = FileArchive;\n/**\n * A RemoteArchive is a file-based archive fetched from a remote location. The URI's scheme dictates the\n * protocol for fetching the archive's contents: `file://` is a local file (just like a FileArchive), `http://` and\n * `https://` specify HTTP and HTTPS, respectively, and specific providers may recognize custom schemes.\n */\nclass RemoteArchive extends Archive {\n constructor(uri) {\n super();\n this.uri = Promise.resolve(uri);\n }\n}\nexports.RemoteArchive = RemoteArchive;\n","\"use strict\";\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst utils = require(\"../utils\");\n/**\n * Asset represents a single blob of text or data that is managed as a first class entity.\n */\nclass Asset {\n constructor() {\n /**\n * A private field to help with RTTI that works in SxS scenarios.\n * @internal\n */\n // tslint:disable-next-line:variable-name\n this.__pulumiAsset = true;\n }\n /**\n * Returns true if the given object is an instance of an Asset. This is designed to work even when\n * multiple copies of the Pulumi SDK have been loaded into the same process.\n */\n static isInstance(obj) {\n return utils.isInstance(obj, \"__pulumiAsset\");\n }\n}\nexports.Asset = Asset;\n/**\n * Blob is a kind of asset produced from an in-memory blob represented as a byte array.\n */\n/* IDEA: enable this once Uint8Array is supported.\nexport class Blob extends Asset {\n constructor(data: Uint8Array) {\n super();\n }\n}\n*/\n/**\n * FileAsset is a kind of asset produced from a given path to a file on the local filesystem.\n */\nclass FileAsset extends Asset {\n constructor(path) {\n super();\n this.path = Promise.resolve(path);\n }\n}\nexports.FileAsset = FileAsset;\n/**\n * StringAsset is a kind of asset produced from an in-memory UTF8-encoded string.\n */\nclass StringAsset extends Asset {\n constructor(text) {\n super();\n this.text = Promise.resolve(text);\n }\n}\nexports.StringAsset = StringAsset;\n/**\n * RemoteAsset is a kind of asset produced from a given URI string. The URI's scheme dictates the protocol for fetching\n * contents: `file://` specifies a local file, `http://` and `https://` specify HTTP and HTTPS, respectively. Note that\n * specific providers may recognize alternative schemes; this is merely the base-most set that all providers support.\n */\nclass RemoteAsset extends Asset {\n constructor(uri) {\n super();\n this.uri = Promise.resolve(uri);\n }\n}\nexports.RemoteAsset = RemoteAsset;\n","\"use strict\";\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__export(require(\"./archive\"));\n__export(require(\"./asset\"));\n","\"use strict\";\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst errors_1 = require(\"./errors\");\nconst metadata_1 = require(\"./metadata\");\nconst output_1 = require(\"./output\");\nconst runtime_1 = require(\"./runtime\");\nfunction makeSecret(value) {\n return new output_1.Output([], Promise.resolve(value), \n /*isKnown:*/ Promise.resolve(true), /*isSecret:*/ Promise.resolve(true), Promise.resolve([]));\n}\n/**\n * Config is a bag of related configuration state. Each bag contains any number of configuration variables, indexed by\n * simple keys, and each has a name that uniquely identifies it; two bags with different names do not share values for\n * variables that otherwise share the same key. For example, a bag whose name is `pulumi:foo`, with keys `a`, `b`,\n * and `c`, is entirely separate from a bag whose name is `pulumi:bar` with the same simple key names. Each key has a\n * fully qualified names, such as `pulumi:foo:a`, ..., and `pulumi:bar:a`, respectively.\n */\nclass Config {\n constructor(name) {\n if (name === undefined) {\n name = metadata_1.getProject();\n }\n if (name.endsWith(\":config\")) {\n name = name.replace(/:config$/, \"\");\n }\n this.name = name;\n }\n /**\n * get loads an optional configuration value by its key, or undefined if it doesn't exist.\n *\n * @param key The key to lookup.\n * @param opts An options bag to constrain legal values.\n */\n get(key, opts) {\n const v = runtime_1.getConfig(this.fullKey(key));\n if (v === undefined) {\n return undefined;\n }\n if (opts) {\n // SAFETY: if allowedValues != null, verifying v ∈ K[]\n if (opts.allowedValues !== undefined && opts.allowedValues.indexOf(v) === -1) {\n throw new ConfigEnumError(this.fullKey(key), v, opts.allowedValues);\n }\n else if (opts.minLength !== undefined && v.length < opts.minLength) {\n throw new ConfigRangeError(this.fullKey(key), v, opts.minLength, undefined);\n }\n else if (opts.maxLength !== undefined && v.length > opts.maxLength) {\n throw new ConfigRangeError(this.fullKey(key), v, undefined, opts.maxLength);\n }\n else if (opts.pattern !== undefined) {\n let pattern = opts.pattern;\n if (typeof pattern === \"string\") {\n pattern = new RegExp(pattern);\n }\n if (!pattern.test(v)) {\n throw new ConfigPatternError(this.fullKey(key), v, pattern);\n }\n }\n }\n // SAFETY:\n // allowedValues != null ⇒ v ∈ K[]\n // allowedValues == null ⇒ K = string & v : string\n return v;\n }\n /**\n * getSecret loads an optional configuration value by its key, marking it as a secret, or undefined if it\n * doesn't exist.\n *\n * @param key The key to lookup.\n * @param opts An options bag to constrain legal values.\n */\n getSecret(key, opts) {\n const v = this.get(key, opts);\n if (v === undefined) {\n return undefined;\n }\n return makeSecret(v);\n }\n /**\n * getBoolean loads an optional configuration value, as a boolean, by its key, or undefined if it doesn't exist.\n * If the configuration value isn't a legal boolean, this function will throw an error.\n *\n * @param key The key to lookup.\n */\n getBoolean(key) {\n const v = this.get(key);\n if (v === undefined) {\n return undefined;\n }\n else if (v === \"true\") {\n return true;\n }\n else if (v === \"false\") {\n return false;\n }\n throw new ConfigTypeError(this.fullKey(key), v, \"boolean\");\n }\n /**\n * getSecretBoolean loads an optional configuration value, as a boolean, by its key, making it as a secret\n * or undefined if it doesn't exist. If the configuration value isn't a legal boolean, this function will\n * throw an error.\n *\n * @param key The key to lookup.\n */\n getSecretBoolean(key) {\n const v = this.getBoolean(key);\n if (v === undefined) {\n return undefined;\n }\n return makeSecret(v);\n }\n /**\n * getNumber loads an optional configuration value, as a number, by its key, or undefined if it doesn't exist.\n * If the configuration value isn't a legal number, this function will throw an error.\n *\n * @param key The key to lookup.\n * @param opts An options bag to constrain legal values.\n */\n getNumber(key, opts) {\n const v = this.get(key);\n if (v === undefined) {\n return undefined;\n }\n const f = parseFloat(v);\n if (isNaN(f)) {\n throw new ConfigTypeError(this.fullKey(key), v, \"number\");\n }\n if (opts) {\n if (opts.min !== undefined && f < opts.min) {\n throw new ConfigRangeError(this.fullKey(key), f, opts.min, undefined);\n }\n else if (opts.max !== undefined && f > opts.max) {\n throw new ConfigRangeError(this.fullKey(key), f, undefined, opts.max);\n }\n }\n return f;\n }\n /**\n * getSecretNumber loads an optional configuration value, as a number, by its key, marking it as a secret\n * or undefined if it doesn't exist.\n * If the configuration value isn't a legal number, this function will throw an error.\n *\n * @param key The key to lookup.\n * @param opts An options bag to constrain legal values.\n */\n getSecretNumber(key, opts) {\n const v = this.getNumber(key, opts);\n if (v === undefined) {\n return undefined;\n }\n return makeSecret(v);\n }\n /**\n * getObject loads an optional configuration value, as an object, by its key, or undefined if it doesn't exist.\n * This routine simply JSON parses and doesn't validate the shape of the contents.\n *\n * @param key The key to lookup.\n */\n getObject(key) {\n const v = this.get(key);\n if (v === undefined) {\n return undefined;\n }\n try {\n return JSON.parse(v);\n }\n catch (err) {\n throw new ConfigTypeError(this.fullKey(key), v, \"JSON object\");\n }\n }\n /**\n * getSecretObject loads an optional configuration value, as an object, by its key, marking it as a secret\n * or undefined if it doesn't exist.\n * This routine simply JSON parses and doesn't validate the shape of the contents.\n *\n * @param key The key to lookup.\n */\n getSecretObject(key) {\n const v = this.getObject(key);\n if (v === undefined) {\n return undefined;\n }\n return makeSecret(v);\n }\n /**\n * require loads a configuration value by its given key. If it doesn't exist, an error is thrown.\n *\n * @param key The key to lookup.\n * @param opts An options bag to constrain legal values.\n */\n require(key, opts) {\n const v = this.get(key, opts);\n if (v === undefined) {\n throw new ConfigMissingError(this.fullKey(key));\n }\n return v;\n }\n /**\n * require loads a configuration value by its given key, marking it as a secet. If it doesn't exist, an error\n * is thrown.\n *\n * @param key The key to lookup.\n * @param opts An options bag to constrain legal values.\n */\n requireSecret(key, opts) {\n return makeSecret(this.require(key, opts));\n }\n /**\n * requireBoolean loads a configuration value, as a boolean, by its given key. If it doesn't exist, or the\n * configuration value is not a legal boolean, an error is thrown.\n *\n * @param key The key to lookup.\n */\n requireBoolean(key) {\n const v = this.getBoolean(key);\n if (v === undefined) {\n throw new ConfigMissingError(this.fullKey(key));\n }\n return v;\n }\n /**\n * requireSecretBoolean loads a configuration value, as a boolean, by its given key, marking it as a secret.\n * If it doesn't exist, or the configuration value is not a legal boolean, an error is thrown.\n *\n * @param key The key to lookup.\n */\n requireSecretBoolean(key) {\n return makeSecret(this.requireBoolean(key));\n }\n /**\n * requireNumber loads a configuration value, as a number, by its given key. If it doesn't exist, or the\n * configuration value is not a legal number, an error is thrown.\n *\n * @param key The key to lookup.\n * @param opts An options bag to constrain legal values.\n */\n requireNumber(key, opts) {\n const v = this.getNumber(key, opts);\n if (v === undefined) {\n throw new ConfigMissingError(this.fullKey(key));\n }\n return v;\n }\n /**\n * requireSecretNumber loads a configuration value, as a number, by its given key, marking it as a secret.\n * If it doesn't exist, or the configuration value is not a legal number, an error is thrown.\n *\n * @param key The key to lookup.\n * @param opts An options bag to constrain legal values.\n */\n requireSecretNumber(key, opts) {\n return makeSecret(this.requireNumber(key, opts));\n }\n /**\n * requireObject loads a configuration value as a JSON string and deserializes the JSON into a JavaScript object. If\n * it doesn't exist, or the configuration value is not a legal JSON string, an error is thrown.\n *\n * @param key The key to lookup.\n */\n requireObject(key) {\n const v = this.getObject(key);\n if (v === undefined) {\n throw new ConfigMissingError(this.fullKey(key));\n }\n return v;\n }\n /**\n * requireSecretObject loads a configuration value as a JSON string and deserializes the JSON into a JavaScript\n * object, marking it as a secret. If it doesn't exist, or the configuration value is not a legal JSON\n * string, an error is thrown.\n *\n * @param key The key to lookup.\n */\n requireSecretObject(key) {\n return makeSecret(this.requireObject(key));\n }\n /**\n * fullKey turns a simple configuration key into a fully resolved one, by prepending the bag's name.\n *\n * @param key The key to lookup.\n */\n fullKey(key) {\n return `${this.name}:${key}`;\n }\n}\nexports.Config = Config;\n/**\n * ConfigTypeError is used when a configuration value is of the wrong type.\n */\nclass ConfigTypeError extends errors_1.RunError {\n constructor(key, v, expectedType) {\n super(`Configuration '${key}' value '${v}' is not a valid ${expectedType}`);\n }\n}\n/**\n * ConfigEnumError is used when a configuration value isn't a correct enum value.\n */\nclass ConfigEnumError extends errors_1.RunError {\n constructor(key, v, values) {\n super(`Configuration '${key}' value '${v}' is not a legal enum value (${JSON.stringify(values)})`);\n }\n}\n/**\n * ConfigRangeError is used when a configuration value is outside of the range of legal sizes.\n */\nclass ConfigRangeError extends errors_1.RunError {\n constructor(key, v, min, max) {\n let range;\n if (max === undefined) {\n range = `min ${min}`;\n }\n else if (min === undefined) {\n range = `max ${max}`;\n }\n else {\n range = `${min}-${max}`;\n }\n if (typeof v === \"string\") {\n range += \" chars\";\n }\n super(`Configuration '${key}' value '${v}' is outside of the legal range (${range}, inclusive)`);\n }\n}\n/**\n * ConfigPatternError is used when a configuration value does not match the given regular expression.\n */\nclass ConfigPatternError extends errors_1.RunError {\n constructor(key, v, regexp) {\n super(`Configuration '${key}' value '${v}' does not match the regular expression ${regexp.toString()}`);\n }\n}\n/**\n * ConfigMissingError is used when a configuration value is completely missing.\n */\nclass ConfigMissingError extends errors_1.RunError {\n constructor(key) {\n super(`Missing required configuration variable '${key}'\\n` +\n `\\tplease set a value using the command \\`pulumi config set ${key} \\``);\n this.key = key;\n }\n}\n","\"use strict\";\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst resource = require(\"../resource\");\nconst runtime = require(\"../runtime\");\nfunction serializeProvider(provider) {\n return runtime.serializeFunction(() => provider).then(sf => sf.text);\n}\n/**\n * Resource represents a Pulumi Resource that incorporates an inline implementation of the Resource's CRUD operations.\n */\nclass Resource extends resource.CustomResource {\n /**\n * Creates a new dynamic resource.\n *\n * @param provider The implementation of the resource's CRUD operations.\n * @param name The name of the resource.\n * @param props The arguments to use to populate the new resource. Must not define the reserved\n * property \"__provider\".\n * @param opts A bag of options that control this resource's behavior.\n */\n constructor(provider, name, props, opts) {\n const providerKey = \"__provider\";\n if (props[providerKey]) {\n throw new Error(\"A dynamic resource must not define the __provider key\");\n }\n props[providerKey] = serializeProvider(provider);\n super(\"pulumi-nodejs:dynamic:Resource\", name, props, opts);\n }\n}\nexports.Resource = Resource;\n","\"use strict\";\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst grpc = require(\"@grpc/grpc-js\");\nconst utils = require(\"./utils\");\n/**\n * RunError can be used for terminating a program abruptly, but resulting in a clean exit rather\n * than the usual verbose unhandled error logic which emits the source program text and complete\n * stack trace. This type should be rarely used. Ideally ResourceError should always be used so\n * that as many errors as possible can be associated with a Resource.\n */\nclass RunError extends Error {\n constructor(message) {\n super(message);\n /**\n * A private field to help with RTTI that works in SxS scenarios.\n * @internal\n */\n // tslint:disable-next-line:variable-name\n this.__pulumiRunError = true;\n }\n /**\n * Returns true if the given object is an instance of a RunError. This is designed to work even when\n * multiple copies of the Pulumi SDK have been loaded into the same process.\n */\n static isInstance(obj) {\n return utils.isInstance(obj, \"__pulumiRunError\");\n }\n}\nexports.RunError = RunError;\n/**\n * ResourceError can be used for terminating a program abruptly, specifically associating the\n * problem with a Resource. Depending on the nature of the problem, clients can choose whether or\n * not a call stack should be returned as well. This should be very rare, and would only indicate\n * no usefulness of presenting that stack to the user.\n */\nclass ResourceError extends Error {\n constructor(message, resource, hideStack) {\n super(message);\n this.resource = resource;\n this.hideStack = hideStack;\n /**\n * A private field to help with RTTI that works in SxS scenarios.\n * @internal\n */\n // tslint:disable-next-line:variable-name\n this.__pulumResourceError = true;\n }\n /**\n * Returns true if the given object is an instance of a ResourceError. This is designed to work even when\n * multiple copies of the Pulumi SDK have been loaded into the same process.\n */\n static isInstance(obj) {\n return utils.isInstance(obj, \"__pulumResourceError\");\n }\n}\nexports.ResourceError = ResourceError;\nfunction isGrpcError(err) {\n const code = err.code;\n return code === grpc.status.UNAVAILABLE || code === grpc.status.CANCELLED;\n}\nexports.isGrpcError = isGrpcError;\n","\"use strict\";\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\n// Enable source map support so we get good stack traces.\nrequire(\"source-map-support/register\");\n// Export top-level elements.\n__export(require(\"./config\"));\n__export(require(\"./errors\"));\n__export(require(\"./metadata\"));\n__export(require(\"./output\"));\n__export(require(\"./resource\"));\n__export(require(\"./stackReference\"));\n// Export submodules individually.\nconst asset = require(\"./asset\");\nexports.asset = asset;\nconst dynamic = require(\"./dynamic\");\nexports.dynamic = dynamic;\nconst iterable = require(\"./iterable\");\nexports.iterable = iterable;\nconst log = require(\"./log\");\nexports.log = log;\nconst provider = require(\"./provider\");\nexports.provider = provider;\nconst runtime = require(\"./runtime\");\nexports.runtime = runtime;\nconst utils = require(\"./utils\");\nexports.utils = utils;\n// @pulumi is a deployment-only module. If someone tries to capture it, and we fail for some reason\n// we want to give a good message about what the problem likely is. Note that capturing a\n// deployment time module can be ok in some cases. For example, using \"new pulumi.Config\" is fine.\n// However, in general, the majority of this API is not safe to use at 'run time' and will fail.\n/** @internal */\nexports.deploymentOnlyModule = true;\n","\"use strict\";\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst output_1 = require(\"../output\");\n/**\n * toObject takes an array of T values, and a selector that produces key/value pairs from those inputs,\n * and converts this array into an output object with those keys and values.\n *\n * For instance, given an array as follows\n *\n * [{ s: \"a\", n: 1 }, { s: \"b\", n: 2 }, { s: \"c\", n: 3 }]\n *\n * and whose selector is roughly `(e) => [e.s, e.n]`, the resulting object will be\n *\n * { \"a\": 1, \"b\": 2, \"c\": 3 }\n *\n */\nfunction toObject(iter, selector) {\n return output_1.Output.create(iter).apply(elems => {\n const array = [];\n for (const e of elems) {\n array.push(selector(e));\n }\n return output_1.Output.create(array).apply(kvps => {\n const obj = {};\n for (const kvp of kvps) {\n obj[kvp[0]] = kvp[1];\n }\n return obj;\n });\n });\n}\nexports.toObject = toObject;\n/**\n * groupBy takes an array of T values, and a selector that prduces key/value pairs from those inputs,\n * and converts this array into an output object, with those keys, and where each property is an array of values,\n * in the case that the same key shows up multiple times in the input.\n *\n * For instance, given an array as follows\n *\n * [{ s: \"a\", n: 1 }, { s: \"a\", n: 2 }, { s: \"b\", n: 1 }]\n *\n * and whose selector is roughly `(e) => [e.s, e.n]`, the resulting object will be\n *\n * { \"a\": [1, 2], \"b\": [1] }\n *\n */\nfunction groupBy(iter, selector) {\n return output_1.Output.create(iter).apply(elems => {\n const array = [];\n for (const e of elems) {\n array.push(selector(e));\n }\n return output_1.Output.create(array).apply(kvps => {\n const obj = {};\n for (const kvp of kvps) {\n let r = obj[kvp[0]];\n if (!r) {\n r = [];\n obj[kvp[0]] = r;\n }\n r.push(kvp[1]);\n }\n return obj;\n });\n });\n}\nexports.groupBy = groupBy;\n","\"use strict\";\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst settings_1 = require(\"../runtime/settings\");\nconst engproto = require(\"../proto/engine_pb.js\");\nlet errcnt = 0;\nlet lastLog = Promise.resolve();\n/**\n * hasErrors returns true if any errors have occurred in the program.\n */\nfunction hasErrors() {\n return errcnt > 0;\n}\nexports.hasErrors = hasErrors;\n/**\n * debug logs a debug-level message that is generally hidden from end-users.\n */\nfunction debug(msg, resource, streamId, ephemeral) {\n const engine = settings_1.getEngine();\n if (engine) {\n return log(engine, engproto.LogSeverity.DEBUG, msg, resource, streamId, ephemeral);\n }\n else {\n return Promise.resolve();\n }\n}\nexports.debug = debug;\n/**\n * info logs an informational message that is generally printed to stdout during resource operations.\n */\nfunction info(msg, resource, streamId, ephemeral) {\n const engine = settings_1.getEngine();\n if (engine) {\n return log(engine, engproto.LogSeverity.INFO, msg, resource, streamId, ephemeral);\n }\n else {\n console.log(`info: [runtime] ${msg}`);\n return Promise.resolve();\n }\n}\nexports.info = info;\n/**\n * warn logs a warning to indicate that something went wrong, but not catastrophically so.\n */\nfunction warn(msg, resource, streamId, ephemeral) {\n const engine = settings_1.getEngine();\n if (engine) {\n return log(engine, engproto.LogSeverity.WARNING, msg, resource, streamId, ephemeral);\n }\n else {\n console.warn(`warning: [runtime] ${msg}`);\n return Promise.resolve();\n }\n}\nexports.warn = warn;\n/**\n * error logs a fatal error to indicate that the tool should stop processing resource operations immediately.\n */\nfunction error(msg, resource, streamId, ephemeral) {\n errcnt++; // remember the error so we can suppress leaks.\n const engine = settings_1.getEngine();\n if (engine) {\n return log(engine, engproto.LogSeverity.ERROR, msg, resource, streamId, ephemeral);\n }\n else {\n console.error(`error: [runtime] ${msg}`);\n return Promise.resolve();\n }\n}\nexports.error = error;\nfunction log(engine, sev, msg, resource, streamId, ephemeral) {\n // Ensure we log everything in serial order.\n const keepAlive = settings_1.rpcKeepAlive();\n const urnPromise = resource\n ? resource.urn.promise()\n : Promise.resolve(\"\");\n lastLog = Promise.all([lastLog, urnPromise]).then(([_, urn]) => {\n return new Promise((resolve, reject) => {\n try {\n const req = new engproto.LogRequest();\n req.setSeverity(sev);\n req.setMessage(msg);\n req.setUrn(urn);\n req.setStreamid(streamId === undefined ? 0 : streamId);\n req.setEphemeral(ephemeral === true);\n engine.log(req, () => {\n resolve(); // let the next log through\n keepAlive(); // permit RPC channel tear-downs\n });\n }\n catch (err) {\n reject(err);\n }\n });\n });\n return lastLog.catch(() => undefined);\n}\n","\"use strict\";\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\n// This file exports metadata about the context in which a program is being run.\nconst runtime = require(\"./runtime\");\n/**\n * getProject returns the current project name. It throws an exception if none is registered.\n */\nfunction getProject() {\n return runtime.getProject();\n}\nexports.getProject = getProject;\n/**\n * getStack returns the current stack name. It throws an exception if none is registered.\n */\nfunction getStack() {\n return runtime.getStack();\n}\nexports.getStack = getStack;\n","exports = module.exports = SemVer\n\nvar debug\n/* istanbul ignore next */\nif (typeof process === 'object' &&\n process.env &&\n process.env.NODE_DEBUG &&\n /\\bsemver\\b/i.test(process.env.NODE_DEBUG)) {\n debug = function () {\n var args = Array.prototype.slice.call(arguments, 0)\n args.unshift('SEMVER')\n console.log.apply(console, args)\n }\n} else {\n debug = function () {}\n}\n\n// Note: this is the semver.org version of the spec that it implements\n// Not necessarily the package version of this code.\nexports.SEMVER_SPEC_VERSION = '2.0.0'\n\nvar MAX_LENGTH = 256\nvar MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||\n /* istanbul ignore next */ 9007199254740991\n\n// Max safe segment length for coercion.\nvar MAX_SAFE_COMPONENT_LENGTH = 16\n\n// The actual regexps go on exports.re\nvar re = exports.re = []\nvar src = exports.src = []\nvar t = exports.tokens = {}\nvar R = 0\n\nfunction tok (n) {\n t[n] = R++\n}\n\n// The following Regular Expressions can be used for tokenizing,\n// validating, and parsing SemVer version strings.\n\n// ## Numeric Identifier\n// A single `0`, or a non-zero digit followed by zero or more digits.\n\ntok('NUMERICIDENTIFIER')\nsrc[t.NUMERICIDENTIFIER] = '0|[1-9]\\\\d*'\ntok('NUMERICIDENTIFIERLOOSE')\nsrc[t.NUMERICIDENTIFIERLOOSE] = '[0-9]+'\n\n// ## Non-numeric Identifier\n// Zero or more digits, followed by a letter or hyphen, and then zero or\n// more letters, digits, or hyphens.\n\ntok('NONNUMERICIDENTIFIER')\nsrc[t.NONNUMERICIDENTIFIER] = '\\\\d*[a-zA-Z-][a-zA-Z0-9-]*'\n\n// ## Main Version\n// Three dot-separated numeric identifiers.\n\ntok('MAINVERSION')\nsrc[t.MAINVERSION] = '(' + src[t.NUMERICIDENTIFIER] + ')\\\\.' +\n '(' + src[t.NUMERICIDENTIFIER] + ')\\\\.' +\n '(' + src[t.NUMERICIDENTIFIER] + ')'\n\ntok('MAINVERSIONLOOSE')\nsrc[t.MAINVERSIONLOOSE] = '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\\\.' +\n '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\\\.' +\n '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')'\n\n// ## Pre-release Version Identifier\n// A numeric identifier, or a non-numeric identifier.\n\ntok('PRERELEASEIDENTIFIER')\nsrc[t.PRERELEASEIDENTIFIER] = '(?:' + src[t.NUMERICIDENTIFIER] +\n '|' + src[t.NONNUMERICIDENTIFIER] + ')'\n\ntok('PRERELEASEIDENTIFIERLOOSE')\nsrc[t.PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[t.NUMERICIDENTIFIERLOOSE] +\n '|' + src[t.NONNUMERICIDENTIFIER] + ')'\n\n// ## Pre-release Version\n// Hyphen, followed by one or more dot-separated pre-release version\n// identifiers.\n\ntok('PRERELEASE')\nsrc[t.PRERELEASE] = '(?:-(' + src[t.PRERELEASEIDENTIFIER] +\n '(?:\\\\.' + src[t.PRERELEASEIDENTIFIER] + ')*))'\n\ntok('PRERELEASELOOSE')\nsrc[t.PRERELEASELOOSE] = '(?:-?(' + src[t.PRERELEASEIDENTIFIERLOOSE] +\n '(?:\\\\.' + src[t.PRERELEASEIDENTIFIERLOOSE] + ')*))'\n\n// ## Build Metadata Identifier\n// Any combination of digits, letters, or hyphens.\n\ntok('BUILDIDENTIFIER')\nsrc[t.BUILDIDENTIFIER] = '[0-9A-Za-z-]+'\n\n// ## Build Metadata\n// Plus sign, followed by one or more period-separated build metadata\n// identifiers.\n\ntok('BUILD')\nsrc[t.BUILD] = '(?:\\\\+(' + src[t.BUILDIDENTIFIER] +\n '(?:\\\\.' + src[t.BUILDIDENTIFIER] + ')*))'\n\n// ## Full Version String\n// A main version, followed optionally by a pre-release version and\n// build metadata.\n\n// Note that the only major, minor, patch, and pre-release sections of\n// the version string are capturing groups. The build metadata is not a\n// capturing group, because it should not ever be used in version\n// comparison.\n\ntok('FULL')\ntok('FULLPLAIN')\nsrc[t.FULLPLAIN] = 'v?' + src[t.MAINVERSION] +\n src[t.PRERELEASE] + '?' +\n src[t.BUILD] + '?'\n\nsrc[t.FULL] = '^' + src[t.FULLPLAIN] + '$'\n\n// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.\n// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty\n// common in the npm registry.\ntok('LOOSEPLAIN')\nsrc[t.LOOSEPLAIN] = '[v=\\\\s]*' + src[t.MAINVERSIONLOOSE] +\n src[t.PRERELEASELOOSE] + '?' +\n src[t.BUILD] + '?'\n\ntok('LOOSE')\nsrc[t.LOOSE] = '^' + src[t.LOOSEPLAIN] + '$'\n\ntok('GTLT')\nsrc[t.GTLT] = '((?:<|>)?=?)'\n\n// Something like \"2.*\" or \"1.2.x\".\n// Note that \"x.x\" is a valid xRange identifer, meaning \"any version\"\n// Only the first item is strictly required.\ntok('XRANGEIDENTIFIERLOOSE')\nsrc[t.XRANGEIDENTIFIERLOOSE] = src[t.NUMERICIDENTIFIERLOOSE] + '|x|X|\\\\*'\ntok('XRANGEIDENTIFIER')\nsrc[t.XRANGEIDENTIFIER] = src[t.NUMERICIDENTIFIER] + '|x|X|\\\\*'\n\ntok('XRANGEPLAIN')\nsrc[t.XRANGEPLAIN] = '[v=\\\\s]*(' + src[t.XRANGEIDENTIFIER] + ')' +\n '(?:\\\\.(' + src[t.XRANGEIDENTIFIER] + ')' +\n '(?:\\\\.(' + src[t.XRANGEIDENTIFIER] + ')' +\n '(?:' + src[t.PRERELEASE] + ')?' +\n src[t.BUILD] + '?' +\n ')?)?'\n\ntok('XRANGEPLAINLOOSE')\nsrc[t.XRANGEPLAINLOOSE] = '[v=\\\\s]*(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' +\n '(?:\\\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' +\n '(?:\\\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' +\n '(?:' + src[t.PRERELEASELOOSE] + ')?' +\n src[t.BUILD] + '?' +\n ')?)?'\n\ntok('XRANGE')\nsrc[t.XRANGE] = '^' + src[t.GTLT] + '\\\\s*' + src[t.XRANGEPLAIN] + '$'\ntok('XRANGELOOSE')\nsrc[t.XRANGELOOSE] = '^' + src[t.GTLT] + '\\\\s*' + src[t.XRANGEPLAINLOOSE] + '$'\n\n// Coercion.\n// Extract anything that could conceivably be a part of a valid semver\ntok('COERCE')\nsrc[t.COERCE] = '(^|[^\\\\d])' +\n '(\\\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' +\n '(?:\\\\.(\\\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' +\n '(?:\\\\.(\\\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' +\n '(?:$|[^\\\\d])'\ntok('COERCERTL')\nre[t.COERCERTL] = new RegExp(src[t.COERCE], 'g')\n\n// Tilde ranges.\n// Meaning is \"reasonably at or greater than\"\ntok('LONETILDE')\nsrc[t.LONETILDE] = '(?:~>?)'\n\ntok('TILDETRIM')\nsrc[t.TILDETRIM] = '(\\\\s*)' + src[t.LONETILDE] + '\\\\s+'\nre[t.TILDETRIM] = new RegExp(src[t.TILDETRIM], 'g')\nvar tildeTrimReplace = '$1~'\n\ntok('TILDE')\nsrc[t.TILDE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAIN] + '$'\ntok('TILDELOOSE')\nsrc[t.TILDELOOSE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAINLOOSE] + '$'\n\n// Caret ranges.\n// Meaning is \"at least and backwards compatible with\"\ntok('LONECARET')\nsrc[t.LONECARET] = '(?:\\\\^)'\n\ntok('CARETTRIM')\nsrc[t.CARETTRIM] = '(\\\\s*)' + src[t.LONECARET] + '\\\\s+'\nre[t.CARETTRIM] = new RegExp(src[t.CARETTRIM], 'g')\nvar caretTrimReplace = '$1^'\n\ntok('CARET')\nsrc[t.CARET] = '^' + src[t.LONECARET] + src[t.XRANGEPLAIN] + '$'\ntok('CARETLOOSE')\nsrc[t.CARETLOOSE] = '^' + src[t.LONECARET] + src[t.XRANGEPLAINLOOSE] + '$'\n\n// A simple gt/lt/eq thing, or just \"\" to indicate \"any version\"\ntok('COMPARATORLOOSE')\nsrc[t.COMPARATORLOOSE] = '^' + src[t.GTLT] + '\\\\s*(' + src[t.LOOSEPLAIN] + ')$|^$'\ntok('COMPARATOR')\nsrc[t.COMPARATOR] = '^' + src[t.GTLT] + '\\\\s*(' + src[t.FULLPLAIN] + ')$|^$'\n\n// An expression to strip any whitespace between the gtlt and the thing\n// it modifies, so that `> 1.2.3` ==> `>1.2.3`\ntok('COMPARATORTRIM')\nsrc[t.COMPARATORTRIM] = '(\\\\s*)' + src[t.GTLT] +\n '\\\\s*(' + src[t.LOOSEPLAIN] + '|' + src[t.XRANGEPLAIN] + ')'\n\n// this one has to use the /g flag\nre[t.COMPARATORTRIM] = new RegExp(src[t.COMPARATORTRIM], 'g')\nvar comparatorTrimReplace = '$1$2$3'\n\n// Something like `1.2.3 - 1.2.4`\n// Note that these all use the loose form, because they'll be\n// checked against either the strict or loose comparator form\n// later.\ntok('HYPHENRANGE')\nsrc[t.HYPHENRANGE] = '^\\\\s*(' + src[t.XRANGEPLAIN] + ')' +\n '\\\\s+-\\\\s+' +\n '(' + src[t.XRANGEPLAIN] + ')' +\n '\\\\s*$'\n\ntok('HYPHENRANGELOOSE')\nsrc[t.HYPHENRANGELOOSE] = '^\\\\s*(' + src[t.XRANGEPLAINLOOSE] + ')' +\n '\\\\s+-\\\\s+' +\n '(' + src[t.XRANGEPLAINLOOSE] + ')' +\n '\\\\s*$'\n\n// Star ranges basically just allow anything at all.\ntok('STAR')\nsrc[t.STAR] = '(<|>)?=?\\\\s*\\\\*'\n\n// Compile to actual regexp objects.\n// All are flag-free, unless they were created above with a flag.\nfor (var i = 0; i < R; i++) {\n debug(i, src[i])\n if (!re[i]) {\n re[i] = new RegExp(src[i])\n }\n}\n\nexports.parse = parse\nfunction parse (version, options) {\n if (!options || typeof options !== 'object') {\n options = {\n loose: !!options,\n includePrerelease: false\n }\n }\n\n if (version instanceof SemVer) {\n return version\n }\n\n if (typeof version !== 'string') {\n return null\n }\n\n if (version.length > MAX_LENGTH) {\n return null\n }\n\n var r = options.loose ? re[t.LOOSE] : re[t.FULL]\n if (!r.test(version)) {\n return null\n }\n\n try {\n return new SemVer(version, options)\n } catch (er) {\n return null\n }\n}\n\nexports.valid = valid\nfunction valid (version, options) {\n var v = parse(version, options)\n return v ? v.version : null\n}\n\nexports.clean = clean\nfunction clean (version, options) {\n var s = parse(version.trim().replace(/^[=v]+/, ''), options)\n return s ? s.version : null\n}\n\nexports.SemVer = SemVer\n\nfunction SemVer (version, options) {\n if (!options || typeof options !== 'object') {\n options = {\n loose: !!options,\n includePrerelease: false\n }\n }\n if (version instanceof SemVer) {\n if (version.loose === options.loose) {\n return version\n } else {\n version = version.version\n }\n } else if (typeof version !== 'string') {\n throw new TypeError('Invalid Version: ' + version)\n }\n\n if (version.length > MAX_LENGTH) {\n throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters')\n }\n\n if (!(this instanceof SemVer)) {\n return new SemVer(version, options)\n }\n\n debug('SemVer', version, options)\n this.options = options\n this.loose = !!options.loose\n\n var m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])\n\n if (!m) {\n throw new TypeError('Invalid Version: ' + version)\n }\n\n this.raw = version\n\n // these are actually numbers\n this.major = +m[1]\n this.minor = +m[2]\n this.patch = +m[3]\n\n if (this.major > MAX_SAFE_INTEGER || this.major < 0) {\n throw new TypeError('Invalid major version')\n }\n\n if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {\n throw new TypeError('Invalid minor version')\n }\n\n if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {\n throw new TypeError('Invalid patch version')\n }\n\n // numberify any prerelease numeric ids\n if (!m[4]) {\n this.prerelease = []\n } else {\n this.prerelease = m[4].split('.').map(function (id) {\n if (/^[0-9]+$/.test(id)) {\n var num = +id\n if (num >= 0 && num < MAX_SAFE_INTEGER) {\n return num\n }\n }\n return id\n })\n }\n\n this.build = m[5] ? m[5].split('.') : []\n this.format()\n}\n\nSemVer.prototype.format = function () {\n this.version = this.major + '.' + this.minor + '.' + this.patch\n if (this.prerelease.length) {\n this.version += '-' + this.prerelease.join('.')\n }\n return this.version\n}\n\nSemVer.prototype.toString = function () {\n return this.version\n}\n\nSemVer.prototype.compare = function (other) {\n debug('SemVer.compare', this.version, this.options, other)\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n return this.compareMain(other) || this.comparePre(other)\n}\n\nSemVer.prototype.compareMain = function (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n return compareIdentifiers(this.major, other.major) ||\n compareIdentifiers(this.minor, other.minor) ||\n compareIdentifiers(this.patch, other.patch)\n}\n\nSemVer.prototype.comparePre = function (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n // NOT having a prerelease is > having one\n if (this.prerelease.length && !other.prerelease.length) {\n return -1\n } else if (!this.prerelease.length && other.prerelease.length) {\n return 1\n } else if (!this.prerelease.length && !other.prerelease.length) {\n return 0\n }\n\n var i = 0\n do {\n var a = this.prerelease[i]\n var b = other.prerelease[i]\n debug('prerelease compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n}\n\nSemVer.prototype.compareBuild = function (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n var i = 0\n do {\n var a = this.build[i]\n var b = other.build[i]\n debug('prerelease compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n}\n\n// preminor will bump the version up to the next minor release, and immediately\n// down to pre-release. premajor and prepatch work the same way.\nSemVer.prototype.inc = function (release, identifier) {\n switch (release) {\n case 'premajor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor = 0\n this.major++\n this.inc('pre', identifier)\n break\n case 'preminor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor++\n this.inc('pre', identifier)\n break\n case 'prepatch':\n // If this is already a prerelease, it will bump to the next version\n // drop any prereleases that might already exist, since they are not\n // relevant at this point.\n this.prerelease.length = 0\n this.inc('patch', identifier)\n this.inc('pre', identifier)\n break\n // If the input is a non-prerelease version, this acts the same as\n // prepatch.\n case 'prerelease':\n if (this.prerelease.length === 0) {\n this.inc('patch', identifier)\n }\n this.inc('pre', identifier)\n break\n\n case 'major':\n // If this is a pre-major version, bump up to the same major version.\n // Otherwise increment major.\n // 1.0.0-5 bumps to 1.0.0\n // 1.1.0 bumps to 2.0.0\n if (this.minor !== 0 ||\n this.patch !== 0 ||\n this.prerelease.length === 0) {\n this.major++\n }\n this.minor = 0\n this.patch = 0\n this.prerelease = []\n break\n case 'minor':\n // If this is a pre-minor version, bump up to the same minor version.\n // Otherwise increment minor.\n // 1.2.0-5 bumps to 1.2.0\n // 1.2.1 bumps to 1.3.0\n if (this.patch !== 0 || this.prerelease.length === 0) {\n this.minor++\n }\n this.patch = 0\n this.prerelease = []\n break\n case 'patch':\n // If this is not a pre-release version, it will increment the patch.\n // If it is a pre-release it will bump up to the same patch version.\n // 1.2.0-5 patches to 1.2.0\n // 1.2.0 patches to 1.2.1\n if (this.prerelease.length === 0) {\n this.patch++\n }\n this.prerelease = []\n break\n // This probably shouldn't be used publicly.\n // 1.0.0 \"pre\" would become 1.0.0-0 which is the wrong direction.\n case 'pre':\n if (this.prerelease.length === 0) {\n this.prerelease = [0]\n } else {\n var i = this.prerelease.length\n while (--i >= 0) {\n if (typeof this.prerelease[i] === 'number') {\n this.prerelease[i]++\n i = -2\n }\n }\n if (i === -1) {\n // didn't increment anything\n this.prerelease.push(0)\n }\n }\n if (identifier) {\n // 1.2.0-beta.1 bumps to 1.2.0-beta.2,\n // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0\n if (this.prerelease[0] === identifier) {\n if (isNaN(this.prerelease[1])) {\n this.prerelease = [identifier, 0]\n }\n } else {\n this.prerelease = [identifier, 0]\n }\n }\n break\n\n default:\n throw new Error('invalid increment argument: ' + release)\n }\n this.format()\n this.raw = this.version\n return this\n}\n\nexports.inc = inc\nfunction inc (version, release, loose, identifier) {\n if (typeof (loose) === 'string') {\n identifier = loose\n loose = undefined\n }\n\n try {\n return new SemVer(version, loose).inc(release, identifier).version\n } catch (er) {\n return null\n }\n}\n\nexports.diff = diff\nfunction diff (version1, version2) {\n if (eq(version1, version2)) {\n return null\n } else {\n var v1 = parse(version1)\n var v2 = parse(version2)\n var prefix = ''\n if (v1.prerelease.length || v2.prerelease.length) {\n prefix = 'pre'\n var defaultResult = 'prerelease'\n }\n for (var key in v1) {\n if (key === 'major' || key === 'minor' || key === 'patch') {\n if (v1[key] !== v2[key]) {\n return prefix + key\n }\n }\n }\n return defaultResult // may be undefined\n }\n}\n\nexports.compareIdentifiers = compareIdentifiers\n\nvar numeric = /^[0-9]+$/\nfunction compareIdentifiers (a, b) {\n var anum = numeric.test(a)\n var bnum = numeric.test(b)\n\n if (anum && bnum) {\n a = +a\n b = +b\n }\n\n return a === b ? 0\n : (anum && !bnum) ? -1\n : (bnum && !anum) ? 1\n : a < b ? -1\n : 1\n}\n\nexports.rcompareIdentifiers = rcompareIdentifiers\nfunction rcompareIdentifiers (a, b) {\n return compareIdentifiers(b, a)\n}\n\nexports.major = major\nfunction major (a, loose) {\n return new SemVer(a, loose).major\n}\n\nexports.minor = minor\nfunction minor (a, loose) {\n return new SemVer(a, loose).minor\n}\n\nexports.patch = patch\nfunction patch (a, loose) {\n return new SemVer(a, loose).patch\n}\n\nexports.compare = compare\nfunction compare (a, b, loose) {\n return new SemVer(a, loose).compare(new SemVer(b, loose))\n}\n\nexports.compareLoose = compareLoose\nfunction compareLoose (a, b) {\n return compare(a, b, true)\n}\n\nexports.compareBuild = compareBuild\nfunction compareBuild (a, b, loose) {\n var versionA = new SemVer(a, loose)\n var versionB = new SemVer(b, loose)\n return versionA.compare(versionB) || versionA.compareBuild(versionB)\n}\n\nexports.rcompare = rcompare\nfunction rcompare (a, b, loose) {\n return compare(b, a, loose)\n}\n\nexports.sort = sort\nfunction sort (list, loose) {\n return list.sort(function (a, b) {\n return exports.compareBuild(a, b, loose)\n })\n}\n\nexports.rsort = rsort\nfunction rsort (list, loose) {\n return list.sort(function (a, b) {\n return exports.compareBuild(b, a, loose)\n })\n}\n\nexports.gt = gt\nfunction gt (a, b, loose) {\n return compare(a, b, loose) > 0\n}\n\nexports.lt = lt\nfunction lt (a, b, loose) {\n return compare(a, b, loose) < 0\n}\n\nexports.eq = eq\nfunction eq (a, b, loose) {\n return compare(a, b, loose) === 0\n}\n\nexports.neq = neq\nfunction neq (a, b, loose) {\n return compare(a, b, loose) !== 0\n}\n\nexports.gte = gte\nfunction gte (a, b, loose) {\n return compare(a, b, loose) >= 0\n}\n\nexports.lte = lte\nfunction lte (a, b, loose) {\n return compare(a, b, loose) <= 0\n}\n\nexports.cmp = cmp\nfunction cmp (a, op, b, loose) {\n switch (op) {\n case '===':\n if (typeof a === 'object')\n a = a.version\n if (typeof b === 'object')\n b = b.version\n return a === b\n\n case '!==':\n if (typeof a === 'object')\n a = a.version\n if (typeof b === 'object')\n b = b.version\n return a !== b\n\n case '':\n case '=':\n case '==':\n return eq(a, b, loose)\n\n case '!=':\n return neq(a, b, loose)\n\n case '>':\n return gt(a, b, loose)\n\n case '>=':\n return gte(a, b, loose)\n\n case '<':\n return lt(a, b, loose)\n\n case '<=':\n return lte(a, b, loose)\n\n default:\n throw new TypeError('Invalid operator: ' + op)\n }\n}\n\nexports.Comparator = Comparator\nfunction Comparator (comp, options) {\n if (!options || typeof options !== 'object') {\n options = {\n loose: !!options,\n includePrerelease: false\n }\n }\n\n if (comp instanceof Comparator) {\n if (comp.loose === !!options.loose) {\n return comp\n } else {\n comp = comp.value\n }\n }\n\n if (!(this instanceof Comparator)) {\n return new Comparator(comp, options)\n }\n\n debug('comparator', comp, options)\n this.options = options\n this.loose = !!options.loose\n this.parse(comp)\n\n if (this.semver === ANY) {\n this.value = ''\n } else {\n this.value = this.operator + this.semver.version\n }\n\n debug('comp', this)\n}\n\nvar ANY = {}\nComparator.prototype.parse = function (comp) {\n var r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]\n var m = comp.match(r)\n\n if (!m) {\n throw new TypeError('Invalid comparator: ' + comp)\n }\n\n this.operator = m[1] !== undefined ? m[1] : ''\n if (this.operator === '=') {\n this.operator = ''\n }\n\n // if it literally is just '>' or '' then allow anything.\n if (!m[2]) {\n this.semver = ANY\n } else {\n this.semver = new SemVer(m[2], this.options.loose)\n }\n}\n\nComparator.prototype.toString = function () {\n return this.value\n}\n\nComparator.prototype.test = function (version) {\n debug('Comparator.test', version, this.options.loose)\n\n if (this.semver === ANY || version === ANY) {\n return true\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n return cmp(version, this.operator, this.semver, this.options)\n}\n\nComparator.prototype.intersects = function (comp, options) {\n if (!(comp instanceof Comparator)) {\n throw new TypeError('a Comparator is required')\n }\n\n if (!options || typeof options !== 'object') {\n options = {\n loose: !!options,\n includePrerelease: false\n }\n }\n\n var rangeTmp\n\n if (this.operator === '') {\n if (this.value === '') {\n return true\n }\n rangeTmp = new Range(comp.value, options)\n return satisfies(this.value, rangeTmp, options)\n } else if (comp.operator === '') {\n if (comp.value === '') {\n return true\n }\n rangeTmp = new Range(this.value, options)\n return satisfies(comp.semver, rangeTmp, options)\n }\n\n var sameDirectionIncreasing =\n (this.operator === '>=' || this.operator === '>') &&\n (comp.operator === '>=' || comp.operator === '>')\n var sameDirectionDecreasing =\n (this.operator === '<=' || this.operator === '<') &&\n (comp.operator === '<=' || comp.operator === '<')\n var sameSemVer = this.semver.version === comp.semver.version\n var differentDirectionsInclusive =\n (this.operator === '>=' || this.operator === '<=') &&\n (comp.operator === '>=' || comp.operator === '<=')\n var oppositeDirectionsLessThan =\n cmp(this.semver, '<', comp.semver, options) &&\n ((this.operator === '>=' || this.operator === '>') &&\n (comp.operator === '<=' || comp.operator === '<'))\n var oppositeDirectionsGreaterThan =\n cmp(this.semver, '>', comp.semver, options) &&\n ((this.operator === '<=' || this.operator === '<') &&\n (comp.operator === '>=' || comp.operator === '>'))\n\n return sameDirectionIncreasing || sameDirectionDecreasing ||\n (sameSemVer && differentDirectionsInclusive) ||\n oppositeDirectionsLessThan || oppositeDirectionsGreaterThan\n}\n\nexports.Range = Range\nfunction Range (range, options) {\n if (!options || typeof options !== 'object') {\n options = {\n loose: !!options,\n includePrerelease: false\n }\n }\n\n if (range instanceof Range) {\n if (range.loose === !!options.loose &&\n range.includePrerelease === !!options.includePrerelease) {\n return range\n } else {\n return new Range(range.raw, options)\n }\n }\n\n if (range instanceof Comparator) {\n return new Range(range.value, options)\n }\n\n if (!(this instanceof Range)) {\n return new Range(range, options)\n }\n\n this.options = options\n this.loose = !!options.loose\n this.includePrerelease = !!options.includePrerelease\n\n // First, split based on boolean or ||\n this.raw = range\n this.set = range.split(/\\s*\\|\\|\\s*/).map(function (range) {\n return this.parseRange(range.trim())\n }, this).filter(function (c) {\n // throw out any that are not relevant for whatever reason\n return c.length\n })\n\n if (!this.set.length) {\n throw new TypeError('Invalid SemVer Range: ' + range)\n }\n\n this.format()\n}\n\nRange.prototype.format = function () {\n this.range = this.set.map(function (comps) {\n return comps.join(' ').trim()\n }).join('||').trim()\n return this.range\n}\n\nRange.prototype.toString = function () {\n return this.range\n}\n\nRange.prototype.parseRange = function (range) {\n var loose = this.options.loose\n range = range.trim()\n // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`\n var hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]\n range = range.replace(hr, hyphenReplace)\n debug('hyphen replace', range)\n // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`\n range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)\n debug('comparator trim', range, re[t.COMPARATORTRIM])\n\n // `~ 1.2.3` => `~1.2.3`\n range = range.replace(re[t.TILDETRIM], tildeTrimReplace)\n\n // `^ 1.2.3` => `^1.2.3`\n range = range.replace(re[t.CARETTRIM], caretTrimReplace)\n\n // normalize spaces\n range = range.split(/\\s+/).join(' ')\n\n // At this point, the range is completely trimmed and\n // ready to be split into comparators.\n\n var compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]\n var set = range.split(' ').map(function (comp) {\n return parseComparator(comp, this.options)\n }, this).join(' ').split(/\\s+/)\n if (this.options.loose) {\n // in loose mode, throw out any that are not valid comparators\n set = set.filter(function (comp) {\n return !!comp.match(compRe)\n })\n }\n set = set.map(function (comp) {\n return new Comparator(comp, this.options)\n }, this)\n\n return set\n}\n\nRange.prototype.intersects = function (range, options) {\n if (!(range instanceof Range)) {\n throw new TypeError('a Range is required')\n }\n\n return this.set.some(function (thisComparators) {\n return (\n isSatisfiable(thisComparators, options) &&\n range.set.some(function (rangeComparators) {\n return (\n isSatisfiable(rangeComparators, options) &&\n thisComparators.every(function (thisComparator) {\n return rangeComparators.every(function (rangeComparator) {\n return thisComparator.intersects(rangeComparator, options)\n })\n })\n )\n })\n )\n })\n}\n\n// take a set of comparators and determine whether there\n// exists a version which can satisfy it\nfunction isSatisfiable (comparators, options) {\n var result = true\n var remainingComparators = comparators.slice()\n var testComparator = remainingComparators.pop()\n\n while (result && remainingComparators.length) {\n result = remainingComparators.every(function (otherComparator) {\n return testComparator.intersects(otherComparator, options)\n })\n\n testComparator = remainingComparators.pop()\n }\n\n return result\n}\n\n// Mostly just for testing and legacy API reasons\nexports.toComparators = toComparators\nfunction toComparators (range, options) {\n return new Range(range, options).set.map(function (comp) {\n return comp.map(function (c) {\n return c.value\n }).join(' ').trim().split(' ')\n })\n}\n\n// comprised of xranges, tildes, stars, and gtlt's at this point.\n// already replaced the hyphen ranges\n// turn into a set of JUST comparators.\nfunction parseComparator (comp, options) {\n debug('comp', comp, options)\n comp = replaceCarets(comp, options)\n debug('caret', comp)\n comp = replaceTildes(comp, options)\n debug('tildes', comp)\n comp = replaceXRanges(comp, options)\n debug('xrange', comp)\n comp = replaceStars(comp, options)\n debug('stars', comp)\n return comp\n}\n\nfunction isX (id) {\n return !id || id.toLowerCase() === 'x' || id === '*'\n}\n\n// ~, ~> --> * (any, kinda silly)\n// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0\n// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0\n// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0\n// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0\n// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0\nfunction replaceTildes (comp, options) {\n return comp.trim().split(/\\s+/).map(function (comp) {\n return replaceTilde(comp, options)\n }).join(' ')\n}\n\nfunction replaceTilde (comp, options) {\n var r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]\n return comp.replace(r, function (_, M, m, p, pr) {\n debug('tilde', comp, _, M, m, p, pr)\n var ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'\n } else if (isX(p)) {\n // ~1.2 == >=1.2.0 <1.3.0\n ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'\n } else if (pr) {\n debug('replaceTilde pr', pr)\n ret = '>=' + M + '.' + m + '.' + p + '-' + pr +\n ' <' + M + '.' + (+m + 1) + '.0'\n } else {\n // ~1.2.3 == >=1.2.3 <1.3.0\n ret = '>=' + M + '.' + m + '.' + p +\n ' <' + M + '.' + (+m + 1) + '.0'\n }\n\n debug('tilde return', ret)\n return ret\n })\n}\n\n// ^ --> * (any, kinda silly)\n// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0\n// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0\n// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0\n// ^1.2.3 --> >=1.2.3 <2.0.0\n// ^1.2.0 --> >=1.2.0 <2.0.0\nfunction replaceCarets (comp, options) {\n return comp.trim().split(/\\s+/).map(function (comp) {\n return replaceCaret(comp, options)\n }).join(' ')\n}\n\nfunction replaceCaret (comp, options) {\n debug('caret', comp, options)\n var r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]\n return comp.replace(r, function (_, M, m, p, pr) {\n debug('caret', comp, _, M, m, p, pr)\n var ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'\n } else if (isX(p)) {\n if (M === '0') {\n ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'\n } else {\n ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0'\n }\n } else if (pr) {\n debug('replaceCaret pr', pr)\n if (M === '0') {\n if (m === '0') {\n ret = '>=' + M + '.' + m + '.' + p + '-' + pr +\n ' <' + M + '.' + m + '.' + (+p + 1)\n } else {\n ret = '>=' + M + '.' + m + '.' + p + '-' + pr +\n ' <' + M + '.' + (+m + 1) + '.0'\n }\n } else {\n ret = '>=' + M + '.' + m + '.' + p + '-' + pr +\n ' <' + (+M + 1) + '.0.0'\n }\n } else {\n debug('no pr')\n if (M === '0') {\n if (m === '0') {\n ret = '>=' + M + '.' + m + '.' + p +\n ' <' + M + '.' + m + '.' + (+p + 1)\n } else {\n ret = '>=' + M + '.' + m + '.' + p +\n ' <' + M + '.' + (+m + 1) + '.0'\n }\n } else {\n ret = '>=' + M + '.' + m + '.' + p +\n ' <' + (+M + 1) + '.0.0'\n }\n }\n\n debug('caret return', ret)\n return ret\n })\n}\n\nfunction replaceXRanges (comp, options) {\n debug('replaceXRanges', comp, options)\n return comp.split(/\\s+/).map(function (comp) {\n return replaceXRange(comp, options)\n }).join(' ')\n}\n\nfunction replaceXRange (comp, options) {\n comp = comp.trim()\n var r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]\n return comp.replace(r, function (ret, gtlt, M, m, p, pr) {\n debug('xRange', comp, ret, gtlt, M, m, p, pr)\n var xM = isX(M)\n var xm = xM || isX(m)\n var xp = xm || isX(p)\n var anyX = xp\n\n if (gtlt === '=' && anyX) {\n gtlt = ''\n }\n\n // if we're including prereleases in the match, then we need\n // to fix this to -0, the lowest possible prerelease value\n pr = options.includePrerelease ? '-0' : ''\n\n if (xM) {\n if (gtlt === '>' || gtlt === '<') {\n // nothing is allowed\n ret = '<0.0.0-0'\n } else {\n // nothing is forbidden\n ret = '*'\n }\n } else if (gtlt && anyX) {\n // we know patch is an x, because we have any x at all.\n // replace X with 0\n if (xm) {\n m = 0\n }\n p = 0\n\n if (gtlt === '>') {\n // >1 => >=2.0.0\n // >1.2 => >=1.3.0\n // >1.2.3 => >= 1.2.4\n gtlt = '>='\n if (xm) {\n M = +M + 1\n m = 0\n p = 0\n } else {\n m = +m + 1\n p = 0\n }\n } else if (gtlt === '<=') {\n // <=0.7.x is actually <0.8.0, since any 0.7.x should\n // pass. Similarly, <=7.x is actually <8.0.0, etc.\n gtlt = '<'\n if (xm) {\n M = +M + 1\n } else {\n m = +m + 1\n }\n }\n\n ret = gtlt + M + '.' + m + '.' + p + pr\n } else if (xm) {\n ret = '>=' + M + '.0.0' + pr + ' <' + (+M + 1) + '.0.0' + pr\n } else if (xp) {\n ret = '>=' + M + '.' + m + '.0' + pr +\n ' <' + M + '.' + (+m + 1) + '.0' + pr\n }\n\n debug('xRange return', ret)\n\n return ret\n })\n}\n\n// Because * is AND-ed with everything else in the comparator,\n// and '' means \"any version\", just remove the *s entirely.\nfunction replaceStars (comp, options) {\n debug('replaceStars', comp, options)\n // Looseness is ignored here. star is always as loose as it gets!\n return comp.trim().replace(re[t.STAR], '')\n}\n\n// This function is passed to string.replace(re[t.HYPHENRANGE])\n// M, m, patch, prerelease, build\n// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5\n// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do\n// 1.2 - 3.4 => >=1.2.0 <3.5.0\nfunction hyphenReplace ($0,\n from, fM, fm, fp, fpr, fb,\n to, tM, tm, tp, tpr, tb) {\n if (isX(fM)) {\n from = ''\n } else if (isX(fm)) {\n from = '>=' + fM + '.0.0'\n } else if (isX(fp)) {\n from = '>=' + fM + '.' + fm + '.0'\n } else {\n from = '>=' + from\n }\n\n if (isX(tM)) {\n to = ''\n } else if (isX(tm)) {\n to = '<' + (+tM + 1) + '.0.0'\n } else if (isX(tp)) {\n to = '<' + tM + '.' + (+tm + 1) + '.0'\n } else if (tpr) {\n to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr\n } else {\n to = '<=' + to\n }\n\n return (from + ' ' + to).trim()\n}\n\n// if ANY of the sets match ALL of its comparators, then pass\nRange.prototype.test = function (version) {\n if (!version) {\n return false\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n for (var i = 0; i < this.set.length; i++) {\n if (testSet(this.set[i], version, this.options)) {\n return true\n }\n }\n return false\n}\n\nfunction testSet (set, version, options) {\n for (var i = 0; i < set.length; i++) {\n if (!set[i].test(version)) {\n return false\n }\n }\n\n if (version.prerelease.length && !options.includePrerelease) {\n // Find the set of versions that are allowed to have prereleases\n // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0\n // That should allow `1.2.3-pr.2` to pass.\n // However, `1.2.4-alpha.notready` should NOT be allowed,\n // even though it's within the range set by the comparators.\n for (i = 0; i < set.length; i++) {\n debug(set[i].semver)\n if (set[i].semver === ANY) {\n continue\n }\n\n if (set[i].semver.prerelease.length > 0) {\n var allowed = set[i].semver\n if (allowed.major === version.major &&\n allowed.minor === version.minor &&\n allowed.patch === version.patch) {\n return true\n }\n }\n }\n\n // Version has a -pre, but it's not one of the ones we like.\n return false\n }\n\n return true\n}\n\nexports.satisfies = satisfies\nfunction satisfies (version, range, options) {\n try {\n range = new Range(range, options)\n } catch (er) {\n return false\n }\n return range.test(version)\n}\n\nexports.maxSatisfying = maxSatisfying\nfunction maxSatisfying (versions, range, options) {\n var max = null\n var maxSV = null\n try {\n var rangeObj = new Range(range, options)\n } catch (er) {\n return null\n }\n versions.forEach(function (v) {\n if (rangeObj.test(v)) {\n // satisfies(v, range, options)\n if (!max || maxSV.compare(v) === -1) {\n // compare(max, v, true)\n max = v\n maxSV = new SemVer(max, options)\n }\n }\n })\n return max\n}\n\nexports.minSatisfying = minSatisfying\nfunction minSatisfying (versions, range, options) {\n var min = null\n var minSV = null\n try {\n var rangeObj = new Range(range, options)\n } catch (er) {\n return null\n }\n versions.forEach(function (v) {\n if (rangeObj.test(v)) {\n // satisfies(v, range, options)\n if (!min || minSV.compare(v) === 1) {\n // compare(min, v, true)\n min = v\n minSV = new SemVer(min, options)\n }\n }\n })\n return min\n}\n\nexports.minVersion = minVersion\nfunction minVersion (range, loose) {\n range = new Range(range, loose)\n\n var minver = new SemVer('0.0.0')\n if (range.test(minver)) {\n return minver\n }\n\n minver = new SemVer('0.0.0-0')\n if (range.test(minver)) {\n return minver\n }\n\n minver = null\n for (var i = 0; i < range.set.length; ++i) {\n var comparators = range.set[i]\n\n comparators.forEach(function (comparator) {\n // Clone to avoid manipulating the comparator's semver object.\n var compver = new SemVer(comparator.semver.version)\n switch (comparator.operator) {\n case '>':\n if (compver.prerelease.length === 0) {\n compver.patch++\n } else {\n compver.prerelease.push(0)\n }\n compver.raw = compver.format()\n /* fallthrough */\n case '':\n case '>=':\n if (!minver || gt(minver, compver)) {\n minver = compver\n }\n break\n case '<':\n case '<=':\n /* Ignore maximum versions */\n break\n /* istanbul ignore next */\n default:\n throw new Error('Unexpected operation: ' + comparator.operator)\n }\n })\n }\n\n if (minver && range.test(minver)) {\n return minver\n }\n\n return null\n}\n\nexports.validRange = validRange\nfunction validRange (range, options) {\n try {\n // Return '*' instead of '' so that truthiness works.\n // This will throw if it's invalid anyway\n return new Range(range, options).range || '*'\n } catch (er) {\n return null\n }\n}\n\n// Determine if version is less than all the versions possible in the range\nexports.ltr = ltr\nfunction ltr (version, range, options) {\n return outside(version, range, '<', options)\n}\n\n// Determine if version is greater than all the versions possible in the range.\nexports.gtr = gtr\nfunction gtr (version, range, options) {\n return outside(version, range, '>', options)\n}\n\nexports.outside = outside\nfunction outside (version, range, hilo, options) {\n version = new SemVer(version, options)\n range = new Range(range, options)\n\n var gtfn, ltefn, ltfn, comp, ecomp\n switch (hilo) {\n case '>':\n gtfn = gt\n ltefn = lte\n ltfn = lt\n comp = '>'\n ecomp = '>='\n break\n case '<':\n gtfn = lt\n ltefn = gte\n ltfn = gt\n comp = '<'\n ecomp = '<='\n break\n default:\n throw new TypeError('Must provide a hilo val of \"<\" or \">\"')\n }\n\n // If it satisifes the range it is not outside\n if (satisfies(version, range, options)) {\n return false\n }\n\n // From now on, variable terms are as if we're in \"gtr\" mode.\n // but note that everything is flipped for the \"ltr\" function.\n\n for (var i = 0; i < range.set.length; ++i) {\n var comparators = range.set[i]\n\n var high = null\n var low = null\n\n comparators.forEach(function (comparator) {\n if (comparator.semver === ANY) {\n comparator = new Comparator('>=0.0.0')\n }\n high = high || comparator\n low = low || comparator\n if (gtfn(comparator.semver, high.semver, options)) {\n high = comparator\n } else if (ltfn(comparator.semver, low.semver, options)) {\n low = comparator\n }\n })\n\n // If the edge version comparator has a operator then our version\n // isn't outside it\n if (high.operator === comp || high.operator === ecomp) {\n return false\n }\n\n // If the lowest version comparator has an operator and our version\n // is less than it then it isn't higher than the range\n if ((!low.operator || low.operator === comp) &&\n ltefn(version, low.semver)) {\n return false\n } else if (low.operator === ecomp && ltfn(version, low.semver)) {\n return false\n }\n }\n return true\n}\n\nexports.prerelease = prerelease\nfunction prerelease (version, options) {\n var parsed = parse(version, options)\n return (parsed && parsed.prerelease.length) ? parsed.prerelease : null\n}\n\nexports.intersects = intersects\nfunction intersects (r1, r2, options) {\n r1 = new Range(r1, options)\n r2 = new Range(r2, options)\n return r1.intersects(r2)\n}\n\nexports.coerce = coerce\nfunction coerce (version, options) {\n if (version instanceof SemVer) {\n return version\n }\n\n if (typeof version === 'number') {\n version = String(version)\n }\n\n if (typeof version !== 'string') {\n return null\n }\n\n options = options || {}\n\n var match = null\n if (!options.rtl) {\n match = version.match(re[t.COERCE])\n } else {\n // Find the right-most coercible string that does not share\n // a terminus with a more left-ward coercible string.\n // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'\n //\n // Walk through the string checking with a /g regexp\n // Manually set the index so as to pick up overlapping matches.\n // Stop when we get a match that ends at the string end, since no\n // coercible string can be more right-ward without the same terminus.\n var next\n while ((next = re[t.COERCERTL].exec(version)) &&\n (!match || match.index + match[0].length !== version.length)\n ) {\n if (!match ||\n next.index + next[0].length !== match.index + match[0].length) {\n match = next\n }\n re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length\n }\n // leave it in a clean state\n re[t.COERCERTL].lastIndex = -1\n }\n\n if (match === null) {\n return null\n }\n\n return parse(match[2] +\n '.' + (match[3] || '0') +\n '.' + (match[4] || '0'), options)\n}\n","require('./').install();\n","var SourceMapConsumer = require('source-map').SourceMapConsumer;\nvar path = require('path');\n\nvar fs;\ntry {\n fs = require('fs');\n if (!fs.existsSync || !fs.readFileSync) {\n // fs doesn't have all methods we need\n fs = null;\n }\n} catch (err) {\n /* nop */\n}\n\n// Only install once if called multiple times\nvar errorFormatterInstalled = false;\nvar uncaughtShimInstalled = false;\n\n// If true, the caches are reset before a stack trace formatting operation\nvar emptyCacheBetweenOperations = false;\n\n// Supports {browser, node, auto}\nvar environment = \"auto\";\n\n// Maps a file path to a string containing the file contents\nvar fileContentsCache = {};\n\n// Maps a file path to a source map for that file\nvar sourceMapCache = {};\n\n// Regex for detecting source maps\nvar reSourceMap = /^data:application\\/json[^,]+base64,/;\n\n// Priority list of retrieve handlers\nvar retrieveFileHandlers = [];\nvar retrieveMapHandlers = [];\n\nfunction isInBrowser() {\n if (environment === \"browser\")\n return true;\n if (environment === \"node\")\n return false;\n return ((typeof window !== 'undefined') && (typeof XMLHttpRequest === 'function') && !(window.require && window.module && window.process && window.process.type === \"renderer\"));\n}\n\nfunction hasGlobalProcessEventEmitter() {\n return ((typeof process === 'object') && (process !== null) && (typeof process.on === 'function'));\n}\n\nfunction handlerExec(list) {\n return function(arg) {\n for (var i = 0; i < list.length; i++) {\n var ret = list[i](arg);\n if (ret) {\n return ret;\n }\n }\n return null;\n };\n}\n\nvar retrieveFile = handlerExec(retrieveFileHandlers);\n\nretrieveFileHandlers.push(function(path) {\n // Trim the path to make sure there is no extra whitespace.\n path = path.trim();\n if (path in fileContentsCache) {\n return fileContentsCache[path];\n }\n\n var contents = null;\n if (!fs) {\n // Use SJAX if we are in the browser\n var xhr = new XMLHttpRequest();\n xhr.open('GET', path, false);\n xhr.send(null);\n var contents = null\n if (xhr.readyState === 4 && xhr.status === 200) {\n contents = xhr.responseText\n }\n } else if (fs.existsSync(path)) {\n // Otherwise, use the filesystem\n try {\n contents = fs.readFileSync(path, 'utf8');\n } catch (er) {\n contents = '';\n }\n }\n\n return fileContentsCache[path] = contents;\n});\n\n// Support URLs relative to a directory, but be careful about a protocol prefix\n// in case we are in the browser (i.e. directories may start with \"http://\")\nfunction supportRelativeURL(file, url) {\n if (!file) return url;\n var dir = path.dirname(file);\n var match = /^\\w+:\\/\\/[^\\/]*/.exec(dir);\n var protocol = match ? match[0] : '';\n return protocol + path.resolve(dir.slice(protocol.length), url);\n}\n\nfunction retrieveSourceMapURL(source) {\n var fileData;\n\n if (isInBrowser()) {\n try {\n var xhr = new XMLHttpRequest();\n xhr.open('GET', source, false);\n xhr.send(null);\n fileData = xhr.readyState === 4 ? xhr.responseText : null;\n\n // Support providing a sourceMappingURL via the SourceMap header\n var sourceMapHeader = xhr.getResponseHeader(\"SourceMap\") ||\n xhr.getResponseHeader(\"X-SourceMap\");\n if (sourceMapHeader) {\n return sourceMapHeader;\n }\n } catch (e) {\n }\n }\n\n // Get the URL of the source map\n fileData = retrieveFile(source);\n var re = /(?:\\/\\/[@#][ \\t]+sourceMappingURL=([^\\s'\"]+?)[ \\t]*$)|(?:\\/\\*[@#][ \\t]+sourceMappingURL=([^\\*]+?)[ \\t]*(?:\\*\\/)[ \\t]*$)/mg;\n // Keep executing the search to find the *last* sourceMappingURL to avoid\n // picking up sourceMappingURLs from comments, strings, etc.\n var lastMatch, match;\n while (match = re.exec(fileData)) lastMatch = match;\n if (!lastMatch) return null;\n return lastMatch[1];\n};\n\n// Can be overridden by the retrieveSourceMap option to install. Takes a\n// generated source filename; returns a {map, optional url} object, or null if\n// there is no source map. The map field may be either a string or the parsed\n// JSON object (ie, it must be a valid argument to the SourceMapConsumer\n// constructor).\nvar retrieveSourceMap = handlerExec(retrieveMapHandlers);\nretrieveMapHandlers.push(function(source) {\n var sourceMappingURL = retrieveSourceMapURL(source);\n if (!sourceMappingURL) return null;\n\n // Read the contents of the source map\n var sourceMapData;\n if (reSourceMap.test(sourceMappingURL)) {\n // Support source map URL as a data url\n var rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(',') + 1);\n sourceMapData = new Buffer(rawData, \"base64\").toString();\n sourceMappingURL = source;\n } else {\n // Support source map URLs relative to the source URL\n sourceMappingURL = supportRelativeURL(source, sourceMappingURL);\n sourceMapData = retrieveFile(sourceMappingURL);\n }\n\n if (!sourceMapData) {\n return null;\n }\n\n return {\n url: sourceMappingURL,\n map: sourceMapData\n };\n});\n\nfunction mapSourcePosition(position) {\n var sourceMap = sourceMapCache[position.source];\n if (!sourceMap) {\n // Call the (overrideable) retrieveSourceMap function to get the source map.\n var urlAndMap = retrieveSourceMap(position.source);\n if (urlAndMap) {\n sourceMap = sourceMapCache[position.source] = {\n url: urlAndMap.url,\n map: new SourceMapConsumer(urlAndMap.map)\n };\n\n // Load all sources stored inline with the source map into the file cache\n // to pretend like they are already loaded. They may not exist on disk.\n if (sourceMap.map.sourcesContent) {\n sourceMap.map.sources.forEach(function(source, i) {\n var contents = sourceMap.map.sourcesContent[i];\n if (contents) {\n var url = supportRelativeURL(sourceMap.url, source);\n fileContentsCache[url] = contents;\n }\n });\n }\n } else {\n sourceMap = sourceMapCache[position.source] = {\n url: null,\n map: null\n };\n }\n }\n\n // Resolve the source URL relative to the URL of the source map\n if (sourceMap && sourceMap.map) {\n var originalPosition = sourceMap.map.originalPositionFor(position);\n\n // Only return the original position if a matching line was found. If no\n // matching line is found then we return position instead, which will cause\n // the stack trace to print the path and line for the compiled file. It is\n // better to give a precise location in the compiled file than a vague\n // location in the original file.\n if (originalPosition.source !== null) {\n originalPosition.source = supportRelativeURL(\n sourceMap.url, originalPosition.source);\n return originalPosition;\n }\n }\n\n return position;\n}\n\n// Parses code generated by FormatEvalOrigin(), a function inside V8:\n// https://code.google.com/p/v8/source/browse/trunk/src/messages.js\nfunction mapEvalOrigin(origin) {\n // Most eval() calls are in this format\n var match = /^eval at ([^(]+) \\((.+):(\\d+):(\\d+)\\)$/.exec(origin);\n if (match) {\n var position = mapSourcePosition({\n source: match[2],\n line: +match[3],\n column: match[4] - 1\n });\n return 'eval at ' + match[1] + ' (' + position.source + ':' +\n position.line + ':' + (position.column + 1) + ')';\n }\n\n // Parse nested eval() calls using recursion\n match = /^eval at ([^(]+) \\((.+)\\)$/.exec(origin);\n if (match) {\n return 'eval at ' + match[1] + ' (' + mapEvalOrigin(match[2]) + ')';\n }\n\n // Make sure we still return useful information if we didn't find anything\n return origin;\n}\n\n// This is copied almost verbatim from the V8 source code at\n// https://code.google.com/p/v8/source/browse/trunk/src/messages.js. The\n// implementation of wrapCallSite() used to just forward to the actual source\n// code of CallSite.prototype.toString but unfortunately a new release of V8\n// did something to the prototype chain and broke the shim. The only fix I\n// could find was copy/paste.\nfunction CallSiteToString() {\n var fileName;\n var fileLocation = \"\";\n if (this.isNative()) {\n fileLocation = \"native\";\n } else {\n fileName = this.getScriptNameOrSourceURL();\n if (!fileName && this.isEval()) {\n fileLocation = this.getEvalOrigin();\n fileLocation += \", \"; // Expecting source position to follow.\n }\n\n if (fileName) {\n fileLocation += fileName;\n } else {\n // Source code does not originate from a file and is not native, but we\n // can still get the source position inside the source string, e.g. in\n // an eval string.\n fileLocation += \"\";\n }\n var lineNumber = this.getLineNumber();\n if (lineNumber != null) {\n fileLocation += \":\" + lineNumber;\n var columnNumber = this.getColumnNumber();\n if (columnNumber) {\n fileLocation += \":\" + columnNumber;\n }\n }\n }\n\n var line = \"\";\n var functionName = this.getFunctionName();\n var addSuffix = true;\n var isConstructor = this.isConstructor();\n var isMethodCall = !(this.isToplevel() || isConstructor);\n if (isMethodCall) {\n var typeName = this.getTypeName();\n // Fixes shim to be backward compatable with Node v0 to v4\n if (typeName === \"[object Object]\") {\n typeName = \"null\";\n }\n var methodName = this.getMethodName();\n if (functionName) {\n if (typeName && functionName.indexOf(typeName) != 0) {\n line += typeName + \".\";\n }\n line += functionName;\n if (methodName && functionName.indexOf(\".\" + methodName) != functionName.length - methodName.length - 1) {\n line += \" [as \" + methodName + \"]\";\n }\n } else {\n line += typeName + \".\" + (methodName || \"\");\n }\n } else if (isConstructor) {\n line += \"new \" + (functionName || \"\");\n } else if (functionName) {\n line += functionName;\n } else {\n line += fileLocation;\n addSuffix = false;\n }\n if (addSuffix) {\n line += \" (\" + fileLocation + \")\";\n }\n return line;\n}\n\nfunction cloneCallSite(frame) {\n var object = {};\n Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) {\n object[name] = /^(?:is|get)/.test(name) ? function() { return frame[name].call(frame); } : frame[name];\n });\n object.toString = CallSiteToString;\n return object;\n}\n\nfunction wrapCallSite(frame) {\n if(frame.isNative()) {\n return frame;\n }\n\n // Most call sites will return the source file from getFileName(), but code\n // passed to eval() ending in \"//# sourceURL=...\" will return the source file\n // from getScriptNameOrSourceURL() instead\n var source = frame.getFileName() || frame.getScriptNameOrSourceURL();\n if (source) {\n var line = frame.getLineNumber();\n var column = frame.getColumnNumber() - 1;\n\n // Fix position in Node where some (internal) code is prepended.\n // See https://github.com/evanw/node-source-map-support/issues/36\n var headerLength = 62;\n if (line === 1 && column > headerLength && !isInBrowser() && !frame.isEval()) {\n column -= headerLength;\n }\n\n var position = mapSourcePosition({\n source: source,\n line: line,\n column: column\n });\n frame = cloneCallSite(frame);\n frame.getFileName = function() { return position.source; };\n frame.getLineNumber = function() { return position.line; };\n frame.getColumnNumber = function() { return position.column + 1; };\n frame.getScriptNameOrSourceURL = function() { return position.source; };\n return frame;\n }\n\n // Code called using eval() needs special handling\n var origin = frame.isEval() && frame.getEvalOrigin();\n if (origin) {\n origin = mapEvalOrigin(origin);\n frame = cloneCallSite(frame);\n frame.getEvalOrigin = function() { return origin; };\n return frame;\n }\n\n // If we get here then we were unable to change the source position\n return frame;\n}\n\n// This function is part of the V8 stack trace API, for more info see:\n// http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi\nfunction prepareStackTrace(error, stack) {\n if (emptyCacheBetweenOperations) {\n fileContentsCache = {};\n sourceMapCache = {};\n }\n\n return error + stack.map(function(frame) {\n return '\\n at ' + wrapCallSite(frame);\n }).join('');\n}\n\n// Generate position and snippet of original source with pointer\nfunction getErrorSource(error) {\n var match = /\\n at [^(]+ \\((.*):(\\d+):(\\d+)\\)/.exec(error.stack);\n if (match) {\n var source = match[1];\n var line = +match[2];\n var column = +match[3];\n\n // Support the inline sourceContents inside the source map\n var contents = fileContentsCache[source];\n\n // Support files on disk\n if (!contents && fs && fs.existsSync(source)) {\n try {\n contents = fs.readFileSync(source, 'utf8');\n } catch (er) {\n contents = '';\n }\n }\n\n // Format the line from the original source code like node does\n if (contents) {\n var code = contents.split(/(?:\\r\\n|\\r|\\n)/)[line - 1];\n if (code) {\n return source + ':' + line + '\\n' + code + '\\n' +\n new Array(column).join(' ') + '^';\n }\n }\n }\n return null;\n}\n\nfunction printErrorAndExit (error) {\n var source = getErrorSource(error);\n\n if (source) {\n console.error();\n console.error(source);\n }\n\n console.error(error.stack);\n process.exit(1);\n}\n\nfunction shimEmitUncaughtException () {\n var origEmit = process.emit;\n\n process.emit = function (type) {\n if (type === 'uncaughtException') {\n var hasStack = (arguments[1] && arguments[1].stack);\n var hasListeners = (this.listeners(type).length > 0);\n\n if (hasStack && !hasListeners) {\n return printErrorAndExit(arguments[1]);\n }\n }\n\n return origEmit.apply(this, arguments);\n };\n}\n\nexports.wrapCallSite = wrapCallSite;\nexports.getErrorSource = getErrorSource;\nexports.mapSourcePosition = mapSourcePosition;\nexports.retrieveSourceMap = retrieveSourceMap;\n\nexports.install = function(options) {\n options = options || {};\n\n if (options.environment) {\n environment = options.environment;\n if ([\"node\", \"browser\", \"auto\"].indexOf(environment) === -1) {\n throw new Error(\"environment \" + environment + \" was unknown. Available options are {auto, browser, node}\")\n }\n }\n\n // Allow sources to be found by methods other than reading the files\n // directly from disk.\n if (options.retrieveFile) {\n if (options.overrideRetrieveFile) {\n retrieveFileHandlers.length = 0;\n }\n\n retrieveFileHandlers.unshift(options.retrieveFile);\n }\n\n // Allow source maps to be found by methods other than reading the files\n // directly from disk.\n if (options.retrieveSourceMap) {\n if (options.overrideRetrieveSourceMap) {\n retrieveMapHandlers.length = 0;\n }\n\n retrieveMapHandlers.unshift(options.retrieveSourceMap);\n }\n\n // Support runtime transpilers that include inline source maps\n if (options.hookRequire && !isInBrowser()) {\n var Module;\n try {\n Module = require('module');\n } catch (err) {\n // NOP: Loading in catch block to convert webpack error to warning.\n }\n var $compile = Module.prototype._compile;\n\n if (!$compile.__sourceMapSupport) {\n Module.prototype._compile = function(content, filename) {\n fileContentsCache[filename] = content;\n sourceMapCache[filename] = undefined;\n return $compile.call(this, content, filename);\n };\n\n Module.prototype._compile.__sourceMapSupport = true;\n }\n }\n\n // Configure options\n if (!emptyCacheBetweenOperations) {\n emptyCacheBetweenOperations = 'emptyCacheBetweenOperations' in options ?\n options.emptyCacheBetweenOperations : false;\n }\n\n // Install the error reformatter\n if (!errorFormatterInstalled) {\n errorFormatterInstalled = true;\n Error.prepareStackTrace = prepareStackTrace;\n }\n\n if (!uncaughtShimInstalled) {\n var installHandler = 'handleUncaughtExceptions' in options ?\n options.handleUncaughtExceptions : true;\n\n // Provide the option to not install the uncaught exception handler. This is\n // to support other uncaught exception handlers (in test frameworks, for\n // example). If this handler is not installed and there are no other uncaught\n // exception handlers, uncaught exceptions will be caught by node's built-in\n // exception handler and the process will still be terminated. However, the\n // generated JavaScript code will be shown above the stack trace instead of\n // the original source code.\n if (installHandler && hasGlobalProcessEventEmitter()) {\n uncaughtShimInstalled = true;\n shimEmitUncaughtException();\n }\n }\n};\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\nvar has = Object.prototype.hasOwnProperty;\nvar hasNativeMap = typeof Map !== \"undefined\";\n\n/**\n * A data structure which is a combination of an array and a set. Adding a new\n * member is O(1), testing for membership is O(1), and finding the index of an\n * element is O(1). Removing elements from the set is not supported. Only\n * strings are supported for membership.\n */\nfunction ArraySet() {\n this._array = [];\n this._set = hasNativeMap ? new Map() : Object.create(null);\n}\n\n/**\n * Static method for creating ArraySet instances from an existing array.\n */\nArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {\n var set = new ArraySet();\n for (var i = 0, len = aArray.length; i < len; i++) {\n set.add(aArray[i], aAllowDuplicates);\n }\n return set;\n};\n\n/**\n * Return how many unique items are in this ArraySet. If duplicates have been\n * added, than those do not count towards the size.\n *\n * @returns Number\n */\nArraySet.prototype.size = function ArraySet_size() {\n return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;\n};\n\n/**\n * Add the given string to this set.\n *\n * @param String aStr\n */\nArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {\n var sStr = hasNativeMap ? aStr : util.toSetString(aStr);\n var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);\n var idx = this._array.length;\n if (!isDuplicate || aAllowDuplicates) {\n this._array.push(aStr);\n }\n if (!isDuplicate) {\n if (hasNativeMap) {\n this._set.set(aStr, idx);\n } else {\n this._set[sStr] = idx;\n }\n }\n};\n\n/**\n * Is the given string a member of this set?\n *\n * @param String aStr\n */\nArraySet.prototype.has = function ArraySet_has(aStr) {\n if (hasNativeMap) {\n return this._set.has(aStr);\n } else {\n var sStr = util.toSetString(aStr);\n return has.call(this._set, sStr);\n }\n};\n\n/**\n * What is the index of the given string in the array?\n *\n * @param String aStr\n */\nArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {\n if (hasNativeMap) {\n var idx = this._set.get(aStr);\n if (idx >= 0) {\n return idx;\n }\n } else {\n var sStr = util.toSetString(aStr);\n if (has.call(this._set, sStr)) {\n return this._set[sStr];\n }\n }\n\n throw new Error('\"' + aStr + '\" is not in the set.');\n};\n\n/**\n * What is the element at the given index?\n *\n * @param Number aIdx\n */\nArraySet.prototype.at = function ArraySet_at(aIdx) {\n if (aIdx >= 0 && aIdx < this._array.length) {\n return this._array[aIdx];\n }\n throw new Error('No element indexed by ' + aIdx);\n};\n\n/**\n * Returns the array representation of this set (which has the proper indices\n * indicated by indexOf). Note that this is a copy of the internal array used\n * for storing the members so that no one can mess with internal state.\n */\nArraySet.prototype.toArray = function ArraySet_toArray() {\n return this._array.slice();\n};\n\nexports.ArraySet = ArraySet;\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n *\n * Based on the Base 64 VLQ implementation in Closure Compiler:\n * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java\n *\n * Copyright 2011 The Closure Compiler Authors. All rights reserved.\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials provided\n * with the distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\nvar base64 = require('./base64');\n\n// A single base 64 digit can contain 6 bits of data. For the base 64 variable\n// length quantities we use in the source map spec, the first bit is the sign,\n// the next four bits are the actual value, and the 6th bit is the\n// continuation bit. The continuation bit tells us whether there are more\n// digits in this value following this digit.\n//\n// Continuation\n// | Sign\n// | |\n// V V\n// 101011\n\nvar VLQ_BASE_SHIFT = 5;\n\n// binary: 100000\nvar VLQ_BASE = 1 << VLQ_BASE_SHIFT;\n\n// binary: 011111\nvar VLQ_BASE_MASK = VLQ_BASE - 1;\n\n// binary: 100000\nvar VLQ_CONTINUATION_BIT = VLQ_BASE;\n\n/**\n * Converts from a two-complement value to a value where the sign bit is\n * placed in the least significant bit. For example, as decimals:\n * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)\n * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)\n */\nfunction toVLQSigned(aValue) {\n return aValue < 0\n ? ((-aValue) << 1) + 1\n : (aValue << 1) + 0;\n}\n\n/**\n * Converts to a two-complement value from a value where the sign bit is\n * placed in the least significant bit. For example, as decimals:\n * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1\n * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2\n */\nfunction fromVLQSigned(aValue) {\n var isNegative = (aValue & 1) === 1;\n var shifted = aValue >> 1;\n return isNegative\n ? -shifted\n : shifted;\n}\n\n/**\n * Returns the base 64 VLQ encoded value.\n */\nexports.encode = function base64VLQ_encode(aValue) {\n var encoded = \"\";\n var digit;\n\n var vlq = toVLQSigned(aValue);\n\n do {\n digit = vlq & VLQ_BASE_MASK;\n vlq >>>= VLQ_BASE_SHIFT;\n if (vlq > 0) {\n // There are still more digits in this value, so we must make sure the\n // continuation bit is marked.\n digit |= VLQ_CONTINUATION_BIT;\n }\n encoded += base64.encode(digit);\n } while (vlq > 0);\n\n return encoded;\n};\n\n/**\n * Decodes the next base 64 VLQ value from the given string and returns the\n * value and the rest of the string via the out parameter.\n */\nexports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {\n var strLen = aStr.length;\n var result = 0;\n var shift = 0;\n var continuation, digit;\n\n do {\n if (aIndex >= strLen) {\n throw new Error(\"Expected more digits in base 64 VLQ value.\");\n }\n\n digit = base64.decode(aStr.charCodeAt(aIndex++));\n if (digit === -1) {\n throw new Error(\"Invalid base64 digit: \" + aStr.charAt(aIndex - 1));\n }\n\n continuation = !!(digit & VLQ_CONTINUATION_BIT);\n digit &= VLQ_BASE_MASK;\n result = result + (digit << shift);\n shift += VLQ_BASE_SHIFT;\n } while (continuation);\n\n aOutParam.value = fromVLQSigned(result);\n aOutParam.rest = aIndex;\n};\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');\n\n/**\n * Encode an integer in the range of 0 to 63 to a single base 64 digit.\n */\nexports.encode = function (number) {\n if (0 <= number && number < intToCharMap.length) {\n return intToCharMap[number];\n }\n throw new TypeError(\"Must be between 0 and 63: \" + number);\n};\n\n/**\n * Decode a single base 64 character code digit to an integer. Returns -1 on\n * failure.\n */\nexports.decode = function (charCode) {\n var bigA = 65; // 'A'\n var bigZ = 90; // 'Z'\n\n var littleA = 97; // 'a'\n var littleZ = 122; // 'z'\n\n var zero = 48; // '0'\n var nine = 57; // '9'\n\n var plus = 43; // '+'\n var slash = 47; // '/'\n\n var littleOffset = 26;\n var numberOffset = 52;\n\n // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ\n if (bigA <= charCode && charCode <= bigZ) {\n return (charCode - bigA);\n }\n\n // 26 - 51: abcdefghijklmnopqrstuvwxyz\n if (littleA <= charCode && charCode <= littleZ) {\n return (charCode - littleA + littleOffset);\n }\n\n // 52 - 61: 0123456789\n if (zero <= charCode && charCode <= nine) {\n return (charCode - zero + numberOffset);\n }\n\n // 62: +\n if (charCode == plus) {\n return 62;\n }\n\n // 63: /\n if (charCode == slash) {\n return 63;\n }\n\n // Invalid base64 digit.\n return -1;\n};\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nexports.GREATEST_LOWER_BOUND = 1;\nexports.LEAST_UPPER_BOUND = 2;\n\n/**\n * Recursive implementation of binary search.\n *\n * @param aLow Indices here and lower do not contain the needle.\n * @param aHigh Indices here and higher do not contain the needle.\n * @param aNeedle The element being searched for.\n * @param aHaystack The non-empty array being searched.\n * @param aCompare Function which takes two elements and returns -1, 0, or 1.\n * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n */\nfunction recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {\n // This function terminates when one of the following is true:\n //\n // 1. We find the exact element we are looking for.\n //\n // 2. We did not find the exact element, but we can return the index of\n // the next-closest element.\n //\n // 3. We did not find the exact element, and there is no next-closest\n // element than the one we are searching for, so we return -1.\n var mid = Math.floor((aHigh - aLow) / 2) + aLow;\n var cmp = aCompare(aNeedle, aHaystack[mid], true);\n if (cmp === 0) {\n // Found the element we are looking for.\n return mid;\n }\n else if (cmp > 0) {\n // Our needle is greater than aHaystack[mid].\n if (aHigh - mid > 1) {\n // The element is in the upper half.\n return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);\n }\n\n // The exact needle element was not found in this haystack. Determine if\n // we are in termination case (3) or (2) and return the appropriate thing.\n if (aBias == exports.LEAST_UPPER_BOUND) {\n return aHigh < aHaystack.length ? aHigh : -1;\n } else {\n return mid;\n }\n }\n else {\n // Our needle is less than aHaystack[mid].\n if (mid - aLow > 1) {\n // The element is in the lower half.\n return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);\n }\n\n // we are in termination case (3) or (2) and return the appropriate thing.\n if (aBias == exports.LEAST_UPPER_BOUND) {\n return mid;\n } else {\n return aLow < 0 ? -1 : aLow;\n }\n }\n}\n\n/**\n * This is an implementation of binary search which will always try and return\n * the index of the closest element if there is no exact hit. This is because\n * mappings between original and generated line/col pairs are single points,\n * and there is an implicit region between each of them, so a miss just means\n * that you aren't on the very start of a region.\n *\n * @param aNeedle The element you are looking for.\n * @param aHaystack The array that is being searched.\n * @param aCompare A function which takes the needle and an element in the\n * array and returns -1, 0, or 1 depending on whether the needle is less\n * than, equal to, or greater than the element, respectively.\n * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.\n */\nexports.search = function search(aNeedle, aHaystack, aCompare, aBias) {\n if (aHaystack.length === 0) {\n return -1;\n }\n\n var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,\n aCompare, aBias || exports.GREATEST_LOWER_BOUND);\n if (index < 0) {\n return -1;\n }\n\n // We have found either the exact element, or the next-closest element than\n // the one we are searching for. However, there may be more than one such\n // element. Make sure we always return the smallest of these.\n while (index - 1 >= 0) {\n if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {\n break;\n }\n --index;\n }\n\n return index;\n};\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2014 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\n\n/**\n * Determine whether mappingB is after mappingA with respect to generated\n * position.\n */\nfunction generatedPositionAfter(mappingA, mappingB) {\n // Optimized for most common case\n var lineA = mappingA.generatedLine;\n var lineB = mappingB.generatedLine;\n var columnA = mappingA.generatedColumn;\n var columnB = mappingB.generatedColumn;\n return lineB > lineA || lineB == lineA && columnB >= columnA ||\n util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;\n}\n\n/**\n * A data structure to provide a sorted view of accumulated mappings in a\n * performance conscious manner. It trades a neglibable overhead in general\n * case for a large speedup in case of mappings being added in order.\n */\nfunction MappingList() {\n this._array = [];\n this._sorted = true;\n // Serves as infimum\n this._last = {generatedLine: -1, generatedColumn: 0};\n}\n\n/**\n * Iterate through internal items. This method takes the same arguments that\n * `Array.prototype.forEach` takes.\n *\n * NOTE: The order of the mappings is NOT guaranteed.\n */\nMappingList.prototype.unsortedForEach =\n function MappingList_forEach(aCallback, aThisArg) {\n this._array.forEach(aCallback, aThisArg);\n };\n\n/**\n * Add the given source mapping.\n *\n * @param Object aMapping\n */\nMappingList.prototype.add = function MappingList_add(aMapping) {\n if (generatedPositionAfter(this._last, aMapping)) {\n this._last = aMapping;\n this._array.push(aMapping);\n } else {\n this._sorted = false;\n this._array.push(aMapping);\n }\n};\n\n/**\n * Returns the flat, sorted array of mappings. The mappings are sorted by\n * generated position.\n *\n * WARNING: This method returns internal data without copying, for\n * performance. The return value must NOT be mutated, and should be treated as\n * an immutable borrow. If you want to take ownership, you must make your own\n * copy.\n */\nMappingList.prototype.toArray = function MappingList_toArray() {\n if (!this._sorted) {\n this._array.sort(util.compareByGeneratedPositionsInflated);\n this._sorted = true;\n }\n return this._array;\n};\n\nexports.MappingList = MappingList;\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\n// It turns out that some (most?) JavaScript engines don't self-host\n// `Array.prototype.sort`. This makes sense because C++ will likely remain\n// faster than JS when doing raw CPU-intensive sorting. However, when using a\n// custom comparator function, calling back and forth between the VM's C++ and\n// JIT'd JS is rather slow *and* loses JIT type information, resulting in\n// worse generated code for the comparator function than would be optimal. In\n// fact, when sorting with a comparator, these costs outweigh the benefits of\n// sorting in C++. By using our own JS-implemented Quick Sort (below), we get\n// a ~3500ms mean speed-up in `bench/bench.html`.\n\n/**\n * Swap the elements indexed by `x` and `y` in the array `ary`.\n *\n * @param {Array} ary\n * The array.\n * @param {Number} x\n * The index of the first item.\n * @param {Number} y\n * The index of the second item.\n */\nfunction swap(ary, x, y) {\n var temp = ary[x];\n ary[x] = ary[y];\n ary[y] = temp;\n}\n\n/**\n * Returns a random integer within the range `low .. high` inclusive.\n *\n * @param {Number} low\n * The lower bound on the range.\n * @param {Number} high\n * The upper bound on the range.\n */\nfunction randomIntInRange(low, high) {\n return Math.round(low + (Math.random() * (high - low)));\n}\n\n/**\n * The Quick Sort algorithm.\n *\n * @param {Array} ary\n * An array to sort.\n * @param {function} comparator\n * Function to use to compare two items.\n * @param {Number} p\n * Start index of the array\n * @param {Number} r\n * End index of the array\n */\nfunction doQuickSort(ary, comparator, p, r) {\n // If our lower bound is less than our upper bound, we (1) partition the\n // array into two pieces and (2) recurse on each half. If it is not, this is\n // the empty array and our base case.\n\n if (p < r) {\n // (1) Partitioning.\n //\n // The partitioning chooses a pivot between `p` and `r` and moves all\n // elements that are less than or equal to the pivot to the before it, and\n // all the elements that are greater than it after it. The effect is that\n // once partition is done, the pivot is in the exact place it will be when\n // the array is put in sorted order, and it will not need to be moved\n // again. This runs in O(n) time.\n\n // Always choose a random pivot so that an input array which is reverse\n // sorted does not cause O(n^2) running time.\n var pivotIndex = randomIntInRange(p, r);\n var i = p - 1;\n\n swap(ary, pivotIndex, r);\n var pivot = ary[r];\n\n // Immediately after `j` is incremented in this loop, the following hold\n // true:\n //\n // * Every element in `ary[p .. i]` is less than or equal to the pivot.\n //\n // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.\n for (var j = p; j < r; j++) {\n if (comparator(ary[j], pivot) <= 0) {\n i += 1;\n swap(ary, i, j);\n }\n }\n\n swap(ary, i + 1, j);\n var q = i + 1;\n\n // (2) Recurse on each half.\n\n doQuickSort(ary, comparator, p, q - 1);\n doQuickSort(ary, comparator, q + 1, r);\n }\n}\n\n/**\n * Sort the given array in-place with the given comparator function.\n *\n * @param {Array} ary\n * An array to sort.\n * @param {function} comparator\n * Function to use to compare two items.\n */\nexports.quickSort = function (ary, comparator) {\n doQuickSort(ary, comparator, 0, ary.length - 1);\n};\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\nvar binarySearch = require('./binary-search');\nvar ArraySet = require('./array-set').ArraySet;\nvar base64VLQ = require('./base64-vlq');\nvar quickSort = require('./quick-sort').quickSort;\n\nfunction SourceMapConsumer(aSourceMap) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = JSON.parse(aSourceMap.replace(/^\\)\\]\\}'/, ''));\n }\n\n return sourceMap.sections != null\n ? new IndexedSourceMapConsumer(sourceMap)\n : new BasicSourceMapConsumer(sourceMap);\n}\n\nSourceMapConsumer.fromSourceMap = function(aSourceMap) {\n return BasicSourceMapConsumer.fromSourceMap(aSourceMap);\n}\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nSourceMapConsumer.prototype._version = 3;\n\n// `__generatedMappings` and `__originalMappings` are arrays that hold the\n// parsed mapping coordinates from the source map's \"mappings\" attribute. They\n// are lazily instantiated, accessed via the `_generatedMappings` and\n// `_originalMappings` getters respectively, and we only parse the mappings\n// and create these arrays once queried for a source location. We jump through\n// these hoops because there can be many thousands of mappings, and parsing\n// them is expensive, so we only want to do it if we must.\n//\n// Each object in the arrays is of the form:\n//\n// {\n// generatedLine: The line number in the generated code,\n// generatedColumn: The column number in the generated code,\n// source: The path to the original source file that generated this\n// chunk of code,\n// originalLine: The line number in the original source that\n// corresponds to this chunk of generated code,\n// originalColumn: The column number in the original source that\n// corresponds to this chunk of generated code,\n// name: The name of the original symbol which generated this chunk of\n// code.\n// }\n//\n// All properties except for `generatedLine` and `generatedColumn` can be\n// `null`.\n//\n// `_generatedMappings` is ordered by the generated positions.\n//\n// `_originalMappings` is ordered by the original positions.\n\nSourceMapConsumer.prototype.__generatedMappings = null;\nObject.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {\n get: function () {\n if (!this.__generatedMappings) {\n this._parseMappings(this._mappings, this.sourceRoot);\n }\n\n return this.__generatedMappings;\n }\n});\n\nSourceMapConsumer.prototype.__originalMappings = null;\nObject.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {\n get: function () {\n if (!this.__originalMappings) {\n this._parseMappings(this._mappings, this.sourceRoot);\n }\n\n return this.__originalMappings;\n }\n});\n\nSourceMapConsumer.prototype._charIsMappingSeparator =\n function SourceMapConsumer_charIsMappingSeparator(aStr, index) {\n var c = aStr.charAt(index);\n return c === \";\" || c === \",\";\n };\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nSourceMapConsumer.prototype._parseMappings =\n function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n throw new Error(\"Subclasses must implement _parseMappings\");\n };\n\nSourceMapConsumer.GENERATED_ORDER = 1;\nSourceMapConsumer.ORIGINAL_ORDER = 2;\n\nSourceMapConsumer.GREATEST_LOWER_BOUND = 1;\nSourceMapConsumer.LEAST_UPPER_BOUND = 2;\n\n/**\n * Iterate over each mapping between an original source/line/column and a\n * generated line/column in this source map.\n *\n * @param Function aCallback\n * The function that is called with each mapping.\n * @param Object aContext\n * Optional. If specified, this object will be the value of `this` every\n * time that `aCallback` is called.\n * @param aOrder\n * Either `SourceMapConsumer.GENERATED_ORDER` or\n * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to\n * iterate over the mappings sorted by the generated file's line/column\n * order or the original's source/line/column order, respectively. Defaults to\n * `SourceMapConsumer.GENERATED_ORDER`.\n */\nSourceMapConsumer.prototype.eachMapping =\n function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {\n var context = aContext || null;\n var order = aOrder || SourceMapConsumer.GENERATED_ORDER;\n\n var mappings;\n switch (order) {\n case SourceMapConsumer.GENERATED_ORDER:\n mappings = this._generatedMappings;\n break;\n case SourceMapConsumer.ORIGINAL_ORDER:\n mappings = this._originalMappings;\n break;\n default:\n throw new Error(\"Unknown order of iteration.\");\n }\n\n var sourceRoot = this.sourceRoot;\n mappings.map(function (mapping) {\n var source = mapping.source === null ? null : this._sources.at(mapping.source);\n if (source != null && sourceRoot != null) {\n source = util.join(sourceRoot, source);\n }\n return {\n source: source,\n generatedLine: mapping.generatedLine,\n generatedColumn: mapping.generatedColumn,\n originalLine: mapping.originalLine,\n originalColumn: mapping.originalColumn,\n name: mapping.name === null ? null : this._names.at(mapping.name)\n };\n }, this).forEach(aCallback, context);\n };\n\n/**\n * Returns all generated line and column information for the original source,\n * line, and column provided. If no column is provided, returns all mappings\n * corresponding to a either the line we are searching for or the next\n * closest line that has any mappings. Otherwise, returns all mappings\n * corresponding to the given line and either the column we are searching for\n * or the next closest column that has any offsets.\n *\n * The only argument is an object with the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source.\n * - column: Optional. the column number in the original source.\n *\n * and an array of objects is returned, each with the following properties:\n *\n * - line: The line number in the generated source, or null.\n * - column: The column number in the generated source, or null.\n */\nSourceMapConsumer.prototype.allGeneratedPositionsFor =\n function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {\n var line = util.getArg(aArgs, 'line');\n\n // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping\n // returns the index of the closest mapping less than the needle. By\n // setting needle.originalColumn to 0, we thus find the last mapping for\n // the given line, provided such a mapping exists.\n var needle = {\n source: util.getArg(aArgs, 'source'),\n originalLine: line,\n originalColumn: util.getArg(aArgs, 'column', 0)\n };\n\n if (this.sourceRoot != null) {\n needle.source = util.relative(this.sourceRoot, needle.source);\n }\n if (!this._sources.has(needle.source)) {\n return [];\n }\n needle.source = this._sources.indexOf(needle.source);\n\n var mappings = [];\n\n var index = this._findMapping(needle,\n this._originalMappings,\n \"originalLine\",\n \"originalColumn\",\n util.compareByOriginalPositions,\n binarySearch.LEAST_UPPER_BOUND);\n if (index >= 0) {\n var mapping = this._originalMappings[index];\n\n if (aArgs.column === undefined) {\n var originalLine = mapping.originalLine;\n\n // Iterate until either we run out of mappings, or we run into\n // a mapping for a different line than the one we found. Since\n // mappings are sorted, this is guaranteed to find all mappings for\n // the line we found.\n while (mapping && mapping.originalLine === originalLine) {\n mappings.push({\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n });\n\n mapping = this._originalMappings[++index];\n }\n } else {\n var originalColumn = mapping.originalColumn;\n\n // Iterate until either we run out of mappings, or we run into\n // a mapping for a different line than the one we were searching for.\n // Since mappings are sorted, this is guaranteed to find all mappings for\n // the line we are searching for.\n while (mapping &&\n mapping.originalLine === line &&\n mapping.originalColumn == originalColumn) {\n mappings.push({\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n });\n\n mapping = this._originalMappings[++index];\n }\n }\n }\n\n return mappings;\n };\n\nexports.SourceMapConsumer = SourceMapConsumer;\n\n/**\n * A BasicSourceMapConsumer instance represents a parsed source map which we can\n * query for information about the original file positions by giving it a file\n * position in the generated source.\n *\n * The only parameter is the raw source map (either as a JSON string, or\n * already parsed to an object). According to the spec, source maps have the\n * following attributes:\n *\n * - version: Which version of the source map spec this map is following.\n * - sources: An array of URLs to the original source files.\n * - names: An array of identifiers which can be referrenced by individual mappings.\n * - sourceRoot: Optional. The URL root from which all sources are relative.\n * - sourcesContent: Optional. An array of contents of the original source files.\n * - mappings: A string of base64 VLQs which contain the actual mappings.\n * - file: Optional. The generated file this source map is associated with.\n *\n * Here is an example source map, taken from the source map spec[0]:\n *\n * {\n * version : 3,\n * file: \"out.js\",\n * sourceRoot : \"\",\n * sources: [\"foo.js\", \"bar.js\"],\n * names: [\"src\", \"maps\", \"are\", \"fun\"],\n * mappings: \"AA,AB;;ABCDE;\"\n * }\n *\n * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#\n */\nfunction BasicSourceMapConsumer(aSourceMap) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = JSON.parse(aSourceMap.replace(/^\\)\\]\\}'/, ''));\n }\n\n var version = util.getArg(sourceMap, 'version');\n var sources = util.getArg(sourceMap, 'sources');\n // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which\n // requires the array) to play nice here.\n var names = util.getArg(sourceMap, 'names', []);\n var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);\n var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);\n var mappings = util.getArg(sourceMap, 'mappings');\n var file = util.getArg(sourceMap, 'file', null);\n\n // Once again, Sass deviates from the spec and supplies the version as a\n // string rather than a number, so we use loose equality checking here.\n if (version != this._version) {\n throw new Error('Unsupported version: ' + version);\n }\n\n sources = sources\n .map(String)\n // Some source maps produce relative source paths like \"./foo.js\" instead of\n // \"foo.js\". Normalize these first so that future comparisons will succeed.\n // See bugzil.la/1090768.\n .map(util.normalize)\n // Always ensure that absolute sources are internally stored relative to\n // the source root, if the source root is absolute. Not doing this would\n // be particularly problematic when the source root is a prefix of the\n // source (valid, but why??). See github issue #199 and bugzil.la/1188982.\n .map(function (source) {\n return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)\n ? util.relative(sourceRoot, source)\n : source;\n });\n\n // Pass `true` below to allow duplicate names and sources. While source maps\n // are intended to be compressed and deduplicated, the TypeScript compiler\n // sometimes generates source maps with duplicates in them. See Github issue\n // #72 and bugzil.la/889492.\n this._names = ArraySet.fromArray(names.map(String), true);\n this._sources = ArraySet.fromArray(sources, true);\n\n this.sourceRoot = sourceRoot;\n this.sourcesContent = sourcesContent;\n this._mappings = mappings;\n this.file = file;\n}\n\nBasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\nBasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;\n\n/**\n * Create a BasicSourceMapConsumer from a SourceMapGenerator.\n *\n * @param SourceMapGenerator aSourceMap\n * The source map that will be consumed.\n * @returns BasicSourceMapConsumer\n */\nBasicSourceMapConsumer.fromSourceMap =\n function SourceMapConsumer_fromSourceMap(aSourceMap) {\n var smc = Object.create(BasicSourceMapConsumer.prototype);\n\n var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);\n var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);\n smc.sourceRoot = aSourceMap._sourceRoot;\n smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),\n smc.sourceRoot);\n smc.file = aSourceMap._file;\n\n // Because we are modifying the entries (by converting string sources and\n // names to indices into the sources and names ArraySets), we have to make\n // a copy of the entry or else bad things happen. Shared mutable state\n // strikes again! See github issue #191.\n\n var generatedMappings = aSourceMap._mappings.toArray().slice();\n var destGeneratedMappings = smc.__generatedMappings = [];\n var destOriginalMappings = smc.__originalMappings = [];\n\n for (var i = 0, length = generatedMappings.length; i < length; i++) {\n var srcMapping = generatedMappings[i];\n var destMapping = new Mapping;\n destMapping.generatedLine = srcMapping.generatedLine;\n destMapping.generatedColumn = srcMapping.generatedColumn;\n\n if (srcMapping.source) {\n destMapping.source = sources.indexOf(srcMapping.source);\n destMapping.originalLine = srcMapping.originalLine;\n destMapping.originalColumn = srcMapping.originalColumn;\n\n if (srcMapping.name) {\n destMapping.name = names.indexOf(srcMapping.name);\n }\n\n destOriginalMappings.push(destMapping);\n }\n\n destGeneratedMappings.push(destMapping);\n }\n\n quickSort(smc.__originalMappings, util.compareByOriginalPositions);\n\n return smc;\n };\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nBasicSourceMapConsumer.prototype._version = 3;\n\n/**\n * The list of original sources.\n */\nObject.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {\n get: function () {\n return this._sources.toArray().map(function (s) {\n return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s;\n }, this);\n }\n});\n\n/**\n * Provide the JIT with a nice shape / hidden class.\n */\nfunction Mapping() {\n this.generatedLine = 0;\n this.generatedColumn = 0;\n this.source = null;\n this.originalLine = null;\n this.originalColumn = null;\n this.name = null;\n}\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nBasicSourceMapConsumer.prototype._parseMappings =\n function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n var generatedLine = 1;\n var previousGeneratedColumn = 0;\n var previousOriginalLine = 0;\n var previousOriginalColumn = 0;\n var previousSource = 0;\n var previousName = 0;\n var length = aStr.length;\n var index = 0;\n var cachedSegments = {};\n var temp = {};\n var originalMappings = [];\n var generatedMappings = [];\n var mapping, str, segment, end, value;\n\n while (index < length) {\n if (aStr.charAt(index) === ';') {\n generatedLine++;\n index++;\n previousGeneratedColumn = 0;\n }\n else if (aStr.charAt(index) === ',') {\n index++;\n }\n else {\n mapping = new Mapping();\n mapping.generatedLine = generatedLine;\n\n // Because each offset is encoded relative to the previous one,\n // many segments often have the same encoding. We can exploit this\n // fact by caching the parsed variable length fields of each segment,\n // allowing us to avoid a second parse if we encounter the same\n // segment again.\n for (end = index; end < length; end++) {\n if (this._charIsMappingSeparator(aStr, end)) {\n break;\n }\n }\n str = aStr.slice(index, end);\n\n segment = cachedSegments[str];\n if (segment) {\n index += str.length;\n } else {\n segment = [];\n while (index < end) {\n base64VLQ.decode(aStr, index, temp);\n value = temp.value;\n index = temp.rest;\n segment.push(value);\n }\n\n if (segment.length === 2) {\n throw new Error('Found a source, but no line and column');\n }\n\n if (segment.length === 3) {\n throw new Error('Found a source and line, but no column');\n }\n\n cachedSegments[str] = segment;\n }\n\n // Generated column.\n mapping.generatedColumn = previousGeneratedColumn + segment[0];\n previousGeneratedColumn = mapping.generatedColumn;\n\n if (segment.length > 1) {\n // Original source.\n mapping.source = previousSource + segment[1];\n previousSource += segment[1];\n\n // Original line.\n mapping.originalLine = previousOriginalLine + segment[2];\n previousOriginalLine = mapping.originalLine;\n // Lines are stored 0-based\n mapping.originalLine += 1;\n\n // Original column.\n mapping.originalColumn = previousOriginalColumn + segment[3];\n previousOriginalColumn = mapping.originalColumn;\n\n if (segment.length > 4) {\n // Original name.\n mapping.name = previousName + segment[4];\n previousName += segment[4];\n }\n }\n\n generatedMappings.push(mapping);\n if (typeof mapping.originalLine === 'number') {\n originalMappings.push(mapping);\n }\n }\n }\n\n quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);\n this.__generatedMappings = generatedMappings;\n\n quickSort(originalMappings, util.compareByOriginalPositions);\n this.__originalMappings = originalMappings;\n };\n\n/**\n * Find the mapping that best matches the hypothetical \"needle\" mapping that\n * we are searching for in the given \"haystack\" of mappings.\n */\nBasicSourceMapConsumer.prototype._findMapping =\n function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,\n aColumnName, aComparator, aBias) {\n // To return the position we are searching for, we must first find the\n // mapping for the given position and then return the opposite position it\n // points to. Because the mappings are sorted, we can use binary search to\n // find the best mapping.\n\n if (aNeedle[aLineName] <= 0) {\n throw new TypeError('Line must be greater than or equal to 1, got '\n + aNeedle[aLineName]);\n }\n if (aNeedle[aColumnName] < 0) {\n throw new TypeError('Column must be greater than or equal to 0, got '\n + aNeedle[aColumnName]);\n }\n\n return binarySearch.search(aNeedle, aMappings, aComparator, aBias);\n };\n\n/**\n * Compute the last column for each generated mapping. The last column is\n * inclusive.\n */\nBasicSourceMapConsumer.prototype.computeColumnSpans =\n function SourceMapConsumer_computeColumnSpans() {\n for (var index = 0; index < this._generatedMappings.length; ++index) {\n var mapping = this._generatedMappings[index];\n\n // Mappings do not contain a field for the last generated columnt. We\n // can come up with an optimistic estimate, however, by assuming that\n // mappings are contiguous (i.e. given two consecutive mappings, the\n // first mapping ends where the second one starts).\n if (index + 1 < this._generatedMappings.length) {\n var nextMapping = this._generatedMappings[index + 1];\n\n if (mapping.generatedLine === nextMapping.generatedLine) {\n mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;\n continue;\n }\n }\n\n // The last mapping for each line spans the entire line.\n mapping.lastGeneratedColumn = Infinity;\n }\n };\n\n/**\n * Returns the original source, line, and column information for the generated\n * source's line and column positions provided. The only argument is an object\n * with the following properties:\n *\n * - line: The line number in the generated source.\n * - column: The column number in the generated source.\n * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n *\n * and an object is returned with the following properties:\n *\n * - source: The original source file, or null.\n * - line: The line number in the original source, or null.\n * - column: The column number in the original source, or null.\n * - name: The original identifier, or null.\n */\nBasicSourceMapConsumer.prototype.originalPositionFor =\n function SourceMapConsumer_originalPositionFor(aArgs) {\n var needle = {\n generatedLine: util.getArg(aArgs, 'line'),\n generatedColumn: util.getArg(aArgs, 'column')\n };\n\n var index = this._findMapping(\n needle,\n this._generatedMappings,\n \"generatedLine\",\n \"generatedColumn\",\n util.compareByGeneratedPositionsDeflated,\n util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n );\n\n if (index >= 0) {\n var mapping = this._generatedMappings[index];\n\n if (mapping.generatedLine === needle.generatedLine) {\n var source = util.getArg(mapping, 'source', null);\n if (source !== null) {\n source = this._sources.at(source);\n if (this.sourceRoot != null) {\n source = util.join(this.sourceRoot, source);\n }\n }\n var name = util.getArg(mapping, 'name', null);\n if (name !== null) {\n name = this._names.at(name);\n }\n return {\n source: source,\n line: util.getArg(mapping, 'originalLine', null),\n column: util.getArg(mapping, 'originalColumn', null),\n name: name\n };\n }\n }\n\n return {\n source: null,\n line: null,\n column: null,\n name: null\n };\n };\n\n/**\n * Return true if we have the source content for every source in the source\n * map, false otherwise.\n */\nBasicSourceMapConsumer.prototype.hasContentsOfAllSources =\n function BasicSourceMapConsumer_hasContentsOfAllSources() {\n if (!this.sourcesContent) {\n return false;\n }\n return this.sourcesContent.length >= this._sources.size() &&\n !this.sourcesContent.some(function (sc) { return sc == null; });\n };\n\n/**\n * Returns the original source content. The only argument is the url of the\n * original source file. Returns null if no original source content is\n * available.\n */\nBasicSourceMapConsumer.prototype.sourceContentFor =\n function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n if (!this.sourcesContent) {\n return null;\n }\n\n if (this.sourceRoot != null) {\n aSource = util.relative(this.sourceRoot, aSource);\n }\n\n if (this._sources.has(aSource)) {\n return this.sourcesContent[this._sources.indexOf(aSource)];\n }\n\n var url;\n if (this.sourceRoot != null\n && (url = util.urlParse(this.sourceRoot))) {\n // XXX: file:// URIs and absolute paths lead to unexpected behavior for\n // many users. We can help them out when they expect file:// URIs to\n // behave like it would if they were running a local HTTP server. See\n // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.\n var fileUriAbsPath = aSource.replace(/^file:\\/\\//, \"\");\n if (url.scheme == \"file\"\n && this._sources.has(fileUriAbsPath)) {\n return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]\n }\n\n if ((!url.path || url.path == \"/\")\n && this._sources.has(\"/\" + aSource)) {\n return this.sourcesContent[this._sources.indexOf(\"/\" + aSource)];\n }\n }\n\n // This function is used recursively from\n // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we\n // don't want to throw if we can't find the source - we just want to\n // return null, so we provide a flag to exit gracefully.\n if (nullOnMissing) {\n return null;\n }\n else {\n throw new Error('\"' + aSource + '\" is not in the SourceMap.');\n }\n };\n\n/**\n * Returns the generated line and column information for the original source,\n * line, and column positions provided. The only argument is an object with\n * the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source.\n * - column: The column number in the original source.\n * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n *\n * and an object is returned with the following properties:\n *\n * - line: The line number in the generated source, or null.\n * - column: The column number in the generated source, or null.\n */\nBasicSourceMapConsumer.prototype.generatedPositionFor =\n function SourceMapConsumer_generatedPositionFor(aArgs) {\n var source = util.getArg(aArgs, 'source');\n if (this.sourceRoot != null) {\n source = util.relative(this.sourceRoot, source);\n }\n if (!this._sources.has(source)) {\n return {\n line: null,\n column: null,\n lastColumn: null\n };\n }\n source = this._sources.indexOf(source);\n\n var needle = {\n source: source,\n originalLine: util.getArg(aArgs, 'line'),\n originalColumn: util.getArg(aArgs, 'column')\n };\n\n var index = this._findMapping(\n needle,\n this._originalMappings,\n \"originalLine\",\n \"originalColumn\",\n util.compareByOriginalPositions,\n util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n );\n\n if (index >= 0) {\n var mapping = this._originalMappings[index];\n\n if (mapping.source === needle.source) {\n return {\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n };\n }\n }\n\n return {\n line: null,\n column: null,\n lastColumn: null\n };\n };\n\nexports.BasicSourceMapConsumer = BasicSourceMapConsumer;\n\n/**\n * An IndexedSourceMapConsumer instance represents a parsed source map which\n * we can query for information. It differs from BasicSourceMapConsumer in\n * that it takes \"indexed\" source maps (i.e. ones with a \"sections\" field) as\n * input.\n *\n * The only parameter is a raw source map (either as a JSON string, or already\n * parsed to an object). According to the spec for indexed source maps, they\n * have the following attributes:\n *\n * - version: Which version of the source map spec this map is following.\n * - file: Optional. The generated file this source map is associated with.\n * - sections: A list of section definitions.\n *\n * Each value under the \"sections\" field has two fields:\n * - offset: The offset into the original specified at which this section\n * begins to apply, defined as an object with a \"line\" and \"column\"\n * field.\n * - map: A source map definition. This source map could also be indexed,\n * but doesn't have to be.\n *\n * Instead of the \"map\" field, it's also possible to have a \"url\" field\n * specifying a URL to retrieve a source map from, but that's currently\n * unsupported.\n *\n * Here's an example source map, taken from the source map spec[0], but\n * modified to omit a section which uses the \"url\" field.\n *\n * {\n * version : 3,\n * file: \"app.js\",\n * sections: [{\n * offset: {line:100, column:10},\n * map: {\n * version : 3,\n * file: \"section.js\",\n * sources: [\"foo.js\", \"bar.js\"],\n * names: [\"src\", \"maps\", \"are\", \"fun\"],\n * mappings: \"AAAA,E;;ABCDE;\"\n * }\n * }],\n * }\n *\n * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt\n */\nfunction IndexedSourceMapConsumer(aSourceMap) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = JSON.parse(aSourceMap.replace(/^\\)\\]\\}'/, ''));\n }\n\n var version = util.getArg(sourceMap, 'version');\n var sections = util.getArg(sourceMap, 'sections');\n\n if (version != this._version) {\n throw new Error('Unsupported version: ' + version);\n }\n\n this._sources = new ArraySet();\n this._names = new ArraySet();\n\n var lastOffset = {\n line: -1,\n column: 0\n };\n this._sections = sections.map(function (s) {\n if (s.url) {\n // The url field will require support for asynchronicity.\n // See https://github.com/mozilla/source-map/issues/16\n throw new Error('Support for url field in sections not implemented.');\n }\n var offset = util.getArg(s, 'offset');\n var offsetLine = util.getArg(offset, 'line');\n var offsetColumn = util.getArg(offset, 'column');\n\n if (offsetLine < lastOffset.line ||\n (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {\n throw new Error('Section offsets must be ordered and non-overlapping.');\n }\n lastOffset = offset;\n\n return {\n generatedOffset: {\n // The offset fields are 0-based, but we use 1-based indices when\n // encoding/decoding from VLQ.\n generatedLine: offsetLine + 1,\n generatedColumn: offsetColumn + 1\n },\n consumer: new SourceMapConsumer(util.getArg(s, 'map'))\n }\n });\n}\n\nIndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\nIndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nIndexedSourceMapConsumer.prototype._version = 3;\n\n/**\n * The list of original sources.\n */\nObject.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {\n get: function () {\n var sources = [];\n for (var i = 0; i < this._sections.length; i++) {\n for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {\n sources.push(this._sections[i].consumer.sources[j]);\n }\n }\n return sources;\n }\n});\n\n/**\n * Returns the original source, line, and column information for the generated\n * source's line and column positions provided. The only argument is an object\n * with the following properties:\n *\n * - line: The line number in the generated source.\n * - column: The column number in the generated source.\n *\n * and an object is returned with the following properties:\n *\n * - source: The original source file, or null.\n * - line: The line number in the original source, or null.\n * - column: The column number in the original source, or null.\n * - name: The original identifier, or null.\n */\nIndexedSourceMapConsumer.prototype.originalPositionFor =\n function IndexedSourceMapConsumer_originalPositionFor(aArgs) {\n var needle = {\n generatedLine: util.getArg(aArgs, 'line'),\n generatedColumn: util.getArg(aArgs, 'column')\n };\n\n // Find the section containing the generated position we're trying to map\n // to an original position.\n var sectionIndex = binarySearch.search(needle, this._sections,\n function(needle, section) {\n var cmp = needle.generatedLine - section.generatedOffset.generatedLine;\n if (cmp) {\n return cmp;\n }\n\n return (needle.generatedColumn -\n section.generatedOffset.generatedColumn);\n });\n var section = this._sections[sectionIndex];\n\n if (!section) {\n return {\n source: null,\n line: null,\n column: null,\n name: null\n };\n }\n\n return section.consumer.originalPositionFor({\n line: needle.generatedLine -\n (section.generatedOffset.generatedLine - 1),\n column: needle.generatedColumn -\n (section.generatedOffset.generatedLine === needle.generatedLine\n ? section.generatedOffset.generatedColumn - 1\n : 0),\n bias: aArgs.bias\n });\n };\n\n/**\n * Return true if we have the source content for every source in the source\n * map, false otherwise.\n */\nIndexedSourceMapConsumer.prototype.hasContentsOfAllSources =\n function IndexedSourceMapConsumer_hasContentsOfAllSources() {\n return this._sections.every(function (s) {\n return s.consumer.hasContentsOfAllSources();\n });\n };\n\n/**\n * Returns the original source content. The only argument is the url of the\n * original source file. Returns null if no original source content is\n * available.\n */\nIndexedSourceMapConsumer.prototype.sourceContentFor =\n function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n\n var content = section.consumer.sourceContentFor(aSource, true);\n if (content) {\n return content;\n }\n }\n if (nullOnMissing) {\n return null;\n }\n else {\n throw new Error('\"' + aSource + '\" is not in the SourceMap.');\n }\n };\n\n/**\n * Returns the generated line and column information for the original source,\n * line, and column positions provided. The only argument is an object with\n * the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source.\n * - column: The column number in the original source.\n *\n * and an object is returned with the following properties:\n *\n * - line: The line number in the generated source, or null.\n * - column: The column number in the generated source, or null.\n */\nIndexedSourceMapConsumer.prototype.generatedPositionFor =\n function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n\n // Only consider this section if the requested source is in the list of\n // sources of the consumer.\n if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) {\n continue;\n }\n var generatedPosition = section.consumer.generatedPositionFor(aArgs);\n if (generatedPosition) {\n var ret = {\n line: generatedPosition.line +\n (section.generatedOffset.generatedLine - 1),\n column: generatedPosition.column +\n (section.generatedOffset.generatedLine === generatedPosition.line\n ? section.generatedOffset.generatedColumn - 1\n : 0)\n };\n return ret;\n }\n }\n\n return {\n line: null,\n column: null\n };\n };\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nIndexedSourceMapConsumer.prototype._parseMappings =\n function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n this.__generatedMappings = [];\n this.__originalMappings = [];\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n var sectionMappings = section.consumer._generatedMappings;\n for (var j = 0; j < sectionMappings.length; j++) {\n var mapping = sectionMappings[j];\n\n var source = section.consumer._sources.at(mapping.source);\n if (section.consumer.sourceRoot !== null) {\n source = util.join(section.consumer.sourceRoot, source);\n }\n this._sources.add(source);\n source = this._sources.indexOf(source);\n\n var name = section.consumer._names.at(mapping.name);\n this._names.add(name);\n name = this._names.indexOf(name);\n\n // The mappings coming from the consumer for the section have\n // generated positions relative to the start of the section, so we\n // need to offset them to be relative to the start of the concatenated\n // generated file.\n var adjustedMapping = {\n source: source,\n generatedLine: mapping.generatedLine +\n (section.generatedOffset.generatedLine - 1),\n generatedColumn: mapping.generatedColumn +\n (section.generatedOffset.generatedLine === mapping.generatedLine\n ? section.generatedOffset.generatedColumn - 1\n : 0),\n originalLine: mapping.originalLine,\n originalColumn: mapping.originalColumn,\n name: name\n };\n\n this.__generatedMappings.push(adjustedMapping);\n if (typeof adjustedMapping.originalLine === 'number') {\n this.__originalMappings.push(adjustedMapping);\n }\n }\n }\n\n quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);\n quickSort(this.__originalMappings, util.compareByOriginalPositions);\n };\n\nexports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar base64VLQ = require('./base64-vlq');\nvar util = require('./util');\nvar ArraySet = require('./array-set').ArraySet;\nvar MappingList = require('./mapping-list').MappingList;\n\n/**\n * An instance of the SourceMapGenerator represents a source map which is\n * being built incrementally. You may pass an object with the following\n * properties:\n *\n * - file: The filename of the generated source.\n * - sourceRoot: A root for all relative URLs in this source map.\n */\nfunction SourceMapGenerator(aArgs) {\n if (!aArgs) {\n aArgs = {};\n }\n this._file = util.getArg(aArgs, 'file', null);\n this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);\n this._skipValidation = util.getArg(aArgs, 'skipValidation', false);\n this._sources = new ArraySet();\n this._names = new ArraySet();\n this._mappings = new MappingList();\n this._sourcesContents = null;\n}\n\nSourceMapGenerator.prototype._version = 3;\n\n/**\n * Creates a new SourceMapGenerator based on a SourceMapConsumer\n *\n * @param aSourceMapConsumer The SourceMap.\n */\nSourceMapGenerator.fromSourceMap =\n function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {\n var sourceRoot = aSourceMapConsumer.sourceRoot;\n var generator = new SourceMapGenerator({\n file: aSourceMapConsumer.file,\n sourceRoot: sourceRoot\n });\n aSourceMapConsumer.eachMapping(function (mapping) {\n var newMapping = {\n generated: {\n line: mapping.generatedLine,\n column: mapping.generatedColumn\n }\n };\n\n if (mapping.source != null) {\n newMapping.source = mapping.source;\n if (sourceRoot != null) {\n newMapping.source = util.relative(sourceRoot, newMapping.source);\n }\n\n newMapping.original = {\n line: mapping.originalLine,\n column: mapping.originalColumn\n };\n\n if (mapping.name != null) {\n newMapping.name = mapping.name;\n }\n }\n\n generator.addMapping(newMapping);\n });\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n generator.setSourceContent(sourceFile, content);\n }\n });\n return generator;\n };\n\n/**\n * Add a single mapping from original source line and column to the generated\n * source's line and column for this source map being created. The mapping\n * object should have the following properties:\n *\n * - generated: An object with the generated line and column positions.\n * - original: An object with the original line and column positions.\n * - source: The original source file (relative to the sourceRoot).\n * - name: An optional original token name for this mapping.\n */\nSourceMapGenerator.prototype.addMapping =\n function SourceMapGenerator_addMapping(aArgs) {\n var generated = util.getArg(aArgs, 'generated');\n var original = util.getArg(aArgs, 'original', null);\n var source = util.getArg(aArgs, 'source', null);\n var name = util.getArg(aArgs, 'name', null);\n\n if (!this._skipValidation) {\n this._validateMapping(generated, original, source, name);\n }\n\n if (source != null) {\n source = String(source);\n if (!this._sources.has(source)) {\n this._sources.add(source);\n }\n }\n\n if (name != null) {\n name = String(name);\n if (!this._names.has(name)) {\n this._names.add(name);\n }\n }\n\n this._mappings.add({\n generatedLine: generated.line,\n generatedColumn: generated.column,\n originalLine: original != null && original.line,\n originalColumn: original != null && original.column,\n source: source,\n name: name\n });\n };\n\n/**\n * Set the source content for a source file.\n */\nSourceMapGenerator.prototype.setSourceContent =\n function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {\n var source = aSourceFile;\n if (this._sourceRoot != null) {\n source = util.relative(this._sourceRoot, source);\n }\n\n if (aSourceContent != null) {\n // Add the source content to the _sourcesContents map.\n // Create a new _sourcesContents map if the property is null.\n if (!this._sourcesContents) {\n this._sourcesContents = Object.create(null);\n }\n this._sourcesContents[util.toSetString(source)] = aSourceContent;\n } else if (this._sourcesContents) {\n // Remove the source file from the _sourcesContents map.\n // If the _sourcesContents map is empty, set the property to null.\n delete this._sourcesContents[util.toSetString(source)];\n if (Object.keys(this._sourcesContents).length === 0) {\n this._sourcesContents = null;\n }\n }\n };\n\n/**\n * Applies the mappings of a sub-source-map for a specific source file to the\n * source map being generated. Each mapping to the supplied source file is\n * rewritten using the supplied source map. Note: The resolution for the\n * resulting mappings is the minimium of this map and the supplied map.\n *\n * @param aSourceMapConsumer The source map to be applied.\n * @param aSourceFile Optional. The filename of the source file.\n * If omitted, SourceMapConsumer's file property will be used.\n * @param aSourceMapPath Optional. The dirname of the path to the source map\n * to be applied. If relative, it is relative to the SourceMapConsumer.\n * This parameter is needed when the two source maps aren't in the same\n * directory, and the source map to be applied contains relative source\n * paths. If so, those relative source paths need to be rewritten\n * relative to the SourceMapGenerator.\n */\nSourceMapGenerator.prototype.applySourceMap =\n function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {\n var sourceFile = aSourceFile;\n // If aSourceFile is omitted, we will use the file property of the SourceMap\n if (aSourceFile == null) {\n if (aSourceMapConsumer.file == null) {\n throw new Error(\n 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +\n 'or the source map\\'s \"file\" property. Both were omitted.'\n );\n }\n sourceFile = aSourceMapConsumer.file;\n }\n var sourceRoot = this._sourceRoot;\n // Make \"sourceFile\" relative if an absolute Url is passed.\n if (sourceRoot != null) {\n sourceFile = util.relative(sourceRoot, sourceFile);\n }\n // Applying the SourceMap can add and remove items from the sources and\n // the names array.\n var newSources = new ArraySet();\n var newNames = new ArraySet();\n\n // Find mappings for the \"sourceFile\"\n this._mappings.unsortedForEach(function (mapping) {\n if (mapping.source === sourceFile && mapping.originalLine != null) {\n // Check if it can be mapped by the source map, then update the mapping.\n var original = aSourceMapConsumer.originalPositionFor({\n line: mapping.originalLine,\n column: mapping.originalColumn\n });\n if (original.source != null) {\n // Copy mapping\n mapping.source = original.source;\n if (aSourceMapPath != null) {\n mapping.source = util.join(aSourceMapPath, mapping.source)\n }\n if (sourceRoot != null) {\n mapping.source = util.relative(sourceRoot, mapping.source);\n }\n mapping.originalLine = original.line;\n mapping.originalColumn = original.column;\n if (original.name != null) {\n mapping.name = original.name;\n }\n }\n }\n\n var source = mapping.source;\n if (source != null && !newSources.has(source)) {\n newSources.add(source);\n }\n\n var name = mapping.name;\n if (name != null && !newNames.has(name)) {\n newNames.add(name);\n }\n\n }, this);\n this._sources = newSources;\n this._names = newNames;\n\n // Copy sourcesContents of applied map.\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n if (aSourceMapPath != null) {\n sourceFile = util.join(aSourceMapPath, sourceFile);\n }\n if (sourceRoot != null) {\n sourceFile = util.relative(sourceRoot, sourceFile);\n }\n this.setSourceContent(sourceFile, content);\n }\n }, this);\n };\n\n/**\n * A mapping can have one of the three levels of data:\n *\n * 1. Just the generated position.\n * 2. The Generated position, original position, and original source.\n * 3. Generated and original position, original source, as well as a name\n * token.\n *\n * To maintain consistency, we validate that any new mapping being added falls\n * in to one of these categories.\n */\nSourceMapGenerator.prototype._validateMapping =\n function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,\n aName) {\n // When aOriginal is truthy but has empty values for .line and .column,\n // it is most likely a programmer error. In this case we throw a very\n // specific error message to try to guide them the right way.\n // For example: https://github.com/Polymer/polymer-bundler/pull/519\n if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {\n throw new Error(\n 'original.line and original.column are not numbers -- you probably meant to omit ' +\n 'the original mapping entirely and only map the generated position. If so, pass ' +\n 'null for the original mapping instead of an object with empty or null values.'\n );\n }\n\n if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n && aGenerated.line > 0 && aGenerated.column >= 0\n && !aOriginal && !aSource && !aName) {\n // Case 1.\n return;\n }\n else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n && aOriginal && 'line' in aOriginal && 'column' in aOriginal\n && aGenerated.line > 0 && aGenerated.column >= 0\n && aOriginal.line > 0 && aOriginal.column >= 0\n && aSource) {\n // Cases 2 and 3.\n return;\n }\n else {\n throw new Error('Invalid mapping: ' + JSON.stringify({\n generated: aGenerated,\n source: aSource,\n original: aOriginal,\n name: aName\n }));\n }\n };\n\n/**\n * Serialize the accumulated mappings in to the stream of base 64 VLQs\n * specified by the source map format.\n */\nSourceMapGenerator.prototype._serializeMappings =\n function SourceMapGenerator_serializeMappings() {\n var previousGeneratedColumn = 0;\n var previousGeneratedLine = 1;\n var previousOriginalColumn = 0;\n var previousOriginalLine = 0;\n var previousName = 0;\n var previousSource = 0;\n var result = '';\n var next;\n var mapping;\n var nameIdx;\n var sourceIdx;\n\n var mappings = this._mappings.toArray();\n for (var i = 0, len = mappings.length; i < len; i++) {\n mapping = mappings[i];\n next = ''\n\n if (mapping.generatedLine !== previousGeneratedLine) {\n previousGeneratedColumn = 0;\n while (mapping.generatedLine !== previousGeneratedLine) {\n next += ';';\n previousGeneratedLine++;\n }\n }\n else {\n if (i > 0) {\n if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {\n continue;\n }\n next += ',';\n }\n }\n\n next += base64VLQ.encode(mapping.generatedColumn\n - previousGeneratedColumn);\n previousGeneratedColumn = mapping.generatedColumn;\n\n if (mapping.source != null) {\n sourceIdx = this._sources.indexOf(mapping.source);\n next += base64VLQ.encode(sourceIdx - previousSource);\n previousSource = sourceIdx;\n\n // lines are stored 0-based in SourceMap spec version 3\n next += base64VLQ.encode(mapping.originalLine - 1\n - previousOriginalLine);\n previousOriginalLine = mapping.originalLine - 1;\n\n next += base64VLQ.encode(mapping.originalColumn\n - previousOriginalColumn);\n previousOriginalColumn = mapping.originalColumn;\n\n if (mapping.name != null) {\n nameIdx = this._names.indexOf(mapping.name);\n next += base64VLQ.encode(nameIdx - previousName);\n previousName = nameIdx;\n }\n }\n\n result += next;\n }\n\n return result;\n };\n\nSourceMapGenerator.prototype._generateSourcesContent =\n function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {\n return aSources.map(function (source) {\n if (!this._sourcesContents) {\n return null;\n }\n if (aSourceRoot != null) {\n source = util.relative(aSourceRoot, source);\n }\n var key = util.toSetString(source);\n return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)\n ? this._sourcesContents[key]\n : null;\n }, this);\n };\n\n/**\n * Externalize the source map.\n */\nSourceMapGenerator.prototype.toJSON =\n function SourceMapGenerator_toJSON() {\n var map = {\n version: this._version,\n sources: this._sources.toArray(),\n names: this._names.toArray(),\n mappings: this._serializeMappings()\n };\n if (this._file != null) {\n map.file = this._file;\n }\n if (this._sourceRoot != null) {\n map.sourceRoot = this._sourceRoot;\n }\n if (this._sourcesContents) {\n map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);\n }\n\n return map;\n };\n\n/**\n * Render the source map being generated to a string.\n */\nSourceMapGenerator.prototype.toString =\n function SourceMapGenerator_toString() {\n return JSON.stringify(this.toJSON());\n };\n\nexports.SourceMapGenerator = SourceMapGenerator;\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar SourceMapGenerator = require('./source-map-generator').SourceMapGenerator;\nvar util = require('./util');\n\n// Matches a Windows-style `\\r\\n` newline or a `\\n` newline used by all other\n// operating systems these days (capturing the result).\nvar REGEX_NEWLINE = /(\\r?\\n)/;\n\n// Newline character code for charCodeAt() comparisons\nvar NEWLINE_CODE = 10;\n\n// Private symbol for identifying `SourceNode`s when multiple versions of\n// the source-map library are loaded. This MUST NOT CHANGE across\n// versions!\nvar isSourceNode = \"$$$isSourceNode$$$\";\n\n/**\n * SourceNodes provide a way to abstract over interpolating/concatenating\n * snippets of generated JavaScript source code while maintaining the line and\n * column information associated with the original source code.\n *\n * @param aLine The original line number.\n * @param aColumn The original column number.\n * @param aSource The original source's filename.\n * @param aChunks Optional. An array of strings which are snippets of\n * generated JS, or other SourceNodes.\n * @param aName The original identifier.\n */\nfunction SourceNode(aLine, aColumn, aSource, aChunks, aName) {\n this.children = [];\n this.sourceContents = {};\n this.line = aLine == null ? null : aLine;\n this.column = aColumn == null ? null : aColumn;\n this.source = aSource == null ? null : aSource;\n this.name = aName == null ? null : aName;\n this[isSourceNode] = true;\n if (aChunks != null) this.add(aChunks);\n}\n\n/**\n * Creates a SourceNode from generated code and a SourceMapConsumer.\n *\n * @param aGeneratedCode The generated code\n * @param aSourceMapConsumer The SourceMap for the generated code\n * @param aRelativePath Optional. The path that relative sources in the\n * SourceMapConsumer should be relative to.\n */\nSourceNode.fromStringWithSourceMap =\n function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {\n // The SourceNode we want to fill with the generated code\n // and the SourceMap\n var node = new SourceNode();\n\n // All even indices of this array are one line of the generated code,\n // while all odd indices are the newlines between two adjacent lines\n // (since `REGEX_NEWLINE` captures its match).\n // Processed fragments are accessed by calling `shiftNextLine`.\n var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);\n var remainingLinesIndex = 0;\n var shiftNextLine = function() {\n var lineContents = getNextLine();\n // The last line of a file might not have a newline.\n var newLine = getNextLine() || \"\";\n return lineContents + newLine;\n\n function getNextLine() {\n return remainingLinesIndex < remainingLines.length ?\n remainingLines[remainingLinesIndex++] : undefined;\n }\n };\n\n // We need to remember the position of \"remainingLines\"\n var lastGeneratedLine = 1, lastGeneratedColumn = 0;\n\n // The generate SourceNodes we need a code range.\n // To extract it current and last mapping is used.\n // Here we store the last mapping.\n var lastMapping = null;\n\n aSourceMapConsumer.eachMapping(function (mapping) {\n if (lastMapping !== null) {\n // We add the code from \"lastMapping\" to \"mapping\":\n // First check if there is a new line in between.\n if (lastGeneratedLine < mapping.generatedLine) {\n // Associate first line with \"lastMapping\"\n addMappingWithCode(lastMapping, shiftNextLine());\n lastGeneratedLine++;\n lastGeneratedColumn = 0;\n // The remaining code is added without mapping\n } else {\n // There is no new line in between.\n // Associate the code between \"lastGeneratedColumn\" and\n // \"mapping.generatedColumn\" with \"lastMapping\"\n var nextLine = remainingLines[remainingLinesIndex];\n var code = nextLine.substr(0, mapping.generatedColumn -\n lastGeneratedColumn);\n remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -\n lastGeneratedColumn);\n lastGeneratedColumn = mapping.generatedColumn;\n addMappingWithCode(lastMapping, code);\n // No more remaining code, continue\n lastMapping = mapping;\n return;\n }\n }\n // We add the generated code until the first mapping\n // to the SourceNode without any mapping.\n // Each line is added as separate string.\n while (lastGeneratedLine < mapping.generatedLine) {\n node.add(shiftNextLine());\n lastGeneratedLine++;\n }\n if (lastGeneratedColumn < mapping.generatedColumn) {\n var nextLine = remainingLines[remainingLinesIndex];\n node.add(nextLine.substr(0, mapping.generatedColumn));\n remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);\n lastGeneratedColumn = mapping.generatedColumn;\n }\n lastMapping = mapping;\n }, this);\n // We have processed all mappings.\n if (remainingLinesIndex < remainingLines.length) {\n if (lastMapping) {\n // Associate the remaining code in the current line with \"lastMapping\"\n addMappingWithCode(lastMapping, shiftNextLine());\n }\n // and add the remaining lines without any mapping\n node.add(remainingLines.splice(remainingLinesIndex).join(\"\"));\n }\n\n // Copy sourcesContent into SourceNode\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n if (aRelativePath != null) {\n sourceFile = util.join(aRelativePath, sourceFile);\n }\n node.setSourceContent(sourceFile, content);\n }\n });\n\n return node;\n\n function addMappingWithCode(mapping, code) {\n if (mapping === null || mapping.source === undefined) {\n node.add(code);\n } else {\n var source = aRelativePath\n ? util.join(aRelativePath, mapping.source)\n : mapping.source;\n node.add(new SourceNode(mapping.originalLine,\n mapping.originalColumn,\n source,\n code,\n mapping.name));\n }\n }\n };\n\n/**\n * Add a chunk of generated JS to this source node.\n *\n * @param aChunk A string snippet of generated JS code, another instance of\n * SourceNode, or an array where each member is one of those things.\n */\nSourceNode.prototype.add = function SourceNode_add(aChunk) {\n if (Array.isArray(aChunk)) {\n aChunk.forEach(function (chunk) {\n this.add(chunk);\n }, this);\n }\n else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n if (aChunk) {\n this.children.push(aChunk);\n }\n }\n else {\n throw new TypeError(\n \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n );\n }\n return this;\n};\n\n/**\n * Add a chunk of generated JS to the beginning of this source node.\n *\n * @param aChunk A string snippet of generated JS code, another instance of\n * SourceNode, or an array where each member is one of those things.\n */\nSourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {\n if (Array.isArray(aChunk)) {\n for (var i = aChunk.length-1; i >= 0; i--) {\n this.prepend(aChunk[i]);\n }\n }\n else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n this.children.unshift(aChunk);\n }\n else {\n throw new TypeError(\n \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n );\n }\n return this;\n};\n\n/**\n * Walk over the tree of JS snippets in this node and its children. The\n * walking function is called once for each snippet of JS and is passed that\n * snippet and the its original associated source's line/column location.\n *\n * @param aFn The traversal function.\n */\nSourceNode.prototype.walk = function SourceNode_walk(aFn) {\n var chunk;\n for (var i = 0, len = this.children.length; i < len; i++) {\n chunk = this.children[i];\n if (chunk[isSourceNode]) {\n chunk.walk(aFn);\n }\n else {\n if (chunk !== '') {\n aFn(chunk, { source: this.source,\n line: this.line,\n column: this.column,\n name: this.name });\n }\n }\n }\n};\n\n/**\n * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between\n * each of `this.children`.\n *\n * @param aSep The separator.\n */\nSourceNode.prototype.join = function SourceNode_join(aSep) {\n var newChildren;\n var i;\n var len = this.children.length;\n if (len > 0) {\n newChildren = [];\n for (i = 0; i < len-1; i++) {\n newChildren.push(this.children[i]);\n newChildren.push(aSep);\n }\n newChildren.push(this.children[i]);\n this.children = newChildren;\n }\n return this;\n};\n\n/**\n * Call String.prototype.replace on the very right-most source snippet. Useful\n * for trimming whitespace from the end of a source node, etc.\n *\n * @param aPattern The pattern to replace.\n * @param aReplacement The thing to replace the pattern with.\n */\nSourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {\n var lastChild = this.children[this.children.length - 1];\n if (lastChild[isSourceNode]) {\n lastChild.replaceRight(aPattern, aReplacement);\n }\n else if (typeof lastChild === 'string') {\n this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);\n }\n else {\n this.children.push(''.replace(aPattern, aReplacement));\n }\n return this;\n};\n\n/**\n * Set the source content for a source file. This will be added to the SourceMapGenerator\n * in the sourcesContent field.\n *\n * @param aSourceFile The filename of the source file\n * @param aSourceContent The content of the source file\n */\nSourceNode.prototype.setSourceContent =\n function SourceNode_setSourceContent(aSourceFile, aSourceContent) {\n this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;\n };\n\n/**\n * Walk over the tree of SourceNodes. The walking function is called for each\n * source file content and is passed the filename and source content.\n *\n * @param aFn The traversal function.\n */\nSourceNode.prototype.walkSourceContents =\n function SourceNode_walkSourceContents(aFn) {\n for (var i = 0, len = this.children.length; i < len; i++) {\n if (this.children[i][isSourceNode]) {\n this.children[i].walkSourceContents(aFn);\n }\n }\n\n var sources = Object.keys(this.sourceContents);\n for (var i = 0, len = sources.length; i < len; i++) {\n aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);\n }\n };\n\n/**\n * Return the string representation of this source node. Walks over the tree\n * and concatenates all the various snippets together to one string.\n */\nSourceNode.prototype.toString = function SourceNode_toString() {\n var str = \"\";\n this.walk(function (chunk) {\n str += chunk;\n });\n return str;\n};\n\n/**\n * Returns the string representation of this source node along with a source\n * map.\n */\nSourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {\n var generated = {\n code: \"\",\n line: 1,\n column: 0\n };\n var map = new SourceMapGenerator(aArgs);\n var sourceMappingActive = false;\n var lastOriginalSource = null;\n var lastOriginalLine = null;\n var lastOriginalColumn = null;\n var lastOriginalName = null;\n this.walk(function (chunk, original) {\n generated.code += chunk;\n if (original.source !== null\n && original.line !== null\n && original.column !== null) {\n if(lastOriginalSource !== original.source\n || lastOriginalLine !== original.line\n || lastOriginalColumn !== original.column\n || lastOriginalName !== original.name) {\n map.addMapping({\n source: original.source,\n original: {\n line: original.line,\n column: original.column\n },\n generated: {\n line: generated.line,\n column: generated.column\n },\n name: original.name\n });\n }\n lastOriginalSource = original.source;\n lastOriginalLine = original.line;\n lastOriginalColumn = original.column;\n lastOriginalName = original.name;\n sourceMappingActive = true;\n } else if (sourceMappingActive) {\n map.addMapping({\n generated: {\n line: generated.line,\n column: generated.column\n }\n });\n lastOriginalSource = null;\n sourceMappingActive = false;\n }\n for (var idx = 0, length = chunk.length; idx < length; idx++) {\n if (chunk.charCodeAt(idx) === NEWLINE_CODE) {\n generated.line++;\n generated.column = 0;\n // Mappings end at eol\n if (idx + 1 === length) {\n lastOriginalSource = null;\n sourceMappingActive = false;\n } else if (sourceMappingActive) {\n map.addMapping({\n source: original.source,\n original: {\n line: original.line,\n column: original.column\n },\n generated: {\n line: generated.line,\n column: generated.column\n },\n name: original.name\n });\n }\n } else {\n generated.column++;\n }\n }\n });\n this.walkSourceContents(function (sourceFile, sourceContent) {\n map.setSourceContent(sourceFile, sourceContent);\n });\n\n return { code: generated.code, map: map };\n};\n\nexports.SourceNode = SourceNode;\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\n/**\n * This is a helper function for getting values from parameter/options\n * objects.\n *\n * @param args The object we are extracting values from\n * @param name The name of the property we are getting.\n * @param defaultValue An optional value to return if the property is missing\n * from the object. If this is not specified and the property is missing, an\n * error will be thrown.\n */\nfunction getArg(aArgs, aName, aDefaultValue) {\n if (aName in aArgs) {\n return aArgs[aName];\n } else if (arguments.length === 3) {\n return aDefaultValue;\n } else {\n throw new Error('\"' + aName + '\" is a required argument.');\n }\n}\nexports.getArg = getArg;\n\nvar urlRegexp = /^(?:([\\w+\\-.]+):)?\\/\\/(?:(\\w+:\\w+)@)?([\\w.]*)(?::(\\d+))?(\\S*)$/;\nvar dataUrlRegexp = /^data:.+\\,.+$/;\n\nfunction urlParse(aUrl) {\n var match = aUrl.match(urlRegexp);\n if (!match) {\n return null;\n }\n return {\n scheme: match[1],\n auth: match[2],\n host: match[3],\n port: match[4],\n path: match[5]\n };\n}\nexports.urlParse = urlParse;\n\nfunction urlGenerate(aParsedUrl) {\n var url = '';\n if (aParsedUrl.scheme) {\n url += aParsedUrl.scheme + ':';\n }\n url += '//';\n if (aParsedUrl.auth) {\n url += aParsedUrl.auth + '@';\n }\n if (aParsedUrl.host) {\n url += aParsedUrl.host;\n }\n if (aParsedUrl.port) {\n url += \":\" + aParsedUrl.port\n }\n if (aParsedUrl.path) {\n url += aParsedUrl.path;\n }\n return url;\n}\nexports.urlGenerate = urlGenerate;\n\n/**\n * Normalizes a path, or the path portion of a URL:\n *\n * - Replaces consecutive slashes with one slash.\n * - Removes unnecessary '.' parts.\n * - Removes unnecessary '/..' parts.\n *\n * Based on code in the Node.js 'path' core module.\n *\n * @param aPath The path or url to normalize.\n */\nfunction normalize(aPath) {\n var path = aPath;\n var url = urlParse(aPath);\n if (url) {\n if (!url.path) {\n return aPath;\n }\n path = url.path;\n }\n var isAbsolute = exports.isAbsolute(path);\n\n var parts = path.split(/\\/+/);\n for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {\n part = parts[i];\n if (part === '.') {\n parts.splice(i, 1);\n } else if (part === '..') {\n up++;\n } else if (up > 0) {\n if (part === '') {\n // The first part is blank if the path is absolute. Trying to go\n // above the root is a no-op. Therefore we can remove all '..' parts\n // directly after the root.\n parts.splice(i + 1, up);\n up = 0;\n } else {\n parts.splice(i, 2);\n up--;\n }\n }\n }\n path = parts.join('/');\n\n if (path === '') {\n path = isAbsolute ? '/' : '.';\n }\n\n if (url) {\n url.path = path;\n return urlGenerate(url);\n }\n return path;\n}\nexports.normalize = normalize;\n\n/**\n * Joins two paths/URLs.\n *\n * @param aRoot The root path or URL.\n * @param aPath The path or URL to be joined with the root.\n *\n * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a\n * scheme-relative URL: Then the scheme of aRoot, if any, is prepended\n * first.\n * - Otherwise aPath is a path. If aRoot is a URL, then its path portion\n * is updated with the result and aRoot is returned. Otherwise the result\n * is returned.\n * - If aPath is absolute, the result is aPath.\n * - Otherwise the two paths are joined with a slash.\n * - Joining for example 'http://' and 'www.example.com' is also supported.\n */\nfunction join(aRoot, aPath) {\n if (aRoot === \"\") {\n aRoot = \".\";\n }\n if (aPath === \"\") {\n aPath = \".\";\n }\n var aPathUrl = urlParse(aPath);\n var aRootUrl = urlParse(aRoot);\n if (aRootUrl) {\n aRoot = aRootUrl.path || '/';\n }\n\n // `join(foo, '//www.example.org')`\n if (aPathUrl && !aPathUrl.scheme) {\n if (aRootUrl) {\n aPathUrl.scheme = aRootUrl.scheme;\n }\n return urlGenerate(aPathUrl);\n }\n\n if (aPathUrl || aPath.match(dataUrlRegexp)) {\n return aPath;\n }\n\n // `join('http://', 'www.example.com')`\n if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {\n aRootUrl.host = aPath;\n return urlGenerate(aRootUrl);\n }\n\n var joined = aPath.charAt(0) === '/'\n ? aPath\n : normalize(aRoot.replace(/\\/+$/, '') + '/' + aPath);\n\n if (aRootUrl) {\n aRootUrl.path = joined;\n return urlGenerate(aRootUrl);\n }\n return joined;\n}\nexports.join = join;\n\nexports.isAbsolute = function (aPath) {\n return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp);\n};\n\n/**\n * Make a path relative to a URL or another path.\n *\n * @param aRoot The root path or URL.\n * @param aPath The path or URL to be made relative to aRoot.\n */\nfunction relative(aRoot, aPath) {\n if (aRoot === \"\") {\n aRoot = \".\";\n }\n\n aRoot = aRoot.replace(/\\/$/, '');\n\n // It is possible for the path to be above the root. In this case, simply\n // checking whether the root is a prefix of the path won't work. Instead, we\n // need to remove components from the root one by one, until either we find\n // a prefix that fits, or we run out of components to remove.\n var level = 0;\n while (aPath.indexOf(aRoot + '/') !== 0) {\n var index = aRoot.lastIndexOf(\"/\");\n if (index < 0) {\n return aPath;\n }\n\n // If the only part of the root that is left is the scheme (i.e. http://,\n // file:///, etc.), one or more slashes (/), or simply nothing at all, we\n // have exhausted all components, so the path is not relative to the root.\n aRoot = aRoot.slice(0, index);\n if (aRoot.match(/^([^\\/]+:\\/)?\\/*$/)) {\n return aPath;\n }\n\n ++level;\n }\n\n // Make sure we add a \"../\" for each component we removed from the root.\n return Array(level + 1).join(\"../\") + aPath.substr(aRoot.length + 1);\n}\nexports.relative = relative;\n\nvar supportsNullProto = (function () {\n var obj = Object.create(null);\n return !('__proto__' in obj);\n}());\n\nfunction identity (s) {\n return s;\n}\n\n/**\n * Because behavior goes wacky when you set `__proto__` on objects, we\n * have to prefix all the strings in our set with an arbitrary character.\n *\n * See https://github.com/mozilla/source-map/pull/31 and\n * https://github.com/mozilla/source-map/issues/30\n *\n * @param String aStr\n */\nfunction toSetString(aStr) {\n if (isProtoString(aStr)) {\n return '$' + aStr;\n }\n\n return aStr;\n}\nexports.toSetString = supportsNullProto ? identity : toSetString;\n\nfunction fromSetString(aStr) {\n if (isProtoString(aStr)) {\n return aStr.slice(1);\n }\n\n return aStr;\n}\nexports.fromSetString = supportsNullProto ? identity : fromSetString;\n\nfunction isProtoString(s) {\n if (!s) {\n return false;\n }\n\n var length = s.length;\n\n if (length < 9 /* \"__proto__\".length */) {\n return false;\n }\n\n if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||\n s.charCodeAt(length - 2) !== 95 /* '_' */ ||\n s.charCodeAt(length - 3) !== 111 /* 'o' */ ||\n s.charCodeAt(length - 4) !== 116 /* 't' */ ||\n s.charCodeAt(length - 5) !== 111 /* 'o' */ ||\n s.charCodeAt(length - 6) !== 114 /* 'r' */ ||\n s.charCodeAt(length - 7) !== 112 /* 'p' */ ||\n s.charCodeAt(length - 8) !== 95 /* '_' */ ||\n s.charCodeAt(length - 9) !== 95 /* '_' */) {\n return false;\n }\n\n for (var i = length - 10; i >= 0; i--) {\n if (s.charCodeAt(i) !== 36 /* '$' */) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Comparator between two mappings where the original positions are compared.\n *\n * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n * mappings with the same original source/line/column, but different generated\n * line and column the same. Useful when searching for a mapping with a\n * stubbed out mapping.\n */\nfunction compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {\n var cmp = mappingA.source - mappingB.source;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0 || onlyCompareOriginal) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n return mappingA.name - mappingB.name;\n}\nexports.compareByOriginalPositions = compareByOriginalPositions;\n\n/**\n * Comparator between two mappings with deflated source and name indices where\n * the generated positions are compared.\n *\n * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n * mappings with the same generated line and column, but different\n * source/name/original line and column the same. Useful when searching for a\n * mapping with a stubbed out mapping.\n */\nfunction compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {\n var cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0 || onlyCompareGenerated) {\n return cmp;\n }\n\n cmp = mappingA.source - mappingB.source;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n return mappingA.name - mappingB.name;\n}\nexports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;\n\nfunction strcmp(aStr1, aStr2) {\n if (aStr1 === aStr2) {\n return 0;\n }\n\n if (aStr1 > aStr2) {\n return 1;\n }\n\n return -1;\n}\n\n/**\n * Comparator between two mappings with inflated source and name strings where\n * the generated positions are compared.\n */\nfunction compareByGeneratedPositionsInflated(mappingA, mappingB) {\n var cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;\n","/*\n * Copyright 2009-2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE.txt or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\nexports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator;\nexports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer;\nexports.SourceNode = require('./lib/source-node').SourceNode;\n","\"use strict\";\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst resource_1 = require(\"./resource\");\nconst runtime = require(\"./runtime\");\nconst utils = require(\"./utils\");\n/**\n * Output helps encode the relationship between Resources in a Pulumi application. Specifically an\n * Output holds onto a piece of Data and the Resource it was generated from. An Output value can\n * then be provided when constructing new Resources, allowing that new Resource to know both the\n * value as well as the Resource the value came from. This allows for a precise 'Resource\n * dependency graph' to be created, which properly tracks the relationship between resources.\n */\nclass OutputImpl {\n /** @internal */\n constructor(resources, promise, isKnown, isSecret, allResources) {\n /**\n * A private field to help with RTTI that works in SxS scenarios.\n *\n * This is internal instead of being truly private, to support mixins and our serialization model.\n * @internal\n */\n // tslint:disable-next-line:variable-name\n this.__pulumiOutput = true;\n // Always create a copy so that no one accidentally modifies our Resource list.\n const resourcesCopy = copyResources(resources);\n // Create a copy of the async resources. Populate this with the sync-resources if that's\n // all we have. That way this is always ensured to be a superset of the list of sync resources.\n allResources = allResources || Promise.resolve([]);\n const allResourcesCopy = allResources.then(r => utils.union(copyResources(r), resourcesCopy));\n // We are only known if we are not explicitly unknown and the resolved value of the output\n // contains no distinguished unknown values.\n isKnown = Promise.all([isKnown, promise]).then(([known, val]) => known && !containsUnknowns(val));\n const lifted = Promise.all([allResourcesCopy, promise, isKnown, isSecret])\n .then(([liftedResources, value, liftedIsKnown, liftedIsSecret]) => liftInnerOutput(liftedResources, value, liftedIsKnown, liftedIsSecret));\n this.resources = () => resourcesCopy;\n this.allResources = () => lifted.then(l => l.allResources);\n this.isKnown = lifted.then(l => l.isKnown);\n this.isSecret = lifted.then(l => l.isSecret);\n this.promise = (withUnknowns) => OutputImpl.getPromisedValue(lifted.then(l => l.value), withUnknowns);\n this.toString = () => {\n const message = `Calling [toString] on an [Output] is not supported.\n\nTo get the value of an Output as an Output consider either:\n1: o.apply(v => \\`prefix\\${v}suffix\\`)\n2: pulumi.interpolate \\`prefix\\${v}suffix\\`\n\nSee https://pulumi.io/help/outputs for more details.\nThis function may throw in a future version of @pulumi/pulumi.`;\n return message;\n };\n this.toJSON = () => {\n const message = `Calling [toJSON] on an [Output] is not supported.\n\nTo get the value of an Output as a JSON value or JSON string consider either:\n 1: o.apply(v => v.toJSON())\n 2: o.apply(v => JSON.stringify(v))\n\nSee https://pulumi.io/help/outputs for more details.\nThis function may throw in a future version of @pulumi/pulumi.`;\n return message;\n };\n return new Proxy(this, {\n get: (obj, prop) => {\n // Recreate the prototype walk to ensure we find any actual members defined directly\n // on `Output`.\n for (let o = obj; o; o = Object.getPrototypeOf(o)) {\n if (o.hasOwnProperty(prop)) {\n return o[prop];\n }\n }\n // Always explicitly fail on a member called 'then'. It is used by other systems to\n // determine if this is a Promise, and we do not want to indicate that that's what\n // we are.\n if (prop === \"then\") {\n return undefined;\n }\n // Do not lift members that start with __. Technically, if all libraries were\n // using this version of pulumi/pulumi we would not need this. However, this is\n // so that downstream consumers can use this version of pulumi/pulumi while also\n // passing these new Outputs to older versions of pulumi/pulumi. The reason this\n // can be a problem is that older versions do an RTTI check that simply asks questions\n // like:\n //\n // Is there a member on this object called '__pulumiResource'\n //\n // If we automatically lift such a member (even if it eventually points to 'undefined'),\n // then those RTTI checks will succeed.\n //\n // Note: this should be safe to not lift as, in general, properties with this prefix\n // are not at all common (and in general are used to represent private things anyway\n // that likely should not be exposed).\n //\n // Similarly, do not respond to the 'doNotCapture' member name. It serves a similar\n // RTTI purpose.\n if (typeof prop === \"string\") {\n if (prop.startsWith(\"__\") || prop === \"doNotCapture\" || prop === \"deploymentOnlyModule\") {\n return undefined;\n }\n }\n // Fail out if we are being accessed using a symbol. Many APIs will access with a\n // well known symbol (like 'Symbol.toPrimitive') to check for the presence of something.\n // They will only check for the existence of that member, and we don't want to make it\n // appear that have those.\n //\n // Another way of putting this is that we only forward 'string/number' members to our\n // underlying value.\n if (typeof prop === \"symbol\") {\n return undefined;\n }\n // Else for *any other* property lookup, succeed the lookup and return a lifted\n // `apply` on the underlying `Output`.\n return obj.apply((ob) => {\n if (ob === undefined || ob === null) {\n return undefined;\n }\n else if (isUnknown(ob)) {\n // If the value of this output is unknown, the result of the access should also be unknown.\n // This is conceptually consistent, and also prevents us from returning a \"known undefined\"\n // value from the `ob[prop]` expression below.\n return exports.unknown;\n }\n return ob[prop];\n }, /*runWithUnknowns:*/ true);\n },\n });\n }\n static create(val) {\n return output(val);\n }\n /**\n * Returns true if the given object is an instance of Output. This is designed to work even when\n * multiple copies of the Pulumi SDK have been loaded into the same process.\n */\n static isInstance(obj) {\n return utils.isInstance(obj, \"__pulumiOutput\");\n }\n /** @internal */\n static getPromisedValue(promise, withUnknowns) {\n return __awaiter(this, void 0, void 0, function* () {\n // If the caller did not explicitly ask to see unknown values and val contains unknowns, return undefined. This\n // preserves compatibility with earlier versions of the Pulumi SDK.\n const val = yield promise;\n if (!withUnknowns && containsUnknowns(val)) {\n return undefined;\n }\n return val;\n });\n }\n get() {\n throw new Error(`Cannot call '.get' during update or preview.\nTo manipulate the value of this Output, use '.apply' instead.`);\n }\n // runWithUnknowns requests that `func` is run even if `isKnown` resolves to `false`. This is used to allow\n // callers to process fully- or partially-unknown values and return a known result. the output proxy takes\n // advantage of this to allow proxied property accesses to return known values even if other properties of\n // the containing object are unknown.\n apply(func, runWithUnknowns) {\n // we're inside the modern `output` code, so it's safe to call `.allResources!` here.\n const applied = Promise.all([this.allResources(), this.promise(/*withUnknowns*/ true), this.isKnown, this.isSecret])\n .then(([allResources, value, isKnown, isSecret]) => applyHelperAsync(allResources, value, isKnown, isSecret, func, !!runWithUnknowns));\n const result = new OutputImpl(this.resources(), applied.then(a => a.value), applied.then(a => a.isKnown), applied.then(a => a.isSecret), applied.then(a => a.allResources));\n return result;\n }\n}\n/** @internal */\nfunction getAllResources(op) {\n return op.allResources instanceof Function\n ? op.allResources()\n : Promise.resolve(op.resources());\n}\nexports.getAllResources = getAllResources;\nfunction copyResources(resources) {\n const copy = Array.isArray(resources) ? new Set(resources) :\n resources instanceof Set ? new Set(resources) :\n new Set([resources]);\n return copy;\n}\nfunction liftInnerOutput(allResources, value, isKnown, isSecret) {\n return __awaiter(this, void 0, void 0, function* () {\n if (!exports.Output.isInstance(value)) {\n // 'value' itself wasn't an output, no need to transform any of the data we got.\n return { allResources, value, isKnown, isSecret };\n }\n // 'value' was an Output. So we unwrap that to get the inner value/isKnown/isSecret/resources\n // returned by that Output and merge with the state passed in to get the state of the final Output.\n // Note: we intentionally await all the promises of the inner output. This way we properly\n // propagate any rejections of any of these promises through the outer output as well.\n const innerValue = yield value.promise(/*withUnknowns*/ true);\n const innerIsKnown = yield value.isKnown;\n const innerIsSecret = yield (value.isSecret || Promise.resolve(false));\n // If we're working with a new-style output, grab all its resources and merge into ours.\n // Otherwise, if this is an old-style output, just grab the resources it was known to have\n // at construction time.\n const innerResources = yield getAllResources(value);\n const totalResources = utils.union(allResources, innerResources);\n return {\n allResources: totalResources,\n value: innerValue,\n isKnown: innerIsKnown,\n isSecret: isSecret || innerIsSecret,\n };\n });\n}\n// tslint:disable:max-line-length\nfunction applyHelperAsync(allResources, value, isKnown, isSecret, func, runWithUnknowns) {\n return __awaiter(this, void 0, void 0, function* () {\n if (runtime.isDryRun()) {\n // During previews only perform the apply if the engine was able to give us an actual value\n // for this Output.\n const applyDuringPreview = isKnown || runWithUnknowns;\n if (!applyDuringPreview) {\n // We didn't actually run the function, our new Output is definitely **not** known.\n return {\n allResources,\n value: undefined,\n isKnown: false,\n isSecret,\n };\n }\n // If we are running with unknown values and the value is explicitly unknown but does not actually\n // contain any unknown values, collapse its value to the unknown value. This ensures that callbacks\n // that expect to see unknowns during preview in outputs that are not known will always do so.\n if (!isKnown && runWithUnknowns && !containsUnknowns(value)) {\n value = exports.unknown;\n }\n }\n const transformed = yield func(value);\n // We successfully ran the inner function. Our new Output should be considered known. We\n // preserve secretness from our original Output to the new one we're creating.\n return liftInnerOutput(allResources, transformed, /*isKnown*/ true, isSecret);\n });\n}\n// Returns an promise denoting if the output is a secret or not. This is not the same as just calling `.isSecret`\n// because in cases where the output does not have a `isSecret` property and it is a Proxy, we need to ignore\n// the isSecret member that the proxy reports back.\n// This calls the public implementation so that we only make any calculations in a single place.\n/** @internal */\nfunction isSecretOutput(o) {\n return isSecret(o);\n}\nexports.isSecretOutput = isSecretOutput;\n// Helper function for `output`. This function trivially recurses through an object, copying it,\n// while also lifting any inner Outputs (with all their respective state) to a top-level Output at\n// the end. If there are no inner outputs, this will not affect the data (except by producing a new\n// copy of it).\n//\n// Importantly:\n//\n// 1. Resources encountered while recursing are not touched. This helps ensure they stay Resources\n// (with an appropriate prototype chain).\n// 2. Primitive values (string, number, etc.) are returned as is.\n// 3. Arrays and Record are recursed into. An Array<...> that contains any Outputs wil become an\n// Output>. A Record that contains any Output values will be an\n// Output>. In both cases of recursion, the outer Output's\n// known/secret/resources will be computed from the nested Outputs.\nfunction outputRec(val) {\n if (val === null || typeof val !== \"object\") {\n // strings, numbers, booleans, functions, symbols, undefineds, nulls are all returned as\n // themselves. They are always 'known' (i.e. we can safely 'apply' off of them even during\n // preview).\n return val;\n }\n else if (resource_1.Resource.isInstance(val)) {\n // Don't unwrap Resources, there are existing codepaths that return Resources through\n // Outputs and we want to preserve them as is when flattening.\n return val;\n }\n else if (isUnknown(val)) {\n return val;\n }\n else if (val instanceof Promise) {\n // Recurse into the value the Promise points to. This may end up producing a\n // Promise. Wrap this in another Output as the final result. This Output's\n // construction will be able to merge the inner Output's data with its own. See\n // liftInnerOutput for more details.\n return createSimpleOutput(val.then(v => outputRec(v)));\n }\n else if (exports.Output.isInstance(val)) {\n // We create a new output here from the raw pieces of the original output in order to\n // accommodate outputs from downlevel SxS SDKs. This ensures that within this package it is\n // safe to assume the implementation of any Output returned by the `output` function.\n //\n // This includes:\n // 1. that first-class unknowns are properly represented in the system: if this was a\n // downlevel output where val.isKnown resolves to false, this guarantees that the\n // returned output's promise resolves to unknown.\n // 2. That the `isSecret` property is available.\n // 3. That the `.allResources` is available.\n const allResources = getAllResources(val);\n const newOutput = new OutputImpl(val.resources(), val.promise(/*withUnknowns*/ true), val.isKnown, val.isSecret, allResources);\n return newOutput.apply(outputRec, /*runWithUnknowns*/ true);\n }\n else if (val instanceof Array) {\n const allValues = [];\n let hasOutputs = false;\n for (const v of val) {\n const ev = outputRec(v);\n allValues.push(ev);\n if (exports.Output.isInstance(ev)) {\n hasOutputs = true;\n }\n }\n // If we didn't encounter any nested Outputs, we don't need to do anything. We can just\n // return this value as is.\n if (!hasOutputs) {\n // Note: we intentionally return 'allValues' here and not 'val'. This ensures we get a\n // copy. This has been behavior we've had since the beginning and there may be subtle\n // logic out there that depends on this that we would not want ot break.\n return allValues;\n }\n // Otherwise, combine the data from all the outputs/non-outputs to one final output.\n const promisedArray = Promise.all(allValues.map(v => getAwaitableValue(v)));\n const [syncResources, isKnown, isSecret, allResources] = getResourcesAndDetails(allValues);\n return new exports.Output(syncResources, promisedArray, isKnown, isSecret, allResources);\n }\n else {\n const promisedValues = [];\n let hasOutputs = false;\n for (const k of Object.keys(val)) {\n const ev = outputRec(val[k]);\n promisedValues.push({ key: k, value: ev });\n if (exports.Output.isInstance(ev)) {\n hasOutputs = true;\n }\n }\n if (!hasOutputs) {\n // Note: we intentionally return a new value here and not 'val'. This ensures we get a\n // copy. This has been behavior we've had since the beginning and there may be subtle\n // logic out there that depends on this that we would not want ot break.\n return promisedValues.reduce((o, kvp) => { o[kvp.key] = kvp.value; return o; }, {});\n }\n const promisedObject = getPromisedObject(promisedValues);\n const [syncResources, isKnown, isSecret, allResources] = getResourcesAndDetails(promisedValues.map(kvp => kvp.value));\n return new exports.Output(syncResources, promisedObject, isKnown, isSecret, allResources);\n }\n}\nfunction output(val) {\n const ov = outputRec(val);\n return exports.Output.isInstance(ov) ? ov : createSimpleOutput(ov);\n}\nexports.output = output;\nfunction secret(val) {\n const o = output(val);\n // we called `output` right above this, so it's safe to call `.allResources` on the result.\n return new exports.Output(o.resources(), o.promise(/*withUnknowns*/ true), o.isKnown, Promise.resolve(true), o.allResources());\n}\nexports.secret = secret;\n/**\n * [unsecret] behaves the same as [output] except the returned output takes the existing output and unwraps the secret\n */\nfunction unsecret(val) {\n return new exports.Output(val.resources(), val.promise(/*withUnknowns*/ true), val.isKnown, Promise.resolve(false), val.allResources());\n}\nexports.unsecret = unsecret;\nfunction isSecret(val) {\n return exports.Output.isInstance(val.isSecret) ? Promise.resolve(false) : val.isSecret;\n}\nexports.isSecret = isSecret;\nfunction createSimpleOutput(val) {\n return new exports.Output(new Set(), val instanceof Promise ? val : Promise.resolve(val), \n /*isKnown*/ Promise.resolve(true), \n /*isSecret */ Promise.resolve(false), Promise.resolve(new Set()));\n}\nfunction all(val) {\n // Our recursive `output` helper already does exactly what `all` needs to do in terms of the\n // implementation. Why have both `output` and `all` then? Currently, to the best of our\n // abilities, we haven't been able to make a single signature for both that can unify tuples and\n // arrays for TypeScript. So `all` is much better when dealing with a tuple of heterogenous\n // values, while `output` is good for everything else.\n //\n // Specifically ``all` can take an `[Output, Output]` and produce an\n // `Output<[string, number]>` However, `output` for that same type will produce an\n // `Output<(string|number)[]>` which is definitely suboptimal.\n return output(val);\n}\nexports.all = all;\nfunction getAwaitableValue(v) {\n if (exports.Output.isInstance(v)) {\n return v.promise(/* withUnknowns */ true);\n }\n else {\n return v;\n }\n}\nfunction getPromisedObject(keysAndOutputs) {\n return __awaiter(this, void 0, void 0, function* () {\n const result = {};\n for (const kvp of keysAndOutputs) {\n result[kvp.key] = yield getAwaitableValue(kvp.value);\n }\n return result;\n });\n}\nfunction getResourcesAndDetails(allValues) {\n const syncResources = new Set();\n const allOutputs = [];\n for (const v of allValues) {\n if (exports.Output.isInstance(v)) {\n allOutputs.push(v);\n for (const res of v.resources()) {\n syncResources.add(res);\n }\n }\n }\n // All the outputs were generated in `function all` using `output(v)`. So it's safe\n // to call `.allResources!` here.\n const allResources = Promise.all(allOutputs.map(o => o.allResources())).then(arr => {\n const result = new Set();\n for (const set of arr) {\n for (const res of set) {\n result.add(res);\n }\n }\n return result;\n });\n // A merged output is known if all of its inputs are known.\n const isKnown = Promise.all(allOutputs.map(o => o.isKnown)).then(ps => ps.every(b => b));\n // A merged output is secret if any of its inputs are secret.\n const isSecret = Promise.all(allOutputs.map(o => isSecretOutput(o))).then(ps => ps.some(b => b));\n return [syncResources, isKnown, isSecret, allResources];\n}\n/**\n * Unknown represents a value that is unknown. These values correspond to unknown property values received from the\n * Pulumi engine as part of the result of a resource registration (see runtime/rpc.ts). User code is not typically\n * exposed to these values: any Output<> that contains an Unknown will itself be unknown, so any user callbacks\n * passed to `apply` will not be run. Internal callers of `apply` can request that they are run even with unknown\n * values; the output proxy takes advantage of this to allow proxied property accesses to return known values even\n * if other properties of the containing object are unknown.\n */\nclass Unknown {\n constructor() {\n /**\n * A private field to help with RTTI that works in SxS scenarios.\n *\n * This is internal instead of being truly private, to support mixins and our serialization model.\n * @internal\n */\n // tslint:disable-next-line:variable-name\n this.__pulumiUnknown = true;\n }\n /**\n * Returns true if the given object is an instance of Unknown. This is designed to work even when\n * multiple copies of the Pulumi SDK have been loaded into the same process.\n */\n static isInstance(obj) {\n return utils.isInstance(obj, \"__pulumiUnknown\");\n }\n}\n/**\n * unknown is the singleton unknown value.\n * @internal\n */\nexports.unknown = new Unknown();\n/**\n * isUnknown returns true if the given value is unknown.\n */\nfunction isUnknown(val) {\n return Unknown.isInstance(val);\n}\nexports.isUnknown = isUnknown;\n/**\n * containsUnknowns returns true if the given value is or contains unknown values.\n */\nfunction containsUnknowns(value) {\n return impl(value, new Set());\n function impl(val, seen) {\n if (val === null || typeof val !== \"object\") {\n return false;\n }\n else if (isUnknown(val)) {\n return true;\n }\n else if (seen.has(val)) {\n return false;\n }\n seen.add(val);\n if (val instanceof Array) {\n return val.some(e => impl(e, seen));\n }\n else {\n return Object.keys(val).some(k => impl(val[k], seen));\n }\n }\n}\nexports.containsUnknowns = containsUnknowns;\n// tslint:disable-next-line:variable-name\nexports.Output = OutputImpl;\n/**\n * [concat] takes a sequence of [Inputs], stringifies each, and concatenates all values into one\n * final string. Individual inputs can be any sort of [Input] value. i.e. they can be [Promise]s,\n * [Output]s, or just plain JavaScript values. This can be used like so:\n *\n * ```ts\n * // 'server' and 'loadBalancer' are both resources that expose [Output] properties.\n * let val: Output = pulumi.concat(\"http://\", server.hostname, \":\", loadBalancer.port);\n * ```\n *\n */\nfunction concat(...params) {\n return output(params).apply(array => array.join(\"\"));\n}\nexports.concat = concat;\n/**\n * [interpolate] is similar to [concat] but is designed to be used as a tagged template expression.\n * i.e.:\n *\n * ```ts\n * // 'server' and 'loadBalancer' are both resources that expose [Output] properties.\n * let val: Output = pulumi.interpolate `http://${server.hostname}:${loadBalancer.port}`\n * ```\n *\n * As with [concat] the 'placeholders' between `${}` can be any Inputs. i.e. they can be\n * [Promise]s, [Output]s, or just plain JavaScript values.\n */\nfunction interpolate(literals, ...placeholders) {\n return output(placeholders).apply(unwrapped => {\n let result = \"\";\n // interleave the literals with the placeholders\n for (let i = 0; i < unwrapped.length; i++) {\n result += literals[i];\n result += unwrapped[i];\n }\n // add the last literal\n result += literals[literals.length - 1];\n return result;\n });\n}\nexports.interpolate = interpolate;\n","// GENERATED CODE -- DO NOT EDIT!\n\n// Original file comments:\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//\n'use strict';\nvar grpc = require('@grpc/grpc-js');\nvar engine_pb = require('./engine_pb.js');\nvar google_protobuf_empty_pb = require('google-protobuf/google/protobuf/empty_pb.js');\n\nfunction serialize_google_protobuf_Empty(arg) {\n if (!(arg instanceof google_protobuf_empty_pb.Empty)) {\n throw new Error('Expected argument of type google.protobuf.Empty');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_google_protobuf_Empty(buffer_arg) {\n return google_protobuf_empty_pb.Empty.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_GetRootResourceRequest(arg) {\n if (!(arg instanceof engine_pb.GetRootResourceRequest)) {\n throw new Error('Expected argument of type pulumirpc.GetRootResourceRequest');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_GetRootResourceRequest(buffer_arg) {\n return engine_pb.GetRootResourceRequest.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_GetRootResourceResponse(arg) {\n if (!(arg instanceof engine_pb.GetRootResourceResponse)) {\n throw new Error('Expected argument of type pulumirpc.GetRootResourceResponse');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_GetRootResourceResponse(buffer_arg) {\n return engine_pb.GetRootResourceResponse.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_LogRequest(arg) {\n if (!(arg instanceof engine_pb.LogRequest)) {\n throw new Error('Expected argument of type pulumirpc.LogRequest');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_LogRequest(buffer_arg) {\n return engine_pb.LogRequest.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_SetRootResourceRequest(arg) {\n if (!(arg instanceof engine_pb.SetRootResourceRequest)) {\n throw new Error('Expected argument of type pulumirpc.SetRootResourceRequest');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_SetRootResourceRequest(buffer_arg) {\n return engine_pb.SetRootResourceRequest.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_SetRootResourceResponse(arg) {\n if (!(arg instanceof engine_pb.SetRootResourceResponse)) {\n throw new Error('Expected argument of type pulumirpc.SetRootResourceResponse');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_SetRootResourceResponse(buffer_arg) {\n return engine_pb.SetRootResourceResponse.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\n\n// Engine is an auxiliary service offered to language and resource provider plugins. Its main purpose today is\n// to serve as a common logging endpoint, but it also serves as a state storage mechanism for language hosts\n// that can't store their own global state.\nvar EngineService = exports.EngineService = {\n // Log logs a global message in the engine, including errors and warnings.\nlog: {\n path: '/pulumirpc.Engine/Log',\n requestStream: false,\n responseStream: false,\n requestType: engine_pb.LogRequest,\n responseType: google_protobuf_empty_pb.Empty,\n requestSerialize: serialize_pulumirpc_LogRequest,\n requestDeserialize: deserialize_pulumirpc_LogRequest,\n responseSerialize: serialize_google_protobuf_Empty,\n responseDeserialize: deserialize_google_protobuf_Empty,\n },\n // GetRootResource gets the URN of the root resource, the resource that should be the root of all\n// otherwise-unparented resources.\ngetRootResource: {\n path: '/pulumirpc.Engine/GetRootResource',\n requestStream: false,\n responseStream: false,\n requestType: engine_pb.GetRootResourceRequest,\n responseType: engine_pb.GetRootResourceResponse,\n requestSerialize: serialize_pulumirpc_GetRootResourceRequest,\n requestDeserialize: deserialize_pulumirpc_GetRootResourceRequest,\n responseSerialize: serialize_pulumirpc_GetRootResourceResponse,\n responseDeserialize: deserialize_pulumirpc_GetRootResourceResponse,\n },\n // SetRootResource sets the URN of the root resource.\nsetRootResource: {\n path: '/pulumirpc.Engine/SetRootResource',\n requestStream: false,\n responseStream: false,\n requestType: engine_pb.SetRootResourceRequest,\n responseType: engine_pb.SetRootResourceResponse,\n requestSerialize: serialize_pulumirpc_SetRootResourceRequest,\n requestDeserialize: deserialize_pulumirpc_SetRootResourceRequest,\n responseSerialize: serialize_pulumirpc_SetRootResourceResponse,\n responseDeserialize: deserialize_pulumirpc_SetRootResourceResponse,\n },\n};\n\nexports.EngineClient = grpc.makeGenericClientConstructor(EngineService);\n","// source: engine.proto\n/**\n * @fileoverview\n * @enhanceable\n * @suppress {messageConventions} JS Compiler reports an error if a variable or\n * field starts with 'MSG_' and isn't a translatable message.\n * @public\n */\n// GENERATED CODE -- DO NOT EDIT!\n\nvar jspb = require('google-protobuf');\nvar goog = jspb;\nvar proto = { pulumirpc: {} }, global = proto;\n\nvar google_protobuf_empty_pb = require('google-protobuf/google/protobuf/empty_pb.js');\ngoog.object.extend(proto, google_protobuf_empty_pb);\ngoog.exportSymbol('proto.pulumirpc.GetRootResourceRequest', null, global);\ngoog.exportSymbol('proto.pulumirpc.GetRootResourceResponse', null, global);\ngoog.exportSymbol('proto.pulumirpc.LogRequest', null, global);\ngoog.exportSymbol('proto.pulumirpc.LogSeverity', null, global);\ngoog.exportSymbol('proto.pulumirpc.SetRootResourceRequest', null, global);\ngoog.exportSymbol('proto.pulumirpc.SetRootResourceResponse', null, global);\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.LogRequest = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, null, null);\n};\ngoog.inherits(proto.pulumirpc.LogRequest, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.LogRequest.displayName = 'proto.pulumirpc.LogRequest';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.GetRootResourceRequest = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, null, null);\n};\ngoog.inherits(proto.pulumirpc.GetRootResourceRequest, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.GetRootResourceRequest.displayName = 'proto.pulumirpc.GetRootResourceRequest';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.GetRootResourceResponse = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, null, null);\n};\ngoog.inherits(proto.pulumirpc.GetRootResourceResponse, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.GetRootResourceResponse.displayName = 'proto.pulumirpc.GetRootResourceResponse';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.SetRootResourceRequest = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, null, null);\n};\ngoog.inherits(proto.pulumirpc.SetRootResourceRequest, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.SetRootResourceRequest.displayName = 'proto.pulumirpc.SetRootResourceRequest';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.SetRootResourceResponse = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, null, null);\n};\ngoog.inherits(proto.pulumirpc.SetRootResourceResponse, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.SetRootResourceResponse.displayName = 'proto.pulumirpc.SetRootResourceResponse';\n}\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.LogRequest.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.LogRequest.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.LogRequest} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.LogRequest.toObject = function(includeInstance, msg) {\n var f, obj = {\n severity: jspb.Message.getFieldWithDefault(msg, 1, 0),\n message: jspb.Message.getFieldWithDefault(msg, 2, \"\"),\n urn: jspb.Message.getFieldWithDefault(msg, 3, \"\"),\n streamid: jspb.Message.getFieldWithDefault(msg, 4, 0),\n ephemeral: jspb.Message.getBooleanFieldWithDefault(msg, 5, false)\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.LogRequest}\n */\nproto.pulumirpc.LogRequest.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.LogRequest;\n return proto.pulumirpc.LogRequest.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.LogRequest} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.LogRequest}\n */\nproto.pulumirpc.LogRequest.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {!proto.pulumirpc.LogSeverity} */ (reader.readEnum());\n msg.setSeverity(value);\n break;\n case 2:\n var value = /** @type {string} */ (reader.readString());\n msg.setMessage(value);\n break;\n case 3:\n var value = /** @type {string} */ (reader.readString());\n msg.setUrn(value);\n break;\n case 4:\n var value = /** @type {number} */ (reader.readInt32());\n msg.setStreamid(value);\n break;\n case 5:\n var value = /** @type {boolean} */ (reader.readBool());\n msg.setEphemeral(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.LogRequest.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.LogRequest.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.LogRequest} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.LogRequest.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getSeverity();\n if (f !== 0.0) {\n writer.writeEnum(\n 1,\n f\n );\n }\n f = message.getMessage();\n if (f.length > 0) {\n writer.writeString(\n 2,\n f\n );\n }\n f = message.getUrn();\n if (f.length > 0) {\n writer.writeString(\n 3,\n f\n );\n }\n f = message.getStreamid();\n if (f !== 0) {\n writer.writeInt32(\n 4,\n f\n );\n }\n f = message.getEphemeral();\n if (f) {\n writer.writeBool(\n 5,\n f\n );\n }\n};\n\n\n/**\n * optional LogSeverity severity = 1;\n * @return {!proto.pulumirpc.LogSeverity}\n */\nproto.pulumirpc.LogRequest.prototype.getSeverity = function() {\n return /** @type {!proto.pulumirpc.LogSeverity} */ (jspb.Message.getFieldWithDefault(this, 1, 0));\n};\n\n\n/**\n * @param {!proto.pulumirpc.LogSeverity} value\n * @return {!proto.pulumirpc.LogRequest} returns this\n */\nproto.pulumirpc.LogRequest.prototype.setSeverity = function(value) {\n return jspb.Message.setProto3EnumField(this, 1, value);\n};\n\n\n/**\n * optional string message = 2;\n * @return {string}\n */\nproto.pulumirpc.LogRequest.prototype.getMessage = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.LogRequest} returns this\n */\nproto.pulumirpc.LogRequest.prototype.setMessage = function(value) {\n return jspb.Message.setProto3StringField(this, 2, value);\n};\n\n\n/**\n * optional string urn = 3;\n * @return {string}\n */\nproto.pulumirpc.LogRequest.prototype.getUrn = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.LogRequest} returns this\n */\nproto.pulumirpc.LogRequest.prototype.setUrn = function(value) {\n return jspb.Message.setProto3StringField(this, 3, value);\n};\n\n\n/**\n * optional int32 streamId = 4;\n * @return {number}\n */\nproto.pulumirpc.LogRequest.prototype.getStreamid = function() {\n return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 4, 0));\n};\n\n\n/**\n * @param {number} value\n * @return {!proto.pulumirpc.LogRequest} returns this\n */\nproto.pulumirpc.LogRequest.prototype.setStreamid = function(value) {\n return jspb.Message.setProto3IntField(this, 4, value);\n};\n\n\n/**\n * optional bool ephemeral = 5;\n * @return {boolean}\n */\nproto.pulumirpc.LogRequest.prototype.getEphemeral = function() {\n return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 5, false));\n};\n\n\n/**\n * @param {boolean} value\n * @return {!proto.pulumirpc.LogRequest} returns this\n */\nproto.pulumirpc.LogRequest.prototype.setEphemeral = function(value) {\n return jspb.Message.setProto3BooleanField(this, 5, value);\n};\n\n\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.GetRootResourceRequest.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.GetRootResourceRequest.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.GetRootResourceRequest} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.GetRootResourceRequest.toObject = function(includeInstance, msg) {\n var f, obj = {\n\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.GetRootResourceRequest}\n */\nproto.pulumirpc.GetRootResourceRequest.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.GetRootResourceRequest;\n return proto.pulumirpc.GetRootResourceRequest.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.GetRootResourceRequest} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.GetRootResourceRequest}\n */\nproto.pulumirpc.GetRootResourceRequest.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.GetRootResourceRequest.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.GetRootResourceRequest.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.GetRootResourceRequest} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.GetRootResourceRequest.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n};\n\n\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.GetRootResourceResponse.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.GetRootResourceResponse.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.GetRootResourceResponse} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.GetRootResourceResponse.toObject = function(includeInstance, msg) {\n var f, obj = {\n urn: jspb.Message.getFieldWithDefault(msg, 1, \"\")\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.GetRootResourceResponse}\n */\nproto.pulumirpc.GetRootResourceResponse.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.GetRootResourceResponse;\n return proto.pulumirpc.GetRootResourceResponse.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.GetRootResourceResponse} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.GetRootResourceResponse}\n */\nproto.pulumirpc.GetRootResourceResponse.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {string} */ (reader.readString());\n msg.setUrn(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.GetRootResourceResponse.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.GetRootResourceResponse.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.GetRootResourceResponse} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.GetRootResourceResponse.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getUrn();\n if (f.length > 0) {\n writer.writeString(\n 1,\n f\n );\n }\n};\n\n\n/**\n * optional string urn = 1;\n * @return {string}\n */\nproto.pulumirpc.GetRootResourceResponse.prototype.getUrn = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.GetRootResourceResponse} returns this\n */\nproto.pulumirpc.GetRootResourceResponse.prototype.setUrn = function(value) {\n return jspb.Message.setProto3StringField(this, 1, value);\n};\n\n\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.SetRootResourceRequest.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.SetRootResourceRequest.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.SetRootResourceRequest} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.SetRootResourceRequest.toObject = function(includeInstance, msg) {\n var f, obj = {\n urn: jspb.Message.getFieldWithDefault(msg, 1, \"\")\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.SetRootResourceRequest}\n */\nproto.pulumirpc.SetRootResourceRequest.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.SetRootResourceRequest;\n return proto.pulumirpc.SetRootResourceRequest.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.SetRootResourceRequest} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.SetRootResourceRequest}\n */\nproto.pulumirpc.SetRootResourceRequest.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {string} */ (reader.readString());\n msg.setUrn(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.SetRootResourceRequest.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.SetRootResourceRequest.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.SetRootResourceRequest} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.SetRootResourceRequest.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getUrn();\n if (f.length > 0) {\n writer.writeString(\n 1,\n f\n );\n }\n};\n\n\n/**\n * optional string urn = 1;\n * @return {string}\n */\nproto.pulumirpc.SetRootResourceRequest.prototype.getUrn = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.SetRootResourceRequest} returns this\n */\nproto.pulumirpc.SetRootResourceRequest.prototype.setUrn = function(value) {\n return jspb.Message.setProto3StringField(this, 1, value);\n};\n\n\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.SetRootResourceResponse.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.SetRootResourceResponse.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.SetRootResourceResponse} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.SetRootResourceResponse.toObject = function(includeInstance, msg) {\n var f, obj = {\n\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.SetRootResourceResponse}\n */\nproto.pulumirpc.SetRootResourceResponse.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.SetRootResourceResponse;\n return proto.pulumirpc.SetRootResourceResponse.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.SetRootResourceResponse} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.SetRootResourceResponse}\n */\nproto.pulumirpc.SetRootResourceResponse.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.SetRootResourceResponse.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.SetRootResourceResponse.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.SetRootResourceResponse} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.SetRootResourceResponse.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n};\n\n\n/**\n * @enum {number}\n */\nproto.pulumirpc.LogSeverity = {\n DEBUG: 0,\n INFO: 1,\n WARNING: 2,\n ERROR: 3\n};\n\ngoog.object.extend(exports, proto.pulumirpc);\n","// GENERATED CODE -- DO NOT EDIT!\n\n// Original file comments:\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//\n'use strict';\nvar grpc = require('@grpc/grpc-js');\nvar language_pb = require('./language_pb.js');\nvar plugin_pb = require('./plugin_pb.js');\nvar google_protobuf_empty_pb = require('google-protobuf/google/protobuf/empty_pb.js');\n\nfunction serialize_google_protobuf_Empty(arg) {\n if (!(arg instanceof google_protobuf_empty_pb.Empty)) {\n throw new Error('Expected argument of type google.protobuf.Empty');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_google_protobuf_Empty(buffer_arg) {\n return google_protobuf_empty_pb.Empty.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_GetRequiredPluginsRequest(arg) {\n if (!(arg instanceof language_pb.GetRequiredPluginsRequest)) {\n throw new Error('Expected argument of type pulumirpc.GetRequiredPluginsRequest');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_GetRequiredPluginsRequest(buffer_arg) {\n return language_pb.GetRequiredPluginsRequest.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_GetRequiredPluginsResponse(arg) {\n if (!(arg instanceof language_pb.GetRequiredPluginsResponse)) {\n throw new Error('Expected argument of type pulumirpc.GetRequiredPluginsResponse');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_GetRequiredPluginsResponse(buffer_arg) {\n return language_pb.GetRequiredPluginsResponse.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_PluginInfo(arg) {\n if (!(arg instanceof plugin_pb.PluginInfo)) {\n throw new Error('Expected argument of type pulumirpc.PluginInfo');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_PluginInfo(buffer_arg) {\n return plugin_pb.PluginInfo.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_RunRequest(arg) {\n if (!(arg instanceof language_pb.RunRequest)) {\n throw new Error('Expected argument of type pulumirpc.RunRequest');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_RunRequest(buffer_arg) {\n return language_pb.RunRequest.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_RunResponse(arg) {\n if (!(arg instanceof language_pb.RunResponse)) {\n throw new Error('Expected argument of type pulumirpc.RunResponse');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_RunResponse(buffer_arg) {\n return language_pb.RunResponse.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\n\n// LanguageRuntime is the interface that the planning monitor uses to drive execution of an interpreter responsible\n// for confguring and creating resource objects.\nvar LanguageRuntimeService = exports.LanguageRuntimeService = {\n // GetRequiredPlugins computes the complete set of anticipated plugins required by a program.\ngetRequiredPlugins: {\n path: '/pulumirpc.LanguageRuntime/GetRequiredPlugins',\n requestStream: false,\n responseStream: false,\n requestType: language_pb.GetRequiredPluginsRequest,\n responseType: language_pb.GetRequiredPluginsResponse,\n requestSerialize: serialize_pulumirpc_GetRequiredPluginsRequest,\n requestDeserialize: deserialize_pulumirpc_GetRequiredPluginsRequest,\n responseSerialize: serialize_pulumirpc_GetRequiredPluginsResponse,\n responseDeserialize: deserialize_pulumirpc_GetRequiredPluginsResponse,\n },\n // Run executes a program and returns its result.\nrun: {\n path: '/pulumirpc.LanguageRuntime/Run',\n requestStream: false,\n responseStream: false,\n requestType: language_pb.RunRequest,\n responseType: language_pb.RunResponse,\n requestSerialize: serialize_pulumirpc_RunRequest,\n requestDeserialize: deserialize_pulumirpc_RunRequest,\n responseSerialize: serialize_pulumirpc_RunResponse,\n responseDeserialize: deserialize_pulumirpc_RunResponse,\n },\n // GetPluginInfo returns generic information about this plugin, like its version.\ngetPluginInfo: {\n path: '/pulumirpc.LanguageRuntime/GetPluginInfo',\n requestStream: false,\n responseStream: false,\n requestType: google_protobuf_empty_pb.Empty,\n responseType: plugin_pb.PluginInfo,\n requestSerialize: serialize_google_protobuf_Empty,\n requestDeserialize: deserialize_google_protobuf_Empty,\n responseSerialize: serialize_pulumirpc_PluginInfo,\n responseDeserialize: deserialize_pulumirpc_PluginInfo,\n },\n};\n\nexports.LanguageRuntimeClient = grpc.makeGenericClientConstructor(LanguageRuntimeService);\n","// source: language.proto\n/**\n * @fileoverview\n * @enhanceable\n * @suppress {messageConventions} JS Compiler reports an error if a variable or\n * field starts with 'MSG_' and isn't a translatable message.\n * @public\n */\n// GENERATED CODE -- DO NOT EDIT!\n\nvar jspb = require('google-protobuf');\nvar goog = jspb;\nvar proto = { pulumirpc: {} }, global = proto;\n\nvar plugin_pb = require('./plugin_pb.js');\ngoog.object.extend(proto, plugin_pb);\nvar google_protobuf_empty_pb = require('google-protobuf/google/protobuf/empty_pb.js');\ngoog.object.extend(proto, google_protobuf_empty_pb);\ngoog.exportSymbol('proto.pulumirpc.GetRequiredPluginsRequest', null, global);\ngoog.exportSymbol('proto.pulumirpc.GetRequiredPluginsResponse', null, global);\ngoog.exportSymbol('proto.pulumirpc.RunRequest', null, global);\ngoog.exportSymbol('proto.pulumirpc.RunResponse', null, global);\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.GetRequiredPluginsRequest = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, null, null);\n};\ngoog.inherits(proto.pulumirpc.GetRequiredPluginsRequest, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.GetRequiredPluginsRequest.displayName = 'proto.pulumirpc.GetRequiredPluginsRequest';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.GetRequiredPluginsResponse = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, proto.pulumirpc.GetRequiredPluginsResponse.repeatedFields_, null);\n};\ngoog.inherits(proto.pulumirpc.GetRequiredPluginsResponse, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.GetRequiredPluginsResponse.displayName = 'proto.pulumirpc.GetRequiredPluginsResponse';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.RunRequest = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, proto.pulumirpc.RunRequest.repeatedFields_, null);\n};\ngoog.inherits(proto.pulumirpc.RunRequest, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.RunRequest.displayName = 'proto.pulumirpc.RunRequest';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.RunResponse = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, null, null);\n};\ngoog.inherits(proto.pulumirpc.RunResponse, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.RunResponse.displayName = 'proto.pulumirpc.RunResponse';\n}\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.GetRequiredPluginsRequest.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.GetRequiredPluginsRequest.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.GetRequiredPluginsRequest} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.GetRequiredPluginsRequest.toObject = function(includeInstance, msg) {\n var f, obj = {\n project: jspb.Message.getFieldWithDefault(msg, 1, \"\"),\n pwd: jspb.Message.getFieldWithDefault(msg, 2, \"\"),\n program: jspb.Message.getFieldWithDefault(msg, 3, \"\")\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.GetRequiredPluginsRequest}\n */\nproto.pulumirpc.GetRequiredPluginsRequest.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.GetRequiredPluginsRequest;\n return proto.pulumirpc.GetRequiredPluginsRequest.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.GetRequiredPluginsRequest} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.GetRequiredPluginsRequest}\n */\nproto.pulumirpc.GetRequiredPluginsRequest.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {string} */ (reader.readString());\n msg.setProject(value);\n break;\n case 2:\n var value = /** @type {string} */ (reader.readString());\n msg.setPwd(value);\n break;\n case 3:\n var value = /** @type {string} */ (reader.readString());\n msg.setProgram(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.GetRequiredPluginsRequest.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.GetRequiredPluginsRequest.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.GetRequiredPluginsRequest} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.GetRequiredPluginsRequest.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getProject();\n if (f.length > 0) {\n writer.writeString(\n 1,\n f\n );\n }\n f = message.getPwd();\n if (f.length > 0) {\n writer.writeString(\n 2,\n f\n );\n }\n f = message.getProgram();\n if (f.length > 0) {\n writer.writeString(\n 3,\n f\n );\n }\n};\n\n\n/**\n * optional string project = 1;\n * @return {string}\n */\nproto.pulumirpc.GetRequiredPluginsRequest.prototype.getProject = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.GetRequiredPluginsRequest} returns this\n */\nproto.pulumirpc.GetRequiredPluginsRequest.prototype.setProject = function(value) {\n return jspb.Message.setProto3StringField(this, 1, value);\n};\n\n\n/**\n * optional string pwd = 2;\n * @return {string}\n */\nproto.pulumirpc.GetRequiredPluginsRequest.prototype.getPwd = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.GetRequiredPluginsRequest} returns this\n */\nproto.pulumirpc.GetRequiredPluginsRequest.prototype.setPwd = function(value) {\n return jspb.Message.setProto3StringField(this, 2, value);\n};\n\n\n/**\n * optional string program = 3;\n * @return {string}\n */\nproto.pulumirpc.GetRequiredPluginsRequest.prototype.getProgram = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.GetRequiredPluginsRequest} returns this\n */\nproto.pulumirpc.GetRequiredPluginsRequest.prototype.setProgram = function(value) {\n return jspb.Message.setProto3StringField(this, 3, value);\n};\n\n\n\n/**\n * List of repeated fields within this message type.\n * @private {!Array}\n * @const\n */\nproto.pulumirpc.GetRequiredPluginsResponse.repeatedFields_ = [1];\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.GetRequiredPluginsResponse.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.GetRequiredPluginsResponse.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.GetRequiredPluginsResponse} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.GetRequiredPluginsResponse.toObject = function(includeInstance, msg) {\n var f, obj = {\n pluginsList: jspb.Message.toObjectList(msg.getPluginsList(),\n plugin_pb.PluginDependency.toObject, includeInstance)\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.GetRequiredPluginsResponse}\n */\nproto.pulumirpc.GetRequiredPluginsResponse.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.GetRequiredPluginsResponse;\n return proto.pulumirpc.GetRequiredPluginsResponse.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.GetRequiredPluginsResponse} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.GetRequiredPluginsResponse}\n */\nproto.pulumirpc.GetRequiredPluginsResponse.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = new plugin_pb.PluginDependency;\n reader.readMessage(value,plugin_pb.PluginDependency.deserializeBinaryFromReader);\n msg.addPlugins(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.GetRequiredPluginsResponse.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.GetRequiredPluginsResponse.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.GetRequiredPluginsResponse} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.GetRequiredPluginsResponse.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getPluginsList();\n if (f.length > 0) {\n writer.writeRepeatedMessage(\n 1,\n f,\n plugin_pb.PluginDependency.serializeBinaryToWriter\n );\n }\n};\n\n\n/**\n * repeated PluginDependency plugins = 1;\n * @return {!Array}\n */\nproto.pulumirpc.GetRequiredPluginsResponse.prototype.getPluginsList = function() {\n return /** @type{!Array} */ (\n jspb.Message.getRepeatedWrapperField(this, plugin_pb.PluginDependency, 1));\n};\n\n\n/**\n * @param {!Array} value\n * @return {!proto.pulumirpc.GetRequiredPluginsResponse} returns this\n*/\nproto.pulumirpc.GetRequiredPluginsResponse.prototype.setPluginsList = function(value) {\n return jspb.Message.setRepeatedWrapperField(this, 1, value);\n};\n\n\n/**\n * @param {!proto.pulumirpc.PluginDependency=} opt_value\n * @param {number=} opt_index\n * @return {!proto.pulumirpc.PluginDependency}\n */\nproto.pulumirpc.GetRequiredPluginsResponse.prototype.addPlugins = function(opt_value, opt_index) {\n return jspb.Message.addToRepeatedWrapperField(this, 1, opt_value, proto.pulumirpc.PluginDependency, opt_index);\n};\n\n\n/**\n * Clears the list making it empty but non-null.\n * @return {!proto.pulumirpc.GetRequiredPluginsResponse} returns this\n */\nproto.pulumirpc.GetRequiredPluginsResponse.prototype.clearPluginsList = function() {\n return this.setPluginsList([]);\n};\n\n\n\n/**\n * List of repeated fields within this message type.\n * @private {!Array}\n * @const\n */\nproto.pulumirpc.RunRequest.repeatedFields_ = [5];\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.RunRequest.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.RunRequest.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.RunRequest} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.RunRequest.toObject = function(includeInstance, msg) {\n var f, obj = {\n project: jspb.Message.getFieldWithDefault(msg, 1, \"\"),\n stack: jspb.Message.getFieldWithDefault(msg, 2, \"\"),\n pwd: jspb.Message.getFieldWithDefault(msg, 3, \"\"),\n program: jspb.Message.getFieldWithDefault(msg, 4, \"\"),\n argsList: (f = jspb.Message.getRepeatedField(msg, 5)) == null ? undefined : f,\n configMap: (f = msg.getConfigMap()) ? f.toObject(includeInstance, undefined) : [],\n dryrun: jspb.Message.getBooleanFieldWithDefault(msg, 7, false),\n parallel: jspb.Message.getFieldWithDefault(msg, 8, 0),\n monitorAddress: jspb.Message.getFieldWithDefault(msg, 9, \"\"),\n querymode: jspb.Message.getBooleanFieldWithDefault(msg, 10, false)\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.RunRequest}\n */\nproto.pulumirpc.RunRequest.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.RunRequest;\n return proto.pulumirpc.RunRequest.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.RunRequest} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.RunRequest}\n */\nproto.pulumirpc.RunRequest.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {string} */ (reader.readString());\n msg.setProject(value);\n break;\n case 2:\n var value = /** @type {string} */ (reader.readString());\n msg.setStack(value);\n break;\n case 3:\n var value = /** @type {string} */ (reader.readString());\n msg.setPwd(value);\n break;\n case 4:\n var value = /** @type {string} */ (reader.readString());\n msg.setProgram(value);\n break;\n case 5:\n var value = /** @type {string} */ (reader.readString());\n msg.addArgs(value);\n break;\n case 6:\n var value = msg.getConfigMap();\n reader.readMessage(value, function(message, reader) {\n jspb.Map.deserializeBinary(message, reader, jspb.BinaryReader.prototype.readString, jspb.BinaryReader.prototype.readString, null, \"\", \"\");\n });\n break;\n case 7:\n var value = /** @type {boolean} */ (reader.readBool());\n msg.setDryrun(value);\n break;\n case 8:\n var value = /** @type {number} */ (reader.readInt32());\n msg.setParallel(value);\n break;\n case 9:\n var value = /** @type {string} */ (reader.readString());\n msg.setMonitorAddress(value);\n break;\n case 10:\n var value = /** @type {boolean} */ (reader.readBool());\n msg.setQuerymode(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.RunRequest.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.RunRequest.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.RunRequest} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.RunRequest.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getProject();\n if (f.length > 0) {\n writer.writeString(\n 1,\n f\n );\n }\n f = message.getStack();\n if (f.length > 0) {\n writer.writeString(\n 2,\n f\n );\n }\n f = message.getPwd();\n if (f.length > 0) {\n writer.writeString(\n 3,\n f\n );\n }\n f = message.getProgram();\n if (f.length > 0) {\n writer.writeString(\n 4,\n f\n );\n }\n f = message.getArgsList();\n if (f.length > 0) {\n writer.writeRepeatedString(\n 5,\n f\n );\n }\n f = message.getConfigMap(true);\n if (f && f.getLength() > 0) {\n f.serializeBinary(6, writer, jspb.BinaryWriter.prototype.writeString, jspb.BinaryWriter.prototype.writeString);\n }\n f = message.getDryrun();\n if (f) {\n writer.writeBool(\n 7,\n f\n );\n }\n f = message.getParallel();\n if (f !== 0) {\n writer.writeInt32(\n 8,\n f\n );\n }\n f = message.getMonitorAddress();\n if (f.length > 0) {\n writer.writeString(\n 9,\n f\n );\n }\n f = message.getQuerymode();\n if (f) {\n writer.writeBool(\n 10,\n f\n );\n }\n};\n\n\n/**\n * optional string project = 1;\n * @return {string}\n */\nproto.pulumirpc.RunRequest.prototype.getProject = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.RunRequest} returns this\n */\nproto.pulumirpc.RunRequest.prototype.setProject = function(value) {\n return jspb.Message.setProto3StringField(this, 1, value);\n};\n\n\n/**\n * optional string stack = 2;\n * @return {string}\n */\nproto.pulumirpc.RunRequest.prototype.getStack = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.RunRequest} returns this\n */\nproto.pulumirpc.RunRequest.prototype.setStack = function(value) {\n return jspb.Message.setProto3StringField(this, 2, value);\n};\n\n\n/**\n * optional string pwd = 3;\n * @return {string}\n */\nproto.pulumirpc.RunRequest.prototype.getPwd = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.RunRequest} returns this\n */\nproto.pulumirpc.RunRequest.prototype.setPwd = function(value) {\n return jspb.Message.setProto3StringField(this, 3, value);\n};\n\n\n/**\n * optional string program = 4;\n * @return {string}\n */\nproto.pulumirpc.RunRequest.prototype.getProgram = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 4, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.RunRequest} returns this\n */\nproto.pulumirpc.RunRequest.prototype.setProgram = function(value) {\n return jspb.Message.setProto3StringField(this, 4, value);\n};\n\n\n/**\n * repeated string args = 5;\n * @return {!Array}\n */\nproto.pulumirpc.RunRequest.prototype.getArgsList = function() {\n return /** @type {!Array} */ (jspb.Message.getRepeatedField(this, 5));\n};\n\n\n/**\n * @param {!Array} value\n * @return {!proto.pulumirpc.RunRequest} returns this\n */\nproto.pulumirpc.RunRequest.prototype.setArgsList = function(value) {\n return jspb.Message.setField(this, 5, value || []);\n};\n\n\n/**\n * @param {string} value\n * @param {number=} opt_index\n * @return {!proto.pulumirpc.RunRequest} returns this\n */\nproto.pulumirpc.RunRequest.prototype.addArgs = function(value, opt_index) {\n return jspb.Message.addToRepeatedField(this, 5, value, opt_index);\n};\n\n\n/**\n * Clears the list making it empty but non-null.\n * @return {!proto.pulumirpc.RunRequest} returns this\n */\nproto.pulumirpc.RunRequest.prototype.clearArgsList = function() {\n return this.setArgsList([]);\n};\n\n\n/**\n * map config = 6;\n * @param {boolean=} opt_noLazyCreate Do not create the map if\n * empty, instead returning `undefined`\n * @return {!jspb.Map}\n */\nproto.pulumirpc.RunRequest.prototype.getConfigMap = function(opt_noLazyCreate) {\n return /** @type {!jspb.Map} */ (\n jspb.Message.getMapField(this, 6, opt_noLazyCreate,\n null));\n};\n\n\n/**\n * Clears values from the map. The map will be non-null.\n * @return {!proto.pulumirpc.RunRequest} returns this\n */\nproto.pulumirpc.RunRequest.prototype.clearConfigMap = function() {\n this.getConfigMap().clear();\n return this;};\n\n\n/**\n * optional bool dryRun = 7;\n * @return {boolean}\n */\nproto.pulumirpc.RunRequest.prototype.getDryrun = function() {\n return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 7, false));\n};\n\n\n/**\n * @param {boolean} value\n * @return {!proto.pulumirpc.RunRequest} returns this\n */\nproto.pulumirpc.RunRequest.prototype.setDryrun = function(value) {\n return jspb.Message.setProto3BooleanField(this, 7, value);\n};\n\n\n/**\n * optional int32 parallel = 8;\n * @return {number}\n */\nproto.pulumirpc.RunRequest.prototype.getParallel = function() {\n return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 8, 0));\n};\n\n\n/**\n * @param {number} value\n * @return {!proto.pulumirpc.RunRequest} returns this\n */\nproto.pulumirpc.RunRequest.prototype.setParallel = function(value) {\n return jspb.Message.setProto3IntField(this, 8, value);\n};\n\n\n/**\n * optional string monitor_address = 9;\n * @return {string}\n */\nproto.pulumirpc.RunRequest.prototype.getMonitorAddress = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 9, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.RunRequest} returns this\n */\nproto.pulumirpc.RunRequest.prototype.setMonitorAddress = function(value) {\n return jspb.Message.setProto3StringField(this, 9, value);\n};\n\n\n/**\n * optional bool queryMode = 10;\n * @return {boolean}\n */\nproto.pulumirpc.RunRequest.prototype.getQuerymode = function() {\n return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 10, false));\n};\n\n\n/**\n * @param {boolean} value\n * @return {!proto.pulumirpc.RunRequest} returns this\n */\nproto.pulumirpc.RunRequest.prototype.setQuerymode = function(value) {\n return jspb.Message.setProto3BooleanField(this, 10, value);\n};\n\n\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.RunResponse.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.RunResponse.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.RunResponse} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.RunResponse.toObject = function(includeInstance, msg) {\n var f, obj = {\n error: jspb.Message.getFieldWithDefault(msg, 1, \"\"),\n bail: jspb.Message.getBooleanFieldWithDefault(msg, 2, false)\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.RunResponse}\n */\nproto.pulumirpc.RunResponse.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.RunResponse;\n return proto.pulumirpc.RunResponse.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.RunResponse} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.RunResponse}\n */\nproto.pulumirpc.RunResponse.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {string} */ (reader.readString());\n msg.setError(value);\n break;\n case 2:\n var value = /** @type {boolean} */ (reader.readBool());\n msg.setBail(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.RunResponse.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.RunResponse.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.RunResponse} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.RunResponse.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getError();\n if (f.length > 0) {\n writer.writeString(\n 1,\n f\n );\n }\n f = message.getBail();\n if (f) {\n writer.writeBool(\n 2,\n f\n );\n }\n};\n\n\n/**\n * optional string error = 1;\n * @return {string}\n */\nproto.pulumirpc.RunResponse.prototype.getError = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.RunResponse} returns this\n */\nproto.pulumirpc.RunResponse.prototype.setError = function(value) {\n return jspb.Message.setProto3StringField(this, 1, value);\n};\n\n\n/**\n * optional bool bail = 2;\n * @return {boolean}\n */\nproto.pulumirpc.RunResponse.prototype.getBail = function() {\n return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 2, false));\n};\n\n\n/**\n * @param {boolean} value\n * @return {!proto.pulumirpc.RunResponse} returns this\n */\nproto.pulumirpc.RunResponse.prototype.setBail = function(value) {\n return jspb.Message.setProto3BooleanField(this, 2, value);\n};\n\n\ngoog.object.extend(exports, proto.pulumirpc);\n","// source: plugin.proto\n/**\n * @fileoverview\n * @enhanceable\n * @suppress {messageConventions} JS Compiler reports an error if a variable or\n * field starts with 'MSG_' and isn't a translatable message.\n * @public\n */\n// GENERATED CODE -- DO NOT EDIT!\n\nvar jspb = require('google-protobuf');\nvar goog = jspb;\nvar proto = { pulumirpc: {} }, global = proto;\n\ngoog.exportSymbol('proto.pulumirpc.PluginDependency', null, global);\ngoog.exportSymbol('proto.pulumirpc.PluginInfo', null, global);\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.PluginInfo = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, null, null);\n};\ngoog.inherits(proto.pulumirpc.PluginInfo, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.PluginInfo.displayName = 'proto.pulumirpc.PluginInfo';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.PluginDependency = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, null, null);\n};\ngoog.inherits(proto.pulumirpc.PluginDependency, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.PluginDependency.displayName = 'proto.pulumirpc.PluginDependency';\n}\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.PluginInfo.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.PluginInfo.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.PluginInfo} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.PluginInfo.toObject = function(includeInstance, msg) {\n var f, obj = {\n version: jspb.Message.getFieldWithDefault(msg, 1, \"\")\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.PluginInfo}\n */\nproto.pulumirpc.PluginInfo.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.PluginInfo;\n return proto.pulumirpc.PluginInfo.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.PluginInfo} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.PluginInfo}\n */\nproto.pulumirpc.PluginInfo.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {string} */ (reader.readString());\n msg.setVersion(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.PluginInfo.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.PluginInfo.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.PluginInfo} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.PluginInfo.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getVersion();\n if (f.length > 0) {\n writer.writeString(\n 1,\n f\n );\n }\n};\n\n\n/**\n * optional string version = 1;\n * @return {string}\n */\nproto.pulumirpc.PluginInfo.prototype.getVersion = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.PluginInfo} returns this\n */\nproto.pulumirpc.PluginInfo.prototype.setVersion = function(value) {\n return jspb.Message.setProto3StringField(this, 1, value);\n};\n\n\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.PluginDependency.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.PluginDependency.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.PluginDependency} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.PluginDependency.toObject = function(includeInstance, msg) {\n var f, obj = {\n name: jspb.Message.getFieldWithDefault(msg, 1, \"\"),\n kind: jspb.Message.getFieldWithDefault(msg, 2, \"\"),\n version: jspb.Message.getFieldWithDefault(msg, 3, \"\"),\n server: jspb.Message.getFieldWithDefault(msg, 4, \"\")\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.PluginDependency}\n */\nproto.pulumirpc.PluginDependency.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.PluginDependency;\n return proto.pulumirpc.PluginDependency.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.PluginDependency} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.PluginDependency}\n */\nproto.pulumirpc.PluginDependency.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {string} */ (reader.readString());\n msg.setName(value);\n break;\n case 2:\n var value = /** @type {string} */ (reader.readString());\n msg.setKind(value);\n break;\n case 3:\n var value = /** @type {string} */ (reader.readString());\n msg.setVersion(value);\n break;\n case 4:\n var value = /** @type {string} */ (reader.readString());\n msg.setServer(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.PluginDependency.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.PluginDependency.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.PluginDependency} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.PluginDependency.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getName();\n if (f.length > 0) {\n writer.writeString(\n 1,\n f\n );\n }\n f = message.getKind();\n if (f.length > 0) {\n writer.writeString(\n 2,\n f\n );\n }\n f = message.getVersion();\n if (f.length > 0) {\n writer.writeString(\n 3,\n f\n );\n }\n f = message.getServer();\n if (f.length > 0) {\n writer.writeString(\n 4,\n f\n );\n }\n};\n\n\n/**\n * optional string name = 1;\n * @return {string}\n */\nproto.pulumirpc.PluginDependency.prototype.getName = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.PluginDependency} returns this\n */\nproto.pulumirpc.PluginDependency.prototype.setName = function(value) {\n return jspb.Message.setProto3StringField(this, 1, value);\n};\n\n\n/**\n * optional string kind = 2;\n * @return {string}\n */\nproto.pulumirpc.PluginDependency.prototype.getKind = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.PluginDependency} returns this\n */\nproto.pulumirpc.PluginDependency.prototype.setKind = function(value) {\n return jspb.Message.setProto3StringField(this, 2, value);\n};\n\n\n/**\n * optional string version = 3;\n * @return {string}\n */\nproto.pulumirpc.PluginDependency.prototype.getVersion = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.PluginDependency} returns this\n */\nproto.pulumirpc.PluginDependency.prototype.setVersion = function(value) {\n return jspb.Message.setProto3StringField(this, 3, value);\n};\n\n\n/**\n * optional string server = 4;\n * @return {string}\n */\nproto.pulumirpc.PluginDependency.prototype.getServer = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 4, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.PluginDependency} returns this\n */\nproto.pulumirpc.PluginDependency.prototype.setServer = function(value) {\n return jspb.Message.setProto3StringField(this, 4, value);\n};\n\n\ngoog.object.extend(exports, proto.pulumirpc);\n","// GENERATED CODE -- DO NOT EDIT!\n\n// Original file comments:\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//\n'use strict';\nvar grpc = require('@grpc/grpc-js');\nvar provider_pb = require('./provider_pb.js');\nvar plugin_pb = require('./plugin_pb.js');\nvar google_protobuf_empty_pb = require('google-protobuf/google/protobuf/empty_pb.js');\nvar google_protobuf_struct_pb = require('google-protobuf/google/protobuf/struct_pb.js');\n\nfunction serialize_google_protobuf_Empty(arg) {\n if (!(arg instanceof google_protobuf_empty_pb.Empty)) {\n throw new Error('Expected argument of type google.protobuf.Empty');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_google_protobuf_Empty(buffer_arg) {\n return google_protobuf_empty_pb.Empty.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_CheckRequest(arg) {\n if (!(arg instanceof provider_pb.CheckRequest)) {\n throw new Error('Expected argument of type pulumirpc.CheckRequest');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_CheckRequest(buffer_arg) {\n return provider_pb.CheckRequest.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_CheckResponse(arg) {\n if (!(arg instanceof provider_pb.CheckResponse)) {\n throw new Error('Expected argument of type pulumirpc.CheckResponse');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_CheckResponse(buffer_arg) {\n return provider_pb.CheckResponse.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_ConfigureRequest(arg) {\n if (!(arg instanceof provider_pb.ConfigureRequest)) {\n throw new Error('Expected argument of type pulumirpc.ConfigureRequest');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_ConfigureRequest(buffer_arg) {\n return provider_pb.ConfigureRequest.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_ConfigureResponse(arg) {\n if (!(arg instanceof provider_pb.ConfigureResponse)) {\n throw new Error('Expected argument of type pulumirpc.ConfigureResponse');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_ConfigureResponse(buffer_arg) {\n return provider_pb.ConfigureResponse.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_ConstructRequest(arg) {\n if (!(arg instanceof provider_pb.ConstructRequest)) {\n throw new Error('Expected argument of type pulumirpc.ConstructRequest');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_ConstructRequest(buffer_arg) {\n return provider_pb.ConstructRequest.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_ConstructResponse(arg) {\n if (!(arg instanceof provider_pb.ConstructResponse)) {\n throw new Error('Expected argument of type pulumirpc.ConstructResponse');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_ConstructResponse(buffer_arg) {\n return provider_pb.ConstructResponse.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_CreateRequest(arg) {\n if (!(arg instanceof provider_pb.CreateRequest)) {\n throw new Error('Expected argument of type pulumirpc.CreateRequest');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_CreateRequest(buffer_arg) {\n return provider_pb.CreateRequest.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_CreateResponse(arg) {\n if (!(arg instanceof provider_pb.CreateResponse)) {\n throw new Error('Expected argument of type pulumirpc.CreateResponse');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_CreateResponse(buffer_arg) {\n return provider_pb.CreateResponse.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_DeleteRequest(arg) {\n if (!(arg instanceof provider_pb.DeleteRequest)) {\n throw new Error('Expected argument of type pulumirpc.DeleteRequest');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_DeleteRequest(buffer_arg) {\n return provider_pb.DeleteRequest.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_DiffRequest(arg) {\n if (!(arg instanceof provider_pb.DiffRequest)) {\n throw new Error('Expected argument of type pulumirpc.DiffRequest');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_DiffRequest(buffer_arg) {\n return provider_pb.DiffRequest.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_DiffResponse(arg) {\n if (!(arg instanceof provider_pb.DiffResponse)) {\n throw new Error('Expected argument of type pulumirpc.DiffResponse');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_DiffResponse(buffer_arg) {\n return provider_pb.DiffResponse.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_GetSchemaRequest(arg) {\n if (!(arg instanceof provider_pb.GetSchemaRequest)) {\n throw new Error('Expected argument of type pulumirpc.GetSchemaRequest');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_GetSchemaRequest(buffer_arg) {\n return provider_pb.GetSchemaRequest.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_GetSchemaResponse(arg) {\n if (!(arg instanceof provider_pb.GetSchemaResponse)) {\n throw new Error('Expected argument of type pulumirpc.GetSchemaResponse');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_GetSchemaResponse(buffer_arg) {\n return provider_pb.GetSchemaResponse.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_InvokeRequest(arg) {\n if (!(arg instanceof provider_pb.InvokeRequest)) {\n throw new Error('Expected argument of type pulumirpc.InvokeRequest');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_InvokeRequest(buffer_arg) {\n return provider_pb.InvokeRequest.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_InvokeResponse(arg) {\n if (!(arg instanceof provider_pb.InvokeResponse)) {\n throw new Error('Expected argument of type pulumirpc.InvokeResponse');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_InvokeResponse(buffer_arg) {\n return provider_pb.InvokeResponse.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_PluginInfo(arg) {\n if (!(arg instanceof plugin_pb.PluginInfo)) {\n throw new Error('Expected argument of type pulumirpc.PluginInfo');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_PluginInfo(buffer_arg) {\n return plugin_pb.PluginInfo.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_ReadRequest(arg) {\n if (!(arg instanceof provider_pb.ReadRequest)) {\n throw new Error('Expected argument of type pulumirpc.ReadRequest');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_ReadRequest(buffer_arg) {\n return provider_pb.ReadRequest.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_ReadResponse(arg) {\n if (!(arg instanceof provider_pb.ReadResponse)) {\n throw new Error('Expected argument of type pulumirpc.ReadResponse');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_ReadResponse(buffer_arg) {\n return provider_pb.ReadResponse.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_UpdateRequest(arg) {\n if (!(arg instanceof provider_pb.UpdateRequest)) {\n throw new Error('Expected argument of type pulumirpc.UpdateRequest');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_UpdateRequest(buffer_arg) {\n return provider_pb.UpdateRequest.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_UpdateResponse(arg) {\n if (!(arg instanceof provider_pb.UpdateResponse)) {\n throw new Error('Expected argument of type pulumirpc.UpdateResponse');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_UpdateResponse(buffer_arg) {\n return provider_pb.UpdateResponse.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\n\n// ResourceProvider is a service that understands how to create, read, update, or delete resources for types defined\n// within a single package. It is driven by the overall planning engine in response to resource diffs.\nvar ResourceProviderService = exports.ResourceProviderService = {\n // GetSchema fetches the schema for this resource provider.\ngetSchema: {\n path: '/pulumirpc.ResourceProvider/GetSchema',\n requestStream: false,\n responseStream: false,\n requestType: provider_pb.GetSchemaRequest,\n responseType: provider_pb.GetSchemaResponse,\n requestSerialize: serialize_pulumirpc_GetSchemaRequest,\n requestDeserialize: deserialize_pulumirpc_GetSchemaRequest,\n responseSerialize: serialize_pulumirpc_GetSchemaResponse,\n responseDeserialize: deserialize_pulumirpc_GetSchemaResponse,\n },\n // CheckConfig validates the configuration for this resource provider.\ncheckConfig: {\n path: '/pulumirpc.ResourceProvider/CheckConfig',\n requestStream: false,\n responseStream: false,\n requestType: provider_pb.CheckRequest,\n responseType: provider_pb.CheckResponse,\n requestSerialize: serialize_pulumirpc_CheckRequest,\n requestDeserialize: deserialize_pulumirpc_CheckRequest,\n responseSerialize: serialize_pulumirpc_CheckResponse,\n responseDeserialize: deserialize_pulumirpc_CheckResponse,\n },\n // DiffConfig checks the impact a hypothetical change to this provider's configuration will have on the provider.\ndiffConfig: {\n path: '/pulumirpc.ResourceProvider/DiffConfig',\n requestStream: false,\n responseStream: false,\n requestType: provider_pb.DiffRequest,\n responseType: provider_pb.DiffResponse,\n requestSerialize: serialize_pulumirpc_DiffRequest,\n requestDeserialize: deserialize_pulumirpc_DiffRequest,\n responseSerialize: serialize_pulumirpc_DiffResponse,\n responseDeserialize: deserialize_pulumirpc_DiffResponse,\n },\n // Configure configures the resource provider with \"globals\" that control its behavior.\nconfigure: {\n path: '/pulumirpc.ResourceProvider/Configure',\n requestStream: false,\n responseStream: false,\n requestType: provider_pb.ConfigureRequest,\n responseType: provider_pb.ConfigureResponse,\n requestSerialize: serialize_pulumirpc_ConfigureRequest,\n requestDeserialize: deserialize_pulumirpc_ConfigureRequest,\n responseSerialize: serialize_pulumirpc_ConfigureResponse,\n responseDeserialize: deserialize_pulumirpc_ConfigureResponse,\n },\n // Invoke dynamically executes a built-in function in the provider.\ninvoke: {\n path: '/pulumirpc.ResourceProvider/Invoke',\n requestStream: false,\n responseStream: false,\n requestType: provider_pb.InvokeRequest,\n responseType: provider_pb.InvokeResponse,\n requestSerialize: serialize_pulumirpc_InvokeRequest,\n requestDeserialize: deserialize_pulumirpc_InvokeRequest,\n responseSerialize: serialize_pulumirpc_InvokeResponse,\n responseDeserialize: deserialize_pulumirpc_InvokeResponse,\n },\n // StreamInvoke dynamically executes a built-in function in the provider, which returns a stream\n// of responses.\nstreamInvoke: {\n path: '/pulumirpc.ResourceProvider/StreamInvoke',\n requestStream: false,\n responseStream: true,\n requestType: provider_pb.InvokeRequest,\n responseType: provider_pb.InvokeResponse,\n requestSerialize: serialize_pulumirpc_InvokeRequest,\n requestDeserialize: deserialize_pulumirpc_InvokeRequest,\n responseSerialize: serialize_pulumirpc_InvokeResponse,\n responseDeserialize: deserialize_pulumirpc_InvokeResponse,\n },\n // Check validates that the given property bag is valid for a resource of the given type and returns the inputs\n// that should be passed to successive calls to Diff, Create, or Update for this resource. As a rule, the provider\n// inputs returned by a call to Check should preserve the original representation of the properties as present in\n// the program inputs. Though this rule is not required for correctness, violations thereof can negatively impact\n// the end-user experience, as the provider inputs are using for detecting and rendering diffs.\ncheck: {\n path: '/pulumirpc.ResourceProvider/Check',\n requestStream: false,\n responseStream: false,\n requestType: provider_pb.CheckRequest,\n responseType: provider_pb.CheckResponse,\n requestSerialize: serialize_pulumirpc_CheckRequest,\n requestDeserialize: deserialize_pulumirpc_CheckRequest,\n responseSerialize: serialize_pulumirpc_CheckResponse,\n responseDeserialize: deserialize_pulumirpc_CheckResponse,\n },\n // Diff checks what impacts a hypothetical update will have on the resource's properties.\ndiff: {\n path: '/pulumirpc.ResourceProvider/Diff',\n requestStream: false,\n responseStream: false,\n requestType: provider_pb.DiffRequest,\n responseType: provider_pb.DiffResponse,\n requestSerialize: serialize_pulumirpc_DiffRequest,\n requestDeserialize: deserialize_pulumirpc_DiffRequest,\n responseSerialize: serialize_pulumirpc_DiffResponse,\n responseDeserialize: deserialize_pulumirpc_DiffResponse,\n },\n // Create allocates a new instance of the provided resource and returns its unique ID afterwards. (The input ID\n// must be blank.) If this call fails, the resource must not have been created (i.e., it is \"transactional\").\ncreate: {\n path: '/pulumirpc.ResourceProvider/Create',\n requestStream: false,\n responseStream: false,\n requestType: provider_pb.CreateRequest,\n responseType: provider_pb.CreateResponse,\n requestSerialize: serialize_pulumirpc_CreateRequest,\n requestDeserialize: deserialize_pulumirpc_CreateRequest,\n responseSerialize: serialize_pulumirpc_CreateResponse,\n responseDeserialize: deserialize_pulumirpc_CreateResponse,\n },\n // Read the current live state associated with a resource. Enough state must be include in the inputs to uniquely\n// identify the resource; this is typically just the resource ID, but may also include some properties.\nread: {\n path: '/pulumirpc.ResourceProvider/Read',\n requestStream: false,\n responseStream: false,\n requestType: provider_pb.ReadRequest,\n responseType: provider_pb.ReadResponse,\n requestSerialize: serialize_pulumirpc_ReadRequest,\n requestDeserialize: deserialize_pulumirpc_ReadRequest,\n responseSerialize: serialize_pulumirpc_ReadResponse,\n responseDeserialize: deserialize_pulumirpc_ReadResponse,\n },\n // Update updates an existing resource with new values.\nupdate: {\n path: '/pulumirpc.ResourceProvider/Update',\n requestStream: false,\n responseStream: false,\n requestType: provider_pb.UpdateRequest,\n responseType: provider_pb.UpdateResponse,\n requestSerialize: serialize_pulumirpc_UpdateRequest,\n requestDeserialize: deserialize_pulumirpc_UpdateRequest,\n responseSerialize: serialize_pulumirpc_UpdateResponse,\n responseDeserialize: deserialize_pulumirpc_UpdateResponse,\n },\n // Delete tears down an existing resource with the given ID. If it fails, the resource is assumed to still exist.\ndelete: {\n path: '/pulumirpc.ResourceProvider/Delete',\n requestStream: false,\n responseStream: false,\n requestType: provider_pb.DeleteRequest,\n responseType: google_protobuf_empty_pb.Empty,\n requestSerialize: serialize_pulumirpc_DeleteRequest,\n requestDeserialize: deserialize_pulumirpc_DeleteRequest,\n responseSerialize: serialize_google_protobuf_Empty,\n responseDeserialize: deserialize_google_protobuf_Empty,\n },\n // Construct creates a new instance of the provided component resource and returns its state.\nconstruct: {\n path: '/pulumirpc.ResourceProvider/Construct',\n requestStream: false,\n responseStream: false,\n requestType: provider_pb.ConstructRequest,\n responseType: provider_pb.ConstructResponse,\n requestSerialize: serialize_pulumirpc_ConstructRequest,\n requestDeserialize: deserialize_pulumirpc_ConstructRequest,\n responseSerialize: serialize_pulumirpc_ConstructResponse,\n responseDeserialize: deserialize_pulumirpc_ConstructResponse,\n },\n // Cancel signals the provider to abort all outstanding resource operations.\ncancel: {\n path: '/pulumirpc.ResourceProvider/Cancel',\n requestStream: false,\n responseStream: false,\n requestType: google_protobuf_empty_pb.Empty,\n responseType: google_protobuf_empty_pb.Empty,\n requestSerialize: serialize_google_protobuf_Empty,\n requestDeserialize: deserialize_google_protobuf_Empty,\n responseSerialize: serialize_google_protobuf_Empty,\n responseDeserialize: deserialize_google_protobuf_Empty,\n },\n // GetPluginInfo returns generic information about this plugin, like its version.\ngetPluginInfo: {\n path: '/pulumirpc.ResourceProvider/GetPluginInfo',\n requestStream: false,\n responseStream: false,\n requestType: google_protobuf_empty_pb.Empty,\n responseType: plugin_pb.PluginInfo,\n requestSerialize: serialize_google_protobuf_Empty,\n requestDeserialize: deserialize_google_protobuf_Empty,\n responseSerialize: serialize_pulumirpc_PluginInfo,\n responseDeserialize: deserialize_pulumirpc_PluginInfo,\n },\n};\n\nexports.ResourceProviderClient = grpc.makeGenericClientConstructor(ResourceProviderService);\n","// source: provider.proto\n/**\n * @fileoverview\n * @enhanceable\n * @suppress {messageConventions} JS Compiler reports an error if a variable or\n * field starts with 'MSG_' and isn't a translatable message.\n * @public\n */\n// GENERATED CODE -- DO NOT EDIT!\n\nvar jspb = require('google-protobuf');\nvar goog = jspb;\nvar proto = { pulumirpc: {} }, global = proto;\n\nvar plugin_pb = require('./plugin_pb.js');\ngoog.object.extend(proto, plugin_pb);\nvar google_protobuf_empty_pb = require('google-protobuf/google/protobuf/empty_pb.js');\ngoog.object.extend(proto, google_protobuf_empty_pb);\nvar google_protobuf_struct_pb = require('google-protobuf/google/protobuf/struct_pb.js');\ngoog.object.extend(proto, google_protobuf_struct_pb);\ngoog.exportSymbol('proto.pulumirpc.CheckFailure', null, global);\ngoog.exportSymbol('proto.pulumirpc.CheckRequest', null, global);\ngoog.exportSymbol('proto.pulumirpc.CheckResponse', null, global);\ngoog.exportSymbol('proto.pulumirpc.ConfigureErrorMissingKeys', null, global);\ngoog.exportSymbol('proto.pulumirpc.ConfigureErrorMissingKeys.MissingKey', null, global);\ngoog.exportSymbol('proto.pulumirpc.ConfigureRequest', null, global);\ngoog.exportSymbol('proto.pulumirpc.ConfigureResponse', null, global);\ngoog.exportSymbol('proto.pulumirpc.ConstructRequest', null, global);\ngoog.exportSymbol('proto.pulumirpc.ConstructRequest.PropertyDependencies', null, global);\ngoog.exportSymbol('proto.pulumirpc.ConstructResponse', null, global);\ngoog.exportSymbol('proto.pulumirpc.ConstructResponse.PropertyDependencies', null, global);\ngoog.exportSymbol('proto.pulumirpc.CreateRequest', null, global);\ngoog.exportSymbol('proto.pulumirpc.CreateResponse', null, global);\ngoog.exportSymbol('proto.pulumirpc.DeleteRequest', null, global);\ngoog.exportSymbol('proto.pulumirpc.DiffRequest', null, global);\ngoog.exportSymbol('proto.pulumirpc.DiffResponse', null, global);\ngoog.exportSymbol('proto.pulumirpc.DiffResponse.DiffChanges', null, global);\ngoog.exportSymbol('proto.pulumirpc.ErrorResourceInitFailed', null, global);\ngoog.exportSymbol('proto.pulumirpc.GetSchemaRequest', null, global);\ngoog.exportSymbol('proto.pulumirpc.GetSchemaResponse', null, global);\ngoog.exportSymbol('proto.pulumirpc.InvokeRequest', null, global);\ngoog.exportSymbol('proto.pulumirpc.InvokeResponse', null, global);\ngoog.exportSymbol('proto.pulumirpc.PropertyDiff', null, global);\ngoog.exportSymbol('proto.pulumirpc.PropertyDiff.Kind', null, global);\ngoog.exportSymbol('proto.pulumirpc.ReadRequest', null, global);\ngoog.exportSymbol('proto.pulumirpc.ReadResponse', null, global);\ngoog.exportSymbol('proto.pulumirpc.UpdateRequest', null, global);\ngoog.exportSymbol('proto.pulumirpc.UpdateResponse', null, global);\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.GetSchemaRequest = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, null, null);\n};\ngoog.inherits(proto.pulumirpc.GetSchemaRequest, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.GetSchemaRequest.displayName = 'proto.pulumirpc.GetSchemaRequest';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.GetSchemaResponse = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, null, null);\n};\ngoog.inherits(proto.pulumirpc.GetSchemaResponse, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.GetSchemaResponse.displayName = 'proto.pulumirpc.GetSchemaResponse';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.ConfigureRequest = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, null, null);\n};\ngoog.inherits(proto.pulumirpc.ConfigureRequest, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.ConfigureRequest.displayName = 'proto.pulumirpc.ConfigureRequest';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.ConfigureResponse = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, null, null);\n};\ngoog.inherits(proto.pulumirpc.ConfigureResponse, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.ConfigureResponse.displayName = 'proto.pulumirpc.ConfigureResponse';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.ConfigureErrorMissingKeys = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, proto.pulumirpc.ConfigureErrorMissingKeys.repeatedFields_, null);\n};\ngoog.inherits(proto.pulumirpc.ConfigureErrorMissingKeys, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.ConfigureErrorMissingKeys.displayName = 'proto.pulumirpc.ConfigureErrorMissingKeys';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.ConfigureErrorMissingKeys.MissingKey = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, null, null);\n};\ngoog.inherits(proto.pulumirpc.ConfigureErrorMissingKeys.MissingKey, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.ConfigureErrorMissingKeys.MissingKey.displayName = 'proto.pulumirpc.ConfigureErrorMissingKeys.MissingKey';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.InvokeRequest = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, null, null);\n};\ngoog.inherits(proto.pulumirpc.InvokeRequest, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.InvokeRequest.displayName = 'proto.pulumirpc.InvokeRequest';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.InvokeResponse = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, proto.pulumirpc.InvokeResponse.repeatedFields_, null);\n};\ngoog.inherits(proto.pulumirpc.InvokeResponse, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.InvokeResponse.displayName = 'proto.pulumirpc.InvokeResponse';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.CheckRequest = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, null, null);\n};\ngoog.inherits(proto.pulumirpc.CheckRequest, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.CheckRequest.displayName = 'proto.pulumirpc.CheckRequest';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.CheckResponse = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, proto.pulumirpc.CheckResponse.repeatedFields_, null);\n};\ngoog.inherits(proto.pulumirpc.CheckResponse, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.CheckResponse.displayName = 'proto.pulumirpc.CheckResponse';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.CheckFailure = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, null, null);\n};\ngoog.inherits(proto.pulumirpc.CheckFailure, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.CheckFailure.displayName = 'proto.pulumirpc.CheckFailure';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.DiffRequest = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, proto.pulumirpc.DiffRequest.repeatedFields_, null);\n};\ngoog.inherits(proto.pulumirpc.DiffRequest, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.DiffRequest.displayName = 'proto.pulumirpc.DiffRequest';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.PropertyDiff = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, null, null);\n};\ngoog.inherits(proto.pulumirpc.PropertyDiff, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.PropertyDiff.displayName = 'proto.pulumirpc.PropertyDiff';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.DiffResponse = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, proto.pulumirpc.DiffResponse.repeatedFields_, null);\n};\ngoog.inherits(proto.pulumirpc.DiffResponse, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.DiffResponse.displayName = 'proto.pulumirpc.DiffResponse';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.CreateRequest = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, null, null);\n};\ngoog.inherits(proto.pulumirpc.CreateRequest, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.CreateRequest.displayName = 'proto.pulumirpc.CreateRequest';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.CreateResponse = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, null, null);\n};\ngoog.inherits(proto.pulumirpc.CreateResponse, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.CreateResponse.displayName = 'proto.pulumirpc.CreateResponse';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.ReadRequest = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, null, null);\n};\ngoog.inherits(proto.pulumirpc.ReadRequest, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.ReadRequest.displayName = 'proto.pulumirpc.ReadRequest';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.ReadResponse = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, null, null);\n};\ngoog.inherits(proto.pulumirpc.ReadResponse, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.ReadResponse.displayName = 'proto.pulumirpc.ReadResponse';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.UpdateRequest = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, proto.pulumirpc.UpdateRequest.repeatedFields_, null);\n};\ngoog.inherits(proto.pulumirpc.UpdateRequest, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.UpdateRequest.displayName = 'proto.pulumirpc.UpdateRequest';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.UpdateResponse = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, null, null);\n};\ngoog.inherits(proto.pulumirpc.UpdateResponse, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.UpdateResponse.displayName = 'proto.pulumirpc.UpdateResponse';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.DeleteRequest = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, null, null);\n};\ngoog.inherits(proto.pulumirpc.DeleteRequest, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.DeleteRequest.displayName = 'proto.pulumirpc.DeleteRequest';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.ConstructRequest = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, proto.pulumirpc.ConstructRequest.repeatedFields_, null);\n};\ngoog.inherits(proto.pulumirpc.ConstructRequest, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.ConstructRequest.displayName = 'proto.pulumirpc.ConstructRequest';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.ConstructRequest.PropertyDependencies = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, proto.pulumirpc.ConstructRequest.PropertyDependencies.repeatedFields_, null);\n};\ngoog.inherits(proto.pulumirpc.ConstructRequest.PropertyDependencies, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.ConstructRequest.PropertyDependencies.displayName = 'proto.pulumirpc.ConstructRequest.PropertyDependencies';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.ConstructResponse = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, null, null);\n};\ngoog.inherits(proto.pulumirpc.ConstructResponse, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.ConstructResponse.displayName = 'proto.pulumirpc.ConstructResponse';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.ConstructResponse.PropertyDependencies = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, proto.pulumirpc.ConstructResponse.PropertyDependencies.repeatedFields_, null);\n};\ngoog.inherits(proto.pulumirpc.ConstructResponse.PropertyDependencies, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.ConstructResponse.PropertyDependencies.displayName = 'proto.pulumirpc.ConstructResponse.PropertyDependencies';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.ErrorResourceInitFailed = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, proto.pulumirpc.ErrorResourceInitFailed.repeatedFields_, null);\n};\ngoog.inherits(proto.pulumirpc.ErrorResourceInitFailed, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.ErrorResourceInitFailed.displayName = 'proto.pulumirpc.ErrorResourceInitFailed';\n}\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.GetSchemaRequest.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.GetSchemaRequest.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.GetSchemaRequest} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.GetSchemaRequest.toObject = function(includeInstance, msg) {\n var f, obj = {\n version: jspb.Message.getFieldWithDefault(msg, 1, 0)\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.GetSchemaRequest}\n */\nproto.pulumirpc.GetSchemaRequest.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.GetSchemaRequest;\n return proto.pulumirpc.GetSchemaRequest.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.GetSchemaRequest} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.GetSchemaRequest}\n */\nproto.pulumirpc.GetSchemaRequest.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {number} */ (reader.readInt32());\n msg.setVersion(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.GetSchemaRequest.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.GetSchemaRequest.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.GetSchemaRequest} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.GetSchemaRequest.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getVersion();\n if (f !== 0) {\n writer.writeInt32(\n 1,\n f\n );\n }\n};\n\n\n/**\n * optional int32 version = 1;\n * @return {number}\n */\nproto.pulumirpc.GetSchemaRequest.prototype.getVersion = function() {\n return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 1, 0));\n};\n\n\n/**\n * @param {number} value\n * @return {!proto.pulumirpc.GetSchemaRequest} returns this\n */\nproto.pulumirpc.GetSchemaRequest.prototype.setVersion = function(value) {\n return jspb.Message.setProto3IntField(this, 1, value);\n};\n\n\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.GetSchemaResponse.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.GetSchemaResponse.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.GetSchemaResponse} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.GetSchemaResponse.toObject = function(includeInstance, msg) {\n var f, obj = {\n schema: jspb.Message.getFieldWithDefault(msg, 1, \"\")\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.GetSchemaResponse}\n */\nproto.pulumirpc.GetSchemaResponse.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.GetSchemaResponse;\n return proto.pulumirpc.GetSchemaResponse.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.GetSchemaResponse} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.GetSchemaResponse}\n */\nproto.pulumirpc.GetSchemaResponse.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {string} */ (reader.readString());\n msg.setSchema(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.GetSchemaResponse.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.GetSchemaResponse.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.GetSchemaResponse} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.GetSchemaResponse.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getSchema();\n if (f.length > 0) {\n writer.writeString(\n 1,\n f\n );\n }\n};\n\n\n/**\n * optional string schema = 1;\n * @return {string}\n */\nproto.pulumirpc.GetSchemaResponse.prototype.getSchema = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.GetSchemaResponse} returns this\n */\nproto.pulumirpc.GetSchemaResponse.prototype.setSchema = function(value) {\n return jspb.Message.setProto3StringField(this, 1, value);\n};\n\n\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.ConfigureRequest.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.ConfigureRequest.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.ConfigureRequest} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.ConfigureRequest.toObject = function(includeInstance, msg) {\n var f, obj = {\n variablesMap: (f = msg.getVariablesMap()) ? f.toObject(includeInstance, undefined) : [],\n args: (f = msg.getArgs()) && google_protobuf_struct_pb.Struct.toObject(includeInstance, f),\n acceptsecrets: jspb.Message.getBooleanFieldWithDefault(msg, 3, false),\n acceptresources: jspb.Message.getBooleanFieldWithDefault(msg, 4, false)\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.ConfigureRequest}\n */\nproto.pulumirpc.ConfigureRequest.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.ConfigureRequest;\n return proto.pulumirpc.ConfigureRequest.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.ConfigureRequest} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.ConfigureRequest}\n */\nproto.pulumirpc.ConfigureRequest.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = msg.getVariablesMap();\n reader.readMessage(value, function(message, reader) {\n jspb.Map.deserializeBinary(message, reader, jspb.BinaryReader.prototype.readString, jspb.BinaryReader.prototype.readString, null, \"\", \"\");\n });\n break;\n case 2:\n var value = new google_protobuf_struct_pb.Struct;\n reader.readMessage(value,google_protobuf_struct_pb.Struct.deserializeBinaryFromReader);\n msg.setArgs(value);\n break;\n case 3:\n var value = /** @type {boolean} */ (reader.readBool());\n msg.setAcceptsecrets(value);\n break;\n case 4:\n var value = /** @type {boolean} */ (reader.readBool());\n msg.setAcceptresources(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.ConfigureRequest.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.ConfigureRequest.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.ConfigureRequest} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.ConfigureRequest.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getVariablesMap(true);\n if (f && f.getLength() > 0) {\n f.serializeBinary(1, writer, jspb.BinaryWriter.prototype.writeString, jspb.BinaryWriter.prototype.writeString);\n }\n f = message.getArgs();\n if (f != null) {\n writer.writeMessage(\n 2,\n f,\n google_protobuf_struct_pb.Struct.serializeBinaryToWriter\n );\n }\n f = message.getAcceptsecrets();\n if (f) {\n writer.writeBool(\n 3,\n f\n );\n }\n f = message.getAcceptresources();\n if (f) {\n writer.writeBool(\n 4,\n f\n );\n }\n};\n\n\n/**\n * map variables = 1;\n * @param {boolean=} opt_noLazyCreate Do not create the map if\n * empty, instead returning `undefined`\n * @return {!jspb.Map}\n */\nproto.pulumirpc.ConfigureRequest.prototype.getVariablesMap = function(opt_noLazyCreate) {\n return /** @type {!jspb.Map} */ (\n jspb.Message.getMapField(this, 1, opt_noLazyCreate,\n null));\n};\n\n\n/**\n * Clears values from the map. The map will be non-null.\n * @return {!proto.pulumirpc.ConfigureRequest} returns this\n */\nproto.pulumirpc.ConfigureRequest.prototype.clearVariablesMap = function() {\n this.getVariablesMap().clear();\n return this;};\n\n\n/**\n * optional google.protobuf.Struct args = 2;\n * @return {?proto.google.protobuf.Struct}\n */\nproto.pulumirpc.ConfigureRequest.prototype.getArgs = function() {\n return /** @type{?proto.google.protobuf.Struct} */ (\n jspb.Message.getWrapperField(this, google_protobuf_struct_pb.Struct, 2));\n};\n\n\n/**\n * @param {?proto.google.protobuf.Struct|undefined} value\n * @return {!proto.pulumirpc.ConfigureRequest} returns this\n*/\nproto.pulumirpc.ConfigureRequest.prototype.setArgs = function(value) {\n return jspb.Message.setWrapperField(this, 2, value);\n};\n\n\n/**\n * Clears the message field making it undefined.\n * @return {!proto.pulumirpc.ConfigureRequest} returns this\n */\nproto.pulumirpc.ConfigureRequest.prototype.clearArgs = function() {\n return this.setArgs(undefined);\n};\n\n\n/**\n * Returns whether this field is set.\n * @return {boolean}\n */\nproto.pulumirpc.ConfigureRequest.prototype.hasArgs = function() {\n return jspb.Message.getField(this, 2) != null;\n};\n\n\n/**\n * optional bool acceptSecrets = 3;\n * @return {boolean}\n */\nproto.pulumirpc.ConfigureRequest.prototype.getAcceptsecrets = function() {\n return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 3, false));\n};\n\n\n/**\n * @param {boolean} value\n * @return {!proto.pulumirpc.ConfigureRequest} returns this\n */\nproto.pulumirpc.ConfigureRequest.prototype.setAcceptsecrets = function(value) {\n return jspb.Message.setProto3BooleanField(this, 3, value);\n};\n\n\n/**\n * optional bool acceptResources = 4;\n * @return {boolean}\n */\nproto.pulumirpc.ConfigureRequest.prototype.getAcceptresources = function() {\n return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 4, false));\n};\n\n\n/**\n * @param {boolean} value\n * @return {!proto.pulumirpc.ConfigureRequest} returns this\n */\nproto.pulumirpc.ConfigureRequest.prototype.setAcceptresources = function(value) {\n return jspb.Message.setProto3BooleanField(this, 4, value);\n};\n\n\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.ConfigureResponse.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.ConfigureResponse.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.ConfigureResponse} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.ConfigureResponse.toObject = function(includeInstance, msg) {\n var f, obj = {\n acceptsecrets: jspb.Message.getBooleanFieldWithDefault(msg, 1, false),\n supportspreview: jspb.Message.getBooleanFieldWithDefault(msg, 2, false),\n acceptresources: jspb.Message.getBooleanFieldWithDefault(msg, 3, false)\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.ConfigureResponse}\n */\nproto.pulumirpc.ConfigureResponse.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.ConfigureResponse;\n return proto.pulumirpc.ConfigureResponse.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.ConfigureResponse} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.ConfigureResponse}\n */\nproto.pulumirpc.ConfigureResponse.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {boolean} */ (reader.readBool());\n msg.setAcceptsecrets(value);\n break;\n case 2:\n var value = /** @type {boolean} */ (reader.readBool());\n msg.setSupportspreview(value);\n break;\n case 3:\n var value = /** @type {boolean} */ (reader.readBool());\n msg.setAcceptresources(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.ConfigureResponse.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.ConfigureResponse.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.ConfigureResponse} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.ConfigureResponse.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getAcceptsecrets();\n if (f) {\n writer.writeBool(\n 1,\n f\n );\n }\n f = message.getSupportspreview();\n if (f) {\n writer.writeBool(\n 2,\n f\n );\n }\n f = message.getAcceptresources();\n if (f) {\n writer.writeBool(\n 3,\n f\n );\n }\n};\n\n\n/**\n * optional bool acceptSecrets = 1;\n * @return {boolean}\n */\nproto.pulumirpc.ConfigureResponse.prototype.getAcceptsecrets = function() {\n return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 1, false));\n};\n\n\n/**\n * @param {boolean} value\n * @return {!proto.pulumirpc.ConfigureResponse} returns this\n */\nproto.pulumirpc.ConfigureResponse.prototype.setAcceptsecrets = function(value) {\n return jspb.Message.setProto3BooleanField(this, 1, value);\n};\n\n\n/**\n * optional bool supportsPreview = 2;\n * @return {boolean}\n */\nproto.pulumirpc.ConfigureResponse.prototype.getSupportspreview = function() {\n return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 2, false));\n};\n\n\n/**\n * @param {boolean} value\n * @return {!proto.pulumirpc.ConfigureResponse} returns this\n */\nproto.pulumirpc.ConfigureResponse.prototype.setSupportspreview = function(value) {\n return jspb.Message.setProto3BooleanField(this, 2, value);\n};\n\n\n/**\n * optional bool acceptResources = 3;\n * @return {boolean}\n */\nproto.pulumirpc.ConfigureResponse.prototype.getAcceptresources = function() {\n return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 3, false));\n};\n\n\n/**\n * @param {boolean} value\n * @return {!proto.pulumirpc.ConfigureResponse} returns this\n */\nproto.pulumirpc.ConfigureResponse.prototype.setAcceptresources = function(value) {\n return jspb.Message.setProto3BooleanField(this, 3, value);\n};\n\n\n\n/**\n * List of repeated fields within this message type.\n * @private {!Array}\n * @const\n */\nproto.pulumirpc.ConfigureErrorMissingKeys.repeatedFields_ = [1];\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.ConfigureErrorMissingKeys.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.ConfigureErrorMissingKeys.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.ConfigureErrorMissingKeys} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.ConfigureErrorMissingKeys.toObject = function(includeInstance, msg) {\n var f, obj = {\n missingkeysList: jspb.Message.toObjectList(msg.getMissingkeysList(),\n proto.pulumirpc.ConfigureErrorMissingKeys.MissingKey.toObject, includeInstance)\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.ConfigureErrorMissingKeys}\n */\nproto.pulumirpc.ConfigureErrorMissingKeys.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.ConfigureErrorMissingKeys;\n return proto.pulumirpc.ConfigureErrorMissingKeys.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.ConfigureErrorMissingKeys} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.ConfigureErrorMissingKeys}\n */\nproto.pulumirpc.ConfigureErrorMissingKeys.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = new proto.pulumirpc.ConfigureErrorMissingKeys.MissingKey;\n reader.readMessage(value,proto.pulumirpc.ConfigureErrorMissingKeys.MissingKey.deserializeBinaryFromReader);\n msg.addMissingkeys(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.ConfigureErrorMissingKeys.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.ConfigureErrorMissingKeys.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.ConfigureErrorMissingKeys} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.ConfigureErrorMissingKeys.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getMissingkeysList();\n if (f.length > 0) {\n writer.writeRepeatedMessage(\n 1,\n f,\n proto.pulumirpc.ConfigureErrorMissingKeys.MissingKey.serializeBinaryToWriter\n );\n }\n};\n\n\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.ConfigureErrorMissingKeys.MissingKey.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.ConfigureErrorMissingKeys.MissingKey.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.ConfigureErrorMissingKeys.MissingKey} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.ConfigureErrorMissingKeys.MissingKey.toObject = function(includeInstance, msg) {\n var f, obj = {\n name: jspb.Message.getFieldWithDefault(msg, 1, \"\"),\n description: jspb.Message.getFieldWithDefault(msg, 2, \"\")\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.ConfigureErrorMissingKeys.MissingKey}\n */\nproto.pulumirpc.ConfigureErrorMissingKeys.MissingKey.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.ConfigureErrorMissingKeys.MissingKey;\n return proto.pulumirpc.ConfigureErrorMissingKeys.MissingKey.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.ConfigureErrorMissingKeys.MissingKey} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.ConfigureErrorMissingKeys.MissingKey}\n */\nproto.pulumirpc.ConfigureErrorMissingKeys.MissingKey.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {string} */ (reader.readString());\n msg.setName(value);\n break;\n case 2:\n var value = /** @type {string} */ (reader.readString());\n msg.setDescription(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.ConfigureErrorMissingKeys.MissingKey.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.ConfigureErrorMissingKeys.MissingKey.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.ConfigureErrorMissingKeys.MissingKey} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.ConfigureErrorMissingKeys.MissingKey.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getName();\n if (f.length > 0) {\n writer.writeString(\n 1,\n f\n );\n }\n f = message.getDescription();\n if (f.length > 0) {\n writer.writeString(\n 2,\n f\n );\n }\n};\n\n\n/**\n * optional string name = 1;\n * @return {string}\n */\nproto.pulumirpc.ConfigureErrorMissingKeys.MissingKey.prototype.getName = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.ConfigureErrorMissingKeys.MissingKey} returns this\n */\nproto.pulumirpc.ConfigureErrorMissingKeys.MissingKey.prototype.setName = function(value) {\n return jspb.Message.setProto3StringField(this, 1, value);\n};\n\n\n/**\n * optional string description = 2;\n * @return {string}\n */\nproto.pulumirpc.ConfigureErrorMissingKeys.MissingKey.prototype.getDescription = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.ConfigureErrorMissingKeys.MissingKey} returns this\n */\nproto.pulumirpc.ConfigureErrorMissingKeys.MissingKey.prototype.setDescription = function(value) {\n return jspb.Message.setProto3StringField(this, 2, value);\n};\n\n\n/**\n * repeated MissingKey missingKeys = 1;\n * @return {!Array}\n */\nproto.pulumirpc.ConfigureErrorMissingKeys.prototype.getMissingkeysList = function() {\n return /** @type{!Array} */ (\n jspb.Message.getRepeatedWrapperField(this, proto.pulumirpc.ConfigureErrorMissingKeys.MissingKey, 1));\n};\n\n\n/**\n * @param {!Array} value\n * @return {!proto.pulumirpc.ConfigureErrorMissingKeys} returns this\n*/\nproto.pulumirpc.ConfigureErrorMissingKeys.prototype.setMissingkeysList = function(value) {\n return jspb.Message.setRepeatedWrapperField(this, 1, value);\n};\n\n\n/**\n * @param {!proto.pulumirpc.ConfigureErrorMissingKeys.MissingKey=} opt_value\n * @param {number=} opt_index\n * @return {!proto.pulumirpc.ConfigureErrorMissingKeys.MissingKey}\n */\nproto.pulumirpc.ConfigureErrorMissingKeys.prototype.addMissingkeys = function(opt_value, opt_index) {\n return jspb.Message.addToRepeatedWrapperField(this, 1, opt_value, proto.pulumirpc.ConfigureErrorMissingKeys.MissingKey, opt_index);\n};\n\n\n/**\n * Clears the list making it empty but non-null.\n * @return {!proto.pulumirpc.ConfigureErrorMissingKeys} returns this\n */\nproto.pulumirpc.ConfigureErrorMissingKeys.prototype.clearMissingkeysList = function() {\n return this.setMissingkeysList([]);\n};\n\n\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.InvokeRequest.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.InvokeRequest.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.InvokeRequest} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.InvokeRequest.toObject = function(includeInstance, msg) {\n var f, obj = {\n tok: jspb.Message.getFieldWithDefault(msg, 1, \"\"),\n args: (f = msg.getArgs()) && google_protobuf_struct_pb.Struct.toObject(includeInstance, f),\n provider: jspb.Message.getFieldWithDefault(msg, 3, \"\"),\n version: jspb.Message.getFieldWithDefault(msg, 4, \"\"),\n acceptresources: jspb.Message.getBooleanFieldWithDefault(msg, 5, false)\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.InvokeRequest}\n */\nproto.pulumirpc.InvokeRequest.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.InvokeRequest;\n return proto.pulumirpc.InvokeRequest.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.InvokeRequest} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.InvokeRequest}\n */\nproto.pulumirpc.InvokeRequest.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {string} */ (reader.readString());\n msg.setTok(value);\n break;\n case 2:\n var value = new google_protobuf_struct_pb.Struct;\n reader.readMessage(value,google_protobuf_struct_pb.Struct.deserializeBinaryFromReader);\n msg.setArgs(value);\n break;\n case 3:\n var value = /** @type {string} */ (reader.readString());\n msg.setProvider(value);\n break;\n case 4:\n var value = /** @type {string} */ (reader.readString());\n msg.setVersion(value);\n break;\n case 5:\n var value = /** @type {boolean} */ (reader.readBool());\n msg.setAcceptresources(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.InvokeRequest.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.InvokeRequest.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.InvokeRequest} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.InvokeRequest.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getTok();\n if (f.length > 0) {\n writer.writeString(\n 1,\n f\n );\n }\n f = message.getArgs();\n if (f != null) {\n writer.writeMessage(\n 2,\n f,\n google_protobuf_struct_pb.Struct.serializeBinaryToWriter\n );\n }\n f = message.getProvider();\n if (f.length > 0) {\n writer.writeString(\n 3,\n f\n );\n }\n f = message.getVersion();\n if (f.length > 0) {\n writer.writeString(\n 4,\n f\n );\n }\n f = message.getAcceptresources();\n if (f) {\n writer.writeBool(\n 5,\n f\n );\n }\n};\n\n\n/**\n * optional string tok = 1;\n * @return {string}\n */\nproto.pulumirpc.InvokeRequest.prototype.getTok = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.InvokeRequest} returns this\n */\nproto.pulumirpc.InvokeRequest.prototype.setTok = function(value) {\n return jspb.Message.setProto3StringField(this, 1, value);\n};\n\n\n/**\n * optional google.protobuf.Struct args = 2;\n * @return {?proto.google.protobuf.Struct}\n */\nproto.pulumirpc.InvokeRequest.prototype.getArgs = function() {\n return /** @type{?proto.google.protobuf.Struct} */ (\n jspb.Message.getWrapperField(this, google_protobuf_struct_pb.Struct, 2));\n};\n\n\n/**\n * @param {?proto.google.protobuf.Struct|undefined} value\n * @return {!proto.pulumirpc.InvokeRequest} returns this\n*/\nproto.pulumirpc.InvokeRequest.prototype.setArgs = function(value) {\n return jspb.Message.setWrapperField(this, 2, value);\n};\n\n\n/**\n * Clears the message field making it undefined.\n * @return {!proto.pulumirpc.InvokeRequest} returns this\n */\nproto.pulumirpc.InvokeRequest.prototype.clearArgs = function() {\n return this.setArgs(undefined);\n};\n\n\n/**\n * Returns whether this field is set.\n * @return {boolean}\n */\nproto.pulumirpc.InvokeRequest.prototype.hasArgs = function() {\n return jspb.Message.getField(this, 2) != null;\n};\n\n\n/**\n * optional string provider = 3;\n * @return {string}\n */\nproto.pulumirpc.InvokeRequest.prototype.getProvider = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.InvokeRequest} returns this\n */\nproto.pulumirpc.InvokeRequest.prototype.setProvider = function(value) {\n return jspb.Message.setProto3StringField(this, 3, value);\n};\n\n\n/**\n * optional string version = 4;\n * @return {string}\n */\nproto.pulumirpc.InvokeRequest.prototype.getVersion = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 4, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.InvokeRequest} returns this\n */\nproto.pulumirpc.InvokeRequest.prototype.setVersion = function(value) {\n return jspb.Message.setProto3StringField(this, 4, value);\n};\n\n\n/**\n * optional bool acceptResources = 5;\n * @return {boolean}\n */\nproto.pulumirpc.InvokeRequest.prototype.getAcceptresources = function() {\n return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 5, false));\n};\n\n\n/**\n * @param {boolean} value\n * @return {!proto.pulumirpc.InvokeRequest} returns this\n */\nproto.pulumirpc.InvokeRequest.prototype.setAcceptresources = function(value) {\n return jspb.Message.setProto3BooleanField(this, 5, value);\n};\n\n\n\n/**\n * List of repeated fields within this message type.\n * @private {!Array}\n * @const\n */\nproto.pulumirpc.InvokeResponse.repeatedFields_ = [2];\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.InvokeResponse.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.InvokeResponse.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.InvokeResponse} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.InvokeResponse.toObject = function(includeInstance, msg) {\n var f, obj = {\n pb_return: (f = msg.getReturn()) && google_protobuf_struct_pb.Struct.toObject(includeInstance, f),\n failuresList: jspb.Message.toObjectList(msg.getFailuresList(),\n proto.pulumirpc.CheckFailure.toObject, includeInstance)\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.InvokeResponse}\n */\nproto.pulumirpc.InvokeResponse.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.InvokeResponse;\n return proto.pulumirpc.InvokeResponse.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.InvokeResponse} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.InvokeResponse}\n */\nproto.pulumirpc.InvokeResponse.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = new google_protobuf_struct_pb.Struct;\n reader.readMessage(value,google_protobuf_struct_pb.Struct.deserializeBinaryFromReader);\n msg.setReturn(value);\n break;\n case 2:\n var value = new proto.pulumirpc.CheckFailure;\n reader.readMessage(value,proto.pulumirpc.CheckFailure.deserializeBinaryFromReader);\n msg.addFailures(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.InvokeResponse.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.InvokeResponse.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.InvokeResponse} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.InvokeResponse.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getReturn();\n if (f != null) {\n writer.writeMessage(\n 1,\n f,\n google_protobuf_struct_pb.Struct.serializeBinaryToWriter\n );\n }\n f = message.getFailuresList();\n if (f.length > 0) {\n writer.writeRepeatedMessage(\n 2,\n f,\n proto.pulumirpc.CheckFailure.serializeBinaryToWriter\n );\n }\n};\n\n\n/**\n * optional google.protobuf.Struct return = 1;\n * @return {?proto.google.protobuf.Struct}\n */\nproto.pulumirpc.InvokeResponse.prototype.getReturn = function() {\n return /** @type{?proto.google.protobuf.Struct} */ (\n jspb.Message.getWrapperField(this, google_protobuf_struct_pb.Struct, 1));\n};\n\n\n/**\n * @param {?proto.google.protobuf.Struct|undefined} value\n * @return {!proto.pulumirpc.InvokeResponse} returns this\n*/\nproto.pulumirpc.InvokeResponse.prototype.setReturn = function(value) {\n return jspb.Message.setWrapperField(this, 1, value);\n};\n\n\n/**\n * Clears the message field making it undefined.\n * @return {!proto.pulumirpc.InvokeResponse} returns this\n */\nproto.pulumirpc.InvokeResponse.prototype.clearReturn = function() {\n return this.setReturn(undefined);\n};\n\n\n/**\n * Returns whether this field is set.\n * @return {boolean}\n */\nproto.pulumirpc.InvokeResponse.prototype.hasReturn = function() {\n return jspb.Message.getField(this, 1) != null;\n};\n\n\n/**\n * repeated CheckFailure failures = 2;\n * @return {!Array}\n */\nproto.pulumirpc.InvokeResponse.prototype.getFailuresList = function() {\n return /** @type{!Array} */ (\n jspb.Message.getRepeatedWrapperField(this, proto.pulumirpc.CheckFailure, 2));\n};\n\n\n/**\n * @param {!Array} value\n * @return {!proto.pulumirpc.InvokeResponse} returns this\n*/\nproto.pulumirpc.InvokeResponse.prototype.setFailuresList = function(value) {\n return jspb.Message.setRepeatedWrapperField(this, 2, value);\n};\n\n\n/**\n * @param {!proto.pulumirpc.CheckFailure=} opt_value\n * @param {number=} opt_index\n * @return {!proto.pulumirpc.CheckFailure}\n */\nproto.pulumirpc.InvokeResponse.prototype.addFailures = function(opt_value, opt_index) {\n return jspb.Message.addToRepeatedWrapperField(this, 2, opt_value, proto.pulumirpc.CheckFailure, opt_index);\n};\n\n\n/**\n * Clears the list making it empty but non-null.\n * @return {!proto.pulumirpc.InvokeResponse} returns this\n */\nproto.pulumirpc.InvokeResponse.prototype.clearFailuresList = function() {\n return this.setFailuresList([]);\n};\n\n\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.CheckRequest.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.CheckRequest.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.CheckRequest} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.CheckRequest.toObject = function(includeInstance, msg) {\n var f, obj = {\n urn: jspb.Message.getFieldWithDefault(msg, 1, \"\"),\n olds: (f = msg.getOlds()) && google_protobuf_struct_pb.Struct.toObject(includeInstance, f),\n news: (f = msg.getNews()) && google_protobuf_struct_pb.Struct.toObject(includeInstance, f)\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.CheckRequest}\n */\nproto.pulumirpc.CheckRequest.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.CheckRequest;\n return proto.pulumirpc.CheckRequest.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.CheckRequest} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.CheckRequest}\n */\nproto.pulumirpc.CheckRequest.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {string} */ (reader.readString());\n msg.setUrn(value);\n break;\n case 2:\n var value = new google_protobuf_struct_pb.Struct;\n reader.readMessage(value,google_protobuf_struct_pb.Struct.deserializeBinaryFromReader);\n msg.setOlds(value);\n break;\n case 3:\n var value = new google_protobuf_struct_pb.Struct;\n reader.readMessage(value,google_protobuf_struct_pb.Struct.deserializeBinaryFromReader);\n msg.setNews(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.CheckRequest.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.CheckRequest.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.CheckRequest} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.CheckRequest.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getUrn();\n if (f.length > 0) {\n writer.writeString(\n 1,\n f\n );\n }\n f = message.getOlds();\n if (f != null) {\n writer.writeMessage(\n 2,\n f,\n google_protobuf_struct_pb.Struct.serializeBinaryToWriter\n );\n }\n f = message.getNews();\n if (f != null) {\n writer.writeMessage(\n 3,\n f,\n google_protobuf_struct_pb.Struct.serializeBinaryToWriter\n );\n }\n};\n\n\n/**\n * optional string urn = 1;\n * @return {string}\n */\nproto.pulumirpc.CheckRequest.prototype.getUrn = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.CheckRequest} returns this\n */\nproto.pulumirpc.CheckRequest.prototype.setUrn = function(value) {\n return jspb.Message.setProto3StringField(this, 1, value);\n};\n\n\n/**\n * optional google.protobuf.Struct olds = 2;\n * @return {?proto.google.protobuf.Struct}\n */\nproto.pulumirpc.CheckRequest.prototype.getOlds = function() {\n return /** @type{?proto.google.protobuf.Struct} */ (\n jspb.Message.getWrapperField(this, google_protobuf_struct_pb.Struct, 2));\n};\n\n\n/**\n * @param {?proto.google.protobuf.Struct|undefined} value\n * @return {!proto.pulumirpc.CheckRequest} returns this\n*/\nproto.pulumirpc.CheckRequest.prototype.setOlds = function(value) {\n return jspb.Message.setWrapperField(this, 2, value);\n};\n\n\n/**\n * Clears the message field making it undefined.\n * @return {!proto.pulumirpc.CheckRequest} returns this\n */\nproto.pulumirpc.CheckRequest.prototype.clearOlds = function() {\n return this.setOlds(undefined);\n};\n\n\n/**\n * Returns whether this field is set.\n * @return {boolean}\n */\nproto.pulumirpc.CheckRequest.prototype.hasOlds = function() {\n return jspb.Message.getField(this, 2) != null;\n};\n\n\n/**\n * optional google.protobuf.Struct news = 3;\n * @return {?proto.google.protobuf.Struct}\n */\nproto.pulumirpc.CheckRequest.prototype.getNews = function() {\n return /** @type{?proto.google.protobuf.Struct} */ (\n jspb.Message.getWrapperField(this, google_protobuf_struct_pb.Struct, 3));\n};\n\n\n/**\n * @param {?proto.google.protobuf.Struct|undefined} value\n * @return {!proto.pulumirpc.CheckRequest} returns this\n*/\nproto.pulumirpc.CheckRequest.prototype.setNews = function(value) {\n return jspb.Message.setWrapperField(this, 3, value);\n};\n\n\n/**\n * Clears the message field making it undefined.\n * @return {!proto.pulumirpc.CheckRequest} returns this\n */\nproto.pulumirpc.CheckRequest.prototype.clearNews = function() {\n return this.setNews(undefined);\n};\n\n\n/**\n * Returns whether this field is set.\n * @return {boolean}\n */\nproto.pulumirpc.CheckRequest.prototype.hasNews = function() {\n return jspb.Message.getField(this, 3) != null;\n};\n\n\n\n/**\n * List of repeated fields within this message type.\n * @private {!Array}\n * @const\n */\nproto.pulumirpc.CheckResponse.repeatedFields_ = [2];\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.CheckResponse.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.CheckResponse.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.CheckResponse} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.CheckResponse.toObject = function(includeInstance, msg) {\n var f, obj = {\n inputs: (f = msg.getInputs()) && google_protobuf_struct_pb.Struct.toObject(includeInstance, f),\n failuresList: jspb.Message.toObjectList(msg.getFailuresList(),\n proto.pulumirpc.CheckFailure.toObject, includeInstance)\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.CheckResponse}\n */\nproto.pulumirpc.CheckResponse.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.CheckResponse;\n return proto.pulumirpc.CheckResponse.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.CheckResponse} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.CheckResponse}\n */\nproto.pulumirpc.CheckResponse.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = new google_protobuf_struct_pb.Struct;\n reader.readMessage(value,google_protobuf_struct_pb.Struct.deserializeBinaryFromReader);\n msg.setInputs(value);\n break;\n case 2:\n var value = new proto.pulumirpc.CheckFailure;\n reader.readMessage(value,proto.pulumirpc.CheckFailure.deserializeBinaryFromReader);\n msg.addFailures(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.CheckResponse.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.CheckResponse.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.CheckResponse} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.CheckResponse.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getInputs();\n if (f != null) {\n writer.writeMessage(\n 1,\n f,\n google_protobuf_struct_pb.Struct.serializeBinaryToWriter\n );\n }\n f = message.getFailuresList();\n if (f.length > 0) {\n writer.writeRepeatedMessage(\n 2,\n f,\n proto.pulumirpc.CheckFailure.serializeBinaryToWriter\n );\n }\n};\n\n\n/**\n * optional google.protobuf.Struct inputs = 1;\n * @return {?proto.google.protobuf.Struct}\n */\nproto.pulumirpc.CheckResponse.prototype.getInputs = function() {\n return /** @type{?proto.google.protobuf.Struct} */ (\n jspb.Message.getWrapperField(this, google_protobuf_struct_pb.Struct, 1));\n};\n\n\n/**\n * @param {?proto.google.protobuf.Struct|undefined} value\n * @return {!proto.pulumirpc.CheckResponse} returns this\n*/\nproto.pulumirpc.CheckResponse.prototype.setInputs = function(value) {\n return jspb.Message.setWrapperField(this, 1, value);\n};\n\n\n/**\n * Clears the message field making it undefined.\n * @return {!proto.pulumirpc.CheckResponse} returns this\n */\nproto.pulumirpc.CheckResponse.prototype.clearInputs = function() {\n return this.setInputs(undefined);\n};\n\n\n/**\n * Returns whether this field is set.\n * @return {boolean}\n */\nproto.pulumirpc.CheckResponse.prototype.hasInputs = function() {\n return jspb.Message.getField(this, 1) != null;\n};\n\n\n/**\n * repeated CheckFailure failures = 2;\n * @return {!Array}\n */\nproto.pulumirpc.CheckResponse.prototype.getFailuresList = function() {\n return /** @type{!Array} */ (\n jspb.Message.getRepeatedWrapperField(this, proto.pulumirpc.CheckFailure, 2));\n};\n\n\n/**\n * @param {!Array} value\n * @return {!proto.pulumirpc.CheckResponse} returns this\n*/\nproto.pulumirpc.CheckResponse.prototype.setFailuresList = function(value) {\n return jspb.Message.setRepeatedWrapperField(this, 2, value);\n};\n\n\n/**\n * @param {!proto.pulumirpc.CheckFailure=} opt_value\n * @param {number=} opt_index\n * @return {!proto.pulumirpc.CheckFailure}\n */\nproto.pulumirpc.CheckResponse.prototype.addFailures = function(opt_value, opt_index) {\n return jspb.Message.addToRepeatedWrapperField(this, 2, opt_value, proto.pulumirpc.CheckFailure, opt_index);\n};\n\n\n/**\n * Clears the list making it empty but non-null.\n * @return {!proto.pulumirpc.CheckResponse} returns this\n */\nproto.pulumirpc.CheckResponse.prototype.clearFailuresList = function() {\n return this.setFailuresList([]);\n};\n\n\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.CheckFailure.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.CheckFailure.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.CheckFailure} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.CheckFailure.toObject = function(includeInstance, msg) {\n var f, obj = {\n property: jspb.Message.getFieldWithDefault(msg, 1, \"\"),\n reason: jspb.Message.getFieldWithDefault(msg, 2, \"\")\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.CheckFailure}\n */\nproto.pulumirpc.CheckFailure.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.CheckFailure;\n return proto.pulumirpc.CheckFailure.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.CheckFailure} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.CheckFailure}\n */\nproto.pulumirpc.CheckFailure.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {string} */ (reader.readString());\n msg.setProperty(value);\n break;\n case 2:\n var value = /** @type {string} */ (reader.readString());\n msg.setReason(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.CheckFailure.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.CheckFailure.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.CheckFailure} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.CheckFailure.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getProperty();\n if (f.length > 0) {\n writer.writeString(\n 1,\n f\n );\n }\n f = message.getReason();\n if (f.length > 0) {\n writer.writeString(\n 2,\n f\n );\n }\n};\n\n\n/**\n * optional string property = 1;\n * @return {string}\n */\nproto.pulumirpc.CheckFailure.prototype.getProperty = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.CheckFailure} returns this\n */\nproto.pulumirpc.CheckFailure.prototype.setProperty = function(value) {\n return jspb.Message.setProto3StringField(this, 1, value);\n};\n\n\n/**\n * optional string reason = 2;\n * @return {string}\n */\nproto.pulumirpc.CheckFailure.prototype.getReason = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.CheckFailure} returns this\n */\nproto.pulumirpc.CheckFailure.prototype.setReason = function(value) {\n return jspb.Message.setProto3StringField(this, 2, value);\n};\n\n\n\n/**\n * List of repeated fields within this message type.\n * @private {!Array}\n * @const\n */\nproto.pulumirpc.DiffRequest.repeatedFields_ = [5];\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.DiffRequest.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.DiffRequest.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.DiffRequest} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.DiffRequest.toObject = function(includeInstance, msg) {\n var f, obj = {\n id: jspb.Message.getFieldWithDefault(msg, 1, \"\"),\n urn: jspb.Message.getFieldWithDefault(msg, 2, \"\"),\n olds: (f = msg.getOlds()) && google_protobuf_struct_pb.Struct.toObject(includeInstance, f),\n news: (f = msg.getNews()) && google_protobuf_struct_pb.Struct.toObject(includeInstance, f),\n ignorechangesList: (f = jspb.Message.getRepeatedField(msg, 5)) == null ? undefined : f\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.DiffRequest}\n */\nproto.pulumirpc.DiffRequest.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.DiffRequest;\n return proto.pulumirpc.DiffRequest.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.DiffRequest} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.DiffRequest}\n */\nproto.pulumirpc.DiffRequest.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {string} */ (reader.readString());\n msg.setId(value);\n break;\n case 2:\n var value = /** @type {string} */ (reader.readString());\n msg.setUrn(value);\n break;\n case 3:\n var value = new google_protobuf_struct_pb.Struct;\n reader.readMessage(value,google_protobuf_struct_pb.Struct.deserializeBinaryFromReader);\n msg.setOlds(value);\n break;\n case 4:\n var value = new google_protobuf_struct_pb.Struct;\n reader.readMessage(value,google_protobuf_struct_pb.Struct.deserializeBinaryFromReader);\n msg.setNews(value);\n break;\n case 5:\n var value = /** @type {string} */ (reader.readString());\n msg.addIgnorechanges(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.DiffRequest.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.DiffRequest.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.DiffRequest} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.DiffRequest.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getId();\n if (f.length > 0) {\n writer.writeString(\n 1,\n f\n );\n }\n f = message.getUrn();\n if (f.length > 0) {\n writer.writeString(\n 2,\n f\n );\n }\n f = message.getOlds();\n if (f != null) {\n writer.writeMessage(\n 3,\n f,\n google_protobuf_struct_pb.Struct.serializeBinaryToWriter\n );\n }\n f = message.getNews();\n if (f != null) {\n writer.writeMessage(\n 4,\n f,\n google_protobuf_struct_pb.Struct.serializeBinaryToWriter\n );\n }\n f = message.getIgnorechangesList();\n if (f.length > 0) {\n writer.writeRepeatedString(\n 5,\n f\n );\n }\n};\n\n\n/**\n * optional string id = 1;\n * @return {string}\n */\nproto.pulumirpc.DiffRequest.prototype.getId = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.DiffRequest} returns this\n */\nproto.pulumirpc.DiffRequest.prototype.setId = function(value) {\n return jspb.Message.setProto3StringField(this, 1, value);\n};\n\n\n/**\n * optional string urn = 2;\n * @return {string}\n */\nproto.pulumirpc.DiffRequest.prototype.getUrn = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.DiffRequest} returns this\n */\nproto.pulumirpc.DiffRequest.prototype.setUrn = function(value) {\n return jspb.Message.setProto3StringField(this, 2, value);\n};\n\n\n/**\n * optional google.protobuf.Struct olds = 3;\n * @return {?proto.google.protobuf.Struct}\n */\nproto.pulumirpc.DiffRequest.prototype.getOlds = function() {\n return /** @type{?proto.google.protobuf.Struct} */ (\n jspb.Message.getWrapperField(this, google_protobuf_struct_pb.Struct, 3));\n};\n\n\n/**\n * @param {?proto.google.protobuf.Struct|undefined} value\n * @return {!proto.pulumirpc.DiffRequest} returns this\n*/\nproto.pulumirpc.DiffRequest.prototype.setOlds = function(value) {\n return jspb.Message.setWrapperField(this, 3, value);\n};\n\n\n/**\n * Clears the message field making it undefined.\n * @return {!proto.pulumirpc.DiffRequest} returns this\n */\nproto.pulumirpc.DiffRequest.prototype.clearOlds = function() {\n return this.setOlds(undefined);\n};\n\n\n/**\n * Returns whether this field is set.\n * @return {boolean}\n */\nproto.pulumirpc.DiffRequest.prototype.hasOlds = function() {\n return jspb.Message.getField(this, 3) != null;\n};\n\n\n/**\n * optional google.protobuf.Struct news = 4;\n * @return {?proto.google.protobuf.Struct}\n */\nproto.pulumirpc.DiffRequest.prototype.getNews = function() {\n return /** @type{?proto.google.protobuf.Struct} */ (\n jspb.Message.getWrapperField(this, google_protobuf_struct_pb.Struct, 4));\n};\n\n\n/**\n * @param {?proto.google.protobuf.Struct|undefined} value\n * @return {!proto.pulumirpc.DiffRequest} returns this\n*/\nproto.pulumirpc.DiffRequest.prototype.setNews = function(value) {\n return jspb.Message.setWrapperField(this, 4, value);\n};\n\n\n/**\n * Clears the message field making it undefined.\n * @return {!proto.pulumirpc.DiffRequest} returns this\n */\nproto.pulumirpc.DiffRequest.prototype.clearNews = function() {\n return this.setNews(undefined);\n};\n\n\n/**\n * Returns whether this field is set.\n * @return {boolean}\n */\nproto.pulumirpc.DiffRequest.prototype.hasNews = function() {\n return jspb.Message.getField(this, 4) != null;\n};\n\n\n/**\n * repeated string ignoreChanges = 5;\n * @return {!Array}\n */\nproto.pulumirpc.DiffRequest.prototype.getIgnorechangesList = function() {\n return /** @type {!Array} */ (jspb.Message.getRepeatedField(this, 5));\n};\n\n\n/**\n * @param {!Array} value\n * @return {!proto.pulumirpc.DiffRequest} returns this\n */\nproto.pulumirpc.DiffRequest.prototype.setIgnorechangesList = function(value) {\n return jspb.Message.setField(this, 5, value || []);\n};\n\n\n/**\n * @param {string} value\n * @param {number=} opt_index\n * @return {!proto.pulumirpc.DiffRequest} returns this\n */\nproto.pulumirpc.DiffRequest.prototype.addIgnorechanges = function(value, opt_index) {\n return jspb.Message.addToRepeatedField(this, 5, value, opt_index);\n};\n\n\n/**\n * Clears the list making it empty but non-null.\n * @return {!proto.pulumirpc.DiffRequest} returns this\n */\nproto.pulumirpc.DiffRequest.prototype.clearIgnorechangesList = function() {\n return this.setIgnorechangesList([]);\n};\n\n\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.PropertyDiff.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.PropertyDiff.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.PropertyDiff} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.PropertyDiff.toObject = function(includeInstance, msg) {\n var f, obj = {\n kind: jspb.Message.getFieldWithDefault(msg, 1, 0),\n inputdiff: jspb.Message.getBooleanFieldWithDefault(msg, 2, false)\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.PropertyDiff}\n */\nproto.pulumirpc.PropertyDiff.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.PropertyDiff;\n return proto.pulumirpc.PropertyDiff.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.PropertyDiff} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.PropertyDiff}\n */\nproto.pulumirpc.PropertyDiff.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {!proto.pulumirpc.PropertyDiff.Kind} */ (reader.readEnum());\n msg.setKind(value);\n break;\n case 2:\n var value = /** @type {boolean} */ (reader.readBool());\n msg.setInputdiff(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.PropertyDiff.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.PropertyDiff.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.PropertyDiff} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.PropertyDiff.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getKind();\n if (f !== 0.0) {\n writer.writeEnum(\n 1,\n f\n );\n }\n f = message.getInputdiff();\n if (f) {\n writer.writeBool(\n 2,\n f\n );\n }\n};\n\n\n/**\n * @enum {number}\n */\nproto.pulumirpc.PropertyDiff.Kind = {\n ADD: 0,\n ADD_REPLACE: 1,\n DELETE: 2,\n DELETE_REPLACE: 3,\n UPDATE: 4,\n UPDATE_REPLACE: 5\n};\n\n/**\n * optional Kind kind = 1;\n * @return {!proto.pulumirpc.PropertyDiff.Kind}\n */\nproto.pulumirpc.PropertyDiff.prototype.getKind = function() {\n return /** @type {!proto.pulumirpc.PropertyDiff.Kind} */ (jspb.Message.getFieldWithDefault(this, 1, 0));\n};\n\n\n/**\n * @param {!proto.pulumirpc.PropertyDiff.Kind} value\n * @return {!proto.pulumirpc.PropertyDiff} returns this\n */\nproto.pulumirpc.PropertyDiff.prototype.setKind = function(value) {\n return jspb.Message.setProto3EnumField(this, 1, value);\n};\n\n\n/**\n * optional bool inputDiff = 2;\n * @return {boolean}\n */\nproto.pulumirpc.PropertyDiff.prototype.getInputdiff = function() {\n return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 2, false));\n};\n\n\n/**\n * @param {boolean} value\n * @return {!proto.pulumirpc.PropertyDiff} returns this\n */\nproto.pulumirpc.PropertyDiff.prototype.setInputdiff = function(value) {\n return jspb.Message.setProto3BooleanField(this, 2, value);\n};\n\n\n\n/**\n * List of repeated fields within this message type.\n * @private {!Array}\n * @const\n */\nproto.pulumirpc.DiffResponse.repeatedFields_ = [1,2,5];\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.DiffResponse.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.DiffResponse.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.DiffResponse} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.DiffResponse.toObject = function(includeInstance, msg) {\n var f, obj = {\n replacesList: (f = jspb.Message.getRepeatedField(msg, 1)) == null ? undefined : f,\n stablesList: (f = jspb.Message.getRepeatedField(msg, 2)) == null ? undefined : f,\n deletebeforereplace: jspb.Message.getBooleanFieldWithDefault(msg, 3, false),\n changes: jspb.Message.getFieldWithDefault(msg, 4, 0),\n diffsList: (f = jspb.Message.getRepeatedField(msg, 5)) == null ? undefined : f,\n detaileddiffMap: (f = msg.getDetaileddiffMap()) ? f.toObject(includeInstance, proto.pulumirpc.PropertyDiff.toObject) : [],\n hasdetaileddiff: jspb.Message.getBooleanFieldWithDefault(msg, 7, false)\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.DiffResponse}\n */\nproto.pulumirpc.DiffResponse.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.DiffResponse;\n return proto.pulumirpc.DiffResponse.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.DiffResponse} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.DiffResponse}\n */\nproto.pulumirpc.DiffResponse.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {string} */ (reader.readString());\n msg.addReplaces(value);\n break;\n case 2:\n var value = /** @type {string} */ (reader.readString());\n msg.addStables(value);\n break;\n case 3:\n var value = /** @type {boolean} */ (reader.readBool());\n msg.setDeletebeforereplace(value);\n break;\n case 4:\n var value = /** @type {!proto.pulumirpc.DiffResponse.DiffChanges} */ (reader.readEnum());\n msg.setChanges(value);\n break;\n case 5:\n var value = /** @type {string} */ (reader.readString());\n msg.addDiffs(value);\n break;\n case 6:\n var value = msg.getDetaileddiffMap();\n reader.readMessage(value, function(message, reader) {\n jspb.Map.deserializeBinary(message, reader, jspb.BinaryReader.prototype.readString, jspb.BinaryReader.prototype.readMessage, proto.pulumirpc.PropertyDiff.deserializeBinaryFromReader, \"\", new proto.pulumirpc.PropertyDiff());\n });\n break;\n case 7:\n var value = /** @type {boolean} */ (reader.readBool());\n msg.setHasdetaileddiff(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.DiffResponse.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.DiffResponse.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.DiffResponse} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.DiffResponse.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getReplacesList();\n if (f.length > 0) {\n writer.writeRepeatedString(\n 1,\n f\n );\n }\n f = message.getStablesList();\n if (f.length > 0) {\n writer.writeRepeatedString(\n 2,\n f\n );\n }\n f = message.getDeletebeforereplace();\n if (f) {\n writer.writeBool(\n 3,\n f\n );\n }\n f = message.getChanges();\n if (f !== 0.0) {\n writer.writeEnum(\n 4,\n f\n );\n }\n f = message.getDiffsList();\n if (f.length > 0) {\n writer.writeRepeatedString(\n 5,\n f\n );\n }\n f = message.getDetaileddiffMap(true);\n if (f && f.getLength() > 0) {\n f.serializeBinary(6, writer, jspb.BinaryWriter.prototype.writeString, jspb.BinaryWriter.prototype.writeMessage, proto.pulumirpc.PropertyDiff.serializeBinaryToWriter);\n }\n f = message.getHasdetaileddiff();\n if (f) {\n writer.writeBool(\n 7,\n f\n );\n }\n};\n\n\n/**\n * @enum {number}\n */\nproto.pulumirpc.DiffResponse.DiffChanges = {\n DIFF_UNKNOWN: 0,\n DIFF_NONE: 1,\n DIFF_SOME: 2\n};\n\n/**\n * repeated string replaces = 1;\n * @return {!Array}\n */\nproto.pulumirpc.DiffResponse.prototype.getReplacesList = function() {\n return /** @type {!Array} */ (jspb.Message.getRepeatedField(this, 1));\n};\n\n\n/**\n * @param {!Array} value\n * @return {!proto.pulumirpc.DiffResponse} returns this\n */\nproto.pulumirpc.DiffResponse.prototype.setReplacesList = function(value) {\n return jspb.Message.setField(this, 1, value || []);\n};\n\n\n/**\n * @param {string} value\n * @param {number=} opt_index\n * @return {!proto.pulumirpc.DiffResponse} returns this\n */\nproto.pulumirpc.DiffResponse.prototype.addReplaces = function(value, opt_index) {\n return jspb.Message.addToRepeatedField(this, 1, value, opt_index);\n};\n\n\n/**\n * Clears the list making it empty but non-null.\n * @return {!proto.pulumirpc.DiffResponse} returns this\n */\nproto.pulumirpc.DiffResponse.prototype.clearReplacesList = function() {\n return this.setReplacesList([]);\n};\n\n\n/**\n * repeated string stables = 2;\n * @return {!Array}\n */\nproto.pulumirpc.DiffResponse.prototype.getStablesList = function() {\n return /** @type {!Array} */ (jspb.Message.getRepeatedField(this, 2));\n};\n\n\n/**\n * @param {!Array} value\n * @return {!proto.pulumirpc.DiffResponse} returns this\n */\nproto.pulumirpc.DiffResponse.prototype.setStablesList = function(value) {\n return jspb.Message.setField(this, 2, value || []);\n};\n\n\n/**\n * @param {string} value\n * @param {number=} opt_index\n * @return {!proto.pulumirpc.DiffResponse} returns this\n */\nproto.pulumirpc.DiffResponse.prototype.addStables = function(value, opt_index) {\n return jspb.Message.addToRepeatedField(this, 2, value, opt_index);\n};\n\n\n/**\n * Clears the list making it empty but non-null.\n * @return {!proto.pulumirpc.DiffResponse} returns this\n */\nproto.pulumirpc.DiffResponse.prototype.clearStablesList = function() {\n return this.setStablesList([]);\n};\n\n\n/**\n * optional bool deleteBeforeReplace = 3;\n * @return {boolean}\n */\nproto.pulumirpc.DiffResponse.prototype.getDeletebeforereplace = function() {\n return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 3, false));\n};\n\n\n/**\n * @param {boolean} value\n * @return {!proto.pulumirpc.DiffResponse} returns this\n */\nproto.pulumirpc.DiffResponse.prototype.setDeletebeforereplace = function(value) {\n return jspb.Message.setProto3BooleanField(this, 3, value);\n};\n\n\n/**\n * optional DiffChanges changes = 4;\n * @return {!proto.pulumirpc.DiffResponse.DiffChanges}\n */\nproto.pulumirpc.DiffResponse.prototype.getChanges = function() {\n return /** @type {!proto.pulumirpc.DiffResponse.DiffChanges} */ (jspb.Message.getFieldWithDefault(this, 4, 0));\n};\n\n\n/**\n * @param {!proto.pulumirpc.DiffResponse.DiffChanges} value\n * @return {!proto.pulumirpc.DiffResponse} returns this\n */\nproto.pulumirpc.DiffResponse.prototype.setChanges = function(value) {\n return jspb.Message.setProto3EnumField(this, 4, value);\n};\n\n\n/**\n * repeated string diffs = 5;\n * @return {!Array}\n */\nproto.pulumirpc.DiffResponse.prototype.getDiffsList = function() {\n return /** @type {!Array} */ (jspb.Message.getRepeatedField(this, 5));\n};\n\n\n/**\n * @param {!Array} value\n * @return {!proto.pulumirpc.DiffResponse} returns this\n */\nproto.pulumirpc.DiffResponse.prototype.setDiffsList = function(value) {\n return jspb.Message.setField(this, 5, value || []);\n};\n\n\n/**\n * @param {string} value\n * @param {number=} opt_index\n * @return {!proto.pulumirpc.DiffResponse} returns this\n */\nproto.pulumirpc.DiffResponse.prototype.addDiffs = function(value, opt_index) {\n return jspb.Message.addToRepeatedField(this, 5, value, opt_index);\n};\n\n\n/**\n * Clears the list making it empty but non-null.\n * @return {!proto.pulumirpc.DiffResponse} returns this\n */\nproto.pulumirpc.DiffResponse.prototype.clearDiffsList = function() {\n return this.setDiffsList([]);\n};\n\n\n/**\n * map detailedDiff = 6;\n * @param {boolean=} opt_noLazyCreate Do not create the map if\n * empty, instead returning `undefined`\n * @return {!jspb.Map}\n */\nproto.pulumirpc.DiffResponse.prototype.getDetaileddiffMap = function(opt_noLazyCreate) {\n return /** @type {!jspb.Map} */ (\n jspb.Message.getMapField(this, 6, opt_noLazyCreate,\n proto.pulumirpc.PropertyDiff));\n};\n\n\n/**\n * Clears values from the map. The map will be non-null.\n * @return {!proto.pulumirpc.DiffResponse} returns this\n */\nproto.pulumirpc.DiffResponse.prototype.clearDetaileddiffMap = function() {\n this.getDetaileddiffMap().clear();\n return this;};\n\n\n/**\n * optional bool hasDetailedDiff = 7;\n * @return {boolean}\n */\nproto.pulumirpc.DiffResponse.prototype.getHasdetaileddiff = function() {\n return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 7, false));\n};\n\n\n/**\n * @param {boolean} value\n * @return {!proto.pulumirpc.DiffResponse} returns this\n */\nproto.pulumirpc.DiffResponse.prototype.setHasdetaileddiff = function(value) {\n return jspb.Message.setProto3BooleanField(this, 7, value);\n};\n\n\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.CreateRequest.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.CreateRequest.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.CreateRequest} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.CreateRequest.toObject = function(includeInstance, msg) {\n var f, obj = {\n urn: jspb.Message.getFieldWithDefault(msg, 1, \"\"),\n properties: (f = msg.getProperties()) && google_protobuf_struct_pb.Struct.toObject(includeInstance, f),\n timeout: jspb.Message.getFloatingPointFieldWithDefault(msg, 3, 0.0),\n preview: jspb.Message.getBooleanFieldWithDefault(msg, 4, false)\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.CreateRequest}\n */\nproto.pulumirpc.CreateRequest.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.CreateRequest;\n return proto.pulumirpc.CreateRequest.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.CreateRequest} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.CreateRequest}\n */\nproto.pulumirpc.CreateRequest.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {string} */ (reader.readString());\n msg.setUrn(value);\n break;\n case 2:\n var value = new google_protobuf_struct_pb.Struct;\n reader.readMessage(value,google_protobuf_struct_pb.Struct.deserializeBinaryFromReader);\n msg.setProperties(value);\n break;\n case 3:\n var value = /** @type {number} */ (reader.readDouble());\n msg.setTimeout(value);\n break;\n case 4:\n var value = /** @type {boolean} */ (reader.readBool());\n msg.setPreview(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.CreateRequest.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.CreateRequest.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.CreateRequest} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.CreateRequest.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getUrn();\n if (f.length > 0) {\n writer.writeString(\n 1,\n f\n );\n }\n f = message.getProperties();\n if (f != null) {\n writer.writeMessage(\n 2,\n f,\n google_protobuf_struct_pb.Struct.serializeBinaryToWriter\n );\n }\n f = message.getTimeout();\n if (f !== 0.0) {\n writer.writeDouble(\n 3,\n f\n );\n }\n f = message.getPreview();\n if (f) {\n writer.writeBool(\n 4,\n f\n );\n }\n};\n\n\n/**\n * optional string urn = 1;\n * @return {string}\n */\nproto.pulumirpc.CreateRequest.prototype.getUrn = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.CreateRequest} returns this\n */\nproto.pulumirpc.CreateRequest.prototype.setUrn = function(value) {\n return jspb.Message.setProto3StringField(this, 1, value);\n};\n\n\n/**\n * optional google.protobuf.Struct properties = 2;\n * @return {?proto.google.protobuf.Struct}\n */\nproto.pulumirpc.CreateRequest.prototype.getProperties = function() {\n return /** @type{?proto.google.protobuf.Struct} */ (\n jspb.Message.getWrapperField(this, google_protobuf_struct_pb.Struct, 2));\n};\n\n\n/**\n * @param {?proto.google.protobuf.Struct|undefined} value\n * @return {!proto.pulumirpc.CreateRequest} returns this\n*/\nproto.pulumirpc.CreateRequest.prototype.setProperties = function(value) {\n return jspb.Message.setWrapperField(this, 2, value);\n};\n\n\n/**\n * Clears the message field making it undefined.\n * @return {!proto.pulumirpc.CreateRequest} returns this\n */\nproto.pulumirpc.CreateRequest.prototype.clearProperties = function() {\n return this.setProperties(undefined);\n};\n\n\n/**\n * Returns whether this field is set.\n * @return {boolean}\n */\nproto.pulumirpc.CreateRequest.prototype.hasProperties = function() {\n return jspb.Message.getField(this, 2) != null;\n};\n\n\n/**\n * optional double timeout = 3;\n * @return {number}\n */\nproto.pulumirpc.CreateRequest.prototype.getTimeout = function() {\n return /** @type {number} */ (jspb.Message.getFloatingPointFieldWithDefault(this, 3, 0.0));\n};\n\n\n/**\n * @param {number} value\n * @return {!proto.pulumirpc.CreateRequest} returns this\n */\nproto.pulumirpc.CreateRequest.prototype.setTimeout = function(value) {\n return jspb.Message.setProto3FloatField(this, 3, value);\n};\n\n\n/**\n * optional bool preview = 4;\n * @return {boolean}\n */\nproto.pulumirpc.CreateRequest.prototype.getPreview = function() {\n return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 4, false));\n};\n\n\n/**\n * @param {boolean} value\n * @return {!proto.pulumirpc.CreateRequest} returns this\n */\nproto.pulumirpc.CreateRequest.prototype.setPreview = function(value) {\n return jspb.Message.setProto3BooleanField(this, 4, value);\n};\n\n\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.CreateResponse.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.CreateResponse.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.CreateResponse} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.CreateResponse.toObject = function(includeInstance, msg) {\n var f, obj = {\n id: jspb.Message.getFieldWithDefault(msg, 1, \"\"),\n properties: (f = msg.getProperties()) && google_protobuf_struct_pb.Struct.toObject(includeInstance, f)\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.CreateResponse}\n */\nproto.pulumirpc.CreateResponse.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.CreateResponse;\n return proto.pulumirpc.CreateResponse.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.CreateResponse} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.CreateResponse}\n */\nproto.pulumirpc.CreateResponse.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {string} */ (reader.readString());\n msg.setId(value);\n break;\n case 2:\n var value = new google_protobuf_struct_pb.Struct;\n reader.readMessage(value,google_protobuf_struct_pb.Struct.deserializeBinaryFromReader);\n msg.setProperties(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.CreateResponse.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.CreateResponse.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.CreateResponse} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.CreateResponse.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getId();\n if (f.length > 0) {\n writer.writeString(\n 1,\n f\n );\n }\n f = message.getProperties();\n if (f != null) {\n writer.writeMessage(\n 2,\n f,\n google_protobuf_struct_pb.Struct.serializeBinaryToWriter\n );\n }\n};\n\n\n/**\n * optional string id = 1;\n * @return {string}\n */\nproto.pulumirpc.CreateResponse.prototype.getId = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.CreateResponse} returns this\n */\nproto.pulumirpc.CreateResponse.prototype.setId = function(value) {\n return jspb.Message.setProto3StringField(this, 1, value);\n};\n\n\n/**\n * optional google.protobuf.Struct properties = 2;\n * @return {?proto.google.protobuf.Struct}\n */\nproto.pulumirpc.CreateResponse.prototype.getProperties = function() {\n return /** @type{?proto.google.protobuf.Struct} */ (\n jspb.Message.getWrapperField(this, google_protobuf_struct_pb.Struct, 2));\n};\n\n\n/**\n * @param {?proto.google.protobuf.Struct|undefined} value\n * @return {!proto.pulumirpc.CreateResponse} returns this\n*/\nproto.pulumirpc.CreateResponse.prototype.setProperties = function(value) {\n return jspb.Message.setWrapperField(this, 2, value);\n};\n\n\n/**\n * Clears the message field making it undefined.\n * @return {!proto.pulumirpc.CreateResponse} returns this\n */\nproto.pulumirpc.CreateResponse.prototype.clearProperties = function() {\n return this.setProperties(undefined);\n};\n\n\n/**\n * Returns whether this field is set.\n * @return {boolean}\n */\nproto.pulumirpc.CreateResponse.prototype.hasProperties = function() {\n return jspb.Message.getField(this, 2) != null;\n};\n\n\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.ReadRequest.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.ReadRequest.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.ReadRequest} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.ReadRequest.toObject = function(includeInstance, msg) {\n var f, obj = {\n id: jspb.Message.getFieldWithDefault(msg, 1, \"\"),\n urn: jspb.Message.getFieldWithDefault(msg, 2, \"\"),\n properties: (f = msg.getProperties()) && google_protobuf_struct_pb.Struct.toObject(includeInstance, f),\n inputs: (f = msg.getInputs()) && google_protobuf_struct_pb.Struct.toObject(includeInstance, f)\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.ReadRequest}\n */\nproto.pulumirpc.ReadRequest.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.ReadRequest;\n return proto.pulumirpc.ReadRequest.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.ReadRequest} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.ReadRequest}\n */\nproto.pulumirpc.ReadRequest.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {string} */ (reader.readString());\n msg.setId(value);\n break;\n case 2:\n var value = /** @type {string} */ (reader.readString());\n msg.setUrn(value);\n break;\n case 3:\n var value = new google_protobuf_struct_pb.Struct;\n reader.readMessage(value,google_protobuf_struct_pb.Struct.deserializeBinaryFromReader);\n msg.setProperties(value);\n break;\n case 4:\n var value = new google_protobuf_struct_pb.Struct;\n reader.readMessage(value,google_protobuf_struct_pb.Struct.deserializeBinaryFromReader);\n msg.setInputs(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.ReadRequest.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.ReadRequest.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.ReadRequest} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.ReadRequest.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getId();\n if (f.length > 0) {\n writer.writeString(\n 1,\n f\n );\n }\n f = message.getUrn();\n if (f.length > 0) {\n writer.writeString(\n 2,\n f\n );\n }\n f = message.getProperties();\n if (f != null) {\n writer.writeMessage(\n 3,\n f,\n google_protobuf_struct_pb.Struct.serializeBinaryToWriter\n );\n }\n f = message.getInputs();\n if (f != null) {\n writer.writeMessage(\n 4,\n f,\n google_protobuf_struct_pb.Struct.serializeBinaryToWriter\n );\n }\n};\n\n\n/**\n * optional string id = 1;\n * @return {string}\n */\nproto.pulumirpc.ReadRequest.prototype.getId = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.ReadRequest} returns this\n */\nproto.pulumirpc.ReadRequest.prototype.setId = function(value) {\n return jspb.Message.setProto3StringField(this, 1, value);\n};\n\n\n/**\n * optional string urn = 2;\n * @return {string}\n */\nproto.pulumirpc.ReadRequest.prototype.getUrn = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.ReadRequest} returns this\n */\nproto.pulumirpc.ReadRequest.prototype.setUrn = function(value) {\n return jspb.Message.setProto3StringField(this, 2, value);\n};\n\n\n/**\n * optional google.protobuf.Struct properties = 3;\n * @return {?proto.google.protobuf.Struct}\n */\nproto.pulumirpc.ReadRequest.prototype.getProperties = function() {\n return /** @type{?proto.google.protobuf.Struct} */ (\n jspb.Message.getWrapperField(this, google_protobuf_struct_pb.Struct, 3));\n};\n\n\n/**\n * @param {?proto.google.protobuf.Struct|undefined} value\n * @return {!proto.pulumirpc.ReadRequest} returns this\n*/\nproto.pulumirpc.ReadRequest.prototype.setProperties = function(value) {\n return jspb.Message.setWrapperField(this, 3, value);\n};\n\n\n/**\n * Clears the message field making it undefined.\n * @return {!proto.pulumirpc.ReadRequest} returns this\n */\nproto.pulumirpc.ReadRequest.prototype.clearProperties = function() {\n return this.setProperties(undefined);\n};\n\n\n/**\n * Returns whether this field is set.\n * @return {boolean}\n */\nproto.pulumirpc.ReadRequest.prototype.hasProperties = function() {\n return jspb.Message.getField(this, 3) != null;\n};\n\n\n/**\n * optional google.protobuf.Struct inputs = 4;\n * @return {?proto.google.protobuf.Struct}\n */\nproto.pulumirpc.ReadRequest.prototype.getInputs = function() {\n return /** @type{?proto.google.protobuf.Struct} */ (\n jspb.Message.getWrapperField(this, google_protobuf_struct_pb.Struct, 4));\n};\n\n\n/**\n * @param {?proto.google.protobuf.Struct|undefined} value\n * @return {!proto.pulumirpc.ReadRequest} returns this\n*/\nproto.pulumirpc.ReadRequest.prototype.setInputs = function(value) {\n return jspb.Message.setWrapperField(this, 4, value);\n};\n\n\n/**\n * Clears the message field making it undefined.\n * @return {!proto.pulumirpc.ReadRequest} returns this\n */\nproto.pulumirpc.ReadRequest.prototype.clearInputs = function() {\n return this.setInputs(undefined);\n};\n\n\n/**\n * Returns whether this field is set.\n * @return {boolean}\n */\nproto.pulumirpc.ReadRequest.prototype.hasInputs = function() {\n return jspb.Message.getField(this, 4) != null;\n};\n\n\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.ReadResponse.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.ReadResponse.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.ReadResponse} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.ReadResponse.toObject = function(includeInstance, msg) {\n var f, obj = {\n id: jspb.Message.getFieldWithDefault(msg, 1, \"\"),\n properties: (f = msg.getProperties()) && google_protobuf_struct_pb.Struct.toObject(includeInstance, f),\n inputs: (f = msg.getInputs()) && google_protobuf_struct_pb.Struct.toObject(includeInstance, f)\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.ReadResponse}\n */\nproto.pulumirpc.ReadResponse.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.ReadResponse;\n return proto.pulumirpc.ReadResponse.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.ReadResponse} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.ReadResponse}\n */\nproto.pulumirpc.ReadResponse.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {string} */ (reader.readString());\n msg.setId(value);\n break;\n case 2:\n var value = new google_protobuf_struct_pb.Struct;\n reader.readMessage(value,google_protobuf_struct_pb.Struct.deserializeBinaryFromReader);\n msg.setProperties(value);\n break;\n case 3:\n var value = new google_protobuf_struct_pb.Struct;\n reader.readMessage(value,google_protobuf_struct_pb.Struct.deserializeBinaryFromReader);\n msg.setInputs(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.ReadResponse.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.ReadResponse.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.ReadResponse} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.ReadResponse.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getId();\n if (f.length > 0) {\n writer.writeString(\n 1,\n f\n );\n }\n f = message.getProperties();\n if (f != null) {\n writer.writeMessage(\n 2,\n f,\n google_protobuf_struct_pb.Struct.serializeBinaryToWriter\n );\n }\n f = message.getInputs();\n if (f != null) {\n writer.writeMessage(\n 3,\n f,\n google_protobuf_struct_pb.Struct.serializeBinaryToWriter\n );\n }\n};\n\n\n/**\n * optional string id = 1;\n * @return {string}\n */\nproto.pulumirpc.ReadResponse.prototype.getId = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.ReadResponse} returns this\n */\nproto.pulumirpc.ReadResponse.prototype.setId = function(value) {\n return jspb.Message.setProto3StringField(this, 1, value);\n};\n\n\n/**\n * optional google.protobuf.Struct properties = 2;\n * @return {?proto.google.protobuf.Struct}\n */\nproto.pulumirpc.ReadResponse.prototype.getProperties = function() {\n return /** @type{?proto.google.protobuf.Struct} */ (\n jspb.Message.getWrapperField(this, google_protobuf_struct_pb.Struct, 2));\n};\n\n\n/**\n * @param {?proto.google.protobuf.Struct|undefined} value\n * @return {!proto.pulumirpc.ReadResponse} returns this\n*/\nproto.pulumirpc.ReadResponse.prototype.setProperties = function(value) {\n return jspb.Message.setWrapperField(this, 2, value);\n};\n\n\n/**\n * Clears the message field making it undefined.\n * @return {!proto.pulumirpc.ReadResponse} returns this\n */\nproto.pulumirpc.ReadResponse.prototype.clearProperties = function() {\n return this.setProperties(undefined);\n};\n\n\n/**\n * Returns whether this field is set.\n * @return {boolean}\n */\nproto.pulumirpc.ReadResponse.prototype.hasProperties = function() {\n return jspb.Message.getField(this, 2) != null;\n};\n\n\n/**\n * optional google.protobuf.Struct inputs = 3;\n * @return {?proto.google.protobuf.Struct}\n */\nproto.pulumirpc.ReadResponse.prototype.getInputs = function() {\n return /** @type{?proto.google.protobuf.Struct} */ (\n jspb.Message.getWrapperField(this, google_protobuf_struct_pb.Struct, 3));\n};\n\n\n/**\n * @param {?proto.google.protobuf.Struct|undefined} value\n * @return {!proto.pulumirpc.ReadResponse} returns this\n*/\nproto.pulumirpc.ReadResponse.prototype.setInputs = function(value) {\n return jspb.Message.setWrapperField(this, 3, value);\n};\n\n\n/**\n * Clears the message field making it undefined.\n * @return {!proto.pulumirpc.ReadResponse} returns this\n */\nproto.pulumirpc.ReadResponse.prototype.clearInputs = function() {\n return this.setInputs(undefined);\n};\n\n\n/**\n * Returns whether this field is set.\n * @return {boolean}\n */\nproto.pulumirpc.ReadResponse.prototype.hasInputs = function() {\n return jspb.Message.getField(this, 3) != null;\n};\n\n\n\n/**\n * List of repeated fields within this message type.\n * @private {!Array}\n * @const\n */\nproto.pulumirpc.UpdateRequest.repeatedFields_ = [6];\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.UpdateRequest.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.UpdateRequest.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.UpdateRequest} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.UpdateRequest.toObject = function(includeInstance, msg) {\n var f, obj = {\n id: jspb.Message.getFieldWithDefault(msg, 1, \"\"),\n urn: jspb.Message.getFieldWithDefault(msg, 2, \"\"),\n olds: (f = msg.getOlds()) && google_protobuf_struct_pb.Struct.toObject(includeInstance, f),\n news: (f = msg.getNews()) && google_protobuf_struct_pb.Struct.toObject(includeInstance, f),\n timeout: jspb.Message.getFloatingPointFieldWithDefault(msg, 5, 0.0),\n ignorechangesList: (f = jspb.Message.getRepeatedField(msg, 6)) == null ? undefined : f,\n preview: jspb.Message.getBooleanFieldWithDefault(msg, 7, false)\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.UpdateRequest}\n */\nproto.pulumirpc.UpdateRequest.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.UpdateRequest;\n return proto.pulumirpc.UpdateRequest.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.UpdateRequest} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.UpdateRequest}\n */\nproto.pulumirpc.UpdateRequest.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {string} */ (reader.readString());\n msg.setId(value);\n break;\n case 2:\n var value = /** @type {string} */ (reader.readString());\n msg.setUrn(value);\n break;\n case 3:\n var value = new google_protobuf_struct_pb.Struct;\n reader.readMessage(value,google_protobuf_struct_pb.Struct.deserializeBinaryFromReader);\n msg.setOlds(value);\n break;\n case 4:\n var value = new google_protobuf_struct_pb.Struct;\n reader.readMessage(value,google_protobuf_struct_pb.Struct.deserializeBinaryFromReader);\n msg.setNews(value);\n break;\n case 5:\n var value = /** @type {number} */ (reader.readDouble());\n msg.setTimeout(value);\n break;\n case 6:\n var value = /** @type {string} */ (reader.readString());\n msg.addIgnorechanges(value);\n break;\n case 7:\n var value = /** @type {boolean} */ (reader.readBool());\n msg.setPreview(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.UpdateRequest.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.UpdateRequest.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.UpdateRequest} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.UpdateRequest.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getId();\n if (f.length > 0) {\n writer.writeString(\n 1,\n f\n );\n }\n f = message.getUrn();\n if (f.length > 0) {\n writer.writeString(\n 2,\n f\n );\n }\n f = message.getOlds();\n if (f != null) {\n writer.writeMessage(\n 3,\n f,\n google_protobuf_struct_pb.Struct.serializeBinaryToWriter\n );\n }\n f = message.getNews();\n if (f != null) {\n writer.writeMessage(\n 4,\n f,\n google_protobuf_struct_pb.Struct.serializeBinaryToWriter\n );\n }\n f = message.getTimeout();\n if (f !== 0.0) {\n writer.writeDouble(\n 5,\n f\n );\n }\n f = message.getIgnorechangesList();\n if (f.length > 0) {\n writer.writeRepeatedString(\n 6,\n f\n );\n }\n f = message.getPreview();\n if (f) {\n writer.writeBool(\n 7,\n f\n );\n }\n};\n\n\n/**\n * optional string id = 1;\n * @return {string}\n */\nproto.pulumirpc.UpdateRequest.prototype.getId = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.UpdateRequest} returns this\n */\nproto.pulumirpc.UpdateRequest.prototype.setId = function(value) {\n return jspb.Message.setProto3StringField(this, 1, value);\n};\n\n\n/**\n * optional string urn = 2;\n * @return {string}\n */\nproto.pulumirpc.UpdateRequest.prototype.getUrn = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.UpdateRequest} returns this\n */\nproto.pulumirpc.UpdateRequest.prototype.setUrn = function(value) {\n return jspb.Message.setProto3StringField(this, 2, value);\n};\n\n\n/**\n * optional google.protobuf.Struct olds = 3;\n * @return {?proto.google.protobuf.Struct}\n */\nproto.pulumirpc.UpdateRequest.prototype.getOlds = function() {\n return /** @type{?proto.google.protobuf.Struct} */ (\n jspb.Message.getWrapperField(this, google_protobuf_struct_pb.Struct, 3));\n};\n\n\n/**\n * @param {?proto.google.protobuf.Struct|undefined} value\n * @return {!proto.pulumirpc.UpdateRequest} returns this\n*/\nproto.pulumirpc.UpdateRequest.prototype.setOlds = function(value) {\n return jspb.Message.setWrapperField(this, 3, value);\n};\n\n\n/**\n * Clears the message field making it undefined.\n * @return {!proto.pulumirpc.UpdateRequest} returns this\n */\nproto.pulumirpc.UpdateRequest.prototype.clearOlds = function() {\n return this.setOlds(undefined);\n};\n\n\n/**\n * Returns whether this field is set.\n * @return {boolean}\n */\nproto.pulumirpc.UpdateRequest.prototype.hasOlds = function() {\n return jspb.Message.getField(this, 3) != null;\n};\n\n\n/**\n * optional google.protobuf.Struct news = 4;\n * @return {?proto.google.protobuf.Struct}\n */\nproto.pulumirpc.UpdateRequest.prototype.getNews = function() {\n return /** @type{?proto.google.protobuf.Struct} */ (\n jspb.Message.getWrapperField(this, google_protobuf_struct_pb.Struct, 4));\n};\n\n\n/**\n * @param {?proto.google.protobuf.Struct|undefined} value\n * @return {!proto.pulumirpc.UpdateRequest} returns this\n*/\nproto.pulumirpc.UpdateRequest.prototype.setNews = function(value) {\n return jspb.Message.setWrapperField(this, 4, value);\n};\n\n\n/**\n * Clears the message field making it undefined.\n * @return {!proto.pulumirpc.UpdateRequest} returns this\n */\nproto.pulumirpc.UpdateRequest.prototype.clearNews = function() {\n return this.setNews(undefined);\n};\n\n\n/**\n * Returns whether this field is set.\n * @return {boolean}\n */\nproto.pulumirpc.UpdateRequest.prototype.hasNews = function() {\n return jspb.Message.getField(this, 4) != null;\n};\n\n\n/**\n * optional double timeout = 5;\n * @return {number}\n */\nproto.pulumirpc.UpdateRequest.prototype.getTimeout = function() {\n return /** @type {number} */ (jspb.Message.getFloatingPointFieldWithDefault(this, 5, 0.0));\n};\n\n\n/**\n * @param {number} value\n * @return {!proto.pulumirpc.UpdateRequest} returns this\n */\nproto.pulumirpc.UpdateRequest.prototype.setTimeout = function(value) {\n return jspb.Message.setProto3FloatField(this, 5, value);\n};\n\n\n/**\n * repeated string ignoreChanges = 6;\n * @return {!Array}\n */\nproto.pulumirpc.UpdateRequest.prototype.getIgnorechangesList = function() {\n return /** @type {!Array} */ (jspb.Message.getRepeatedField(this, 6));\n};\n\n\n/**\n * @param {!Array} value\n * @return {!proto.pulumirpc.UpdateRequest} returns this\n */\nproto.pulumirpc.UpdateRequest.prototype.setIgnorechangesList = function(value) {\n return jspb.Message.setField(this, 6, value || []);\n};\n\n\n/**\n * @param {string} value\n * @param {number=} opt_index\n * @return {!proto.pulumirpc.UpdateRequest} returns this\n */\nproto.pulumirpc.UpdateRequest.prototype.addIgnorechanges = function(value, opt_index) {\n return jspb.Message.addToRepeatedField(this, 6, value, opt_index);\n};\n\n\n/**\n * Clears the list making it empty but non-null.\n * @return {!proto.pulumirpc.UpdateRequest} returns this\n */\nproto.pulumirpc.UpdateRequest.prototype.clearIgnorechangesList = function() {\n return this.setIgnorechangesList([]);\n};\n\n\n/**\n * optional bool preview = 7;\n * @return {boolean}\n */\nproto.pulumirpc.UpdateRequest.prototype.getPreview = function() {\n return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 7, false));\n};\n\n\n/**\n * @param {boolean} value\n * @return {!proto.pulumirpc.UpdateRequest} returns this\n */\nproto.pulumirpc.UpdateRequest.prototype.setPreview = function(value) {\n return jspb.Message.setProto3BooleanField(this, 7, value);\n};\n\n\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.UpdateResponse.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.UpdateResponse.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.UpdateResponse} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.UpdateResponse.toObject = function(includeInstance, msg) {\n var f, obj = {\n properties: (f = msg.getProperties()) && google_protobuf_struct_pb.Struct.toObject(includeInstance, f)\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.UpdateResponse}\n */\nproto.pulumirpc.UpdateResponse.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.UpdateResponse;\n return proto.pulumirpc.UpdateResponse.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.UpdateResponse} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.UpdateResponse}\n */\nproto.pulumirpc.UpdateResponse.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = new google_protobuf_struct_pb.Struct;\n reader.readMessage(value,google_protobuf_struct_pb.Struct.deserializeBinaryFromReader);\n msg.setProperties(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.UpdateResponse.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.UpdateResponse.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.UpdateResponse} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.UpdateResponse.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getProperties();\n if (f != null) {\n writer.writeMessage(\n 1,\n f,\n google_protobuf_struct_pb.Struct.serializeBinaryToWriter\n );\n }\n};\n\n\n/**\n * optional google.protobuf.Struct properties = 1;\n * @return {?proto.google.protobuf.Struct}\n */\nproto.pulumirpc.UpdateResponse.prototype.getProperties = function() {\n return /** @type{?proto.google.protobuf.Struct} */ (\n jspb.Message.getWrapperField(this, google_protobuf_struct_pb.Struct, 1));\n};\n\n\n/**\n * @param {?proto.google.protobuf.Struct|undefined} value\n * @return {!proto.pulumirpc.UpdateResponse} returns this\n*/\nproto.pulumirpc.UpdateResponse.prototype.setProperties = function(value) {\n return jspb.Message.setWrapperField(this, 1, value);\n};\n\n\n/**\n * Clears the message field making it undefined.\n * @return {!proto.pulumirpc.UpdateResponse} returns this\n */\nproto.pulumirpc.UpdateResponse.prototype.clearProperties = function() {\n return this.setProperties(undefined);\n};\n\n\n/**\n * Returns whether this field is set.\n * @return {boolean}\n */\nproto.pulumirpc.UpdateResponse.prototype.hasProperties = function() {\n return jspb.Message.getField(this, 1) != null;\n};\n\n\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.DeleteRequest.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.DeleteRequest.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.DeleteRequest} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.DeleteRequest.toObject = function(includeInstance, msg) {\n var f, obj = {\n id: jspb.Message.getFieldWithDefault(msg, 1, \"\"),\n urn: jspb.Message.getFieldWithDefault(msg, 2, \"\"),\n properties: (f = msg.getProperties()) && google_protobuf_struct_pb.Struct.toObject(includeInstance, f),\n timeout: jspb.Message.getFloatingPointFieldWithDefault(msg, 4, 0.0)\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.DeleteRequest}\n */\nproto.pulumirpc.DeleteRequest.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.DeleteRequest;\n return proto.pulumirpc.DeleteRequest.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.DeleteRequest} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.DeleteRequest}\n */\nproto.pulumirpc.DeleteRequest.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {string} */ (reader.readString());\n msg.setId(value);\n break;\n case 2:\n var value = /** @type {string} */ (reader.readString());\n msg.setUrn(value);\n break;\n case 3:\n var value = new google_protobuf_struct_pb.Struct;\n reader.readMessage(value,google_protobuf_struct_pb.Struct.deserializeBinaryFromReader);\n msg.setProperties(value);\n break;\n case 4:\n var value = /** @type {number} */ (reader.readDouble());\n msg.setTimeout(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.DeleteRequest.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.DeleteRequest.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.DeleteRequest} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.DeleteRequest.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getId();\n if (f.length > 0) {\n writer.writeString(\n 1,\n f\n );\n }\n f = message.getUrn();\n if (f.length > 0) {\n writer.writeString(\n 2,\n f\n );\n }\n f = message.getProperties();\n if (f != null) {\n writer.writeMessage(\n 3,\n f,\n google_protobuf_struct_pb.Struct.serializeBinaryToWriter\n );\n }\n f = message.getTimeout();\n if (f !== 0.0) {\n writer.writeDouble(\n 4,\n f\n );\n }\n};\n\n\n/**\n * optional string id = 1;\n * @return {string}\n */\nproto.pulumirpc.DeleteRequest.prototype.getId = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.DeleteRequest} returns this\n */\nproto.pulumirpc.DeleteRequest.prototype.setId = function(value) {\n return jspb.Message.setProto3StringField(this, 1, value);\n};\n\n\n/**\n * optional string urn = 2;\n * @return {string}\n */\nproto.pulumirpc.DeleteRequest.prototype.getUrn = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.DeleteRequest} returns this\n */\nproto.pulumirpc.DeleteRequest.prototype.setUrn = function(value) {\n return jspb.Message.setProto3StringField(this, 2, value);\n};\n\n\n/**\n * optional google.protobuf.Struct properties = 3;\n * @return {?proto.google.protobuf.Struct}\n */\nproto.pulumirpc.DeleteRequest.prototype.getProperties = function() {\n return /** @type{?proto.google.protobuf.Struct} */ (\n jspb.Message.getWrapperField(this, google_protobuf_struct_pb.Struct, 3));\n};\n\n\n/**\n * @param {?proto.google.protobuf.Struct|undefined} value\n * @return {!proto.pulumirpc.DeleteRequest} returns this\n*/\nproto.pulumirpc.DeleteRequest.prototype.setProperties = function(value) {\n return jspb.Message.setWrapperField(this, 3, value);\n};\n\n\n/**\n * Clears the message field making it undefined.\n * @return {!proto.pulumirpc.DeleteRequest} returns this\n */\nproto.pulumirpc.DeleteRequest.prototype.clearProperties = function() {\n return this.setProperties(undefined);\n};\n\n\n/**\n * Returns whether this field is set.\n * @return {boolean}\n */\nproto.pulumirpc.DeleteRequest.prototype.hasProperties = function() {\n return jspb.Message.getField(this, 3) != null;\n};\n\n\n/**\n * optional double timeout = 4;\n * @return {number}\n */\nproto.pulumirpc.DeleteRequest.prototype.getTimeout = function() {\n return /** @type {number} */ (jspb.Message.getFloatingPointFieldWithDefault(this, 4, 0.0));\n};\n\n\n/**\n * @param {number} value\n * @return {!proto.pulumirpc.DeleteRequest} returns this\n */\nproto.pulumirpc.DeleteRequest.prototype.setTimeout = function(value) {\n return jspb.Message.setProto3FloatField(this, 4, value);\n};\n\n\n\n/**\n * List of repeated fields within this message type.\n * @private {!Array}\n * @const\n */\nproto.pulumirpc.ConstructRequest.repeatedFields_ = [14,15];\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.ConstructRequest.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.ConstructRequest.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.ConstructRequest} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.ConstructRequest.toObject = function(includeInstance, msg) {\n var f, obj = {\n project: jspb.Message.getFieldWithDefault(msg, 1, \"\"),\n stack: jspb.Message.getFieldWithDefault(msg, 2, \"\"),\n configMap: (f = msg.getConfigMap()) ? f.toObject(includeInstance, undefined) : [],\n dryrun: jspb.Message.getBooleanFieldWithDefault(msg, 4, false),\n parallel: jspb.Message.getFieldWithDefault(msg, 5, 0),\n monitorendpoint: jspb.Message.getFieldWithDefault(msg, 6, \"\"),\n type: jspb.Message.getFieldWithDefault(msg, 7, \"\"),\n name: jspb.Message.getFieldWithDefault(msg, 8, \"\"),\n parent: jspb.Message.getFieldWithDefault(msg, 9, \"\"),\n inputs: (f = msg.getInputs()) && google_protobuf_struct_pb.Struct.toObject(includeInstance, f),\n inputdependenciesMap: (f = msg.getInputdependenciesMap()) ? f.toObject(includeInstance, proto.pulumirpc.ConstructRequest.PropertyDependencies.toObject) : [],\n protect: jspb.Message.getBooleanFieldWithDefault(msg, 12, false),\n providersMap: (f = msg.getProvidersMap()) ? f.toObject(includeInstance, undefined) : [],\n aliasesList: (f = jspb.Message.getRepeatedField(msg, 14)) == null ? undefined : f,\n dependenciesList: (f = jspb.Message.getRepeatedField(msg, 15)) == null ? undefined : f\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.ConstructRequest}\n */\nproto.pulumirpc.ConstructRequest.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.ConstructRequest;\n return proto.pulumirpc.ConstructRequest.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.ConstructRequest} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.ConstructRequest}\n */\nproto.pulumirpc.ConstructRequest.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {string} */ (reader.readString());\n msg.setProject(value);\n break;\n case 2:\n var value = /** @type {string} */ (reader.readString());\n msg.setStack(value);\n break;\n case 3:\n var value = msg.getConfigMap();\n reader.readMessage(value, function(message, reader) {\n jspb.Map.deserializeBinary(message, reader, jspb.BinaryReader.prototype.readString, jspb.BinaryReader.prototype.readString, null, \"\", \"\");\n });\n break;\n case 4:\n var value = /** @type {boolean} */ (reader.readBool());\n msg.setDryrun(value);\n break;\n case 5:\n var value = /** @type {number} */ (reader.readInt32());\n msg.setParallel(value);\n break;\n case 6:\n var value = /** @type {string} */ (reader.readString());\n msg.setMonitorendpoint(value);\n break;\n case 7:\n var value = /** @type {string} */ (reader.readString());\n msg.setType(value);\n break;\n case 8:\n var value = /** @type {string} */ (reader.readString());\n msg.setName(value);\n break;\n case 9:\n var value = /** @type {string} */ (reader.readString());\n msg.setParent(value);\n break;\n case 10:\n var value = new google_protobuf_struct_pb.Struct;\n reader.readMessage(value,google_protobuf_struct_pb.Struct.deserializeBinaryFromReader);\n msg.setInputs(value);\n break;\n case 11:\n var value = msg.getInputdependenciesMap();\n reader.readMessage(value, function(message, reader) {\n jspb.Map.deserializeBinary(message, reader, jspb.BinaryReader.prototype.readString, jspb.BinaryReader.prototype.readMessage, proto.pulumirpc.ConstructRequest.PropertyDependencies.deserializeBinaryFromReader, \"\", new proto.pulumirpc.ConstructRequest.PropertyDependencies());\n });\n break;\n case 12:\n var value = /** @type {boolean} */ (reader.readBool());\n msg.setProtect(value);\n break;\n case 13:\n var value = msg.getProvidersMap();\n reader.readMessage(value, function(message, reader) {\n jspb.Map.deserializeBinary(message, reader, jspb.BinaryReader.prototype.readString, jspb.BinaryReader.prototype.readString, null, \"\", \"\");\n });\n break;\n case 14:\n var value = /** @type {string} */ (reader.readString());\n msg.addAliases(value);\n break;\n case 15:\n var value = /** @type {string} */ (reader.readString());\n msg.addDependencies(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.ConstructRequest.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.ConstructRequest.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.ConstructRequest} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.ConstructRequest.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getProject();\n if (f.length > 0) {\n writer.writeString(\n 1,\n f\n );\n }\n f = message.getStack();\n if (f.length > 0) {\n writer.writeString(\n 2,\n f\n );\n }\n f = message.getConfigMap(true);\n if (f && f.getLength() > 0) {\n f.serializeBinary(3, writer, jspb.BinaryWriter.prototype.writeString, jspb.BinaryWriter.prototype.writeString);\n }\n f = message.getDryrun();\n if (f) {\n writer.writeBool(\n 4,\n f\n );\n }\n f = message.getParallel();\n if (f !== 0) {\n writer.writeInt32(\n 5,\n f\n );\n }\n f = message.getMonitorendpoint();\n if (f.length > 0) {\n writer.writeString(\n 6,\n f\n );\n }\n f = message.getType();\n if (f.length > 0) {\n writer.writeString(\n 7,\n f\n );\n }\n f = message.getName();\n if (f.length > 0) {\n writer.writeString(\n 8,\n f\n );\n }\n f = message.getParent();\n if (f.length > 0) {\n writer.writeString(\n 9,\n f\n );\n }\n f = message.getInputs();\n if (f != null) {\n writer.writeMessage(\n 10,\n f,\n google_protobuf_struct_pb.Struct.serializeBinaryToWriter\n );\n }\n f = message.getInputdependenciesMap(true);\n if (f && f.getLength() > 0) {\n f.serializeBinary(11, writer, jspb.BinaryWriter.prototype.writeString, jspb.BinaryWriter.prototype.writeMessage, proto.pulumirpc.ConstructRequest.PropertyDependencies.serializeBinaryToWriter);\n }\n f = message.getProtect();\n if (f) {\n writer.writeBool(\n 12,\n f\n );\n }\n f = message.getProvidersMap(true);\n if (f && f.getLength() > 0) {\n f.serializeBinary(13, writer, jspb.BinaryWriter.prototype.writeString, jspb.BinaryWriter.prototype.writeString);\n }\n f = message.getAliasesList();\n if (f.length > 0) {\n writer.writeRepeatedString(\n 14,\n f\n );\n }\n f = message.getDependenciesList();\n if (f.length > 0) {\n writer.writeRepeatedString(\n 15,\n f\n );\n }\n};\n\n\n\n/**\n * List of repeated fields within this message type.\n * @private {!Array}\n * @const\n */\nproto.pulumirpc.ConstructRequest.PropertyDependencies.repeatedFields_ = [1];\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.ConstructRequest.PropertyDependencies.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.ConstructRequest.PropertyDependencies.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.ConstructRequest.PropertyDependencies} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.ConstructRequest.PropertyDependencies.toObject = function(includeInstance, msg) {\n var f, obj = {\n urnsList: (f = jspb.Message.getRepeatedField(msg, 1)) == null ? undefined : f\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.ConstructRequest.PropertyDependencies}\n */\nproto.pulumirpc.ConstructRequest.PropertyDependencies.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.ConstructRequest.PropertyDependencies;\n return proto.pulumirpc.ConstructRequest.PropertyDependencies.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.ConstructRequest.PropertyDependencies} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.ConstructRequest.PropertyDependencies}\n */\nproto.pulumirpc.ConstructRequest.PropertyDependencies.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {string} */ (reader.readString());\n msg.addUrns(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.ConstructRequest.PropertyDependencies.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.ConstructRequest.PropertyDependencies.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.ConstructRequest.PropertyDependencies} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.ConstructRequest.PropertyDependencies.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getUrnsList();\n if (f.length > 0) {\n writer.writeRepeatedString(\n 1,\n f\n );\n }\n};\n\n\n/**\n * repeated string urns = 1;\n * @return {!Array}\n */\nproto.pulumirpc.ConstructRequest.PropertyDependencies.prototype.getUrnsList = function() {\n return /** @type {!Array} */ (jspb.Message.getRepeatedField(this, 1));\n};\n\n\n/**\n * @param {!Array} value\n * @return {!proto.pulumirpc.ConstructRequest.PropertyDependencies} returns this\n */\nproto.pulumirpc.ConstructRequest.PropertyDependencies.prototype.setUrnsList = function(value) {\n return jspb.Message.setField(this, 1, value || []);\n};\n\n\n/**\n * @param {string} value\n * @param {number=} opt_index\n * @return {!proto.pulumirpc.ConstructRequest.PropertyDependencies} returns this\n */\nproto.pulumirpc.ConstructRequest.PropertyDependencies.prototype.addUrns = function(value, opt_index) {\n return jspb.Message.addToRepeatedField(this, 1, value, opt_index);\n};\n\n\n/**\n * Clears the list making it empty but non-null.\n * @return {!proto.pulumirpc.ConstructRequest.PropertyDependencies} returns this\n */\nproto.pulumirpc.ConstructRequest.PropertyDependencies.prototype.clearUrnsList = function() {\n return this.setUrnsList([]);\n};\n\n\n/**\n * optional string project = 1;\n * @return {string}\n */\nproto.pulumirpc.ConstructRequest.prototype.getProject = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.ConstructRequest} returns this\n */\nproto.pulumirpc.ConstructRequest.prototype.setProject = function(value) {\n return jspb.Message.setProto3StringField(this, 1, value);\n};\n\n\n/**\n * optional string stack = 2;\n * @return {string}\n */\nproto.pulumirpc.ConstructRequest.prototype.getStack = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.ConstructRequest} returns this\n */\nproto.pulumirpc.ConstructRequest.prototype.setStack = function(value) {\n return jspb.Message.setProto3StringField(this, 2, value);\n};\n\n\n/**\n * map config = 3;\n * @param {boolean=} opt_noLazyCreate Do not create the map if\n * empty, instead returning `undefined`\n * @return {!jspb.Map}\n */\nproto.pulumirpc.ConstructRequest.prototype.getConfigMap = function(opt_noLazyCreate) {\n return /** @type {!jspb.Map} */ (\n jspb.Message.getMapField(this, 3, opt_noLazyCreate,\n null));\n};\n\n\n/**\n * Clears values from the map. The map will be non-null.\n * @return {!proto.pulumirpc.ConstructRequest} returns this\n */\nproto.pulumirpc.ConstructRequest.prototype.clearConfigMap = function() {\n this.getConfigMap().clear();\n return this;};\n\n\n/**\n * optional bool dryRun = 4;\n * @return {boolean}\n */\nproto.pulumirpc.ConstructRequest.prototype.getDryrun = function() {\n return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 4, false));\n};\n\n\n/**\n * @param {boolean} value\n * @return {!proto.pulumirpc.ConstructRequest} returns this\n */\nproto.pulumirpc.ConstructRequest.prototype.setDryrun = function(value) {\n return jspb.Message.setProto3BooleanField(this, 4, value);\n};\n\n\n/**\n * optional int32 parallel = 5;\n * @return {number}\n */\nproto.pulumirpc.ConstructRequest.prototype.getParallel = function() {\n return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 5, 0));\n};\n\n\n/**\n * @param {number} value\n * @return {!proto.pulumirpc.ConstructRequest} returns this\n */\nproto.pulumirpc.ConstructRequest.prototype.setParallel = function(value) {\n return jspb.Message.setProto3IntField(this, 5, value);\n};\n\n\n/**\n * optional string monitorEndpoint = 6;\n * @return {string}\n */\nproto.pulumirpc.ConstructRequest.prototype.getMonitorendpoint = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 6, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.ConstructRequest} returns this\n */\nproto.pulumirpc.ConstructRequest.prototype.setMonitorendpoint = function(value) {\n return jspb.Message.setProto3StringField(this, 6, value);\n};\n\n\n/**\n * optional string type = 7;\n * @return {string}\n */\nproto.pulumirpc.ConstructRequest.prototype.getType = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 7, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.ConstructRequest} returns this\n */\nproto.pulumirpc.ConstructRequest.prototype.setType = function(value) {\n return jspb.Message.setProto3StringField(this, 7, value);\n};\n\n\n/**\n * optional string name = 8;\n * @return {string}\n */\nproto.pulumirpc.ConstructRequest.prototype.getName = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 8, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.ConstructRequest} returns this\n */\nproto.pulumirpc.ConstructRequest.prototype.setName = function(value) {\n return jspb.Message.setProto3StringField(this, 8, value);\n};\n\n\n/**\n * optional string parent = 9;\n * @return {string}\n */\nproto.pulumirpc.ConstructRequest.prototype.getParent = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 9, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.ConstructRequest} returns this\n */\nproto.pulumirpc.ConstructRequest.prototype.setParent = function(value) {\n return jspb.Message.setProto3StringField(this, 9, value);\n};\n\n\n/**\n * optional google.protobuf.Struct inputs = 10;\n * @return {?proto.google.protobuf.Struct}\n */\nproto.pulumirpc.ConstructRequest.prototype.getInputs = function() {\n return /** @type{?proto.google.protobuf.Struct} */ (\n jspb.Message.getWrapperField(this, google_protobuf_struct_pb.Struct, 10));\n};\n\n\n/**\n * @param {?proto.google.protobuf.Struct|undefined} value\n * @return {!proto.pulumirpc.ConstructRequest} returns this\n*/\nproto.pulumirpc.ConstructRequest.prototype.setInputs = function(value) {\n return jspb.Message.setWrapperField(this, 10, value);\n};\n\n\n/**\n * Clears the message field making it undefined.\n * @return {!proto.pulumirpc.ConstructRequest} returns this\n */\nproto.pulumirpc.ConstructRequest.prototype.clearInputs = function() {\n return this.setInputs(undefined);\n};\n\n\n/**\n * Returns whether this field is set.\n * @return {boolean}\n */\nproto.pulumirpc.ConstructRequest.prototype.hasInputs = function() {\n return jspb.Message.getField(this, 10) != null;\n};\n\n\n/**\n * map inputDependencies = 11;\n * @param {boolean=} opt_noLazyCreate Do not create the map if\n * empty, instead returning `undefined`\n * @return {!jspb.Map}\n */\nproto.pulumirpc.ConstructRequest.prototype.getInputdependenciesMap = function(opt_noLazyCreate) {\n return /** @type {!jspb.Map} */ (\n jspb.Message.getMapField(this, 11, opt_noLazyCreate,\n proto.pulumirpc.ConstructRequest.PropertyDependencies));\n};\n\n\n/**\n * Clears values from the map. The map will be non-null.\n * @return {!proto.pulumirpc.ConstructRequest} returns this\n */\nproto.pulumirpc.ConstructRequest.prototype.clearInputdependenciesMap = function() {\n this.getInputdependenciesMap().clear();\n return this;};\n\n\n/**\n * optional bool protect = 12;\n * @return {boolean}\n */\nproto.pulumirpc.ConstructRequest.prototype.getProtect = function() {\n return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 12, false));\n};\n\n\n/**\n * @param {boolean} value\n * @return {!proto.pulumirpc.ConstructRequest} returns this\n */\nproto.pulumirpc.ConstructRequest.prototype.setProtect = function(value) {\n return jspb.Message.setProto3BooleanField(this, 12, value);\n};\n\n\n/**\n * map providers = 13;\n * @param {boolean=} opt_noLazyCreate Do not create the map if\n * empty, instead returning `undefined`\n * @return {!jspb.Map}\n */\nproto.pulumirpc.ConstructRequest.prototype.getProvidersMap = function(opt_noLazyCreate) {\n return /** @type {!jspb.Map} */ (\n jspb.Message.getMapField(this, 13, opt_noLazyCreate,\n null));\n};\n\n\n/**\n * Clears values from the map. The map will be non-null.\n * @return {!proto.pulumirpc.ConstructRequest} returns this\n */\nproto.pulumirpc.ConstructRequest.prototype.clearProvidersMap = function() {\n this.getProvidersMap().clear();\n return this;};\n\n\n/**\n * repeated string aliases = 14;\n * @return {!Array}\n */\nproto.pulumirpc.ConstructRequest.prototype.getAliasesList = function() {\n return /** @type {!Array} */ (jspb.Message.getRepeatedField(this, 14));\n};\n\n\n/**\n * @param {!Array} value\n * @return {!proto.pulumirpc.ConstructRequest} returns this\n */\nproto.pulumirpc.ConstructRequest.prototype.setAliasesList = function(value) {\n return jspb.Message.setField(this, 14, value || []);\n};\n\n\n/**\n * @param {string} value\n * @param {number=} opt_index\n * @return {!proto.pulumirpc.ConstructRequest} returns this\n */\nproto.pulumirpc.ConstructRequest.prototype.addAliases = function(value, opt_index) {\n return jspb.Message.addToRepeatedField(this, 14, value, opt_index);\n};\n\n\n/**\n * Clears the list making it empty but non-null.\n * @return {!proto.pulumirpc.ConstructRequest} returns this\n */\nproto.pulumirpc.ConstructRequest.prototype.clearAliasesList = function() {\n return this.setAliasesList([]);\n};\n\n\n/**\n * repeated string dependencies = 15;\n * @return {!Array}\n */\nproto.pulumirpc.ConstructRequest.prototype.getDependenciesList = function() {\n return /** @type {!Array} */ (jspb.Message.getRepeatedField(this, 15));\n};\n\n\n/**\n * @param {!Array} value\n * @return {!proto.pulumirpc.ConstructRequest} returns this\n */\nproto.pulumirpc.ConstructRequest.prototype.setDependenciesList = function(value) {\n return jspb.Message.setField(this, 15, value || []);\n};\n\n\n/**\n * @param {string} value\n * @param {number=} opt_index\n * @return {!proto.pulumirpc.ConstructRequest} returns this\n */\nproto.pulumirpc.ConstructRequest.prototype.addDependencies = function(value, opt_index) {\n return jspb.Message.addToRepeatedField(this, 15, value, opt_index);\n};\n\n\n/**\n * Clears the list making it empty but non-null.\n * @return {!proto.pulumirpc.ConstructRequest} returns this\n */\nproto.pulumirpc.ConstructRequest.prototype.clearDependenciesList = function() {\n return this.setDependenciesList([]);\n};\n\n\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.ConstructResponse.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.ConstructResponse.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.ConstructResponse} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.ConstructResponse.toObject = function(includeInstance, msg) {\n var f, obj = {\n urn: jspb.Message.getFieldWithDefault(msg, 1, \"\"),\n state: (f = msg.getState()) && google_protobuf_struct_pb.Struct.toObject(includeInstance, f),\n statedependenciesMap: (f = msg.getStatedependenciesMap()) ? f.toObject(includeInstance, proto.pulumirpc.ConstructResponse.PropertyDependencies.toObject) : []\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.ConstructResponse}\n */\nproto.pulumirpc.ConstructResponse.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.ConstructResponse;\n return proto.pulumirpc.ConstructResponse.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.ConstructResponse} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.ConstructResponse}\n */\nproto.pulumirpc.ConstructResponse.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {string} */ (reader.readString());\n msg.setUrn(value);\n break;\n case 2:\n var value = new google_protobuf_struct_pb.Struct;\n reader.readMessage(value,google_protobuf_struct_pb.Struct.deserializeBinaryFromReader);\n msg.setState(value);\n break;\n case 3:\n var value = msg.getStatedependenciesMap();\n reader.readMessage(value, function(message, reader) {\n jspb.Map.deserializeBinary(message, reader, jspb.BinaryReader.prototype.readString, jspb.BinaryReader.prototype.readMessage, proto.pulumirpc.ConstructResponse.PropertyDependencies.deserializeBinaryFromReader, \"\", new proto.pulumirpc.ConstructResponse.PropertyDependencies());\n });\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.ConstructResponse.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.ConstructResponse.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.ConstructResponse} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.ConstructResponse.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getUrn();\n if (f.length > 0) {\n writer.writeString(\n 1,\n f\n );\n }\n f = message.getState();\n if (f != null) {\n writer.writeMessage(\n 2,\n f,\n google_protobuf_struct_pb.Struct.serializeBinaryToWriter\n );\n }\n f = message.getStatedependenciesMap(true);\n if (f && f.getLength() > 0) {\n f.serializeBinary(3, writer, jspb.BinaryWriter.prototype.writeString, jspb.BinaryWriter.prototype.writeMessage, proto.pulumirpc.ConstructResponse.PropertyDependencies.serializeBinaryToWriter);\n }\n};\n\n\n\n/**\n * List of repeated fields within this message type.\n * @private {!Array}\n * @const\n */\nproto.pulumirpc.ConstructResponse.PropertyDependencies.repeatedFields_ = [1];\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.ConstructResponse.PropertyDependencies.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.ConstructResponse.PropertyDependencies.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.ConstructResponse.PropertyDependencies} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.ConstructResponse.PropertyDependencies.toObject = function(includeInstance, msg) {\n var f, obj = {\n urnsList: (f = jspb.Message.getRepeatedField(msg, 1)) == null ? undefined : f\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.ConstructResponse.PropertyDependencies}\n */\nproto.pulumirpc.ConstructResponse.PropertyDependencies.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.ConstructResponse.PropertyDependencies;\n return proto.pulumirpc.ConstructResponse.PropertyDependencies.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.ConstructResponse.PropertyDependencies} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.ConstructResponse.PropertyDependencies}\n */\nproto.pulumirpc.ConstructResponse.PropertyDependencies.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {string} */ (reader.readString());\n msg.addUrns(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.ConstructResponse.PropertyDependencies.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.ConstructResponse.PropertyDependencies.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.ConstructResponse.PropertyDependencies} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.ConstructResponse.PropertyDependencies.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getUrnsList();\n if (f.length > 0) {\n writer.writeRepeatedString(\n 1,\n f\n );\n }\n};\n\n\n/**\n * repeated string urns = 1;\n * @return {!Array}\n */\nproto.pulumirpc.ConstructResponse.PropertyDependencies.prototype.getUrnsList = function() {\n return /** @type {!Array} */ (jspb.Message.getRepeatedField(this, 1));\n};\n\n\n/**\n * @param {!Array} value\n * @return {!proto.pulumirpc.ConstructResponse.PropertyDependencies} returns this\n */\nproto.pulumirpc.ConstructResponse.PropertyDependencies.prototype.setUrnsList = function(value) {\n return jspb.Message.setField(this, 1, value || []);\n};\n\n\n/**\n * @param {string} value\n * @param {number=} opt_index\n * @return {!proto.pulumirpc.ConstructResponse.PropertyDependencies} returns this\n */\nproto.pulumirpc.ConstructResponse.PropertyDependencies.prototype.addUrns = function(value, opt_index) {\n return jspb.Message.addToRepeatedField(this, 1, value, opt_index);\n};\n\n\n/**\n * Clears the list making it empty but non-null.\n * @return {!proto.pulumirpc.ConstructResponse.PropertyDependencies} returns this\n */\nproto.pulumirpc.ConstructResponse.PropertyDependencies.prototype.clearUrnsList = function() {\n return this.setUrnsList([]);\n};\n\n\n/**\n * optional string urn = 1;\n * @return {string}\n */\nproto.pulumirpc.ConstructResponse.prototype.getUrn = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.ConstructResponse} returns this\n */\nproto.pulumirpc.ConstructResponse.prototype.setUrn = function(value) {\n return jspb.Message.setProto3StringField(this, 1, value);\n};\n\n\n/**\n * optional google.protobuf.Struct state = 2;\n * @return {?proto.google.protobuf.Struct}\n */\nproto.pulumirpc.ConstructResponse.prototype.getState = function() {\n return /** @type{?proto.google.protobuf.Struct} */ (\n jspb.Message.getWrapperField(this, google_protobuf_struct_pb.Struct, 2));\n};\n\n\n/**\n * @param {?proto.google.protobuf.Struct|undefined} value\n * @return {!proto.pulumirpc.ConstructResponse} returns this\n*/\nproto.pulumirpc.ConstructResponse.prototype.setState = function(value) {\n return jspb.Message.setWrapperField(this, 2, value);\n};\n\n\n/**\n * Clears the message field making it undefined.\n * @return {!proto.pulumirpc.ConstructResponse} returns this\n */\nproto.pulumirpc.ConstructResponse.prototype.clearState = function() {\n return this.setState(undefined);\n};\n\n\n/**\n * Returns whether this field is set.\n * @return {boolean}\n */\nproto.pulumirpc.ConstructResponse.prototype.hasState = function() {\n return jspb.Message.getField(this, 2) != null;\n};\n\n\n/**\n * map stateDependencies = 3;\n * @param {boolean=} opt_noLazyCreate Do not create the map if\n * empty, instead returning `undefined`\n * @return {!jspb.Map}\n */\nproto.pulumirpc.ConstructResponse.prototype.getStatedependenciesMap = function(opt_noLazyCreate) {\n return /** @type {!jspb.Map} */ (\n jspb.Message.getMapField(this, 3, opt_noLazyCreate,\n proto.pulumirpc.ConstructResponse.PropertyDependencies));\n};\n\n\n/**\n * Clears values from the map. The map will be non-null.\n * @return {!proto.pulumirpc.ConstructResponse} returns this\n */\nproto.pulumirpc.ConstructResponse.prototype.clearStatedependenciesMap = function() {\n this.getStatedependenciesMap().clear();\n return this;};\n\n\n\n/**\n * List of repeated fields within this message type.\n * @private {!Array}\n * @const\n */\nproto.pulumirpc.ErrorResourceInitFailed.repeatedFields_ = [3];\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.ErrorResourceInitFailed.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.ErrorResourceInitFailed.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.ErrorResourceInitFailed} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.ErrorResourceInitFailed.toObject = function(includeInstance, msg) {\n var f, obj = {\n id: jspb.Message.getFieldWithDefault(msg, 1, \"\"),\n properties: (f = msg.getProperties()) && google_protobuf_struct_pb.Struct.toObject(includeInstance, f),\n reasonsList: (f = jspb.Message.getRepeatedField(msg, 3)) == null ? undefined : f,\n inputs: (f = msg.getInputs()) && google_protobuf_struct_pb.Struct.toObject(includeInstance, f)\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.ErrorResourceInitFailed}\n */\nproto.pulumirpc.ErrorResourceInitFailed.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.ErrorResourceInitFailed;\n return proto.pulumirpc.ErrorResourceInitFailed.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.ErrorResourceInitFailed} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.ErrorResourceInitFailed}\n */\nproto.pulumirpc.ErrorResourceInitFailed.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {string} */ (reader.readString());\n msg.setId(value);\n break;\n case 2:\n var value = new google_protobuf_struct_pb.Struct;\n reader.readMessage(value,google_protobuf_struct_pb.Struct.deserializeBinaryFromReader);\n msg.setProperties(value);\n break;\n case 3:\n var value = /** @type {string} */ (reader.readString());\n msg.addReasons(value);\n break;\n case 4:\n var value = new google_protobuf_struct_pb.Struct;\n reader.readMessage(value,google_protobuf_struct_pb.Struct.deserializeBinaryFromReader);\n msg.setInputs(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.ErrorResourceInitFailed.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.ErrorResourceInitFailed.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.ErrorResourceInitFailed} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.ErrorResourceInitFailed.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getId();\n if (f.length > 0) {\n writer.writeString(\n 1,\n f\n );\n }\n f = message.getProperties();\n if (f != null) {\n writer.writeMessage(\n 2,\n f,\n google_protobuf_struct_pb.Struct.serializeBinaryToWriter\n );\n }\n f = message.getReasonsList();\n if (f.length > 0) {\n writer.writeRepeatedString(\n 3,\n f\n );\n }\n f = message.getInputs();\n if (f != null) {\n writer.writeMessage(\n 4,\n f,\n google_protobuf_struct_pb.Struct.serializeBinaryToWriter\n );\n }\n};\n\n\n/**\n * optional string id = 1;\n * @return {string}\n */\nproto.pulumirpc.ErrorResourceInitFailed.prototype.getId = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.ErrorResourceInitFailed} returns this\n */\nproto.pulumirpc.ErrorResourceInitFailed.prototype.setId = function(value) {\n return jspb.Message.setProto3StringField(this, 1, value);\n};\n\n\n/**\n * optional google.protobuf.Struct properties = 2;\n * @return {?proto.google.protobuf.Struct}\n */\nproto.pulumirpc.ErrorResourceInitFailed.prototype.getProperties = function() {\n return /** @type{?proto.google.protobuf.Struct} */ (\n jspb.Message.getWrapperField(this, google_protobuf_struct_pb.Struct, 2));\n};\n\n\n/**\n * @param {?proto.google.protobuf.Struct|undefined} value\n * @return {!proto.pulumirpc.ErrorResourceInitFailed} returns this\n*/\nproto.pulumirpc.ErrorResourceInitFailed.prototype.setProperties = function(value) {\n return jspb.Message.setWrapperField(this, 2, value);\n};\n\n\n/**\n * Clears the message field making it undefined.\n * @return {!proto.pulumirpc.ErrorResourceInitFailed} returns this\n */\nproto.pulumirpc.ErrorResourceInitFailed.prototype.clearProperties = function() {\n return this.setProperties(undefined);\n};\n\n\n/**\n * Returns whether this field is set.\n * @return {boolean}\n */\nproto.pulumirpc.ErrorResourceInitFailed.prototype.hasProperties = function() {\n return jspb.Message.getField(this, 2) != null;\n};\n\n\n/**\n * repeated string reasons = 3;\n * @return {!Array}\n */\nproto.pulumirpc.ErrorResourceInitFailed.prototype.getReasonsList = function() {\n return /** @type {!Array} */ (jspb.Message.getRepeatedField(this, 3));\n};\n\n\n/**\n * @param {!Array} value\n * @return {!proto.pulumirpc.ErrorResourceInitFailed} returns this\n */\nproto.pulumirpc.ErrorResourceInitFailed.prototype.setReasonsList = function(value) {\n return jspb.Message.setField(this, 3, value || []);\n};\n\n\n/**\n * @param {string} value\n * @param {number=} opt_index\n * @return {!proto.pulumirpc.ErrorResourceInitFailed} returns this\n */\nproto.pulumirpc.ErrorResourceInitFailed.prototype.addReasons = function(value, opt_index) {\n return jspb.Message.addToRepeatedField(this, 3, value, opt_index);\n};\n\n\n/**\n * Clears the list making it empty but non-null.\n * @return {!proto.pulumirpc.ErrorResourceInitFailed} returns this\n */\nproto.pulumirpc.ErrorResourceInitFailed.prototype.clearReasonsList = function() {\n return this.setReasonsList([]);\n};\n\n\n/**\n * optional google.protobuf.Struct inputs = 4;\n * @return {?proto.google.protobuf.Struct}\n */\nproto.pulumirpc.ErrorResourceInitFailed.prototype.getInputs = function() {\n return /** @type{?proto.google.protobuf.Struct} */ (\n jspb.Message.getWrapperField(this, google_protobuf_struct_pb.Struct, 4));\n};\n\n\n/**\n * @param {?proto.google.protobuf.Struct|undefined} value\n * @return {!proto.pulumirpc.ErrorResourceInitFailed} returns this\n*/\nproto.pulumirpc.ErrorResourceInitFailed.prototype.setInputs = function(value) {\n return jspb.Message.setWrapperField(this, 4, value);\n};\n\n\n/**\n * Clears the message field making it undefined.\n * @return {!proto.pulumirpc.ErrorResourceInitFailed} returns this\n */\nproto.pulumirpc.ErrorResourceInitFailed.prototype.clearInputs = function() {\n return this.setInputs(undefined);\n};\n\n\n/**\n * Returns whether this field is set.\n * @return {boolean}\n */\nproto.pulumirpc.ErrorResourceInitFailed.prototype.hasInputs = function() {\n return jspb.Message.getField(this, 4) != null;\n};\n\n\ngoog.object.extend(exports, proto.pulumirpc);\n","// GENERATED CODE -- DO NOT EDIT!\n\n// Original file comments:\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//\n'use strict';\nvar grpc = require('@grpc/grpc-js');\nvar resource_pb = require('./resource_pb.js');\nvar google_protobuf_empty_pb = require('google-protobuf/google/protobuf/empty_pb.js');\nvar google_protobuf_struct_pb = require('google-protobuf/google/protobuf/struct_pb.js');\nvar provider_pb = require('./provider_pb.js');\n\nfunction serialize_google_protobuf_Empty(arg) {\n if (!(arg instanceof google_protobuf_empty_pb.Empty)) {\n throw new Error('Expected argument of type google.protobuf.Empty');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_google_protobuf_Empty(buffer_arg) {\n return google_protobuf_empty_pb.Empty.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_InvokeRequest(arg) {\n if (!(arg instanceof provider_pb.InvokeRequest)) {\n throw new Error('Expected argument of type pulumirpc.InvokeRequest');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_InvokeRequest(buffer_arg) {\n return provider_pb.InvokeRequest.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_InvokeResponse(arg) {\n if (!(arg instanceof provider_pb.InvokeResponse)) {\n throw new Error('Expected argument of type pulumirpc.InvokeResponse');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_InvokeResponse(buffer_arg) {\n return provider_pb.InvokeResponse.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_ReadResourceRequest(arg) {\n if (!(arg instanceof resource_pb.ReadResourceRequest)) {\n throw new Error('Expected argument of type pulumirpc.ReadResourceRequest');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_ReadResourceRequest(buffer_arg) {\n return resource_pb.ReadResourceRequest.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_ReadResourceResponse(arg) {\n if (!(arg instanceof resource_pb.ReadResourceResponse)) {\n throw new Error('Expected argument of type pulumirpc.ReadResourceResponse');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_ReadResourceResponse(buffer_arg) {\n return resource_pb.ReadResourceResponse.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_RegisterResourceOutputsRequest(arg) {\n if (!(arg instanceof resource_pb.RegisterResourceOutputsRequest)) {\n throw new Error('Expected argument of type pulumirpc.RegisterResourceOutputsRequest');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_RegisterResourceOutputsRequest(buffer_arg) {\n return resource_pb.RegisterResourceOutputsRequest.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_RegisterResourceRequest(arg) {\n if (!(arg instanceof resource_pb.RegisterResourceRequest)) {\n throw new Error('Expected argument of type pulumirpc.RegisterResourceRequest');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_RegisterResourceRequest(buffer_arg) {\n return resource_pb.RegisterResourceRequest.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_RegisterResourceResponse(arg) {\n if (!(arg instanceof resource_pb.RegisterResourceResponse)) {\n throw new Error('Expected argument of type pulumirpc.RegisterResourceResponse');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_RegisterResourceResponse(buffer_arg) {\n return resource_pb.RegisterResourceResponse.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_SupportsFeatureRequest(arg) {\n if (!(arg instanceof resource_pb.SupportsFeatureRequest)) {\n throw new Error('Expected argument of type pulumirpc.SupportsFeatureRequest');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_SupportsFeatureRequest(buffer_arg) {\n return resource_pb.SupportsFeatureRequest.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\nfunction serialize_pulumirpc_SupportsFeatureResponse(arg) {\n if (!(arg instanceof resource_pb.SupportsFeatureResponse)) {\n throw new Error('Expected argument of type pulumirpc.SupportsFeatureResponse');\n }\n return Buffer.from(arg.serializeBinary());\n}\n\nfunction deserialize_pulumirpc_SupportsFeatureResponse(buffer_arg) {\n return resource_pb.SupportsFeatureResponse.deserializeBinary(new Uint8Array(buffer_arg));\n}\n\n\n// ResourceMonitor is the interface a source uses to talk back to the planning monitor orchestrating the execution.\nvar ResourceMonitorService = exports.ResourceMonitorService = {\n supportsFeature: {\n path: '/pulumirpc.ResourceMonitor/SupportsFeature',\n requestStream: false,\n responseStream: false,\n requestType: resource_pb.SupportsFeatureRequest,\n responseType: resource_pb.SupportsFeatureResponse,\n requestSerialize: serialize_pulumirpc_SupportsFeatureRequest,\n requestDeserialize: deserialize_pulumirpc_SupportsFeatureRequest,\n responseSerialize: serialize_pulumirpc_SupportsFeatureResponse,\n responseDeserialize: deserialize_pulumirpc_SupportsFeatureResponse,\n },\n invoke: {\n path: '/pulumirpc.ResourceMonitor/Invoke',\n requestStream: false,\n responseStream: false,\n requestType: provider_pb.InvokeRequest,\n responseType: provider_pb.InvokeResponse,\n requestSerialize: serialize_pulumirpc_InvokeRequest,\n requestDeserialize: deserialize_pulumirpc_InvokeRequest,\n responseSerialize: serialize_pulumirpc_InvokeResponse,\n responseDeserialize: deserialize_pulumirpc_InvokeResponse,\n },\n streamInvoke: {\n path: '/pulumirpc.ResourceMonitor/StreamInvoke',\n requestStream: false,\n responseStream: true,\n requestType: provider_pb.InvokeRequest,\n responseType: provider_pb.InvokeResponse,\n requestSerialize: serialize_pulumirpc_InvokeRequest,\n requestDeserialize: deserialize_pulumirpc_InvokeRequest,\n responseSerialize: serialize_pulumirpc_InvokeResponse,\n responseDeserialize: deserialize_pulumirpc_InvokeResponse,\n },\n readResource: {\n path: '/pulumirpc.ResourceMonitor/ReadResource',\n requestStream: false,\n responseStream: false,\n requestType: resource_pb.ReadResourceRequest,\n responseType: resource_pb.ReadResourceResponse,\n requestSerialize: serialize_pulumirpc_ReadResourceRequest,\n requestDeserialize: deserialize_pulumirpc_ReadResourceRequest,\n responseSerialize: serialize_pulumirpc_ReadResourceResponse,\n responseDeserialize: deserialize_pulumirpc_ReadResourceResponse,\n },\n registerResource: {\n path: '/pulumirpc.ResourceMonitor/RegisterResource',\n requestStream: false,\n responseStream: false,\n requestType: resource_pb.RegisterResourceRequest,\n responseType: resource_pb.RegisterResourceResponse,\n requestSerialize: serialize_pulumirpc_RegisterResourceRequest,\n requestDeserialize: deserialize_pulumirpc_RegisterResourceRequest,\n responseSerialize: serialize_pulumirpc_RegisterResourceResponse,\n responseDeserialize: deserialize_pulumirpc_RegisterResourceResponse,\n },\n registerResourceOutputs: {\n path: '/pulumirpc.ResourceMonitor/RegisterResourceOutputs',\n requestStream: false,\n responseStream: false,\n requestType: resource_pb.RegisterResourceOutputsRequest,\n responseType: google_protobuf_empty_pb.Empty,\n requestSerialize: serialize_pulumirpc_RegisterResourceOutputsRequest,\n requestDeserialize: deserialize_pulumirpc_RegisterResourceOutputsRequest,\n responseSerialize: serialize_google_protobuf_Empty,\n responseDeserialize: deserialize_google_protobuf_Empty,\n },\n};\n\nexports.ResourceMonitorClient = grpc.makeGenericClientConstructor(ResourceMonitorService);\n","// source: resource.proto\n/**\n * @fileoverview\n * @enhanceable\n * @suppress {messageConventions} JS Compiler reports an error if a variable or\n * field starts with 'MSG_' and isn't a translatable message.\n * @public\n */\n// GENERATED CODE -- DO NOT EDIT!\n\nvar jspb = require('google-protobuf');\nvar goog = jspb;\nvar proto = { pulumirpc: {} }, global = proto;\n\nvar google_protobuf_empty_pb = require('google-protobuf/google/protobuf/empty_pb.js');\ngoog.object.extend(proto, google_protobuf_empty_pb);\nvar google_protobuf_struct_pb = require('google-protobuf/google/protobuf/struct_pb.js');\ngoog.object.extend(proto, google_protobuf_struct_pb);\nvar provider_pb = require('./provider_pb.js');\ngoog.object.extend(proto, provider_pb);\ngoog.exportSymbol('proto.pulumirpc.ReadResourceRequest', null, global);\ngoog.exportSymbol('proto.pulumirpc.ReadResourceResponse', null, global);\ngoog.exportSymbol('proto.pulumirpc.RegisterResourceOutputsRequest', null, global);\ngoog.exportSymbol('proto.pulumirpc.RegisterResourceRequest', null, global);\ngoog.exportSymbol('proto.pulumirpc.RegisterResourceRequest.CustomTimeouts', null, global);\ngoog.exportSymbol('proto.pulumirpc.RegisterResourceRequest.PropertyDependencies', null, global);\ngoog.exportSymbol('proto.pulumirpc.RegisterResourceResponse', null, global);\ngoog.exportSymbol('proto.pulumirpc.RegisterResourceResponse.PropertyDependencies', null, global);\ngoog.exportSymbol('proto.pulumirpc.SupportsFeatureRequest', null, global);\ngoog.exportSymbol('proto.pulumirpc.SupportsFeatureResponse', null, global);\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.SupportsFeatureRequest = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, null, null);\n};\ngoog.inherits(proto.pulumirpc.SupportsFeatureRequest, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.SupportsFeatureRequest.displayName = 'proto.pulumirpc.SupportsFeatureRequest';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.SupportsFeatureResponse = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, null, null);\n};\ngoog.inherits(proto.pulumirpc.SupportsFeatureResponse, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.SupportsFeatureResponse.displayName = 'proto.pulumirpc.SupportsFeatureResponse';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.ReadResourceRequest = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, proto.pulumirpc.ReadResourceRequest.repeatedFields_, null);\n};\ngoog.inherits(proto.pulumirpc.ReadResourceRequest, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.ReadResourceRequest.displayName = 'proto.pulumirpc.ReadResourceRequest';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.ReadResourceResponse = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, null, null);\n};\ngoog.inherits(proto.pulumirpc.ReadResourceResponse, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.ReadResourceResponse.displayName = 'proto.pulumirpc.ReadResourceResponse';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.RegisterResourceRequest = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, proto.pulumirpc.RegisterResourceRequest.repeatedFields_, null);\n};\ngoog.inherits(proto.pulumirpc.RegisterResourceRequest, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.RegisterResourceRequest.displayName = 'proto.pulumirpc.RegisterResourceRequest';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.RegisterResourceRequest.PropertyDependencies = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, proto.pulumirpc.RegisterResourceRequest.PropertyDependencies.repeatedFields_, null);\n};\ngoog.inherits(proto.pulumirpc.RegisterResourceRequest.PropertyDependencies, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.RegisterResourceRequest.PropertyDependencies.displayName = 'proto.pulumirpc.RegisterResourceRequest.PropertyDependencies';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.RegisterResourceRequest.CustomTimeouts = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, null, null);\n};\ngoog.inherits(proto.pulumirpc.RegisterResourceRequest.CustomTimeouts, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.RegisterResourceRequest.CustomTimeouts.displayName = 'proto.pulumirpc.RegisterResourceRequest.CustomTimeouts';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.RegisterResourceResponse = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, proto.pulumirpc.RegisterResourceResponse.repeatedFields_, null);\n};\ngoog.inherits(proto.pulumirpc.RegisterResourceResponse, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.RegisterResourceResponse.displayName = 'proto.pulumirpc.RegisterResourceResponse';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.RegisterResourceResponse.PropertyDependencies = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, proto.pulumirpc.RegisterResourceResponse.PropertyDependencies.repeatedFields_, null);\n};\ngoog.inherits(proto.pulumirpc.RegisterResourceResponse.PropertyDependencies, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.RegisterResourceResponse.PropertyDependencies.displayName = 'proto.pulumirpc.RegisterResourceResponse.PropertyDependencies';\n}\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.pulumirpc.RegisterResourceOutputsRequest = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, null, null);\n};\ngoog.inherits(proto.pulumirpc.RegisterResourceOutputsRequest, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.pulumirpc.RegisterResourceOutputsRequest.displayName = 'proto.pulumirpc.RegisterResourceOutputsRequest';\n}\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.SupportsFeatureRequest.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.SupportsFeatureRequest.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.SupportsFeatureRequest} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.SupportsFeatureRequest.toObject = function(includeInstance, msg) {\n var f, obj = {\n id: jspb.Message.getFieldWithDefault(msg, 1, \"\")\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.SupportsFeatureRequest}\n */\nproto.pulumirpc.SupportsFeatureRequest.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.SupportsFeatureRequest;\n return proto.pulumirpc.SupportsFeatureRequest.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.SupportsFeatureRequest} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.SupportsFeatureRequest}\n */\nproto.pulumirpc.SupportsFeatureRequest.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {string} */ (reader.readString());\n msg.setId(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.SupportsFeatureRequest.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.SupportsFeatureRequest.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.SupportsFeatureRequest} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.SupportsFeatureRequest.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getId();\n if (f.length > 0) {\n writer.writeString(\n 1,\n f\n );\n }\n};\n\n\n/**\n * optional string id = 1;\n * @return {string}\n */\nproto.pulumirpc.SupportsFeatureRequest.prototype.getId = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.SupportsFeatureRequest} returns this\n */\nproto.pulumirpc.SupportsFeatureRequest.prototype.setId = function(value) {\n return jspb.Message.setProto3StringField(this, 1, value);\n};\n\n\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.SupportsFeatureResponse.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.SupportsFeatureResponse.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.SupportsFeatureResponse} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.SupportsFeatureResponse.toObject = function(includeInstance, msg) {\n var f, obj = {\n hassupport: jspb.Message.getBooleanFieldWithDefault(msg, 1, false)\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.SupportsFeatureResponse}\n */\nproto.pulumirpc.SupportsFeatureResponse.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.SupportsFeatureResponse;\n return proto.pulumirpc.SupportsFeatureResponse.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.SupportsFeatureResponse} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.SupportsFeatureResponse}\n */\nproto.pulumirpc.SupportsFeatureResponse.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {boolean} */ (reader.readBool());\n msg.setHassupport(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.SupportsFeatureResponse.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.SupportsFeatureResponse.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.SupportsFeatureResponse} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.SupportsFeatureResponse.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getHassupport();\n if (f) {\n writer.writeBool(\n 1,\n f\n );\n }\n};\n\n\n/**\n * optional bool hasSupport = 1;\n * @return {boolean}\n */\nproto.pulumirpc.SupportsFeatureResponse.prototype.getHassupport = function() {\n return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 1, false));\n};\n\n\n/**\n * @param {boolean} value\n * @return {!proto.pulumirpc.SupportsFeatureResponse} returns this\n */\nproto.pulumirpc.SupportsFeatureResponse.prototype.setHassupport = function(value) {\n return jspb.Message.setProto3BooleanField(this, 1, value);\n};\n\n\n\n/**\n * List of repeated fields within this message type.\n * @private {!Array}\n * @const\n */\nproto.pulumirpc.ReadResourceRequest.repeatedFields_ = [6,10,11];\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.ReadResourceRequest.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.ReadResourceRequest.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.ReadResourceRequest} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.ReadResourceRequest.toObject = function(includeInstance, msg) {\n var f, obj = {\n id: jspb.Message.getFieldWithDefault(msg, 1, \"\"),\n type: jspb.Message.getFieldWithDefault(msg, 2, \"\"),\n name: jspb.Message.getFieldWithDefault(msg, 3, \"\"),\n parent: jspb.Message.getFieldWithDefault(msg, 4, \"\"),\n properties: (f = msg.getProperties()) && google_protobuf_struct_pb.Struct.toObject(includeInstance, f),\n dependenciesList: (f = jspb.Message.getRepeatedField(msg, 6)) == null ? undefined : f,\n provider: jspb.Message.getFieldWithDefault(msg, 7, \"\"),\n version: jspb.Message.getFieldWithDefault(msg, 8, \"\"),\n acceptsecrets: jspb.Message.getBooleanFieldWithDefault(msg, 9, false),\n additionalsecretoutputsList: (f = jspb.Message.getRepeatedField(msg, 10)) == null ? undefined : f,\n aliasesList: (f = jspb.Message.getRepeatedField(msg, 11)) == null ? undefined : f,\n acceptresources: jspb.Message.getBooleanFieldWithDefault(msg, 12, false)\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.ReadResourceRequest}\n */\nproto.pulumirpc.ReadResourceRequest.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.ReadResourceRequest;\n return proto.pulumirpc.ReadResourceRequest.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.ReadResourceRequest} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.ReadResourceRequest}\n */\nproto.pulumirpc.ReadResourceRequest.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {string} */ (reader.readString());\n msg.setId(value);\n break;\n case 2:\n var value = /** @type {string} */ (reader.readString());\n msg.setType(value);\n break;\n case 3:\n var value = /** @type {string} */ (reader.readString());\n msg.setName(value);\n break;\n case 4:\n var value = /** @type {string} */ (reader.readString());\n msg.setParent(value);\n break;\n case 5:\n var value = new google_protobuf_struct_pb.Struct;\n reader.readMessage(value,google_protobuf_struct_pb.Struct.deserializeBinaryFromReader);\n msg.setProperties(value);\n break;\n case 6:\n var value = /** @type {string} */ (reader.readString());\n msg.addDependencies(value);\n break;\n case 7:\n var value = /** @type {string} */ (reader.readString());\n msg.setProvider(value);\n break;\n case 8:\n var value = /** @type {string} */ (reader.readString());\n msg.setVersion(value);\n break;\n case 9:\n var value = /** @type {boolean} */ (reader.readBool());\n msg.setAcceptsecrets(value);\n break;\n case 10:\n var value = /** @type {string} */ (reader.readString());\n msg.addAdditionalsecretoutputs(value);\n break;\n case 11:\n var value = /** @type {string} */ (reader.readString());\n msg.addAliases(value);\n break;\n case 12:\n var value = /** @type {boolean} */ (reader.readBool());\n msg.setAcceptresources(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.ReadResourceRequest.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.ReadResourceRequest.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.ReadResourceRequest} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.ReadResourceRequest.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getId();\n if (f.length > 0) {\n writer.writeString(\n 1,\n f\n );\n }\n f = message.getType();\n if (f.length > 0) {\n writer.writeString(\n 2,\n f\n );\n }\n f = message.getName();\n if (f.length > 0) {\n writer.writeString(\n 3,\n f\n );\n }\n f = message.getParent();\n if (f.length > 0) {\n writer.writeString(\n 4,\n f\n );\n }\n f = message.getProperties();\n if (f != null) {\n writer.writeMessage(\n 5,\n f,\n google_protobuf_struct_pb.Struct.serializeBinaryToWriter\n );\n }\n f = message.getDependenciesList();\n if (f.length > 0) {\n writer.writeRepeatedString(\n 6,\n f\n );\n }\n f = message.getProvider();\n if (f.length > 0) {\n writer.writeString(\n 7,\n f\n );\n }\n f = message.getVersion();\n if (f.length > 0) {\n writer.writeString(\n 8,\n f\n );\n }\n f = message.getAcceptsecrets();\n if (f) {\n writer.writeBool(\n 9,\n f\n );\n }\n f = message.getAdditionalsecretoutputsList();\n if (f.length > 0) {\n writer.writeRepeatedString(\n 10,\n f\n );\n }\n f = message.getAliasesList();\n if (f.length > 0) {\n writer.writeRepeatedString(\n 11,\n f\n );\n }\n f = message.getAcceptresources();\n if (f) {\n writer.writeBool(\n 12,\n f\n );\n }\n};\n\n\n/**\n * optional string id = 1;\n * @return {string}\n */\nproto.pulumirpc.ReadResourceRequest.prototype.getId = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.ReadResourceRequest} returns this\n */\nproto.pulumirpc.ReadResourceRequest.prototype.setId = function(value) {\n return jspb.Message.setProto3StringField(this, 1, value);\n};\n\n\n/**\n * optional string type = 2;\n * @return {string}\n */\nproto.pulumirpc.ReadResourceRequest.prototype.getType = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.ReadResourceRequest} returns this\n */\nproto.pulumirpc.ReadResourceRequest.prototype.setType = function(value) {\n return jspb.Message.setProto3StringField(this, 2, value);\n};\n\n\n/**\n * optional string name = 3;\n * @return {string}\n */\nproto.pulumirpc.ReadResourceRequest.prototype.getName = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.ReadResourceRequest} returns this\n */\nproto.pulumirpc.ReadResourceRequest.prototype.setName = function(value) {\n return jspb.Message.setProto3StringField(this, 3, value);\n};\n\n\n/**\n * optional string parent = 4;\n * @return {string}\n */\nproto.pulumirpc.ReadResourceRequest.prototype.getParent = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 4, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.ReadResourceRequest} returns this\n */\nproto.pulumirpc.ReadResourceRequest.prototype.setParent = function(value) {\n return jspb.Message.setProto3StringField(this, 4, value);\n};\n\n\n/**\n * optional google.protobuf.Struct properties = 5;\n * @return {?proto.google.protobuf.Struct}\n */\nproto.pulumirpc.ReadResourceRequest.prototype.getProperties = function() {\n return /** @type{?proto.google.protobuf.Struct} */ (\n jspb.Message.getWrapperField(this, google_protobuf_struct_pb.Struct, 5));\n};\n\n\n/**\n * @param {?proto.google.protobuf.Struct|undefined} value\n * @return {!proto.pulumirpc.ReadResourceRequest} returns this\n*/\nproto.pulumirpc.ReadResourceRequest.prototype.setProperties = function(value) {\n return jspb.Message.setWrapperField(this, 5, value);\n};\n\n\n/**\n * Clears the message field making it undefined.\n * @return {!proto.pulumirpc.ReadResourceRequest} returns this\n */\nproto.pulumirpc.ReadResourceRequest.prototype.clearProperties = function() {\n return this.setProperties(undefined);\n};\n\n\n/**\n * Returns whether this field is set.\n * @return {boolean}\n */\nproto.pulumirpc.ReadResourceRequest.prototype.hasProperties = function() {\n return jspb.Message.getField(this, 5) != null;\n};\n\n\n/**\n * repeated string dependencies = 6;\n * @return {!Array}\n */\nproto.pulumirpc.ReadResourceRequest.prototype.getDependenciesList = function() {\n return /** @type {!Array} */ (jspb.Message.getRepeatedField(this, 6));\n};\n\n\n/**\n * @param {!Array} value\n * @return {!proto.pulumirpc.ReadResourceRequest} returns this\n */\nproto.pulumirpc.ReadResourceRequest.prototype.setDependenciesList = function(value) {\n return jspb.Message.setField(this, 6, value || []);\n};\n\n\n/**\n * @param {string} value\n * @param {number=} opt_index\n * @return {!proto.pulumirpc.ReadResourceRequest} returns this\n */\nproto.pulumirpc.ReadResourceRequest.prototype.addDependencies = function(value, opt_index) {\n return jspb.Message.addToRepeatedField(this, 6, value, opt_index);\n};\n\n\n/**\n * Clears the list making it empty but non-null.\n * @return {!proto.pulumirpc.ReadResourceRequest} returns this\n */\nproto.pulumirpc.ReadResourceRequest.prototype.clearDependenciesList = function() {\n return this.setDependenciesList([]);\n};\n\n\n/**\n * optional string provider = 7;\n * @return {string}\n */\nproto.pulumirpc.ReadResourceRequest.prototype.getProvider = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 7, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.ReadResourceRequest} returns this\n */\nproto.pulumirpc.ReadResourceRequest.prototype.setProvider = function(value) {\n return jspb.Message.setProto3StringField(this, 7, value);\n};\n\n\n/**\n * optional string version = 8;\n * @return {string}\n */\nproto.pulumirpc.ReadResourceRequest.prototype.getVersion = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 8, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.ReadResourceRequest} returns this\n */\nproto.pulumirpc.ReadResourceRequest.prototype.setVersion = function(value) {\n return jspb.Message.setProto3StringField(this, 8, value);\n};\n\n\n/**\n * optional bool acceptSecrets = 9;\n * @return {boolean}\n */\nproto.pulumirpc.ReadResourceRequest.prototype.getAcceptsecrets = function() {\n return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 9, false));\n};\n\n\n/**\n * @param {boolean} value\n * @return {!proto.pulumirpc.ReadResourceRequest} returns this\n */\nproto.pulumirpc.ReadResourceRequest.prototype.setAcceptsecrets = function(value) {\n return jspb.Message.setProto3BooleanField(this, 9, value);\n};\n\n\n/**\n * repeated string additionalSecretOutputs = 10;\n * @return {!Array}\n */\nproto.pulumirpc.ReadResourceRequest.prototype.getAdditionalsecretoutputsList = function() {\n return /** @type {!Array} */ (jspb.Message.getRepeatedField(this, 10));\n};\n\n\n/**\n * @param {!Array} value\n * @return {!proto.pulumirpc.ReadResourceRequest} returns this\n */\nproto.pulumirpc.ReadResourceRequest.prototype.setAdditionalsecretoutputsList = function(value) {\n return jspb.Message.setField(this, 10, value || []);\n};\n\n\n/**\n * @param {string} value\n * @param {number=} opt_index\n * @return {!proto.pulumirpc.ReadResourceRequest} returns this\n */\nproto.pulumirpc.ReadResourceRequest.prototype.addAdditionalsecretoutputs = function(value, opt_index) {\n return jspb.Message.addToRepeatedField(this, 10, value, opt_index);\n};\n\n\n/**\n * Clears the list making it empty but non-null.\n * @return {!proto.pulumirpc.ReadResourceRequest} returns this\n */\nproto.pulumirpc.ReadResourceRequest.prototype.clearAdditionalsecretoutputsList = function() {\n return this.setAdditionalsecretoutputsList([]);\n};\n\n\n/**\n * repeated string aliases = 11;\n * @return {!Array}\n */\nproto.pulumirpc.ReadResourceRequest.prototype.getAliasesList = function() {\n return /** @type {!Array} */ (jspb.Message.getRepeatedField(this, 11));\n};\n\n\n/**\n * @param {!Array} value\n * @return {!proto.pulumirpc.ReadResourceRequest} returns this\n */\nproto.pulumirpc.ReadResourceRequest.prototype.setAliasesList = function(value) {\n return jspb.Message.setField(this, 11, value || []);\n};\n\n\n/**\n * @param {string} value\n * @param {number=} opt_index\n * @return {!proto.pulumirpc.ReadResourceRequest} returns this\n */\nproto.pulumirpc.ReadResourceRequest.prototype.addAliases = function(value, opt_index) {\n return jspb.Message.addToRepeatedField(this, 11, value, opt_index);\n};\n\n\n/**\n * Clears the list making it empty but non-null.\n * @return {!proto.pulumirpc.ReadResourceRequest} returns this\n */\nproto.pulumirpc.ReadResourceRequest.prototype.clearAliasesList = function() {\n return this.setAliasesList([]);\n};\n\n\n/**\n * optional bool acceptResources = 12;\n * @return {boolean}\n */\nproto.pulumirpc.ReadResourceRequest.prototype.getAcceptresources = function() {\n return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 12, false));\n};\n\n\n/**\n * @param {boolean} value\n * @return {!proto.pulumirpc.ReadResourceRequest} returns this\n */\nproto.pulumirpc.ReadResourceRequest.prototype.setAcceptresources = function(value) {\n return jspb.Message.setProto3BooleanField(this, 12, value);\n};\n\n\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.ReadResourceResponse.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.ReadResourceResponse.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.ReadResourceResponse} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.ReadResourceResponse.toObject = function(includeInstance, msg) {\n var f, obj = {\n urn: jspb.Message.getFieldWithDefault(msg, 1, \"\"),\n properties: (f = msg.getProperties()) && google_protobuf_struct_pb.Struct.toObject(includeInstance, f)\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.ReadResourceResponse}\n */\nproto.pulumirpc.ReadResourceResponse.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.ReadResourceResponse;\n return proto.pulumirpc.ReadResourceResponse.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.ReadResourceResponse} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.ReadResourceResponse}\n */\nproto.pulumirpc.ReadResourceResponse.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {string} */ (reader.readString());\n msg.setUrn(value);\n break;\n case 2:\n var value = new google_protobuf_struct_pb.Struct;\n reader.readMessage(value,google_protobuf_struct_pb.Struct.deserializeBinaryFromReader);\n msg.setProperties(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.ReadResourceResponse.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.ReadResourceResponse.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.ReadResourceResponse} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.ReadResourceResponse.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getUrn();\n if (f.length > 0) {\n writer.writeString(\n 1,\n f\n );\n }\n f = message.getProperties();\n if (f != null) {\n writer.writeMessage(\n 2,\n f,\n google_protobuf_struct_pb.Struct.serializeBinaryToWriter\n );\n }\n};\n\n\n/**\n * optional string urn = 1;\n * @return {string}\n */\nproto.pulumirpc.ReadResourceResponse.prototype.getUrn = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.ReadResourceResponse} returns this\n */\nproto.pulumirpc.ReadResourceResponse.prototype.setUrn = function(value) {\n return jspb.Message.setProto3StringField(this, 1, value);\n};\n\n\n/**\n * optional google.protobuf.Struct properties = 2;\n * @return {?proto.google.protobuf.Struct}\n */\nproto.pulumirpc.ReadResourceResponse.prototype.getProperties = function() {\n return /** @type{?proto.google.protobuf.Struct} */ (\n jspb.Message.getWrapperField(this, google_protobuf_struct_pb.Struct, 2));\n};\n\n\n/**\n * @param {?proto.google.protobuf.Struct|undefined} value\n * @return {!proto.pulumirpc.ReadResourceResponse} returns this\n*/\nproto.pulumirpc.ReadResourceResponse.prototype.setProperties = function(value) {\n return jspb.Message.setWrapperField(this, 2, value);\n};\n\n\n/**\n * Clears the message field making it undefined.\n * @return {!proto.pulumirpc.ReadResourceResponse} returns this\n */\nproto.pulumirpc.ReadResourceResponse.prototype.clearProperties = function() {\n return this.setProperties(undefined);\n};\n\n\n/**\n * Returns whether this field is set.\n * @return {boolean}\n */\nproto.pulumirpc.ReadResourceResponse.prototype.hasProperties = function() {\n return jspb.Message.getField(this, 2) != null;\n};\n\n\n\n/**\n * List of repeated fields within this message type.\n * @private {!Array}\n * @const\n */\nproto.pulumirpc.RegisterResourceRequest.repeatedFields_ = [7,12,14,15];\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.RegisterResourceRequest.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.RegisterResourceRequest} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.RegisterResourceRequest.toObject = function(includeInstance, msg) {\n var f, obj = {\n type: jspb.Message.getFieldWithDefault(msg, 1, \"\"),\n name: jspb.Message.getFieldWithDefault(msg, 2, \"\"),\n parent: jspb.Message.getFieldWithDefault(msg, 3, \"\"),\n custom: jspb.Message.getBooleanFieldWithDefault(msg, 4, false),\n object: (f = msg.getObject()) && google_protobuf_struct_pb.Struct.toObject(includeInstance, f),\n protect: jspb.Message.getBooleanFieldWithDefault(msg, 6, false),\n dependenciesList: (f = jspb.Message.getRepeatedField(msg, 7)) == null ? undefined : f,\n provider: jspb.Message.getFieldWithDefault(msg, 8, \"\"),\n propertydependenciesMap: (f = msg.getPropertydependenciesMap()) ? f.toObject(includeInstance, proto.pulumirpc.RegisterResourceRequest.PropertyDependencies.toObject) : [],\n deletebeforereplace: jspb.Message.getBooleanFieldWithDefault(msg, 10, false),\n version: jspb.Message.getFieldWithDefault(msg, 11, \"\"),\n ignorechangesList: (f = jspb.Message.getRepeatedField(msg, 12)) == null ? undefined : f,\n acceptsecrets: jspb.Message.getBooleanFieldWithDefault(msg, 13, false),\n additionalsecretoutputsList: (f = jspb.Message.getRepeatedField(msg, 14)) == null ? undefined : f,\n aliasesList: (f = jspb.Message.getRepeatedField(msg, 15)) == null ? undefined : f,\n importid: jspb.Message.getFieldWithDefault(msg, 16, \"\"),\n customtimeouts: (f = msg.getCustomtimeouts()) && proto.pulumirpc.RegisterResourceRequest.CustomTimeouts.toObject(includeInstance, f),\n deletebeforereplacedefined: jspb.Message.getBooleanFieldWithDefault(msg, 18, false),\n supportspartialvalues: jspb.Message.getBooleanFieldWithDefault(msg, 19, false),\n remote: jspb.Message.getBooleanFieldWithDefault(msg, 20, false),\n acceptresources: jspb.Message.getBooleanFieldWithDefault(msg, 21, false)\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.RegisterResourceRequest}\n */\nproto.pulumirpc.RegisterResourceRequest.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.RegisterResourceRequest;\n return proto.pulumirpc.RegisterResourceRequest.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.RegisterResourceRequest} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.RegisterResourceRequest}\n */\nproto.pulumirpc.RegisterResourceRequest.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {string} */ (reader.readString());\n msg.setType(value);\n break;\n case 2:\n var value = /** @type {string} */ (reader.readString());\n msg.setName(value);\n break;\n case 3:\n var value = /** @type {string} */ (reader.readString());\n msg.setParent(value);\n break;\n case 4:\n var value = /** @type {boolean} */ (reader.readBool());\n msg.setCustom(value);\n break;\n case 5:\n var value = new google_protobuf_struct_pb.Struct;\n reader.readMessage(value,google_protobuf_struct_pb.Struct.deserializeBinaryFromReader);\n msg.setObject(value);\n break;\n case 6:\n var value = /** @type {boolean} */ (reader.readBool());\n msg.setProtect(value);\n break;\n case 7:\n var value = /** @type {string} */ (reader.readString());\n msg.addDependencies(value);\n break;\n case 8:\n var value = /** @type {string} */ (reader.readString());\n msg.setProvider(value);\n break;\n case 9:\n var value = msg.getPropertydependenciesMap();\n reader.readMessage(value, function(message, reader) {\n jspb.Map.deserializeBinary(message, reader, jspb.BinaryReader.prototype.readString, jspb.BinaryReader.prototype.readMessage, proto.pulumirpc.RegisterResourceRequest.PropertyDependencies.deserializeBinaryFromReader, \"\", new proto.pulumirpc.RegisterResourceRequest.PropertyDependencies());\n });\n break;\n case 10:\n var value = /** @type {boolean} */ (reader.readBool());\n msg.setDeletebeforereplace(value);\n break;\n case 11:\n var value = /** @type {string} */ (reader.readString());\n msg.setVersion(value);\n break;\n case 12:\n var value = /** @type {string} */ (reader.readString());\n msg.addIgnorechanges(value);\n break;\n case 13:\n var value = /** @type {boolean} */ (reader.readBool());\n msg.setAcceptsecrets(value);\n break;\n case 14:\n var value = /** @type {string} */ (reader.readString());\n msg.addAdditionalsecretoutputs(value);\n break;\n case 15:\n var value = /** @type {string} */ (reader.readString());\n msg.addAliases(value);\n break;\n case 16:\n var value = /** @type {string} */ (reader.readString());\n msg.setImportid(value);\n break;\n case 17:\n var value = new proto.pulumirpc.RegisterResourceRequest.CustomTimeouts;\n reader.readMessage(value,proto.pulumirpc.RegisterResourceRequest.CustomTimeouts.deserializeBinaryFromReader);\n msg.setCustomtimeouts(value);\n break;\n case 18:\n var value = /** @type {boolean} */ (reader.readBool());\n msg.setDeletebeforereplacedefined(value);\n break;\n case 19:\n var value = /** @type {boolean} */ (reader.readBool());\n msg.setSupportspartialvalues(value);\n break;\n case 20:\n var value = /** @type {boolean} */ (reader.readBool());\n msg.setRemote(value);\n break;\n case 21:\n var value = /** @type {boolean} */ (reader.readBool());\n msg.setAcceptresources(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.RegisterResourceRequest.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.RegisterResourceRequest} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.RegisterResourceRequest.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getType();\n if (f.length > 0) {\n writer.writeString(\n 1,\n f\n );\n }\n f = message.getName();\n if (f.length > 0) {\n writer.writeString(\n 2,\n f\n );\n }\n f = message.getParent();\n if (f.length > 0) {\n writer.writeString(\n 3,\n f\n );\n }\n f = message.getCustom();\n if (f) {\n writer.writeBool(\n 4,\n f\n );\n }\n f = message.getObject();\n if (f != null) {\n writer.writeMessage(\n 5,\n f,\n google_protobuf_struct_pb.Struct.serializeBinaryToWriter\n );\n }\n f = message.getProtect();\n if (f) {\n writer.writeBool(\n 6,\n f\n );\n }\n f = message.getDependenciesList();\n if (f.length > 0) {\n writer.writeRepeatedString(\n 7,\n f\n );\n }\n f = message.getProvider();\n if (f.length > 0) {\n writer.writeString(\n 8,\n f\n );\n }\n f = message.getPropertydependenciesMap(true);\n if (f && f.getLength() > 0) {\n f.serializeBinary(9, writer, jspb.BinaryWriter.prototype.writeString, jspb.BinaryWriter.prototype.writeMessage, proto.pulumirpc.RegisterResourceRequest.PropertyDependencies.serializeBinaryToWriter);\n }\n f = message.getDeletebeforereplace();\n if (f) {\n writer.writeBool(\n 10,\n f\n );\n }\n f = message.getVersion();\n if (f.length > 0) {\n writer.writeString(\n 11,\n f\n );\n }\n f = message.getIgnorechangesList();\n if (f.length > 0) {\n writer.writeRepeatedString(\n 12,\n f\n );\n }\n f = message.getAcceptsecrets();\n if (f) {\n writer.writeBool(\n 13,\n f\n );\n }\n f = message.getAdditionalsecretoutputsList();\n if (f.length > 0) {\n writer.writeRepeatedString(\n 14,\n f\n );\n }\n f = message.getAliasesList();\n if (f.length > 0) {\n writer.writeRepeatedString(\n 15,\n f\n );\n }\n f = message.getImportid();\n if (f.length > 0) {\n writer.writeString(\n 16,\n f\n );\n }\n f = message.getCustomtimeouts();\n if (f != null) {\n writer.writeMessage(\n 17,\n f,\n proto.pulumirpc.RegisterResourceRequest.CustomTimeouts.serializeBinaryToWriter\n );\n }\n f = message.getDeletebeforereplacedefined();\n if (f) {\n writer.writeBool(\n 18,\n f\n );\n }\n f = message.getSupportspartialvalues();\n if (f) {\n writer.writeBool(\n 19,\n f\n );\n }\n f = message.getRemote();\n if (f) {\n writer.writeBool(\n 20,\n f\n );\n }\n f = message.getAcceptresources();\n if (f) {\n writer.writeBool(\n 21,\n f\n );\n }\n};\n\n\n\n/**\n * List of repeated fields within this message type.\n * @private {!Array}\n * @const\n */\nproto.pulumirpc.RegisterResourceRequest.PropertyDependencies.repeatedFields_ = [1];\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.RegisterResourceRequest.PropertyDependencies.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.RegisterResourceRequest.PropertyDependencies.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.RegisterResourceRequest.PropertyDependencies} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.RegisterResourceRequest.PropertyDependencies.toObject = function(includeInstance, msg) {\n var f, obj = {\n urnsList: (f = jspb.Message.getRepeatedField(msg, 1)) == null ? undefined : f\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.RegisterResourceRequest.PropertyDependencies}\n */\nproto.pulumirpc.RegisterResourceRequest.PropertyDependencies.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.RegisterResourceRequest.PropertyDependencies;\n return proto.pulumirpc.RegisterResourceRequest.PropertyDependencies.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.RegisterResourceRequest.PropertyDependencies} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.RegisterResourceRequest.PropertyDependencies}\n */\nproto.pulumirpc.RegisterResourceRequest.PropertyDependencies.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {string} */ (reader.readString());\n msg.addUrns(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.RegisterResourceRequest.PropertyDependencies.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.RegisterResourceRequest.PropertyDependencies.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.RegisterResourceRequest.PropertyDependencies} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.RegisterResourceRequest.PropertyDependencies.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getUrnsList();\n if (f.length > 0) {\n writer.writeRepeatedString(\n 1,\n f\n );\n }\n};\n\n\n/**\n * repeated string urns = 1;\n * @return {!Array}\n */\nproto.pulumirpc.RegisterResourceRequest.PropertyDependencies.prototype.getUrnsList = function() {\n return /** @type {!Array} */ (jspb.Message.getRepeatedField(this, 1));\n};\n\n\n/**\n * @param {!Array} value\n * @return {!proto.pulumirpc.RegisterResourceRequest.PropertyDependencies} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.PropertyDependencies.prototype.setUrnsList = function(value) {\n return jspb.Message.setField(this, 1, value || []);\n};\n\n\n/**\n * @param {string} value\n * @param {number=} opt_index\n * @return {!proto.pulumirpc.RegisterResourceRequest.PropertyDependencies} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.PropertyDependencies.prototype.addUrns = function(value, opt_index) {\n return jspb.Message.addToRepeatedField(this, 1, value, opt_index);\n};\n\n\n/**\n * Clears the list making it empty but non-null.\n * @return {!proto.pulumirpc.RegisterResourceRequest.PropertyDependencies} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.PropertyDependencies.prototype.clearUrnsList = function() {\n return this.setUrnsList([]);\n};\n\n\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.RegisterResourceRequest.CustomTimeouts.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.RegisterResourceRequest.CustomTimeouts.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.RegisterResourceRequest.CustomTimeouts} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.RegisterResourceRequest.CustomTimeouts.toObject = function(includeInstance, msg) {\n var f, obj = {\n create: jspb.Message.getFieldWithDefault(msg, 1, \"\"),\n update: jspb.Message.getFieldWithDefault(msg, 2, \"\"),\n pb_delete: jspb.Message.getFieldWithDefault(msg, 3, \"\")\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.RegisterResourceRequest.CustomTimeouts}\n */\nproto.pulumirpc.RegisterResourceRequest.CustomTimeouts.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.RegisterResourceRequest.CustomTimeouts;\n return proto.pulumirpc.RegisterResourceRequest.CustomTimeouts.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.RegisterResourceRequest.CustomTimeouts} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.RegisterResourceRequest.CustomTimeouts}\n */\nproto.pulumirpc.RegisterResourceRequest.CustomTimeouts.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {string} */ (reader.readString());\n msg.setCreate(value);\n break;\n case 2:\n var value = /** @type {string} */ (reader.readString());\n msg.setUpdate(value);\n break;\n case 3:\n var value = /** @type {string} */ (reader.readString());\n msg.setDelete(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.RegisterResourceRequest.CustomTimeouts.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.RegisterResourceRequest.CustomTimeouts.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.RegisterResourceRequest.CustomTimeouts} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.RegisterResourceRequest.CustomTimeouts.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getCreate();\n if (f.length > 0) {\n writer.writeString(\n 1,\n f\n );\n }\n f = message.getUpdate();\n if (f.length > 0) {\n writer.writeString(\n 2,\n f\n );\n }\n f = message.getDelete();\n if (f.length > 0) {\n writer.writeString(\n 3,\n f\n );\n }\n};\n\n\n/**\n * optional string create = 1;\n * @return {string}\n */\nproto.pulumirpc.RegisterResourceRequest.CustomTimeouts.prototype.getCreate = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.RegisterResourceRequest.CustomTimeouts} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.CustomTimeouts.prototype.setCreate = function(value) {\n return jspb.Message.setProto3StringField(this, 1, value);\n};\n\n\n/**\n * optional string update = 2;\n * @return {string}\n */\nproto.pulumirpc.RegisterResourceRequest.CustomTimeouts.prototype.getUpdate = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.RegisterResourceRequest.CustomTimeouts} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.CustomTimeouts.prototype.setUpdate = function(value) {\n return jspb.Message.setProto3StringField(this, 2, value);\n};\n\n\n/**\n * optional string delete = 3;\n * @return {string}\n */\nproto.pulumirpc.RegisterResourceRequest.CustomTimeouts.prototype.getDelete = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.RegisterResourceRequest.CustomTimeouts} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.CustomTimeouts.prototype.setDelete = function(value) {\n return jspb.Message.setProto3StringField(this, 3, value);\n};\n\n\n/**\n * optional string type = 1;\n * @return {string}\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.getType = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.RegisterResourceRequest} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.setType = function(value) {\n return jspb.Message.setProto3StringField(this, 1, value);\n};\n\n\n/**\n * optional string name = 2;\n * @return {string}\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.getName = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.RegisterResourceRequest} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.setName = function(value) {\n return jspb.Message.setProto3StringField(this, 2, value);\n};\n\n\n/**\n * optional string parent = 3;\n * @return {string}\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.getParent = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.RegisterResourceRequest} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.setParent = function(value) {\n return jspb.Message.setProto3StringField(this, 3, value);\n};\n\n\n/**\n * optional bool custom = 4;\n * @return {boolean}\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.getCustom = function() {\n return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 4, false));\n};\n\n\n/**\n * @param {boolean} value\n * @return {!proto.pulumirpc.RegisterResourceRequest} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.setCustom = function(value) {\n return jspb.Message.setProto3BooleanField(this, 4, value);\n};\n\n\n/**\n * optional google.protobuf.Struct object = 5;\n * @return {?proto.google.protobuf.Struct}\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.getObject = function() {\n return /** @type{?proto.google.protobuf.Struct} */ (\n jspb.Message.getWrapperField(this, google_protobuf_struct_pb.Struct, 5));\n};\n\n\n/**\n * @param {?proto.google.protobuf.Struct|undefined} value\n * @return {!proto.pulumirpc.RegisterResourceRequest} returns this\n*/\nproto.pulumirpc.RegisterResourceRequest.prototype.setObject = function(value) {\n return jspb.Message.setWrapperField(this, 5, value);\n};\n\n\n/**\n * Clears the message field making it undefined.\n * @return {!proto.pulumirpc.RegisterResourceRequest} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.clearObject = function() {\n return this.setObject(undefined);\n};\n\n\n/**\n * Returns whether this field is set.\n * @return {boolean}\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.hasObject = function() {\n return jspb.Message.getField(this, 5) != null;\n};\n\n\n/**\n * optional bool protect = 6;\n * @return {boolean}\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.getProtect = function() {\n return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 6, false));\n};\n\n\n/**\n * @param {boolean} value\n * @return {!proto.pulumirpc.RegisterResourceRequest} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.setProtect = function(value) {\n return jspb.Message.setProto3BooleanField(this, 6, value);\n};\n\n\n/**\n * repeated string dependencies = 7;\n * @return {!Array}\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.getDependenciesList = function() {\n return /** @type {!Array} */ (jspb.Message.getRepeatedField(this, 7));\n};\n\n\n/**\n * @param {!Array} value\n * @return {!proto.pulumirpc.RegisterResourceRequest} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.setDependenciesList = function(value) {\n return jspb.Message.setField(this, 7, value || []);\n};\n\n\n/**\n * @param {string} value\n * @param {number=} opt_index\n * @return {!proto.pulumirpc.RegisterResourceRequest} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.addDependencies = function(value, opt_index) {\n return jspb.Message.addToRepeatedField(this, 7, value, opt_index);\n};\n\n\n/**\n * Clears the list making it empty but non-null.\n * @return {!proto.pulumirpc.RegisterResourceRequest} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.clearDependenciesList = function() {\n return this.setDependenciesList([]);\n};\n\n\n/**\n * optional string provider = 8;\n * @return {string}\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.getProvider = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 8, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.RegisterResourceRequest} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.setProvider = function(value) {\n return jspb.Message.setProto3StringField(this, 8, value);\n};\n\n\n/**\n * map propertyDependencies = 9;\n * @param {boolean=} opt_noLazyCreate Do not create the map if\n * empty, instead returning `undefined`\n * @return {!jspb.Map}\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.getPropertydependenciesMap = function(opt_noLazyCreate) {\n return /** @type {!jspb.Map} */ (\n jspb.Message.getMapField(this, 9, opt_noLazyCreate,\n proto.pulumirpc.RegisterResourceRequest.PropertyDependencies));\n};\n\n\n/**\n * Clears values from the map. The map will be non-null.\n * @return {!proto.pulumirpc.RegisterResourceRequest} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.clearPropertydependenciesMap = function() {\n this.getPropertydependenciesMap().clear();\n return this;};\n\n\n/**\n * optional bool deleteBeforeReplace = 10;\n * @return {boolean}\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.getDeletebeforereplace = function() {\n return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 10, false));\n};\n\n\n/**\n * @param {boolean} value\n * @return {!proto.pulumirpc.RegisterResourceRequest} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.setDeletebeforereplace = function(value) {\n return jspb.Message.setProto3BooleanField(this, 10, value);\n};\n\n\n/**\n * optional string version = 11;\n * @return {string}\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.getVersion = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 11, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.RegisterResourceRequest} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.setVersion = function(value) {\n return jspb.Message.setProto3StringField(this, 11, value);\n};\n\n\n/**\n * repeated string ignoreChanges = 12;\n * @return {!Array}\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.getIgnorechangesList = function() {\n return /** @type {!Array} */ (jspb.Message.getRepeatedField(this, 12));\n};\n\n\n/**\n * @param {!Array} value\n * @return {!proto.pulumirpc.RegisterResourceRequest} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.setIgnorechangesList = function(value) {\n return jspb.Message.setField(this, 12, value || []);\n};\n\n\n/**\n * @param {string} value\n * @param {number=} opt_index\n * @return {!proto.pulumirpc.RegisterResourceRequest} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.addIgnorechanges = function(value, opt_index) {\n return jspb.Message.addToRepeatedField(this, 12, value, opt_index);\n};\n\n\n/**\n * Clears the list making it empty but non-null.\n * @return {!proto.pulumirpc.RegisterResourceRequest} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.clearIgnorechangesList = function() {\n return this.setIgnorechangesList([]);\n};\n\n\n/**\n * optional bool acceptSecrets = 13;\n * @return {boolean}\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.getAcceptsecrets = function() {\n return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 13, false));\n};\n\n\n/**\n * @param {boolean} value\n * @return {!proto.pulumirpc.RegisterResourceRequest} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.setAcceptsecrets = function(value) {\n return jspb.Message.setProto3BooleanField(this, 13, value);\n};\n\n\n/**\n * repeated string additionalSecretOutputs = 14;\n * @return {!Array}\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.getAdditionalsecretoutputsList = function() {\n return /** @type {!Array} */ (jspb.Message.getRepeatedField(this, 14));\n};\n\n\n/**\n * @param {!Array} value\n * @return {!proto.pulumirpc.RegisterResourceRequest} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.setAdditionalsecretoutputsList = function(value) {\n return jspb.Message.setField(this, 14, value || []);\n};\n\n\n/**\n * @param {string} value\n * @param {number=} opt_index\n * @return {!proto.pulumirpc.RegisterResourceRequest} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.addAdditionalsecretoutputs = function(value, opt_index) {\n return jspb.Message.addToRepeatedField(this, 14, value, opt_index);\n};\n\n\n/**\n * Clears the list making it empty but non-null.\n * @return {!proto.pulumirpc.RegisterResourceRequest} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.clearAdditionalsecretoutputsList = function() {\n return this.setAdditionalsecretoutputsList([]);\n};\n\n\n/**\n * repeated string aliases = 15;\n * @return {!Array}\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.getAliasesList = function() {\n return /** @type {!Array} */ (jspb.Message.getRepeatedField(this, 15));\n};\n\n\n/**\n * @param {!Array} value\n * @return {!proto.pulumirpc.RegisterResourceRequest} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.setAliasesList = function(value) {\n return jspb.Message.setField(this, 15, value || []);\n};\n\n\n/**\n * @param {string} value\n * @param {number=} opt_index\n * @return {!proto.pulumirpc.RegisterResourceRequest} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.addAliases = function(value, opt_index) {\n return jspb.Message.addToRepeatedField(this, 15, value, opt_index);\n};\n\n\n/**\n * Clears the list making it empty but non-null.\n * @return {!proto.pulumirpc.RegisterResourceRequest} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.clearAliasesList = function() {\n return this.setAliasesList([]);\n};\n\n\n/**\n * optional string importId = 16;\n * @return {string}\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.getImportid = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 16, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.RegisterResourceRequest} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.setImportid = function(value) {\n return jspb.Message.setProto3StringField(this, 16, value);\n};\n\n\n/**\n * optional CustomTimeouts customTimeouts = 17;\n * @return {?proto.pulumirpc.RegisterResourceRequest.CustomTimeouts}\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.getCustomtimeouts = function() {\n return /** @type{?proto.pulumirpc.RegisterResourceRequest.CustomTimeouts} */ (\n jspb.Message.getWrapperField(this, proto.pulumirpc.RegisterResourceRequest.CustomTimeouts, 17));\n};\n\n\n/**\n * @param {?proto.pulumirpc.RegisterResourceRequest.CustomTimeouts|undefined} value\n * @return {!proto.pulumirpc.RegisterResourceRequest} returns this\n*/\nproto.pulumirpc.RegisterResourceRequest.prototype.setCustomtimeouts = function(value) {\n return jspb.Message.setWrapperField(this, 17, value);\n};\n\n\n/**\n * Clears the message field making it undefined.\n * @return {!proto.pulumirpc.RegisterResourceRequest} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.clearCustomtimeouts = function() {\n return this.setCustomtimeouts(undefined);\n};\n\n\n/**\n * Returns whether this field is set.\n * @return {boolean}\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.hasCustomtimeouts = function() {\n return jspb.Message.getField(this, 17) != null;\n};\n\n\n/**\n * optional bool deleteBeforeReplaceDefined = 18;\n * @return {boolean}\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.getDeletebeforereplacedefined = function() {\n return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 18, false));\n};\n\n\n/**\n * @param {boolean} value\n * @return {!proto.pulumirpc.RegisterResourceRequest} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.setDeletebeforereplacedefined = function(value) {\n return jspb.Message.setProto3BooleanField(this, 18, value);\n};\n\n\n/**\n * optional bool supportsPartialValues = 19;\n * @return {boolean}\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.getSupportspartialvalues = function() {\n return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 19, false));\n};\n\n\n/**\n * @param {boolean} value\n * @return {!proto.pulumirpc.RegisterResourceRequest} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.setSupportspartialvalues = function(value) {\n return jspb.Message.setProto3BooleanField(this, 19, value);\n};\n\n\n/**\n * optional bool remote = 20;\n * @return {boolean}\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.getRemote = function() {\n return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 20, false));\n};\n\n\n/**\n * @param {boolean} value\n * @return {!proto.pulumirpc.RegisterResourceRequest} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.setRemote = function(value) {\n return jspb.Message.setProto3BooleanField(this, 20, value);\n};\n\n\n/**\n * optional bool acceptResources = 21;\n * @return {boolean}\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.getAcceptresources = function() {\n return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 21, false));\n};\n\n\n/**\n * @param {boolean} value\n * @return {!proto.pulumirpc.RegisterResourceRequest} returns this\n */\nproto.pulumirpc.RegisterResourceRequest.prototype.setAcceptresources = function(value) {\n return jspb.Message.setProto3BooleanField(this, 21, value);\n};\n\n\n\n/**\n * List of repeated fields within this message type.\n * @private {!Array}\n * @const\n */\nproto.pulumirpc.RegisterResourceResponse.repeatedFields_ = [5];\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.RegisterResourceResponse.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.RegisterResourceResponse.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.RegisterResourceResponse} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.RegisterResourceResponse.toObject = function(includeInstance, msg) {\n var f, obj = {\n urn: jspb.Message.getFieldWithDefault(msg, 1, \"\"),\n id: jspb.Message.getFieldWithDefault(msg, 2, \"\"),\n object: (f = msg.getObject()) && google_protobuf_struct_pb.Struct.toObject(includeInstance, f),\n stable: jspb.Message.getBooleanFieldWithDefault(msg, 4, false),\n stablesList: (f = jspb.Message.getRepeatedField(msg, 5)) == null ? undefined : f,\n propertydependenciesMap: (f = msg.getPropertydependenciesMap()) ? f.toObject(includeInstance, proto.pulumirpc.RegisterResourceResponse.PropertyDependencies.toObject) : []\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.RegisterResourceResponse}\n */\nproto.pulumirpc.RegisterResourceResponse.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.RegisterResourceResponse;\n return proto.pulumirpc.RegisterResourceResponse.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.RegisterResourceResponse} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.RegisterResourceResponse}\n */\nproto.pulumirpc.RegisterResourceResponse.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {string} */ (reader.readString());\n msg.setUrn(value);\n break;\n case 2:\n var value = /** @type {string} */ (reader.readString());\n msg.setId(value);\n break;\n case 3:\n var value = new google_protobuf_struct_pb.Struct;\n reader.readMessage(value,google_protobuf_struct_pb.Struct.deserializeBinaryFromReader);\n msg.setObject(value);\n break;\n case 4:\n var value = /** @type {boolean} */ (reader.readBool());\n msg.setStable(value);\n break;\n case 5:\n var value = /** @type {string} */ (reader.readString());\n msg.addStables(value);\n break;\n case 6:\n var value = msg.getPropertydependenciesMap();\n reader.readMessage(value, function(message, reader) {\n jspb.Map.deserializeBinary(message, reader, jspb.BinaryReader.prototype.readString, jspb.BinaryReader.prototype.readMessage, proto.pulumirpc.RegisterResourceResponse.PropertyDependencies.deserializeBinaryFromReader, \"\", new proto.pulumirpc.RegisterResourceResponse.PropertyDependencies());\n });\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.RegisterResourceResponse.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.RegisterResourceResponse.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.RegisterResourceResponse} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.RegisterResourceResponse.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getUrn();\n if (f.length > 0) {\n writer.writeString(\n 1,\n f\n );\n }\n f = message.getId();\n if (f.length > 0) {\n writer.writeString(\n 2,\n f\n );\n }\n f = message.getObject();\n if (f != null) {\n writer.writeMessage(\n 3,\n f,\n google_protobuf_struct_pb.Struct.serializeBinaryToWriter\n );\n }\n f = message.getStable();\n if (f) {\n writer.writeBool(\n 4,\n f\n );\n }\n f = message.getStablesList();\n if (f.length > 0) {\n writer.writeRepeatedString(\n 5,\n f\n );\n }\n f = message.getPropertydependenciesMap(true);\n if (f && f.getLength() > 0) {\n f.serializeBinary(6, writer, jspb.BinaryWriter.prototype.writeString, jspb.BinaryWriter.prototype.writeMessage, proto.pulumirpc.RegisterResourceResponse.PropertyDependencies.serializeBinaryToWriter);\n }\n};\n\n\n\n/**\n * List of repeated fields within this message type.\n * @private {!Array}\n * @const\n */\nproto.pulumirpc.RegisterResourceResponse.PropertyDependencies.repeatedFields_ = [1];\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.RegisterResourceResponse.PropertyDependencies.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.RegisterResourceResponse.PropertyDependencies.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.RegisterResourceResponse.PropertyDependencies} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.RegisterResourceResponse.PropertyDependencies.toObject = function(includeInstance, msg) {\n var f, obj = {\n urnsList: (f = jspb.Message.getRepeatedField(msg, 1)) == null ? undefined : f\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.RegisterResourceResponse.PropertyDependencies}\n */\nproto.pulumirpc.RegisterResourceResponse.PropertyDependencies.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.RegisterResourceResponse.PropertyDependencies;\n return proto.pulumirpc.RegisterResourceResponse.PropertyDependencies.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.RegisterResourceResponse.PropertyDependencies} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.RegisterResourceResponse.PropertyDependencies}\n */\nproto.pulumirpc.RegisterResourceResponse.PropertyDependencies.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {string} */ (reader.readString());\n msg.addUrns(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.RegisterResourceResponse.PropertyDependencies.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.RegisterResourceResponse.PropertyDependencies.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.RegisterResourceResponse.PropertyDependencies} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.RegisterResourceResponse.PropertyDependencies.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getUrnsList();\n if (f.length > 0) {\n writer.writeRepeatedString(\n 1,\n f\n );\n }\n};\n\n\n/**\n * repeated string urns = 1;\n * @return {!Array}\n */\nproto.pulumirpc.RegisterResourceResponse.PropertyDependencies.prototype.getUrnsList = function() {\n return /** @type {!Array} */ (jspb.Message.getRepeatedField(this, 1));\n};\n\n\n/**\n * @param {!Array} value\n * @return {!proto.pulumirpc.RegisterResourceResponse.PropertyDependencies} returns this\n */\nproto.pulumirpc.RegisterResourceResponse.PropertyDependencies.prototype.setUrnsList = function(value) {\n return jspb.Message.setField(this, 1, value || []);\n};\n\n\n/**\n * @param {string} value\n * @param {number=} opt_index\n * @return {!proto.pulumirpc.RegisterResourceResponse.PropertyDependencies} returns this\n */\nproto.pulumirpc.RegisterResourceResponse.PropertyDependencies.prototype.addUrns = function(value, opt_index) {\n return jspb.Message.addToRepeatedField(this, 1, value, opt_index);\n};\n\n\n/**\n * Clears the list making it empty but non-null.\n * @return {!proto.pulumirpc.RegisterResourceResponse.PropertyDependencies} returns this\n */\nproto.pulumirpc.RegisterResourceResponse.PropertyDependencies.prototype.clearUrnsList = function() {\n return this.setUrnsList([]);\n};\n\n\n/**\n * optional string urn = 1;\n * @return {string}\n */\nproto.pulumirpc.RegisterResourceResponse.prototype.getUrn = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.RegisterResourceResponse} returns this\n */\nproto.pulumirpc.RegisterResourceResponse.prototype.setUrn = function(value) {\n return jspb.Message.setProto3StringField(this, 1, value);\n};\n\n\n/**\n * optional string id = 2;\n * @return {string}\n */\nproto.pulumirpc.RegisterResourceResponse.prototype.getId = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.RegisterResourceResponse} returns this\n */\nproto.pulumirpc.RegisterResourceResponse.prototype.setId = function(value) {\n return jspb.Message.setProto3StringField(this, 2, value);\n};\n\n\n/**\n * optional google.protobuf.Struct object = 3;\n * @return {?proto.google.protobuf.Struct}\n */\nproto.pulumirpc.RegisterResourceResponse.prototype.getObject = function() {\n return /** @type{?proto.google.protobuf.Struct} */ (\n jspb.Message.getWrapperField(this, google_protobuf_struct_pb.Struct, 3));\n};\n\n\n/**\n * @param {?proto.google.protobuf.Struct|undefined} value\n * @return {!proto.pulumirpc.RegisterResourceResponse} returns this\n*/\nproto.pulumirpc.RegisterResourceResponse.prototype.setObject = function(value) {\n return jspb.Message.setWrapperField(this, 3, value);\n};\n\n\n/**\n * Clears the message field making it undefined.\n * @return {!proto.pulumirpc.RegisterResourceResponse} returns this\n */\nproto.pulumirpc.RegisterResourceResponse.prototype.clearObject = function() {\n return this.setObject(undefined);\n};\n\n\n/**\n * Returns whether this field is set.\n * @return {boolean}\n */\nproto.pulumirpc.RegisterResourceResponse.prototype.hasObject = function() {\n return jspb.Message.getField(this, 3) != null;\n};\n\n\n/**\n * optional bool stable = 4;\n * @return {boolean}\n */\nproto.pulumirpc.RegisterResourceResponse.prototype.getStable = function() {\n return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 4, false));\n};\n\n\n/**\n * @param {boolean} value\n * @return {!proto.pulumirpc.RegisterResourceResponse} returns this\n */\nproto.pulumirpc.RegisterResourceResponse.prototype.setStable = function(value) {\n return jspb.Message.setProto3BooleanField(this, 4, value);\n};\n\n\n/**\n * repeated string stables = 5;\n * @return {!Array}\n */\nproto.pulumirpc.RegisterResourceResponse.prototype.getStablesList = function() {\n return /** @type {!Array} */ (jspb.Message.getRepeatedField(this, 5));\n};\n\n\n/**\n * @param {!Array} value\n * @return {!proto.pulumirpc.RegisterResourceResponse} returns this\n */\nproto.pulumirpc.RegisterResourceResponse.prototype.setStablesList = function(value) {\n return jspb.Message.setField(this, 5, value || []);\n};\n\n\n/**\n * @param {string} value\n * @param {number=} opt_index\n * @return {!proto.pulumirpc.RegisterResourceResponse} returns this\n */\nproto.pulumirpc.RegisterResourceResponse.prototype.addStables = function(value, opt_index) {\n return jspb.Message.addToRepeatedField(this, 5, value, opt_index);\n};\n\n\n/**\n * Clears the list making it empty but non-null.\n * @return {!proto.pulumirpc.RegisterResourceResponse} returns this\n */\nproto.pulumirpc.RegisterResourceResponse.prototype.clearStablesList = function() {\n return this.setStablesList([]);\n};\n\n\n/**\n * map propertyDependencies = 6;\n * @param {boolean=} opt_noLazyCreate Do not create the map if\n * empty, instead returning `undefined`\n * @return {!jspb.Map}\n */\nproto.pulumirpc.RegisterResourceResponse.prototype.getPropertydependenciesMap = function(opt_noLazyCreate) {\n return /** @type {!jspb.Map} */ (\n jspb.Message.getMapField(this, 6, opt_noLazyCreate,\n proto.pulumirpc.RegisterResourceResponse.PropertyDependencies));\n};\n\n\n/**\n * Clears values from the map. The map will be non-null.\n * @return {!proto.pulumirpc.RegisterResourceResponse} returns this\n */\nproto.pulumirpc.RegisterResourceResponse.prototype.clearPropertydependenciesMap = function() {\n this.getPropertydependenciesMap().clear();\n return this;};\n\n\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.pulumirpc.RegisterResourceOutputsRequest.prototype.toObject = function(opt_includeInstance) {\n return proto.pulumirpc.RegisterResourceOutputsRequest.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.pulumirpc.RegisterResourceOutputsRequest} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.RegisterResourceOutputsRequest.toObject = function(includeInstance, msg) {\n var f, obj = {\n urn: jspb.Message.getFieldWithDefault(msg, 1, \"\"),\n outputs: (f = msg.getOutputs()) && google_protobuf_struct_pb.Struct.toObject(includeInstance, f)\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.pulumirpc.RegisterResourceOutputsRequest}\n */\nproto.pulumirpc.RegisterResourceOutputsRequest.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.pulumirpc.RegisterResourceOutputsRequest;\n return proto.pulumirpc.RegisterResourceOutputsRequest.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.pulumirpc.RegisterResourceOutputsRequest} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.pulumirpc.RegisterResourceOutputsRequest}\n */\nproto.pulumirpc.RegisterResourceOutputsRequest.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {string} */ (reader.readString());\n msg.setUrn(value);\n break;\n case 2:\n var value = new google_protobuf_struct_pb.Struct;\n reader.readMessage(value,google_protobuf_struct_pb.Struct.deserializeBinaryFromReader);\n msg.setOutputs(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.pulumirpc.RegisterResourceOutputsRequest.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.pulumirpc.RegisterResourceOutputsRequest.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.pulumirpc.RegisterResourceOutputsRequest} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.pulumirpc.RegisterResourceOutputsRequest.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getUrn();\n if (f.length > 0) {\n writer.writeString(\n 1,\n f\n );\n }\n f = message.getOutputs();\n if (f != null) {\n writer.writeMessage(\n 2,\n f,\n google_protobuf_struct_pb.Struct.serializeBinaryToWriter\n );\n }\n};\n\n\n/**\n * optional string urn = 1;\n * @return {string}\n */\nproto.pulumirpc.RegisterResourceOutputsRequest.prototype.getUrn = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.pulumirpc.RegisterResourceOutputsRequest} returns this\n */\nproto.pulumirpc.RegisterResourceOutputsRequest.prototype.setUrn = function(value) {\n return jspb.Message.setProto3StringField(this, 1, value);\n};\n\n\n/**\n * optional google.protobuf.Struct outputs = 2;\n * @return {?proto.google.protobuf.Struct}\n */\nproto.pulumirpc.RegisterResourceOutputsRequest.prototype.getOutputs = function() {\n return /** @type{?proto.google.protobuf.Struct} */ (\n jspb.Message.getWrapperField(this, google_protobuf_struct_pb.Struct, 2));\n};\n\n\n/**\n * @param {?proto.google.protobuf.Struct|undefined} value\n * @return {!proto.pulumirpc.RegisterResourceOutputsRequest} returns this\n*/\nproto.pulumirpc.RegisterResourceOutputsRequest.prototype.setOutputs = function(value) {\n return jspb.Message.setWrapperField(this, 2, value);\n};\n\n\n/**\n * Clears the message field making it undefined.\n * @return {!proto.pulumirpc.RegisterResourceOutputsRequest} returns this\n */\nproto.pulumirpc.RegisterResourceOutputsRequest.prototype.clearOutputs = function() {\n return this.setOutputs(undefined);\n};\n\n\n/**\n * Returns whether this field is set.\n * @return {boolean}\n */\nproto.pulumirpc.RegisterResourceOutputsRequest.prototype.hasOutputs = function() {\n return jspb.Message.getField(this, 2) != null;\n};\n\n\ngoog.object.extend(exports, proto.pulumirpc);\n","// source: status.proto\n/**\n * @fileoverview\n * @enhanceable\n * @suppress {messageConventions} JS Compiler reports an error if a variable or\n * field starts with 'MSG_' and isn't a translatable message.\n * @public\n */\n// GENERATED CODE -- DO NOT EDIT!\n\nvar jspb = require('google-protobuf');\nvar goog = jspb;\nvar global = Function('return this')();\n\nvar google_protobuf_any_pb = require('google-protobuf/google/protobuf/any_pb.js');\ngoog.object.extend(proto, google_protobuf_any_pb);\ngoog.exportSymbol('proto.google.rpc.Status', null, global);\n/**\n * Generated by JsPbCodeGenerator.\n * @param {Array=} opt_data Optional initial data array, typically from a\n * server response, or constructed directly in Javascript. The array is used\n * in place and becomes part of the constructed object. It is not cloned.\n * If no data is provided, the constructed object will be empty, but still\n * valid.\n * @extends {jspb.Message}\n * @constructor\n */\nproto.google.rpc.Status = function(opt_data) {\n jspb.Message.initialize(this, opt_data, 0, -1, proto.google.rpc.Status.repeatedFields_, null);\n};\ngoog.inherits(proto.google.rpc.Status, jspb.Message);\nif (goog.DEBUG && !COMPILED) {\n /**\n * @public\n * @override\n */\n proto.google.rpc.Status.displayName = 'proto.google.rpc.Status';\n}\n\n/**\n * List of repeated fields within this message type.\n * @private {!Array}\n * @const\n */\nproto.google.rpc.Status.repeatedFields_ = [3];\n\n\n\nif (jspb.Message.GENERATE_TO_OBJECT) {\n/**\n * Creates an object representation of this proto.\n * Field names that are reserved in JavaScript and will be renamed to pb_name.\n * Optional fields that are not set will be set to undefined.\n * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n * For the list of reserved names please see:\n * net/proto2/compiler/js/internal/generator.cc#kKeyword.\n * @param {boolean=} opt_includeInstance Deprecated. whether to include the\n * JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @return {!Object}\n */\nproto.google.rpc.Status.prototype.toObject = function(opt_includeInstance) {\n return proto.google.rpc.Status.toObject(opt_includeInstance, this);\n};\n\n\n/**\n * Static version of the {@see toObject} method.\n * @param {boolean|undefined} includeInstance Deprecated. Whether to include\n * the JSPB instance for transitional soy proto support:\n * http://goto/soy-param-migration\n * @param {!proto.google.rpc.Status} msg The msg instance to transform.\n * @return {!Object}\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.google.rpc.Status.toObject = function(includeInstance, msg) {\n var f, obj = {\n code: jspb.Message.getFieldWithDefault(msg, 1, 0),\n message: jspb.Message.getFieldWithDefault(msg, 2, \"\"),\n detailsList: jspb.Message.toObjectList(msg.getDetailsList(),\n google_protobuf_any_pb.Any.toObject, includeInstance)\n };\n\n if (includeInstance) {\n obj.$jspbMessageInstance = msg;\n }\n return obj;\n};\n}\n\n\n/**\n * Deserializes binary data (in protobuf wire format).\n * @param {jspb.ByteSource} bytes The bytes to deserialize.\n * @return {!proto.google.rpc.Status}\n */\nproto.google.rpc.Status.deserializeBinary = function(bytes) {\n var reader = new jspb.BinaryReader(bytes);\n var msg = new proto.google.rpc.Status;\n return proto.google.rpc.Status.deserializeBinaryFromReader(msg, reader);\n};\n\n\n/**\n * Deserializes binary data (in protobuf wire format) from the\n * given reader into the given message object.\n * @param {!proto.google.rpc.Status} msg The message object to deserialize into.\n * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n * @return {!proto.google.rpc.Status}\n */\nproto.google.rpc.Status.deserializeBinaryFromReader = function(msg, reader) {\n while (reader.nextField()) {\n if (reader.isEndGroup()) {\n break;\n }\n var field = reader.getFieldNumber();\n switch (field) {\n case 1:\n var value = /** @type {number} */ (reader.readInt32());\n msg.setCode(value);\n break;\n case 2:\n var value = /** @type {string} */ (reader.readString());\n msg.setMessage(value);\n break;\n case 3:\n var value = new google_protobuf_any_pb.Any;\n reader.readMessage(value,google_protobuf_any_pb.Any.deserializeBinaryFromReader);\n msg.addDetails(value);\n break;\n default:\n reader.skipField();\n break;\n }\n }\n return msg;\n};\n\n\n/**\n * Serializes the message to binary data (in protobuf wire format).\n * @return {!Uint8Array}\n */\nproto.google.rpc.Status.prototype.serializeBinary = function() {\n var writer = new jspb.BinaryWriter();\n proto.google.rpc.Status.serializeBinaryToWriter(this, writer);\n return writer.getResultBuffer();\n};\n\n\n/**\n * Serializes the given message to binary data (in protobuf wire\n * format), writing to the given BinaryWriter.\n * @param {!proto.google.rpc.Status} message\n * @param {!jspb.BinaryWriter} writer\n * @suppress {unusedLocalVariables} f is only used for nested messages\n */\nproto.google.rpc.Status.serializeBinaryToWriter = function(message, writer) {\n var f = undefined;\n f = message.getCode();\n if (f !== 0) {\n writer.writeInt32(\n 1,\n f\n );\n }\n f = message.getMessage();\n if (f.length > 0) {\n writer.writeString(\n 2,\n f\n );\n }\n f = message.getDetailsList();\n if (f.length > 0) {\n writer.writeRepeatedMessage(\n 3,\n f,\n google_protobuf_any_pb.Any.serializeBinaryToWriter\n );\n }\n};\n\n\n/**\n * optional int32 code = 1;\n * @return {number}\n */\nproto.google.rpc.Status.prototype.getCode = function() {\n return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 1, 0));\n};\n\n\n/**\n * @param {number} value\n * @return {!proto.google.rpc.Status} returns this\n */\nproto.google.rpc.Status.prototype.setCode = function(value) {\n return jspb.Message.setProto3IntField(this, 1, value);\n};\n\n\n/**\n * optional string message = 2;\n * @return {string}\n */\nproto.google.rpc.Status.prototype.getMessage = function() {\n return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, \"\"));\n};\n\n\n/**\n * @param {string} value\n * @return {!proto.google.rpc.Status} returns this\n */\nproto.google.rpc.Status.prototype.setMessage = function(value) {\n return jspb.Message.setProto3StringField(this, 2, value);\n};\n\n\n/**\n * repeated google.protobuf.Any details = 3;\n * @return {!Array}\n */\nproto.google.rpc.Status.prototype.getDetailsList = function() {\n return /** @type{!Array} */ (\n jspb.Message.getRepeatedWrapperField(this, google_protobuf_any_pb.Any, 3));\n};\n\n\n/**\n * @param {!Array} value\n * @return {!proto.google.rpc.Status} returns this\n*/\nproto.google.rpc.Status.prototype.setDetailsList = function(value) {\n return jspb.Message.setRepeatedWrapperField(this, 3, value);\n};\n\n\n/**\n * @param {!proto.google.protobuf.Any=} opt_value\n * @param {number=} opt_index\n * @return {!proto.google.protobuf.Any}\n */\nproto.google.rpc.Status.prototype.addDetails = function(opt_value, opt_index) {\n return jspb.Message.addToRepeatedWrapperField(this, 3, opt_value, proto.google.protobuf.Any, opt_index);\n};\n\n\n/**\n * Clears the list making it empty but non-null.\n * @return {!proto.google.rpc.Status} returns this\n */\nproto.google.rpc.Status.prototype.clearDetailsList = function() {\n return this.setDetailsList([]);\n};\n\n\ngoog.object.extend(exports, proto.google.rpc);\n","\"use strict\";\n// Copyright 2016-2020, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__export(require(\"./server\"));\n","\"use strict\";\n// Copyright 2016-2020, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst grpc = require(\"@grpc/grpc-js\");\nconst log = require(\"../log\");\nconst output_1 = require(\"../output\");\nconst resource = require(\"../resource\");\nconst runtime = require(\"../runtime\");\nconst requireFromString = require(\"require-from-string\");\nconst anyproto = require(\"google-protobuf/google/protobuf/any_pb.js\");\nconst emptyproto = require(\"google-protobuf/google/protobuf/empty_pb.js\");\nconst structproto = require(\"google-protobuf/google/protobuf/struct_pb.js\");\nconst provproto = require(\"../proto/provider_pb.js\");\nconst provrpc = require(\"../proto/provider_grpc_pb.js\");\nconst plugproto = require(\"../proto/plugin_pb.js\");\nconst statusproto = require(\"../proto/status_pb.js\");\nclass Server {\n constructor(engineAddr, provider) {\n this.engineAddr = engineAddr;\n this.provider = provider;\n }\n // Misc. methods\n cancel(call, callback) {\n callback(undefined, new emptyproto.Empty());\n }\n getPluginInfo(call, callback) {\n const resp = new plugproto.PluginInfo();\n resp.setVersion(this.provider.version);\n callback(undefined, resp);\n }\n getSchema(call, callback) {\n callback({\n code: grpc.status.UNIMPLEMENTED,\n details: \"Not yet implemented: GetSchema\",\n }, undefined);\n }\n // Config methods\n checkConfig(call, callback) {\n callback({\n code: grpc.status.UNIMPLEMENTED,\n details: \"Not yet implemented: CheckConfig\",\n }, undefined);\n }\n diffConfig(call, callback) {\n callback({\n code: grpc.status.UNIMPLEMENTED,\n details: \"Not yet implemented: DiffConfig\",\n }, undefined);\n }\n configure(call, callback) {\n const resp = new provproto.ConfigureResponse();\n resp.setAcceptsecrets(true);\n resp.setAcceptresources(true);\n callback(undefined, resp);\n }\n // CRUD resource methods\n check(call, callback) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n const req = call.request;\n const resp = new provproto.CheckResponse();\n const olds = req.getOlds().toJavaScript();\n const news = req.getNews().toJavaScript();\n let inputs = news;\n let failures = [];\n if (this.provider.check) {\n const result = yield this.provider.check(req.getUrn(), olds, news);\n if (result.inputs) {\n inputs = result.inputs;\n }\n if (result.failures) {\n failures = result.failures;\n }\n }\n else {\n // If no check method was provided, propagate the new inputs as-is.\n inputs = news;\n }\n resp.setInputs(structproto.Struct.fromJavaScript(inputs));\n if (failures.length !== 0) {\n const failureList = [];\n for (const f of failures) {\n const failure = new provproto.CheckFailure();\n failure.setProperty(f.property);\n failure.setReason(f.reason);\n failureList.push(failure);\n }\n resp.setFailuresList(failureList);\n }\n callback(undefined, resp);\n }\n catch (e) {\n console.error(`${e}: ${e.stack}`);\n callback(e, undefined);\n }\n });\n }\n diff(call, callback) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n const req = call.request;\n const resp = new provproto.DiffResponse();\n const olds = req.getOlds().toJavaScript();\n const news = req.getNews().toJavaScript();\n if (this.provider.diff) {\n const result = yield this.provider.diff(req.getId(), req.getUrn(), olds, news);\n if (result.changes === true) {\n resp.setChanges(provproto.DiffResponse.DiffChanges.DIFF_SOME);\n }\n else if (result.changes === false) {\n resp.setChanges(provproto.DiffResponse.DiffChanges.DIFF_NONE);\n }\n else {\n resp.setChanges(provproto.DiffResponse.DiffChanges.DIFF_UNKNOWN);\n }\n if (result.replaces && result.replaces.length !== 0) {\n resp.setReplacesList(result.replaces);\n }\n if (result.deleteBeforeReplace) {\n resp.setDeletebeforereplace(result.deleteBeforeReplace);\n }\n }\n callback(undefined, resp);\n }\n catch (e) {\n console.error(`${e}: ${e.stack}`);\n callback(e, undefined);\n }\n });\n }\n create(call, callback) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n const req = call.request;\n if (!this.provider.create) {\n callback(new Error(`unknown resource type ${req.getUrn()}`), undefined);\n return;\n }\n const resp = new provproto.CreateResponse();\n const props = req.getProperties().toJavaScript();\n const result = yield this.provider.create(req.getUrn(), props);\n resp.setId(result.id);\n resp.setProperties(structproto.Struct.fromJavaScript(result.outs));\n callback(undefined, resp);\n }\n catch (e) {\n const response = grpcResponseFromError(e);\n return callback(/*err:*/ response, /*value:*/ null, /*metadata:*/ response.metadata);\n }\n });\n }\n read(call, callback) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n const req = call.request;\n const resp = new provproto.ReadResponse();\n const id = req.getId();\n const props = req.getProperties().toJavaScript();\n if (this.provider.read) {\n const result = yield this.provider.read(id, req.getUrn(), props);\n resp.setId(result.id);\n resp.setProperties(structproto.Struct.fromJavaScript(result.props));\n }\n else {\n // In the event of a missing read, simply return back the input state.\n resp.setId(id);\n resp.setProperties(req.getProperties());\n }\n callback(undefined, resp);\n }\n catch (e) {\n console.error(`${e}: ${e.stack}`);\n callback(e, undefined);\n }\n });\n }\n update(call, callback) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n const req = call.request;\n const resp = new provproto.UpdateResponse();\n const olds = req.getOlds().toJavaScript();\n const news = req.getNews().toJavaScript();\n let result = {};\n if (this.provider.update) {\n result = (yield this.provider.update(req.getId(), req.getUrn(), olds, news)) || {};\n }\n resp.setProperties(structproto.Struct.fromJavaScript(result.outs));\n callback(undefined, resp);\n }\n catch (e) {\n const response = grpcResponseFromError(e);\n return callback(/*err:*/ response, /*value:*/ null, /*metadata:*/ response.metadata);\n }\n });\n }\n delete(call, callback) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n const req = call.request;\n const props = req.getProperties().toJavaScript();\n if (this.provider.delete) {\n yield this.provider.delete(req.getId(), req.getUrn(), props);\n }\n callback(undefined, new emptyproto.Empty());\n }\n catch (e) {\n console.error(`${e}: ${e.stack}`);\n callback(e, undefined);\n }\n });\n }\n construct(call, callback) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n const req = call.request;\n const type = req.getType();\n const name = req.getName();\n if (!this.provider.construct) {\n callback(new Error(`unknown resource type ${type}`), undefined);\n return;\n }\n // Configure the runtime.\n //\n // NOTE: these are globals! We should ensure that all settings are identical between calls, and eventually\n // refactor so we can avoid the global state.\n runtime.resetOptions(req.getProject(), req.getStack(), req.getParallel(), this.engineAddr, req.getMonitorendpoint(), req.getDryrun());\n const pulumiConfig = {};\n const rpcConfig = req.getConfigMap();\n if (rpcConfig) {\n for (const [k, v] of rpcConfig.entries()) {\n pulumiConfig[k] = v;\n }\n }\n runtime.setAllConfig(pulumiConfig);\n // Deserialize the inputs and apply appropriate dependencies.\n const inputs = {};\n const inputDependencies = req.getInputdependenciesMap();\n const deserializedInputs = runtime.deserializeProperties(req.getInputs());\n for (const k of Object.keys(deserializedInputs)) {\n const inputDeps = inputDependencies.get(k);\n const deps = (inputDeps ? inputDeps.getUrnsList() : [])\n .map(depUrn => new resource.DependencyResource(depUrn));\n const input = deserializedInputs[k];\n inputs[k] = new output_1.Output(deps, Promise.resolve(runtime.unwrapRpcSecret(input)), Promise.resolve(true), Promise.resolve(runtime.isRpcSecret(input)), Promise.resolve([]));\n }\n // Rebuild the resource options.\n const dependsOn = [];\n for (const urn of req.getDependenciesList()) {\n dependsOn.push(new resource.DependencyResource(urn));\n }\n const providers = {};\n const rpcProviders = req.getProvidersMap();\n if (rpcProviders) {\n for (const [pkg, ref] of rpcProviders.entries()) {\n providers[pkg] = new resource.DependencyProviderResource(ref);\n }\n }\n const opts = {\n aliases: req.getAliasesList(),\n dependsOn: dependsOn,\n protect: req.getProtect(),\n providers: providers,\n parent: req.getParent() ? new resource.DependencyResource(req.getParent()) : undefined,\n };\n const result = yield this.provider.construct(name, type, inputs, opts);\n const resp = new provproto.ConstructResponse();\n resp.setUrn(yield output_1.output(result.urn).promise());\n const [state, stateDependencies] = yield runtime.serializeResourceProperties(`construct(${type}, ${name})`, result.state);\n const stateDependenciesMap = resp.getStatedependenciesMap();\n for (const [key, resources] of stateDependencies) {\n const deps = new provproto.ConstructResponse.PropertyDependencies();\n deps.setUrnsList(yield Promise.all(Array.from(resources).map(r => r.urn.promise())));\n stateDependenciesMap.set(key, deps);\n }\n resp.setState(structproto.Struct.fromJavaScript(state));\n callback(undefined, resp);\n }\n catch (e) {\n console.error(`${e}: ${e.stack}`);\n callback(e, undefined);\n }\n });\n }\n invoke(call, callback) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n const req = call.request;\n if (!this.provider.invoke) {\n callback(new Error(`unknown function ${req.getTok()}`), undefined);\n return;\n }\n const args = req.getArgs().toJavaScript();\n const result = yield this.provider.invoke(req.getTok(), args);\n const resp = new provproto.InvokeResponse();\n resp.setProperties(structproto.Struct.fromJavaScript(result.outputs));\n if ((result.failures || []).length !== 0) {\n const failureList = [];\n for (const f of result.failures) {\n const failure = new provproto.CheckFailure();\n failure.setProperty(f.property);\n failure.setReason(f.reason);\n failureList.push(failure);\n }\n resp.setFailuresList(failureList);\n }\n callback(undefined, resp);\n }\n catch (e) {\n console.error(`${e}: ${e.stack}`);\n callback(e, undefined);\n }\n });\n }\n streamInvoke(call, callback) {\n return __awaiter(this, void 0, void 0, function* () {\n callback({\n code: grpc.status.UNIMPLEMENTED,\n details: \"Not yet implemented: StreamInvoke\",\n }, undefined);\n });\n }\n}\n// grpcResponseFromError creates a gRPC response representing an error from a dynamic provider's\n// resource. This is typically either a creation error, in which the API server has (virtually)\n// rejected the resource, or an initialization error, where the API server has accepted the\n// resource, but it failed to initialize (e.g., the app code is continually crashing and the\n// resource has failed to become alive).\nfunction grpcResponseFromError(e) {\n // Create response object.\n const resp = new statusproto.Status();\n resp.setCode(grpc.status.UNKNOWN);\n resp.setMessage(e.message);\n const metadata = new grpc.Metadata();\n if (e.id) {\n // Object created successfully, but failed to initialize. Pack initialization failure into\n // details.\n const detail = new provproto.ErrorResourceInitFailed();\n detail.setId(e.id);\n detail.setProperties(structproto.Struct.fromJavaScript(e.properties || {}));\n detail.setReasonsList(e.reasons || []);\n const details = new anyproto.Any();\n details.pack(detail.serializeBinary(), \"pulumirpc.ErrorResourceInitFailed\");\n // Add details to metadata.\n resp.addDetails(details);\n // NOTE: `grpc-status-details-bin` is a magic field that allows us to send structured\n // protobuf data as an error back through gRPC. This notion of details is a first-class in\n // the Go gRPC implementation, and the nodejs implementation has not quite caught up to it,\n // which is why it's cumbersome here.\n metadata.add(\"grpc-status-details-bin\", Buffer.from(resp.serializeBinary()));\n }\n return {\n code: grpc.status.UNKNOWN,\n message: e.message,\n metadata: metadata,\n };\n}\nfunction main(provider, args) {\n return __awaiter(this, void 0, void 0, function* () {\n // We track all uncaught errors here. If we have any, we will make sure we always have a non-0 exit\n // code.\n const uncaughtErrors = new Set();\n const uncaughtHandler = (err) => {\n if (!uncaughtErrors.has(err)) {\n uncaughtErrors.add(err);\n // Use `pulumi.log.error` here to tell the engine there was a fatal error, which should\n // stop processing subsequent resource operations.\n log.error(err.stack || err.message || (\"\" + err));\n }\n };\n process.on(\"uncaughtException\", uncaughtHandler);\n // @ts-ignore 'unhandledRejection' will almost always invoke uncaughtHandler with an Error. so just\n // suppress the TS strictness here.\n process.on(\"unhandledRejection\", uncaughtHandler);\n process.on(\"exit\", (code) => {\n // If there were any uncaught errors at all, we always want to exit with an error code.\n if (code === 0 && uncaughtErrors.size > 0) {\n process.exitCode = 1;\n }\n });\n // The program requires a single argument: the address of the RPC endpoint for the engine. It\n // optionally also takes a second argument, a reference back to the engine, but this may be missing.\n if (args.length === 0) {\n console.error(\"fatal: Missing address\");\n process.exit(-1);\n return;\n }\n const engineAddr = args[0];\n // Finally connect up the gRPC client/server and listen for incoming requests.\n const server = new grpc.Server({\n \"grpc.max_receive_message_length\": runtime.maxRPCMessageSize,\n });\n server.addService(provrpc.ResourceProviderService, new Server(engineAddr, provider));\n const port = yield new Promise((resolve, reject) => {\n server.bindAsync(`0.0.0.0:0`, grpc.ServerCredentials.createInsecure(), (err, p) => {\n if (err) {\n reject(err);\n }\n else {\n resolve(p);\n }\n });\n });\n server.start();\n // Emit the address so the monitor can read it to connect. The gRPC server will keep the message loop alive.\n console.log(port);\n });\n}\nexports.main = main;\n","\"use strict\";\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst errors_1 = require(\"./errors\");\nconst output_1 = require(\"./output\");\nconst runtime_1 = require(\"./runtime\");\nconst resource_1 = require(\"./runtime/resource\");\nconst settings_1 = require(\"./runtime/settings\");\nconst utils = require(\"./utils\");\n/**\n * createUrn computes a URN from the combination of a resource name, resource type, optional parent,\n * optional project and optional stack.\n */\nfunction createUrn(name, type, parent, project, stack) {\n let parentPrefix;\n if (parent) {\n let parentUrn;\n if (Resource.isInstance(parent)) {\n parentUrn = parent.urn;\n }\n else {\n parentUrn = output_1.output(parent);\n }\n parentPrefix = parentUrn.apply(parentUrnString => parentUrnString.substring(0, parentUrnString.lastIndexOf(\"::\")) + \"$\");\n }\n else {\n parentPrefix = output_1.output(`urn:pulumi:${stack || settings_1.getStack()}::${project || settings_1.getProject()}::`);\n }\n return output_1.interpolate `${parentPrefix}${type}::${name}`;\n}\nexports.createUrn = createUrn;\n// inheritedChildAlias computes the alias that should be applied to a child based on an alias applied to it's parent.\n// This may involve changing the name of the resource in cases where the resource has a named derived from the name of\n// the parent, and the parent name changed.\nfunction inheritedChildAlias(childName, parentName, parentAlias, childType) {\n // If the child name has the parent name as a prefix, then we make the assumption that it was\n // constructed from the convention of using `{name}-details` as the name of the child resource. To\n // ensure this is aliased correctly, we must then also replace the parent aliases name in the prefix of\n // the child resource name.\n //\n // For example:\n // * name: \"newapp-function\"\n // * opts.parent.__name: \"newapp\"\n // * parentAlias: \"urn:pulumi:stackname::projectname::awsx:ec2:Vpc::app\"\n // * parentAliasName: \"app\"\n // * aliasName: \"app-function\"\n // * childAlias: \"urn:pulumi:stackname::projectname::aws:s3/bucket:Bucket::app-function\"\n let aliasName = output_1.output(childName);\n if (childName.startsWith(parentName)) {\n aliasName = output_1.output(parentAlias).apply(parentAliasUrn => {\n const parentAliasName = parentAliasUrn.substring(parentAliasUrn.lastIndexOf(\"::\") + 2);\n return parentAliasName + childName.substring(parentName.length);\n });\n }\n return createUrn(aliasName, childType, parentAlias);\n}\n/**\n * Resource represents a class whose CRUD operations are implemented by a provider plugin.\n */\nclass Resource {\n /**\n * Creates and registers a new resource object. [t] is the fully qualified type token and\n * [name] is the \"name\" part to use in creating a stable and globally unique URN for the object.\n * dependsOn is an optional list of other resources that this resource depends on, controlling\n * the order in which we perform resource operations.\n *\n * @param t The type of the resource.\n * @param name The _unique_ name of the resource.\n * @param custom True to indicate that this is a custom resource, managed by a plugin.\n * @param props The arguments to use to populate the new resource.\n * @param opts A bag of options that control this resource's behavior.\n * @param remote True if this is a remote component resource.\n * @param dependency True if this is a synthetic resource used internally for dependency tracking.\n */\n constructor(t, name, custom, props = {}, opts = {}, remote = false, dependency = false) {\n /**\n * A private field to help with RTTI that works in SxS scenarios.\n * @internal\n */\n // tslint:disable-next-line:variable-name\n this.__pulumiResource = true;\n if (dependency) {\n this.__protect = false;\n this.__providers = {};\n return;\n }\n if (opts.parent && !Resource.isInstance(opts.parent)) {\n throw new Error(`Resource parent is not a valid Resource: ${opts.parent}`);\n }\n if (!t) {\n throw new errors_1.ResourceError(\"Missing resource type argument\", opts.parent);\n }\n if (!name) {\n throw new errors_1.ResourceError(\"Missing resource name argument (for URN creation)\", opts.parent);\n }\n // Before anything else - if there are transformations registered, invoke them in order to transform the properties and\n // options assigned to this resource.\n const parent = opts.parent || runtime_1.getStackResource() || { __transformations: undefined };\n this.__transformations = [...(opts.transformations || []), ...(parent.__transformations || [])];\n for (const transformation of this.__transformations) {\n const tres = transformation({ resource: this, type: t, name, props, opts });\n if (tres) {\n if (tres.opts.parent !== opts.parent) {\n // This is currently not allowed because the parent tree is needed to establish what\n // transformation to apply in the first place, and to compute inheritance of other\n // resource options in the Resource constructor before transformations are run (so\n // modifying it here would only even partially take affect). It's theoretically\n // possible this restriction could be lifted in the future, but for now just\n // disallow re-parenting resources in transformations to be safe.\n throw new Error(\"Transformations cannot currently be used to change the `parent` of a resource.\");\n }\n props = tres.props;\n opts = tres.opts;\n }\n }\n this.__name = name;\n // Make a shallow clone of opts to ensure we don't modify the value passed in.\n opts = Object.assign({}, opts);\n if (opts.provider && opts.providers) {\n throw new errors_1.ResourceError(\"Do not supply both 'provider' and 'providers' options to a ComponentResource.\", opts.parent);\n }\n // Check the parent type if one exists and fill in any default options.\n this.__providers = {};\n if (opts.parent) {\n this.__parentResource = opts.parent;\n this.__parentResource.__childResources = this.__parentResource.__childResources || new Set();\n this.__parentResource.__childResources.add(this);\n if (opts.protect === undefined) {\n opts.protect = opts.parent.__protect;\n }\n // Make a copy of the aliases array, and add to it any implicit aliases inherited from its parent\n opts.aliases = [...(opts.aliases || [])];\n if (opts.parent.__name) {\n for (const parentAlias of (opts.parent.__aliases || [])) {\n opts.aliases.push(inheritedChildAlias(name, opts.parent.__name, parentAlias, t));\n }\n }\n this.__providers = opts.parent.__providers;\n }\n if (custom) {\n const provider = opts.provider;\n if (provider === undefined) {\n if (opts.parent) {\n // If no provider was given, but we have a parent, then inherit the\n // provider from our parent.\n opts.provider = opts.parent.getProvider(t);\n }\n }\n else {\n // If a provider was specified, add it to the providers map under this type's package so that\n // any children of this resource inherit its provider.\n const typeComponents = t.split(\":\");\n if (typeComponents.length === 3) {\n const pkg = typeComponents[0];\n this.__providers = Object.assign(Object.assign({}, this.__providers), { [pkg]: provider });\n }\n }\n }\n else {\n // Note: we checked above that at most one of opts.provider or opts.providers is set.\n // If opts.provider is set, treat that as if we were given a array of provider with that\n // single value in it. Otherwise, take the array or map of providers, convert it to a\n // map and combine with any providers we've already set from our parent.\n const providers = opts.provider\n ? convertToProvidersMap([opts.provider])\n : convertToProvidersMap(opts.providers);\n this.__providers = Object.assign(Object.assign({}, this.__providers), providers);\n }\n this.__protect = !!opts.protect;\n // Collapse any `Alias`es down to URNs. We have to wait until this point to do so because we do not know the\n // default `name` and `type` to apply until we are inside the resource constructor.\n this.__aliases = [];\n if (opts.aliases) {\n for (const alias of opts.aliases) {\n this.__aliases.push(collapseAliasToUrn(alias, name, t, opts.parent));\n }\n }\n if (opts.urn) {\n // This is a resource that already exists. Read its state from the engine.\n resource_1.getResource(this, props, custom, opts.urn);\n }\n else if (opts.id) {\n // If this is a custom resource that already exists, read its state from the provider.\n if (!custom) {\n throw new errors_1.ResourceError(\"Cannot read an existing resource unless it has a custom provider\", opts.parent);\n }\n resource_1.readResource(this, t, name, props, opts);\n }\n else {\n // Kick off the resource registration. If we are actually performing a deployment, this\n // resource's properties will be resolved asynchronously after the operation completes, so\n // that dependent computations resolve normally. If we are just planning, on the other\n // hand, values will never resolve.\n resource_1.registerResource(this, t, name, custom, remote, urn => new DependencyResource(urn), props, opts);\n }\n }\n static isInstance(obj) {\n return utils.isInstance(obj, \"__pulumiResource\");\n }\n // getProvider fetches the provider for the given module member, if any.\n getProvider(moduleMember) {\n const memComponents = moduleMember.split(\":\");\n if (memComponents.length !== 3) {\n return undefined;\n }\n const pkg = memComponents[0];\n return this.__providers[pkg];\n }\n}\nexports.Resource = Resource;\nfunction convertToProvidersMap(providers) {\n if (!providers) {\n return {};\n }\n if (!Array.isArray(providers)) {\n return providers;\n }\n const result = {};\n for (const provider of providers) {\n result[provider.getPackage()] = provider;\n }\n return result;\n}\nResource.doNotCapture = true;\n/**\n * Constant to represent the 'root stack' resource for a Pulumi application. The purpose of this is\n * solely to make it easy to write an [Alias] like so:\n *\n * `aliases: [{ parent: rootStackResource }]`.\n *\n * This indicates that the prior name for a resource was created based on it being parented directly\n * by the stack itself and no other resources. Note: this is equivalent to:\n *\n * `aliases: [{ parent: undefined }]`\n *\n * However, the former form is preferable as it is more self-descriptive, while the latter may look\n * a bit confusing and may incorrectly look like something that could be removed without changing\n * semantics.\n */\nexports.rootStackResource = undefined;\n// collapseAliasToUrn turns an Alias into a URN given a set of default data\nfunction collapseAliasToUrn(alias, defaultName, defaultType, defaultParent) {\n return output_1.output(alias).apply(a => {\n if (typeof a === \"string\") {\n return output_1.output(a);\n }\n const name = a.hasOwnProperty(\"name\") ? a.name : defaultName;\n const type = a.hasOwnProperty(\"type\") ? a.type : defaultType;\n const parent = a.hasOwnProperty(\"parent\") ? a.parent : defaultParent;\n const project = a.hasOwnProperty(\"project\") ? a.project : settings_1.getProject();\n const stack = a.hasOwnProperty(\"stack\") ? a.stack : settings_1.getStack();\n if (name === undefined) {\n throw new Error(\"No valid 'name' passed in for alias.\");\n }\n if (type === undefined) {\n throw new Error(\"No valid 'type' passed in for alias.\");\n }\n return createUrn(name, type, parent, project, stack);\n });\n}\n/**\n * CustomResource is a resource whose create, read, update, and delete (CRUD) operations are managed\n * by performing external operations on some physical entity. The engine understands how to diff\n * and perform partial updates of them, and these CRUD operations are implemented in a dynamically\n * loaded plugin for the defining package.\n */\nclass CustomResource extends Resource {\n /**\n * Creates and registers a new managed resource. t is the fully qualified type token and name\n * is the \"name\" part to use in creating a stable and globally unique URN for the object.\n * dependsOn is an optional list of other resources that this resource depends on, controlling\n * the order in which we perform resource operations. Creating an instance does not necessarily\n * perform a create on the physical entity which it represents, and instead, this is dependent\n * upon the diffing of the new goal state compared to the current known resource state.\n *\n * @param t The type of the resource.\n * @param name The _unique_ name of the resource.\n * @param props The arguments to use to populate the new resource.\n * @param opts A bag of options that control this resource's behavior.\n * @param dependency True if this is a synthetic resource used internally for dependency tracking.\n */\n constructor(t, name, props, opts = {}, dependency = false) {\n if (opts.providers) {\n throw new errors_1.ResourceError(\"Do not supply 'providers' option to a CustomResource. Did you mean 'provider' instead?\", opts.parent);\n }\n super(t, name, true, props, opts, false, dependency);\n this.__pulumiCustomResource = true;\n this.__pulumiType = t;\n }\n /**\n * Returns true if the given object is an instance of CustomResource. This is designed to work even when\n * multiple copies of the Pulumi SDK have been loaded into the same process.\n */\n static isInstance(obj) {\n return utils.isInstance(obj, \"__pulumiCustomResource\");\n }\n}\nexports.CustomResource = CustomResource;\nCustomResource.doNotCapture = true;\n/**\n * ProviderResource is a resource that implements CRUD operations for other custom resources. These resources are\n * managed similarly to other resources, including the usual diffing and update semantics.\n */\nclass ProviderResource extends CustomResource {\n /**\n * Creates and registers a new provider resource for a particular package.\n *\n * @param pkg The package associated with this provider.\n * @param name The _unique_ name of the provider.\n * @param props The configuration to use for this provider.\n * @param opts A bag of options that control this provider's behavior.\n * @param dependency True if this is a synthetic resource used internally for dependency tracking.\n */\n constructor(pkg, name, props, opts = {}, dependency = false) {\n super(`pulumi:providers:${pkg}`, name, props, opts, dependency);\n this.pkg = pkg;\n }\n static register(provider) {\n return __awaiter(this, void 0, void 0, function* () {\n if (provider === undefined) {\n return undefined;\n }\n if (!provider.__registrationId) {\n const providerURN = yield provider.urn.promise();\n const providerID = (yield provider.id.promise()) || runtime_1.unknownValue;\n provider.__registrationId = `${providerURN}::${providerID}`;\n }\n return provider.__registrationId;\n });\n }\n /** @internal */\n getPackage() {\n return this.pkg;\n }\n}\nexports.ProviderResource = ProviderResource;\n/**\n * ComponentResource is a resource that aggregates one or more other child resources into a higher\n * level abstraction. The component resource itself is a resource, but does not require custom CRUD\n * operations for provisioning.\n */\nclass ComponentResource extends Resource {\n /**\n * Creates and registers a new component resource. [type] is the fully qualified type token and\n * [name] is the \"name\" part to use in creating a stable and globally unique URN for the object.\n * [opts.parent] is the optional parent for this component, and [opts.dependsOn] is an optional\n * list of other resources that this resource depends on, controlling the order in which we\n * perform resource operations.\n *\n * @param t The type of the resource.\n * @param name The _unique_ name of the resource.\n * @param args Information passed to [initialize] method.\n * @param opts A bag of options that control this resource's behavior.\n * @param remote True if this is a remote component resource.\n */\n constructor(type, name, args = {}, opts = {}, remote = false) {\n // Explicitly ignore the props passed in. We allow them for back compat reasons. However,\n // we explicitly do not want to pass them along to the engine. The ComponentResource acts\n // only as a container for other resources. Another way to think about this is that a normal\n // 'custom resource' corresponds to real piece of cloud infrastructure. So, when it changes\n // in some way, the cloud resource needs to be updated (and vice versa). That is not true\n // for a component resource. The component is just used for organizational purposes and does\n // not correspond to a real piece of cloud infrastructure. As such, changes to it *itself*\n // do not have any effect on the cloud side of things at all.\n super(type, name, /*custom:*/ false, /*props:*/ remote ? args : {}, opts, remote);\n /**\n * A private field to help with RTTI that works in SxS scenarios.\n * @internal\n */\n // tslint:disable-next-line:variable-name\n this.__pulumiComponentResource = true;\n /** @internal */\n // tslint:disable-next-line:variable-name\n this.__registered = false;\n this.__registered = remote;\n this.__data = remote ? Promise.resolve({}) : this.initializeAndRegisterOutputs(args);\n }\n /**\n * Returns true if the given object is an instance of CustomResource. This is designed to work even when\n * multiple copies of the Pulumi SDK have been loaded into the same process.\n */\n static isInstance(obj) {\n return utils.isInstance(obj, \"__pulumiComponentResource\");\n }\n /** @internal */\n initializeAndRegisterOutputs(args) {\n return __awaiter(this, void 0, void 0, function* () {\n const data = yield this.initialize(args);\n this.registerOutputs();\n return data;\n });\n }\n /**\n * Can be overridden by a subclass to asynchronously initialize data for this Component\n * automatically when constructed. The data will be available immediately for subclass\n * constructors to use. To access the data use `.getData`.\n */\n initialize(args) {\n return __awaiter(this, void 0, void 0, function* () {\n return undefined;\n });\n }\n /**\n * Retrieves the data produces by [initialize]. The data is immediately available in a\n * derived class's constructor after the `super(...)` call to `ComponentResource`.\n */\n getData() {\n return this.__data;\n }\n /**\n * registerOutputs registers synthetic outputs that a component has initialized, usually by\n * allocating other child sub-resources and propagating their resulting property values.\n *\n * ComponentResources can call this at the end of their constructor to indicate that they are\n * done creating child resources. This is not strictly necessary as this will automatically be\n * called after the `initialize` method completes.\n */\n registerOutputs(outputs) {\n if (this.__registered) {\n return;\n }\n this.__registered = true;\n resource_1.registerResourceOutputs(this, outputs || {});\n }\n}\nexports.ComponentResource = ComponentResource;\nComponentResource.doNotCapture = true;\nComponentResource.prototype.registerOutputs.doNotCapture = true;\nComponentResource.prototype.initialize.doNotCapture = true;\nComponentResource.prototype.initializeAndRegisterOutputs.doNotCapture = true;\n/** @internal */\nexports.testingOptions = {\n isDryRun: false,\n};\nfunction mergeOptions(opts1, opts2) {\n const dest = Object.assign({}, opts1);\n const source = Object.assign({}, opts2);\n // Ensure provider/providers are all expanded into the `ProviderResource[]` form.\n // This makes merging simple.\n expandProviders(dest);\n expandProviders(source);\n // iterate specifically over the supplied properties in [source]. Note: there may not be an\n // corresponding value in [dest].\n for (const key of Object.keys(source)) {\n const destVal = dest[key];\n const sourceVal = source[key];\n // For 'dependsOn' we might have singleton resources in both options bags. We\n // want to make sure we combine them into a collection.\n if (key === \"dependsOn\") {\n dest[key] = merge(destVal, sourceVal, /*alwaysCreateArray:*/ true);\n continue;\n }\n dest[key] = merge(destVal, sourceVal, /*alwaysCreateArray:*/ false);\n }\n // Now, if we are left with a .providers that is just a single key/value pair, then\n // collapse that down into .provider form.\n normalizeProviders(dest);\n return dest;\n}\nexports.mergeOptions = mergeOptions;\nfunction isPromiseOrOutput(val) {\n return val instanceof Promise || output_1.Output.isInstance(val);\n}\nfunction expandProviders(options) {\n // Move 'provider' up to 'providers' if we have it.\n if (options.provider) {\n options.providers = [options.provider];\n }\n // Convert 'providers' map to array form.\n if (options.providers && !Array.isArray(options.providers)) {\n options.providers = utils.values(options.providers);\n }\n delete options.provider;\n}\nfunction normalizeProviders(opts) {\n // If we have only 0-1 providers, then merge that back down to the .provider field.\n const providers = opts.providers;\n if (providers) {\n if (providers.length === 0) {\n delete opts.providers;\n }\n else if (providers.length === 1) {\n opts.provider = providers[0];\n delete opts.providers;\n }\n else {\n opts.providers = {};\n for (const res of providers) {\n opts.providers[res.getPackage()] = res;\n }\n }\n }\n}\n/** @internal for testing purposes. */\nfunction merge(dest, source, alwaysCreateArray) {\n // unwind any top level promise/outputs.\n if (isPromiseOrOutput(dest)) {\n return output_1.output(dest).apply(d => merge(d, source, alwaysCreateArray));\n }\n if (isPromiseOrOutput(source)) {\n return output_1.output(source).apply(s => merge(dest, s, alwaysCreateArray));\n }\n // If either are an array, make a new array and merge the values into it.\n // Otherwise, just overwrite the destination with the source value.\n if (alwaysCreateArray || Array.isArray(dest) || Array.isArray(source)) {\n const result = [];\n addToArray(result, dest);\n addToArray(result, source);\n return result;\n }\n return source;\n}\nexports.merge = merge;\nfunction addToArray(resultArray, value) {\n if (Array.isArray(value)) {\n resultArray.push(...value);\n }\n else if (value !== undefined && value !== null) {\n resultArray.push(value);\n }\n}\n/**\n * A DependencyResource is a resource that is used to indicate that an Output has a dependency on a particular\n * resource. These resources are only created when dealing with remote component resources.\n */\nclass DependencyResource extends CustomResource {\n constructor(urn) {\n super(\"\", \"\", {}, {}, true);\n this.urn = new output_1.Output(this, Promise.resolve(urn), Promise.resolve(true), Promise.resolve(false), Promise.resolve([]));\n }\n}\nexports.DependencyResource = DependencyResource;\n/**\n * A DependencyProviderResource is a resource that is used by the provider SDK as a stand-in for a provider that\n * is only used for its reference. Its only valid properties are its URN and ID.\n */\nclass DependencyProviderResource extends ProviderResource {\n constructor(ref) {\n super(\"\", \"\", {}, {}, true);\n // Parse the URN and ID out of the provider reference.\n const lastSep = ref.lastIndexOf(\"::\");\n if (lastSep === -1) {\n throw new Error(`expected '::' in provider reference ${ref}`);\n }\n const urn = ref.slice(0, lastSep);\n const id = ref.slice(lastSep + 2);\n this.urn = new output_1.Output(this, Promise.resolve(urn), Promise.resolve(true), Promise.resolve(false), Promise.resolve([]));\n this.id = new output_1.Output(this, Promise.resolve(id), Promise.resolve(true), Promise.resolve(false), Promise.resolve([]));\n }\n}\nexports.DependencyProviderResource = DependencyProviderResource;\n","\"use strict\";\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst closeValue = \"7473659d-924c-414d-84e5-b1640b2a6296\";\n// PushableAsyncIterable is an `AsyncIterable` that data can be pushed to. It is useful for turning\n// push-based callback APIs into pull-based `AsyncIterable` APIs. For example, a user can write:\n//\n// const queue = new PushableAsyncIterable();\n// call.on(\"data\", (thing: any) => queue.push(live));\n//\n// And then later consume `queue` as any other `AsyncIterable`:\n//\n// for await (const l of list) {\n// console.log(l.metadata.name);\n// }\n//\n// Note that this class implements `AsyncIterable`. This is for a fundamental reason:\n// the user can call `complete` at any time. `AsyncIteratable` would normally know when an element\n// is the last, but in this case it can't. Or, another way to look at it is, the last element is\n// guaranteed to be `undefined`.\n/** @internal */\nclass PushableAsyncIterable {\n constructor() {\n this.bufferedData = [];\n this.nextQueue = [];\n this.completed = false;\n }\n push(payload) {\n if (this.nextQueue.length === 0) {\n this.bufferedData.push(payload);\n }\n else {\n const resolve = this.nextQueue.shift();\n resolve(payload);\n }\n }\n complete() {\n this.completed = true;\n if (this.nextQueue.length > 0) {\n const resolve = this.nextQueue.shift();\n resolve(closeValue);\n }\n }\n shift() {\n return new Promise(resolve => {\n if (this.bufferedData.length === 0) {\n if (this.completed === true) {\n resolve(closeValue);\n }\n this.nextQueue.push(resolve);\n }\n else {\n resolve(this.bufferedData.shift());\n }\n });\n }\n [Symbol.asyncIterator]() {\n const t = this;\n return {\n next() {\n return __awaiter(this, void 0, void 0, function* () {\n const value = yield t.shift();\n if (value === closeValue) {\n return { value: undefined, done: true };\n }\n return { value, done: false };\n });\n },\n };\n }\n}\nexports.PushableAsyncIterable = PushableAsyncIterable;\n","\"use strict\";\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n// tslint:disable:max-line-length\nconst fs = require(\"fs\");\nconst normalize = require(\"normalize-package-data\");\nconst readPackageTree = require(\"read-package-tree\");\nconst upath = require(\"upath\");\nconst __1 = require(\"../..\");\nconst asset = require(\"../../asset\");\nconst errors_1 = require(\"../../errors\");\nfunction computeCodePaths(optionsOrExtraIncludePaths, extraIncludePackages, extraExcludePackages) {\n return __awaiter(this, void 0, void 0, function* () {\n let options;\n if (Array.isArray(optionsOrExtraIncludePaths)) {\n __1.log.warn(\"'function computeCodePaths(string[])' is deprecated. Use the [computeCodePaths] overload that takes a [CodePathOptions] instead.\");\n options = {\n extraIncludePaths: optionsOrExtraIncludePaths,\n extraIncludePackages,\n extraExcludePackages,\n };\n }\n else {\n options = optionsOrExtraIncludePaths || {};\n }\n return computeCodePathsWorker(options);\n });\n}\nexports.computeCodePaths = computeCodePaths;\nfunction computeCodePathsWorker(options) {\n return __awaiter(this, void 0, void 0, function* () {\n // Construct the set of paths to include in the archive for upload.\n // Find folders for all packages requested by the user. Note: all paths in this should\n // be normalized.\n const normalizedPathSet = yield allFoldersForPackages(new Set(options.extraIncludePackages || []), new Set(options.extraExcludePackages || []), options.logResource);\n // Add all paths explicitly requested by the user\n const extraIncludePaths = options.extraIncludePaths || [];\n for (const path of extraIncludePaths) {\n normalizedPathSet.add(upath.normalize(path));\n }\n const codePaths = new Map();\n // For each of the required paths, add the corresponding FileArchive or FileAsset to the\n // AssetMap.\n for (const normalizedPath of normalizedPathSet) {\n // Don't include a path if there is another path higher up that will include this one.\n if (isSubsumedByHigherPath(normalizedPath, normalizedPathSet)) {\n continue;\n }\n // The Asset model does not support a consistent way to embed a file-or-directory into an\n // `AssetArchive`, so we stat the path to figure out which it is and use the appropriate\n // Asset constructor.\n const stats = fs.lstatSync(normalizedPath);\n if (stats.isDirectory()) {\n codePaths.set(normalizedPath, new asset.FileArchive(normalizedPath));\n }\n else {\n codePaths.set(normalizedPath, new asset.FileAsset(normalizedPath));\n }\n }\n return codePaths;\n });\n}\nfunction isSubsumedByHigherPath(normalizedPath, normalizedPathSet) {\n for (const otherNormalizedPath of normalizedPathSet) {\n if (normalizedPath.length > otherNormalizedPath.length &&\n normalizedPath.startsWith(otherNormalizedPath)) {\n // Have to make sure we're actually a sub-directory of that other path. For example,\n // if we have: node_modules/mime-types, that's not subsumed by node_modules/mime\n const nextChar = normalizedPath.charAt(otherNormalizedPath.length);\n return nextChar === \"/\";\n }\n }\n return false;\n}\n// allFolders computes the set of package folders that are transitively required by the root\n// 'dependencies' node in the client's project.json file.\nfunction allFoldersForPackages(includedPackages, excludedPackages, logResource) {\n return new Promise((resolve, reject) => {\n readPackageTree(\".\", undefined, (err, root) => {\n try {\n if (err) {\n return reject(err);\n }\n // read-package-tree defers to read-package-json to parse the project.json file. If that\n // fails, root.error is set to the underlying error. Unfortunately, read-package-json is\n // very finicky and can fail for reasons that are not relevant to us. For example, it\n // can fail if a \"version\" string is not a legal semver. We still want to proceed here\n // as this is not an actual problem for determining the set of dependencies.\n if (root.error) {\n if (!root.realpath) {\n throw new errors_1.ResourceError(\"Failed to parse package.json. Underlying issue:\\n \" + root.error.toString(), logResource);\n }\n // From: https://github.com/npm/read-package-tree/blob/5245c6e50d7f46ae65191782622ec75bbe80561d/rpt.js#L121\n root.package = computeDependenciesDirectlyFromPackageFile(upath.join(root.realpath, \"package.json\"), logResource);\n }\n // This is the core starting point of the algorithm. We use readPackageTree to get\n // the package.json information for this project, and then we start by walking the\n // .dependencies node in that package. Importantly, we do not look at things like\n // .devDependencies or or .peerDependencies. These are not what are considered part\n // of the final runtime configuration of the app and should not be uploaded.\n const referencedPackages = new Set(includedPackages);\n if (root.package && root.package.dependencies) {\n for (const depName of Object.keys(root.package.dependencies)) {\n referencedPackages.add(depName);\n }\n }\n // package.json files can contain circularities. For example es6-iterator depends\n // on es5-ext, which depends on es6-iterator, which depends on es5-ext:\n // https://github.com/medikoo/es6-iterator/blob/0eac672d3f4bb3ccc986bbd5b7ffc718a0822b74/package.json#L20\n // https://github.com/medikoo/es5-ext/blob/792c9051e5ad9d7671dd4e3957eee075107e9e43/package.json#L29\n //\n // So keep track of the paths we've looked and don't recurse if we hit something again.\n const seenPaths = new Set();\n const normalizedPackagePaths = new Set();\n for (const pkg of referencedPackages) {\n addPackageAndDependenciesToSet(root, pkg, seenPaths, normalizedPackagePaths, excludedPackages);\n }\n return resolve(normalizedPackagePaths);\n }\n catch (error) {\n return reject(error);\n }\n });\n });\n}\nfunction computeDependenciesDirectlyFromPackageFile(path, logResource) {\n // read the package.json file in directly. if any of these fail an error will be thrown\n // and bubbled back out to user.\n const contents = readFile();\n const data = parse();\n // 'normalize-package-data' can throw if 'version' isn't a valid string. We don't care about\n // 'version' so just delete it.\n // https://github.com/npm/normalize-package-data/blob/df8ea05b8cd38531e8b70ac7906f420344f55bab/lib/fixer.js#L191\n delete data.version;\n // 'normalize-package-data' can throw if 'name' isn't a valid string. We don't care about\n // 'name' so just delete it.\n // https://github.com/npm/normalize-package-data/blob/df8ea05b8cd38531e8b70ac7906f420344f55bab/lib/fixer.js#L211\n delete data.name;\n normalize(data);\n return data;\n function readFile() {\n try {\n return fs.readFileSync(path);\n }\n catch (err) {\n throw new errors_1.ResourceError(`Error reading file '${path}' when computing package dependencies. ${err}`, logResource);\n }\n }\n function parse() {\n try {\n return JSON.parse(contents.toString());\n }\n catch (err) {\n throw new errors_1.ResourceError(`Error parsing file '${path}' when computing package dependencies. ${err}`, logResource);\n }\n }\n}\n// addPackageAndDependenciesToSet adds all required dependencies for the requested pkg name from the given root package\n// into the set. It will recurse into all dependencies of the package.\nfunction addPackageAndDependenciesToSet(root, pkg, seenPaths, normalizedPackagePaths, excludedPackages) {\n // Don't process this packages if it was in the set the user wants to exclude.\n if (excludedPackages.has(pkg)) {\n return;\n }\n const child = findDependency(root, pkg);\n if (!child) {\n console.warn(`Could not include required dependency '${pkg}' in '${upath.resolve(root.path)}'.`);\n return;\n }\n // Don't process a child path if we've already encountered it.\n const normalizedPath = upath.normalize(child.path);\n if (seenPaths.has(normalizedPath)) {\n return;\n }\n seenPaths.add(normalizedPath);\n if (child.package.pulumi) {\n // This was a pulumi deployment-time package. Check if it had a:\n //\n // `pulumi: { runtimeDependencies: ... }`\n //\n // section. In this case, we don't want to add this specific package, but we do want to\n // include all the runtime dependencies it says are necessary.\n recurse(child.package.pulumi.runtimeDependencies);\n }\n else if (pkg.startsWith(\"@pulumi\")) {\n // exclude it if it's an @pulumi package. These packages are intended for deployment\n // time only and will only bloat up the serialized lambda package. Note: this code can\n // be removed once all pulumi packages add a \"pulumi\" section to their package.json.\n return;\n }\n else {\n // Normal package. Add the normalized path to it, and all transitively add all of its\n // dependencies.\n normalizedPackagePaths.add(normalizedPath);\n recurse(child.package.dependencies);\n }\n return;\n function recurse(dependencies) {\n if (dependencies) {\n for (const dep of Object.keys(dependencies)) {\n addPackageAndDependenciesToSet(child, dep, seenPaths, normalizedPackagePaths, excludedPackages);\n }\n }\n }\n}\n// findDependency searches the package tree starting at a root node (possibly a child) for a match\n// for the given name. It is assumed that the tree was correctly constructed such that dependencies\n// are resolved to compatible versions in the closest available match starting at the provided root\n// and walking up to the head of the tree.\nfunction findDependency(root, name) {\n for (; root; root = root.parent) {\n for (const child of root.children) {\n let childName = child.name;\n // Note: `read-package-tree` returns incorrect `.name` properties for packages in an\n // organization - like `@types/express` or `@protobufjs/path`. Compute the correct name\n // from the `path` property instead. Match any name that ends with something that looks\n // like `@foo/bar`, such as `node_modules/@foo/bar` or\n // `node_modules/baz/node_modules/@foo/bar.\n const childFolderName = upath.basename(child.path);\n const parentFolderName = upath.basename(upath.dirname(child.path));\n if (parentFolderName[0] === \"@\") {\n childName = upath.join(parentFolderName, childFolderName);\n }\n if (childName === name) {\n return child;\n }\n }\n }\n return undefined;\n}\n",null,"\"use strict\";\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst ts = require(\"typescript\");\nconst log = require(\"../../log\");\nconst utils = require(\"./utils\");\n// These are the special globals we've marked as ones we do not want to capture by value.\n// These values have a dual meaning. They mean one thing at deployment time and one thing\n// at cloud-execution time. By **not** capturing-by-value we take the view that the user\n// wants the cloud-execution time view of things.\nconst nodeModuleGlobals = {\n \"__dirname\": true,\n \"__filename\": true,\n // We definitely should not try to capture/serialize 'require'. Not only will it bottom\n // out as a native function, but it is definitely something the user intends to run\n // against the right module environment at cloud-execution time and not deployment time.\n \"require\": true,\n};\n// Gets the text of the provided function (using .toString()) and massages it so that it is a legal\n// function declaration. Note: this ties us heavily to V8 and its representation for functions. In\n// particular, it has expectations around how functions/lambdas/methods/generators/constructors etc.\n// are represented. If these change, this will likely break us.\n/** @internal */\nfunction parseFunction(funcString) {\n const [error, functionCode] = parseFunctionCode(funcString);\n if (error) {\n return [error, undefined];\n }\n // In practice it's not guaranteed that a function's toString is parsable by TypeScript.\n // V8 intrinsics are prefixed with a '%' and TypeScript does not consider that to be a valid\n // identifier.\n const [parseError, file] = createSourceFile(functionCode);\n if (parseError) {\n return [parseError, undefined];\n }\n const capturedVariables = computeCapturedVariableNames(file);\n // if we're looking at an arrow function, the it is always using lexical 'this's\n // so we don't have to bother even examining it.\n const usesNonLexicalThis = !functionCode.isArrowFunction && computeUsesNonLexicalThis(file);\n const result = functionCode;\n result.capturedVariables = capturedVariables;\n result.usesNonLexicalThis = usesNonLexicalThis;\n if (result.capturedVariables.required.has(\"this\")) {\n return [\n \"arrow function captured 'this'. Assign 'this' to another name outside function and capture that.\",\n result,\n ];\n }\n return [\"\", result];\n}\nexports.parseFunction = parseFunction;\nfunction parseFunctionCode(funcString) {\n if (funcString.startsWith(\"[Function:\")) {\n return [`the function form was not understood.`, undefined];\n }\n // Split this constant out so that if this function *itself* is closure serialized,\n // it will not be thought to be native code itself.\n const nativeCodeString = \"[native \" + \"code]\";\n if (funcString.indexOf(nativeCodeString) !== -1) {\n return [`it was a native code function.`, undefined];\n }\n // There are three general forms of node toString'ed Functions we're trying to find out here.\n //\n // 1. `[mods] (...) => ...\n //\n // i.e. an arrow function. We need to ensure that arrow-functions stay arrow-functions,\n // and non-arrow-functions end up looking like normal `function` functions. This will make\n // it so that we can correctly handle 'this' properly depending on if that should be\n // treated as the lexical capture of 'this' or the non-lexical 'this'.\n //\n // 2. `class Foo { ... }`\n //\n // i.e. node uses the entire string of a class when toString'ing the constructor function\n // for it.\n //\n // 3. `[mods] function ...\n //\n // i.e. a normal function (maybe async, maybe a get/set function, but def not an arrow\n // function)\n if (tryParseAsArrowFunction(funcString)) {\n return [\"\", { funcExprWithoutName: funcString, isArrowFunction: true }];\n }\n // First check to see if this startsWith 'class'. If so, this is definitely a class. This\n // works as Node does not place preceding comments on a class/function, allowing us to just\n // directly see if we've started with the right text.\n if (funcString.startsWith(\"class \")) {\n // class constructor function. We want to get the actual constructor\n // in the class definition (synthesizing an empty one if one does not)\n // exist.\n const [file, firstDiagnostic] = tryCreateSourceFile(funcString);\n if (firstDiagnostic) {\n return [`the class could not be parsed: ${firstDiagnostic}`, undefined];\n }\n const classDecl = file.statements.find(x => ts.isClassDeclaration(x));\n if (!classDecl) {\n return [`the class form was not understood:\\n${funcString}`, undefined];\n }\n const constructor = classDecl.members.find(m => ts.isConstructorDeclaration(m));\n if (!constructor) {\n // class without explicit constructor.\n const isSubClass = classDecl.heritageClauses && classDecl.heritageClauses.some(c => c.token === ts.SyntaxKind.ExtendsKeyword);\n return isSubClass\n ? makeFunctionDeclaration(\"constructor() { super(); }\", /*isAsync:*/ false, /*isFunctionDeclaration:*/ false)\n : makeFunctionDeclaration(\"constructor() { }\", /*isAsync:*/ false, /*isFunctionDeclaration:*/ false);\n }\n const constructorCode = funcString.substring(constructor.getStart(file, /*includeJsDocComment*/ false), constructor.end).trim();\n return makeFunctionDeclaration(constructorCode, /*isAsync:*/ false, /*isFunctionDeclaration: */ false);\n }\n let isAsync = false;\n if (funcString.startsWith(\"async \")) {\n isAsync = true;\n funcString = funcString.substr(\"async\".length).trimLeft();\n }\n if (funcString.startsWith(\"function get \") || funcString.startsWith(\"function set \")) {\n const trimmed = funcString.substr(\"function get\".length);\n return makeFunctionDeclaration(trimmed, isAsync, /*isFunctionDeclaration: */ false);\n }\n if (funcString.startsWith(\"get \") || funcString.startsWith(\"set \")) {\n const trimmed = funcString.substr(\"get \".length);\n return makeFunctionDeclaration(trimmed, isAsync, /*isFunctionDeclaration: */ false);\n }\n if (funcString.startsWith(\"function\")) {\n const trimmed = funcString.substr(\"function\".length);\n return makeFunctionDeclaration(trimmed, isAsync, /*isFunctionDeclaration: */ true);\n }\n // Add \"function\" (this will make methods parseable). i.e. \"foo() { }\" becomes\n // \"function foo() { }\"\n // this also does the right thing for functions with computed names.\n return makeFunctionDeclaration(funcString, isAsync, /*isFunctionDeclaration: */ false);\n}\nfunction tryParseAsArrowFunction(toParse) {\n const [file] = tryCreateSourceFile(toParse);\n if (!file || file.statements.length !== 1) {\n return false;\n }\n const firstStatement = file.statements[0];\n return ts.isExpressionStatement(firstStatement) &&\n ts.isArrowFunction(firstStatement.expression);\n}\nfunction makeFunctionDeclaration(v, isAsync, isFunctionDeclaration) {\n let prefix = isAsync ? \"async \" : \"\";\n prefix += \"function \";\n v = v.trimLeft();\n if (v.startsWith(\"*\")) {\n v = v.substr(1).trimLeft();\n prefix = \"function* \";\n }\n const openParenIndex = v.indexOf(\"(\");\n if (openParenIndex < 0) {\n return [`the function form was not understood.`, undefined];\n }\n if (isComputed(v, openParenIndex)) {\n v = v.substr(openParenIndex);\n return [\"\", {\n funcExprWithoutName: prefix + v,\n funcExprWithName: prefix + \"__computed\" + v,\n functionDeclarationName: undefined,\n isArrowFunction: false,\n }];\n }\n const nameChunk = v.substr(0, openParenIndex);\n const funcName = utils.isLegalMemberName(nameChunk)\n ? utils.isLegalFunctionName(nameChunk) ? nameChunk : \"/*\" + nameChunk + \"*/\"\n : \"\";\n const commentedName = utils.isLegalMemberName(nameChunk) ? \"/*\" + nameChunk + \"*/\" : \"\";\n v = v.substr(openParenIndex).trimLeft();\n return [\"\", {\n funcExprWithoutName: prefix + commentedName + v,\n funcExprWithName: prefix + funcName + v,\n functionDeclarationName: isFunctionDeclaration ? nameChunk : undefined,\n isArrowFunction: false,\n }];\n}\nfunction isComputed(v, openParenIndex) {\n if (openParenIndex === 0) {\n // node 8 and lower use no name at all for computed members.\n return true;\n }\n if (v.length > 0 && v.charAt(0) === \"[\") {\n // node 10 actually has the name as: [expr]\n return true;\n }\n return false;\n}\nfunction createSourceFile(serializedFunction) {\n const funcstr = serializedFunction.funcExprWithName || serializedFunction.funcExprWithoutName;\n // Wrap with parens to make into something parseable. This is necessary as many\n // types of functions are valid function expressions, but not valid function\n // declarations. i.e. \"function () { }\". This is not a valid function declaration\n // (it's missing a name). But it's totally legal as \"(function () { })\".\n const toParse = \"(\" + funcstr + \")\";\n const [file, firstDiagnostic] = tryCreateSourceFile(toParse);\n if (firstDiagnostic) {\n return [`the function could not be parsed: ${firstDiagnostic}`, null];\n }\n return [\"\", file];\n}\nfunction tryCreateSourceFile(toParse) {\n const file = ts.createSourceFile(\"\", toParse, ts.ScriptTarget.Latest, /*setParentNodes:*/ true, ts.ScriptKind.TS);\n const diagnostics = file.parseDiagnostics;\n if (diagnostics.length) {\n return [undefined, `${diagnostics[0].messageText}`];\n }\n return [file, undefined];\n}\nfunction computeUsesNonLexicalThis(file) {\n let inTopmostFunction = false;\n let usesNonLexicalThis = false;\n ts.forEachChild(file, walk);\n return usesNonLexicalThis;\n function walk(node) {\n if (!node) {\n return;\n }\n switch (node.kind) {\n case ts.SyntaxKind.SuperKeyword:\n case ts.SyntaxKind.ThisKeyword:\n usesNonLexicalThis = true;\n break;\n case ts.SyntaxKind.CallExpression:\n return visitCallExpression(node);\n case ts.SyntaxKind.MethodDeclaration:\n case ts.SyntaxKind.FunctionDeclaration:\n case ts.SyntaxKind.FunctionExpression:\n return visitBaseFunction(node);\n // Note: it is intentional that we ignore ArrowFunction. If we use 'this' inside of it,\n // then that should be considered a use of the non-lexical-this from an outer function.\n // i.e.\n // function f() { var v = () => console.log(this) }\n //\n // case ts.SyntaxKind.ArrowFunction:\n default:\n break;\n }\n ts.forEachChild(node, walk);\n }\n function visitBaseFunction(node) {\n if (inTopmostFunction) {\n // we're already in the topmost function. No need to descend into any\n // further functions.\n return;\n }\n // Entering the topmost function.\n inTopmostFunction = true;\n // Now, visit its body to see if we use 'this/super'.\n walk(node.body);\n inTopmostFunction = false;\n }\n function visitCallExpression(node) {\n // Most call expressions are normal. But we must special case one kind of function:\n // TypeScript's __awaiter functions. They are of the form `__awaiter(this, void 0, void 0,\n // function* (){})`,\n // The first 'this' argument is passed along in case the expression awaited uses 'this'.\n // However, doing that can be very bad for us as in many cases the 'this' just refers to the\n // surrounding module, and the awaited expression won't be using that 'this' at all.\n walk(node.expression);\n if (isAwaiterCall(node)) {\n const lastFunction = node.arguments[3];\n walk(lastFunction.body);\n return;\n }\n // For normal calls, just walk all arguments normally.\n for (const arg of node.arguments) {\n walk(arg);\n }\n }\n}\n/**\n * computeCapturedVariableNames computes the set of free variables in a given function string. Note that this string is\n * expected to be the usual V8-serialized function expression text.\n */\nfunction computeCapturedVariableNames(file) {\n // Now that we've parsed the file, compute the free variables, and return them.\n let required = new Map();\n let optional = new Map();\n const scopes = [];\n let functionVars = new Set();\n // Recurse through the tree. We use typescript's AST here and generally walk the entire\n // tree. One subtlety to be aware of is that we generally assume that when we hit an\n // identifier that it either introduces a new variable, or it lexically references a\n // variable. This clearly doesn't make sense for *all* identifiers. For example, if you\n // have \"console.log\" then \"console\" tries to lexically reference a variable, but \"log\" does\n // not. So, to avoid that being an issue, we carefully decide when to recurse. For\n // example, for member access expressions (i.e. A.B) we do not recurse down the right side.\n ts.forEachChild(file, walk);\n // Now just return all variables whose value is true. Filter out any that are part of the built-in\n // Node.js global object, however, since those are implicitly availble on the other side of serialization.\n const result = { required: new Map(), optional: new Map() };\n for (const key of required.keys()) {\n if (!isBuiltIn(key)) {\n result.required.set(key, required.get(key).concat(optional.has(key) ? optional.get(key) : []));\n }\n }\n for (const key of optional.keys()) {\n if (!isBuiltIn(key) && !required.has(key)) {\n result.optional.set(key, optional.get(key));\n }\n }\n log.debug(`Found free variables: ${JSON.stringify(result)}`);\n return result;\n function isBuiltIn(ident) {\n // The __awaiter is never considered built-in. We do this as async/await code will generate\n // this (so we will need it), but some libraries (like tslib) will add this to the 'global'\n // object. If we think this is built-in, we won't serialize it, and the function may not\n // actually be available if the import that caused it to get attached isn't included in the\n // final serialized code.\n if (ident === \"__awaiter\") {\n return false;\n }\n // Anything in the global dictionary is a built-in. So is anything that's a global Node.js object;\n // note that these only exist in the scope of modules, and so are not truly global in the usual sense.\n // See https://nodejs.org/api/globals.html for more details.\n return global.hasOwnProperty(ident) || nodeModuleGlobals[ident];\n }\n function currentScope() {\n return scopes[scopes.length - 1];\n }\n function visitIdentifier(node) {\n // Remember undeclared identifiers during the walk, as they are possibly free.\n const name = node.text;\n for (let i = scopes.length - 1; i >= 0; i--) {\n if (scopes[i].has(name)) {\n // This is currently known in the scope chain, so do not add it as free.\n return;\n }\n }\n // We reached the top of the scope chain and this wasn't found; it's captured.\n const capturedPropertyChain = determineCapturedPropertyChain(node);\n if (node.parent.kind === ts.SyntaxKind.TypeOfExpression) {\n // \"typeof undeclared_id\" is legal in JS (and is actually used in libraries). So keep\n // track that we would like to capture this variable, but mark that capture as optional\n // so we will not throw if we aren't able to find it in scope.\n optional.set(name, combineProperties(optional.get(name), capturedPropertyChain));\n }\n else {\n required.set(name, combineProperties(required.get(name), capturedPropertyChain));\n }\n }\n function walk(node) {\n if (!node) {\n return;\n }\n switch (node.kind) {\n case ts.SyntaxKind.Identifier:\n return visitIdentifier(node);\n case ts.SyntaxKind.ThisKeyword:\n return visitThisExpression(node);\n case ts.SyntaxKind.Block:\n return visitBlockStatement(node);\n case ts.SyntaxKind.CallExpression:\n return visitCallExpression(node);\n case ts.SyntaxKind.CatchClause:\n return visitCatchClause(node);\n case ts.SyntaxKind.MethodDeclaration:\n return visitMethodDeclaration(node);\n case ts.SyntaxKind.MetaProperty:\n // don't walk down an es6 metaproperty (i.e. \"new.target\"). It doesn't\n // capture anything.\n return;\n case ts.SyntaxKind.PropertyAssignment:\n return visitPropertyAssignment(node);\n case ts.SyntaxKind.PropertyAccessExpression:\n return visitPropertyAccessExpression(node);\n case ts.SyntaxKind.FunctionDeclaration:\n case ts.SyntaxKind.FunctionExpression:\n return visitFunctionDeclarationOrExpression(node);\n case ts.SyntaxKind.ArrowFunction:\n return visitBaseFunction(node, /*isArrowFunction:*/ true, /*name:*/ undefined);\n case ts.SyntaxKind.VariableDeclaration:\n return visitVariableDeclaration(node);\n default:\n break;\n }\n ts.forEachChild(node, walk);\n }\n function visitThisExpression(node) {\n required.set(\"this\", combineProperties(required.get(\"this\"), determineCapturedPropertyChain(node)));\n }\n function combineProperties(existing, current) {\n if (existing && existing.length === 0) {\n // We already want to capture everything. Keep things that way.\n return existing;\n }\n if (current === undefined) {\n // We want to capture everything. So ignore any properties we've filtered down\n // to and just capture them all.\n return [];\n }\n // We want to capture a specific set of properties. Add this set of properties\n // into the existing set.\n const combined = existing || [];\n combined.push(current);\n return combined;\n }\n // Finds nodes of the form `(...expr...).PropName` or `(...expr...)[\"PropName\"]`\n // For element access expressions, the argument must be a string literal.\n function isPropertyOrElementAccessExpression(node) {\n if (ts.isPropertyAccessExpression(node)) {\n return true;\n }\n if (ts.isElementAccessExpression(node) && ts.isStringLiteral(node.argumentExpression)) {\n return true;\n }\n return false;\n }\n function determineCapturedPropertyChain(node) {\n let infos;\n // Walk up a sequence of property-access'es, recording the names we hit, until we hit\n // something that isn't a property-access.\n while (node &&\n node.parent &&\n isPropertyOrElementAccessExpression(node.parent) &&\n node.parent.expression === node) {\n if (!infos) {\n infos = [];\n }\n const propOrElementAccess = node.parent;\n const name = ts.isPropertyAccessExpression(propOrElementAccess)\n ? propOrElementAccess.name.text\n : propOrElementAccess.argumentExpression.text;\n const invoked = propOrElementAccess.parent !== undefined &&\n ts.isCallExpression(propOrElementAccess.parent) &&\n propOrElementAccess.parent.expression === propOrElementAccess;\n // Keep track if this name was invoked. If so, we'll have to analyze it later\n // to see if it captured 'this'\n infos.push({ name, invoked });\n node = propOrElementAccess;\n }\n if (infos) {\n // Invariant checking.\n if (infos.length === 0) {\n throw new Error(\"How did we end up with an empty list?\");\n }\n for (let i = 0; i < infos.length - 1; i++) {\n if (infos[i].invoked) {\n throw new Error(\"Only the last item in the dotted chain is allowed to be invoked.\");\n }\n }\n return { infos };\n }\n // For all other cases, capture everything.\n return undefined;\n }\n function visitBlockStatement(node) {\n // Push new scope, visit all block statements, and then restore the scope.\n scopes.push(new Set());\n ts.forEachChild(node, walk);\n scopes.pop();\n }\n function visitFunctionDeclarationOrExpression(node) {\n // A function declaration is special in one way: its identifier is added to the current function's\n // var-style variables, so that its name is in scope no matter the order of surrounding references to it.\n if (node.name) {\n functionVars.add(node.name.text);\n }\n visitBaseFunction(node, /*isArrowFunction:*/ false, node.name);\n }\n function visitBaseFunction(node, isArrowFunction, functionName) {\n // First, push new free vars list, scope, and function vars\n const savedRequired = required;\n const savedOptional = optional;\n const savedFunctionVars = functionVars;\n required = new Map();\n optional = new Map();\n functionVars = new Set();\n scopes.push(new Set());\n // If this is a named function, it's name is in scope at the top level of itself.\n if (functionName) {\n functionVars.add(functionName.text);\n }\n // this/arguments are in scope inside any non-arrow function.\n if (!isArrowFunction) {\n functionVars.add(\"this\");\n functionVars.add(\"arguments\");\n }\n // The parameters of any function are in scope at the top level of the function.\n for (const param of node.parameters) {\n nameWalk(param.name, /*isVar:*/ true);\n // Parse default argument expressions\n if (param.initializer) {\n walk(param.initializer);\n }\n }\n // Next, visit the body underneath this new context.\n walk(node.body);\n // Remove any function-scoped variables that we encountered during the walk.\n for (const v of functionVars) {\n required.delete(v);\n optional.delete(v);\n }\n // Restore the prior context and merge our free list with the previous one.\n scopes.pop();\n mergeMaps(savedRequired, required);\n mergeMaps(savedOptional, optional);\n functionVars = savedFunctionVars;\n required = savedRequired;\n optional = savedOptional;\n }\n function mergeMaps(target, source) {\n for (const key of source.keys()) {\n const sourcePropInfos = source.get(key);\n let targetPropInfos = target.get(key);\n if (sourcePropInfos.length === 0) {\n // we want to capture everything. Make sure that's reflected in the target.\n targetPropInfos = [];\n }\n else {\n // we want to capture a subet of properties. merge that subset into whatever\n // subset we've recorded so far.\n for (const sourceInfo of sourcePropInfos) {\n targetPropInfos = combineProperties(targetPropInfos, sourceInfo);\n }\n }\n target.set(key, targetPropInfos);\n }\n }\n function visitCatchClause(node) {\n scopes.push(new Set());\n // Add the catch pattern to the scope as a variable. Note that it is scoped to our current\n // fresh scope (so it can't be seen by the rest of the function).\n if (node.variableDeclaration) {\n nameWalk(node.variableDeclaration.name, /*isVar:*/ false);\n }\n // And then visit the block without adding them as free variables.\n walk(node.block);\n // Relinquish the scope so the error patterns aren't available beyond the catch.\n scopes.pop();\n }\n function visitCallExpression(node) {\n // Most call expressions are normal. But we must special case one kind of function:\n // TypeScript's __awaiter functions. They are of the form `__awaiter(this, void 0, void 0, function* (){})`,\n // The first 'this' argument is passed along in case the expression awaited uses 'this'.\n // However, doing that can be very bad for us as in many cases the 'this' just refers to the\n // surrounding module, and the awaited expression won't be using that 'this' at all.\n //\n // However, there are cases where 'this' may be legitimately lexically used in the awaited\n // expression and should be captured properly. We'll figure this out by actually descending\n // explicitly into the \"function*(){}\" argument, asking it to be treated as if it was\n // actually a lambda and not a JS function (with the standard js 'this' semantics). By\n // doing this, if 'this' is used inside the function* we'll act as if it's a real lexical\n // capture so that we pass 'this' along.\n walk(node.expression);\n if (isAwaiterCall(node)) {\n return visitBaseFunction(node.arguments[3], \n /*isArrowFunction*/ true, \n /*name*/ undefined);\n }\n // For normal calls, just walk all arguments normally.\n for (const arg of node.arguments) {\n walk(arg);\n }\n }\n function visitMethodDeclaration(node) {\n if (ts.isComputedPropertyName(node.name)) {\n // Don't walk down the 'name' part of the property assignment if it is an identifier. It\n // does not capture any variables. However, if it is a computed property name, walk it\n // as it may capture variables.\n walk(node.name);\n }\n // Always walk the method. Pass 'undefined' for the name as a method's name is not in scope\n // inside itself.\n visitBaseFunction(node, /*isArrowFunction:*/ false, /*name:*/ undefined);\n }\n function visitPropertyAssignment(node) {\n if (ts.isComputedPropertyName(node.name)) {\n // Don't walk down the 'name' part of the property assignment if it is an identifier. It\n // is not capturing any variables. However, if it is a computed property name, walk it\n // as it may capture variables.\n walk(node.name);\n }\n // Always walk the property initializer.\n walk(node.initializer);\n }\n function visitPropertyAccessExpression(node) {\n // Don't walk down the 'name' part of the property access. It could not capture a free variable.\n // i.e. if you have \"A.B\", we should analyze the \"A\" part and not the \"B\" part.\n walk(node.expression);\n }\n function nameWalk(n, isVar) {\n if (!n) {\n return;\n }\n switch (n.kind) {\n case ts.SyntaxKind.Identifier:\n return visitVariableDeclarationIdentifier(n, isVar);\n case ts.SyntaxKind.ObjectBindingPattern:\n case ts.SyntaxKind.ArrayBindingPattern:\n const bindingPattern = n;\n for (const element of bindingPattern.elements) {\n if (ts.isBindingElement(element)) {\n visitBindingElement(element, isVar);\n }\n }\n return;\n default:\n return;\n }\n }\n function visitVariableDeclaration(node) {\n // tslint:disable-next-line:max-line-length\n const isLet = node.parent !== undefined && ts.isVariableDeclarationList(node.parent) && (node.parent.flags & ts.NodeFlags.Let) !== 0;\n // tslint:disable-next-line:max-line-length\n const isConst = node.parent !== undefined && ts.isVariableDeclarationList(node.parent) && (node.parent.flags & ts.NodeFlags.Const) !== 0;\n const isVar = !isLet && !isConst;\n // Walk the declaration's `name` property (which may be an Identifier or Pattern) placing\n // any variables we encounter into the right scope.\n nameWalk(node.name, isVar);\n // Also walk into the variable initializer with the original walker to make sure we see any\n // captures on the right hand side.\n walk(node.initializer);\n }\n function visitVariableDeclarationIdentifier(node, isVar) {\n // If the declaration is an identifier, it isn't a free variable, for whatever scope it\n // pertains to (function-wide for var and scope-wide for let/const). Track it so we can\n // remove any subseqeunt references to that variable, so we know it isn't free.\n if (isVar) {\n functionVars.add(node.text);\n }\n else {\n currentScope().add(node.text);\n }\n }\n function visitBindingElement(node, isVar) {\n // array and object patterns can be quite complex. You can have:\n //\n // var {t} = val; // lookup a property in 'val' called 't' and place into a variable 't'.\n // var {t: m} = val; // lookup a property in 'val' called 't' and place into a variable 'm'.\n // var {t: } = val; // lookup a property in 'val' called 't' and decompose further into the pattern.\n //\n // And, for all of the above, you can have:\n //\n // var {t = def} = val;\n // var {t: m = def} = val;\n // var {t: = def} = val;\n //\n // These are the same as the above, except that if there is no property 't' in 'val',\n // then the default value will be used.\n //\n // You can also have at the end of the literal: { ...rest}\n // Walk the name portion, looking for names to add. for\n //\n // var {t} // this will be 't'.\n //\n // for\n //\n // var {t: m} // this will be 'm'\n //\n // and for\n //\n // var {t: } // this will recurse into the pattern.\n //\n // and for\n //\n // ...rest // this will be 'rest'\n nameWalk(node.name, isVar);\n // if there is a default value, walk it as well, looking for captures.\n walk(node.initializer);\n // importantly, we do not walk into node.propertyName\n // This Name defines what property will be retrieved from the value being pattern\n // matched against. Importantly, it does not define a new name put into scope,\n // nor does it reference a variable in scope.\n }\n}\nfunction isAwaiterCall(node) {\n const result = ts.isIdentifier(node.expression) &&\n node.expression.text === \"__awaiter\" &&\n node.arguments.length === 4 &&\n node.arguments[0].kind === ts.SyntaxKind.ThisKeyword &&\n ts.isFunctionLike(node.arguments[3]);\n return result;\n}\n","\"use strict\";\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst ts = require(\"typescript\");\nconst utils = require(\"./utils\");\n/** @internal */\nfunction rewriteSuperReferences(code, isStatic) {\n const sourceFile = ts.createSourceFile(\"\", code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n // Transform any usages of \"super(...)\" into \"__super.call(this, ...)\", any\n // instance usages of \"super.xxx\" into \"__super.prototype.xxx\" and any static\n // usages of \"super.xxx\" into \"__super.xxx\"\n const transformed = ts.transform(sourceFile, [rewriteSuperCallsWorker]);\n const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });\n const output = printer.printNode(ts.EmitHint.Unspecified, transformed.transformed[0], sourceFile).trim();\n return output;\n function rewriteSuperCallsWorker(transformationContext) {\n const newNodes = new Set();\n let firstFunctionDeclaration = true;\n function visitor(node) {\n // Convert the top level function so it doesn't have a name. We want to convert the user\n // function to an anonymous function so that interior references to the same function\n // bind properly. i.e. if we start with \"function f() { f(); }\" then this gets converted to\n //\n // function __f() {\n // with ({ f: __f }) {\n // return /*f*/() { f(); }\n //\n // This means the inner call properly binds to the *outer* function we create.\n if (firstFunctionDeclaration && ts.isFunctionDeclaration(node)) {\n firstFunctionDeclaration = false;\n const funcDecl = ts.visitEachChild(node, visitor, transformationContext);\n const text = utils.isLegalMemberName(funcDecl.name.text)\n ? \"/*\" + funcDecl.name.text + \"*/\" : \"\";\n return ts.updateFunctionDeclaration(funcDecl, funcDecl.decorators, funcDecl.modifiers, funcDecl.asteriskToken, ts.createIdentifier(text), funcDecl.typeParameters, funcDecl.parameters, funcDecl.type, funcDecl.body);\n }\n if (node.kind === ts.SyntaxKind.SuperKeyword) {\n const newNode = ts.createIdentifier(\"__super\");\n newNodes.add(newNode);\n return newNode;\n }\n else if (ts.isPropertyAccessExpression(node) &&\n node.expression.kind === ts.SyntaxKind.SuperKeyword) {\n const expr = isStatic\n ? ts.createIdentifier(\"__super\")\n : ts.createPropertyAccess(ts.createIdentifier(\"__super\"), \"prototype\");\n const newNode = ts.updatePropertyAccess(node, expr, node.name);\n newNodes.add(newNode);\n return newNode;\n }\n else if (ts.isElementAccessExpression(node) &&\n node.argumentExpression &&\n node.expression.kind === ts.SyntaxKind.SuperKeyword) {\n const expr = isStatic\n ? ts.createIdentifier(\"__super\")\n : ts.createPropertyAccess(ts.createIdentifier(\"__super\"), \"prototype\");\n const newNode = ts.updateElementAccess(node, expr, node.argumentExpression);\n newNodes.add(newNode);\n return newNode;\n }\n // for all other nodes, recurse first (so we update any usages of 'super')\n // below them\n const rewritten = ts.visitEachChild(node, visitor, transformationContext);\n if (ts.isCallExpression(rewritten) &&\n newNodes.has(rewritten.expression)) {\n // this was a call to super() or super.x() or super[\"x\"]();\n // the super will already have been transformed to __super or\n // __super.prototype.x or __super.prototype[\"x\"].\n //\n // to that, we have to add the .call(this, ...) call.\n const argumentsCopy = rewritten.arguments.slice();\n argumentsCopy.unshift(ts.createThis());\n return ts.updateCall(rewritten, ts.createPropertyAccess(rewritten.expression, \"call\"), rewritten.typeArguments, argumentsCopy);\n }\n return rewritten;\n }\n return (node) => ts.visitNode(node, visitor);\n }\n}\nexports.rewriteSuperReferences = rewriteSuperReferences;\n","\"use strict\";\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst __1 = require(\"../..\");\nconst closure = require(\"./createClosure\");\nconst utils = require(\"./utils\");\n/**\n * serializeFunction serializes a JavaScript function into a text form that can be loaded in another execution context,\n * for example as part of a function callback associated with an AWS Lambda. The function serialization captures any\n * variables captured by the function body and serializes those values into the generated text along with the function\n * body. This process is recursive, so that functions referenced by the body of the serialized function will themselves\n * be serialized as well. This process also deeply serializes captured object values, including prototype chains and\n * property descriptors, such that the semantics of the function when deserialized should match the original function.\n *\n * There are several known limitations:\n * - If a native function is captured either directly or indirectly, closure serialization will return an error.\n * - Captured values will be serialized based on their values at the time that `serializeFunction` is called. Mutations\n * to these values after that (but before the deserialized function is used) will not be observed by the deserialized\n * function.\n *\n * @param func The JavaScript function to serialize.\n * @param args Arguments to use to control the serialization of the JavaScript function.\n */\nfunction serializeFunction(func, args = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n const exportName = args.exportName || \"handler\";\n const serialize = args.serialize || (_ => true);\n const isFactoryFunction = args.isFactoryFunction === undefined ? false : args.isFactoryFunction;\n const closureInfo = yield closure.createClosureInfoAsync(func, serialize, args.logResource);\n if (!args.allowSecrets && closureInfo.containsSecrets) {\n throw new Error(\"Secret outputs cannot be captured by a closure.\");\n }\n return serializeJavaScriptText(closureInfo, exportName, isFactoryFunction);\n });\n}\nexports.serializeFunction = serializeFunction;\n/**\n * @deprecated Please use 'serializeFunction' instead.\n */\nfunction serializeFunctionAsync(func, serialize) {\n return __awaiter(this, void 0, void 0, function* () {\n __1.log.warn(\"'function serializeFunctionAsync' is deprecated. Please use 'serializeFunction' instead.\");\n serialize = serialize || (_ => true);\n const closureInfo = yield closure.createClosureInfoAsync(func, serialize, /*logResource:*/ undefined);\n if (closureInfo.containsSecrets) {\n throw new Error(\"Secret outputs cannot be captured by a closure.\");\n }\n return serializeJavaScriptText(closureInfo, \"handler\", /*isFactoryFunction*/ false).text;\n });\n}\nexports.serializeFunctionAsync = serializeFunctionAsync;\n/**\n * serializeJavaScriptText converts a FunctionInfo object into a string representation of a Node.js module body which\n * exposes a single function `exports.handler` representing the serialized function.\n *\n * @param c The FunctionInfo to be serialized into a module string.\n */\nfunction serializeJavaScriptText(outerClosure, exportName, isFactoryFunction) {\n // Now produce a textual representation of the closure and its serialized captured environment.\n // State used to build up the environment variables for all the funcs we generate.\n // In general, we try to create idiomatic code to make the generated code not too\n // hideous. For example, we will try to generate code like:\n //\n // var __e1 = [1, 2, 3] // or\n // var __e2 = { a: 1, b: 2, c: 3 }\n //\n // However, for non-common cases (i.e. sparse arrays, objects with configured properties,\n // etc. etc.) we will spit things out in a much more verbose fashion that eschews\n // prettyness for correct semantics.\n const envEntryToEnvVar = new Map();\n const envVarNames = new Set();\n const functionInfoToEnvVar = new Map();\n let environmentText = \"\";\n let functionText = \"\";\n const outerFunctionName = emitFunctionAndGetName(outerClosure.func);\n if (environmentText) {\n environmentText = \"\\n\" + environmentText;\n }\n // Export the appropriate value. For a normal function, this will just be exporting the name of\n // the module function we created by serializing it. For a factory function this will export\n // the function produced by invoking the factory function once.\n let text;\n const exportText = `exports.${exportName} = ${outerFunctionName}${isFactoryFunction ? \"()\" : \"\"};`;\n if (isFactoryFunction) {\n // for a factory function, we need to call the function at the end. That way all the logic\n // to set up the environment has run.\n text = environmentText + functionText + \"\\n\" + exportText;\n }\n else {\n text = exportText + \"\\n\" + environmentText + functionText;\n }\n return { text, exportName, containsSecrets: outerClosure.containsSecrets };\n function emitFunctionAndGetName(functionInfo) {\n // If this is the first time seeing this function, then actually emit the function code for\n // it. Otherwise, just return the name of the emitted function for anyone that wants to\n // reference it from their own code.\n let functionName = functionInfoToEnvVar.get(functionInfo);\n if (!functionName) {\n functionName = functionInfo.name\n ? createEnvVarName(functionInfo.name, /*addIndexAtEnd:*/ false)\n : createEnvVarName(\"f\", /*addIndexAtEnd:*/ true);\n functionInfoToEnvVar.set(functionInfo, functionName);\n emitFunctionWorker(functionInfo, functionName);\n }\n return functionName;\n }\n function emitFunctionWorker(functionInfo, varName) {\n const capturedValues = envFromEnvObj(functionInfo.capturedValues);\n const thisCapture = capturedValues.this;\n const argumentsCapture = capturedValues.arguments;\n delete capturedValues.this;\n delete capturedValues.arguments;\n const parameters = [...Array(functionInfo.paramCount)].map((_, index) => `__${index}`).join(\", \");\n functionText += \"\\n\" +\n \"function \" + varName + \"(\" + parameters + \") {\\n\" +\n \" return (function() {\\n\" +\n \" with(\" + envObjToString(capturedValues) + \") {\\n\\n\" +\n \"return \" + functionInfo.code + \";\\n\\n\" +\n \" }\\n\" +\n \" }).apply(\" + thisCapture + \", \" + argumentsCapture + \").apply(this, arguments);\\n\" +\n \"}\\n\";\n // If this function is complex (i.e. non-default __proto__, or has properties, etc.)\n // then emit those as well.\n emitComplexObjectProperties(varName, varName, functionInfo);\n if (functionInfo.proto !== undefined) {\n const protoVar = envEntryToString(functionInfo.proto, `${varName}_proto`);\n environmentText += `Object.setPrototypeOf(${varName}, ${protoVar});\\n`;\n }\n }\n function envFromEnvObj(env) {\n const envObj = {};\n for (const [keyEntry, { entry: valEntry }] of env) {\n if (typeof keyEntry.json !== \"string\") {\n throw new Error(\"PropertyMap key was not a string.\");\n }\n const key = keyEntry.json;\n const val = envEntryToString(valEntry, key);\n envObj[key] = val;\n }\n return envObj;\n }\n function envEntryToString(envEntry, varName) {\n const envVar = envEntryToEnvVar.get(envEntry);\n if (envVar !== undefined) {\n return envVar;\n }\n // Complex objects may also be referenced from multiple functions. As such, we have to\n // create variables for them in the environment so that all references to them unify to the\n // same reference to the env variable. Effectively, we need to do this for any object that\n // could be compared for reference-identity. Basic types (strings, numbers, etc.) have\n // value semantics and this can be emitted directly into the code where they are used as\n // there is no way to observe that you are getting a different copy.\n if (isObjOrArrayOrRegExp(envEntry)) {\n return complexEnvEntryToString(envEntry, varName);\n }\n else {\n // Other values (like strings, bools, etc.) can just be emitted inline.\n return simpleEnvEntryToString(envEntry, varName);\n }\n }\n function simpleEnvEntryToString(envEntry, varName) {\n if (envEntry.hasOwnProperty(\"json\")) {\n return JSON.stringify(envEntry.json);\n }\n else if (envEntry.function !== undefined) {\n return emitFunctionAndGetName(envEntry.function);\n }\n else if (envEntry.module !== undefined) {\n return `require(\"${envEntry.module}\")`;\n }\n else if (envEntry.output !== undefined) {\n return envEntryToString(envEntry.output, varName);\n }\n else if (envEntry.expr) {\n // Entry specifies exactly how it should be emitted. So just use whatever\n // it wanted.\n return envEntry.expr;\n }\n else if (envEntry.promise) {\n return `Promise.resolve(${envEntryToString(envEntry.promise, varName)})`;\n }\n else {\n throw new Error(\"Malformed: \" + JSON.stringify(envEntry));\n }\n }\n function complexEnvEntryToString(envEntry, varName) {\n // Call all environment variables __e to make them unique. But suffix\n // them with the original name of the property to help provide context when\n // looking at the source.\n const envVar = createEnvVarName(varName, /*addIndexAtEnd:*/ false);\n envEntryToEnvVar.set(envEntry, envVar);\n if (envEntry.object) {\n emitObject(envVar, envEntry.object, varName);\n }\n else if (envEntry.array) {\n emitArray(envVar, envEntry.array, varName);\n }\n else if (envEntry.regexp) {\n const { source, flags } = envEntry.regexp;\n const regexVal = `new RegExp(${JSON.stringify(source)}, ${JSON.stringify(flags)})`;\n const entryString = `var ${envVar} = ${regexVal};\\n`;\n environmentText += entryString;\n }\n return envVar;\n }\n function createEnvVarName(baseName, addIndexAtEnd) {\n const trimLeadingUnderscoreRegex = /^_*/g;\n const legalName = makeLegalJSName(baseName).replace(trimLeadingUnderscoreRegex, \"\");\n let index = 0;\n let currentName = addIndexAtEnd\n ? \"__\" + legalName + index\n : \"__\" + legalName;\n while (envVarNames.has(currentName)) {\n currentName = addIndexAtEnd\n ? \"__\" + legalName + index\n : \"__\" + index + \"_\" + legalName;\n index++;\n }\n envVarNames.add(currentName);\n return currentName;\n }\n function emitObject(envVar, obj, varName) {\n const complex = isComplex(obj);\n if (complex) {\n // we have a complex child. Because of the possibility of recursion in\n // the object graph, we have to spit out this variable uninitialized first.\n // Then we can walk our children, creating a single assignment per child.\n // This way, if the child ends up referencing us, we'll have already emitted\n // the **initialized** variable for them to reference.\n if (obj.proto) {\n const protoVar = envEntryToString(obj.proto, `${varName}_proto`);\n environmentText += `var ${envVar} = Object.create(${protoVar});\\n`;\n }\n else {\n environmentText += `var ${envVar} = {};\\n`;\n }\n emitComplexObjectProperties(envVar, varName, obj);\n }\n else {\n // All values inside this obj are simple. We can just emit the object\n // directly as an object literal with all children embedded in the literal.\n const props = [];\n for (const [keyEntry, { entry: valEntry }] of obj.env) {\n const keyName = typeof keyEntry.json === \"string\" ? keyEntry.json : \"sym\";\n const propName = envEntryToString(keyEntry, keyName);\n const propVal = simpleEnvEntryToString(valEntry, keyName);\n if (typeof keyEntry.json === \"string\" && utils.isLegalMemberName(keyEntry.json)) {\n props.push(`${keyEntry.json}: ${propVal}`);\n }\n else {\n props.push(`[${propName}]: ${propVal}`);\n }\n }\n const allProps = props.join(\", \");\n const entryString = `var ${envVar} = {${allProps}};\\n`;\n environmentText += entryString;\n }\n function isComplex(o) {\n if (obj.proto !== undefined) {\n return true;\n }\n for (const v of o.env.values()) {\n if (entryIsComplex(v)) {\n return true;\n }\n }\n return false;\n }\n function entryIsComplex(v) {\n return !isSimplePropertyInfo(v.info) || deepContainsObjOrArrayOrRegExp(v.entry);\n }\n }\n function isSimplePropertyInfo(info) {\n if (!info) {\n return true;\n }\n return info.enumerable === true &&\n info.writable === true &&\n info.configurable === true &&\n !info.get && !info.set;\n }\n function emitComplexObjectProperties(envVar, varName, objEntry) {\n for (const [keyEntry, { info, entry: valEntry }] of objEntry.env) {\n const subName = typeof keyEntry.json === \"string\" ? keyEntry.json : \"sym\";\n const keyString = envEntryToString(keyEntry, varName + \"_\" + subName);\n const valString = envEntryToString(valEntry, varName + \"_\" + subName);\n if (isSimplePropertyInfo(info)) {\n // normal property. Just emit simply as a direct assignment.\n if (typeof keyEntry.json === \"string\" && utils.isLegalMemberName(keyEntry.json)) {\n environmentText += `${envVar}.${keyEntry.json} = ${valString};\\n`;\n }\n else {\n environmentText += `${envVar}${`[${keyString}]`} = ${valString};\\n`;\n }\n }\n else {\n // complex property. emit as Object.defineProperty\n emitDefineProperty(info, valString, keyString);\n }\n }\n function emitDefineProperty(desc, entryValue, propName) {\n const copy = {};\n if (desc.configurable) {\n copy.configurable = desc.configurable;\n }\n if (desc.enumerable) {\n copy.enumerable = desc.enumerable;\n }\n if (desc.writable) {\n copy.writable = desc.writable;\n }\n if (desc.get) {\n copy.get = envEntryToString(desc.get, `${varName}_get`);\n }\n if (desc.set) {\n copy.set = envEntryToString(desc.set, `${varName}_set`);\n }\n if (desc.hasValue) {\n copy.value = entryValue;\n }\n const line = `Object.defineProperty(${envVar}, ${propName}, ${envObjToString(copy)});\\n`;\n environmentText += line;\n }\n }\n function emitArray(envVar, arr, varName) {\n if (arr.some(deepContainsObjOrArrayOrRegExp) || isSparse(arr) || hasNonNumericIndices(arr)) {\n // we have a complex child. Because of the possibility of recursion in the object\n // graph, we have to spit out this variable initialized (but empty) first. Then we can\n // walk our children, knowing we'll be able to find this variable if they reference it.\n environmentText += `var ${envVar} = [];\\n`;\n // Walk the names of the array properties directly. This ensures we work efficiently\n // with sparse arrays. i.e. if the array has length 1k, but only has one value in it\n // set, we can just set htat value, instead of setting 999 undefineds.\n let length = 0;\n for (const key of Object.getOwnPropertyNames(arr)) {\n if (key !== \"length\") {\n const entryString = envEntryToString(arr[key], `${varName}_${key}`);\n environmentText += `${envVar}${isNumeric(key) ? `[${key}]` : `.${key}`} = ${entryString};\\n`;\n length++;\n }\n }\n }\n else {\n // All values inside this array are simple. We can just emit the array elements in\n // place. i.e. we can emit as ``var arr = [1, 2, 3]`` as that's far more preferred than\n // having four individual statements to do the same.\n const strings = [];\n for (let i = 0, n = arr.length; i < n; i++) {\n strings.push(simpleEnvEntryToString(arr[i], `${varName}_${i}`));\n }\n const entryString = `var ${envVar} = [${strings.join(\", \")}];\\n`;\n environmentText += entryString;\n }\n }\n}\nserializeJavaScriptText.doNotCapture = true;\nconst makeLegalRegex = /[^0-9a-zA-Z_]/g;\nfunction makeLegalJSName(n) {\n return n.replace(makeLegalRegex, x => \"\");\n}\nfunction isSparse(arr) {\n // getOwnPropertyNames for an array returns all the indices as well as 'length'.\n // so we subtract one to get all the real indices. If that's not the same as\n // the array length, then we must have missing properties and are thus sparse.\n return arr.length !== (Object.getOwnPropertyNames(arr).length - 1);\n}\nfunction hasNonNumericIndices(arr) {\n return Object.keys(arr).some(k => k !== \"length\" && !isNumeric(k));\n}\nfunction isNumeric(n) {\n return !isNaN(parseFloat(n)) && isFinite(+n);\n}\nfunction isObjOrArrayOrRegExp(env) {\n return env.object !== undefined || env.array !== undefined || env.regexp !== undefined;\n}\nfunction deepContainsObjOrArrayOrRegExp(env) {\n return isObjOrArrayOrRegExp(env) ||\n (env.output !== undefined && deepContainsObjOrArrayOrRegExp(env.output)) ||\n (env.promise !== undefined && deepContainsObjOrArrayOrRegExp(env.promise));\n}\n/**\n * Converts an environment object into a string which can be embedded into a serialized function\n * body. Note that this is not JSON serialization, as we may have property values which are\n * variable references to other global functions. In other words, there can be free variables in the\n * resulting object literal.\n *\n * @param envObj The environment object to convert to a string.\n */\nfunction envObjToString(envObj) {\n return `{ ${Object.keys(envObj).map(k => `${k}: ${envObj[k]}`).join(\", \")} }`;\n}\n","\"use strict\";\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst ts = require(\"typescript\");\nconst legalNameRegex = /^[a-zA-Z_][0-9a-zA-Z_]*$/;\n/** @internal */\nfunction isLegalMemberName(n) {\n return legalNameRegex.test(n);\n}\nexports.isLegalMemberName = isLegalMemberName;\n/** @internal */\nfunction isLegalFunctionName(n) {\n if (!isLegalMemberName(n)) {\n return false;\n }\n const scanner = ts.createScanner(ts.ScriptTarget.Latest, /*skipTrivia:*/ false, ts.LanguageVariant.Standard, n);\n const tokenKind = scanner.scan();\n if (tokenKind !== ts.SyntaxKind.Identifier &&\n tokenKind !== ts.SyntaxKind.ConstructorKeyword) {\n return false;\n }\n return true;\n}\nexports.isLegalFunctionName = isLegalFunctionName;\n","\"use strict\";\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\n// This file provides a low-level interface to a few V8 runtime objects. We will use this low-level\n// interface when serializing closures to walk the scope chain and find the value of free variables\n// captured by closures, as well as getting source-level debug information so that we can present\n// high-quality error messages.\n//\n// As a side-effect of importing this file, we must enable the --allow-natives-syntax V8 flag. This\n// is because we are using V8 intrinsics in order to implement this module.\nconst v8 = require(\"v8\");\nv8.setFlagsFromString(\"--allow-natives-syntax\");\nconst v8Hooks = require(\"./v8Hooks\");\nconst v8_v10andLower = require(\"./v8_v10andLower\");\nconst v8_v11andHigher = require(\"./v8_v11andHigher\");\n// Node majorly changed their introspection apis between 10.0 and 11.0 (removing outright some\n// of the APIs we use). Detect if we're before or after this change and delegate to the\nconst versionSpecificV8Module = v8Hooks.isNodeAtLeastV11 ? v8_v11andHigher : v8_v10andLower;\n/**\n * Given a function and a free variable name, lookupCapturedVariableValue looks up the value of that free variable\n * in the scope chain of the provided function. If the free variable is not found, `throwOnFailure` indicates\n * whether or not this function should throw or return `undefined.\n *\n * @param func The function whose scope chain is to be analyzed\n * @param freeVariable The name of the free variable to inspect\n * @param throwOnFailure If true, throws if the free variable can't be found.\n * @returns The value of the free variable. If `throwOnFailure` is false, returns `undefined` if not found.\n * @internal\n */\nexports.lookupCapturedVariableValueAsync = versionSpecificV8Module.lookupCapturedVariableValueAsync;\n/**\n * Given a function, returns the file, line and column number in the file where this function was\n * defined. Returns { \"\", 0, 0 } if the location cannot be found or if the given function has no Script.\n * @internal\n */\nexports.getFunctionLocationAsync = versionSpecificV8Module.getFunctionLocationAsync;\n","\"use strict\";\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n// Module that hooks into v8 and provides information about it to interested parties. Because this\n// hooks into v8 events it is critical that this module is loaded early when the process starts.\n// Otherwise, information may not be known when needed. This module is only intended for use on\n// Node v11 and higher.\nconst v8 = require(\"v8\");\nv8.setFlagsFromString(\"--allow-natives-syntax\");\nconst semver = require(\"semver\");\n// On node11 and above, create an 'inspector session' that can be used to keep track of what is\n// happening through a supported API. Pre-11 we can just call into % intrinsics for the same data.\n/** @internal */\nexports.isNodeAtLeastV11 = semver.gte(process.version, \"11.0.0\");\nconst session = exports.isNodeAtLeastV11\n ? createInspectorSessionAsync()\n : Promise.resolve(undefined);\nconst scriptIdToUrlMap = new Map();\nfunction createInspectorSessionAsync() {\n return __awaiter(this, void 0, void 0, function* () {\n // Delay loading 'inspector' as it is not available on early versions of node, so we can't\n // require it on the outside.\n const inspector = yield Promise.resolve().then(() => require(\"inspector\"));\n const inspectorSession = new inspector.Session();\n inspectorSession.connect();\n // Enable debugging support so we can hear about the Debugger.scriptParsed event. We need that\n // event to know how to map from scriptId's to file-urls.\n yield new Promise((resolve, reject) => {\n inspectorSession.post(\"Debugger.enable\", (err, res) => err ? reject(err) : resolve(res));\n });\n inspectorSession.addListener(\"Debugger.scriptParsed\", event => {\n const { scriptId, url } = event.params;\n scriptIdToUrlMap.set(scriptId, url);\n });\n return inspectorSession;\n });\n}\n/**\n * Returns the inspector session that can be used to query the state of this running Node instance.\n * Must only be called on Node11 and above. On Node10 and below, this will throw.\n * @internal\n */\nfunction getSessionAsync() {\n return __awaiter(this, void 0, void 0, function* () {\n if (!exports.isNodeAtLeastV11) {\n throw new Error(\"Should not call getSessionAsync unless on Node11 or above.\");\n }\n return session;\n });\n}\nexports.getSessionAsync = getSessionAsync;\n/**\n * Returns a promise that can be used to determine when the v8hooks have been injected properly and\n * code that depends on them can continue executing.\n * @internal\n */\nfunction isInitializedAsync() {\n return __awaiter(this, void 0, void 0, function* () {\n yield session;\n });\n}\nexports.isInitializedAsync = isInitializedAsync;\n/**\n * Maps from a script-id to the local file url it corresponds to.\n * @internal\n */\nfunction getScriptUrl(id) {\n return scriptIdToUrlMap.get(id);\n}\nexports.getScriptUrl = getScriptUrl;\n","\"use strict\";\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst semver = require(\"semver\");\nconst isNodeAtLeastV10 = semver.gte(process.version, \"10.0.0\");\n// `GetFunctionScopeDetails` returns a raw JavaScript array. This enum enumerates the objects that\n// are at specific indices of the array. We only care about one of these.\nvar V8ScopeDetailsFields;\n(function (V8ScopeDetailsFields) {\n V8ScopeDetailsFields[V8ScopeDetailsFields[\"kScopeDetailsTypeIndex\"] = 0] = \"kScopeDetailsTypeIndex\";\n V8ScopeDetailsFields[V8ScopeDetailsFields[\"kScopeDetailsObjectIndex\"] = 1] = \"kScopeDetailsObjectIndex\";\n V8ScopeDetailsFields[V8ScopeDetailsFields[\"kScopeDetailsNameIndex\"] = 2] = \"kScopeDetailsNameIndex\";\n V8ScopeDetailsFields[V8ScopeDetailsFields[\"kScopeDetailsStartPositionIndex\"] = 3] = \"kScopeDetailsStartPositionIndex\";\n V8ScopeDetailsFields[V8ScopeDetailsFields[\"kScopeDetailsEndPositionIndex\"] = 4] = \"kScopeDetailsEndPositionIndex\";\n V8ScopeDetailsFields[V8ScopeDetailsFields[\"kScopeDetailsFunctionIndex\"] = 5] = \"kScopeDetailsFunctionIndex\";\n})(V8ScopeDetailsFields || (V8ScopeDetailsFields = {}));\n/** @internal */\nfunction getFunctionLocationAsync(func) {\n return __awaiter(this, void 0, void 0, function* () {\n const script = getScript(func);\n const { line, column } = getLineColumn();\n return { file: script ? script.name : \"\", line, column };\n function getLineColumn() {\n if (script) {\n const pos = getSourcePosition(func);\n try {\n if (isNodeAtLeastV10) {\n return scriptPositionInfo(script, pos);\n }\n else {\n return script.locationFromPosition(pos);\n }\n }\n catch (err) {\n // Be resilient to native functions not being available. In this case, we just return\n // '0,0'. That's not great, but it at least lets us run, and it isn't a terrible\n // experience.\n //\n // Specifically, we only need these locations when we're printing out an error about not\n // being able to serialize something. In that case, we still print out the names of the\n // functions (as well as the call-tree that got us there), *and* we print out the body\n // of the function. With both of these, it is generally not too difficult to find out\n // where the code actually lives.\n }\n }\n return { line: 0, column: 0 };\n }\n });\n}\nexports.getFunctionLocationAsync = getFunctionLocationAsync;\nfunction getScript(func) {\n // The use of the Function constructor here and elsewhere in this file is because\n // because V8 intrinsics are not valid JavaScript identifiers; they all begin with '%',\n // which means that the TypeScript compiler issues errors for them.\n const scriptFunc = new Function(\"func\", \"return %FunctionGetScript(func);\");\n return scriptFunc(func);\n}\n// The second intrinsic is `FunctionGetScriptSourcePosition`, which does about what you'd\n// expect. It returns a `V8SourcePosition`, which can be passed to `V8Script::locationFromPosition`\n// to produce a `V8SourceLocation`.\nconst getSourcePosition = new Function(\"func\", \"return %FunctionGetScriptSourcePosition(func);\");\nfunction scriptPositionInfo(script, pos) {\n if (isNodeAtLeastV10) {\n const scriptPositionInfoFunc = new Function(\"script\", \"pos\", \"return %ScriptPositionInfo(script, pos, false);\");\n return scriptPositionInfoFunc(script, pos);\n }\n // Should not be called if running on Node<10.0.0.\n return undefined;\n}\n/** @internal */\nfunction lookupCapturedVariableValueAsync(func, freeVariable, throwOnFailure) {\n return __awaiter(this, void 0, void 0, function* () {\n // The implementation of this function is now very straightforward since the intrinsics do all of the\n // difficult work.\n const count = getFunctionScopeCount(func);\n for (let i = 0; i < count; i++) {\n const scope = getScopeForFunction(func, i);\n if (freeVariable in scope.scopeObject) {\n return scope.scopeObject[freeVariable];\n }\n }\n if (throwOnFailure) {\n throw new Error(\"Unexpected missing variable in closure environment: \" + freeVariable);\n }\n return undefined;\n });\n}\nexports.lookupCapturedVariableValueAsync = lookupCapturedVariableValueAsync;\n// The last two intrinsics are `GetFunctionScopeCount` and `GetFunctionScopeDetails`.\n// The former function returns the number of scopes in a given function's scope chain, while\n// the latter function returns the i'th entry in a function's scope chain, given a function and\n// index i.\nfunction getFunctionScopeDetails(func, index) {\n const getFunctionScopeDetailsFunc = new Function(\"func\", \"index\", \"return %GetFunctionScopeDetails(func, index);\");\n return getFunctionScopeDetailsFunc(func, index);\n}\nfunction getFunctionScopeCount(func) {\n const getFunctionScopeCountFunc = new Function(\"func\", \"return %GetFunctionScopeCount(func);\");\n return getFunctionScopeCountFunc(func);\n}\n// getScopeForFunction extracts a V8ScopeDetails for the index'th element in the scope chain for the\n// given function.\nfunction getScopeForFunction(func, index) {\n const scopeDetails = getFunctionScopeDetails(func, index);\n return {\n scopeObject: scopeDetails[V8ScopeDetailsFields.kScopeDetailsObjectIndex],\n };\n}\n// All of these functions contain syntax that is not legal TS/JS (i.e. \"%Whatever\"). As such,\n// we cannot serialize them. In case they somehow get captured, just block them from closure\n// serialization entirely.\ngetScript.doNotCapture = true;\ngetSourcePosition.doNotCapture = true;\ngetFunctionScopeDetails.doNotCapture = true;\ngetFunctionScopeCount.doNotCapture = true;\n","\"use strict\";\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst util = require(\"util\");\nconst v8Hooks = require(\"./v8Hooks\");\n/** @internal */\nfunction getFunctionLocationAsync(func) {\n return __awaiter(this, void 0, void 0, function* () {\n // First, find the runtime's internal id for this function.\n const functionId = yield getRuntimeIdForFunctionAsync(func);\n // Now, query for the internal properties the runtime sets up for it.\n const { internalProperties } = yield runtimeGetPropertiesAsync(functionId, /*ownProperties:*/ false);\n // There should normally be an internal property called [[FunctionLocation]]:\n // https://chromium.googlesource.com/v8/v8.git/+/3f99afc93c9ba1ba5df19f123b93cc3079893c9b/src/inspector/v8-debugger.cc#793\n const functionLocation = internalProperties.find(p => p.name === \"[[FunctionLocation]]\");\n if (!functionLocation || !functionLocation.value || !functionLocation.value.value) {\n return { file: \"\", line: 0, column: 0 };\n }\n const value = functionLocation.value.value;\n // Map from the scriptId the value has to a file-url.\n const file = v8Hooks.getScriptUrl(value.scriptId) || \"\";\n const line = value.lineNumber || 0;\n const column = value.columnNumber || 0;\n return { file, line, column };\n });\n}\nexports.getFunctionLocationAsync = getFunctionLocationAsync;\n/** @internal */\nfunction lookupCapturedVariableValueAsync(func, freeVariable, throwOnFailure) {\n return __awaiter(this, void 0, void 0, function* () {\n // First, find the runtime's internal id for this function.\n const functionId = yield getRuntimeIdForFunctionAsync(func);\n // Now, query for the internal properties the runtime sets up for it.\n const { internalProperties } = yield runtimeGetPropertiesAsync(functionId, /*ownProperties:*/ false);\n // There should normally be an internal property called [[Scopes]]:\n // https://chromium.googlesource.com/v8/v8.git/+/3f99afc93c9ba1ba5df19f123b93cc3079893c9b/src/inspector/v8-debugger.cc#820\n const scopes = internalProperties.find(p => p.name === \"[[Scopes]]\");\n if (!scopes) {\n throw new Error(\"Could not find [[Scopes]] property\");\n }\n if (!scopes.value) {\n throw new Error(\"[[Scopes]] property did not have [value]\");\n }\n if (!scopes.value.objectId) {\n throw new Error(\"[[Scopes]].value have objectId\");\n }\n // This is sneaky, but we can actually map back from the [[Scopes]] object to a real in-memory\n // v8 array-like value. Note: this isn't actually a real array. For example, it cannot be\n // iterated. Nor can any actual methods be called on it. However, we can directly index into\n // it, and we can. Similarly, the 'object' type it optionally points at is not a true JS\n // object. So we can't call things like .hasOwnProperty on it. However, the values pointed to\n // by 'object' are the real in-memory JS objects we are looking for. So we can find and return\n // those successfully to our caller.\n const scopesArray = yield getValueForObjectId(scopes.value.objectId);\n // scopesArray is ordered from innermost to outermost.\n for (let i = 0, n = scopesArray.length; i < n; i++) {\n const scope = scopesArray[i];\n if (scope.object) {\n if (freeVariable in scope.object) {\n const val = scope.object[freeVariable];\n return val;\n }\n }\n }\n if (throwOnFailure) {\n throw new Error(\"Unexpected missing variable in closure environment: \" + freeVariable);\n }\n return undefined;\n });\n}\nexports.lookupCapturedVariableValueAsync = lookupCapturedVariableValueAsync;\nfunction getRuntimeIdForFunctionAsync(func) {\n return __awaiter(this, void 0, void 0, function* () {\n // In order to get information about an object, we need to put it in a well known location so\n // that we can call Runtime.evaluate and find it. To do this, we just make a special map on the\n // 'global' object, and map from a unique-id to that object. We then call Runtime.evaluate with\n // an expression that then points to that unique-id in that global object. The runtime will\n // then find the object and give us back an internal id for it. We can then query for\n // information about the object through that internal id.\n //\n // Note: the reason for the mapping object and the unique-id we create is so that we don't run\n // into any issues when being called asynchronously. We don't want to place the object in a\n // location that might be overwritten by another call while we're asynchronously waiting for our\n // original call to complete.\n //\n // We also lazily initialize this in case pulumi has been loaded through another module and has\n // already initialize this global state.\n const globalAny = global;\n if (!globalAny.__inflightFunctions) {\n globalAny.__inflightFunctions = {};\n globalAny.__currentFunctionId = 0;\n }\n // Place the function in a unique location off of the global object.\n const currentFunctionName = \"id\" + globalAny.__currentFunctionId++;\n globalAny.__inflightFunctions[currentFunctionName] = func;\n try {\n const session = yield v8Hooks.getSessionAsync();\n const post = util.promisify(session.post);\n const expression = `global.__inflightFunctions.${currentFunctionName}`;\n // This cast will become unnecessary when we move to TS 3.1.6 or above. In that version they\n // support typesafe '.call' calls.\n const retType = yield post.call(session, \"Runtime.evaluate\", { expression });\n if (retType.exceptionDetails) {\n throw new Error(`Error calling \"Runtime.evaluate(${expression})\": ` + retType.exceptionDetails.text);\n }\n const remoteObject = retType.result;\n if (remoteObject.type !== \"function\") {\n throw new Error(\"Remote object was not 'function': \" + JSON.stringify(remoteObject));\n }\n if (!remoteObject.objectId) {\n throw new Error(\"Remote function does not have 'objectId': \" + JSON.stringify(remoteObject));\n }\n return remoteObject.objectId;\n }\n finally {\n delete globalAny.__inflightFunctions[currentFunctionName];\n }\n });\n}\nfunction runtimeGetPropertiesAsync(objectId, ownProperties) {\n return __awaiter(this, void 0, void 0, function* () {\n const session = yield v8Hooks.getSessionAsync();\n const post = util.promisify(session.post);\n // This cast will become unnecessary when we move to TS 3.1.6 or above. In that version they\n // support typesafe '.call' calls.\n const retType = yield post.call(session, \"Runtime.getProperties\", { objectId, ownProperties });\n if (retType.exceptionDetails) {\n throw new Error(`Error calling \"Runtime.getProperties(${objectId}, ${ownProperties})\": `\n + retType.exceptionDetails.text);\n }\n return { internalProperties: retType.internalProperties || [], properties: retType.result };\n });\n}\nfunction getValueForObjectId(objectId) {\n return __awaiter(this, void 0, void 0, function* () {\n // In order to get the raw JS value for the *remote wrapper* of the [[Scopes]] array, we use\n // Runtime.callFunctionOn on it passing in a fresh function-declaration. The Node runtime will\n // then compile that function, invoking it with the 'real' underlying scopes-array value in\n // memory as the bound 'this' value. Inside that function declaration, we can then access\n // 'this' and assign it to a unique-id in a well known mapping table we have set up. As above,\n // the unique-id is to prevent any issues with multiple in-flight asynchronous calls.\n //\n // We also lazily initialize this in case pulumi has been loaded through another module and has\n // already initialize this global state.\n const globalAny = global;\n if (!globalAny.__inflightCalls) {\n globalAny.__inflightCalls = {};\n globalAny.__currentCallId = 0;\n }\n const session = yield v8Hooks.getSessionAsync();\n const post = util.promisify(session.post);\n // Get an id for an unused location in the global table.\n const tableId = \"id\" + globalAny.__currentCallId++;\n // Now, ask the runtime to call a fictitious method on the scopes-array object. When it\n // does, it will get the actual underlying value for the scopes array and bind it to the\n // 'this' value inside the function. Inside the function we then just grab 'this' and\n // stash it in our global table. After this completes, we'll then have access to it.\n // This cast will become unnecessary when we move to TS 3.1.6 or above. In that version they\n // support typesafe '.call' calls.\n const retType = yield post.call(session, \"Runtime.callFunctionOn\", {\n objectId,\n functionDeclaration: `function () {\n global.__inflightCalls[\"${tableId}\"] = this;\n }`,\n });\n if (retType.exceptionDetails) {\n throw new Error(`Error calling \"Runtime.callFunction(${objectId})\": `\n + retType.exceptionDetails.text);\n }\n if (!globalAny.__inflightCalls.hasOwnProperty(tableId)) {\n throw new Error(`Value was not stored into table after calling \"Runtime.callFunctionOn(${objectId})\"`);\n }\n // Extract value and clear our table entry.\n const val = globalAny.__inflightCalls[tableId];\n delete globalAny.__inflightCalls[tableId];\n return val;\n });\n}\n","\"use strict\";\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * configEnvKey is the environment variable key that the language plugin uses to set configuration values.\n */\nconst configEnvKey = \"PULUMI_CONFIG\";\n/**\n * allConfig returns a copy of the full config map.\n */\nfunction allConfig() {\n const config = parseConfig();\n return Object.assign({}, config);\n}\nexports.allConfig = allConfig;\n/**\n * setAllConfig overwrites the config map.\n */\nfunction setAllConfig(c) {\n const obj = {};\n for (const k of Object.keys(c)) {\n obj[cleanKey(k)] = c[k];\n }\n persistConfig(obj);\n}\nexports.setAllConfig = setAllConfig;\n/**\n * setConfig sets a configuration variable.\n */\nfunction setConfig(k, v) {\n const config = parseConfig();\n config[cleanKey(k)] = v;\n persistConfig(config);\n}\nexports.setConfig = setConfig;\n/**\n * getConfig returns a configuration variable's value or undefined if it is unset.\n */\nfunction getConfig(k) {\n const config = parseConfig();\n return config[k];\n}\nexports.getConfig = getConfig;\n/**\n * parseConfig reads config from the source of truth, the environment.\n * config must always be read this way because automation api introduces\n * new program lifetime semantics where program lifetime != module lifetime.\n */\nfunction parseConfig() {\n const parsedConfig = {};\n const envConfig = process.env[configEnvKey];\n if (envConfig) {\n const envObject = JSON.parse(envConfig);\n for (const k of Object.keys(envObject)) {\n parsedConfig[cleanKey(k)] = envObject[k];\n }\n }\n return parsedConfig;\n}\n/**\n * persistConfig writes config to the environment.\n * config changes must always be persisted to the environment because automation api introduces\n * new program lifetime semantics where program lifetime != module lifetime.\n */\nfunction persistConfig(config) {\n const serializedConfig = JSON.stringify(config);\n process.env[configEnvKey] = serializedConfig;\n}\n/**\n * cleanKey takes a configuration key, and if it is of the form \":config:\" removes\n * the \":config:\" portion. Previously, our keys always had the string \":config:\" in them, and we'd\n * like to remove it. However, the language host needs to continue to set it so we can be compatible\n * with older versions of our packages. Once we stop supporting older packages, we can change the\n * language host to not add this :config: thing and remove this function.\n */\nfunction cleanKey(key) {\n const idx = key.indexOf(\":\");\n if (idx > 0 && key.startsWith(\"config:\", idx + 1)) {\n return key.substring(0, idx) + \":\" + key.substring(idx + 1 + \"config:\".length);\n }\n return key;\n}\n","\"use strict\";\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst log = require(\"../log\");\n/**\n * debugPromiseLeaks can be set to enable promises leaks debugging.\n */\nconst debugPromiseLeaks = !!process.env.PULUMI_DEBUG_PROMISE_LEAKS;\n/**\n * leakDetectorScheduled is true when the promise leak detector is scheduled for process exit.\n */\nlet leakDetectorScheduled = false;\n/**\n * leakCandidates tracks the list of potential leak candidates.\n */\nlet leakCandidates = new Set();\nfunction leakedPromises() {\n const leaked = leakCandidates;\n const promisePlural = leaked.size === 0 ? \"promise was\" : \"promises were\";\n const message = leaked.size === 0 ? \"\" :\n `The Pulumi runtime detected that ${leaked.size} ${promisePlural} still active\\n` +\n \"at the time that the process exited. There are a few ways that this can occur:\\n\" +\n \" * Not using `await` or `.then` on a Promise returned from a Pulumi API\\n\" +\n \" * Introducing a cyclic dependency between two Pulumi Resources\\n\" +\n \" * A bug in the Pulumi Runtime\\n\" +\n \"\\n\" +\n \"Leaving promises active is probably not what you want. If you are unsure about\\n\" +\n \"why you are seeing this message, re-run your program \"\n + \"with the `PULUMI_DEBUG_PROMISE_LEAKS`\\n\" +\n \"environment variable. The Pulumi runtime will then print out additional\\n\" +\n \"debug information about the leaked promises.\";\n if (debugPromiseLeaks) {\n for (const leak of leaked) {\n console.error(\"Promise leak detected:\");\n console.error(promiseDebugString(leak));\n }\n }\n leakCandidates = new Set();\n return [leaked, message];\n}\nexports.leakedPromises = leakedPromises;\nfunction promiseDebugString(p) {\n return `CONTEXT(${p._debugId}): ${p._debugCtx}\\n` +\n `STACK_TRACE:\\n` +\n `${p._debugStackTrace}`;\n}\nexports.promiseDebugString = promiseDebugString;\nlet promiseId = 0;\n/**\n * debuggablePromise optionally wraps a promise with some goo to make it easier to debug common problems.\n * @internal\n */\nfunction debuggablePromise(p, ctx) {\n // Whack some stack onto the promise. Leave them non-enumerable to avoid awkward rendering.\n Object.defineProperty(p, \"_debugId\", { writable: true, value: promiseId });\n Object.defineProperty(p, \"_debugCtx\", { writable: true, value: ctx });\n Object.defineProperty(p, \"_debugStackTrace\", { writable: true, value: new Error().stack });\n promiseId++;\n if (!leakDetectorScheduled) {\n process.on(\"exit\", (code) => {\n // Only print leaks if we're exiting normally. Otherwise, it could be a crash, which of\n // course yields things that look like \"leaks\".\n //\n // process.exitCode is undefined unless set, in which case it's the exit code that was\n // passed to process.exit.\n if ((process.exitCode === undefined || process.exitCode === 0) && !log.hasErrors()) {\n const [leaks, message] = leakedPromises();\n if (leaks.size === 0) {\n // No leaks - proceed with the exit.\n return;\n }\n // If we haven't opted-in to the debug error message, print a more user-friendly message.\n if (!debugPromiseLeaks) {\n console.error(message);\n }\n // Fail the deployment if we leaked any promises.\n process.exitCode = 1;\n }\n });\n leakDetectorScheduled = true;\n }\n // Add this promise to the leak candidates list, and schedule it for removal if it resolves.\n leakCandidates.add(p);\n return p.then((val) => {\n leakCandidates.delete(p);\n return val;\n }).catch((err) => {\n leakCandidates.delete(p);\n err.promise = p;\n throw err;\n });\n}\nexports.debuggablePromise = debuggablePromise;\nprocess.on(\"unhandledRejection\", err => {\n if (err && err.promise) {\n console.log(`unhandled rejection: ${promiseDebugString(err.promise)}`);\n }\n});\n/**\n * errorString produces a string from an error, conditionally including additional diagnostics.\n * @internal\n */\nfunction errorString(err) {\n if (err.stack) {\n return err.stack;\n }\n return err.toString();\n}\nexports.errorString = errorString;\n","\"use strict\";\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar serializeClosure_1 = require(\"./closure/serializeClosure\");\nexports.serializeFunctionAsync = serializeClosure_1.serializeFunctionAsync;\nexports.serializeFunction = serializeClosure_1.serializeFunction;\nvar codePaths_1 = require(\"./closure/codePaths\");\nexports.computeCodePaths = codePaths_1.computeCodePaths;\nvar debuggable_1 = require(\"./debuggable\");\nexports.leakedPromises = debuggable_1.leakedPromises;\nvar mocks_1 = require(\"./mocks\");\nexports.setMocks = mocks_1.setMocks;\n__export(require(\"./config\"));\n__export(require(\"./invoke\"));\n__export(require(\"./resource\"));\n__export(require(\"./rpc\"));\n__export(require(\"./settings\"));\n__export(require(\"./stack\"));\n","\"use strict\";\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst grpc = require(\"@grpc/grpc-js\");\nconst log = require(\"../log\");\nconst debuggable_1 = require(\"./debuggable\");\nconst rpc_1 = require(\"./rpc\");\nconst settings_1 = require(\"./settings\");\nconst resource_1 = require(\"../resource\");\nconst utils = require(\"../utils\");\nconst asyncIterableUtil_1 = require(\"./asyncIterableUtil\");\nconst gstruct = require(\"google-protobuf/google/protobuf/struct_pb.js\");\nconst providerproto = require(\"../proto/provider_pb.js\");\n/**\n * `invoke` dynamically invokes the function, `tok`, which is offered by a provider plugin. `invoke`\n * behaves differently in the case that options contains `{async:true}` or not.\n *\n * In the case where `{async:true}` is present in the options bag:\n *\n * 1. the result of `invoke` will be a Promise resolved to the result value of the provider plugin.\n * 2. the `props` inputs can be a bag of computed values (including, `T`s, `Promise`s,\n * `Output`s etc.).\n *\n *\n * In the case where `{async:true}` is not present in the options bag:\n *\n * 1. the result of `invoke` will be a Promise resolved to the result value of the provider call.\n * However, that Promise will *also* have the respective values of the Provider result exposed\n * directly on it as properties.\n *\n * 2. The inputs must be a bag of simple values, and the result is the result that the Provider\n * produced.\n *\n * Simple values are:\n * 1. `undefined`, `null`, string, number or boolean values.\n * 2. arrays of simple values.\n * 3. objects containing only simple values.\n *\n * Importantly, simple values do *not* include:\n * 1. `Promise`s\n * 2. `Output`s\n * 3. `Asset`s or `Archive`s\n * 4. `Resource`s.\n *\n * All of these contain async values that would prevent `invoke from being able to operate\n * synchronously.\n */\nfunction invoke(tok, props, opts = {}) {\n return invokeAsync(tok, props, opts);\n}\nexports.invoke = invoke;\nfunction streamInvoke(tok, props, opts = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n const label = `StreamInvoking function: tok=${tok} asynchronously`;\n log.debug(label + (settings_1.excessiveDebugOutput ? `, props=${JSON.stringify(props)}` : ``));\n // Wait for all values to be available, and then perform the RPC.\n const done = settings_1.rpcKeepAlive();\n try {\n const serialized = yield rpc_1.serializeProperties(`streamInvoke:${tok}`, props);\n log.debug(`StreamInvoke RPC prepared: tok=${tok}` + settings_1.excessiveDebugOutput\n ? `, obj=${JSON.stringify(serialized)}`\n : ``);\n // Fetch the monitor and make an RPC request.\n const monitor = settings_1.getMonitor();\n const provider = yield resource_1.ProviderResource.register(getProvider(tok, opts));\n const req = createInvokeRequest(tok, serialized, provider, opts);\n // Call `streamInvoke`.\n const call = monitor.streamInvoke(req, {});\n const queue = new asyncIterableUtil_1.PushableAsyncIterable();\n call.on(\"data\", function (thing) {\n const live = deserializeResponse(tok, thing);\n queue.push(live);\n });\n call.on(\"error\", (err) => {\n if (err.code === 1) {\n return;\n }\n throw err;\n });\n call.on(\"end\", () => {\n queue.complete();\n });\n // Return a cancellable handle to the stream.\n return new StreamInvokeResponse(queue, () => call.cancel());\n }\n finally {\n done();\n }\n });\n}\nexports.streamInvoke = streamInvoke;\nfunction invokeAsync(tok, props, opts) {\n return __awaiter(this, void 0, void 0, function* () {\n const label = `Invoking function: tok=${tok} asynchronously`;\n log.debug(label + (settings_1.excessiveDebugOutput ? `, props=${JSON.stringify(props)}` : ``));\n // Wait for all values to be available, and then perform the RPC.\n const done = settings_1.rpcKeepAlive();\n try {\n const serialized = yield rpc_1.serializeProperties(`invoke:${tok}`, props);\n log.debug(`Invoke RPC prepared: tok=${tok}` + settings_1.excessiveDebugOutput ? `, obj=${JSON.stringify(serialized)}` : ``);\n // Fetch the monitor and make an RPC request.\n const monitor = settings_1.getMonitor();\n const provider = yield resource_1.ProviderResource.register(getProvider(tok, opts));\n const req = createInvokeRequest(tok, serialized, provider, opts);\n const resp = yield debuggable_1.debuggablePromise(new Promise((innerResolve, innerReject) => monitor.invoke(req, (err, innerResponse) => {\n log.debug(`Invoke RPC finished: tok=${tok}; err: ${err}, resp: ${innerResponse}`);\n if (err) {\n // If the monitor is unavailable, it is in the process of shutting down or has already\n // shut down. Don't emit an error and don't do any more RPCs, just exit.\n if (err.code === grpc.status.UNAVAILABLE || err.code === grpc.status.CANCELLED) {\n settings_1.terminateRpcs();\n err.message = \"Resource monitor is terminating\";\n innerReject(err);\n return;\n }\n // If the RPC failed, rethrow the error with a native exception and the message that\n // the engine provided - it's suitable for user presentation.\n innerReject(new Error(err.details));\n }\n else {\n innerResolve(innerResponse);\n }\n })), label);\n // Finally propagate any other properties that were given to us as outputs.\n return deserializeResponse(tok, resp);\n }\n finally {\n done();\n }\n });\n}\n// StreamInvokeResponse represents a (potentially infinite) streaming response to `streamInvoke`,\n// with facilities to gracefully cancel and clean up the stream.\nclass StreamInvokeResponse {\n constructor(source, cancelSource) {\n this.source = source;\n this.cancelSource = cancelSource;\n }\n // cancel signals the `streamInvoke` should be cancelled and cleaned up gracefully.\n cancel() {\n this.cancelSource();\n }\n [Symbol.asyncIterator]() {\n return this.source[Symbol.asyncIterator]();\n }\n}\nexports.StreamInvokeResponse = StreamInvokeResponse;\nfunction createInvokeRequest(tok, serialized, provider, opts) {\n if (provider !== undefined && typeof provider !== \"string\") {\n throw new Error(\"Incorrect provider type.\");\n }\n const obj = gstruct.Struct.fromJavaScript(serialized);\n const req = new providerproto.InvokeRequest();\n req.setTok(tok);\n req.setArgs(obj);\n req.setProvider(provider);\n req.setVersion(opts.version || \"\");\n req.setAcceptresources(!utils.disableResourceReferences);\n return req;\n}\nfunction getProvider(tok, opts) {\n return opts.provider ? opts.provider :\n opts.parent ? opts.parent.getProvider(tok) : undefined;\n}\nfunction deserializeResponse(tok, resp) {\n const failures = resp.getFailuresList();\n if (failures && failures.length) {\n let reasons = \"\";\n for (let i = 0; i < failures.length; i++) {\n if (reasons !== \"\") {\n reasons += \"; \";\n }\n reasons += `${failures[i].getReason()} (${failures[i].getProperty()})`;\n }\n throw new Error(`Invoke of '${tok}' failed: ${reasons}`);\n }\n const ret = resp.getReturn();\n return ret === undefined\n ? ret\n : rpc_1.deserializeProperties(ret);\n}\n","\"use strict\";\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst rpc_1 = require(\"./rpc\");\nconst settings_1 = require(\"./settings\");\nconst provproto = require(\"../proto/provider_pb.js\");\nconst resproto = require(\"../proto/resource_pb.js\");\nconst structproto = require(\"google-protobuf/google/protobuf/struct_pb.js\");\nclass MockMonitor {\n constructor(mocks) {\n this.mocks = mocks;\n this.resources = new Map();\n }\n newUrn(parent, type, name) {\n if (parent) {\n const qualifiedType = parent.split(\"::\")[2];\n const parentType = qualifiedType.split(\"$\").pop();\n type = parentType + \"$\" + type;\n }\n return \"urn:pulumi:\" + [settings_1.getStack(), settings_1.getProject(), type, name].join(\"::\");\n }\n invoke(req, callback) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n const tok = req.getTok();\n const inputs = rpc_1.deserializeProperties(req.getArgs());\n if (tok === \"pulumi:pulumi:getResource\") {\n const registeredResource = this.resources.get(inputs.urn);\n if (!registeredResource) {\n throw new Error(`unknown resource ${inputs.urn}`);\n }\n const resp = new provproto.InvokeResponse();\n resp.setReturn(structproto.Struct.fromJavaScript(registeredResource));\n callback(null, resp);\n return;\n }\n const result = this.mocks.call(tok, inputs, req.getProvider());\n const response = new provproto.InvokeResponse();\n response.setReturn(structproto.Struct.fromJavaScript(yield rpc_1.serializeProperties(\"\", result)));\n callback(null, response);\n }\n catch (err) {\n callback(err, undefined);\n }\n });\n }\n readResource(req, callback) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n const result = this.mocks.newResource(req.getType(), req.getName(), rpc_1.deserializeProperties(req.getProperties()), req.getProvider(), req.getId());\n const urn = this.newUrn(req.getParent(), req.getType(), req.getName());\n const serializedState = yield rpc_1.serializeProperties(\"\", result.state);\n this.resources.set(urn, { urn, id: result.id, state: serializedState });\n const response = new resproto.ReadResourceResponse();\n response.setUrn(urn);\n response.setProperties(structproto.Struct.fromJavaScript(serializedState));\n callback(null, response);\n }\n catch (err) {\n callback(err, undefined);\n }\n });\n }\n registerResource(req, callback) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n const result = this.mocks.newResource(req.getType(), req.getName(), rpc_1.deserializeProperties(req.getObject()), req.getProvider(), req.getImportid());\n const urn = this.newUrn(req.getParent(), req.getType(), req.getName());\n const serializedState = yield rpc_1.serializeProperties(\"\", result.state);\n this.resources.set(urn, { urn, id: result.id, state: serializedState });\n const response = new resproto.RegisterResourceResponse();\n response.setUrn(urn);\n response.setId(result.id);\n response.setObject(structproto.Struct.fromJavaScript(serializedState));\n callback(null, response);\n }\n catch (err) {\n callback(err, undefined);\n }\n });\n }\n registerResourceOutputs(req, callback) {\n try {\n const registeredResource = this.resources.get(req.getUrn());\n if (!registeredResource) {\n throw new Error(`unknown resource ${req.getUrn()}`);\n }\n registeredResource.state = req.getOutputs();\n callback(null, {});\n }\n catch (err) {\n callback(err, undefined);\n }\n }\n supportsFeature(req, callback) {\n callback(null, {\n getHassupport: () => true,\n });\n }\n}\nexports.MockMonitor = MockMonitor;\n/**\n * setMocks configures the Pulumi runtime to use the given mocks for testing.\n *\n * @param mocks: The mocks to use for calls to provider functions and resource consrtuction.\n * @param project: If provided, the name of the Pulumi project. Defaults to \"project\".\n * @param stack: If provided, the name of the Pulumi stack. Defaults to \"stack\".\n * @param preview: If provided, indicates whether or not the program is running a preview. Defaults to false.\n */\nfunction setMocks(mocks, project, stack, preview) {\n settings_1.setMockOptions(new MockMonitor(mocks), project, stack, preview);\n}\nexports.setMocks = setMocks;\n","\"use strict\";\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst grpc = require(\"@grpc/grpc-js\");\nconst query = require(\"@pulumi/query\");\nconst log = require(\"../log\");\nconst utils = require(\"../utils\");\nconst output_1 = require(\"../output\");\nconst resource_1 = require(\"../resource\");\nconst debuggable_1 = require(\"./debuggable\");\nconst invoke_1 = require(\"./invoke\");\nconst rpc_1 = require(\"./rpc\");\nconst settings_1 = require(\"./settings\");\nconst gstruct = require(\"google-protobuf/google/protobuf/struct_pb.js\");\nconst providerproto = require(\"../proto/provider_pb.js\");\nconst resproto = require(\"../proto/resource_pb.js\");\n/**\n * Get an existing resource's state from the engine.\n */\nfunction getResource(res, props, custom, urn) {\n // Extract the resource type from the URN.\n const urnParts = urn.split(\"::\");\n const qualifiedType = urnParts[2];\n const urnName = urnParts[3];\n const type = qualifiedType.split(\"$\").pop();\n const label = `resource:urn=${urn}`;\n log.debug(`Getting resource: urn=${urn}`);\n const monitor = settings_1.getMonitor();\n const resopAsync = prepareResource(label, res, custom, props, {});\n const preallocError = new Error();\n debuggable_1.debuggablePromise(resopAsync.then((resop) => __awaiter(this, void 0, void 0, function* () {\n const inputs = yield rpc_1.serializeProperties(label, { urn });\n const req = new providerproto.InvokeRequest();\n req.setTok(\"pulumi:pulumi:getResource\");\n req.setArgs(gstruct.Struct.fromJavaScript(inputs));\n req.setProvider(\"\");\n req.setVersion(\"\");\n // Now run the operation, serializing the invocation if necessary.\n const opLabel = `monitor.getResource(${label})`;\n runAsyncResourceOp(opLabel, () => __awaiter(this, void 0, void 0, function* () {\n let resp;\n let err;\n try {\n if (monitor) {\n resp = yield debuggable_1.debuggablePromise(new Promise((resolve, reject) => monitor.invoke(req, (rpcError, innerResponse) => {\n log.debug(`getResource Invoke RPC finished: err: ${rpcError}, resp: ${innerResponse}`);\n if (rpcError) {\n if (rpcError.code === grpc.status.UNAVAILABLE || rpcError.code === grpc.status.CANCELLED) {\n err = rpcError;\n settings_1.terminateRpcs();\n rpcError.message = \"Resource monitor is terminating\";\n preallocError.code = rpcError.code;\n }\n preallocError.message = `failed to get resource:urn=${urn}: ${rpcError.message}`;\n reject(new Error(rpcError.details));\n }\n else {\n resolve(innerResponse);\n }\n })), opLabel);\n // If the invoke failed, raise an error\n const failures = resp.getFailuresList();\n if (failures && failures.length) {\n let reasons = \"\";\n for (let i = 0; i < failures.length; i++) {\n if (reasons !== \"\") {\n reasons += \"; \";\n }\n reasons += `${failures[i].getReason()} (${failures[i].getProperty()})`;\n }\n throw new Error(`getResource Invoke failed: ${reasons}`);\n }\n // Otherwise, return the response.\n const m = resp.getReturn().getFieldsMap();\n resp = {\n urn: m.get(\"urn\").toJavaScript(),\n id: m.get(\"id\").toJavaScript() || undefined,\n state: m.get(\"state\").getStructValue(),\n };\n }\n }\n catch (e) {\n err = e;\n resp = {\n urn: \"\",\n id: undefined,\n state: undefined,\n };\n }\n resop.resolveURN(resp.urn, err);\n // Note: 'id || undefined' is intentional. We intentionally collapse falsy values to\n // undefined so that later parts of our system don't have to deal with values like 'null'.\n if (resop.resolveID) {\n const id = resp.id || undefined;\n resop.resolveID(id, id !== undefined, err);\n }\n yield resolveOutputs(res, type, urnName, props, resp.state, {}, resop.resolvers, err);\n }));\n })), label);\n}\nexports.getResource = getResource;\n/**\n * Reads an existing custom resource's state from the resource monitor. Note that resources read in this way\n * will not be part of the resulting stack's state, as they are presumed to belong to another.\n */\nfunction readResource(res, t, name, props, opts) {\n const id = opts.id;\n if (!id) {\n throw new Error(\"Cannot read resource whose options are lacking an ID value\");\n }\n const label = `resource:${name}[${t}]#...`;\n log.debug(`Reading resource: id=${output_1.Output.isInstance(id) ? \"Output\" : id}, t=${t}, name=${name}`);\n const monitor = settings_1.getMonitor();\n const resopAsync = prepareResource(label, res, true, props, opts);\n const preallocError = new Error();\n debuggable_1.debuggablePromise(resopAsync.then((resop) => __awaiter(this, void 0, void 0, function* () {\n const resolvedID = yield rpc_1.serializeProperty(label, id, new Set());\n log.debug(`ReadResource RPC prepared: id=${resolvedID}, t=${t}, name=${name}` +\n (settings_1.excessiveDebugOutput ? `, obj=${JSON.stringify(resop.serializedProps)}` : ``));\n // Create a resource request and do the RPC.\n const req = new resproto.ReadResourceRequest();\n req.setType(t);\n req.setName(name);\n req.setId(resolvedID);\n req.setParent(resop.parentURN);\n req.setProvider(resop.providerRef);\n req.setProperties(gstruct.Struct.fromJavaScript(resop.serializedProps));\n req.setDependenciesList(Array.from(resop.allDirectDependencyURNs));\n req.setVersion(opts.version || \"\");\n req.setAcceptsecrets(true);\n req.setAcceptresources(!utils.disableResourceReferences);\n req.setAdditionalsecretoutputsList(opts.additionalSecretOutputs || []);\n // Now run the operation, serializing the invocation if necessary.\n const opLabel = `monitor.readResource(${label})`;\n runAsyncResourceOp(opLabel, () => __awaiter(this, void 0, void 0, function* () {\n let resp;\n let err;\n try {\n if (monitor) {\n // If we're attached to the engine, make an RPC call and wait for it to resolve.\n resp = yield debuggable_1.debuggablePromise(new Promise((resolve, reject) => monitor.readResource(req, (rpcError, innerResponse) => {\n log.debug(`ReadResource RPC finished: ${label}; err: ${rpcError}, resp: ${innerResponse}`);\n if (rpcError) {\n if (rpcError.code === grpc.status.UNAVAILABLE || rpcError.code === grpc.status.CANCELLED) {\n err = rpcError;\n settings_1.terminateRpcs();\n rpcError.message = \"Resource monitor is terminating\";\n preallocError.code = rpcError.code;\n }\n preallocError.message =\n `failed to read resource #${resolvedID} '${name}' [${t}]: ${rpcError.message}`;\n reject(preallocError);\n }\n else {\n resolve(innerResponse);\n }\n })), opLabel);\n }\n else {\n // If we aren't attached to the engine, in test mode, mock up a fake response for testing purposes.\n const mockurn = yield resource_1.createUrn(req.getName(), req.getType(), req.getParent()).promise();\n resp = {\n getUrn: () => mockurn,\n getProperties: () => req.getProperties(),\n };\n }\n }\n catch (e) {\n err = e;\n resp = {\n getUrn: () => \"\",\n getProperties: () => undefined,\n };\n }\n // Now resolve everything: the URN, the ID (supplied as input), and the output properties.\n resop.resolveURN(resp.getUrn(), err);\n resop.resolveID(resolvedID, resolvedID !== undefined, err);\n yield resolveOutputs(res, t, name, props, resp.getProperties(), {}, resop.resolvers, err);\n }));\n })), label);\n}\nexports.readResource = readResource;\n/**\n * registerResource registers a new resource object with a given type t and name. It returns the auto-generated\n * URN and the ID that will resolve after the deployment has completed. All properties will be initialized to property\n * objects that the registration operation will resolve at the right time (or remain unresolved for deployments).\n */\nfunction registerResource(res, t, name, custom, remote, newDependency, props, opts) {\n const label = `resource:${name}[${t}]`;\n log.debug(`Registering resource: t=${t}, name=${name}, custom=${custom}, remote=${remote}`);\n const monitor = settings_1.getMonitor();\n const resopAsync = prepareResource(label, res, custom, props, opts);\n // In order to present a useful stack trace if an error does occur, we preallocate potential\n // errors here. V8 captures a stack trace at the moment an Error is created and this stack\n // trace will lead directly to user code. Throwing in `runAsyncResourceOp` results in an Error\n // with a non-useful stack trace.\n const preallocError = new Error();\n debuggable_1.debuggablePromise(resopAsync.then((resop) => __awaiter(this, void 0, void 0, function* () {\n log.debug(`RegisterResource RPC prepared: t=${t}, name=${name}` +\n (settings_1.excessiveDebugOutput ? `, obj=${JSON.stringify(resop.serializedProps)}` : ``));\n const req = new resproto.RegisterResourceRequest();\n req.setType(t);\n req.setName(name);\n req.setParent(resop.parentURN);\n req.setCustom(custom);\n req.setObject(gstruct.Struct.fromJavaScript(resop.serializedProps));\n req.setProtect(opts.protect);\n req.setProvider(resop.providerRef);\n req.setDependenciesList(Array.from(resop.allDirectDependencyURNs));\n req.setDeletebeforereplace(opts.deleteBeforeReplace || false);\n req.setDeletebeforereplacedefined(opts.deleteBeforeReplace !== undefined);\n req.setIgnorechangesList(opts.ignoreChanges || []);\n req.setVersion(opts.version || \"\");\n req.setAcceptsecrets(true);\n req.setAcceptresources(!utils.disableResourceReferences);\n req.setAdditionalsecretoutputsList(opts.additionalSecretOutputs || []);\n req.setAliasesList(resop.aliases);\n req.setImportid(resop.import || \"\");\n req.setSupportspartialvalues(true);\n req.setRemote(remote);\n const customTimeouts = new resproto.RegisterResourceRequest.CustomTimeouts();\n if (opts.customTimeouts != null) {\n customTimeouts.setCreate(opts.customTimeouts.create);\n customTimeouts.setUpdate(opts.customTimeouts.update);\n customTimeouts.setDelete(opts.customTimeouts.delete);\n }\n req.setCustomtimeouts(customTimeouts);\n const propertyDependencies = req.getPropertydependenciesMap();\n for (const [key, resourceURNs] of resop.propertyToDirectDependencyURNs) {\n const deps = new resproto.RegisterResourceRequest.PropertyDependencies();\n deps.setUrnsList(Array.from(resourceURNs));\n propertyDependencies.set(key, deps);\n }\n // Now run the operation, serializing the invocation if necessary.\n const opLabel = `monitor.registerResource(${label})`;\n runAsyncResourceOp(opLabel, () => __awaiter(this, void 0, void 0, function* () {\n let resp;\n let err;\n try {\n if (monitor) {\n // If we're running with an attachment to the engine, perform the operation.\n resp = yield debuggable_1.debuggablePromise(new Promise((resolve, reject) => monitor.registerResource(req, (rpcErr, innerResponse) => {\n if (rpcErr) {\n err = rpcErr;\n // If the monitor is unavailable, it is in the process of shutting down or has already\n // shut down. Don't emit an error and don't do any more RPCs, just exit.\n if (rpcErr.code === grpc.status.UNAVAILABLE || rpcErr.code === grpc.status.CANCELLED) {\n // Re-emit the message\n settings_1.terminateRpcs();\n rpcErr.message = \"Resource monitor is terminating\";\n preallocError.code = rpcErr.code;\n }\n // Node lets us hack the message as long as we do it before accessing the `stack` property.\n log.debug(`RegisterResource RPC finished: ${label}; err: ${rpcErr}, resp: ${innerResponse}`);\n preallocError.message = `failed to register new resource ${name} [${t}]: ${rpcErr.message}`;\n reject(preallocError);\n }\n else {\n log.debug(`RegisterResource RPC finished: ${label}; err: ${rpcErr}, resp: ${innerResponse}`);\n resolve(innerResponse);\n }\n })), opLabel);\n }\n else {\n // If we aren't attached to the engine, in test mode, mock up a fake response for testing purposes.\n const mockurn = yield resource_1.createUrn(req.getName(), req.getType(), req.getParent()).promise();\n resp = {\n getUrn: () => mockurn,\n getId: () => undefined,\n getObject: () => req.getObject(),\n getPropertydependenciesMap: () => undefined,\n };\n }\n }\n catch (e) {\n err = e;\n resp = {\n getUrn: () => \"\",\n getId: () => undefined,\n getObject: () => req.getObject(),\n getPropertydependenciesMap: () => undefined,\n };\n }\n resop.resolveURN(resp.getUrn(), err);\n // Note: 'id || undefined' is intentional. We intentionally collapse falsy values to\n // undefined so that later parts of our system don't have to deal with values like 'null'.\n if (resop.resolveID) {\n const id = resp.getId() || undefined;\n resop.resolveID(id, id !== undefined, err);\n }\n const deps = {};\n const rpcDeps = resp.getPropertydependenciesMap();\n if (rpcDeps) {\n for (const [k, propertyDeps] of resp.getPropertydependenciesMap().entries()) {\n const urns = propertyDeps.getUrnsList();\n deps[k] = urns.map(urn => newDependency(urn));\n }\n }\n // Now resolve the output properties.\n yield resolveOutputs(res, t, name, props, resp.getObject(), deps, resop.resolvers, err);\n }));\n })), label);\n}\nexports.registerResource = registerResource;\n/**\n * Prepares for an RPC that will manufacture a resource, and hence deals with input and output\n * properties.\n */\nfunction prepareResource(label, res, custom, props, opts) {\n return __awaiter(this, void 0, void 0, function* () {\n // Simply initialize the URN property and get prepared to resolve it later on.\n // Note: a resource urn will always get a value, and thus the output property\n // for it can always run .apply calls.\n let resolveURN;\n {\n let resolveValue;\n let resolveIsKnown;\n res.urn = new output_1.Output(res, debuggable_1.debuggablePromise(new Promise(resolve => resolveValue = resolve), `resolveURN(${label})`), debuggable_1.debuggablePromise(new Promise(resolve => resolveIsKnown = resolve), `resolveURNIsKnown(${label})`), \n /*isSecret:*/ Promise.resolve(false), Promise.resolve(res));\n resolveURN = (v, err) => {\n resolveValue(v);\n resolveIsKnown(err === undefined);\n };\n }\n // If a custom resource, make room for the ID property.\n let resolveID;\n if (custom) {\n let resolveValue;\n let resolveIsKnown;\n res.id = new output_1.Output(res, debuggable_1.debuggablePromise(new Promise(resolve => resolveValue = resolve), `resolveID(${label})`), debuggable_1.debuggablePromise(new Promise(resolve => resolveIsKnown = resolve), `resolveIDIsKnown(${label})`), Promise.resolve(false), Promise.resolve(res));\n resolveID = (v, isKnown, err) => {\n resolveValue(v);\n resolveIsKnown(err ? false : isKnown);\n };\n }\n // Now \"transfer\" all input properties into unresolved Promises on res. This way,\n // this resource will look like it has all its output properties to anyone it is\n // passed to. However, those promises won't actually resolve until the registerResource\n // RPC returns\n const resolvers = rpc_1.transferProperties(res, label, props);\n /** IMPORTANT! We should never await prior to this line, otherwise the Resource will be partly uninitialized. */\n // Before we can proceed, all our dependencies must be finished.\n const explicitDirectDependencies = new Set(yield gatherExplicitDependencies(opts.dependsOn));\n // Serialize out all our props to their final values. In doing so, we'll also collect all\n // the Resources pointed to by any Dependency objects we encounter, adding them to 'propertyDependencies'.\n const [serializedProps, propertyToDirectDependencies] = yield rpc_1.serializeResourceProperties(label, props);\n // Wait for the parent to complete.\n // If no parent was provided, parent to the root resource.\n const parentURN = opts.parent\n ? yield opts.parent.urn.promise()\n : yield settings_1.getRootResource();\n let providerRef;\n let importID;\n if (custom) {\n const customOpts = opts;\n importID = customOpts.import;\n providerRef = yield resource_1.ProviderResource.register(opts.provider);\n }\n // Collect the URNs for explicit/implicit dependencies for the engine so that it can understand\n // the dependency graph and optimize operations accordingly.\n // The list of all dependencies (implicit or explicit).\n const allDirectDependencies = new Set(explicitDirectDependencies);\n const allDirectDependencyURNs = yield getAllTransitivelyReferencedCustomResourceURNs(explicitDirectDependencies);\n const propertyToDirectDependencyURNs = new Map();\n for (const [propertyName, directDependencies] of propertyToDirectDependencies) {\n addAll(allDirectDependencies, directDependencies);\n const urns = yield getAllTransitivelyReferencedCustomResourceURNs(directDependencies);\n addAll(allDirectDependencyURNs, urns);\n propertyToDirectDependencyURNs.set(propertyName, urns);\n }\n // Wait for all aliases. Note that we use `res.__aliases` instead of `opts.aliases` as the former has been processed\n // in the Resource constructor prior to calling `registerResource` - both adding new inherited aliases and\n // simplifying aliases down to URNs.\n const aliases = [];\n const uniqueAliases = new Set();\n for (const alias of (res.__aliases || [])) {\n const aliasVal = yield output_1.output(alias).promise();\n if (!uniqueAliases.has(aliasVal)) {\n uniqueAliases.add(aliasVal);\n aliases.push(aliasVal);\n }\n }\n return {\n resolveURN: resolveURN,\n resolveID: resolveID,\n resolvers: resolvers,\n serializedProps: serializedProps,\n parentURN: parentURN,\n providerRef: providerRef,\n allDirectDependencyURNs: allDirectDependencyURNs,\n propertyToDirectDependencyURNs: propertyToDirectDependencyURNs,\n aliases: aliases,\n import: importID,\n };\n });\n}\nfunction addAll(to, from) {\n for (const val of from) {\n to.add(val);\n }\n}\nfunction getAllTransitivelyReferencedCustomResourceURNs(resources) {\n return __awaiter(this, void 0, void 0, function* () {\n // Go through 'resources', but transitively walk through **Component** resources, collecting any\n // of their child resources. This way, a Component acts as an aggregation really of all the\n // reachable custom resources it parents. This walking will transitively walk through other\n // child ComponentResources, but will stop when it hits custom resources. in other words, if we\n // had:\n //\n // Comp1\n // / \\\n // Cust1 Comp2\n // / \\\n // Cust2 Cust3\n // /\n // Cust4\n //\n // Then the transitively reachable custom resources of Comp1 will be [Cust1, Cust2, Cust3]. It\n // will *not* include `Cust4`.\n // To do this, first we just get the transitively reachable set of resources (not diving\n // into custom resources). In the above picture, if we start with 'Comp1', this will be\n // [Comp1, Cust1, Comp2, Cust2, Cust3]\n const transitivelyReachableResources = yield getTransitivelyReferencedChildResourcesOfComponentResources(resources);\n const transitivelyReachableCustomResources = [...transitivelyReachableResources].filter(r => resource_1.CustomResource.isInstance(r));\n const promises = transitivelyReachableCustomResources.map(r => r.urn.promise());\n const urns = yield Promise.all(promises);\n return new Set(urns);\n });\n}\n/**\n * Recursively walk the resources passed in, returning them and all resources reachable from\n * [Resource.__childResources] through any **Component** resources we encounter.\n */\nfunction getTransitivelyReferencedChildResourcesOfComponentResources(resources) {\n return __awaiter(this, void 0, void 0, function* () {\n // Recursively walk the dependent resources through their children, adding them to the result set.\n const result = new Set();\n yield addTransitivelyReferencedChildResourcesOfComponentResources(resources, result);\n return result;\n });\n}\nfunction addTransitivelyReferencedChildResourcesOfComponentResources(resources, result) {\n return __awaiter(this, void 0, void 0, function* () {\n if (resources) {\n for (const resource of resources) {\n if (!result.has(resource)) {\n result.add(resource);\n if (resource_1.ComponentResource.isInstance(resource)) {\n // This await is safe even if __isConstructed is undefined. Ensure that the\n // resource has completely finished construction. That way all parent/child\n // relationships will have been setup.\n yield resource.__data;\n addTransitivelyReferencedChildResourcesOfComponentResources(resource.__childResources, result);\n }\n }\n }\n }\n });\n}\n/**\n * Gathers explicit dependent Resources from a list of Resources (possibly Promises and/or Outputs).\n */\nfunction gatherExplicitDependencies(dependsOn) {\n return __awaiter(this, void 0, void 0, function* () {\n if (dependsOn) {\n if (Array.isArray(dependsOn)) {\n const dos = [];\n for (const d of dependsOn) {\n dos.push(...(yield gatherExplicitDependencies(d)));\n }\n return dos;\n }\n else if (dependsOn instanceof Promise) {\n return gatherExplicitDependencies(yield dependsOn);\n }\n else if (output_1.Output.isInstance(dependsOn)) {\n // Recursively gather dependencies, await the promise, and append the output's dependencies.\n const dos = dependsOn.apply(v => gatherExplicitDependencies(v));\n const urns = yield dos.promise();\n const dosResources = yield output_1.getAllResources(dos);\n const implicits = yield gatherExplicitDependencies([...dosResources]);\n return ((urns !== null && urns !== void 0 ? urns : [])).concat(implicits);\n }\n else {\n if (!resource_1.Resource.isInstance(dependsOn)) {\n throw new Error(\"'dependsOn' was passed a value that was not a Resource.\");\n }\n return [dependsOn];\n }\n }\n return [];\n });\n}\n/**\n * Finishes a resource creation RPC operation by resolving its outputs to the resulting RPC payload.\n */\nfunction resolveOutputs(res, t, name, props, outputs, deps, resolvers, err) {\n return __awaiter(this, void 0, void 0, function* () {\n // Produce a combined set of property states, starting with inputs and then applying\n // outputs. If the same property exists in the inputs and outputs states, the output wins.\n const allProps = {};\n if (outputs) {\n Object.assign(allProps, rpc_1.deserializeProperties(outputs));\n }\n const label = `resource:${name}[${t}]#...`;\n if (!settings_1.isDryRun() || settings_1.isLegacyApplyEnabled()) {\n for (const key of Object.keys(props)) {\n if (!allProps.hasOwnProperty(key)) {\n // input prop the engine didn't give us a final value for. Just use the value passed into the resource\n // after round-tripping it through serialization. We do the round-tripping primarily s.t. we ensure that\n // Output values are handled properly w.r.t. unknowns.\n const inputProp = yield rpc_1.serializeProperty(label, props[key], new Set());\n if (inputProp === undefined) {\n continue;\n }\n allProps[key] = rpc_1.deserializeProperty(inputProp);\n }\n }\n }\n rpc_1.resolveProperties(res, resolvers, t, name, allProps, deps, err);\n });\n}\n/**\n * registerResourceOutputs completes the resource registration, attaching an optional set of computed outputs.\n */\nfunction registerResourceOutputs(res, outputs) {\n // Now run the operation. Note that we explicitly do not serialize output registration with\n // respect to other resource operations, as outputs may depend on properties of other resources\n // that will not resolve until later turns. This would create a circular promise chain that can\n // never resolve.\n const opLabel = `monitor.registerResourceOutputs(...)`;\n runAsyncResourceOp(opLabel, () => __awaiter(this, void 0, void 0, function* () {\n // The registration could very well still be taking place, so we will need to wait for its URN.\n // Additionally, the output properties might have come from other resources, so we must await those too.\n const urn = yield res.urn.promise();\n const resolved = yield rpc_1.serializeProperties(opLabel, { outputs });\n const outputsObj = gstruct.Struct.fromJavaScript(resolved.outputs);\n log.debug(`RegisterResourceOutputs RPC prepared: urn=${urn}` +\n (settings_1.excessiveDebugOutput ? `, outputs=${JSON.stringify(outputsObj)}` : ``));\n // Fetch the monitor and make an RPC request.\n const monitor = settings_1.getMonitor();\n if (monitor) {\n const req = new resproto.RegisterResourceOutputsRequest();\n req.setUrn(urn);\n req.setOutputs(outputsObj);\n const label = `monitor.registerResourceOutputs(${urn}, ...)`;\n yield debuggable_1.debuggablePromise(new Promise((resolve, reject) => monitor.registerResourceOutputs(req, (err, innerResponse) => {\n log.debug(`RegisterResourceOutputs RPC finished: urn=${urn}; ` +\n `err: ${err}, resp: ${innerResponse}`);\n if (err) {\n // If the monitor is unavailable, it is in the process of shutting down or has already\n // shut down. Don't emit an error and don't do any more RPCs, just exit.\n if (err.code === grpc.status.UNAVAILABLE || err.code === grpc.status.CANCELLED) {\n settings_1.terminateRpcs();\n err.message = \"Resource monitor is terminating\";\n }\n reject(err);\n }\n else {\n log.debug(`RegisterResourceOutputs RPC finished: urn=${urn}; ` +\n `err: ${err}, resp: ${innerResponse}`);\n resolve();\n }\n })), label);\n }\n }), false);\n}\nexports.registerResourceOutputs = registerResourceOutputs;\nfunction isAny(o) {\n return true;\n}\n/**\n * listResourceOutputs returns the resource outputs (if any) for a stack, or an error if the stack\n * cannot be found. Resources are retrieved from the latest stack snapshot, which may include\n * ongoing updates.\n *\n * @param stackName Name of stack to retrieve resource outputs for. Defaults to the current stack.\n * @param typeFilter A [type\n * guard](https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards)\n * that specifies which resource types to list outputs of.\n *\n * @example\n * const buckets = pulumi.runtime.listResourceOutput(aws.s3.Bucket.isInstance);\n */\nfunction listResourceOutputs(typeFilter, stackName) {\n if (typeFilter === undefined) {\n typeFilter = isAny;\n }\n return query\n .from(invoke_1.invoke(\"pulumi:pulumi:readStackResourceOutputs\", {\n stackName: stackName || settings_1.getStack(),\n }).then(({ outputs }) => utils.values(outputs)))\n .map(({ type: typ, outputs }) => {\n return Object.assign(Object.assign({}, outputs), { __pulumiType: typ });\n })\n .filter(typeFilter);\n}\nexports.listResourceOutputs = listResourceOutputs;\n/**\n * resourceChain is used to serialize all resource requests. If we don't do this, all resource operations will be\n * entirely asynchronous, meaning the dataflow graph that results will determine ordering of operations. This\n * causes problems with some resource providers, so for now we will serialize all of them. The issue\n * pulumi/pulumi#335 tracks coming up with a long-term solution here.\n */\nlet resourceChain = Promise.resolve();\nlet resourceChainLabel = undefined;\n// runAsyncResourceOp runs an asynchronous resource operation, possibly serializing it as necessary.\nfunction runAsyncResourceOp(label, callback, serial) {\n // Serialize the invocation if necessary.\n if (serial === undefined) {\n serial = settings_1.serialize();\n }\n const resourceOp = rpc_1.suppressUnhandledGrpcRejections(debuggable_1.debuggablePromise(resourceChain.then(() => __awaiter(this, void 0, void 0, function* () {\n if (serial) {\n resourceChainLabel = label;\n log.debug(`Resource RPC serialization requested: ${label} is current`);\n }\n return callback();\n })), label + \"-initial\"));\n // Ensure the process won't exit until this RPC call finishes and resolve it when appropriate.\n const done = settings_1.rpcKeepAlive();\n const finalOp = debuggable_1.debuggablePromise(resourceOp.then(() => { done(); }, () => { done(); }), label + \"-final\");\n // Set up another promise that propagates the error, if any, so that it triggers unhandled rejection logic.\n resourceOp.catch((err) => Promise.reject(err));\n // If serialization is requested, wait for the prior resource operation to finish before we proceed, serializing\n // them, and make this the current resource operation so that everybody piles up on it.\n if (serial) {\n resourceChain = finalOp;\n if (resourceChainLabel) {\n log.debug(`Resource RPC serialization requested: ${label} is behind ${resourceChainLabel}`);\n }\n }\n}\n","\"use strict\";\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst asset = require(\"../asset\");\nconst errors_1 = require(\"../errors\");\nconst log = require(\"../log\");\nconst output_1 = require(\"../output\");\nconst resource_1 = require(\"../resource\");\nconst debuggable_1 = require(\"./debuggable\");\nconst settings_1 = require(\"./settings\");\nconst semver = require(\"semver\");\nconst gstruct = require(\"google-protobuf/google/protobuf/struct_pb.js\");\n/**\n * transferProperties mutates the 'onto' resource so that it has Promise-valued properties for all\n * the 'props' input/output props. *Importantly* all these promises are completely unresolved. This\n * is because we don't want anyone to observe the values of these properties until the rpc call to\n * registerResource actually returns. This is because the registerResource call may actually\n * override input values, and we only want people to see the final value.\n *\n * The result of this call (beyond the stateful changes to 'onto') is the set of Promise resolvers\n * that will be called post-RPC call. When the registerResource RPC call comes back, the values\n * that the engine actualy produced will be used to resolve all the unresolved promised placed on\n * 'onto'.\n */\nfunction transferProperties(onto, label, props) {\n const resolvers = {};\n for (const k of Object.keys(props)) {\n // Skip \"id\" and \"urn\", since we handle those specially.\n if (k === \"id\" || k === \"urn\") {\n continue;\n }\n // Create a property to wrap the value and store it on the resource.\n if (onto.hasOwnProperty(k)) {\n throw new Error(`Property '${k}' is already initialized on target '${label}`);\n }\n let resolveValue;\n let resolveIsKnown;\n let resolveIsSecret;\n let resolveDeps;\n resolvers[k] = (v, isKnown, isSecret, deps = [], err) => {\n resolveValue(v);\n resolveIsKnown(err ? false : isKnown);\n resolveIsSecret(isSecret);\n resolveDeps(deps);\n };\n const propString = output_1.Output.isInstance(props[k]) ? \"Output\" : `${props[k]}`;\n onto[k] = new output_1.Output(onto, debuggable_1.debuggablePromise(new Promise(resolve => resolveValue = resolve), `transferProperty(${label}, ${k}, ${propString})`), debuggable_1.debuggablePromise(new Promise(resolve => resolveIsKnown = resolve), `transferIsStable(${label}, ${k}, ${propString})`), debuggable_1.debuggablePromise(new Promise(resolve => resolveIsSecret = resolve), `transferIsSecret(${label}, ${k}, ${propString})`), debuggable_1.debuggablePromise(new Promise(resolve => resolveDeps = resolve), `transferDeps(${label}, ${k}, ${propString})`));\n }\n return resolvers;\n}\nexports.transferProperties = transferProperties;\n/**\n * serializeFilteredProperties walks the props object passed in, awaiting all interior promises for\n * properties with keys that match the provided filter, creating a reasonable POJO object that can\n * be remoted over to registerResource.\n */\nfunction serializeFilteredProperties(label, props, acceptKey) {\n return __awaiter(this, void 0, void 0, function* () {\n const propertyToDependentResources = new Map();\n const result = {};\n for (const k of Object.keys(props)) {\n if (acceptKey(k)) {\n // We treat properties with undefined values as if they do not exist.\n const dependentResources = new Set();\n const v = yield serializeProperty(`${label}.${k}`, props[k], dependentResources);\n if (v !== undefined) {\n result[k] = v;\n propertyToDependentResources.set(k, dependentResources);\n }\n }\n }\n return [result, propertyToDependentResources];\n });\n}\n/**\n * serializeResourceProperties walks the props object passed in, awaiting all interior promises besides those for `id`\n * and `urn`, creating a reasonable POJO object that can be remoted over to registerResource.\n */\nfunction serializeResourceProperties(label, props) {\n return __awaiter(this, void 0, void 0, function* () {\n return serializeFilteredProperties(label, props, key => key !== \"id\" && key !== \"urn\");\n });\n}\nexports.serializeResourceProperties = serializeResourceProperties;\n/**\n * serializeProperties walks the props object passed in, awaiting all interior promises, creating a reasonable\n * POJO object that can be remoted over to registerResource.\n */\nfunction serializeProperties(label, props) {\n return __awaiter(this, void 0, void 0, function* () {\n const [result] = yield serializeFilteredProperties(label, props, _ => true);\n return result;\n });\n}\nexports.serializeProperties = serializeProperties;\n/**\n * deserializeProperties fetches the raw outputs and deserializes them from a gRPC call result.\n */\nfunction deserializeProperties(outputsStruct) {\n const props = {};\n const outputs = outputsStruct.toJavaScript();\n for (const k of Object.keys(outputs)) {\n // We treat properties with undefined values as if they do not exist.\n if (outputs[k] !== undefined) {\n props[k] = deserializeProperty(outputs[k]);\n }\n }\n return props;\n}\nexports.deserializeProperties = deserializeProperties;\n/**\n * resolveProperties takes as input a gRPC serialized proto.google.protobuf.Struct and resolves all\n * of the resource's matching properties to the values inside.\n *\n * NOTE: it is imperative that the properties in `allProps` were produced by `deserializeProperties` in order for\n * output properties to work correctly w.r.t. knowns/unknowns: this function assumes that any undefined value in\n * `allProps`represents an unknown value that was returned by an engine operation.\n */\nfunction resolveProperties(res, resolvers, t, name, allProps, deps, err) {\n // If there is an error, just reject everything.\n if (err) {\n for (const k of Object.keys(resolvers)) {\n const resolve = resolvers[k];\n resolve(undefined, true, false, [], err);\n }\n return;\n }\n // Now go ahead and resolve all properties present in the inputs and outputs set.\n for (const k of Object.keys(allProps)) {\n // Skip \"id\" and \"urn\", since we handle those specially.\n if (k === \"id\" || k === \"urn\") {\n continue;\n }\n // Otherwise, unmarshal the value, and store it on the resource object.\n const resolve = resolvers[k];\n if (resolve === undefined) {\n // engine returned a property that was not in our initial property-map. This can happen\n // for outputs that were registered through direct calls to 'registerOutputs'. We do\n // *not* want to do anything with these returned properties. First, the component\n // resources that were calling 'registerOutputs' will have already assigned these fields\n // directly on them themselves. Second, if we were to try to assign here we would have\n // an incredibly bad race condition for two reasons:\n //\n // 1. This call to 'resolveProperties' happens asynchronously at some point far after\n // the resource was constructed. So the user will have been able to observe the\n // initial value up until we get to this point.\n //\n // 2. The component resource will have often assigned a value of some arbitrary type\n // (say, a 'string'). If we overwrite this with an `Output` we'll be changing\n // the type at some non-deterministic point in the future.\n continue;\n }\n // If this value is a secret, unwrap its inner value.\n let value = allProps[k];\n const isSecret = isRpcSecret(value);\n value = unwrapRpcSecret(value);\n try {\n // If the value the engine handed back is or contains an unknown value, the resolver will mark its value as\n // unknown automatically, so we just pass true for isKnown here. Note that unknown values will only be\n // present during previews (i.e. isDryRun() will be true).\n resolve(value, /*isKnown*/ true, isSecret, deps[k]);\n }\n catch (err) {\n throw new Error(`Unable to set property '${k}' on resource '${name}' [${t}]; error: ${debuggable_1.errorString(err)}`);\n }\n }\n // `allProps` may not have contained a value for every resolver: for example, optional outputs may not be present.\n // We will resolve all of these values as `undefined`, and will mark the value as known if we are not running a\n // preview.\n for (const k of Object.keys(resolvers)) {\n if (!allProps.hasOwnProperty(k)) {\n const resolve = resolvers[k];\n resolve(undefined, !settings_1.isDryRun(), false);\n }\n }\n}\nexports.resolveProperties = resolveProperties;\n/**\n * Unknown values are encoded as a distinguished string value.\n */\nexports.unknownValue = \"04da6b54-80e4-46f7-96ec-b56ff0331ba9\";\n/**\n * specialSigKey is sometimes used to encode type identity inside of a map. See pkg/resource/properties.go.\n */\nexports.specialSigKey = \"4dabf18193072939515e22adb298388d\";\n/**\n * specialAssetSig is a randomly assigned hash used to identify assets in maps. See pkg/resource/asset.go.\n */\nexports.specialAssetSig = \"c44067f5952c0a294b673a41bacd8c17\";\n/**\n * specialArchiveSig is a randomly assigned hash used to identify archives in maps. See pkg/resource/asset.go.\n */\nexports.specialArchiveSig = \"0def7320c3a5731c473e5ecbe6d01bc7\";\n/**\n * specialSecretSig is a randomly assigned hash used to identify secrets in maps. See pkg/resource/properties.go.\n */\nexports.specialSecretSig = \"1b47061264138c4ac30d75fd1eb44270\";\n/**\n * specialResourceSig is a randomly assigned hash used to identify resources in maps. See pkg/resource/properties.go.\n */\nexports.specialResourceSig = \"5cf8f73096256a8f31e491e813e4eb8e\";\n/**\n * serializeProperty serializes properties deeply. This understands how to wait on any unresolved promises, as\n * appropriate, in addition to translating certain \"special\" values so that they are ready to go on the wire.\n */\nfunction serializeProperty(ctx, prop, dependentResources) {\n return __awaiter(this, void 0, void 0, function* () {\n // IMPORTANT:\n // IMPORTANT: Keep this in sync with serializePropertiesSync in invoke.ts\n // IMPORTANT:\n if (prop === undefined ||\n prop === null ||\n typeof prop === \"boolean\" ||\n typeof prop === \"number\" ||\n typeof prop === \"string\") {\n if (settings_1.excessiveDebugOutput) {\n log.debug(`Serialize property [${ctx}]: primitive=${prop}`);\n }\n return prop;\n }\n if (asset.Asset.isInstance(prop) || asset.Archive.isInstance(prop)) {\n // Serializing an asset or archive requires the use of a magical signature key, since otherwise it would look\n // like any old weakly typed object/map when received by the other side of the RPC boundary.\n const obj = {\n [exports.specialSigKey]: asset.Asset.isInstance(prop) ? exports.specialAssetSig : exports.specialArchiveSig,\n };\n return yield serializeAllKeys(prop, obj);\n }\n if (prop instanceof Promise) {\n // For a promise input, await the property and then serialize the result.\n if (settings_1.excessiveDebugOutput) {\n log.debug(`Serialize property [${ctx}]: Promise`);\n }\n const subctx = `Promise<${ctx}>`;\n return serializeProperty(subctx, yield debuggable_1.debuggablePromise(prop, `serializeProperty.await(${subctx})`), dependentResources);\n }\n if (output_1.Output.isInstance(prop)) {\n if (settings_1.excessiveDebugOutput) {\n log.debug(`Serialize property [${ctx}]: Output`);\n }\n // handle serializing both old-style outputs (with sync resources) and new-style outputs\n // (with async resources).\n const propResources = yield output_1.getAllResources(prop);\n for (const resource of propResources) {\n dependentResources.add(resource);\n }\n // When serializing an Output, we will either serialize it as its resolved value or the \"unknown value\"\n // sentinel. We will do the former for all outputs created directly by user code (such outputs always\n // resolve isKnown to true) and for any resource outputs that were resolved with known values.\n const isKnown = yield prop.isKnown;\n // You might think that doing an explict `=== true` here is not needed, but it is for a subtle reason. If the\n // output we are serializing is a proxy itself, and it comes from a version of the SDK that did not have the\n // `isSecret` member on `OutputImpl` then the call to `prop.isSecret` here will return an Output itself,\n // which will wrap undefined, if it were to be resolved (since `Output` has no member named .isSecret).\n // so we must compare to the literal true instead of just doing await prop.isSecret.\n const isSecret = (yield prop.isSecret) === true;\n const value = yield serializeProperty(`${ctx}.id`, prop.promise(), dependentResources);\n if (!isKnown) {\n return exports.unknownValue;\n }\n if (isSecret && (yield settings_1.monitorSupportsSecrets())) {\n return {\n [exports.specialSigKey]: exports.specialSecretSig,\n // coerce 'undefined' to 'null' as required by the protobuf system.\n value: value === undefined ? null : value,\n };\n }\n return value;\n }\n if (output_1.isUnknown(prop)) {\n return exports.unknownValue;\n }\n if (resource_1.CustomResource.isInstance(prop)) {\n if (settings_1.excessiveDebugOutput) {\n log.debug(`Serialize property [${ctx}]: custom resource urn`);\n }\n dependentResources.add(prop);\n const id = yield serializeProperty(`${ctx}.id`, prop.id, dependentResources);\n if (yield settings_1.monitorSupportsResourceReferences()) {\n // If we are keeping resources, emit a stronly typed wrapper over the URN\n const urn = yield serializeProperty(`${ctx}.urn`, prop.urn, dependentResources);\n return {\n [exports.specialSigKey]: exports.specialResourceSig,\n urn: urn,\n id: id,\n };\n }\n // Else, return the id for backward compatibility.\n return id;\n }\n if (resource_1.ComponentResource.isInstance(prop)) {\n // Component resources often can contain cycles in them. For example, an awsinfra\n // SecurityGroupRule can point a the awsinfra SecurityGroup, which in turn can point back to\n // its rules through its `egressRules` and `ingressRules` properties. If serializing out\n // the `SecurityGroup` resource ends up trying to serialize out those properties, a deadlock\n // will happen, due to waiting on the child, which is waiting on the parent.\n //\n // Practically, there is no need to actually serialize out a component. It doesn't represent\n // a real resource, nor does it have normal properties that need to be tracked for differences\n // (since changes to its properties don't represent changes to resources in the real world).\n //\n // So, to avoid these problems, while allowing a flexible and simple programming model, we\n // just serialize out the component as its urn. This allows the component to be identified\n // and tracked in a reasonable manner, while not causing us to compute or embed information\n // about it that is not needed, and which can lead to deadlocks.\n if (settings_1.excessiveDebugOutput) {\n log.debug(`Serialize property [${ctx}]: component resource urn`);\n }\n if (yield settings_1.monitorSupportsResourceReferences()) {\n // If we are keeping resources, emit a strongly typed wrapper over the URN\n const urn = yield serializeProperty(`${ctx}.urn`, prop.urn, dependentResources);\n return {\n [exports.specialSigKey]: exports.specialResourceSig,\n urn: urn,\n };\n }\n // Else, return the urn for backward compatibility.\n return serializeProperty(`${ctx}.urn`, prop.urn, dependentResources);\n }\n if (prop instanceof Array) {\n const result = [];\n for (let i = 0; i < prop.length; i++) {\n if (settings_1.excessiveDebugOutput) {\n log.debug(`Serialize property [${ctx}]: array[${i}] element`);\n }\n // When serializing arrays, we serialize any undefined values as `null`. This matches JSON semantics.\n const elem = yield serializeProperty(`${ctx}[${i}]`, prop[i], dependentResources);\n result.push(elem === undefined ? null : elem);\n }\n return result;\n }\n return yield serializeAllKeys(prop, {});\n function serializeAllKeys(innerProp, obj) {\n return __awaiter(this, void 0, void 0, function* () {\n for (const k of Object.keys(innerProp)) {\n if (settings_1.excessiveDebugOutput) {\n log.debug(`Serialize property [${ctx}]: object.${k}`);\n }\n // When serializing an object, we omit any keys with undefined values. This matches JSON semantics.\n const v = yield serializeProperty(`${ctx}.${k}`, innerProp[k], dependentResources);\n if (v !== undefined) {\n obj[k] = v;\n }\n }\n return obj;\n });\n }\n });\n}\nexports.serializeProperty = serializeProperty;\n/**\n * isRpcSecret returns true if obj is a wrapped secret value (i.e. it's an object with the special key set).\n */\nfunction isRpcSecret(obj) {\n return obj && obj[exports.specialSigKey] === exports.specialSecretSig;\n}\nexports.isRpcSecret = isRpcSecret;\n/**\n * unwrapRpcSecret returns the underlying value for a secret, or the value itself if it was not a secret.\n */\nfunction unwrapRpcSecret(obj) {\n if (!isRpcSecret(obj)) {\n return obj;\n }\n return obj.value;\n}\nexports.unwrapRpcSecret = unwrapRpcSecret;\n/**\n * deserializeProperty unpacks some special types, reversing the above process.\n */\nfunction deserializeProperty(prop) {\n if (prop === undefined) {\n throw new Error(\"unexpected undefined property value during deserialization\");\n }\n else if (prop === exports.unknownValue) {\n return settings_1.isDryRun() ? output_1.unknown : undefined;\n }\n else if (prop === null || typeof prop === \"boolean\" || typeof prop === \"number\" || typeof prop === \"string\") {\n return prop;\n }\n else if (prop instanceof Array) {\n // We can just deserialize all the elements of the underlying array and return it.\n // However, we want to push secretness up to the top level (since we can't set sub-properties to secret)\n // values since they are not typed as Output.\n let hadSecret = false;\n const elems = [];\n for (const e of prop) {\n prop = deserializeProperty(e);\n hadSecret = hadSecret || isRpcSecret(prop);\n elems.push(unwrapRpcSecret(prop));\n }\n if (hadSecret) {\n return {\n [exports.specialSigKey]: exports.specialSecretSig,\n value: elems,\n };\n }\n return elems;\n }\n else {\n // We need to recognize assets and archives specially, so we can produce the right runtime objects.\n const sig = prop[exports.specialSigKey];\n if (sig) {\n switch (sig) {\n case exports.specialAssetSig:\n if (prop[\"path\"]) {\n return new asset.FileAsset(prop[\"path\"]);\n }\n else if (prop[\"text\"]) {\n return new asset.StringAsset(prop[\"text\"]);\n }\n else if (prop[\"uri\"]) {\n return new asset.RemoteAsset(prop[\"uri\"]);\n }\n else {\n throw new Error(\"Invalid asset encountered when unmarshaling resource property\");\n }\n case exports.specialArchiveSig:\n if (prop[\"assets\"]) {\n const assets = {};\n for (const name of Object.keys(prop[\"assets\"])) {\n const a = deserializeProperty(prop[\"assets\"][name]);\n if (!(asset.Asset.isInstance(a)) && !(asset.Archive.isInstance(a))) {\n throw new Error(\"Expected an AssetArchive's assets to be unmarshaled Asset or Archive objects\");\n }\n assets[name] = a;\n }\n return new asset.AssetArchive(assets);\n }\n else if (prop[\"path\"]) {\n return new asset.FileArchive(prop[\"path\"]);\n }\n else if (prop[\"uri\"]) {\n return new asset.RemoteArchive(prop[\"uri\"]);\n }\n else {\n throw new Error(\"Invalid archive encountered when unmarshaling resource property\");\n }\n case exports.specialSecretSig:\n return {\n [exports.specialSigKey]: exports.specialSecretSig,\n value: deserializeProperty(prop[\"value\"]),\n };\n case exports.specialResourceSig:\n // Deserialize the resource into a live Resource reference\n const urn = prop[\"urn\"];\n const version = prop[\"packageVersion\"];\n const urnParts = urn.split(\"::\");\n const qualifiedType = urnParts[2];\n const urnName = urnParts[3];\n const type = qualifiedType.split(\"$\").pop();\n const typeParts = type.split(\":\");\n const pkgName = typeParts[0];\n const modName = typeParts.length > 1 ? typeParts[1] : \"\";\n const typName = typeParts.length > 2 ? typeParts[2] : \"\";\n const isProvider = pkgName === \"pulumi\" && modName === \"providers\";\n if (isProvider) {\n const resourcePackage = getResourcePackage(typName, version);\n if (resourcePackage) {\n return resourcePackage.constructProvider(urnName, type, urn);\n }\n }\n else {\n const resourceModule = getResourceModule(pkgName, modName, version);\n if (resourceModule) {\n return resourceModule.construct(urnName, type, urn);\n }\n }\n // If we've made it here, deserialize the reference as either a URN or an ID (if present).\n if (prop[\"id\"]) {\n const id = prop[\"id\"];\n return deserializeProperty(id === \"\" ? exports.unknownValue : id);\n }\n return urn;\n default:\n throw new Error(`Unrecognized signature '${sig}' when unmarshaling resource property`);\n }\n }\n // If there isn't a signature, it's not a special type, and we can simply return the object as a map.\n // However, we want to push secretness up to the top level (since we can't set sub-properties to secret)\n // values since they are not typed as Output.\n const obj = {};\n let hadSecrets = false;\n for (const k of Object.keys(prop)) {\n const o = deserializeProperty(prop[k]);\n hadSecrets = hadSecrets || isRpcSecret(o);\n obj[k] = unwrapRpcSecret(o);\n }\n if (hadSecrets) {\n return {\n [exports.specialSigKey]: exports.specialSecretSig,\n value: obj,\n };\n }\n return obj;\n }\n}\nexports.deserializeProperty = deserializeProperty;\n/**\n * suppressUnhandledGrpcRejections silences any unhandled promise rejections that occur due to gRPC errors. The input\n * promise may still be rejected.\n */\nfunction suppressUnhandledGrpcRejections(p) {\n p.catch(err => {\n if (!errors_1.isGrpcError(err)) {\n throw err;\n }\n });\n return p;\n}\nexports.suppressUnhandledGrpcRejections = suppressUnhandledGrpcRejections;\nfunction sameVersion(a, b) {\n // We treat undefined as a wildcard, so it always equals every other version.\n return a === undefined || b === undefined || semver.eq(a, b);\n}\nfunction checkVersion(want, have) {\n if (want === undefined || have === undefined) {\n return true;\n }\n return have.major === want.major && have.minor >= want.minor && have.patch >= want.patch;\n}\n/** @internal */\nfunction register(source, registrationType, key, item) {\n let items = source.get(key);\n if (items) {\n for (const existing of items) {\n if (sameVersion(existing.version, item.version)) {\n // It is possible for the same version of the same provider SDK to be loaded multiple times in Node.js.\n // In this case, we might legitimately get mutliple registrations of the same resource. It should not\n // matter which we use, so we can just skip re-registering. De-serialized resources will always be\n // instances of classes from the first registered package.\n log.debug(`skip re-registering already registered ${registrationType} ${key}@${item.version}.`);\n return false;\n }\n }\n }\n else {\n items = [];\n source.set(key, items);\n }\n log.debug(`registering ${registrationType} ${key}@${item.version}`);\n items.push(item);\n return true;\n}\nexports.register = register;\n/** @internal */\nfunction getRegistration(source, key, version) {\n var _a;\n const ver = version ? new semver.SemVer(version) : undefined;\n let bestMatch = undefined;\n let bestMatchVersion = undefined;\n for (const existing of (_a = source.get(key), (_a !== null && _a !== void 0 ? _a : []))) {\n const existingVersion = existing.version !== undefined ? new semver.SemVer(existing.version) : undefined;\n if (!checkVersion(ver, existingVersion)) {\n continue;\n }\n if (!bestMatch || (existingVersion && bestMatchVersion && semver.gt(existingVersion, bestMatchVersion))) {\n bestMatch = existing;\n bestMatchVersion = existingVersion;\n }\n }\n return bestMatch;\n}\nexports.getRegistration = getRegistration;\nconst resourcePackages = new Map();\n/** @internal Used only for testing purposes. */\nfunction _resetResourcePackages() {\n resourcePackages.clear();\n}\nexports._resetResourcePackages = _resetResourcePackages;\n/**\n * registerResourcePackage registers a resource package that will be used to construct providers for any URNs matching\n * the package name and version that are deserialized by the current instance of the Pulumi JavaScript SDK.\n */\nfunction registerResourcePackage(pkg, resourcePackage) {\n register(resourcePackages, \"package\", pkg, resourcePackage);\n}\nexports.registerResourcePackage = registerResourcePackage;\nfunction getResourcePackage(pkg, version) {\n return getRegistration(resourcePackages, pkg, version);\n}\nexports.getResourcePackage = getResourcePackage;\nconst resourceModules = new Map();\nfunction moduleKey(pkg, mod) {\n return `${pkg}:${mod}`;\n}\n/** @internal Used only for testing purposes. */\nfunction _resetResourceModules() {\n resourceModules.clear();\n}\nexports._resetResourceModules = _resetResourceModules;\n/**\n * registerResourceModule registers a resource module that will be used to construct resources for any URNs matching\n * the module name and version that are deserialized by the current instance of the Pulumi JavaScript SDK.\n */\nfunction registerResourceModule(pkg, mod, module) {\n const key = moduleKey(pkg, mod);\n register(resourceModules, \"module\", key, module);\n}\nexports.registerResourceModule = registerResourceModule;\nfunction getResourceModule(pkg, mod, version) {\n const key = moduleKey(pkg, mod);\n return getRegistration(resourceModules, key, version);\n}\nexports.getResourceModule = getResourceModule;\n","\"use strict\";\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst grpc = require(\"@grpc/grpc-js\");\nconst fs = require(\"fs\");\nconst path = require(\"path\");\nconst debuggable_1 = require(\"./debuggable\");\nconst engrpc = require(\"../proto/engine_grpc_pb.js\");\nconst engproto = require(\"../proto/engine_pb.js\");\nconst provproto = require(\"../proto/provider_pb.js\");\nconst resrpc = require(\"../proto/resource_grpc_pb.js\");\nconst resproto = require(\"../proto/resource_pb.js\");\nconst structproto = require(\"google-protobuf/google/protobuf/struct_pb.js\");\n// maxRPCMessageSize raises the gRPC Max Message size from `4194304` (4mb) to `419430400` (400mb)\nexports.maxRPCMessageSize = 1024 * 1024 * 400;\nconst grpcChannelOptions = { \"grpc.max_receive_message_length\": exports.maxRPCMessageSize };\n/**\n * excessiveDebugOutput enables, well, pretty excessive debug output pertaining to resources and properties.\n */\nexports.excessiveDebugOutput = false;\nconst nodeEnvKeys = {\n project: \"PULUMI_NODEJS_PROJECT\",\n stack: \"PULUMI_NODEJS_STACK\",\n dryRun: \"PULUMI_NODEJS_DRY_RUN\",\n queryMode: \"PULUMI_NODEJS_QUERY_MODE\",\n parallel: \"PULUMI_NODEJS_PARALLEL\",\n monitorAddr: \"PULUMI_NODEJS_MONITOR\",\n engineAddr: \"PULUMI_NODEJS_ENGINE\",\n syncDir: \"PULUMI_NODEJS_SYNC\",\n};\nconst pulumiEnvKeys = {\n testMode: \"PULUMI_TEST_MODE\",\n legacyApply: \"PULUMI_ENABLE_LEGACY_APPLY\",\n};\n// reset options resets nodejs runtime global state (such as rpc clients),\n// and sets nodejs runtime option env vars to the specified values.\nfunction resetOptions(project, stack, parallel, engineAddr, monitorAddr, preview) {\n monitor = undefined;\n engine = undefined;\n rootResource = undefined;\n rpcDone = Promise.resolve();\n featureSupport = {};\n // reset node specific environment variables in the process\n process.env[nodeEnvKeys.project] = project;\n process.env[nodeEnvKeys.stack] = stack;\n process.env[nodeEnvKeys.dryRun] = preview.toString();\n process.env[nodeEnvKeys.queryMode] = isQueryMode.toString();\n process.env[nodeEnvKeys.parallel] = parallel.toString();\n process.env[nodeEnvKeys.monitorAddr] = monitorAddr;\n process.env[nodeEnvKeys.engineAddr] = engineAddr;\n}\nexports.resetOptions = resetOptions;\nfunction setMockOptions(mockMonitor, project, stack, preview) {\n const opts = options();\n resetOptions(project || opts.project || \"project\", stack || opts.stack || \"stack\", opts.parallel || -1, opts.engineAddr || \"\", opts.monitorAddr || \"\", preview || false);\n monitor = mockMonitor;\n}\nexports.setMockOptions = setMockOptions;\n/** @internal Used only for testing purposes. */\nfunction _setIsDryRun(val) {\n process.env[nodeEnvKeys.dryRun] = val.toString();\n}\nexports._setIsDryRun = _setIsDryRun;\n/**\n * Returns true if we're currently performing a dry-run, or false if this is a true update. Note that we\n * always consider executions in test mode to be \"dry-runs\", since we will never actually carry out an update,\n * and therefore certain output properties will never be resolved.\n */\nfunction isDryRun() {\n return options().dryRun === true;\n}\nexports.isDryRun = isDryRun;\n/** @internal Used only for testing purposes */\nfunction _reset() {\n resetOptions(\"\", \"\", -1, \"\", \"\", false);\n}\nexports._reset = _reset;\n/** @internal Used only for testing purposes */\nfunction _setTestModeEnabled(val) {\n process.env[pulumiEnvKeys.testMode] = val.toString();\n}\nexports._setTestModeEnabled = _setTestModeEnabled;\n/** @internal Used only for testing purposes */\nfunction _setFeatureSupport(key, val) {\n featureSupport[key] = val;\n}\nexports._setFeatureSupport = _setFeatureSupport;\n/**\n * Returns true if test mode is enabled (PULUMI_TEST_MODE).\n */\nfunction isTestModeEnabled() {\n return options().testModeEnabled === true;\n}\nexports.isTestModeEnabled = isTestModeEnabled;\n/**\n * Checks that test mode is enabled and, if not, throws an error.\n */\nfunction requireTestModeEnabled() {\n if (!isTestModeEnabled()) {\n throw new Error(\"Program run without the Pulumi engine available; re-run using the `pulumi` CLI\");\n }\n}\n/** @internal Used only for testing purposes. */\nfunction _setQueryMode(val) {\n process.env[nodeEnvKeys.queryMode] = val.toString();\n}\nexports._setQueryMode = _setQueryMode;\n/**\n * Returns true if query mode is enabled.\n */\nfunction isQueryMode() {\n return options().queryMode === true;\n}\nexports.isQueryMode = isQueryMode;\n/**\n * Returns true if we will resolve missing outputs to inputs during preview (PULUMI_ENABLE_LEGACY_APPLY).\n */\nfunction isLegacyApplyEnabled() {\n return options().legacyApply === true;\n}\nexports.isLegacyApplyEnabled = isLegacyApplyEnabled;\n/**\n * Get the project being run by the current update.\n */\nfunction getProject() {\n const project = options().project;\n if (project) {\n return project;\n }\n // If the project is missing, specialize the error. First, if test mode is disabled:\n requireTestModeEnabled();\n // And now an error if test mode is enabled, instructing how to manually configure the project:\n throw new Error(\"Missing project name; for test mode, please call `pulumi.runtime.setMocks`\");\n}\nexports.getProject = getProject;\n/** @internal Used only for testing purposes. */\nfunction _setProject(val) {\n process.env[nodeEnvKeys.project] = val;\n}\nexports._setProject = _setProject;\n/**\n * Get the stack being targeted by the current update.\n */\nfunction getStack() {\n const stack = options().stack;\n if (stack) {\n return stack;\n }\n // If the stack is missing, specialize the error. First, if test mode is disabled:\n requireTestModeEnabled();\n // And now an error if test mode is enabled, instructing how to manually configure the stack:\n throw new Error(\"Missing stack name; for test mode, please set PULUMI_NODEJS_STACK\");\n}\nexports.getStack = getStack;\n/** @internal Used only for testing purposes. */\nfunction _setStack(val) {\n process.env[nodeEnvKeys.stack] = val;\n}\nexports._setStack = _setStack;\n/**\n * monitor is a live connection to the resource monitor that tracks deployments (lazily initialized).\n */\nlet monitor;\nlet featureSupport = {};\n/**\n * hasMonitor returns true if we are currently connected to a resource monitoring service.\n */\nfunction hasMonitor() {\n return !!monitor && !!options().monitorAddr;\n}\nexports.hasMonitor = hasMonitor;\n/**\n * getMonitor returns the current resource monitoring service client for RPC communications.\n */\nfunction getMonitor() {\n if (monitor === undefined) {\n const addr = options().monitorAddr;\n if (addr) {\n // Lazily initialize the RPC connection to the monitor.\n monitor = new resrpc.ResourceMonitorClient(addr, grpc.credentials.createInsecure(), grpcChannelOptions);\n }\n else {\n // If test mode isn't enabled, we can't run the program without an engine.\n requireTestModeEnabled();\n }\n }\n return monitor;\n}\nexports.getMonitor = getMonitor;\nlet syncInvokes;\n/** @internal */\nfunction tryGetSyncInvokes() {\n const syncDir = options().syncDir;\n if (syncInvokes === undefined && syncDir) {\n const requests = fs.openSync(path.join(syncDir, \"invoke_req\"), fs.constants.O_WRONLY | fs.constants.O_SYNC);\n const responses = fs.openSync(path.join(syncDir, \"invoke_res\"), fs.constants.O_RDONLY | fs.constants.O_SYNC);\n syncInvokes = { requests, responses };\n }\n return syncInvokes;\n}\nexports.tryGetSyncInvokes = tryGetSyncInvokes;\n/**\n * engine is a live connection to the engine, used for logging, etc. (lazily initialized).\n */\nlet engine;\n/**\n * hasEngine returns true if we are currently connected to an engine.\n */\nfunction hasEngine() {\n return !!engine && !!options().engineAddr;\n}\nexports.hasEngine = hasEngine;\n/**\n * getEngine returns the current engine, if any, for RPC communications back to the resource engine.\n */\nfunction getEngine() {\n if (engine === undefined) {\n const addr = options().engineAddr;\n if (addr) {\n // Lazily initialize the RPC connection to the engine.\n engine = new engrpc.EngineClient(addr, grpc.credentials.createInsecure(), grpcChannelOptions);\n }\n }\n return engine;\n}\nexports.getEngine = getEngine;\nfunction terminateRpcs() {\n disconnectSync();\n}\nexports.terminateRpcs = terminateRpcs;\n/**\n * serialize returns true if resource operations should be serialized.\n */\nfunction serialize() {\n return options().parallel === 1;\n}\nexports.serialize = serialize;\n/**\n * options returns the options from the environment, which is the source of truth. Options are global per process.\n * For CLI driven programs, pulumi-language-nodejs sets environment variables prior to the user program loading,\n * meaning that options could be loaded up front and cached.\n * Automation API and multi-language components introduced more complex lifecycles for runtime options().\n * These language hosts manage the lifecycle of options manually throughout the lifetime of the nodejs process.\n * In addition, node module resolution can lead to duplicate copies of @pulumi/pulumi and thus duplicate options\n * objects that may not be synced if options are cached upfront. Mutating options must write to the environment\n * and reading options must always read directly from the environment.\n\n */\nfunction options() {\n // The only option that needs parsing is the parallelism flag. Ignore any failures.\n let parallel;\n const parallelOpt = process.env[nodeEnvKeys.parallel];\n if (parallelOpt) {\n try {\n parallel = parseInt(parallelOpt, 10);\n }\n catch (err) {\n // ignore.\n }\n }\n // Now just hydrate the rest from environment variables. These might be missing, in which case\n // we will fail later on when we actually need to create an RPC connection back to the engine.\n return {\n // node runtime\n project: process.env[nodeEnvKeys.project],\n stack: process.env[nodeEnvKeys.stack],\n dryRun: (process.env[nodeEnvKeys.dryRun] === \"true\"),\n queryMode: (process.env[nodeEnvKeys.queryMode] === \"true\"),\n parallel: parallel,\n monitorAddr: process.env[nodeEnvKeys.monitorAddr],\n engineAddr: process.env[nodeEnvKeys.engineAddr],\n syncDir: process.env[nodeEnvKeys.syncDir],\n // pulumi specific\n testModeEnabled: (process.env[pulumiEnvKeys.testMode] === \"true\"),\n legacyApply: (process.env[pulumiEnvKeys.legacyApply] === \"true\"),\n };\n}\n/**\n * disconnect permanently disconnects from the server, closing the connections. It waits for the existing RPC\n * queue to drain. If any RPCs come in afterwards, however, they will crash the process.\n */\nfunction disconnect() {\n let done;\n const closeCallback = () => {\n if (done !== rpcDone) {\n // If the done promise has changed, some activity occurred in between callbacks. Wait again.\n done = rpcDone;\n return debuggable_1.debuggablePromise(done.then(closeCallback), \"disconnect\");\n }\n disconnectSync();\n return Promise.resolve();\n };\n return closeCallback();\n}\nexports.disconnect = disconnect;\n/**\n * disconnectSync permanently disconnects from the server, closing the connections. Unlike `disconnect`. it does not\n * wait for the existing RPC queue to drain. Any RPCs that come in after this call will crash the process.\n */\nfunction disconnectSync() {\n // Otherwise, actually perform the close activities (ignoring errors and crashes).\n if (monitor) {\n try {\n monitor.close();\n }\n catch (err) {\n // ignore.\n }\n monitor = null;\n }\n if (engine) {\n try {\n engine.close();\n }\n catch (err) {\n // ignore.\n }\n engine = null;\n }\n}\nexports.disconnectSync = disconnectSync;\n/**\n * rpcDone resolves when the last known client-side RPC call finishes.\n */\nlet rpcDone = Promise.resolve();\n/**\n * rpcKeepAlive registers a pending call to ensure that we don't prematurely disconnect from the server. It returns\n * a function that, when invoked, signals that the RPC has completed.\n */\nfunction rpcKeepAlive() {\n let done = undefined;\n const donePromise = debuggable_1.debuggablePromise(new Promise(resolve => done = resolve), \"rpcKeepAlive\");\n rpcDone = rpcDone.then(() => donePromise);\n return done;\n}\nexports.rpcKeepAlive = rpcKeepAlive;\nlet rootResource;\n/**\n * getRootResource returns a root resource URN that will automatically become the default parent of all resources. This\n * can be used to ensure that all resources without explicit parents are parented to a common parent resource.\n */\nfunction getRootResource() {\n const engineRef = getEngine();\n if (!engineRef) {\n return Promise.resolve(undefined);\n }\n const req = new engproto.GetRootResourceRequest();\n return new Promise((resolve, reject) => {\n engineRef.getRootResource(req, (err, resp) => {\n // Back-compat case - if the engine we're speaking to isn't aware that it can save and load root resources,\n // fall back to the old behavior.\n if (err && err.code === grpc.status.UNIMPLEMENTED) {\n if (rootResource) {\n rootResource.then(resolve);\n return;\n }\n resolve(undefined);\n }\n if (err) {\n return reject(err);\n }\n const urn = resp.getUrn();\n if (urn) {\n return resolve(urn);\n }\n return resolve(undefined);\n });\n });\n}\nexports.getRootResource = getRootResource;\n/**\n * setRootResource registers a resource that will become the default parent for all resources without explicit parents.\n */\nfunction setRootResource(res) {\n return __awaiter(this, void 0, void 0, function* () {\n const engineRef = getEngine();\n if (!engineRef) {\n return Promise.resolve();\n }\n const req = new engproto.SetRootResourceRequest();\n const urn = yield res.urn.promise();\n req.setUrn(urn);\n return new Promise((resolve, reject) => {\n engineRef.setRootResource(req, (err, resp) => {\n // Back-compat case - if the engine we're speaking to isn't aware that it can save and load root resources,\n // fall back to the old behavior.\n if (err && err.code === grpc.status.UNIMPLEMENTED) {\n rootResource = res.urn.promise();\n return resolve();\n }\n if (err) {\n return reject(err);\n }\n return resolve();\n });\n });\n });\n}\nexports.setRootResource = setRootResource;\n/**\n * monitorSupportsFeature returns a promise that when resolved tells you if the resource monitor we are connected\n * to is able to support a particular feature.\n */\nfunction monitorSupportsFeature(feature) {\n return __awaiter(this, void 0, void 0, function* () {\n const monitorRef = getMonitor();\n if (!monitorRef) {\n // If there's no monitor and test mode is disabled, just return false. Otherwise, return whatever is present in\n // the featureSupport map.\n return isTestModeEnabled() && featureSupport[feature];\n }\n if (featureSupport[feature] === undefined) {\n const req = new resproto.SupportsFeatureRequest();\n req.setId(feature);\n const result = yield new Promise((resolve, reject) => {\n monitorRef.supportsFeature(req, (err, resp) => {\n // Back-compat case - if the monitor doesn't let us ask if it supports a feature, it doesn't support\n // secrets.\n if (err && err.code === grpc.status.UNIMPLEMENTED) {\n return resolve(false);\n }\n if (err) {\n return reject(err);\n }\n return resolve(resp.getHassupport());\n });\n });\n featureSupport[feature] = result;\n }\n return featureSupport[feature];\n });\n}\nexports.monitorSupportsFeature = monitorSupportsFeature;\n/**\n * monitorSupportsSecrets returns a promise that when resolved tells you if the resource monitor we are connected\n * to is able to support secrets across its RPC interface. When it does, we marshal outputs marked with the secret\n * bit in a special way.\n */\nfunction monitorSupportsSecrets() {\n return monitorSupportsFeature(\"secrets\");\n}\nexports.monitorSupportsSecrets = monitorSupportsSecrets;\n/**\n * monitorSupportsResourceReferences returns a promise that when resolved tells you if the resource monitor we are\n * connected to is able to support resource references across its RPC interface. When it does, we marshal resources\n * in a special way.\n */\nfunction monitorSupportsResourceReferences() {\n return __awaiter(this, void 0, void 0, function* () {\n return monitorSupportsFeature(\"resourceReferences\");\n });\n}\nexports.monitorSupportsResourceReferences = monitorSupportsResourceReferences;\n","\"use strict\";\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst asset = require(\"../asset\");\nconst metadata_1 = require(\"../metadata\");\nconst output_1 = require(\"../output\");\nconst resource_1 = require(\"../resource\");\nconst settings_1 = require(\"./settings\");\n/**\n * rootPulumiStackTypeName is the type name that should be used to construct the root component in the tree of Pulumi\n * resources allocated by a deployment. This must be kept up to date with\n * `github.com/pulumi/pulumi/sdk/v2/go/common/resource/stack.RootStackType`.\n */\nexports.rootPulumiStackTypeName = \"pulumi:pulumi:Stack\";\nlet stackResource;\n// Get the root stack resource for the current stack deployment\nfunction getStackResource() {\n return stackResource;\n}\nexports.getStackResource = getStackResource;\n/**\n * runInPulumiStack creates a new Pulumi stack resource and executes the callback inside of it. Any outputs\n * returned by the callback will be stored as output properties on this resulting Stack object.\n */\nfunction runInPulumiStack(init) {\n if (!settings_1.isQueryMode()) {\n const stack = new Stack(init);\n return stack.outputs.promise();\n }\n else {\n return init();\n }\n}\nexports.runInPulumiStack = runInPulumiStack;\n/**\n * Stack is the root resource for a Pulumi stack. Before invoking the `init` callback, it registers itself as the root\n * resource with the Pulumi engine.\n */\nclass Stack extends resource_1.ComponentResource {\n constructor(init) {\n super(exports.rootPulumiStackTypeName, `${metadata_1.getProject()}-${metadata_1.getStack()}`, { init });\n const data = this.getData();\n this.outputs = output_1.output(data);\n }\n /**\n * runInit invokes the given init callback with this resource set as the root resource. The return value of init is\n * used as the stack's output properties.\n *\n * @param init The callback to run in the context of this Pulumi stack\n */\n initialize(args) {\n const _super = Object.create(null, {\n registerOutputs: { get: () => super.registerOutputs }\n });\n return __awaiter(this, void 0, void 0, function* () {\n const parent = yield settings_1.getRootResource();\n if (parent) {\n throw new Error(\"Only one root Pulumi Stack may be active at once\");\n }\n yield settings_1.setRootResource(this);\n // Set the global reference to the stack resource before invoking this init() function\n stackResource = this;\n let outputs;\n try {\n const inputs = yield args.init();\n outputs = yield massage(inputs, []);\n }\n finally {\n // We want to expose stack outputs as simple pojo objects (including Resources). This\n // helps ensure that outputs can point to resources, and that that is stored and\n // presented as something reasonable, and not as just an id/urn in the case of\n // Resources.\n _super.registerOutputs.call(this, outputs);\n }\n return outputs;\n });\n }\n}\nfunction massage(prop, objectStack) {\n return __awaiter(this, void 0, void 0, function* () {\n if (prop === undefined ||\n prop === null ||\n typeof prop === \"boolean\" ||\n typeof prop === \"number\" ||\n typeof prop === \"string\") {\n return prop;\n }\n if (prop instanceof Promise) {\n return yield massage(yield prop, objectStack);\n }\n if (output_1.Output.isInstance(prop)) {\n const result = prop.apply(v => massage(v, objectStack));\n // explicitly await the underlying promise of the output here. This is necessary to get a\n // deterministic walk of the object graph. We need that deterministic walk, otherwise our\n // actual cycle detection logic (using 'objectStack') doesn't work. i.e. if we don't do\n // this then the main walking logic will be interleaved with the async function this output\n // is executing. This interleaving breaks out assumption about pushing/popping values onto\n // objectStack'\n yield result.promise();\n return result;\n }\n // from this point on, we have complex objects. If we see them again, we don't want to emit\n // them again fully or else we'd loop infinitely.\n if (objectStack.indexOf(prop) >= 0) {\n // Note: for Resources we hit again, emit their urn so cycles can be easily understood\n // in the pojo objects.\n if (resource_1.Resource.isInstance(prop)) {\n return yield massage(prop.urn, objectStack);\n }\n return undefined;\n }\n try {\n // push and pop what we see into a stack. That way if we see the same object through\n // different paths, we will still print it out. We only skip it if it would truly cause\n // recursion.\n objectStack.push(prop);\n return yield massageComplex(prop, objectStack);\n }\n finally {\n const popped = objectStack.pop();\n if (popped !== prop) {\n throw new Error(\"Invariant broken when processing stack outputs\");\n }\n }\n });\n}\nfunction massageComplex(prop, objectStack) {\n return __awaiter(this, void 0, void 0, function* () {\n if (asset.Asset.isInstance(prop)) {\n if (prop.path !== undefined) {\n return { path: prop.path };\n }\n else if (prop.uri !== undefined) {\n return { uri: prop.uri };\n }\n else if (prop.text !== undefined) {\n return { text: \"...\" };\n }\n return undefined;\n }\n if (asset.Archive.isInstance(prop)) {\n if (prop.assets) {\n return { assets: yield massage(prop.assets, objectStack) };\n }\n else if (prop.path !== undefined) {\n return { path: prop.path };\n }\n else if (prop.uri !== undefined) {\n return { uri: prop.uri };\n }\n return undefined;\n }\n if (resource_1.Resource.isInstance(prop)) {\n // Emit a resource as a normal pojo. But filter out all our internal properties so that\n // they don't clutter the display/checkpoint with values not relevant to the application.\n //\n // In preview only, we mark the POJO with \"@isPulumiResource\" to indicate that it is derived\n // from a resource. This allows the engine to perform resource-specific filtering of unknowns\n // from output diffs during a preview. This filtering is not necessary during an update because\n // all property values are known.\n const pojo = yield serializeAllKeys(n => !n.startsWith(\"__\"));\n return !settings_1.isDryRun() ? pojo : Object.assign(Object.assign({}, pojo), { \"@isPulumiResource\": true });\n }\n if (prop instanceof Array) {\n const result = [];\n for (let i = 0; i < prop.length; i++) {\n result[i] = yield massage(prop[i], objectStack);\n }\n return result;\n }\n return yield serializeAllKeys(n => true);\n function serializeAllKeys(include) {\n return __awaiter(this, void 0, void 0, function* () {\n const obj = {};\n for (const k of Object.keys(prop)) {\n if (include(k)) {\n obj[k] = yield massage(prop[k], objectStack);\n }\n }\n return obj;\n });\n }\n });\n}\n/**\n * Add a transformation to all future resources constructed in this Pulumi stack.\n */\nfunction registerStackTransformation(t) {\n if (!stackResource) {\n throw new Error(\"The root stack resource was referenced before it was initialized.\");\n }\n stackResource.__transformations = [...(stackResource.__transformations || []), t];\n}\nexports.registerStackTransformation = registerStackTransformation;\n","\"use strict\";\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst output_1 = require(\"./output\");\nconst resource_1 = require(\"./resource\");\n/**\n * Manages a reference to a Pulumi stack. The referenced stack's outputs are available via the\n * `outputs` property or the `output` method.\n */\nclass StackReference extends resource_1.CustomResource {\n /**\n * Create a StackReference resource with the given unique name, arguments, and options.\n *\n * If args is not specified, the name of the referenced stack will be the name of the StackReference resource.\n *\n * @param name The _unique_ name of the stack reference.\n * @param args The arguments to use to populate this resource's properties.\n * @Param opts A bag of options that control this resource's behavior.\n */\n constructor(name, args, opts) {\n args = args || {};\n const stackReferenceName = args.name || name;\n super(\"pulumi:pulumi:StackReference\", name, {\n name: stackReferenceName,\n outputs: undefined,\n secretOutputNames: undefined,\n }, Object.assign(Object.assign({}, opts), { id: stackReferenceName }));\n }\n /**\n * Fetches the value of the named stack output, or undefined if the stack output was not found.\n *\n * @param name The name of the stack output to fetch.\n */\n getOutput(name) {\n // Note that this is subtly different from \"apply\" here. A default \"apply\" will set the secret bit if any\n // of the inputs are a secret, and this.outputs is always a secret if it contains any secrets. We do this dance\n // so we can ensure that the Output we return is not needlessly tainted as a secret.\n const value = output_1.all([output_1.output(name), this.outputs]).apply(([n, os]) => os[n]);\n // 'value' is an Output produced by our own `.apply` implementation. So it's safe to\n // `.allResources!` on it.\n return new output_1.Output(value.resources(), value.promise(), value.isKnown, isSecretOutputName(this, output_1.output(name)), value.allResources());\n }\n /**\n * Fetches the value of the named stack output, or throws an error if the output was not found.\n *\n * @param name The name of the stack output to fetch.\n */\n requireOutput(name) {\n const value = output_1.all([output_1.output(this.name), output_1.output(name), this.outputs]).apply(([stackname, n, os]) => {\n if (!os.hasOwnProperty(n)) {\n throw new Error(`Required output '${n}' does not exist on stack '${stackname}'.`);\n }\n return os[n];\n });\n return new output_1.Output(value.resources(), value.promise(), value.isKnown, isSecretOutputName(this, output_1.output(name)), value.allResources());\n }\n /**\n * Fetches the value promptly of the named stack output. May return undefined if the value is\n * not known for some reason.\n *\n * This operation is not supported (and will throw) if the named stack output is a secret.\n *\n * @param name The name of the stack output to fetch.\n */\n getOutputValue(name) {\n return __awaiter(this, void 0, void 0, function* () {\n const [out, isSecret] = yield this.readOutputValue(\"getOutputValue\", name, false /*required*/);\n if (isSecret) {\n throw new Error(\"Cannot call 'getOutputValue' if the referenced stack output is a secret. Use 'getOutput' instead.\");\n }\n return out;\n });\n }\n /**\n * Fetches the value promptly of the named stack output. Throws an error if the stack output is\n * not found.\n *\n * This operation is not supported (and will throw) if the named stack output is a secret.\n *\n * @param name The name of the stack output to fetch.\n */\n requireOutputValue(name) {\n return __awaiter(this, void 0, void 0, function* () {\n const [out, isSecret] = yield this.readOutputValue(\"requireOutputSync\", name, true /*required*/);\n if (isSecret) {\n throw new Error(\"Cannot call 'requireOutputValue' if the referenced stack output is a secret. Use 'requireOutput' instead.\");\n }\n return out;\n });\n }\n readOutputValue(callerName, outputName, required) {\n return __awaiter(this, void 0, void 0, function* () {\n const out = required ? this.requireOutput(outputName) : this.getOutput(outputName);\n return Promise.all([out.promise(), out.isSecret]);\n });\n }\n}\nexports.StackReference = StackReference;\nfunction isSecretOutputName(sr, name) {\n return __awaiter(this, void 0, void 0, function* () {\n const nameOutput = output_1.output(name);\n // If either the name or set of secret outputs is unknown, we can't do anything smart, so we just copy the\n // secretness from the entire outputs value.\n if (!((yield nameOutput.isKnown) && (yield sr.secretOutputNames.isKnown))) {\n return yield sr.outputs.isSecret;\n }\n // Otherwise, if we have a list of outputs we know are secret, we can use that list to determine if this\n // output should be secret. Names could be falsy here in cases where we are using an older CLI that did\n // not return this information (in this case we again fallback to the secretness of outputs value).\n const names = yield sr.secretOutputNames.promise();\n if (!names) {\n return yield sr.outputs.isSecret;\n }\n return names.includes(yield nameOutput.promise());\n });\n}\n","\"use strict\";\n// Copyright 2016-2018, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nvar _a;\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Common code for doing RTTI typechecks. RTTI is done by having a boolean property on an object\n * with a special name (like \"__resource\" or \"__asset\"). This function checks that the object\n * exists, has a **boolean** property with that name, and that that boolean property has the value\n * of 'true'. Checking that property is 'boolean' helps ensure that this test works even on proxies\n * that synthesize properties dynamically (like Output). Checking that the property has the 'true'\n * value isn't strictly necessary, but works to make sure that the impls are following a common\n * pattern.\n *\n * @internal\n */\nfunction isInstance(obj, name) {\n return hasTrueBooleanMember(obj, name);\n}\nexports.isInstance = isInstance;\n/** @internal */\nfunction hasTrueBooleanMember(obj, memberName) {\n if (obj === undefined || obj === null) {\n return false;\n }\n const val = obj[memberName];\n if (typeof val !== \"boolean\") {\n return false;\n }\n return val === true;\n}\nexports.hasTrueBooleanMember = hasTrueBooleanMember;\n// Workaround errors we sometimes get on some machines saying that Object.values is not available.\n/** @internal */\nfunction values(obj) {\n const result = [];\n for (const key of Object.keys(obj)) {\n result.push(obj[key]);\n }\n return result;\n}\nexports.values = values;\n/** @internal */\nfunction union(set1, set2) {\n return new Set([...set1, ...set2]);\n}\nexports.union = union;\n/** @internal */\nexports.disableResourceReferences = process.env.PULUMI_DISABLE_RESOURCE_REFERENCES === \"1\" ||\n (_a = process.env.PULUMI_DISABLE_RESOURCE_REFERENCES, (_a !== null && _a !== void 0 ? _a : \"\")).toUpperCase() === \"TRUE\";\n","\"use strict\";\n// Copyright 2016-2020, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst childProcess = require(\"child_process\");\nconst errors_1 = require(\"./errors\");\n/** @internal */\nclass CommandResult {\n constructor(stdout, stderr, code, err) {\n this.stdout = stdout;\n this.stderr = stderr;\n this.code = code;\n this.err = err;\n }\n toString() {\n let errStr = \"\";\n if (this.err) {\n errStr = this.err.toString();\n }\n return `code: ${this.code}\\n stdout: ${this.stdout}\\n stderr: ${this.stderr}\\n err?: ${errStr}\\n`;\n }\n}\nexports.CommandResult = CommandResult;\nconst unknownErrCode = -2;\n/** @internal */\nfunction runPulumiCmd(args, cwd, additionalEnv, onOutput) {\n // all commands should be run in non-interactive mode.\n // this causes commands to fail rather than prompting for input (and thus hanging indefinitely)\n args.push(\"--non-interactive\");\n const env = Object.assign(Object.assign({}, process.env), additionalEnv);\n return new Promise((resolve, reject) => {\n const proc = childProcess.spawn(\"pulumi\", args, { env, cwd });\n // TODO: write to buffers and avoid concatenation\n let stdout = \"\";\n let stderr = \"\";\n proc.stdout.on(\"data\", (data) => {\n if (data && data.toString) {\n data = data.toString();\n }\n if (onOutput) {\n onOutput(data);\n }\n stdout += data;\n });\n proc.stderr.on(\"data\", (data) => {\n stderr += data;\n });\n proc.on(\"exit\", (code, signal) => {\n const resCode = code !== null ? code : unknownErrCode;\n const result = new CommandResult(stdout, stderr, resCode);\n if (code !== 0) {\n return reject(errors_1.createCommandError(result));\n }\n return resolve(result);\n });\n proc.on(\"error\", (err) => {\n const result = new CommandResult(stdout, stderr, unknownErrCode, err);\n return reject(errors_1.createCommandError(result));\n });\n });\n}\nexports.runPulumiCmd = runPulumiCmd;\n","\"use strict\";\n// Copyright 2016-2020, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * CommandError is an error resulting from invocation of a Pulumi Command.\n * @alpha\n */\nclass CommandError extends Error {\n /** @internal */\n constructor(commandResult) {\n super(commandResult.toString());\n this.commandResult = commandResult;\n this.name = \"CommandError\";\n }\n}\nexports.CommandError = CommandError;\n/**\n * ConcurrentUpdateError is thrown when attempting to update a stack that already has an update in progress.\n */\nclass ConcurrentUpdateError extends CommandError {\n /** @internal */\n constructor(commandResult) {\n super(commandResult);\n this.name = \"ConcurrentUpdateError\";\n }\n}\nexports.ConcurrentUpdateError = ConcurrentUpdateError;\n/**\n * StackNotFoundError is thrown when attempting to select a stack that does not exist.\n */\nclass StackNotFoundError extends CommandError {\n /** @internal */\n constructor(commandResult) {\n super(commandResult);\n this.name = \"StackNotFoundError\";\n }\n}\nexports.StackNotFoundError = StackNotFoundError;\n/**\n * StackAlreadyExistsError is thrown when attempting to create a stack that already exists.\n */\nclass StackAlreadyExistsError extends CommandError {\n /** @internal */\n constructor(commandResult) {\n super(commandResult);\n this.name = \"StackAlreadyExistsError\";\n }\n}\nexports.StackAlreadyExistsError = StackAlreadyExistsError;\nconst notFoundRegex = new RegExp(\"no stack named.*found\");\nconst alreadyExistsRegex = new RegExp(\"stack.*already exists\");\nconst conflictText = \"[409] Conflict: Another update is currently in progress.\";\n/** @internal */\nfunction createCommandError(result) {\n const stderr = result.stderr;\n return (notFoundRegex.test(stderr) ? new StackNotFoundError(result) :\n alreadyExistsRegex.test(stderr) ? new StackAlreadyExistsError(result) :\n stderr.indexOf(conflictText) >= 0 ? new ConcurrentUpdateError(result) :\n new CommandError(result));\n}\nexports.createCommandError = createCommandError;\n","\"use strict\";\n// Copyright 2016-2020, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__export(require(\"./cmd\"));\n__export(require(\"./errors\"));\n__export(require(\"./stack\"));\n__export(require(\"./localWorkspace\"));\n","\"use strict\";\n// Copyright 2016-2020, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst fs = require(\"fs\");\nconst yaml = require(\"js-yaml\");\nconst os = require(\"os\");\nconst upath = require(\"upath\");\nconst cmd_1 = require(\"./cmd\");\nconst stack_1 = require(\"./stack\");\n/**\n * LocalWorkspace is a default implementation of the Workspace interface.\n * A Workspace is the execution context containing a single Pulumi project, a program,\n * and multiple stacks. Workspaces are used to manage the execution environment,\n * providing various utilities such as plugin installation, environment configuration\n * ($PULUMI_HOME), and creation, deletion, and listing of Stacks.\n * LocalWorkspace relies on Pulumi.yaml and Pulumi..yaml as the intermediate format\n * for Project and Stack settings. Modifying ProjectSettings will\n * alter the Workspace Pulumi.yaml file, and setting config on a Stack will modify the Pulumi..yaml file.\n * This is identical to the behavior of Pulumi CLI driven workspaces.\n *\n * @alpha\n */\nclass LocalWorkspace {\n constructor(opts) {\n let dir = \"\";\n let envs = {};\n if (opts) {\n const { workDir, pulumiHome, program, envVars, secretsProvider } = opts;\n if (workDir) {\n dir = workDir;\n }\n this.pulumiHome = pulumiHome;\n this.program = program;\n this.secretsProvider = secretsProvider;\n envs = Object.assign({}, envVars);\n }\n if (!dir) {\n dir = fs.mkdtempSync(upath.joinSafe(os.tmpdir(), \"automation-\"));\n }\n this.workDir = dir;\n this.envVars = envs;\n const readinessPromises = [];\n if (opts && opts.projectSettings) {\n readinessPromises.push(this.saveProjectSettings(opts.projectSettings));\n }\n if (opts && opts.stackSettings) {\n for (const [name, value] of Object.entries(opts.stackSettings)) {\n readinessPromises.push(this.saveStackSettings(name, value));\n }\n }\n this.ready = Promise.all(readinessPromises);\n }\n /**\n * Creates a workspace using the specified options. Used for maximal control and customization\n * of the underlying environment before any stacks are created or selected.\n *\n * @param opts Options used to configure the Workspace\n */\n static create(opts) {\n return __awaiter(this, void 0, void 0, function* () {\n const ws = new LocalWorkspace(opts);\n yield ws.ready;\n return ws;\n });\n }\n static createStack(args, opts) {\n return __awaiter(this, void 0, void 0, function* () {\n if (isInlineProgramArgs(args)) {\n return yield this.inlineSourceStackHelper(args, stack_1.Stack.create, opts);\n }\n else if (isLocalProgramArgs(args)) {\n return yield this.localSourceStackHelper(args, stack_1.Stack.create, opts);\n }\n throw new Error(`unexpected args: ${args}`);\n });\n }\n static selectStack(args, opts) {\n return __awaiter(this, void 0, void 0, function* () {\n if (isInlineProgramArgs(args)) {\n return yield this.inlineSourceStackHelper(args, stack_1.Stack.select, opts);\n }\n else if (isLocalProgramArgs(args)) {\n return yield this.localSourceStackHelper(args, stack_1.Stack.select, opts);\n }\n throw new Error(`unexpected args: ${args}`);\n });\n }\n static createOrSelectStack(args, opts) {\n return __awaiter(this, void 0, void 0, function* () {\n if (isInlineProgramArgs(args)) {\n return yield this.inlineSourceStackHelper(args, stack_1.Stack.createOrSelect, opts);\n }\n else if (isLocalProgramArgs(args)) {\n return yield this.localSourceStackHelper(args, stack_1.Stack.createOrSelect, opts);\n }\n throw new Error(`unexpected args: ${args}`);\n });\n }\n static localSourceStackHelper(args, initFn, opts) {\n return __awaiter(this, void 0, void 0, function* () {\n let wsOpts = { workDir: args.workDir };\n if (opts) {\n wsOpts = Object.assign(Object.assign({}, opts), { workDir: args.workDir });\n }\n const ws = new LocalWorkspace(wsOpts);\n yield ws.ready;\n return yield initFn(args.stackName, ws);\n });\n }\n static inlineSourceStackHelper(args, initFn, opts) {\n return __awaiter(this, void 0, void 0, function* () {\n let wsOpts = { program: args.program };\n if (opts) {\n wsOpts = Object.assign(Object.assign({}, opts), { program: args.program });\n }\n if (!wsOpts.projectSettings) {\n wsOpts.projectSettings = defaultProject(args.projectName);\n }\n const ws = new LocalWorkspace(wsOpts);\n yield ws.ready;\n return yield initFn(args.stackName, ws);\n });\n }\n /**\n * Returns the settings object for the current project if any\n * LocalWorkspace reads settings from the Pulumi.yaml in the workspace.\n * A workspace can contain only a single project at a time.\n */\n projectSettings() {\n return __awaiter(this, void 0, void 0, function* () {\n for (const ext of settingsExtensions) {\n const isJSON = ext === \".json\";\n const path = upath.joinSafe(this.workDir, `Pulumi${ext}`);\n if (!fs.existsSync(path)) {\n continue;\n }\n const contents = fs.readFileSync(path).toString();\n if (isJSON) {\n return JSON.parse(contents);\n }\n return yaml.safeLoad(contents);\n }\n throw new Error(`failed to find project settings file in workdir: ${this.workDir}`);\n });\n }\n /**\n * Overwrites the settings object in the current project.\n * There can only be a single project per workspace. Fails if new project name does not match old.\n * LocalWorkspace writes this value to a Pulumi.yaml file in Workspace.WorkDir().\n *\n * @param settings The settings object to save to the Workspace.\n */\n saveProjectSettings(settings) {\n return __awaiter(this, void 0, void 0, function* () {\n let foundExt = \".yaml\";\n for (const ext of settingsExtensions) {\n const testPath = upath.joinSafe(this.workDir, `Pulumi${ext}`);\n if (fs.existsSync(testPath)) {\n foundExt = ext;\n break;\n }\n }\n const path = upath.joinSafe(this.workDir, `Pulumi${foundExt}`);\n let contents;\n if (foundExt === \".json\") {\n contents = JSON.stringify(settings, null, 4);\n }\n else {\n contents = yaml.safeDump(settings, { skipInvalid: true });\n }\n return fs.writeFileSync(path, contents);\n });\n }\n /**\n * Returns the settings object for the stack matching the specified stack name if any.\n * LocalWorkspace reads this from a Pulumi..yaml file in Workspace.WorkDir().\n *\n * @param stackName The stack to retrieve settings from.\n */\n stackSettings(stackName) {\n return __awaiter(this, void 0, void 0, function* () {\n const stackSettingsName = getStackSettingsName(stackName);\n for (const ext of settingsExtensions) {\n const isJSON = ext === \".json\";\n const path = upath.joinSafe(this.workDir, `Pulumi.${stackSettingsName}${ext}`);\n if (!fs.existsSync(path)) {\n continue;\n }\n const contents = fs.readFileSync(path).toString();\n if (isJSON) {\n return JSON.parse(contents);\n }\n return yaml.safeLoad(contents);\n }\n throw new Error(`failed to find stack settings file in workdir: ${this.workDir}`);\n });\n }\n /**\n * Overwrites the settings object for the stack matching the specified stack name.\n * LocalWorkspace writes this value to a Pulumi..yaml file in Workspace.WorkDir()\n *\n * @param stackName The stack to operate on.\n * @param settings The settings object to save.\n */\n saveStackSettings(stackName, settings) {\n return __awaiter(this, void 0, void 0, function* () {\n const stackSettingsName = getStackSettingsName(stackName);\n let foundExt = \".yaml\";\n for (const ext of settingsExtensions) {\n const testPath = upath.joinSafe(this.workDir, `Pulumi.${stackSettingsName}${ext}`);\n if (fs.existsSync(testPath)) {\n foundExt = ext;\n break;\n }\n }\n const path = upath.joinSafe(this.workDir, `Pulumi.${stackSettingsName}${foundExt}`);\n let contents;\n if (foundExt === \".json\") {\n contents = JSON.stringify(settings, null, 4);\n }\n else {\n contents = yaml.safeDump(settings, { skipInvalid: true });\n }\n return fs.writeFileSync(path, contents);\n });\n }\n /**\n * Creates and sets a new stack with the stack name, failing if one already exists.\n *\n * @param stackName The stack to create.\n */\n createStack(stackName) {\n return __awaiter(this, void 0, void 0, function* () {\n const args = [\"stack\", \"init\", stackName];\n if (this.secretsProvider) {\n args.push(\"--secrets-provider\", this.secretsProvider);\n }\n yield this.runPulumiCmd(args);\n });\n }\n /**\n * Selects and sets an existing stack matching the stack name, failing if none exists.\n *\n * @param stackName The stack to select.\n */\n selectStack(stackName) {\n return __awaiter(this, void 0, void 0, function* () {\n yield this.runPulumiCmd([\"stack\", \"select\", stackName]);\n });\n }\n /**\n * Deletes the stack and all associated configuration and history.\n *\n * @param stackName The stack to remove\n */\n removeStack(stackName) {\n return __awaiter(this, void 0, void 0, function* () {\n yield this.runPulumiCmd([\"stack\", \"rm\", \"--yes\", stackName]);\n });\n }\n /**\n * Returns the value associated with the specified stack name and key,\n * scoped to the current workspace. LocalWorkspace reads this config from the matching Pulumi.stack.yaml file.\n *\n * @param stackName The stack to read config from\n * @param key The key to use for the config lookup\n */\n getConfig(stackName, key) {\n return __awaiter(this, void 0, void 0, function* () {\n yield this.selectStack(stackName);\n const result = yield this.runPulumiCmd([\"config\", \"get\", key, \"--json\"]);\n return JSON.parse(result.stdout);\n });\n }\n /**\n * Returns the config map for the specified stack name, scoped to the current workspace.\n * LocalWorkspace reads this config from the matching Pulumi.stack.yaml file.\n *\n * @param stackName The stack to read config from\n */\n getAllConfig(stackName) {\n return __awaiter(this, void 0, void 0, function* () {\n yield this.selectStack(stackName);\n const result = yield this.runPulumiCmd([\"config\", \"--show-secrets\", \"--json\"]);\n return JSON.parse(result.stdout);\n });\n }\n /**\n * Sets the specified key-value pair on the provided stack name.\n * LocalWorkspace writes this value to the matching Pulumi..yaml file in Workspace.WorkDir().\n *\n * @param stackName The stack to operate on\n * @param key The config key to set\n * @param value The value to set\n */\n setConfig(stackName, key, value) {\n return __awaiter(this, void 0, void 0, function* () {\n yield this.selectStack(stackName);\n const secretArg = value.secret ? \"--secret\" : \"--plaintext\";\n yield this.runPulumiCmd([\"config\", \"set\", key, value.value, secretArg]);\n });\n }\n /**\n * Sets all values in the provided config map for the specified stack name.\n * LocalWorkspace writes the config to the matching Pulumi..yaml file in Workspace.WorkDir().\n *\n * @param stackName The stack to operate on\n * @param config The `ConfigMap` to upsert against the existing config.\n */\n setAllConfig(stackName, config) {\n return __awaiter(this, void 0, void 0, function* () {\n let args = [\"config\", \"set-all\", \"--stack\", stackName];\n for (const [key, value] of Object.entries(config)) {\n const secretArg = value.secret ? \"--secret\" : \"--plaintext\";\n args = [...args, secretArg, `${key}=${value.value}`];\n }\n yield this.runPulumiCmd(args);\n });\n }\n /**\n * Removes the specified key-value pair on the provided stack name.\n * It will remove any matching values in the Pulumi..yaml file in Workspace.WorkDir().\n *\n * @param stackName The stack to operate on\n * @param key The config key to remove\n */\n removeConfig(stackName, key) {\n return __awaiter(this, void 0, void 0, function* () {\n yield this.selectStack(stackName);\n yield this.runPulumiCmd([\"config\", \"rm\", key]);\n });\n }\n /**\n *\n * Removes all values in the provided key list for the specified stack name\n * It will remove any matching values in the Pulumi..yaml file in Workspace.WorkDir().\n *\n * @param stackName The stack to operate on\n * @param keys The list of keys to remove from the underlying config\n */\n removeAllConfig(stackName, keys) {\n return __awaiter(this, void 0, void 0, function* () {\n yield this.runPulumiCmd([\"config\", \"rm-all\", \"--stack\", stackName, ...keys]);\n });\n }\n /**\n * Gets and sets the config map used with the last update for Stack matching stack name.\n * It will overwrite all configuration in the Pulumi..yaml file in Workspace.WorkDir().\n *\n * @param stackName The stack to refresh\n */\n refreshConfig(stackName) {\n return __awaiter(this, void 0, void 0, function* () {\n yield this.selectStack(stackName);\n yield this.runPulumiCmd([\"config\", \"refresh\", \"--force\"]);\n return this.getAllConfig(stackName);\n });\n }\n /**\n * Returns the currently authenticated user.\n */\n whoAmI() {\n return __awaiter(this, void 0, void 0, function* () {\n const result = yield this.runPulumiCmd([\"whoami\"]);\n return { user: result.stdout.trim() };\n });\n }\n /**\n * Returns a summary of the currently selected stack, if any.\n */\n stack() {\n return __awaiter(this, void 0, void 0, function* () {\n const stacks = yield this.listStacks();\n for (const stack of stacks) {\n if (stack.current) {\n return stack;\n }\n }\n return undefined;\n });\n }\n /**\n * Returns all Stacks created under the current Project.\n * This queries underlying backend and may return stacks not present in the Workspace (as Pulumi..yaml files).\n */\n listStacks() {\n return __awaiter(this, void 0, void 0, function* () {\n const result = yield this.runPulumiCmd([\"stack\", \"ls\", \"--json\"]);\n return JSON.parse(result.stdout);\n });\n }\n /**\n * Installs a plugin in the Workspace, for example to use cloud providers like AWS or GCP.\n *\n * @param name the name of the plugin.\n * @param version the version of the plugin e.g. \"v1.0.0\".\n * @param kind the kind of plugin, defaults to \"resource\"\n */\n installPlugin(name, version, kind = \"resource\") {\n return __awaiter(this, void 0, void 0, function* () {\n yield this.runPulumiCmd([\"plugin\", \"install\", kind, name, version]);\n });\n }\n /**\n * Removes a plugin from the Workspace matching the specified name and version.\n *\n * @param name the optional name of the plugin.\n * @param versionRange optional semver range to check when removing plugins matching the given name\n * e.g. \"1.0.0\", \">1.0.0\".\n * @param kind he kind of plugin, defaults to \"resource\".\n */\n removePlugin(name, versionRange, kind = \"resource\") {\n return __awaiter(this, void 0, void 0, function* () {\n const args = [\"plugin\", \"rm\", kind];\n if (name) {\n args.push(name);\n }\n if (versionRange) {\n args.push(versionRange);\n }\n args.push(\"--yes\");\n yield this.runPulumiCmd(args);\n });\n }\n /**\n * Returns a list of all plugins installed in the Workspace.\n */\n listPlugins() {\n return __awaiter(this, void 0, void 0, function* () {\n const result = yield this.runPulumiCmd([\"plugin\", \"ls\", \"--json\"]);\n return JSON.parse(result.stdout, (key, value) => {\n if (key === \"installTime\" || key === \"lastUsedTime\") {\n return new Date(value);\n }\n return value;\n });\n });\n }\n /**\n * exportStack exports the deployment state of the stack.\n * This can be combined with Workspace.importStack to edit a stack's state (such as recovery from failed deployments).\n *\n * @param stackName the name of the stack.\n */\n exportStack(stackName) {\n return __awaiter(this, void 0, void 0, function* () {\n yield this.selectStack(stackName);\n const result = yield this.runPulumiCmd([\"stack\", \"export\", \"--show-secrets\"]);\n return JSON.parse(result.stdout);\n });\n }\n /**\n * importStack imports the specified deployment state into a pre-existing stack.\n * This can be combined with Workspace.exportStack to edit a stack's state (such as recovery from failed deployments).\n *\n * @param stackName the name of the stack.\n * @param state the stack state to import.\n */\n importStack(stackName, state) {\n return __awaiter(this, void 0, void 0, function* () {\n yield this.selectStack(stackName);\n const randomSuffix = Math.floor(100000 + Math.random() * 900000);\n const filepath = upath.joinSafe(os.tmpdir(), `automation-${randomSuffix}`);\n const contents = JSON.stringify(state, null, 4);\n fs.writeFileSync(filepath, contents);\n yield this.runPulumiCmd([\"stack\", \"import\", \"--file\", filepath]);\n fs.unlinkSync(filepath);\n });\n }\n /**\n * serializeArgsForOp is hook to provide additional args to every CLI commands before they are executed.\n * Provided with stack name,\n * returns a list of args to append to an invoked command [\"--config=...\", ]\n * LocalWorkspace does not utilize this extensibility point.\n */\n serializeArgsForOp(_) {\n return __awaiter(this, void 0, void 0, function* () {\n // LocalWorkspace does not utilize this extensibility point.\n return [];\n });\n }\n /**\n * postCommandCallback is a hook executed after every command. Called with the stack name.\n * An extensibility point to perform workspace cleanup (CLI operations may create/modify a Pulumi.stack.yaml)\n * LocalWorkspace does not utilize this extensibility point.\n */\n postCommandCallback(_) {\n return __awaiter(this, void 0, void 0, function* () {\n // LocalWorkspace does not utilize this extensibility point.\n return;\n });\n }\n runPulumiCmd(args) {\n return __awaiter(this, void 0, void 0, function* () {\n let envs = {};\n if (this.pulumiHome) {\n envs[\"PULUMI_HOME\"] = this.pulumiHome;\n }\n envs = Object.assign(Object.assign({}, envs), this.envVars);\n return cmd_1.runPulumiCmd(args, this.workDir, envs);\n });\n }\n}\nexports.LocalWorkspace = LocalWorkspace;\n/**\n * Returns true if the provided `args` object satisfies the `LocalProgramArgs` interface.\n *\n * @param args The args object to evaluate\n */\nfunction isLocalProgramArgs(args) {\n return args.workDir !== undefined;\n}\n/**\n * Returns true if the provided `args` object satisfies the `InlineProgramArgs` interface.\n *\n * @param args The args object to evaluate\n */\nfunction isInlineProgramArgs(args) {\n return args.projectName !== undefined &&\n args.program !== undefined;\n}\nconst settingsExtensions = [\".yaml\", \".yml\", \".json\"];\nfunction getStackSettingsName(name) {\n const parts = name.split(\"/\");\n if (parts.length < 1) {\n return name;\n }\n return parts[parts.length - 1];\n}\nfunction defaultProject(projectName) {\n const settings = { name: projectName, runtime: \"nodejs\" };\n return settings;\n}\n","\"use strict\";\n// Copyright 2016-2020, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst errors_1 = require(\"../../errors\");\nconst log = require(\"../../log\");\nconst runtime = require(\"../../runtime\");\nconst langproto = require(\"../../proto/language_pb.js\");\nconst plugproto = require(\"../../proto/plugin_pb.js\");\n// maxRPCMessageSize raises the gRPC Max Message size from `4194304` (4mb) to `419430400` (400mb)\n/** @internal */\nexports.maxRPCMessageSize = 1024 * 1024 * 400;\n/** @internal */\nclass LanguageServer {\n constructor(program) {\n this.program = program;\n this.running = false;\n }\n onPulumiExit() {\n // check for leaks once the CLI exits\n const [leaks, leakMessage] = runtime.leakedPromises();\n if (leaks.size !== 0) {\n throw new Error(leakMessage);\n }\n // these are globals and we need to clean up after ourselves\n runtime.resetOptions(\"\", \"\", -1, \"\", \"\", false);\n }\n getRequiredPlugins(call, callback) {\n const resp = new langproto.GetRequiredPluginsResponse();\n resp.setPluginsList([]);\n callback(undefined, resp);\n }\n run(call, callback) {\n var _a;\n return __awaiter(this, void 0, void 0, function* () {\n const req = call.request;\n const resp = new langproto.RunResponse();\n this.running = true;\n const errorSet = new Set();\n const uncaughtHandler = newUncaughtHandler(errorSet);\n try {\n const args = req.getArgsList();\n const engineAddr = args && args.length > 0 ? args[0] : \"\";\n runtime.resetOptions(req.getProject(), req.getStack(), req.getParallel(), engineAddr, req.getMonitorAddress(), req.getDryrun());\n const config = {};\n for (const [k, v] of ((_a = req.getConfigMap()) === null || _a === void 0 ? void 0 : _a.entries()) || []) {\n config[k] = v;\n }\n runtime.setAllConfig(config);\n process.on(\"uncaughtException\", uncaughtHandler);\n // @ts-ignore 'unhandledRejection' will almost always invoke uncaughtHandler with an Error. so\n // just suppress the TS strictness here.\n process.on(\"unhandledRejection\", uncaughtHandler);\n try {\n yield runtime.runInPulumiStack(this.program);\n yield runtime.disconnect();\n process.off(\"uncaughtException\", uncaughtHandler);\n process.off(\"unhandledRejection\", uncaughtHandler);\n }\n catch (e) {\n yield runtime.disconnect();\n process.off(\"uncaughtException\", uncaughtHandler);\n process.off(\"unhandledRejection\", uncaughtHandler);\n if (!errors_1.isGrpcError(e)) {\n throw e;\n }\n }\n if (errorSet.size !== 0 || log.hasErrors()) {\n throw new Error(\"One or more errors occurred\");\n }\n }\n catch (e) {\n const err = e instanceof Error ? e : new Error(`unknown error ${e}`);\n resp.setError(err.message);\n callback(err, undefined);\n }\n callback(undefined, resp);\n });\n }\n getPluginInfo(call, callback) {\n const resp = new plugproto.PluginInfo();\n resp.setVersion(\"1.0.0\");\n callback(undefined, resp);\n }\n}\nexports.LanguageServer = LanguageServer;\nfunction newUncaughtHandler(errorSet) {\n return (err) => {\n // In node, if you throw an error in a chained promise, but the exception is not finally\n // handled, then you can end up getting an unhandledRejection for each exception/promise\n // pair. Because the exception is the same through all of these, we keep track of it and\n // only report it once so the user doesn't get N messages for the same thing.\n if (errorSet.has(err)) {\n return;\n }\n errorSet.add(err);\n // Default message should be to include the full stack (which includes the message), or\n // fallback to just the message if we can't get the stack.\n //\n // If both the stack and message are empty, then just stringify the err object itself. This\n // is also necessary as users can throw arbitrary things in JS (including non-Errors).\n let defaultMessage = \"\";\n if (!!err) {\n defaultMessage = err.stack || err.message || (\"\" + err);\n }\n // First, log the error.\n if (errors_1.RunError.isInstance(err)) {\n // Always hide the stack for RunErrors.\n log.error(err.message);\n }\n else if (errors_1.ResourceError.isInstance(err)) {\n // Hide the stack if requested to by the ResourceError creator.\n const message = err.hideStack ? err.message : defaultMessage;\n log.error(message, err.resource);\n }\n else if (!errors_1.isGrpcError(err)) {\n log.error(`Unhandled exception: ${defaultMessage}`);\n }\n };\n}\n","\"use strict\";\n// Copyright 2016-2020, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst grpc = require(\"@grpc/grpc-js\");\nconst cmd_1 = require(\"./cmd\");\nconst errors_1 = require(\"./errors\");\nconst server_1 = require(\"./server\");\nconst langrpc = require(\"../../proto/language_grpc_pb.js\");\nconst secretSentinel = \"[secret]\";\n/**\n * Stack is an isolated, independently configurable instance of a Pulumi program.\n * Stack exposes methods for the full pulumi lifecycle (up/preview/refresh/destroy), as well as managing configuration.\n * Multiple Stacks are commonly used to denote different phases of development\n * (such as development, staging and production) or feature branches (such as feature-x-dev, jane-feature-x-dev).\n *\n * @alpha\n */\nclass Stack {\n constructor(name, workspace, mode) {\n this.name = name;\n this.workspace = workspace;\n switch (mode) {\n case \"create\":\n this.ready = workspace.createStack(name);\n return this;\n case \"select\":\n this.ready = workspace.selectStack(name);\n return this;\n case \"createOrSelect\":\n this.ready = workspace.createStack(name).catch((err) => {\n if (err instanceof errors_1.StackAlreadyExistsError) {\n return workspace.selectStack(name);\n }\n throw err;\n });\n return this;\n default:\n throw new Error(`unexpected Stack creation mode: ${mode}`);\n }\n }\n /**\n * Creates a new stack using the given workspace, and stack name.\n * It fails if a stack with that name already exists\n *\n * @param name The name identifying the Stack.\n * @param workspace The Workspace the Stack was created from.\n */\n static create(name, workspace) {\n return __awaiter(this, void 0, void 0, function* () {\n const stack = new Stack(name, workspace, \"create\");\n yield stack.ready;\n return stack;\n });\n }\n /**\n * Selects stack using the given workspace, and stack name.\n * It returns an error if the given Stack does not exist. All LocalWorkspace operations will call `select`\n * before running.\n *\n * @param name The name identifying the Stack.\n * @param workspace The Workspace the Stack was created from.\n */\n static select(name, workspace) {\n return __awaiter(this, void 0, void 0, function* () {\n const stack = new Stack(name, workspace, \"select\");\n yield stack.ready;\n return stack;\n });\n }\n /**\n * Tries to create a new stack using the given workspace and\n * stack name if the stack does not already exist,\n * or falls back to selecting the existing stack. If the stack does not exist,\n * it will be created and selected.\n *\n * @param name The name identifying the Stack.\n * @param workspace The Workspace the Stack was created from.\n */\n static createOrSelect(name, workspace) {\n return __awaiter(this, void 0, void 0, function* () {\n const stack = new Stack(name, workspace, \"createOrSelect\");\n yield stack.ready;\n return stack;\n });\n }\n /**\n * Creates or updates the resources in a stack by executing the program in the Workspace.\n * https://www.pulumi.com/docs/reference/cli/pulumi_up/\n *\n * @param opts Options to customize the behavior of the update.\n */\n up(opts) {\n var _a;\n return __awaiter(this, void 0, void 0, function* () {\n const args = [\"up\", \"--yes\", \"--skip-preview\"];\n let kind = execKind.local;\n let program = this.workspace.program;\n yield this.workspace.selectStack(this.name);\n if (opts) {\n if (opts.program) {\n program = opts.program;\n }\n if (opts.message) {\n args.push(\"--message\", opts.message);\n }\n if (opts.expectNoChanges) {\n args.push(\"--expect-no-changes\");\n }\n if (opts.diff) {\n args.push(\"--diff\");\n }\n if (opts.replace) {\n for (const rURN of opts.replace) {\n args.push(\"--replace\", rURN);\n }\n }\n if (opts.target) {\n for (const tURN of opts.target) {\n args.push(\"--target\", tURN);\n }\n }\n if (opts.targetDependents) {\n args.push(\"--target-dependents\");\n }\n if (opts.parallel) {\n args.push(\"--parallel\", opts.parallel.toString());\n }\n }\n let onExit = () => { return; };\n if (program) {\n kind = execKind.inline;\n const server = new grpc.Server({\n \"grpc.max_receive_message_length\": server_1.maxRPCMessageSize,\n });\n const languageServer = new server_1.LanguageServer(program);\n server.addService(langrpc.LanguageRuntimeService, languageServer);\n const port = yield new Promise((resolve, reject) => {\n server.bindAsync(`0.0.0.0:0`, grpc.ServerCredentials.createInsecure(), (err, p) => {\n if (err) {\n reject(err);\n }\n else {\n resolve(p);\n }\n });\n });\n server.start();\n onExit = () => {\n languageServer.onPulumiExit();\n server.forceShutdown();\n };\n args.push(`--client=127.0.0.1:${port}`);\n }\n args.push(\"--exec-kind\", kind);\n let upResult;\n try {\n upResult = yield this.runPulumiCmd(args, (_a = opts) === null || _a === void 0 ? void 0 : _a.onOutput);\n }\n finally {\n onExit();\n }\n // TODO: do this in parallel after this is fixed https://github.com/pulumi/pulumi/issues/6050\n const outputs = yield this.outputs();\n const summary = yield this.info();\n return {\n stdout: upResult.stdout,\n stderr: upResult.stderr,\n summary: summary,\n outputs: outputs,\n };\n });\n }\n /**\n * Performs a dry-run update to a stack, returning pending changes.\n * https://www.pulumi.com/docs/reference/cli/pulumi_preview/\n *\n * @param opts Options to customize the behavior of the preview.\n */\n preview(opts) {\n return __awaiter(this, void 0, void 0, function* () {\n // TODO JSON\n const args = [\"preview\"];\n let kind = execKind.local;\n let program = this.workspace.program;\n yield this.workspace.selectStack(this.name);\n if (opts) {\n if (opts.program) {\n program = opts.program;\n }\n if (opts.message) {\n args.push(\"--message\", opts.message);\n }\n if (opts.expectNoChanges) {\n args.push(\"--expect-no-changes\");\n }\n if (opts.diff) {\n args.push(\"--diff\");\n }\n if (opts.replace) {\n for (const rURN of opts.replace) {\n args.push(\"--replace\", rURN);\n }\n }\n if (opts.target) {\n for (const tURN of opts.target) {\n args.push(\"--target\", tURN);\n }\n }\n if (opts.targetDependents) {\n args.push(\"--target-dependents\");\n }\n if (opts.parallel) {\n args.push(\"--parallel\", opts.parallel.toString());\n }\n }\n let onExit = () => { return; };\n if (program) {\n kind = execKind.inline;\n const server = new grpc.Server({\n \"grpc.max_receive_message_length\": server_1.maxRPCMessageSize,\n });\n const languageServer = new server_1.LanguageServer(program);\n server.addService(langrpc.LanguageRuntimeService, languageServer);\n const port = yield new Promise((resolve, reject) => {\n server.bindAsync(`0.0.0.0:0`, grpc.ServerCredentials.createInsecure(), (err, p) => {\n if (err) {\n reject(err);\n }\n else {\n resolve(p);\n }\n });\n });\n server.start();\n onExit = () => {\n languageServer.onPulumiExit();\n server.forceShutdown();\n };\n args.push(`--client=127.0.0.1:${port}`);\n }\n args.push(\"--exec-kind\", kind);\n let preResult;\n try {\n preResult = yield this.runPulumiCmd(args);\n }\n finally {\n onExit();\n }\n return {\n stdout: preResult.stdout,\n stderr: preResult.stderr,\n };\n });\n }\n /**\n * Compares the current stack’s resource state with the state known to exist in the actual\n * cloud provider. Any such changes are adopted into the current stack.\n *\n * @param opts Options to customize the behavior of the refresh.\n */\n refresh(opts) {\n var _a;\n return __awaiter(this, void 0, void 0, function* () {\n const args = [\"refresh\", \"--yes\", \"--skip-preview\"];\n yield this.workspace.selectStack(this.name);\n if (opts) {\n if (opts.message) {\n args.push(\"--message\", opts.message);\n }\n if (opts.expectNoChanges) {\n args.push(\"--expect-no-changes\");\n }\n if (opts.target) {\n for (const tURN of opts.target) {\n args.push(\"--target\", tURN);\n }\n }\n if (opts.parallel) {\n args.push(\"--parallel\", opts.parallel.toString());\n }\n }\n const refResult = yield this.runPulumiCmd(args, (_a = opts) === null || _a === void 0 ? void 0 : _a.onOutput);\n const summary = yield this.info();\n return {\n stdout: refResult.stdout,\n stderr: refResult.stderr,\n summary: summary,\n };\n });\n }\n /**\n * Destroy deletes all resources in a stack, leaving all history and configuration intact.\n *\n * @param opts Options to customize the behavior of the destroy.\n */\n destroy(opts) {\n var _a;\n return __awaiter(this, void 0, void 0, function* () {\n const args = [\"destroy\", \"--yes\", \"--skip-preview\"];\n yield this.workspace.selectStack(this.name);\n if (opts) {\n if (opts.message) {\n args.push(\"--message\", opts.message);\n }\n if (opts.target) {\n for (const tURN of opts.target) {\n args.push(\"--target\", tURN);\n }\n }\n if (opts.targetDependents) {\n args.push(\"--target-dependents\");\n }\n if (opts.parallel) {\n args.push(\"--parallel\", opts.parallel.toString());\n }\n }\n const preResult = yield this.runPulumiCmd(args, (_a = opts) === null || _a === void 0 ? void 0 : _a.onOutput);\n const summary = yield this.info();\n return {\n stdout: preResult.stdout,\n stderr: preResult.stderr,\n summary: summary,\n };\n });\n }\n /**\n * Returns the config value associated with the specified key.\n *\n * @param key The key to use for the config lookup\n */\n getConfig(key) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.workspace.getConfig(this.name, key);\n });\n }\n /**\n * Returns the full config map associated with the stack in the Workspace.\n */\n getAllConfig() {\n return __awaiter(this, void 0, void 0, function* () {\n return this.workspace.getAllConfig(this.name);\n });\n }\n /**\n * Sets a config key-value pair on the Stack in the associated Workspace.\n *\n * @param key The key to set.\n * @param value The config value to set.\n */\n setConfig(key, value) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.workspace.setConfig(this.name, key, value);\n });\n }\n /**\n * Sets all specified config values on the stack in the associated Workspace.\n *\n * @param config The map of config key-value pairs to set.\n */\n setAllConfig(config) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.workspace.setAllConfig(this.name, config);\n });\n }\n /**\n * Removes the specified config key from the Stack in the associated Workspace.\n *\n * @param key The config key to remove.\n */\n removeConfig(key) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.workspace.removeConfig(this.name, key);\n });\n }\n /**\n * Removes the specified config keys from the Stack in the associated Workspace.\n *\n * @param keys The config keys to remove.\n */\n removeAllConfig(keys) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.workspace.removeAllConfig(this.name, keys);\n });\n }\n /**\n * Gets and sets the config map used with the last update.\n */\n refreshConfig() {\n return __awaiter(this, void 0, void 0, function* () {\n return this.workspace.refreshConfig(this.name);\n });\n }\n /**\n * Gets the current set of Stack outputs from the last Stack.up().\n */\n outputs() {\n return __awaiter(this, void 0, void 0, function* () {\n yield this.workspace.selectStack(this.name);\n // TODO: do this in parallel after this is fixed https://github.com/pulumi/pulumi/issues/6050\n const maskedResult = yield this.runPulumiCmd([\"stack\", \"output\", \"--json\"]);\n const plaintextResult = yield this.runPulumiCmd([\"stack\", \"output\", \"--json\", \"--show-secrets\"]);\n const maskedOuts = JSON.parse(maskedResult.stdout);\n const plaintextOuts = JSON.parse(plaintextResult.stdout);\n const outputs = {};\n for (const [key, value] of Object.entries(plaintextOuts)) {\n const secret = maskedOuts[key] === secretSentinel;\n outputs[key] = { value, secret };\n }\n return outputs;\n });\n }\n /**\n * Returns a list summarizing all previous and current results from Stack lifecycle operations\n * (up/preview/refresh/destroy).\n */\n history(pageSize, page) {\n return __awaiter(this, void 0, void 0, function* () {\n const args = [\"history\", \"--json\", \"--show-secrets\"];\n if (pageSize) {\n if (!page || page < 1) {\n page = 1;\n }\n args.push(\"--page-size\", Math.floor(pageSize).toString(), \"--page\", Math.floor(page).toString());\n }\n const result = yield this.runPulumiCmd(args);\n return JSON.parse(result.stdout, (key, value) => {\n if (key === \"startTime\" || key === \"endTime\") {\n return new Date(value);\n }\n return value;\n });\n });\n }\n info() {\n return __awaiter(this, void 0, void 0, function* () {\n const history = yield this.history(1 /*pageSize*/);\n if (!history || history.length === 0) {\n return undefined;\n }\n return history[0];\n });\n }\n /**\n * Cancel stops a stack's currently running update. It returns an error if no update is currently running.\n * Note that this operation is _very dangerous_, and may leave the stack in an inconsistent state\n * if a resource operation was pending when the update was canceled.\n * This command is not supported for local backends.\n */\n cancel() {\n return __awaiter(this, void 0, void 0, function* () {\n yield this.workspace.selectStack(this.name);\n yield this.runPulumiCmd([\"cancel\", \"--yes\"]);\n });\n }\n /**\n * exportStack exports the deployment state of the stack.\n * This can be combined with Stack.importStack to edit a stack's state (such as recovery from failed deployments).\n */\n exportStack() {\n return __awaiter(this, void 0, void 0, function* () {\n return this.workspace.exportStack(this.name);\n });\n }\n /**\n * importStack imports the specified deployment state into a pre-existing stack.\n * This can be combined with Stack.exportStack to edit a stack's state (such as recovery from failed deployments).\n *\n * @param state the stack state to import.\n */\n importStack(state) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.workspace.importStack(this.name, state);\n });\n }\n runPulumiCmd(args, onOutput) {\n return __awaiter(this, void 0, void 0, function* () {\n let envs = {};\n const pulumiHome = this.workspace.pulumiHome;\n if (pulumiHome) {\n envs[\"PULUMI_HOME\"] = pulumiHome;\n }\n envs = Object.assign(Object.assign({}, envs), this.workspace.envVars);\n const additionalArgs = yield this.workspace.serializeArgsForOp(this.name);\n args = [...args, ...additionalArgs];\n const result = yield cmd_1.runPulumiCmd(args, this.workspace.workDir, envs, onOutput);\n yield this.workspace.postCommandCallback(this.name);\n return result;\n });\n }\n}\nexports.Stack = Stack;\n/**\n * Returns a stack name formatted with the greatest possible specificity:\n * org/project/stack or user/project/stack\n * Using this format avoids ambiguity in stack identity guards creating or selecting the wrong stack.\n * Note that filestate backends (local file, S3, Azure Blob) do not support stack names in this\n * format, and instead only use the stack name without an org/user or project to qualify it.\n * See: https://github.com/pulumi/pulumi/issues/2522\n *\n * @param org The org (or user) that contains the Stack.\n * @param project The project that parents the Stack.\n * @param stack The name of the Stack.\n */\nfunction fullyQualifiedStackName(org, project, stack) {\n return `${org}/${project}/${stack}`;\n}\nexports.fullyQualifiedStackName = fullyQualifiedStackName;\nconst execKind = {\n local: \"auto.local\",\n inline: \"auto.inline\",\n};\n","\"use strict\";\n// Copyright 2016-2019, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\nvar __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n 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);\n 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); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n};\nvar __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n 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); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst base_1 = require(\"./base\");\nconst operators_1 = require(\"./operators\");\nconst sources_1 = require(\"./sources\");\nclass AsyncQueryableImpl extends base_1.IterableBase {\n constructor(source) {\n super(source);\n }\n //\n // Constructors.\n //\n static from(source) {\n return new AsyncQueryableImpl(sources_1.from(source));\n }\n //\n // Restriction operators.\n //\n filter(f) {\n return this.pipe(operators_1.filter(f));\n }\n //\n // Projection operators.\n //\n flatMap(selector, resultSelector = (t, ti) => ti) {\n return this.pipe(operators_1.flatMap(selector, resultSelector));\n }\n map(f) {\n return this.pipe(operators_1.map(f));\n }\n //\n // Partitioning operators.\n //\n skip(n) {\n return this.pipe(operators_1.skip(n));\n }\n skipWhile(predicate) {\n return this.pipe(operators_1.skipWhile(predicate));\n }\n take(n) {\n return this.pipe(operators_1.take(n));\n }\n takeWhile(predicate) {\n return this.pipe(operators_1.takeWhile(predicate));\n }\n //\n // Join operators.\n //\n join(inner, outerKeySelector, innerKeySelector, resultSelector) {\n return this.pipe(operators_1.join(sources_1.from(inner), outerKeySelector, innerKeySelector, resultSelector));\n }\n groupJoin(inner, outerKeySelector, innerKeySelector, resultSelector) {\n return this.pipe(operators_1.groupJoin(sources_1.from(inner), outerKeySelector, innerKeySelector, resultSelector));\n }\n //\n // Concatenation operators.\n //\n concat(iter) {\n return this.pipe(operators_1.concat(sources_1.from(iter)));\n }\n //\n // Ordering operators.\n //\n reverse() {\n return this.pipe(operators_1.reverse());\n }\n orderBy(keySelector) {\n return this.pipe(operators_1.orderBy(keySelector));\n }\n orderByDescending(keySelector) {\n return this.pipe(operators_1.orderByDescending(keySelector));\n }\n //\n // Grouping operators.\n //\n groupBy(keySelector, elementSelector) {\n return this.pipe(function (source) {\n return __asyncGenerator(this, arguments, function* () {\n var e_1, _a;\n const groups = yield __await(operators_1.groupBy(keySelector, elementSelector)(source));\n try {\n for (var groups_1 = __asyncValues(groups), groups_1_1; groups_1_1 = yield __await(groups_1.next()), !groups_1_1.done;) {\n const group = groups_1_1.value;\n yield yield __await(new GroupingImpl(group.key, sources_1.from(group)));\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (groups_1_1 && !groups_1_1.done && (_a = groups_1.return)) yield __await(_a.call(groups_1));\n }\n finally { if (e_1) throw e_1.error; }\n }\n });\n });\n }\n //\n // Set operators.\n //\n distinct() {\n return this.pipe(operators_1.distinct());\n }\n union(second) {\n return this.pipe(operators_1.union(sources_1.from(second)));\n }\n intersect(second) {\n return this.pipe(operators_1.intersect(sources_1.from(second)));\n }\n except(second) {\n return this.pipe(operators_1.except(sources_1.from(second)));\n }\n //\n // Element operators.\n //\n first(predicate) {\n return operators_1.first(predicate)(this);\n }\n firstOrDefault(defaultValue, predicate) {\n return operators_1.firstOrDefault(defaultValue, predicate)(this);\n }\n last(predicate) {\n return operators_1.last(predicate)(this);\n }\n lastOrDefault(defaultValue, predicate) {\n return operators_1.lastOrDefault(defaultValue, predicate)(this);\n }\n single(predicate) {\n return operators_1.single(predicate)(this);\n }\n singleOrDefault(defaultValue, predicate) {\n return operators_1.singleOrDefault(defaultValue, predicate)(this);\n }\n elementAt(index) {\n return operators_1.elementAt(index)(this);\n }\n elementAtOrDefault(defaultValue, index) {\n return operators_1.elementAtOrDefault(defaultValue, index)(this);\n }\n defaultIfEmpty(defaultValue) {\n return this.pipe(operators_1.defaultIfEmpty(defaultValue));\n }\n //\n // Quantifiers.\n //\n any(predicate) {\n return operators_1.any(predicate)(this);\n }\n all(predicate) {\n return operators_1.all(predicate)(this);\n }\n contains(value) {\n return operators_1.contains(value)(this);\n }\n //\n // Aggregate operators.\n //\n count(predicate) {\n return operators_1.count(predicate)(this);\n }\n sum(selector) {\n return operators_1.sum(selector)(this);\n }\n min(selector) {\n return operators_1.min(selector)(this);\n }\n max(selector) {\n return operators_1.max(selector)(this);\n }\n average(selector) {\n return operators_1.average(selector)(this);\n }\n aggregate(seed, func) {\n return operators_1.aggregate(seed, func)(this);\n }\n //\n // Eval operators.\n //\n toArray() {\n return __awaiter(this, void 0, void 0, function* () {\n return operators_1.toArray()(this);\n });\n }\n toMap(keySelector, elementSelector) {\n return operators_1.toMap(keySelector, elementSelector)(this);\n }\n ofType(typeGuard) {\n return this.pipe(operators_1.ofType(typeGuard));\n }\n forEach(f) {\n var e_2, _a;\n return __awaiter(this, void 0, void 0, function* () {\n try {\n for (var _b = __asyncValues(this), _c; _c = yield _b.next(), !_c.done;) {\n const t = _c.value;\n f(t);\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) yield _a.call(_b);\n }\n finally { if (e_2) throw e_2.error; }\n }\n });\n }\n pipe(...ops) {\n return new AsyncQueryableImpl((function (source) {\n return __asyncGenerator(this, arguments, function* () {\n var e_3, _a;\n let newSource = source;\n for (const op of ops) {\n newSource = op(newSource);\n }\n try {\n for (var newSource_1 = __asyncValues(newSource), newSource_1_1; newSource_1_1 = yield __await(newSource_1.next()), !newSource_1_1.done;) {\n const t = newSource_1_1.value;\n yield yield __await(t);\n }\n }\n catch (e_3_1) { e_3 = { error: e_3_1 }; }\n finally {\n try {\n if (newSource_1_1 && !newSource_1_1.done && (_a = newSource_1.return)) yield __await(_a.call(newSource_1));\n }\n finally { if (e_3) throw e_3.error; }\n }\n });\n })(this));\n }\n}\nexports.AsyncQueryableImpl = AsyncQueryableImpl;\nclass GroupingImpl extends AsyncQueryableImpl {\n constructor(key, group) {\n super(group);\n this.key = key;\n }\n}\nexports.GroupingImpl = GroupingImpl;\n","\"use strict\";\n// Copyright 2016-2019, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nclass IterableBase {\n constructor(core) {\n this.core = core;\n }\n [Symbol.asyncIterator]() {\n return this;\n }\n next(value) {\n return this.core.next(value);\n }\n}\nexports.IterableBase = IterableBase;\nclass GroupedAsyncIterableIteratorImpl extends IterableBase {\n constructor(key, core) {\n super(core);\n this.key = key;\n }\n}\nexports.GroupedAsyncIterableIteratorImpl = GroupedAsyncIterableIteratorImpl;\n","\"use strict\";\n// Copyright 2016-2019, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nvar __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\nvar __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n 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); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//\n// NOTE: We choose to be purposefully conservative about what details are exposed through these\n// interfaces in case we decide to change the implementation drastically later.\n//\n//\n// Polyfill the async iterator per the \"caveats\" section of the feature release notes:\n// https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-3.html#the-for-await-of-statement\n//\nif (typeof Symbol.asyncIterator === \"undefined\") {\n Symbol.asyncIterator = Symbol.asyncIterator || Symbol.for(\"Symbol.asyncIterator\");\n}\nconst asyncQueryable_1 = require(\"./asyncQueryable\");\nconst sources = require(\"./sources\");\n/**\n * Creates an `AsyncQueryable` from things that look `Iterable` or `AsyncIterable`, even if they're\n * wrapped in a `Promise`.\n * @param source Object to convert into an `AsyncQueryable`.\n */\nfunction from(source) {\n return asyncQueryable_1.AsyncQueryableImpl.from(source);\n}\nexports.from = from;\n/**\n * Generates a (potentially infinite) sequence of integral numbers within a range. The first number\n * emitted is `start`, and the last is `stop - 1`. If the enumerated sequence generates zero\n * elements (for example, when `stop <= start + 1`), an exception is thrown.\n * @param start Beginning of the range\n * @param stop Non-inclusive end of the range.\n * @example\n * const squares = await range(0, 3).map(x => x * x).toArray(); // == [0, 1, 4]\n */\nfunction range(start, stop) {\n return asyncQueryable_1.AsyncQueryableImpl.from(sources.range(start, stop));\n}\nexports.range = range;\n/**\n * Returns an empty sequence of `TResult`.\n * @example\n * const noNumbers = await empty().toArray(); // == []\n */\nfunction empty() {\n return asyncQueryable_1.AsyncQueryableImpl.from(sources.from([]));\n}\nexports.empty = empty;\n/**\n * Generates a (potentially infinite) sequence by repeating a single value.\n * @param t Object to repeat\n * @example\n * const ones = await repeat(1).take(3).toArray(); // == [1, 1, 1]\n */\nfunction repeat(t /* TODO: add optional count. */) {\n asyncQueryable_1.AsyncQueryableImpl.from((function () {\n return __asyncGenerator(this, arguments, function* () {\n while (true) {\n yield yield __await(t);\n }\n });\n })());\n}\nexports.repeat = repeat;\n","\"use strict\";\n// Copyright 2016-2019, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\n///////////////////////////////////////////////////////////////////////////////\nfunction isAsyncIterable(o) {\n return typeof o[Symbol.asyncIterator] === \"function\";\n}\nexports.isAsyncIterable = isAsyncIterable;\nfunction isIterable(o) {\n return typeof o[Symbol.iterator] === \"function\";\n}\nexports.isIterable = isIterable;\n","\"use strict\";\n// Copyright 2016-2019, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n 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);\n 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); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n};\nvar __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\nvar __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n 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); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst util_1 = require(\"util\");\nconst base_1 = require(\"./base\");\nconst sources_1 = require(\"./sources\");\n//\n// Restriction operators.\n//\nfunction filter(f) {\n return function (source) {\n return __asyncGenerator(this, arguments, function* () {\n var e_1, _a;\n try {\n for (var _b = __asyncValues(zip(source, sources_1.range(0))), _c; _c = yield __await(_b.next()), !_c.done;) {\n const [t, i] = _c.value;\n if (yield __await(f(t, i))) {\n yield yield __await(t);\n }\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) yield __await(_a.call(_b));\n }\n finally { if (e_1) throw e_1.error; }\n }\n });\n };\n}\nexports.filter = filter;\n//\n// Projection operators.\n//\nfunction flatMap(selector, resultSelector = (t, ti) => ti) {\n return function (source) {\n return __asyncGenerator(this, arguments, function* () {\n var e_2, _a, e_3, _b;\n try {\n for (var _c = __asyncValues(zip(source, sources_1.range(0))), _d; _d = yield __await(_c.next()), !_d.done;) {\n const [t, i] = _d.value;\n const us = selector(t, i);\n try {\n for (var _e = __asyncValues(sources_1.from(us)), _f; _f = yield __await(_e.next()), !_f.done;) {\n const u = _f.value;\n yield yield __await(yield __await(resultSelector(t, u)));\n }\n }\n catch (e_3_1) { e_3 = { error: e_3_1 }; }\n finally {\n try {\n if (_f && !_f.done && (_b = _e.return)) yield __await(_b.call(_e));\n }\n finally { if (e_3) throw e_3.error; }\n }\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (_d && !_d.done && (_a = _c.return)) yield __await(_a.call(_c));\n }\n finally { if (e_2) throw e_2.error; }\n }\n });\n };\n}\nexports.flatMap = flatMap;\nfunction map(f) {\n return function (source) {\n return __asyncGenerator(this, arguments, function* () {\n var e_4, _a;\n try {\n for (var _b = __asyncValues(zip(source, sources_1.range(0))), _c; _c = yield __await(_b.next()), !_c.done;) {\n const [t, i] = _c.value;\n yield yield __await(yield __await(f(t, i)));\n }\n }\n catch (e_4_1) { e_4 = { error: e_4_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) yield __await(_a.call(_b));\n }\n finally { if (e_4) throw e_4.error; }\n }\n });\n };\n}\nexports.map = map;\n//\n// Partitioning operators.\n//\nfunction skip(n) {\n if (n < 0) {\n throw Error(\"skip was provided a negative number of elements to skip\");\n }\n return function (source) {\n return __asyncGenerator(this, arguments, function* () {\n var e_5, _a;\n try {\n for (var _b = __asyncValues(zip(source, sources_1.range(1))), _c; _c = yield __await(_b.next()), !_c.done;) {\n const [t, i] = _c.value;\n if (i > n) {\n yield yield __await(t);\n }\n }\n }\n catch (e_5_1) { e_5 = { error: e_5_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) yield __await(_a.call(_b));\n }\n finally { if (e_5) throw e_5.error; }\n }\n });\n };\n}\nexports.skip = skip;\nfunction skipWhile(predicate) {\n return function (source) {\n return __asyncGenerator(this, arguments, function* () {\n var e_6, _a;\n let stopSkipping = false;\n try {\n for (var _b = __asyncValues(zip(source, sources_1.range(0))), _c; _c = yield __await(_b.next()), !_c.done;) {\n const [t, i] = _c.value;\n if (stopSkipping === true) {\n yield yield __await(t);\n }\n else if ((yield __await(predicate(t, i))) === false) {\n stopSkipping = true;\n yield yield __await(t);\n }\n }\n }\n catch (e_6_1) { e_6 = { error: e_6_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) yield __await(_a.call(_b));\n }\n finally { if (e_6) throw e_6.error; }\n }\n });\n };\n}\nexports.skipWhile = skipWhile;\nfunction take(n) {\n if (n < 0) {\n throw Error(\"take was provided a negative number of elements to take\");\n }\n return function (source) {\n return __asyncGenerator(this, arguments, function* () {\n var e_7, _a;\n try {\n for (var _b = __asyncValues(zip(source, sources_1.range(0))), _c; _c = yield __await(_b.next()), !_c.done;) {\n const [t, i] = _c.value;\n if (i >= n) {\n return yield __await(void 0);\n }\n yield yield __await(t);\n }\n }\n catch (e_7_1) { e_7 = { error: e_7_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) yield __await(_a.call(_b));\n }\n finally { if (e_7) throw e_7.error; }\n }\n });\n };\n}\nexports.take = take;\nfunction takeWhile(predicate) {\n return function (source) {\n return __asyncGenerator(this, arguments, function* () {\n var e_8, _a;\n try {\n for (var _b = __asyncValues(zip(source, sources_1.range(0))), _c; _c = yield __await(_b.next()), !_c.done;) {\n const [t, i] = _c.value;\n if ((yield __await(predicate(t, i))) === false) {\n return yield __await(void 0);\n }\n yield yield __await(t);\n }\n }\n catch (e_8_1) { e_8 = { error: e_8_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) yield __await(_a.call(_b));\n }\n finally { if (e_8) throw e_8.error; }\n }\n });\n };\n}\nexports.takeWhile = takeWhile;\n//\n// Join operators.\n//\nfunction joinHelper(outer, inner, outerKeySelector, innerKeySelector) {\n return __asyncGenerator(this, arguments, function* joinHelper_1() {\n var e_9, _a, e_10, _b;\n const inners = new Map();\n try {\n for (var inner_1 = __asyncValues(inner), inner_1_1; inner_1_1 = yield __await(inner_1.next()), !inner_1_1.done;) {\n const t = inner_1_1.value;\n const key = yield __await(innerKeySelector(t));\n const val = inners.get(key);\n if (inners.has(key)) {\n val.push(t);\n }\n else {\n inners.set(key, [t]);\n }\n }\n }\n catch (e_9_1) { e_9 = { error: e_9_1 }; }\n finally {\n try {\n if (inner_1_1 && !inner_1_1.done && (_a = inner_1.return)) yield __await(_a.call(inner_1));\n }\n finally { if (e_9) throw e_9.error; }\n }\n try {\n for (var outer_1 = __asyncValues(outer), outer_1_1; outer_1_1 = yield __await(outer_1.next()), !outer_1_1.done;) {\n const t = outer_1_1.value;\n const key = yield __await(outerKeySelector(t));\n if (key === undefined) {\n continue;\n }\n else if (inners.has(key)) {\n const innerValues = inners.get(key);\n yield yield __await([t, innerValues]);\n }\n }\n }\n catch (e_10_1) { e_10 = { error: e_10_1 }; }\n finally {\n try {\n if (outer_1_1 && !outer_1_1.done && (_b = outer_1.return)) yield __await(_b.call(outer_1));\n }\n finally { if (e_10) throw e_10.error; }\n }\n });\n}\nfunction join(inner, outerKeySelector, innerKeySelector, resultSelector) {\n return function (outer) {\n return __asyncGenerator(this, arguments, function* () {\n var e_11, _a;\n try {\n for (var _b = __asyncValues(joinHelper(outer, inner, outerKeySelector, innerKeySelector)), _c; _c = yield __await(_b.next()), !_c.done;) {\n const [o, inners] = _c.value;\n for (const i of inners) {\n yield yield __await(yield __await(resultSelector(o, i)));\n }\n }\n }\n catch (e_11_1) { e_11 = { error: e_11_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) yield __await(_a.call(_b));\n }\n finally { if (e_11) throw e_11.error; }\n }\n });\n };\n}\nexports.join = join;\nfunction groupJoin(inner, outerKeySelector, innerKeySelector, resultSelector) {\n return function (outer) {\n return __asyncGenerator(this, arguments, function* () {\n var e_12, _a;\n try {\n for (var _b = __asyncValues(joinHelper(outer, inner, outerKeySelector, innerKeySelector)), _c; _c = yield __await(_b.next()), !_c.done;) {\n const [o, inners] = _c.value;\n yield yield __await(yield __await(resultSelector(o, sources_1.from(inners))));\n }\n }\n catch (e_12_1) { e_12 = { error: e_12_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) yield __await(_a.call(_b));\n }\n finally { if (e_12) throw e_12.error; }\n }\n });\n };\n}\nexports.groupJoin = groupJoin;\n//\n// Concatenation operators.\n//\nfunction concat(iter) {\n return function (source) {\n return __asyncGenerator(this, arguments, function* () {\n var e_13, _a, e_14, _b;\n try {\n for (var source_1 = __asyncValues(source), source_1_1; source_1_1 = yield __await(source_1.next()), !source_1_1.done;) {\n const t = source_1_1.value;\n yield yield __await(t);\n }\n }\n catch (e_13_1) { e_13 = { error: e_13_1 }; }\n finally {\n try {\n if (source_1_1 && !source_1_1.done && (_a = source_1.return)) yield __await(_a.call(source_1));\n }\n finally { if (e_13) throw e_13.error; }\n }\n try {\n for (var iter_1 = __asyncValues(iter), iter_1_1; iter_1_1 = yield __await(iter_1.next()), !iter_1_1.done;) {\n const t = iter_1_1.value;\n yield yield __await(t);\n }\n }\n catch (e_14_1) { e_14 = { error: e_14_1 }; }\n finally {\n try {\n if (iter_1_1 && !iter_1_1.done && (_b = iter_1.return)) yield __await(_b.call(iter_1));\n }\n finally { if (e_14) throw e_14.error; }\n }\n });\n };\n}\nexports.concat = concat;\n//\n// Ordering operators.\n//\nfunction orderBy(keySelector) {\n return function (source) {\n return __asyncGenerator(this, arguments, function* () {\n //\n // NOTE: This horrible little function is necessary because the default behavior of\n // JavaScript's `Array#sort` is to coerce every element in the array into string, and then\n // sort those strings lexically.\n //\n // This, of course, is completely unacceptable. Approximately 0 users call `.sort` on an\n // array of `Object` with the intention that they be sorted in this manner. The right thing\n // to do is to simply assume this is a user error and throw an exception.\n //\n // If the user actually wants to sort an array of `Object` by their stringified\n // representation, let them pass us a key function that performs this conversion explicitly.\n // There is no particular need for Brendan Eich's problems from 30 years ago to become our\n // users' problems today.\n //\n let lastKey;\n const ts = yield __await(map(function (t) {\n return __awaiter(this, void 0, void 0, function* () {\n const key = yield keySelector(t);\n if (lastKey === undefined) {\n lastKey = key;\n }\n else {\n if (util_1.isNumber(key) && util_1.isString(key)) {\n throw Error(\"keySelector must produce a number or a string\");\n }\n if (typeof lastKey !== typeof key) {\n throw Error(`keySelector must produce keys all of the same type, but found ` +\n `${typeof key} and ${typeof lastKey}`);\n }\n }\n return [key, t];\n });\n })(source));\n const keyed = yield __await(toArray()(ts));\n const comparator = ((util_1.isNumber(lastKey)\n ? (a, b) => a - b\n : (a, b) => a.localeCompare(b)));\n const sorted = keyed.sort(([k1], [k2]) => comparator(k1, k2));\n for (const [, t] of sorted) {\n yield yield __await(t);\n }\n });\n };\n}\nexports.orderBy = orderBy;\nfunction orderByDescending(keySelector) {\n return function (source) {\n return reverse()(orderBy(keySelector)(source));\n };\n}\nexports.orderByDescending = orderByDescending;\nfunction reverse() {\n return function (source) {\n return __asyncGenerator(this, arguments, function* () {\n var e_15, _a;\n const ts = [];\n try {\n for (var source_2 = __asyncValues(source), source_2_1; source_2_1 = yield __await(source_2.next()), !source_2_1.done;) {\n const t = source_2_1.value;\n ts.push(t);\n }\n }\n catch (e_15_1) { e_15 = { error: e_15_1 }; }\n finally {\n try {\n if (source_2_1 && !source_2_1.done && (_a = source_2.return)) yield __await(_a.call(source_2));\n }\n finally { if (e_15) throw e_15.error; }\n }\n for (const t of ts.reverse()) {\n yield yield __await(t);\n }\n });\n };\n}\nexports.reverse = reverse;\n//\n// Grouping operators.\n//\nfunction groupBy(keySelector, elementSelector) {\n return function (source) {\n return __asyncGenerator(this, arguments, function* () {\n var e_16, _a;\n if (elementSelector === undefined) {\n elementSelector = t => t;\n }\n const groups = new Map();\n try {\n for (var source_3 = __asyncValues(source), source_3_1; source_3_1 = yield __await(source_3.next()), !source_3_1.done;) {\n const t = source_3_1.value;\n const key = yield __await(keySelector(t));\n const val = yield __await(elementSelector(t));\n if (!groups.has(key)) {\n groups.set(key, [val]);\n }\n else {\n const group = groups.get(key);\n group.push(val);\n }\n }\n }\n catch (e_16_1) { e_16 = { error: e_16_1 }; }\n finally {\n try {\n if (source_3_1 && !source_3_1.done && (_a = source_3.return)) yield __await(_a.call(source_3));\n }\n finally { if (e_16) throw e_16.error; }\n }\n for (const [key, group] of groups) {\n yield yield __await(new base_1.GroupedAsyncIterableIteratorImpl(key, sources_1.from(group)));\n }\n });\n };\n}\nexports.groupBy = groupBy;\n//\n// Set operators.\n//\nfunction distinct() {\n return function (source) {\n return __asyncGenerator(this, arguments, function* () {\n var e_17, _a;\n const dist = new Set();\n try {\n for (var source_4 = __asyncValues(source), source_4_1; source_4_1 = yield __await(source_4.next()), !source_4_1.done;) {\n const t = source_4_1.value;\n if (!dist.has(t)) {\n dist.add(t);\n yield yield __await(t);\n }\n }\n }\n catch (e_17_1) { e_17 = { error: e_17_1 }; }\n finally {\n try {\n if (source_4_1 && !source_4_1.done && (_a = source_4.return)) yield __await(_a.call(source_4));\n }\n finally { if (e_17) throw e_17.error; }\n }\n });\n };\n}\nexports.distinct = distinct;\nfunction union(second) {\n return function (source) {\n return __asyncGenerator(this, arguments, function* () {\n var e_18, _a, e_19, _b;\n const dist = new Set();\n try {\n for (var source_5 = __asyncValues(source), source_5_1; source_5_1 = yield __await(source_5.next()), !source_5_1.done;) {\n const t = source_5_1.value;\n if (!dist.has(t)) {\n dist.add(t);\n yield yield __await(t);\n }\n }\n }\n catch (e_18_1) { e_18 = { error: e_18_1 }; }\n finally {\n try {\n if (source_5_1 && !source_5_1.done && (_a = source_5.return)) yield __await(_a.call(source_5));\n }\n finally { if (e_18) throw e_18.error; }\n }\n try {\n for (var second_1 = __asyncValues(second), second_1_1; second_1_1 = yield __await(second_1.next()), !second_1_1.done;) {\n const t = second_1_1.value;\n if (!dist.has(t)) {\n dist.add(t);\n yield yield __await(t);\n }\n }\n }\n catch (e_19_1) { e_19 = { error: e_19_1 }; }\n finally {\n try {\n if (second_1_1 && !second_1_1.done && (_b = second_1.return)) yield __await(_b.call(second_1));\n }\n finally { if (e_19) throw e_19.error; }\n }\n });\n };\n}\nexports.union = union;\nfunction intersect(second) {\n return function (source) {\n return __asyncGenerator(this, arguments, function* () {\n var e_20, _a, e_21, _b;\n const dist = new Set();\n try {\n for (var source_6 = __asyncValues(source), source_6_1; source_6_1 = yield __await(source_6.next()), !source_6_1.done;) {\n const t = source_6_1.value;\n dist.add(t);\n }\n }\n catch (e_20_1) { e_20 = { error: e_20_1 }; }\n finally {\n try {\n if (source_6_1 && !source_6_1.done && (_a = source_6.return)) yield __await(_a.call(source_6));\n }\n finally { if (e_20) throw e_20.error; }\n }\n const emitted = new Set();\n try {\n for (var second_2 = __asyncValues(second), second_2_1; second_2_1 = yield __await(second_2.next()), !second_2_1.done;) {\n const t = second_2_1.value;\n if (dist.has(t) && !emitted.has(t)) {\n emitted.add(t);\n yield yield __await(t);\n }\n }\n }\n catch (e_21_1) { e_21 = { error: e_21_1 }; }\n finally {\n try {\n if (second_2_1 && !second_2_1.done && (_b = second_2.return)) yield __await(_b.call(second_2));\n }\n finally { if (e_21) throw e_21.error; }\n }\n });\n };\n}\nexports.intersect = intersect;\nfunction except(second) {\n return function (source) {\n return __asyncGenerator(this, arguments, function* () {\n var e_22, _a, e_23, _b;\n const dist = new Set();\n try {\n for (var source_7 = __asyncValues(source), source_7_1; source_7_1 = yield __await(source_7.next()), !source_7_1.done;) {\n const t = source_7_1.value;\n dist.add(t);\n }\n }\n catch (e_22_1) { e_22 = { error: e_22_1 }; }\n finally {\n try {\n if (source_7_1 && !source_7_1.done && (_a = source_7.return)) yield __await(_a.call(source_7));\n }\n finally { if (e_22) throw e_22.error; }\n }\n try {\n for (var second_3 = __asyncValues(second), second_3_1; second_3_1 = yield __await(second_3.next()), !second_3_1.done;) {\n const t = second_3_1.value;\n if (dist.has(t)) {\n dist.delete(t);\n }\n else {\n dist.add(t);\n }\n }\n }\n catch (e_23_1) { e_23 = { error: e_23_1 }; }\n finally {\n try {\n if (second_3_1 && !second_3_1.done && (_b = second_3.return)) yield __await(_b.call(second_3));\n }\n finally { if (e_23) throw e_23.error; }\n }\n for (const t of dist) {\n yield yield __await(t);\n }\n });\n };\n}\nexports.except = except;\n//\n// Conversion operators.\n//\nfunction toArray() {\n return function (source) {\n var source_8, source_8_1;\n var e_24, _a;\n return __awaiter(this, void 0, void 0, function* () {\n const ret = [];\n try {\n for (source_8 = __asyncValues(source); source_8_1 = yield source_8.next(), !source_8_1.done;) {\n const t = source_8_1.value;\n ret.push(t);\n }\n }\n catch (e_24_1) { e_24 = { error: e_24_1 }; }\n finally {\n try {\n if (source_8_1 && !source_8_1.done && (_a = source_8.return)) yield _a.call(source_8);\n }\n finally { if (e_24) throw e_24.error; }\n }\n return ret;\n });\n };\n}\nexports.toArray = toArray;\nfunction toMap(keySelector, elementSelector) {\n return function (source) {\n var source_9, source_9_1;\n var e_25, _a;\n return __awaiter(this, void 0, void 0, function* () {\n if (elementSelector === undefined) {\n elementSelector = x => x;\n }\n const ret = new Map();\n try {\n for (source_9 = __asyncValues(source); source_9_1 = yield source_9.next(), !source_9_1.done;) {\n const t = source_9_1.value;\n const key = yield keySelector(t);\n if (key === undefined) {\n throw Error(\"key selector can't produce a null value\");\n }\n const val = yield elementSelector(t);\n ret.set(key, val);\n }\n }\n catch (e_25_1) { e_25 = { error: e_25_1 }; }\n finally {\n try {\n if (source_9_1 && !source_9_1.done && (_a = source_9.return)) yield _a.call(source_9);\n }\n finally { if (e_25) throw e_25.error; }\n }\n return ret;\n });\n };\n}\nexports.toMap = toMap;\nfunction ofType(typeGuard) {\n return function (source) {\n return __asyncGenerator(this, arguments, function* () {\n var e_26, _a;\n try {\n for (var source_10 = __asyncValues(source), source_10_1; source_10_1 = yield __await(source_10.next()), !source_10_1.done;) {\n const t = source_10_1.value;\n if (typeGuard(t)) {\n yield yield __await(t);\n }\n }\n }\n catch (e_26_1) { e_26 = { error: e_26_1 }; }\n finally {\n try {\n if (source_10_1 && !source_10_1.done && (_a = source_10.return)) yield __await(_a.call(source_10));\n }\n finally { if (e_26) throw e_26.error; }\n }\n });\n };\n}\nexports.ofType = ofType;\n//\n// Element operators.\n//\nfunction first(predicate) {\n return function (source) {\n var source_11, source_11_1;\n var e_27, _a;\n return __awaiter(this, void 0, void 0, function* () {\n if (predicate === undefined) {\n predicate = t => true;\n }\n try {\n for (source_11 = __asyncValues(source); source_11_1 = yield source_11.next(), !source_11_1.done;) {\n const t = source_11_1.value;\n if ((yield predicate(t)) === true) {\n return t;\n }\n }\n }\n catch (e_27_1) { e_27 = { error: e_27_1 }; }\n finally {\n try {\n if (source_11_1 && !source_11_1.done && (_a = source_11.return)) yield _a.call(source_11);\n }\n finally { if (e_27) throw e_27.error; }\n }\n return Promise.reject(\"first could not find any elements that match predicate\");\n });\n };\n}\nexports.first = first;\nfunction firstOrDefault(defaultValue, predicate) {\n return function (source) {\n var source_12, source_12_1;\n var e_28, _a;\n return __awaiter(this, void 0, void 0, function* () {\n if (predicate === undefined) {\n predicate = t => true;\n }\n try {\n for (source_12 = __asyncValues(source); source_12_1 = yield source_12.next(), !source_12_1.done;) {\n const t = source_12_1.value;\n if ((yield predicate(t)) === true) {\n return t;\n }\n }\n }\n catch (e_28_1) { e_28 = { error: e_28_1 }; }\n finally {\n try {\n if (source_12_1 && !source_12_1.done && (_a = source_12.return)) yield _a.call(source_12);\n }\n finally { if (e_28) throw e_28.error; }\n }\n return defaultValue;\n });\n };\n}\nexports.firstOrDefault = firstOrDefault;\nfunction last(predicate) {\n return function (source) {\n var source_13, source_13_1;\n var e_29, _a;\n return __awaiter(this, void 0, void 0, function* () {\n if (predicate === undefined) {\n predicate = t => true;\n }\n let curr;\n try {\n for (source_13 = __asyncValues(source); source_13_1 = yield source_13.next(), !source_13_1.done;) {\n const t = source_13_1.value;\n if ((yield predicate(t)) === true) {\n curr = t;\n }\n }\n }\n catch (e_29_1) { e_29 = { error: e_29_1 }; }\n finally {\n try {\n if (source_13_1 && !source_13_1.done && (_a = source_13.return)) yield _a.call(source_13);\n }\n finally { if (e_29) throw e_29.error; }\n }\n if (curr === undefined) {\n return Promise.reject(\"last could not find any elements that match predicate\");\n }\n else {\n return curr;\n }\n });\n };\n}\nexports.last = last;\nfunction lastOrDefault(defaultValue, predicate) {\n return function (source) {\n var source_14, source_14_1;\n var e_30, _a;\n return __awaiter(this, void 0, void 0, function* () {\n if (predicate === undefined) {\n predicate = t => true;\n }\n let curr;\n try {\n for (source_14 = __asyncValues(source); source_14_1 = yield source_14.next(), !source_14_1.done;) {\n const t = source_14_1.value;\n if ((yield predicate(t)) === true) {\n curr = t;\n }\n }\n }\n catch (e_30_1) { e_30 = { error: e_30_1 }; }\n finally {\n try {\n if (source_14_1 && !source_14_1.done && (_a = source_14.return)) yield _a.call(source_14);\n }\n finally { if (e_30) throw e_30.error; }\n }\n if (curr === undefined) {\n return defaultValue;\n }\n else {\n return curr;\n }\n });\n };\n}\nexports.lastOrDefault = lastOrDefault;\nfunction single(predicate) {\n return function (source) {\n return __awaiter(this, void 0, void 0, function* () {\n if (predicate === undefined) {\n predicate = t => true;\n }\n const seq = yield toArray()(filter(predicate)(source));\n if (seq.length === 0) {\n throw Error(\"single did not find any elements matching the predicate\");\n }\n else if (seq.length > 1) {\n throw Error(\"single found multiple elements matching the predicate\");\n }\n return seq[0];\n });\n };\n}\nexports.single = single;\nfunction singleOrDefault(defaultValue, predicate) {\n return function (source) {\n return __awaiter(this, void 0, void 0, function* () {\n if (predicate === undefined) {\n predicate = t => true;\n }\n const seq = yield toArray()(filter(predicate)(source));\n if (seq.length === 0) {\n return defaultValue;\n }\n else if (seq.length > 1) {\n throw Error(\"single found multiple elements matching the predicate\");\n }\n else {\n return seq[0];\n }\n });\n };\n}\nexports.singleOrDefault = singleOrDefault;\nfunction elementAt(index) {\n return function (source) {\n var e_31, _a;\n return __awaiter(this, void 0, void 0, function* () {\n try {\n // TODO: Maybe support `Array` here if we ever support sync iterables. This would allow us\n // to access that index directly.\n for (var _b = __asyncValues(zip(source, sources_1.range(0))), _c; _c = yield _b.next(), !_c.done;) {\n const [t, i] = _c.value;\n if (i === index) {\n return t;\n }\n }\n }\n catch (e_31_1) { e_31 = { error: e_31_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) yield _a.call(_b);\n }\n finally { if (e_31) throw e_31.error; }\n }\n throw Error(`elementAt tried to find item at index ${index}, but sequence had fewer elements`);\n });\n };\n}\nexports.elementAt = elementAt;\nfunction elementAtOrDefault(defaultValue, index) {\n return function (source) {\n var e_32, _a;\n return __awaiter(this, void 0, void 0, function* () {\n try {\n // TODO: Maybe support `Array` here if we ever support sync iterables. This would allow us\n // to access that index directly.\n for (var _b = __asyncValues(zip(source, sources_1.range(0))), _c; _c = yield _b.next(), !_c.done;) {\n const [t, i] = _c.value;\n if (i === index) {\n return t;\n }\n }\n }\n catch (e_32_1) { e_32 = { error: e_32_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) yield _a.call(_b);\n }\n finally { if (e_32) throw e_32.error; }\n }\n return defaultValue;\n });\n };\n}\nexports.elementAtOrDefault = elementAtOrDefault;\nfunction defaultIfEmpty(defaultValue) {\n return function (source) {\n return __asyncGenerator(this, arguments, function* () {\n var e_33, _a;\n let sequenceEmpty = true;\n try {\n for (var source_15 = __asyncValues(source), source_15_1; source_15_1 = yield __await(source_15.next()), !source_15_1.done;) {\n const t = source_15_1.value;\n sequenceEmpty = false;\n yield yield __await(t);\n }\n }\n catch (e_33_1) { e_33 = { error: e_33_1 }; }\n finally {\n try {\n if (source_15_1 && !source_15_1.done && (_a = source_15.return)) yield __await(_a.call(source_15));\n }\n finally { if (e_33) throw e_33.error; }\n }\n if (sequenceEmpty) {\n yield yield __await(defaultValue);\n }\n });\n };\n}\nexports.defaultIfEmpty = defaultIfEmpty;\n//\n// Quantifiers.\n//\nfunction any(predicate) {\n return function (source) {\n var source_16, source_16_1;\n var e_34, _a;\n return __awaiter(this, void 0, void 0, function* () {\n if (predicate === undefined) {\n predicate = t => true;\n }\n try {\n for (source_16 = __asyncValues(source); source_16_1 = yield source_16.next(), !source_16_1.done;) {\n const t = source_16_1.value;\n if ((yield predicate(t)) === true) {\n return true;\n }\n }\n }\n catch (e_34_1) { e_34 = { error: e_34_1 }; }\n finally {\n try {\n if (source_16_1 && !source_16_1.done && (_a = source_16.return)) yield _a.call(source_16);\n }\n finally { if (e_34) throw e_34.error; }\n }\n return false;\n });\n };\n}\nexports.any = any;\nfunction all(predicate) {\n return function (source) {\n var source_17, source_17_1;\n var e_35, _a;\n return __awaiter(this, void 0, void 0, function* () {\n try {\n for (source_17 = __asyncValues(source); source_17_1 = yield source_17.next(), !source_17_1.done;) {\n const t = source_17_1.value;\n if ((yield predicate(t)) === false) {\n return false;\n }\n }\n }\n catch (e_35_1) { e_35 = { error: e_35_1 }; }\n finally {\n try {\n if (source_17_1 && !source_17_1.done && (_a = source_17.return)) yield _a.call(source_17);\n }\n finally { if (e_35) throw e_35.error; }\n }\n return true;\n });\n };\n}\nexports.all = all;\nfunction contains(value) {\n return function (source) {\n var source_18, source_18_1;\n var e_36, _a;\n return __awaiter(this, void 0, void 0, function* () {\n const dist = new Set([value]);\n try {\n for (source_18 = __asyncValues(source); source_18_1 = yield source_18.next(), !source_18_1.done;) {\n const t = source_18_1.value;\n if (dist.has(t)) {\n return true;\n }\n }\n }\n catch (e_36_1) { e_36 = { error: e_36_1 }; }\n finally {\n try {\n if (source_18_1 && !source_18_1.done && (_a = source_18.return)) yield _a.call(source_18);\n }\n finally { if (e_36) throw e_36.error; }\n }\n return false;\n });\n };\n}\nexports.contains = contains;\n//\n// Aggregate operators.\n//\nfunction count(predicate) {\n return function (source) {\n var source_19, source_19_1;\n var e_37, _a;\n return __awaiter(this, void 0, void 0, function* () {\n if (predicate === undefined) {\n predicate = t => true;\n }\n let n = 0;\n try {\n for (source_19 = __asyncValues(source); source_19_1 = yield source_19.next(), !source_19_1.done;) {\n const t = source_19_1.value;\n if ((yield predicate(t)) === true) {\n n++;\n }\n }\n }\n catch (e_37_1) { e_37 = { error: e_37_1 }; }\n finally {\n try {\n if (source_19_1 && !source_19_1.done && (_a = source_19.return)) yield _a.call(source_19);\n }\n finally { if (e_37) throw e_37.error; }\n }\n return n;\n });\n };\n}\nexports.count = count;\nfunction sum(selector) {\n return function (source) {\n var source_20, source_20_1;\n var e_38, _a;\n return __awaiter(this, void 0, void 0, function* () {\n // If selector is undefined, the source should emit `number`.\n if (selector === undefined) {\n selector = t => t;\n }\n let total = 0;\n try {\n for (source_20 = __asyncValues(source); source_20_1 = yield source_20.next(), !source_20_1.done;) {\n const t = source_20_1.value;\n const toSum = yield selector(t);\n if (!util_1.isNumber(toSum)) {\n throw Error(\"Can't sum things that aren't numbers\");\n }\n total += toSum;\n }\n }\n catch (e_38_1) { e_38 = { error: e_38_1 }; }\n finally {\n try {\n if (source_20_1 && !source_20_1.done && (_a = source_20.return)) yield _a.call(source_20);\n }\n finally { if (e_38) throw e_38.error; }\n }\n return total;\n });\n };\n}\nexports.sum = sum;\nfunction min(selector) {\n return function (source) {\n var source_21, source_21_1;\n var e_39, _a;\n return __awaiter(this, void 0, void 0, function* () {\n // If selector is undefined, the source should emit `number`.\n if (selector === undefined) {\n selector = t => t;\n }\n let minimum = undefined;\n try {\n for (source_21 = __asyncValues(source); source_21_1 = yield source_21.next(), !source_21_1.done;) {\n const t = source_21_1.value;\n const curr = yield selector(t);\n if (minimum === undefined) {\n minimum = curr;\n }\n if (!util_1.isNumber(curr)) {\n throw Error(\"min can't find the minimum of things that aren't numbers\");\n }\n if (minimum > curr) {\n minimum = curr;\n }\n }\n }\n catch (e_39_1) { e_39 = { error: e_39_1 }; }\n finally {\n try {\n if (source_21_1 && !source_21_1.done && (_a = source_21.return)) yield _a.call(source_21);\n }\n finally { if (e_39) throw e_39.error; }\n }\n if (minimum === undefined) {\n throw Error(\"min can't be called on an empty sequence\");\n }\n return minimum;\n });\n };\n}\nexports.min = min;\nfunction max(selector) {\n return function (source) {\n var source_22, source_22_1;\n var e_40, _a;\n return __awaiter(this, void 0, void 0, function* () {\n // If selector is undefined, the source should emit `number`.\n if (selector === undefined) {\n selector = t => t;\n }\n let maximum = undefined;\n try {\n for (source_22 = __asyncValues(source); source_22_1 = yield source_22.next(), !source_22_1.done;) {\n const t = source_22_1.value;\n const curr = yield selector(t);\n if (maximum === undefined) {\n maximum = curr;\n }\n if (!util_1.isNumber(curr)) {\n throw Error(\"max can't find the maximum of things that aren't numbers\");\n }\n if (maximum < curr) {\n maximum = curr;\n }\n }\n }\n catch (e_40_1) { e_40 = { error: e_40_1 }; }\n finally {\n try {\n if (source_22_1 && !source_22_1.done && (_a = source_22.return)) yield _a.call(source_22);\n }\n finally { if (e_40) throw e_40.error; }\n }\n if (maximum === undefined) {\n throw Error(\"max can't be called on an empty sequence\");\n }\n return maximum;\n });\n };\n}\nexports.max = max;\nfunction average(selector) {\n return function (source) {\n var source_23, source_23_1;\n var e_41, _a;\n return __awaiter(this, void 0, void 0, function* () {\n // If selector is undefined, the source should emit `number`.\n if (selector === undefined) {\n selector = t => t;\n }\n let total = 0;\n let cnt = 0;\n try {\n for (source_23 = __asyncValues(source); source_23_1 = yield source_23.next(), !source_23_1.done;) {\n const t = source_23_1.value;\n const toSum = yield selector(t);\n if (!util_1.isNumber(toSum)) {\n throw Error(\"Can't sum things that aren't numbers\");\n }\n total += toSum;\n cnt++;\n }\n }\n catch (e_41_1) { e_41 = { error: e_41_1 }; }\n finally {\n try {\n if (source_23_1 && !source_23_1.done && (_a = source_23.return)) yield _a.call(source_23);\n }\n finally { if (e_41) throw e_41.error; }\n }\n if (cnt === 0) {\n return Promise.reject(\"Can't compute average of empty sequence\");\n }\n return total / cnt;\n });\n };\n}\nexports.average = average;\nfunction aggregate(seed, func) {\n return function (source) {\n var source_24, source_24_1;\n var e_42, _a;\n return __awaiter(this, void 0, void 0, function* () {\n let acc = seed;\n try {\n for (source_24 = __asyncValues(source); source_24_1 = yield source_24.next(), !source_24_1.done;) {\n const t = source_24_1.value;\n acc = yield func(acc, t);\n }\n }\n catch (e_42_1) { e_42 = { error: e_42_1 }; }\n finally {\n try {\n if (source_24_1 && !source_24_1.done && (_a = source_24.return)) yield _a.call(source_24);\n }\n finally { if (e_42) throw e_42.error; }\n }\n return acc;\n });\n };\n}\nexports.aggregate = aggregate;\n//\n// Misc.\n//\nfunction zip(source1, source2, resultSelector = (t1, t2) => [t1, t2]) {\n return __asyncGenerator(this, arguments, function* zip_1() {\n while (true) {\n const result1 = yield __await(source1.next());\n const result2 = yield __await(source2.next());\n if (result1.done || result2.done) {\n return yield __await(void 0);\n }\n else {\n yield yield __await(yield __await(resultSelector(result1.value, result2.value)));\n }\n }\n });\n}\nexports.zip = zip;\n","\"use strict\";\n// Copyright 2016-2019, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nvar __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\nvar __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n 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); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n};\nvar __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n 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);\n 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); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst interfaces_1 = require(\"./interfaces\");\nconst util_1 = require(\"./util\");\nfunction range(start, end) {\n return __asyncGenerator(this, arguments, function* range_1() {\n let i = start;\n while (true) {\n if (end !== undefined && i >= end) {\n return yield __await(void 0);\n }\n yield yield __await(i++);\n }\n });\n}\nexports.range = range;\nfunction from(source) {\n return __asyncGenerator(this, arguments, function* from_1() {\n var e_1, _a;\n let iter;\n if (util_1.isIterable(source) || interfaces_1.isAsyncIterable(source)) {\n iter = source;\n }\n else {\n iter = yield __await(source);\n }\n if (util_1.isIterable(iter)) {\n for (const t of iter) {\n yield yield __await(t);\n }\n }\n else {\n try {\n for (var iter_1 = __asyncValues(iter), iter_1_1; iter_1_1 = yield __await(iter_1.next()), !iter_1_1.done;) {\n const t = iter_1_1.value;\n yield yield __await(t);\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (iter_1_1 && !iter_1_1.done && (_a = iter_1.return)) yield __await(_a.call(iter_1));\n }\n finally { if (e_1) throw e_1.error; }\n }\n }\n });\n}\nexports.from = from;\n","\"use strict\";\n// Copyright 2016-2019, Pulumi Corporation.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nfunction isAsyncIterable(o) {\n return typeof o[Symbol.asyncIterator] === \"function\";\n}\nexports.isAsyncIterable = isAsyncIterable;\nfunction isIterable(o) {\n return typeof o[Symbol.iterator] === \"function\";\n}\nexports.isIterable = isIterable;\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nconst events_1 = require(\"events\");\nconst debug_1 = __importDefault(require(\"debug\"));\nconst promisify_1 = __importDefault(require(\"./promisify\"));\nconst debug = debug_1.default('agent-base');\nfunction isAgent(v) {\n return Boolean(v) && typeof v.addRequest === 'function';\n}\nfunction isSecureEndpoint() {\n const { stack } = new Error();\n if (typeof stack !== 'string')\n return false;\n return stack.split('\\n').some(l => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1);\n}\nfunction createAgent(callback, opts) {\n return new createAgent.Agent(callback, opts);\n}\n(function (createAgent) {\n /**\n * Base `http.Agent` implementation.\n * No pooling/keep-alive is implemented by default.\n *\n * @param {Function} callback\n * @api public\n */\n class Agent extends events_1.EventEmitter {\n constructor(callback, _opts) {\n super();\n let opts = _opts;\n if (typeof callback === 'function') {\n this.callback = callback;\n }\n else if (callback) {\n opts = callback;\n }\n // Timeout for the socket to be returned from the callback\n this.timeout = null;\n if (opts && typeof opts.timeout === 'number') {\n this.timeout = opts.timeout;\n }\n // These aren't actually used by `agent-base`, but are required\n // for the TypeScript definition files in `@types/node` :/\n this.maxFreeSockets = 1;\n this.maxSockets = 1;\n this.maxTotalSockets = Infinity;\n this.sockets = {};\n this.freeSockets = {};\n this.requests = {};\n this.options = {};\n }\n get defaultPort() {\n if (typeof this.explicitDefaultPort === 'number') {\n return this.explicitDefaultPort;\n }\n return isSecureEndpoint() ? 443 : 80;\n }\n set defaultPort(v) {\n this.explicitDefaultPort = v;\n }\n get protocol() {\n if (typeof this.explicitProtocol === 'string') {\n return this.explicitProtocol;\n }\n return isSecureEndpoint() ? 'https:' : 'http:';\n }\n set protocol(v) {\n this.explicitProtocol = v;\n }\n callback(req, opts, fn) {\n throw new Error('\"agent-base\" has no default implementation, you must subclass and override `callback()`');\n }\n /**\n * Called by node-core's \"_http_client.js\" module when creating\n * a new HTTP request with this Agent instance.\n *\n * @api public\n */\n addRequest(req, _opts) {\n const opts = Object.assign({}, _opts);\n if (typeof opts.secureEndpoint !== 'boolean') {\n opts.secureEndpoint = isSecureEndpoint();\n }\n if (opts.host == null) {\n opts.host = 'localhost';\n }\n if (opts.port == null) {\n opts.port = opts.secureEndpoint ? 443 : 80;\n }\n if (opts.protocol == null) {\n opts.protocol = opts.secureEndpoint ? 'https:' : 'http:';\n }\n if (opts.host && opts.path) {\n // If both a `host` and `path` are specified then it's most\n // likely the result of a `url.parse()` call... we need to\n // remove the `path` portion so that `net.connect()` doesn't\n // attempt to open that as a unix socket file.\n delete opts.path;\n }\n delete opts.agent;\n delete opts.hostname;\n delete opts._defaultAgent;\n delete opts.defaultPort;\n delete opts.createConnection;\n // Hint to use \"Connection: close\"\n // XXX: non-documented `http` module API :(\n req._last = true;\n req.shouldKeepAlive = false;\n let timedOut = false;\n let timeoutId = null;\n const timeoutMs = opts.timeout || this.timeout;\n const onerror = (err) => {\n if (req._hadError)\n return;\n req.emit('error', err);\n // For Safety. Some additional errors might fire later on\n // and we need to make sure we don't double-fire the error event.\n req._hadError = true;\n };\n const ontimeout = () => {\n timeoutId = null;\n timedOut = true;\n const err = new Error(`A \"socket\" was not created for HTTP request before ${timeoutMs}ms`);\n err.code = 'ETIMEOUT';\n onerror(err);\n };\n const callbackError = (err) => {\n if (timedOut)\n return;\n if (timeoutId !== null) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n onerror(err);\n };\n const onsocket = (socket) => {\n if (timedOut)\n return;\n if (timeoutId != null) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n if (isAgent(socket)) {\n // `socket` is actually an `http.Agent` instance, so\n // relinquish responsibility for this `req` to the Agent\n // from here on\n debug('Callback returned another Agent instance %o', socket.constructor.name);\n socket.addRequest(req, opts);\n return;\n }\n if (socket) {\n socket.once('free', () => {\n this.freeSocket(socket, opts);\n });\n req.onSocket(socket);\n return;\n }\n const err = new Error(`no Duplex stream was returned to agent-base for \\`${req.method} ${req.path}\\``);\n onerror(err);\n };\n if (typeof this.callback !== 'function') {\n onerror(new Error('`callback` is not defined'));\n return;\n }\n if (!this.promisifiedCallback) {\n if (this.callback.length >= 3) {\n debug('Converting legacy callback function to promise');\n this.promisifiedCallback = promisify_1.default(this.callback);\n }\n else {\n this.promisifiedCallback = this.callback;\n }\n }\n if (typeof timeoutMs === 'number' && timeoutMs > 0) {\n timeoutId = setTimeout(ontimeout, timeoutMs);\n }\n if ('port' in opts && typeof opts.port !== 'number') {\n opts.port = Number(opts.port);\n }\n try {\n debug('Resolving socket for %o request: %o', opts.protocol, `${req.method} ${req.path}`);\n Promise.resolve(this.promisifiedCallback(req, opts)).then(onsocket, callbackError);\n }\n catch (err) {\n Promise.reject(err).catch(callbackError);\n }\n }\n freeSocket(socket, opts) {\n debug('Freeing socket %o %o', socket.constructor.name, opts);\n socket.destroy();\n }\n destroy() {\n debug('Destroying agent %o', this.constructor.name);\n }\n }\n createAgent.Agent = Agent;\n // So that `instanceof` works correctly\n createAgent.prototype = createAgent.Agent.prototype;\n})(createAgent || (createAgent = {}));\nmodule.exports = createAgent;\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nfunction promisify(fn) {\n return function (req, opts) {\n return new Promise((resolve, reject) => {\n fn.call(this, req, opts, (err, rtn) => {\n if (err) {\n reject(err);\n }\n else {\n resolve(rtn);\n }\n });\n });\n };\n}\nexports.default = promisify;\n//# sourceMappingURL=promisify.js.map","\"use strict\";\n\nvar rawAsap = require(\"./raw\");\nvar freeTasks = [];\n\n/**\n * Calls a task as soon as possible after returning, in its own event, with\n * priority over IO events. An exception thrown in a task can be handled by\n * `process.on(\"uncaughtException\") or `domain.on(\"error\")`, but will otherwise\n * crash the process. If the error is handled, all subsequent tasks will\n * resume.\n *\n * @param {{call}} task A callable object, typically a function that takes no\n * arguments.\n */\nmodule.exports = asap;\nfunction asap(task) {\n var rawTask;\n if (freeTasks.length) {\n rawTask = freeTasks.pop();\n } else {\n rawTask = new RawTask();\n }\n rawTask.task = task;\n rawTask.domain = process.domain;\n rawAsap(rawTask);\n}\n\nfunction RawTask() {\n this.task = null;\n this.domain = null;\n}\n\nRawTask.prototype.call = function () {\n if (this.domain) {\n this.domain.enter();\n }\n var threw = true;\n try {\n this.task.call();\n threw = false;\n // If the task throws an exception (presumably) Node.js restores the\n // domain stack for the next event.\n if (this.domain) {\n this.domain.exit();\n }\n } finally {\n // We use try/finally and a threw flag to avoid messing up stack traces\n // when we catch and release errors.\n if (threw) {\n // In Node.js, uncaught exceptions are considered fatal errors.\n // Re-throw them to interrupt flushing!\n // Ensure that flushing continues if an uncaught exception is\n // suppressed listening process.on(\"uncaughtException\") or\n // domain.on(\"error\").\n rawAsap.requestFlush();\n }\n // If the task threw an error, we do not want to exit the domain here.\n // Exiting the domain would prevent the domain from catching the error.\n this.task = null;\n this.domain = null;\n freeTasks.push(this);\n }\n};\n\n","\"use strict\";\n\nvar domain; // The domain module is executed on demand\nvar hasSetImmediate = typeof setImmediate === \"function\";\n\n// Use the fastest means possible to execute a task in its own turn, with\n// priority over other events including network IO events in Node.js.\n//\n// An exception thrown by a task will permanently interrupt the processing of\n// subsequent tasks. The higher level `asap` function ensures that if an\n// exception is thrown by a task, that the task queue will continue flushing as\n// soon as possible, but if you use `rawAsap` directly, you are responsible to\n// either ensure that no exceptions are thrown from your task, or to manually\n// call `rawAsap.requestFlush` if an exception is thrown.\nmodule.exports = rawAsap;\nfunction rawAsap(task) {\n if (!queue.length) {\n requestFlush();\n flushing = true;\n }\n // Avoids a function call\n queue[queue.length] = task;\n}\n\nvar queue = [];\n// Once a flush has been requested, no further calls to `requestFlush` are\n// necessary until the next `flush` completes.\nvar flushing = false;\n// The position of the next task to execute in the task queue. This is\n// preserved between calls to `flush` so that it can be resumed if\n// a task throws an exception.\nvar index = 0;\n// If a task schedules additional tasks recursively, the task queue can grow\n// unbounded. To prevent memory excaustion, the task queue will periodically\n// truncate already-completed tasks.\nvar capacity = 1024;\n\n// The flush function processes all tasks that have been scheduled with\n// `rawAsap` unless and until one of those tasks throws an exception.\n// If a task throws an exception, `flush` ensures that its state will remain\n// consistent and will resume where it left off when called again.\n// However, `flush` does not make any arrangements to be called again if an\n// exception is thrown.\nfunction flush() {\n while (index < queue.length) {\n var currentIndex = index;\n // Advance the index before calling the task. This ensures that we will\n // begin flushing on the next task the task throws an error.\n index = index + 1;\n queue[currentIndex].call();\n // Prevent leaking memory for long chains of recursive calls to `asap`.\n // If we call `asap` within tasks scheduled by `asap`, the queue will\n // grow, but to avoid an O(n) walk for every task we execute, we don't\n // shift tasks off the queue after they have been executed.\n // Instead, we periodically shift 1024 tasks off the queue.\n if (index > capacity) {\n // Manually shift all values starting at the index back to the\n // beginning of the queue.\n for (var scan = 0, newLength = queue.length - index; scan < newLength; scan++) {\n queue[scan] = queue[scan + index];\n }\n queue.length -= index;\n index = 0;\n }\n }\n queue.length = 0;\n index = 0;\n flushing = false;\n}\n\nrawAsap.requestFlush = requestFlush;\nfunction requestFlush() {\n // Ensure flushing is not bound to any domain.\n // It is not sufficient to exit the domain, because domains exist on a stack.\n // To execute code outside of any domain, the following dance is necessary.\n var parentDomain = process.domain;\n if (parentDomain) {\n if (!domain) {\n // Lazy execute the domain module.\n // Only employed if the user elects to use domains.\n domain = require(\"domain\");\n }\n domain.active = process.domain = null;\n }\n\n // `setImmediate` is slower that `process.nextTick`, but `process.nextTick`\n // cannot handle recursion.\n // `requestFlush` will only be called recursively from `asap.js`, to resume\n // flushing after an error is thrown into a domain.\n // Conveniently, `setImmediate` was introduced in the same version\n // `process.nextTick` started throwing recursion errors.\n if (flushing && hasSetImmediate) {\n setImmediate(flush);\n } else {\n process.nextTick(flush);\n }\n\n if (parentDomain) {\n domain.active = process.domain = parentDomain;\n }\n}\n","'use strict';\nmodule.exports = balanced;\nfunction balanced(a, b, str) {\n if (a instanceof RegExp) a = maybeMatch(a, str);\n if (b instanceof RegExp) b = maybeMatch(b, str);\n\n var r = range(a, b, str);\n\n return r && {\n start: r[0],\n end: r[1],\n pre: str.slice(0, r[0]),\n body: str.slice(r[0] + a.length, r[1]),\n post: str.slice(r[1] + b.length)\n };\n}\n\nfunction maybeMatch(reg, str) {\n var m = str.match(reg);\n return m ? m[0] : null;\n}\n\nbalanced.range = range;\nfunction range(a, b, str) {\n var begs, beg, left, right, result;\n var ai = str.indexOf(a);\n var bi = str.indexOf(b, ai + 1);\n var i = ai;\n\n if (ai >= 0 && bi > 0) {\n begs = [];\n left = str.length;\n\n while (i >= 0 && !result) {\n if (i == ai) {\n begs.push(i);\n ai = str.indexOf(a, i + 1);\n } else if (begs.length == 1) {\n result = [ begs.pop(), bi ];\n } else {\n beg = begs.pop();\n if (beg < left) {\n left = beg;\n right = bi;\n }\n\n bi = str.indexOf(b, i + 1);\n }\n\n i = ai < bi && ai >= 0 ? ai : bi;\n }\n\n if (begs.length) {\n result = [ left, right ];\n }\n }\n\n return result;\n}\n","'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n","var register = require('./lib/register')\nvar addHook = require('./lib/add')\nvar removeHook = require('./lib/remove')\n\n// bind with array of arguments: https://stackoverflow.com/a/21792913\nvar bind = Function.bind\nvar bindable = bind.bind(bind)\n\nfunction bindApi (hook, state, name) {\n var removeHookRef = bindable(removeHook, null).apply(null, name ? [state, name] : [state])\n hook.api = { remove: removeHookRef }\n hook.remove = removeHookRef\n\n ;['before', 'error', 'after', 'wrap'].forEach(function (kind) {\n var args = name ? [state, kind, name] : [state, kind]\n hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args)\n })\n}\n\nfunction HookSingular () {\n var singularHookName = 'h'\n var singularHookState = {\n registry: {}\n }\n var singularHook = register.bind(null, singularHookState, singularHookName)\n bindApi(singularHook, singularHookState, singularHookName)\n return singularHook\n}\n\nfunction HookCollection () {\n var state = {\n registry: {}\n }\n\n var hook = register.bind(null, state)\n bindApi(hook, state)\n\n return hook\n}\n\nvar collectionHookDeprecationMessageDisplayed = false\nfunction Hook () {\n if (!collectionHookDeprecationMessageDisplayed) {\n console.warn('[before-after-hook]: \"Hook()\" repurposing warning, use \"Hook.Collection()\". Read more: https://git.io/upgrade-before-after-hook-to-1.4')\n collectionHookDeprecationMessageDisplayed = true\n }\n return HookCollection()\n}\n\nHook.Singular = HookSingular.bind()\nHook.Collection = HookCollection.bind()\n\nmodule.exports = Hook\n// expose constructors as a named property for TypeScript\nmodule.exports.Hook = Hook\nmodule.exports.Singular = Hook.Singular\nmodule.exports.Collection = Hook.Collection\n","module.exports = addHook;\n\nfunction addHook(state, kind, name, hook) {\n var orig = hook;\n if (!state.registry[name]) {\n state.registry[name] = [];\n }\n\n if (kind === \"before\") {\n hook = function (method, options) {\n return Promise.resolve()\n .then(orig.bind(null, options))\n .then(method.bind(null, options));\n };\n }\n\n if (kind === \"after\") {\n hook = function (method, options) {\n var result;\n return Promise.resolve()\n .then(method.bind(null, options))\n .then(function (result_) {\n result = result_;\n return orig(result, options);\n })\n .then(function () {\n return result;\n });\n };\n }\n\n if (kind === \"error\") {\n hook = function (method, options) {\n return Promise.resolve()\n .then(method.bind(null, options))\n .catch(function (error) {\n return orig(error, options);\n });\n };\n }\n\n state.registry[name].push({\n hook: hook,\n orig: orig,\n });\n}\n","module.exports = register;\n\nfunction register(state, name, method, options) {\n if (typeof method !== \"function\") {\n throw new Error(\"method for before hook must be a function\");\n }\n\n if (!options) {\n options = {};\n }\n\n if (Array.isArray(name)) {\n return name.reverse().reduce(function (callback, name) {\n return register.bind(null, state, name, callback, options);\n }, method)();\n }\n\n return Promise.resolve().then(function () {\n if (!state.registry[name]) {\n return method(options);\n }\n\n return state.registry[name].reduce(function (method, registered) {\n return registered.hook.bind(null, method, options);\n }, method)();\n });\n}\n","module.exports = removeHook;\n\nfunction removeHook(state, name, method) {\n if (!state.registry[name]) {\n return;\n }\n\n var index = state.registry[name]\n .map(function (registered) {\n return registered.orig;\n })\n .indexOf(method);\n\n if (index === -1) {\n return;\n }\n\n state.registry[name].splice(index, 1);\n}\n",";(function (globalObject) {\r\n 'use strict';\r\n\r\n/*\r\n * bignumber.js v9.0.1\r\n * A JavaScript library for arbitrary-precision arithmetic.\r\n * https://github.com/MikeMcl/bignumber.js\r\n * Copyright (c) 2020 Michael Mclaughlin \r\n * MIT Licensed.\r\n *\r\n * BigNumber.prototype methods | BigNumber methods\r\n * |\r\n * absoluteValue abs | clone\r\n * comparedTo | config set\r\n * decimalPlaces dp | DECIMAL_PLACES\r\n * dividedBy div | ROUNDING_MODE\r\n * dividedToIntegerBy idiv | EXPONENTIAL_AT\r\n * exponentiatedBy pow | RANGE\r\n * integerValue | CRYPTO\r\n * isEqualTo eq | MODULO_MODE\r\n * isFinite | POW_PRECISION\r\n * isGreaterThan gt | FORMAT\r\n * isGreaterThanOrEqualTo gte | ALPHABET\r\n * isInteger | isBigNumber\r\n * isLessThan lt | maximum max\r\n * isLessThanOrEqualTo lte | minimum min\r\n * isNaN | random\r\n * isNegative | sum\r\n * isPositive |\r\n * isZero |\r\n * minus |\r\n * modulo mod |\r\n * multipliedBy times |\r\n * negated |\r\n * plus |\r\n * precision sd |\r\n * shiftedBy |\r\n * squareRoot sqrt |\r\n * toExponential |\r\n * toFixed |\r\n * toFormat |\r\n * toFraction |\r\n * toJSON |\r\n * toNumber |\r\n * toPrecision |\r\n * toString |\r\n * valueOf |\r\n *\r\n */\r\n\r\n\r\n var BigNumber,\r\n isNumeric = /^-?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i,\r\n mathceil = Math.ceil,\r\n mathfloor = Math.floor,\r\n\r\n bignumberError = '[BigNumber Error] ',\r\n tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ',\r\n\r\n BASE = 1e14,\r\n LOG_BASE = 14,\r\n MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1\r\n // MAX_INT32 = 0x7fffffff, // 2^31 - 1\r\n POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13],\r\n SQRT_BASE = 1e7,\r\n\r\n // EDITABLE\r\n // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and\r\n // the arguments to toExponential, toFixed, toFormat, and toPrecision.\r\n MAX = 1E9; // 0 to MAX_INT32\r\n\r\n\r\n /*\r\n * Create and return a BigNumber constructor.\r\n */\r\n function clone(configObject) {\r\n var div, convertBase, parseNumeric,\r\n P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null },\r\n ONE = new BigNumber(1),\r\n\r\n\r\n //----------------------------- EDITABLE CONFIG DEFAULTS -------------------------------\r\n\r\n\r\n // The default values below must be integers within the inclusive ranges stated.\r\n // The values can also be changed at run-time using BigNumber.set.\r\n\r\n // The maximum number of decimal places for operations involving division.\r\n DECIMAL_PLACES = 20, // 0 to MAX\r\n\r\n // The rounding mode used when rounding to the above decimal places, and when using\r\n // toExponential, toFixed, toFormat and toPrecision, and round (default value).\r\n // UP 0 Away from zero.\r\n // DOWN 1 Towards zero.\r\n // CEIL 2 Towards +Infinity.\r\n // FLOOR 3 Towards -Infinity.\r\n // HALF_UP 4 Towards nearest neighbour. If equidistant, up.\r\n // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.\r\n // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.\r\n // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.\r\n // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.\r\n ROUNDING_MODE = 4, // 0 to 8\r\n\r\n // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS]\r\n\r\n // The exponent value at and beneath which toString returns exponential notation.\r\n // Number type: -7\r\n TO_EXP_NEG = -7, // 0 to -MAX\r\n\r\n // The exponent value at and above which toString returns exponential notation.\r\n // Number type: 21\r\n TO_EXP_POS = 21, // 0 to MAX\r\n\r\n // RANGE : [MIN_EXP, MAX_EXP]\r\n\r\n // The minimum exponent value, beneath which underflow to zero occurs.\r\n // Number type: -324 (5e-324)\r\n MIN_EXP = -1e7, // -1 to -MAX\r\n\r\n // The maximum exponent value, above which overflow to Infinity occurs.\r\n // Number type: 308 (1.7976931348623157e+308)\r\n // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow.\r\n MAX_EXP = 1e7, // 1 to MAX\r\n\r\n // Whether to use cryptographically-secure random number generation, if available.\r\n CRYPTO = false, // true or false\r\n\r\n // The modulo mode used when calculating the modulus: a mod n.\r\n // The quotient (q = a / n) is calculated according to the corresponding rounding mode.\r\n // The remainder (r) is calculated as: r = a - n * q.\r\n //\r\n // UP 0 The remainder is positive if the dividend is negative, else is negative.\r\n // DOWN 1 The remainder has the same sign as the dividend.\r\n // This modulo mode is commonly known as 'truncated division' and is\r\n // equivalent to (a % n) in JavaScript.\r\n // FLOOR 3 The remainder has the same sign as the divisor (Python %).\r\n // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function.\r\n // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)).\r\n // The remainder is always positive.\r\n //\r\n // The truncated division, floored division, Euclidian division and IEEE 754 remainder\r\n // modes are commonly used for the modulus operation.\r\n // Although the other rounding modes can also be used, they may not give useful results.\r\n MODULO_MODE = 1, // 0 to 9\r\n\r\n // The maximum number of significant digits of the result of the exponentiatedBy operation.\r\n // If POW_PRECISION is 0, there will be unlimited significant digits.\r\n POW_PRECISION = 0, // 0 to MAX\r\n\r\n // The format specification used by the BigNumber.prototype.toFormat method.\r\n FORMAT = {\r\n prefix: '',\r\n groupSize: 3,\r\n secondaryGroupSize: 0,\r\n groupSeparator: ',',\r\n decimalSeparator: '.',\r\n fractionGroupSize: 0,\r\n fractionGroupSeparator: '\\xA0', // non-breaking space\r\n suffix: ''\r\n },\r\n\r\n // The alphabet used for base conversion. It must be at least 2 characters long, with no '+',\r\n // '-', '.', whitespace, or repeated character.\r\n // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_'\r\n ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz';\r\n\r\n\r\n //------------------------------------------------------------------------------------------\r\n\r\n\r\n // CONSTRUCTOR\r\n\r\n\r\n /*\r\n * The BigNumber constructor and exported function.\r\n * Create and return a new instance of a BigNumber object.\r\n *\r\n * v {number|string|BigNumber} A numeric value.\r\n * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive.\r\n */\r\n function BigNumber(v, b) {\r\n var alphabet, c, caseChanged, e, i, isNum, len, str,\r\n x = this;\r\n\r\n // Enable constructor call without `new`.\r\n if (!(x instanceof BigNumber)) return new BigNumber(v, b);\r\n\r\n if (b == null) {\r\n\r\n if (v && v._isBigNumber === true) {\r\n x.s = v.s;\r\n\r\n if (!v.c || v.e > MAX_EXP) {\r\n x.c = x.e = null;\r\n } else if (v.e < MIN_EXP) {\r\n x.c = [x.e = 0];\r\n } else {\r\n x.e = v.e;\r\n x.c = v.c.slice();\r\n }\r\n\r\n return;\r\n }\r\n\r\n if ((isNum = typeof v == 'number') && v * 0 == 0) {\r\n\r\n // Use `1 / n` to handle minus zero also.\r\n x.s = 1 / v < 0 ? (v = -v, -1) : 1;\r\n\r\n // Fast path for integers, where n < 2147483648 (2**31).\r\n if (v === ~~v) {\r\n for (e = 0, i = v; i >= 10; i /= 10, e++);\r\n\r\n if (e > MAX_EXP) {\r\n x.c = x.e = null;\r\n } else {\r\n x.e = e;\r\n x.c = [v];\r\n }\r\n\r\n return;\r\n }\r\n\r\n str = String(v);\r\n } else {\r\n\r\n if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum);\r\n\r\n x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1;\r\n }\r\n\r\n // Decimal point?\r\n if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');\r\n\r\n // Exponential form?\r\n if ((i = str.search(/e/i)) > 0) {\r\n\r\n // Determine exponent.\r\n if (e < 0) e = i;\r\n e += +str.slice(i + 1);\r\n str = str.substring(0, i);\r\n } else if (e < 0) {\r\n\r\n // Integer.\r\n e = str.length;\r\n }\r\n\r\n } else {\r\n\r\n // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}'\r\n intCheck(b, 2, ALPHABET.length, 'Base');\r\n\r\n // Allow exponential notation to be used with base 10 argument, while\r\n // also rounding to DECIMAL_PLACES as with other bases.\r\n if (b == 10) {\r\n x = new BigNumber(v);\r\n return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE);\r\n }\r\n\r\n str = String(v);\r\n\r\n if (isNum = typeof v == 'number') {\r\n\r\n // Avoid potential interpretation of Infinity and NaN as base 44+ values.\r\n if (v * 0 != 0) return parseNumeric(x, str, isNum, b);\r\n\r\n x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1;\r\n\r\n // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}'\r\n if (BigNumber.DEBUG && str.replace(/^0\\.0*|\\./, '').length > 15) {\r\n throw Error\r\n (tooManyDigits + v);\r\n }\r\n } else {\r\n x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1;\r\n }\r\n\r\n alphabet = ALPHABET.slice(0, b);\r\n e = i = 0;\r\n\r\n // Check that str is a valid base b number.\r\n // Don't use RegExp, so alphabet can contain special characters.\r\n for (len = str.length; i < len; i++) {\r\n if (alphabet.indexOf(c = str.charAt(i)) < 0) {\r\n if (c == '.') {\r\n\r\n // If '.' is not the first character and it has not be found before.\r\n if (i > e) {\r\n e = len;\r\n continue;\r\n }\r\n } else if (!caseChanged) {\r\n\r\n // Allow e.g. hexadecimal 'FF' as well as 'ff'.\r\n if (str == str.toUpperCase() && (str = str.toLowerCase()) ||\r\n str == str.toLowerCase() && (str = str.toUpperCase())) {\r\n caseChanged = true;\r\n i = -1;\r\n e = 0;\r\n continue;\r\n }\r\n }\r\n\r\n return parseNumeric(x, String(v), isNum, b);\r\n }\r\n }\r\n\r\n // Prevent later check for length on converted number.\r\n isNum = false;\r\n str = convertBase(str, b, 10, x.s);\r\n\r\n // Decimal point?\r\n if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');\r\n else e = str.length;\r\n }\r\n\r\n // Determine leading zeros.\r\n for (i = 0; str.charCodeAt(i) === 48; i++);\r\n\r\n // Determine trailing zeros.\r\n for (len = str.length; str.charCodeAt(--len) === 48;);\r\n\r\n if (str = str.slice(i, ++len)) {\r\n len -= i;\r\n\r\n // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}'\r\n if (isNum && BigNumber.DEBUG &&\r\n len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) {\r\n throw Error\r\n (tooManyDigits + (x.s * v));\r\n }\r\n\r\n // Overflow?\r\n if ((e = e - i - 1) > MAX_EXP) {\r\n\r\n // Infinity.\r\n x.c = x.e = null;\r\n\r\n // Underflow?\r\n } else if (e < MIN_EXP) {\r\n\r\n // Zero.\r\n x.c = [x.e = 0];\r\n } else {\r\n x.e = e;\r\n x.c = [];\r\n\r\n // Transform base\r\n\r\n // e is the base 10 exponent.\r\n // i is where to slice str to get the first element of the coefficient array.\r\n i = (e + 1) % LOG_BASE;\r\n if (e < 0) i += LOG_BASE; // i < 1\r\n\r\n if (i < len) {\r\n if (i) x.c.push(+str.slice(0, i));\r\n\r\n for (len -= LOG_BASE; i < len;) {\r\n x.c.push(+str.slice(i, i += LOG_BASE));\r\n }\r\n\r\n i = LOG_BASE - (str = str.slice(i)).length;\r\n } else {\r\n i -= len;\r\n }\r\n\r\n for (; i--; str += '0');\r\n x.c.push(+str);\r\n }\r\n } else {\r\n\r\n // Zero.\r\n x.c = [x.e = 0];\r\n }\r\n }\r\n\r\n\r\n // CONSTRUCTOR PROPERTIES\r\n\r\n\r\n BigNumber.clone = clone;\r\n\r\n BigNumber.ROUND_UP = 0;\r\n BigNumber.ROUND_DOWN = 1;\r\n BigNumber.ROUND_CEIL = 2;\r\n BigNumber.ROUND_FLOOR = 3;\r\n BigNumber.ROUND_HALF_UP = 4;\r\n BigNumber.ROUND_HALF_DOWN = 5;\r\n BigNumber.ROUND_HALF_EVEN = 6;\r\n BigNumber.ROUND_HALF_CEIL = 7;\r\n BigNumber.ROUND_HALF_FLOOR = 8;\r\n BigNumber.EUCLID = 9;\r\n\r\n\r\n /*\r\n * Configure infrequently-changing library-wide settings.\r\n *\r\n * Accept an object with the following optional properties (if the value of a property is\r\n * a number, it must be an integer within the inclusive range stated):\r\n *\r\n * DECIMAL_PLACES {number} 0 to MAX\r\n * ROUNDING_MODE {number} 0 to 8\r\n * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX]\r\n * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX]\r\n * CRYPTO {boolean} true or false\r\n * MODULO_MODE {number} 0 to 9\r\n * POW_PRECISION {number} 0 to MAX\r\n * ALPHABET {string} A string of two or more unique characters which does\r\n * not contain '.'.\r\n * FORMAT {object} An object with some of the following properties:\r\n * prefix {string}\r\n * groupSize {number}\r\n * secondaryGroupSize {number}\r\n * groupSeparator {string}\r\n * decimalSeparator {string}\r\n * fractionGroupSize {number}\r\n * fractionGroupSeparator {string}\r\n * suffix {string}\r\n *\r\n * (The values assigned to the above FORMAT object properties are not checked for validity.)\r\n *\r\n * E.g.\r\n * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 })\r\n *\r\n * Ignore properties/parameters set to null or undefined, except for ALPHABET.\r\n *\r\n * Return an object with the properties current values.\r\n */\r\n BigNumber.config = BigNumber.set = function (obj) {\r\n var p, v;\r\n\r\n if (obj != null) {\r\n\r\n if (typeof obj == 'object') {\r\n\r\n // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive.\r\n // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) {\r\n v = obj[p];\r\n intCheck(v, 0, MAX, p);\r\n DECIMAL_PLACES = v;\r\n }\r\n\r\n // ROUNDING_MODE {number} Integer, 0 to 8 inclusive.\r\n // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) {\r\n v = obj[p];\r\n intCheck(v, 0, 8, p);\r\n ROUNDING_MODE = v;\r\n }\r\n\r\n // EXPONENTIAL_AT {number|number[]}\r\n // Integer, -MAX to MAX inclusive or\r\n // [integer -MAX to 0 inclusive, 0 to MAX inclusive].\r\n // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) {\r\n v = obj[p];\r\n if (v && v.pop) {\r\n intCheck(v[0], -MAX, 0, p);\r\n intCheck(v[1], 0, MAX, p);\r\n TO_EXP_NEG = v[0];\r\n TO_EXP_POS = v[1];\r\n } else {\r\n intCheck(v, -MAX, MAX, p);\r\n TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v);\r\n }\r\n }\r\n\r\n // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or\r\n // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive].\r\n // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}'\r\n if (obj.hasOwnProperty(p = 'RANGE')) {\r\n v = obj[p];\r\n if (v && v.pop) {\r\n intCheck(v[0], -MAX, -1, p);\r\n intCheck(v[1], 1, MAX, p);\r\n MIN_EXP = v[0];\r\n MAX_EXP = v[1];\r\n } else {\r\n intCheck(v, -MAX, MAX, p);\r\n if (v) {\r\n MIN_EXP = -(MAX_EXP = v < 0 ? -v : v);\r\n } else {\r\n throw Error\r\n (bignumberError + p + ' cannot be zero: ' + v);\r\n }\r\n }\r\n }\r\n\r\n // CRYPTO {boolean} true or false.\r\n // '[BigNumber Error] CRYPTO not true or false: {v}'\r\n // '[BigNumber Error] crypto unavailable'\r\n if (obj.hasOwnProperty(p = 'CRYPTO')) {\r\n v = obj[p];\r\n if (v === !!v) {\r\n if (v) {\r\n if (typeof crypto != 'undefined' && crypto &&\r\n (crypto.getRandomValues || crypto.randomBytes)) {\r\n CRYPTO = v;\r\n } else {\r\n CRYPTO = !v;\r\n throw Error\r\n (bignumberError + 'crypto unavailable');\r\n }\r\n } else {\r\n CRYPTO = v;\r\n }\r\n } else {\r\n throw Error\r\n (bignumberError + p + ' not true or false: ' + v);\r\n }\r\n }\r\n\r\n // MODULO_MODE {number} Integer, 0 to 9 inclusive.\r\n // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'MODULO_MODE')) {\r\n v = obj[p];\r\n intCheck(v, 0, 9, p);\r\n MODULO_MODE = v;\r\n }\r\n\r\n // POW_PRECISION {number} Integer, 0 to MAX inclusive.\r\n // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'POW_PRECISION')) {\r\n v = obj[p];\r\n intCheck(v, 0, MAX, p);\r\n POW_PRECISION = v;\r\n }\r\n\r\n // FORMAT {object}\r\n // '[BigNumber Error] FORMAT not an object: {v}'\r\n if (obj.hasOwnProperty(p = 'FORMAT')) {\r\n v = obj[p];\r\n if (typeof v == 'object') FORMAT = v;\r\n else throw Error\r\n (bignumberError + p + ' not an object: ' + v);\r\n }\r\n\r\n // ALPHABET {string}\r\n // '[BigNumber Error] ALPHABET invalid: {v}'\r\n if (obj.hasOwnProperty(p = 'ALPHABET')) {\r\n v = obj[p];\r\n\r\n // Disallow if less than two characters,\r\n // or if it contains '+', '-', '.', whitespace, or a repeated character.\r\n if (typeof v == 'string' && !/^.?$|[+\\-.\\s]|(.).*\\1/.test(v)) {\r\n ALPHABET = v;\r\n } else {\r\n throw Error\r\n (bignumberError + p + ' invalid: ' + v);\r\n }\r\n }\r\n\r\n } else {\r\n\r\n // '[BigNumber Error] Object expected: {v}'\r\n throw Error\r\n (bignumberError + 'Object expected: ' + obj);\r\n }\r\n }\r\n\r\n return {\r\n DECIMAL_PLACES: DECIMAL_PLACES,\r\n ROUNDING_MODE: ROUNDING_MODE,\r\n EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS],\r\n RANGE: [MIN_EXP, MAX_EXP],\r\n CRYPTO: CRYPTO,\r\n MODULO_MODE: MODULO_MODE,\r\n POW_PRECISION: POW_PRECISION,\r\n FORMAT: FORMAT,\r\n ALPHABET: ALPHABET\r\n };\r\n };\r\n\r\n\r\n /*\r\n * Return true if v is a BigNumber instance, otherwise return false.\r\n *\r\n * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed.\r\n *\r\n * v {any}\r\n *\r\n * '[BigNumber Error] Invalid BigNumber: {v}'\r\n */\r\n BigNumber.isBigNumber = function (v) {\r\n if (!v || v._isBigNumber !== true) return false;\r\n if (!BigNumber.DEBUG) return true;\r\n\r\n var i, n,\r\n c = v.c,\r\n e = v.e,\r\n s = v.s;\r\n\r\n out: if ({}.toString.call(c) == '[object Array]') {\r\n\r\n if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) {\r\n\r\n // If the first element is zero, the BigNumber value must be zero.\r\n if (c[0] === 0) {\r\n if (e === 0 && c.length === 1) return true;\r\n break out;\r\n }\r\n\r\n // Calculate number of digits that c[0] should have, based on the exponent.\r\n i = (e + 1) % LOG_BASE;\r\n if (i < 1) i += LOG_BASE;\r\n\r\n // Calculate number of digits of c[0].\r\n //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) {\r\n if (String(c[0]).length == i) {\r\n\r\n for (i = 0; i < c.length; i++) {\r\n n = c[i];\r\n if (n < 0 || n >= BASE || n !== mathfloor(n)) break out;\r\n }\r\n\r\n // Last element cannot be zero, unless it is the only element.\r\n if (n !== 0) return true;\r\n }\r\n }\r\n\r\n // Infinity/NaN\r\n } else if (c === null && e === null && (s === null || s === 1 || s === -1)) {\r\n return true;\r\n }\r\n\r\n throw Error\r\n (bignumberError + 'Invalid BigNumber: ' + v);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the maximum of the arguments.\r\n *\r\n * arguments {number|string|BigNumber}\r\n */\r\n BigNumber.maximum = BigNumber.max = function () {\r\n return maxOrMin(arguments, P.lt);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the minimum of the arguments.\r\n *\r\n * arguments {number|string|BigNumber}\r\n */\r\n BigNumber.minimum = BigNumber.min = function () {\r\n return maxOrMin(arguments, P.gt);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber with a random value equal to or greater than 0 and less than 1,\r\n * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing\r\n * zeros are produced).\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}'\r\n * '[BigNumber Error] crypto unavailable'\r\n */\r\n BigNumber.random = (function () {\r\n var pow2_53 = 0x20000000000000;\r\n\r\n // Return a 53 bit integer n, where 0 <= n < 9007199254740992.\r\n // Check if Math.random() produces more than 32 bits of randomness.\r\n // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits.\r\n // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1.\r\n var random53bitInt = (Math.random() * pow2_53) & 0x1fffff\r\n ? function () { return mathfloor(Math.random() * pow2_53); }\r\n : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) +\r\n (Math.random() * 0x800000 | 0); };\r\n\r\n return function (dp) {\r\n var a, b, e, k, v,\r\n i = 0,\r\n c = [],\r\n rand = new BigNumber(ONE);\r\n\r\n if (dp == null) dp = DECIMAL_PLACES;\r\n else intCheck(dp, 0, MAX);\r\n\r\n k = mathceil(dp / LOG_BASE);\r\n\r\n if (CRYPTO) {\r\n\r\n // Browsers supporting crypto.getRandomValues.\r\n if (crypto.getRandomValues) {\r\n\r\n a = crypto.getRandomValues(new Uint32Array(k *= 2));\r\n\r\n for (; i < k;) {\r\n\r\n // 53 bits:\r\n // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2)\r\n // 11111 11111111 11111111 11111111 11100000 00000000 00000000\r\n // ((Math.pow(2, 32) - 1) >>> 11).toString(2)\r\n // 11111 11111111 11111111\r\n // 0x20000 is 2^21.\r\n v = a[i] * 0x20000 + (a[i + 1] >>> 11);\r\n\r\n // Rejection sampling:\r\n // 0 <= v < 9007199254740992\r\n // Probability that v >= 9e15, is\r\n // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251\r\n if (v >= 9e15) {\r\n b = crypto.getRandomValues(new Uint32Array(2));\r\n a[i] = b[0];\r\n a[i + 1] = b[1];\r\n } else {\r\n\r\n // 0 <= v <= 8999999999999999\r\n // 0 <= (v % 1e14) <= 99999999999999\r\n c.push(v % 1e14);\r\n i += 2;\r\n }\r\n }\r\n i = k / 2;\r\n\r\n // Node.js supporting crypto.randomBytes.\r\n } else if (crypto.randomBytes) {\r\n\r\n // buffer\r\n a = crypto.randomBytes(k *= 7);\r\n\r\n for (; i < k;) {\r\n\r\n // 0x1000000000000 is 2^48, 0x10000000000 is 2^40\r\n // 0x100000000 is 2^32, 0x1000000 is 2^24\r\n // 11111 11111111 11111111 11111111 11111111 11111111 11111111\r\n // 0 <= v < 9007199254740992\r\n v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) +\r\n (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) +\r\n (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6];\r\n\r\n if (v >= 9e15) {\r\n crypto.randomBytes(7).copy(a, i);\r\n } else {\r\n\r\n // 0 <= (v % 1e14) <= 99999999999999\r\n c.push(v % 1e14);\r\n i += 7;\r\n }\r\n }\r\n i = k / 7;\r\n } else {\r\n CRYPTO = false;\r\n throw Error\r\n (bignumberError + 'crypto unavailable');\r\n }\r\n }\r\n\r\n // Use Math.random.\r\n if (!CRYPTO) {\r\n\r\n for (; i < k;) {\r\n v = random53bitInt();\r\n if (v < 9e15) c[i++] = v % 1e14;\r\n }\r\n }\r\n\r\n k = c[--i];\r\n dp %= LOG_BASE;\r\n\r\n // Convert trailing digits to zeros according to dp.\r\n if (k && dp) {\r\n v = POWS_TEN[LOG_BASE - dp];\r\n c[i] = mathfloor(k / v) * v;\r\n }\r\n\r\n // Remove trailing elements which are zero.\r\n for (; c[i] === 0; c.pop(), i--);\r\n\r\n // Zero?\r\n if (i < 0) {\r\n c = [e = 0];\r\n } else {\r\n\r\n // Remove leading elements which are zero and adjust exponent accordingly.\r\n for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE);\r\n\r\n // Count the digits of the first element of c to determine leading zeros, and...\r\n for (i = 1, v = c[0]; v >= 10; v /= 10, i++);\r\n\r\n // adjust the exponent accordingly.\r\n if (i < LOG_BASE) e -= LOG_BASE - i;\r\n }\r\n\r\n rand.e = e;\r\n rand.c = c;\r\n return rand;\r\n };\r\n })();\r\n\r\n\r\n /*\r\n * Return a BigNumber whose value is the sum of the arguments.\r\n *\r\n * arguments {number|string|BigNumber}\r\n */\r\n BigNumber.sum = function () {\r\n var i = 1,\r\n args = arguments,\r\n sum = new BigNumber(args[0]);\r\n for (; i < args.length;) sum = sum.plus(args[i++]);\r\n return sum;\r\n };\r\n\r\n\r\n // PRIVATE FUNCTIONS\r\n\r\n\r\n // Called by BigNumber and BigNumber.prototype.toString.\r\n convertBase = (function () {\r\n var decimal = '0123456789';\r\n\r\n /*\r\n * Convert string of baseIn to an array of numbers of baseOut.\r\n * Eg. toBaseOut('255', 10, 16) returns [15, 15].\r\n * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5].\r\n */\r\n function toBaseOut(str, baseIn, baseOut, alphabet) {\r\n var j,\r\n arr = [0],\r\n arrL,\r\n i = 0,\r\n len = str.length;\r\n\r\n for (; i < len;) {\r\n for (arrL = arr.length; arrL--; arr[arrL] *= baseIn);\r\n\r\n arr[0] += alphabet.indexOf(str.charAt(i++));\r\n\r\n for (j = 0; j < arr.length; j++) {\r\n\r\n if (arr[j] > baseOut - 1) {\r\n if (arr[j + 1] == null) arr[j + 1] = 0;\r\n arr[j + 1] += arr[j] / baseOut | 0;\r\n arr[j] %= baseOut;\r\n }\r\n }\r\n }\r\n\r\n return arr.reverse();\r\n }\r\n\r\n // Convert a numeric string of baseIn to a numeric string of baseOut.\r\n // If the caller is toString, we are converting from base 10 to baseOut.\r\n // If the caller is BigNumber, we are converting from baseIn to base 10.\r\n return function (str, baseIn, baseOut, sign, callerIsToString) {\r\n var alphabet, d, e, k, r, x, xc, y,\r\n i = str.indexOf('.'),\r\n dp = DECIMAL_PLACES,\r\n rm = ROUNDING_MODE;\r\n\r\n // Non-integer.\r\n if (i >= 0) {\r\n k = POW_PRECISION;\r\n\r\n // Unlimited precision.\r\n POW_PRECISION = 0;\r\n str = str.replace('.', '');\r\n y = new BigNumber(baseIn);\r\n x = y.pow(str.length - i);\r\n POW_PRECISION = k;\r\n\r\n // Convert str as if an integer, then restore the fraction part by dividing the\r\n // result by its base raised to a power.\r\n\r\n y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'),\r\n 10, baseOut, decimal);\r\n y.e = y.c.length;\r\n }\r\n\r\n // Convert the number as integer.\r\n\r\n xc = toBaseOut(str, baseIn, baseOut, callerIsToString\r\n ? (alphabet = ALPHABET, decimal)\r\n : (alphabet = decimal, ALPHABET));\r\n\r\n // xc now represents str as an integer and converted to baseOut. e is the exponent.\r\n e = k = xc.length;\r\n\r\n // Remove trailing zeros.\r\n for (; xc[--k] == 0; xc.pop());\r\n\r\n // Zero?\r\n if (!xc[0]) return alphabet.charAt(0);\r\n\r\n // Does str represent an integer? If so, no need for the division.\r\n if (i < 0) {\r\n --e;\r\n } else {\r\n x.c = xc;\r\n x.e = e;\r\n\r\n // The sign is needed for correct rounding.\r\n x.s = sign;\r\n x = div(x, y, dp, rm, baseOut);\r\n xc = x.c;\r\n r = x.r;\r\n e = x.e;\r\n }\r\n\r\n // xc now represents str converted to baseOut.\r\n\r\n // THe index of the rounding digit.\r\n d = e + dp + 1;\r\n\r\n // The rounding digit: the digit to the right of the digit that may be rounded up.\r\n i = xc[d];\r\n\r\n // Look at the rounding digits and mode to determine whether to round up.\r\n\r\n k = baseOut / 2;\r\n r = r || d < 0 || xc[d + 1] != null;\r\n\r\n r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))\r\n : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||\r\n rm == (x.s < 0 ? 8 : 7));\r\n\r\n // If the index of the rounding digit is not greater than zero, or xc represents\r\n // zero, then the result of the base conversion is zero or, if rounding up, a value\r\n // such as 0.00001.\r\n if (d < 1 || !xc[0]) {\r\n\r\n // 1^-dp or 0\r\n str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0);\r\n } else {\r\n\r\n // Truncate xc to the required number of decimal places.\r\n xc.length = d;\r\n\r\n // Round up?\r\n if (r) {\r\n\r\n // Rounding up may mean the previous digit has to be rounded up and so on.\r\n for (--baseOut; ++xc[--d] > baseOut;) {\r\n xc[d] = 0;\r\n\r\n if (!d) {\r\n ++e;\r\n xc = [1].concat(xc);\r\n }\r\n }\r\n }\r\n\r\n // Determine trailing zeros.\r\n for (k = xc.length; !xc[--k];);\r\n\r\n // E.g. [4, 11, 15] becomes 4bf.\r\n for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++]));\r\n\r\n // Add leading zeros, decimal point and trailing zeros as required.\r\n str = toFixedPoint(str, e, alphabet.charAt(0));\r\n }\r\n\r\n // The caller will add the sign.\r\n return str;\r\n };\r\n })();\r\n\r\n\r\n // Perform division in the specified base. Called by div and convertBase.\r\n div = (function () {\r\n\r\n // Assume non-zero x and k.\r\n function multiply(x, k, base) {\r\n var m, temp, xlo, xhi,\r\n carry = 0,\r\n i = x.length,\r\n klo = k % SQRT_BASE,\r\n khi = k / SQRT_BASE | 0;\r\n\r\n for (x = x.slice(); i--;) {\r\n xlo = x[i] % SQRT_BASE;\r\n xhi = x[i] / SQRT_BASE | 0;\r\n m = khi * xlo + xhi * klo;\r\n temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;\r\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\r\n x[i] = temp % base;\r\n }\r\n\r\n if (carry) x = [carry].concat(x);\r\n\r\n return x;\r\n }\r\n\r\n function compare(a, b, aL, bL) {\r\n var i, cmp;\r\n\r\n if (aL != bL) {\r\n cmp = aL > bL ? 1 : -1;\r\n } else {\r\n\r\n for (i = cmp = 0; i < aL; i++) {\r\n\r\n if (a[i] != b[i]) {\r\n cmp = a[i] > b[i] ? 1 : -1;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n return cmp;\r\n }\r\n\r\n function subtract(a, b, aL, base) {\r\n var i = 0;\r\n\r\n // Subtract b from a.\r\n for (; aL--;) {\r\n a[aL] -= i;\r\n i = a[aL] < b[aL] ? 1 : 0;\r\n a[aL] = i * base + a[aL] - b[aL];\r\n }\r\n\r\n // Remove leading zeros.\r\n for (; !a[0] && a.length > 1; a.splice(0, 1));\r\n }\r\n\r\n // x: dividend, y: divisor.\r\n return function (x, y, dp, rm, base) {\r\n var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0,\r\n yL, yz,\r\n s = x.s == y.s ? 1 : -1,\r\n xc = x.c,\r\n yc = y.c;\r\n\r\n // Either NaN, Infinity or 0?\r\n if (!xc || !xc[0] || !yc || !yc[0]) {\r\n\r\n return new BigNumber(\r\n\r\n // Return NaN if either NaN, or both Infinity or 0.\r\n !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN :\r\n\r\n // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0.\r\n xc && xc[0] == 0 || !yc ? s * 0 : s / 0\r\n );\r\n }\r\n\r\n q = new BigNumber(s);\r\n qc = q.c = [];\r\n e = x.e - y.e;\r\n s = dp + e + 1;\r\n\r\n if (!base) {\r\n base = BASE;\r\n e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE);\r\n s = s / LOG_BASE | 0;\r\n }\r\n\r\n // Result exponent may be one less then the current value of e.\r\n // The coefficients of the BigNumbers from convertBase may have trailing zeros.\r\n for (i = 0; yc[i] == (xc[i] || 0); i++);\r\n\r\n if (yc[i] > (xc[i] || 0)) e--;\r\n\r\n if (s < 0) {\r\n qc.push(1);\r\n more = true;\r\n } else {\r\n xL = xc.length;\r\n yL = yc.length;\r\n i = 0;\r\n s += 2;\r\n\r\n // Normalise xc and yc so highest order digit of yc is >= base / 2.\r\n\r\n n = mathfloor(base / (yc[0] + 1));\r\n\r\n // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1.\r\n // if (n > 1 || n++ == 1 && yc[0] < base / 2) {\r\n if (n > 1) {\r\n yc = multiply(yc, n, base);\r\n xc = multiply(xc, n, base);\r\n yL = yc.length;\r\n xL = xc.length;\r\n }\r\n\r\n xi = yL;\r\n rem = xc.slice(0, yL);\r\n remL = rem.length;\r\n\r\n // Add zeros to make remainder as long as divisor.\r\n for (; remL < yL; rem[remL++] = 0);\r\n yz = yc.slice();\r\n yz = [0].concat(yz);\r\n yc0 = yc[0];\r\n if (yc[1] >= base / 2) yc0++;\r\n // Not necessary, but to prevent trial digit n > base, when using base 3.\r\n // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15;\r\n\r\n do {\r\n n = 0;\r\n\r\n // Compare divisor and remainder.\r\n cmp = compare(yc, rem, yL, remL);\r\n\r\n // If divisor < remainder.\r\n if (cmp < 0) {\r\n\r\n // Calculate trial digit, n.\r\n\r\n rem0 = rem[0];\r\n if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);\r\n\r\n // n is how many times the divisor goes into the current remainder.\r\n n = mathfloor(rem0 / yc0);\r\n\r\n // Algorithm:\r\n // product = divisor multiplied by trial digit (n).\r\n // Compare product and remainder.\r\n // If product is greater than remainder:\r\n // Subtract divisor from product, decrement trial digit.\r\n // Subtract product from remainder.\r\n // If product was less than remainder at the last compare:\r\n // Compare new remainder and divisor.\r\n // If remainder is greater than divisor:\r\n // Subtract divisor from remainder, increment trial digit.\r\n\r\n if (n > 1) {\r\n\r\n // n may be > base only when base is 3.\r\n if (n >= base) n = base - 1;\r\n\r\n // product = divisor * trial digit.\r\n prod = multiply(yc, n, base);\r\n prodL = prod.length;\r\n remL = rem.length;\r\n\r\n // Compare product and remainder.\r\n // If product > remainder then trial digit n too high.\r\n // n is 1 too high about 5% of the time, and is not known to have\r\n // ever been more than 1 too high.\r\n while (compare(prod, rem, prodL, remL) == 1) {\r\n n--;\r\n\r\n // Subtract divisor from product.\r\n subtract(prod, yL < prodL ? yz : yc, prodL, base);\r\n prodL = prod.length;\r\n cmp = 1;\r\n }\r\n } else {\r\n\r\n // n is 0 or 1, cmp is -1.\r\n // If n is 0, there is no need to compare yc and rem again below,\r\n // so change cmp to 1 to avoid it.\r\n // If n is 1, leave cmp as -1, so yc and rem are compared again.\r\n if (n == 0) {\r\n\r\n // divisor < remainder, so n must be at least 1.\r\n cmp = n = 1;\r\n }\r\n\r\n // product = divisor\r\n prod = yc.slice();\r\n prodL = prod.length;\r\n }\r\n\r\n if (prodL < remL) prod = [0].concat(prod);\r\n\r\n // Subtract product from remainder.\r\n subtract(rem, prod, remL, base);\r\n remL = rem.length;\r\n\r\n // If product was < remainder.\r\n if (cmp == -1) {\r\n\r\n // Compare divisor and new remainder.\r\n // If divisor < new remainder, subtract divisor from remainder.\r\n // Trial digit n too low.\r\n // n is 1 too low about 5% of the time, and very rarely 2 too low.\r\n while (compare(yc, rem, yL, remL) < 1) {\r\n n++;\r\n\r\n // Subtract divisor from remainder.\r\n subtract(rem, yL < remL ? yz : yc, remL, base);\r\n remL = rem.length;\r\n }\r\n }\r\n } else if (cmp === 0) {\r\n n++;\r\n rem = [0];\r\n } // else cmp === 1 and n will be 0\r\n\r\n // Add the next digit, n, to the result array.\r\n qc[i++] = n;\r\n\r\n // Update the remainder.\r\n if (rem[0]) {\r\n rem[remL++] = xc[xi] || 0;\r\n } else {\r\n rem = [xc[xi]];\r\n remL = 1;\r\n }\r\n } while ((xi++ < xL || rem[0] != null) && s--);\r\n\r\n more = rem[0] != null;\r\n\r\n // Leading zero?\r\n if (!qc[0]) qc.splice(0, 1);\r\n }\r\n\r\n if (base == BASE) {\r\n\r\n // To calculate q.e, first get the number of digits of qc[0].\r\n for (i = 1, s = qc[0]; s >= 10; s /= 10, i++);\r\n\r\n round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more);\r\n\r\n // Caller is convertBase.\r\n } else {\r\n q.e = e;\r\n q.r = +more;\r\n }\r\n\r\n return q;\r\n };\r\n })();\r\n\r\n\r\n /*\r\n * Return a string representing the value of BigNumber n in fixed-point or exponential\r\n * notation rounded to the specified decimal places or significant digits.\r\n *\r\n * n: a BigNumber.\r\n * i: the index of the last digit required (i.e. the digit that may be rounded up).\r\n * rm: the rounding mode.\r\n * id: 1 (toExponential) or 2 (toPrecision).\r\n */\r\n function format(n, i, rm, id) {\r\n var c0, e, ne, len, str;\r\n\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n\r\n if (!n.c) return n.toString();\r\n\r\n c0 = n.c[0];\r\n ne = n.e;\r\n\r\n if (i == null) {\r\n str = coeffToString(n.c);\r\n str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS)\r\n ? toExponential(str, ne)\r\n : toFixedPoint(str, ne, '0');\r\n } else {\r\n n = round(new BigNumber(n), i, rm);\r\n\r\n // n.e may have changed if the value was rounded up.\r\n e = n.e;\r\n\r\n str = coeffToString(n.c);\r\n len = str.length;\r\n\r\n // toPrecision returns exponential notation if the number of significant digits\r\n // specified is less than the number of digits necessary to represent the integer\r\n // part of the value in fixed-point notation.\r\n\r\n // Exponential notation.\r\n if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) {\r\n\r\n // Append zeros?\r\n for (; len < i; str += '0', len++);\r\n str = toExponential(str, e);\r\n\r\n // Fixed-point notation.\r\n } else {\r\n i -= ne;\r\n str = toFixedPoint(str, e, '0');\r\n\r\n // Append zeros?\r\n if (e + 1 > len) {\r\n if (--i > 0) for (str += '.'; i--; str += '0');\r\n } else {\r\n i += e - len;\r\n if (i > 0) {\r\n if (e + 1 == len) str += '.';\r\n for (; i--; str += '0');\r\n }\r\n }\r\n }\r\n }\r\n\r\n return n.s < 0 && c0 ? '-' + str : str;\r\n }\r\n\r\n\r\n // Handle BigNumber.max and BigNumber.min.\r\n function maxOrMin(args, method) {\r\n var n,\r\n i = 1,\r\n m = new BigNumber(args[0]);\r\n\r\n for (; i < args.length; i++) {\r\n n = new BigNumber(args[i]);\r\n\r\n // If any number is NaN, return NaN.\r\n if (!n.s) {\r\n m = n;\r\n break;\r\n } else if (method.call(m, n)) {\r\n m = n;\r\n }\r\n }\r\n\r\n return m;\r\n }\r\n\r\n\r\n /*\r\n * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP.\r\n * Called by minus, plus and times.\r\n */\r\n function normalise(n, c, e) {\r\n var i = 1,\r\n j = c.length;\r\n\r\n // Remove trailing zeros.\r\n for (; !c[--j]; c.pop());\r\n\r\n // Calculate the base 10 exponent. First get the number of digits of c[0].\r\n for (j = c[0]; j >= 10; j /= 10, i++);\r\n\r\n // Overflow?\r\n if ((e = i + e * LOG_BASE - 1) > MAX_EXP) {\r\n\r\n // Infinity.\r\n n.c = n.e = null;\r\n\r\n // Underflow?\r\n } else if (e < MIN_EXP) {\r\n\r\n // Zero.\r\n n.c = [n.e = 0];\r\n } else {\r\n n.e = e;\r\n n.c = c;\r\n }\r\n\r\n return n;\r\n }\r\n\r\n\r\n // Handle values that fail the validity test in BigNumber.\r\n parseNumeric = (function () {\r\n var basePrefix = /^(-?)0([xbo])(?=\\w[\\w.]*$)/i,\r\n dotAfter = /^([^.]+)\\.$/,\r\n dotBefore = /^\\.([^.]+)$/,\r\n isInfinityOrNaN = /^-?(Infinity|NaN)$/,\r\n whitespaceOrPlus = /^\\s*\\+(?=[\\w.])|^\\s+|\\s+$/g;\r\n\r\n return function (x, str, isNum, b) {\r\n var base,\r\n s = isNum ? str : str.replace(whitespaceOrPlus, '');\r\n\r\n // No exception on ±Infinity or NaN.\r\n if (isInfinityOrNaN.test(s)) {\r\n x.s = isNaN(s) ? null : s < 0 ? -1 : 1;\r\n } else {\r\n if (!isNum) {\r\n\r\n // basePrefix = /^(-?)0([xbo])(?=\\w[\\w.]*$)/i\r\n s = s.replace(basePrefix, function (m, p1, p2) {\r\n base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8;\r\n return !b || b == base ? p1 : m;\r\n });\r\n\r\n if (b) {\r\n base = b;\r\n\r\n // E.g. '1.' to '1', '.1' to '0.1'\r\n s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1');\r\n }\r\n\r\n if (str != s) return new BigNumber(s, base);\r\n }\r\n\r\n // '[BigNumber Error] Not a number: {n}'\r\n // '[BigNumber Error] Not a base {b} number: {n}'\r\n if (BigNumber.DEBUG) {\r\n throw Error\r\n (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str);\r\n }\r\n\r\n // NaN\r\n x.s = null;\r\n }\r\n\r\n x.c = x.e = null;\r\n }\r\n })();\r\n\r\n\r\n /*\r\n * Round x to sd significant digits using rounding mode rm. Check for over/under-flow.\r\n * If r is truthy, it is known that there are more digits after the rounding digit.\r\n */\r\n function round(x, sd, rm, r) {\r\n var d, i, j, k, n, ni, rd,\r\n xc = x.c,\r\n pows10 = POWS_TEN;\r\n\r\n // if x is not Infinity or NaN...\r\n if (xc) {\r\n\r\n // rd is the rounding digit, i.e. the digit after the digit that may be rounded up.\r\n // n is a base 1e14 number, the value of the element of array x.c containing rd.\r\n // ni is the index of n within x.c.\r\n // d is the number of digits of n.\r\n // i is the index of rd within n including leading zeros.\r\n // j is the actual index of rd within n (if < 0, rd is a leading zero).\r\n out: {\r\n\r\n // Get the number of digits of the first element of xc.\r\n for (d = 1, k = xc[0]; k >= 10; k /= 10, d++);\r\n i = sd - d;\r\n\r\n // If the rounding digit is in the first element of xc...\r\n if (i < 0) {\r\n i += LOG_BASE;\r\n j = sd;\r\n n = xc[ni = 0];\r\n\r\n // Get the rounding digit at index j of n.\r\n rd = n / pows10[d - j - 1] % 10 | 0;\r\n } else {\r\n ni = mathceil((i + 1) / LOG_BASE);\r\n\r\n if (ni >= xc.length) {\r\n\r\n if (r) {\r\n\r\n // Needed by sqrt.\r\n for (; xc.length <= ni; xc.push(0));\r\n n = rd = 0;\r\n d = 1;\r\n i %= LOG_BASE;\r\n j = i - LOG_BASE + 1;\r\n } else {\r\n break out;\r\n }\r\n } else {\r\n n = k = xc[ni];\r\n\r\n // Get the number of digits of n.\r\n for (d = 1; k >= 10; k /= 10, d++);\r\n\r\n // Get the index of rd within n.\r\n i %= LOG_BASE;\r\n\r\n // Get the index of rd within n, adjusted for leading zeros.\r\n // The number of leading zeros of n is given by LOG_BASE - d.\r\n j = i - LOG_BASE + d;\r\n\r\n // Get the rounding digit at index j of n.\r\n rd = j < 0 ? 0 : n / pows10[d - j - 1] % 10 | 0;\r\n }\r\n }\r\n\r\n r = r || sd < 0 ||\r\n\r\n // Are there any non-zero digits after the rounding digit?\r\n // The expression n % pows10[d - j - 1] returns all digits of n to the right\r\n // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.\r\n xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]);\r\n\r\n r = rm < 4\r\n ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))\r\n : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 &&\r\n\r\n // Check whether the digit to the left of the rounding digit is odd.\r\n ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 ||\r\n rm == (x.s < 0 ? 8 : 7));\r\n\r\n if (sd < 1 || !xc[0]) {\r\n xc.length = 0;\r\n\r\n if (r) {\r\n\r\n // Convert sd to decimal places.\r\n sd -= x.e + 1;\r\n\r\n // 1, 0.1, 0.01, 0.001, 0.0001 etc.\r\n xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE];\r\n x.e = -sd || 0;\r\n } else {\r\n\r\n // Zero.\r\n xc[0] = x.e = 0;\r\n }\r\n\r\n return x;\r\n }\r\n\r\n // Remove excess digits.\r\n if (i == 0) {\r\n xc.length = ni;\r\n k = 1;\r\n ni--;\r\n } else {\r\n xc.length = ni + 1;\r\n k = pows10[LOG_BASE - i];\r\n\r\n // E.g. 56700 becomes 56000 if 7 is the rounding digit.\r\n // j > 0 means i > number of leading zeros of n.\r\n xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0;\r\n }\r\n\r\n // Round up?\r\n if (r) {\r\n\r\n for (; ;) {\r\n\r\n // If the digit to be rounded up is in the first element of xc...\r\n if (ni == 0) {\r\n\r\n // i will be the length of xc[0] before k is added.\r\n for (i = 1, j = xc[0]; j >= 10; j /= 10, i++);\r\n j = xc[0] += k;\r\n for (k = 1; j >= 10; j /= 10, k++);\r\n\r\n // if i != k the length has increased.\r\n if (i != k) {\r\n x.e++;\r\n if (xc[0] == BASE) xc[0] = 1;\r\n }\r\n\r\n break;\r\n } else {\r\n xc[ni] += k;\r\n if (xc[ni] != BASE) break;\r\n xc[ni--] = 0;\r\n k = 1;\r\n }\r\n }\r\n }\r\n\r\n // Remove trailing zeros.\r\n for (i = xc.length; xc[--i] === 0; xc.pop());\r\n }\r\n\r\n // Overflow? Infinity.\r\n if (x.e > MAX_EXP) {\r\n x.c = x.e = null;\r\n\r\n // Underflow? Zero.\r\n } else if (x.e < MIN_EXP) {\r\n x.c = [x.e = 0];\r\n }\r\n }\r\n\r\n return x;\r\n }\r\n\r\n\r\n function valueOf(n) {\r\n var str,\r\n e = n.e;\r\n\r\n if (e === null) return n.toString();\r\n\r\n str = coeffToString(n.c);\r\n\r\n str = e <= TO_EXP_NEG || e >= TO_EXP_POS\r\n ? toExponential(str, e)\r\n : toFixedPoint(str, e, '0');\r\n\r\n return n.s < 0 ? '-' + str : str;\r\n }\r\n\r\n\r\n // PROTOTYPE/INSTANCE METHODS\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the absolute value of this BigNumber.\r\n */\r\n P.absoluteValue = P.abs = function () {\r\n var x = new BigNumber(this);\r\n if (x.s < 0) x.s = 1;\r\n return x;\r\n };\r\n\r\n\r\n /*\r\n * Return\r\n * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b),\r\n * -1 if the value of this BigNumber is less than the value of BigNumber(y, b),\r\n * 0 if they have the same value,\r\n * or null if the value of either is NaN.\r\n */\r\n P.comparedTo = function (y, b) {\r\n return compare(this, new BigNumber(y, b));\r\n };\r\n\r\n\r\n /*\r\n * If dp is undefined or null or true or false, return the number of decimal places of the\r\n * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN.\r\n *\r\n * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this\r\n * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or\r\n * ROUNDING_MODE if rm is omitted.\r\n *\r\n * [dp] {number} Decimal places: integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n */\r\n P.decimalPlaces = P.dp = function (dp, rm) {\r\n var c, n, v,\r\n x = this;\r\n\r\n if (dp != null) {\r\n intCheck(dp, 0, MAX);\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n\r\n return round(new BigNumber(x), dp + x.e + 1, rm);\r\n }\r\n\r\n if (!(c = x.c)) return null;\r\n n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE;\r\n\r\n // Subtract the number of trailing zeros of the last number.\r\n if (v = c[v]) for (; v % 10 == 0; v /= 10, n--);\r\n if (n < 0) n = 0;\r\n\r\n return n;\r\n };\r\n\r\n\r\n /*\r\n * n / 0 = I\r\n * n / N = N\r\n * n / I = 0\r\n * 0 / n = 0\r\n * 0 / 0 = N\r\n * 0 / N = N\r\n * 0 / I = 0\r\n * N / n = N\r\n * N / 0 = N\r\n * N / N = N\r\n * N / I = N\r\n * I / n = I\r\n * I / 0 = I\r\n * I / N = N\r\n * I / I = N\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber divided by the value of\r\n * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE.\r\n */\r\n P.dividedBy = P.div = function (y, b) {\r\n return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the integer part of dividing the value of this\r\n * BigNumber by the value of BigNumber(y, b).\r\n */\r\n P.dividedToIntegerBy = P.idiv = function (y, b) {\r\n return div(this, new BigNumber(y, b), 0, 1);\r\n };\r\n\r\n\r\n /*\r\n * Return a BigNumber whose value is the value of this BigNumber exponentiated by n.\r\n *\r\n * If m is present, return the result modulo m.\r\n * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE.\r\n * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE.\r\n *\r\n * The modular power operation works efficiently when x, n, and m are integers, otherwise it\r\n * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0.\r\n *\r\n * n {number|string|BigNumber} The exponent. An integer.\r\n * [m] {number|string|BigNumber} The modulus.\r\n *\r\n * '[BigNumber Error] Exponent not an integer: {n}'\r\n */\r\n P.exponentiatedBy = P.pow = function (n, m) {\r\n var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y,\r\n x = this;\r\n\r\n n = new BigNumber(n);\r\n\r\n // Allow NaN and ±Infinity, but not other non-integers.\r\n if (n.c && !n.isInteger()) {\r\n throw Error\r\n (bignumberError + 'Exponent not an integer: ' + valueOf(n));\r\n }\r\n\r\n if (m != null) m = new BigNumber(m);\r\n\r\n // Exponent of MAX_SAFE_INTEGER is 15.\r\n nIsBig = n.e > 14;\r\n\r\n // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0.\r\n if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) {\r\n\r\n // The sign of the result of pow when x is negative depends on the evenness of n.\r\n // If +n overflows to ±Infinity, the evenness of n would be not be known.\r\n y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? 2 - isOdd(n) : +valueOf(n)));\r\n return m ? y.mod(m) : y;\r\n }\r\n\r\n nIsNeg = n.s < 0;\r\n\r\n if (m) {\r\n\r\n // x % m returns NaN if abs(m) is zero, or m is NaN.\r\n if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN);\r\n\r\n isModExp = !nIsNeg && x.isInteger() && m.isInteger();\r\n\r\n if (isModExp) x = x.mod(m);\r\n\r\n // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15.\r\n // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15.\r\n } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0\r\n // [1, 240000000]\r\n ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7\r\n // [80000000000000] [99999750000000]\r\n : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) {\r\n\r\n // If x is negative and n is odd, k = -0, else k = 0.\r\n k = x.s < 0 && isOdd(n) ? -0 : 0;\r\n\r\n // If x >= 1, k = ±Infinity.\r\n if (x.e > -1) k = 1 / k;\r\n\r\n // If n is negative return ±0, else return ±Infinity.\r\n return new BigNumber(nIsNeg ? 1 / k : k);\r\n\r\n } else if (POW_PRECISION) {\r\n\r\n // Truncating each coefficient array to a length of k after each multiplication\r\n // equates to truncating significant digits to POW_PRECISION + [28, 41],\r\n // i.e. there will be a minimum of 28 guard digits retained.\r\n k = mathceil(POW_PRECISION / LOG_BASE + 2);\r\n }\r\n\r\n if (nIsBig) {\r\n half = new BigNumber(0.5);\r\n if (nIsNeg) n.s = 1;\r\n nIsOdd = isOdd(n);\r\n } else {\r\n i = Math.abs(+valueOf(n));\r\n nIsOdd = i % 2;\r\n }\r\n\r\n y = new BigNumber(ONE);\r\n\r\n // Performs 54 loop iterations for n of 9007199254740991.\r\n for (; ;) {\r\n\r\n if (nIsOdd) {\r\n y = y.times(x);\r\n if (!y.c) break;\r\n\r\n if (k) {\r\n if (y.c.length > k) y.c.length = k;\r\n } else if (isModExp) {\r\n y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m));\r\n }\r\n }\r\n\r\n if (i) {\r\n i = mathfloor(i / 2);\r\n if (i === 0) break;\r\n nIsOdd = i % 2;\r\n } else {\r\n n = n.times(half);\r\n round(n, n.e + 1, 1);\r\n\r\n if (n.e > 14) {\r\n nIsOdd = isOdd(n);\r\n } else {\r\n i = +valueOf(n);\r\n if (i === 0) break;\r\n nIsOdd = i % 2;\r\n }\r\n }\r\n\r\n x = x.times(x);\r\n\r\n if (k) {\r\n if (x.c && x.c.length > k) x.c.length = k;\r\n } else if (isModExp) {\r\n x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m));\r\n }\r\n }\r\n\r\n if (isModExp) return y;\r\n if (nIsNeg) y = ONE.div(y);\r\n\r\n return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y;\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer\r\n * using rounding mode rm, or ROUNDING_MODE if rm is omitted.\r\n *\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}'\r\n */\r\n P.integerValue = function (rm) {\r\n var n = new BigNumber(this);\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n return round(n, n.e + 1, rm);\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b),\r\n * otherwise return false.\r\n */\r\n P.isEqualTo = P.eq = function (y, b) {\r\n return compare(this, new BigNumber(y, b)) === 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is a finite number, otherwise return false.\r\n */\r\n P.isFinite = function () {\r\n return !!this.c;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b),\r\n * otherwise return false.\r\n */\r\n P.isGreaterThan = P.gt = function (y, b) {\r\n return compare(this, new BigNumber(y, b)) > 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is greater than or equal to the value of\r\n * BigNumber(y, b), otherwise return false.\r\n */\r\n P.isGreaterThanOrEqualTo = P.gte = function (y, b) {\r\n return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0;\r\n\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is an integer, otherwise return false.\r\n */\r\n P.isInteger = function () {\r\n return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is less than the value of BigNumber(y, b),\r\n * otherwise return false.\r\n */\r\n P.isLessThan = P.lt = function (y, b) {\r\n return compare(this, new BigNumber(y, b)) < 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is less than or equal to the value of\r\n * BigNumber(y, b), otherwise return false.\r\n */\r\n P.isLessThanOrEqualTo = P.lte = function (y, b) {\r\n return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is NaN, otherwise return false.\r\n */\r\n P.isNaN = function () {\r\n return !this.s;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is negative, otherwise return false.\r\n */\r\n P.isNegative = function () {\r\n return this.s < 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is positive, otherwise return false.\r\n */\r\n P.isPositive = function () {\r\n return this.s > 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is 0 or -0, otherwise return false.\r\n */\r\n P.isZero = function () {\r\n return !!this.c && this.c[0] == 0;\r\n };\r\n\r\n\r\n /*\r\n * n - 0 = n\r\n * n - N = N\r\n * n - I = -I\r\n * 0 - n = -n\r\n * 0 - 0 = 0\r\n * 0 - N = N\r\n * 0 - I = -I\r\n * N - n = N\r\n * N - 0 = N\r\n * N - N = N\r\n * N - I = N\r\n * I - n = I\r\n * I - 0 = I\r\n * I - N = N\r\n * I - I = N\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber minus the value of\r\n * BigNumber(y, b).\r\n */\r\n P.minus = function (y, b) {\r\n var i, j, t, xLTy,\r\n x = this,\r\n a = x.s;\r\n\r\n y = new BigNumber(y, b);\r\n b = y.s;\r\n\r\n // Either NaN?\r\n if (!a || !b) return new BigNumber(NaN);\r\n\r\n // Signs differ?\r\n if (a != b) {\r\n y.s = -b;\r\n return x.plus(y);\r\n }\r\n\r\n var xe = x.e / LOG_BASE,\r\n ye = y.e / LOG_BASE,\r\n xc = x.c,\r\n yc = y.c;\r\n\r\n if (!xe || !ye) {\r\n\r\n // Either Infinity?\r\n if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN);\r\n\r\n // Either zero?\r\n if (!xc[0] || !yc[0]) {\r\n\r\n // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.\r\n return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x :\r\n\r\n // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity\r\n ROUNDING_MODE == 3 ? -0 : 0);\r\n }\r\n }\r\n\r\n xe = bitFloor(xe);\r\n ye = bitFloor(ye);\r\n xc = xc.slice();\r\n\r\n // Determine which is the bigger number.\r\n if (a = xe - ye) {\r\n\r\n if (xLTy = a < 0) {\r\n a = -a;\r\n t = xc;\r\n } else {\r\n ye = xe;\r\n t = yc;\r\n }\r\n\r\n t.reverse();\r\n\r\n // Prepend zeros to equalise exponents.\r\n for (b = a; b--; t.push(0));\r\n t.reverse();\r\n } else {\r\n\r\n // Exponents equal. Check digit by digit.\r\n j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b;\r\n\r\n for (a = b = 0; b < j; b++) {\r\n\r\n if (xc[b] != yc[b]) {\r\n xLTy = xc[b] < yc[b];\r\n break;\r\n }\r\n }\r\n }\r\n\r\n // x < y? Point xc to the array of the bigger number.\r\n if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s;\r\n\r\n b = (j = yc.length) - (i = xc.length);\r\n\r\n // Append zeros to xc if shorter.\r\n // No need to add zeros to yc if shorter as subtract only needs to start at yc.length.\r\n if (b > 0) for (; b--; xc[i++] = 0);\r\n b = BASE - 1;\r\n\r\n // Subtract yc from xc.\r\n for (; j > a;) {\r\n\r\n if (xc[--j] < yc[j]) {\r\n for (i = j; i && !xc[--i]; xc[i] = b);\r\n --xc[i];\r\n xc[j] += BASE;\r\n }\r\n\r\n xc[j] -= yc[j];\r\n }\r\n\r\n // Remove leading zeros and adjust exponent accordingly.\r\n for (; xc[0] == 0; xc.splice(0, 1), --ye);\r\n\r\n // Zero?\r\n if (!xc[0]) {\r\n\r\n // Following IEEE 754 (2008) 6.3,\r\n // n - n = +0 but n - n = -0 when rounding towards -Infinity.\r\n y.s = ROUNDING_MODE == 3 ? -1 : 1;\r\n y.c = [y.e = 0];\r\n return y;\r\n }\r\n\r\n // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity\r\n // for finite x and y.\r\n return normalise(y, xc, ye);\r\n };\r\n\r\n\r\n /*\r\n * n % 0 = N\r\n * n % N = N\r\n * n % I = n\r\n * 0 % n = 0\r\n * -0 % n = -0\r\n * 0 % 0 = N\r\n * 0 % N = N\r\n * 0 % I = 0\r\n * N % n = N\r\n * N % 0 = N\r\n * N % N = N\r\n * N % I = N\r\n * I % n = N\r\n * I % 0 = N\r\n * I % N = N\r\n * I % I = N\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber modulo the value of\r\n * BigNumber(y, b). The result depends on the value of MODULO_MODE.\r\n */\r\n P.modulo = P.mod = function (y, b) {\r\n var q, s,\r\n x = this;\r\n\r\n y = new BigNumber(y, b);\r\n\r\n // Return NaN if x is Infinity or NaN, or y is NaN or zero.\r\n if (!x.c || !y.s || y.c && !y.c[0]) {\r\n return new BigNumber(NaN);\r\n\r\n // Return x if y is Infinity or x is zero.\r\n } else if (!y.c || x.c && !x.c[0]) {\r\n return new BigNumber(x);\r\n }\r\n\r\n if (MODULO_MODE == 9) {\r\n\r\n // Euclidian division: q = sign(y) * floor(x / abs(y))\r\n // r = x - qy where 0 <= r < abs(y)\r\n s = y.s;\r\n y.s = 1;\r\n q = div(x, y, 0, 3);\r\n y.s = s;\r\n q.s *= s;\r\n } else {\r\n q = div(x, y, 0, MODULO_MODE);\r\n }\r\n\r\n y = x.minus(q.times(y));\r\n\r\n // To match JavaScript %, ensure sign of zero is sign of dividend.\r\n if (!y.c[0] && MODULO_MODE == 1) y.s = x.s;\r\n\r\n return y;\r\n };\r\n\r\n\r\n /*\r\n * n * 0 = 0\r\n * n * N = N\r\n * n * I = I\r\n * 0 * n = 0\r\n * 0 * 0 = 0\r\n * 0 * N = N\r\n * 0 * I = N\r\n * N * n = N\r\n * N * 0 = N\r\n * N * N = N\r\n * N * I = N\r\n * I * n = I\r\n * I * 0 = N\r\n * I * N = N\r\n * I * I = I\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value\r\n * of BigNumber(y, b).\r\n */\r\n P.multipliedBy = P.times = function (y, b) {\r\n var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc,\r\n base, sqrtBase,\r\n x = this,\r\n xc = x.c,\r\n yc = (y = new BigNumber(y, b)).c;\r\n\r\n // Either NaN, ±Infinity or ±0?\r\n if (!xc || !yc || !xc[0] || !yc[0]) {\r\n\r\n // Return NaN if either is NaN, or one is 0 and the other is Infinity.\r\n if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) {\r\n y.c = y.e = y.s = null;\r\n } else {\r\n y.s *= x.s;\r\n\r\n // Return ±Infinity if either is ±Infinity.\r\n if (!xc || !yc) {\r\n y.c = y.e = null;\r\n\r\n // Return ±0 if either is ±0.\r\n } else {\r\n y.c = [0];\r\n y.e = 0;\r\n }\r\n }\r\n\r\n return y;\r\n }\r\n\r\n e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE);\r\n y.s *= x.s;\r\n xcL = xc.length;\r\n ycL = yc.length;\r\n\r\n // Ensure xc points to longer array and xcL to its length.\r\n if (xcL < ycL) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i;\r\n\r\n // Initialise the result array with zeros.\r\n for (i = xcL + ycL, zc = []; i--; zc.push(0));\r\n\r\n base = BASE;\r\n sqrtBase = SQRT_BASE;\r\n\r\n for (i = ycL; --i >= 0;) {\r\n c = 0;\r\n ylo = yc[i] % sqrtBase;\r\n yhi = yc[i] / sqrtBase | 0;\r\n\r\n for (k = xcL, j = i + k; j > i;) {\r\n xlo = xc[--k] % sqrtBase;\r\n xhi = xc[k] / sqrtBase | 0;\r\n m = yhi * xlo + xhi * ylo;\r\n xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c;\r\n c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi;\r\n zc[j--] = xlo % base;\r\n }\r\n\r\n zc[j] = c;\r\n }\r\n\r\n if (c) {\r\n ++e;\r\n } else {\r\n zc.splice(0, 1);\r\n }\r\n\r\n return normalise(y, zc, e);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the value of this BigNumber negated,\r\n * i.e. multiplied by -1.\r\n */\r\n P.negated = function () {\r\n var x = new BigNumber(this);\r\n x.s = -x.s || null;\r\n return x;\r\n };\r\n\r\n\r\n /*\r\n * n + 0 = n\r\n * n + N = N\r\n * n + I = I\r\n * 0 + n = n\r\n * 0 + 0 = 0\r\n * 0 + N = N\r\n * 0 + I = I\r\n * N + n = N\r\n * N + 0 = N\r\n * N + N = N\r\n * N + I = N\r\n * I + n = I\r\n * I + 0 = I\r\n * I + N = N\r\n * I + I = I\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber plus the value of\r\n * BigNumber(y, b).\r\n */\r\n P.plus = function (y, b) {\r\n var t,\r\n x = this,\r\n a = x.s;\r\n\r\n y = new BigNumber(y, b);\r\n b = y.s;\r\n\r\n // Either NaN?\r\n if (!a || !b) return new BigNumber(NaN);\r\n\r\n // Signs differ?\r\n if (a != b) {\r\n y.s = -b;\r\n return x.minus(y);\r\n }\r\n\r\n var xe = x.e / LOG_BASE,\r\n ye = y.e / LOG_BASE,\r\n xc = x.c,\r\n yc = y.c;\r\n\r\n if (!xe || !ye) {\r\n\r\n // Return ±Infinity if either ±Infinity.\r\n if (!xc || !yc) return new BigNumber(a / 0);\r\n\r\n // Either zero?\r\n // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.\r\n if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0);\r\n }\r\n\r\n xe = bitFloor(xe);\r\n ye = bitFloor(ye);\r\n xc = xc.slice();\r\n\r\n // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts.\r\n if (a = xe - ye) {\r\n if (a > 0) {\r\n ye = xe;\r\n t = yc;\r\n } else {\r\n a = -a;\r\n t = xc;\r\n }\r\n\r\n t.reverse();\r\n for (; a--; t.push(0));\r\n t.reverse();\r\n }\r\n\r\n a = xc.length;\r\n b = yc.length;\r\n\r\n // Point xc to the longer array, and b to the shorter length.\r\n if (a - b < 0) t = yc, yc = xc, xc = t, b = a;\r\n\r\n // Only start adding at yc.length - 1 as the further digits of xc can be ignored.\r\n for (a = 0; b;) {\r\n a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0;\r\n xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE;\r\n }\r\n\r\n if (a) {\r\n xc = [a].concat(xc);\r\n ++ye;\r\n }\r\n\r\n // No need to check for zero, as +x + +y != 0 && -x + -y != 0\r\n // ye = MAX_EXP + 1 possible\r\n return normalise(y, xc, ye);\r\n };\r\n\r\n\r\n /*\r\n * If sd is undefined or null or true or false, return the number of significant digits of\r\n * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN.\r\n * If sd is true include integer-part trailing zeros in the count.\r\n *\r\n * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this\r\n * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or\r\n * ROUNDING_MODE if rm is omitted.\r\n *\r\n * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive.\r\n * boolean: whether to count integer-part trailing zeros: true or false.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}'\r\n */\r\n P.precision = P.sd = function (sd, rm) {\r\n var c, n, v,\r\n x = this;\r\n\r\n if (sd != null && sd !== !!sd) {\r\n intCheck(sd, 1, MAX);\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n\r\n return round(new BigNumber(x), sd, rm);\r\n }\r\n\r\n if (!(c = x.c)) return null;\r\n v = c.length - 1;\r\n n = v * LOG_BASE + 1;\r\n\r\n if (v = c[v]) {\r\n\r\n // Subtract the number of trailing zeros of the last element.\r\n for (; v % 10 == 0; v /= 10, n--);\r\n\r\n // Add the number of digits of the first element.\r\n for (v = c[0]; v >= 10; v /= 10, n++);\r\n }\r\n\r\n if (sd && x.e + 1 > n) n = x.e + 1;\r\n\r\n return n;\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the value of this BigNumber shifted by k places\r\n * (powers of 10). Shift to the right if n > 0, and to the left if n < 0.\r\n *\r\n * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}'\r\n */\r\n P.shiftedBy = function (k) {\r\n intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER);\r\n return this.times('1e' + k);\r\n };\r\n\r\n\r\n /*\r\n * sqrt(-n) = N\r\n * sqrt(N) = N\r\n * sqrt(-I) = N\r\n * sqrt(I) = I\r\n * sqrt(0) = 0\r\n * sqrt(-0) = -0\r\n *\r\n * Return a new BigNumber whose value is the square root of the value of this BigNumber,\r\n * rounded according to DECIMAL_PLACES and ROUNDING_MODE.\r\n */\r\n P.squareRoot = P.sqrt = function () {\r\n var m, n, r, rep, t,\r\n x = this,\r\n c = x.c,\r\n s = x.s,\r\n e = x.e,\r\n dp = DECIMAL_PLACES + 4,\r\n half = new BigNumber('0.5');\r\n\r\n // Negative/NaN/Infinity/zero?\r\n if (s !== 1 || !c || !c[0]) {\r\n return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0);\r\n }\r\n\r\n // Initial estimate.\r\n s = Math.sqrt(+valueOf(x));\r\n\r\n // Math.sqrt underflow/overflow?\r\n // Pass x to Math.sqrt as integer, then adjust the exponent of the result.\r\n if (s == 0 || s == 1 / 0) {\r\n n = coeffToString(c);\r\n if ((n.length + e) % 2 == 0) n += '0';\r\n s = Math.sqrt(+n);\r\n e = bitFloor((e + 1) / 2) - (e < 0 || e % 2);\r\n\r\n if (s == 1 / 0) {\r\n n = '5e' + e;\r\n } else {\r\n n = s.toExponential();\r\n n = n.slice(0, n.indexOf('e') + 1) + e;\r\n }\r\n\r\n r = new BigNumber(n);\r\n } else {\r\n r = new BigNumber(s + '');\r\n }\r\n\r\n // Check for zero.\r\n // r could be zero if MIN_EXP is changed after the this value was created.\r\n // This would cause a division by zero (x/t) and hence Infinity below, which would cause\r\n // coeffToString to throw.\r\n if (r.c[0]) {\r\n e = r.e;\r\n s = e + dp;\r\n if (s < 3) s = 0;\r\n\r\n // Newton-Raphson iteration.\r\n for (; ;) {\r\n t = r;\r\n r = half.times(t.plus(div(x, t, dp, 1)));\r\n\r\n if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) {\r\n\r\n // The exponent of r may here be one less than the final result exponent,\r\n // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits\r\n // are indexed correctly.\r\n if (r.e < e) --s;\r\n n = n.slice(s - 3, s + 1);\r\n\r\n // The 4th rounding digit may be in error by -1 so if the 4 rounding digits\r\n // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the\r\n // iteration.\r\n if (n == '9999' || !rep && n == '4999') {\r\n\r\n // On the first iteration only, check to see if rounding up gives the\r\n // exact result as the nines may infinitely repeat.\r\n if (!rep) {\r\n round(t, t.e + DECIMAL_PLACES + 2, 0);\r\n\r\n if (t.times(t).eq(x)) {\r\n r = t;\r\n break;\r\n }\r\n }\r\n\r\n dp += 4;\r\n s += 4;\r\n rep = 1;\r\n } else {\r\n\r\n // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact\r\n // result. If not, then there are further digits and m will be truthy.\r\n if (!+n || !+n.slice(1) && n.charAt(0) == '5') {\r\n\r\n // Truncate to the first rounding digit.\r\n round(r, r.e + DECIMAL_PLACES + 2, 1);\r\n m = !r.times(r).eq(x);\r\n }\r\n\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n\r\n return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in exponential notation and\r\n * rounded using ROUNDING_MODE to dp fixed decimal places.\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n */\r\n P.toExponential = function (dp, rm) {\r\n if (dp != null) {\r\n intCheck(dp, 0, MAX);\r\n dp++;\r\n }\r\n return format(this, dp, rm, 1);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in fixed-point notation rounding\r\n * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted.\r\n *\r\n * Note: as with JavaScript's number type, (-0).toFixed(0) is '0',\r\n * but e.g. (-0.00001).toFixed(0) is '-0'.\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n */\r\n P.toFixed = function (dp, rm) {\r\n if (dp != null) {\r\n intCheck(dp, 0, MAX);\r\n dp = dp + this.e + 1;\r\n }\r\n return format(this, dp, rm);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in fixed-point notation rounded\r\n * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties\r\n * of the format or FORMAT object (see BigNumber.set).\r\n *\r\n * The formatting object may contain some or all of the properties shown below.\r\n *\r\n * FORMAT = {\r\n * prefix: '',\r\n * groupSize: 3,\r\n * secondaryGroupSize: 0,\r\n * groupSeparator: ',',\r\n * decimalSeparator: '.',\r\n * fractionGroupSize: 0,\r\n * fractionGroupSeparator: '\\xA0', // non-breaking space\r\n * suffix: ''\r\n * };\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n * [format] {object} Formatting options. See FORMAT pbject above.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n * '[BigNumber Error] Argument not an object: {format}'\r\n */\r\n P.toFormat = function (dp, rm, format) {\r\n var str,\r\n x = this;\r\n\r\n if (format == null) {\r\n if (dp != null && rm && typeof rm == 'object') {\r\n format = rm;\r\n rm = null;\r\n } else if (dp && typeof dp == 'object') {\r\n format = dp;\r\n dp = rm = null;\r\n } else {\r\n format = FORMAT;\r\n }\r\n } else if (typeof format != 'object') {\r\n throw Error\r\n (bignumberError + 'Argument not an object: ' + format);\r\n }\r\n\r\n str = x.toFixed(dp, rm);\r\n\r\n if (x.c) {\r\n var i,\r\n arr = str.split('.'),\r\n g1 = +format.groupSize,\r\n g2 = +format.secondaryGroupSize,\r\n groupSeparator = format.groupSeparator || '',\r\n intPart = arr[0],\r\n fractionPart = arr[1],\r\n isNeg = x.s < 0,\r\n intDigits = isNeg ? intPart.slice(1) : intPart,\r\n len = intDigits.length;\r\n\r\n if (g2) i = g1, g1 = g2, g2 = i, len -= i;\r\n\r\n if (g1 > 0 && len > 0) {\r\n i = len % g1 || g1;\r\n intPart = intDigits.substr(0, i);\r\n for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1);\r\n if (g2 > 0) intPart += groupSeparator + intDigits.slice(i);\r\n if (isNeg) intPart = '-' + intPart;\r\n }\r\n\r\n str = fractionPart\r\n ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize)\r\n ? fractionPart.replace(new RegExp('\\\\d{' + g2 + '}\\\\B', 'g'),\r\n '$&' + (format.fractionGroupSeparator || ''))\r\n : fractionPart)\r\n : intPart;\r\n }\r\n\r\n return (format.prefix || '') + str + (format.suffix || '');\r\n };\r\n\r\n\r\n /*\r\n * Return an array of two BigNumbers representing the value of this BigNumber as a simple\r\n * fraction with an integer numerator and an integer denominator.\r\n * The denominator will be a positive non-zero value less than or equal to the specified\r\n * maximum denominator. If a maximum denominator is not specified, the denominator will be\r\n * the lowest value necessary to represent the number exactly.\r\n *\r\n * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator.\r\n *\r\n * '[BigNumber Error] Argument {not an integer|out of range} : {md}'\r\n */\r\n P.toFraction = function (md) {\r\n var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s,\r\n x = this,\r\n xc = x.c;\r\n\r\n if (md != null) {\r\n n = new BigNumber(md);\r\n\r\n // Throw if md is less than one or is not an integer, unless it is Infinity.\r\n if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) {\r\n throw Error\r\n (bignumberError + 'Argument ' +\r\n (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n));\r\n }\r\n }\r\n\r\n if (!xc) return new BigNumber(x);\r\n\r\n d = new BigNumber(ONE);\r\n n1 = d0 = new BigNumber(ONE);\r\n d1 = n0 = new BigNumber(ONE);\r\n s = coeffToString(xc);\r\n\r\n // Determine initial denominator.\r\n // d is a power of 10 and the minimum max denominator that specifies the value exactly.\r\n e = d.e = s.length - x.e - 1;\r\n d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp];\r\n md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n;\r\n\r\n exp = MAX_EXP;\r\n MAX_EXP = 1 / 0;\r\n n = new BigNumber(s);\r\n\r\n // n0 = d1 = 0\r\n n0.c[0] = 0;\r\n\r\n for (; ;) {\r\n q = div(n, d, 0, 1);\r\n d2 = d0.plus(q.times(d1));\r\n if (d2.comparedTo(md) == 1) break;\r\n d0 = d1;\r\n d1 = d2;\r\n n1 = n0.plus(q.times(d2 = n1));\r\n n0 = d2;\r\n d = n.minus(q.times(d2 = d));\r\n n = d2;\r\n }\r\n\r\n d2 = div(md.minus(d0), d1, 0, 1);\r\n n0 = n0.plus(d2.times(n1));\r\n d0 = d0.plus(d2.times(d1));\r\n n0.s = n1.s = x.s;\r\n e = e * 2;\r\n\r\n // Determine which fraction is closer to x, n0/d0 or n1/d1\r\n r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo(\r\n div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0];\r\n\r\n MAX_EXP = exp;\r\n\r\n return r;\r\n };\r\n\r\n\r\n /*\r\n * Return the value of this BigNumber converted to a number primitive.\r\n */\r\n P.toNumber = function () {\r\n return +valueOf(this);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber rounded to sd significant digits\r\n * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits\r\n * necessary to represent the integer part of the value in fixed-point notation, then use\r\n * exponential notation.\r\n *\r\n * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}'\r\n */\r\n P.toPrecision = function (sd, rm) {\r\n if (sd != null) intCheck(sd, 1, MAX);\r\n return format(this, sd, rm, 2);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in base b, or base 10 if b is\r\n * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and\r\n * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent\r\n * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than\r\n * TO_EXP_NEG, return exponential notation.\r\n *\r\n * [b] {number} Integer, 2 to ALPHABET.length inclusive.\r\n *\r\n * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}'\r\n */\r\n P.toString = function (b) {\r\n var str,\r\n n = this,\r\n s = n.s,\r\n e = n.e;\r\n\r\n // Infinity or NaN?\r\n if (e === null) {\r\n if (s) {\r\n str = 'Infinity';\r\n if (s < 0) str = '-' + str;\r\n } else {\r\n str = 'NaN';\r\n }\r\n } else {\r\n if (b == null) {\r\n str = e <= TO_EXP_NEG || e >= TO_EXP_POS\r\n ? toExponential(coeffToString(n.c), e)\r\n : toFixedPoint(coeffToString(n.c), e, '0');\r\n } else if (b === 10) {\r\n n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE);\r\n str = toFixedPoint(coeffToString(n.c), n.e, '0');\r\n } else {\r\n intCheck(b, 2, ALPHABET.length, 'Base');\r\n str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true);\r\n }\r\n\r\n if (s < 0 && n.c[0]) str = '-' + str;\r\n }\r\n\r\n return str;\r\n };\r\n\r\n\r\n /*\r\n * Return as toString, but do not accept a base argument, and include the minus sign for\r\n * negative zero.\r\n */\r\n P.valueOf = P.toJSON = function () {\r\n return valueOf(this);\r\n };\r\n\r\n\r\n P._isBigNumber = true;\r\n\r\n if (configObject != null) BigNumber.set(configObject);\r\n\r\n return BigNumber;\r\n }\r\n\r\n\r\n // PRIVATE HELPER FUNCTIONS\r\n\r\n // These functions don't need access to variables,\r\n // e.g. DECIMAL_PLACES, in the scope of the `clone` function above.\r\n\r\n\r\n function bitFloor(n) {\r\n var i = n | 0;\r\n return n > 0 || n === i ? i : i - 1;\r\n }\r\n\r\n\r\n // Return a coefficient array as a string of base 10 digits.\r\n function coeffToString(a) {\r\n var s, z,\r\n i = 1,\r\n j = a.length,\r\n r = a[0] + '';\r\n\r\n for (; i < j;) {\r\n s = a[i++] + '';\r\n z = LOG_BASE - s.length;\r\n for (; z--; s = '0' + s);\r\n r += s;\r\n }\r\n\r\n // Determine trailing zeros.\r\n for (j = r.length; r.charCodeAt(--j) === 48;);\r\n\r\n return r.slice(0, j + 1 || 1);\r\n }\r\n\r\n\r\n // Compare the value of BigNumbers x and y.\r\n function compare(x, y) {\r\n var a, b,\r\n xc = x.c,\r\n yc = y.c,\r\n i = x.s,\r\n j = y.s,\r\n k = x.e,\r\n l = y.e;\r\n\r\n // Either NaN?\r\n if (!i || !j) return null;\r\n\r\n a = xc && !xc[0];\r\n b = yc && !yc[0];\r\n\r\n // Either zero?\r\n if (a || b) return a ? b ? 0 : -j : i;\r\n\r\n // Signs differ?\r\n if (i != j) return i;\r\n\r\n a = i < 0;\r\n b = k == l;\r\n\r\n // Either Infinity?\r\n if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1;\r\n\r\n // Compare exponents.\r\n if (!b) return k > l ^ a ? 1 : -1;\r\n\r\n j = (k = xc.length) < (l = yc.length) ? k : l;\r\n\r\n // Compare digit by digit.\r\n for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1;\r\n\r\n // Compare lengths.\r\n return k == l ? 0 : k > l ^ a ? 1 : -1;\r\n }\r\n\r\n\r\n /*\r\n * Check that n is a primitive number, an integer, and in range, otherwise throw.\r\n */\r\n function intCheck(n, min, max, name) {\r\n if (n < min || n > max || n !== mathfloor(n)) {\r\n throw Error\r\n (bignumberError + (name || 'Argument') + (typeof n == 'number'\r\n ? n < min || n > max ? ' out of range: ' : ' not an integer: '\r\n : ' not a primitive number: ') + String(n));\r\n }\r\n }\r\n\r\n\r\n // Assumes finite n.\r\n function isOdd(n) {\r\n var k = n.c.length - 1;\r\n return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0;\r\n }\r\n\r\n\r\n function toExponential(str, e) {\r\n return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) +\r\n (e < 0 ? 'e' : 'e+') + e;\r\n }\r\n\r\n\r\n function toFixedPoint(str, e, z) {\r\n var len, zs;\r\n\r\n // Negative exponent?\r\n if (e < 0) {\r\n\r\n // Prepend zeros.\r\n for (zs = z + '.'; ++e; zs += z);\r\n str = zs + str;\r\n\r\n // Positive exponent\r\n } else {\r\n len = str.length;\r\n\r\n // Append zeros.\r\n if (++e > len) {\r\n for (zs = z, e -= len; --e; zs += z);\r\n str += zs;\r\n } else if (e < len) {\r\n str = str.slice(0, e) + '.' + str.slice(e);\r\n }\r\n }\r\n\r\n return str;\r\n }\r\n\r\n\r\n // EXPORT\r\n\r\n\r\n BigNumber = clone();\r\n BigNumber['default'] = BigNumber.BigNumber = BigNumber;\r\n\r\n // AMD.\r\n if (typeof define == 'function' && define.amd) {\r\n define(function () { return BigNumber; });\r\n\r\n // Node.js and other environments that support module.exports.\r\n } else if (typeof module != 'undefined' && module.exports) {\r\n module.exports = BigNumber;\r\n\r\n // Browser.\r\n } else {\r\n if (!globalObject) {\r\n globalObject = typeof self != 'undefined' && self ? self : window;\r\n }\r\n\r\n globalObject.BigNumber = BigNumber;\r\n }\r\n})(this);\r\n","var concatMap = require('concat-map');\nvar balanced = require('balanced-match');\n\nmodule.exports = expandTop;\n\nvar escSlash = '\\0SLASH'+Math.random()+'\\0';\nvar escOpen = '\\0OPEN'+Math.random()+'\\0';\nvar escClose = '\\0CLOSE'+Math.random()+'\\0';\nvar escComma = '\\0COMMA'+Math.random()+'\\0';\nvar escPeriod = '\\0PERIOD'+Math.random()+'\\0';\n\nfunction numeric(str) {\n return parseInt(str, 10) == str\n ? parseInt(str, 10)\n : str.charCodeAt(0);\n}\n\nfunction escapeBraces(str) {\n return str.split('\\\\\\\\').join(escSlash)\n .split('\\\\{').join(escOpen)\n .split('\\\\}').join(escClose)\n .split('\\\\,').join(escComma)\n .split('\\\\.').join(escPeriod);\n}\n\nfunction unescapeBraces(str) {\n return str.split(escSlash).join('\\\\')\n .split(escOpen).join('{')\n .split(escClose).join('}')\n .split(escComma).join(',')\n .split(escPeriod).join('.');\n}\n\n\n// Basically just str.split(\",\"), but handling cases\n// where we have nested braced sections, which should be\n// treated as individual members, like {a,{b,c},d}\nfunction parseCommaParts(str) {\n if (!str)\n return [''];\n\n var parts = [];\n var m = balanced('{', '}', str);\n\n if (!m)\n return str.split(',');\n\n var pre = m.pre;\n var body = m.body;\n var post = m.post;\n var p = pre.split(',');\n\n p[p.length-1] += '{' + body + '}';\n var postParts = parseCommaParts(post);\n if (post.length) {\n p[p.length-1] += postParts.shift();\n p.push.apply(p, postParts);\n }\n\n parts.push.apply(parts, p);\n\n return parts;\n}\n\nfunction expandTop(str) {\n if (!str)\n return [];\n\n // I don't know why Bash 4.3 does this, but it does.\n // Anything starting with {} will have the first two bytes preserved\n // but *only* at the top level, so {},a}b will not expand to anything,\n // but a{},b}c will be expanded to [a}c,abc].\n // One could argue that this is a bug in Bash, but since the goal of\n // this module is to match Bash's rules, we escape a leading {}\n if (str.substr(0, 2) === '{}') {\n str = '\\\\{\\\\}' + str.substr(2);\n }\n\n return expand(escapeBraces(str), true).map(unescapeBraces);\n}\n\nfunction identity(e) {\n return e;\n}\n\nfunction embrace(str) {\n return '{' + str + '}';\n}\nfunction isPadded(el) {\n return /^-?0\\d/.test(el);\n}\n\nfunction lte(i, y) {\n return i <= y;\n}\nfunction gte(i, y) {\n return i >= y;\n}\n\nfunction expand(str, isTop) {\n var expansions = [];\n\n var m = balanced('{', '}', str);\n if (!m || /\\$$/.test(m.pre)) return [str];\n\n var isNumericSequence = /^-?\\d+\\.\\.-?\\d+(?:\\.\\.-?\\d+)?$/.test(m.body);\n var isAlphaSequence = /^[a-zA-Z]\\.\\.[a-zA-Z](?:\\.\\.-?\\d+)?$/.test(m.body);\n var isSequence = isNumericSequence || isAlphaSequence;\n var isOptions = m.body.indexOf(',') >= 0;\n if (!isSequence && !isOptions) {\n // {a},b}\n if (m.post.match(/,.*\\}/)) {\n str = m.pre + '{' + m.body + escClose + m.post;\n return expand(str);\n }\n return [str];\n }\n\n var n;\n if (isSequence) {\n n = m.body.split(/\\.\\./);\n } else {\n n = parseCommaParts(m.body);\n if (n.length === 1) {\n // x{{a,b}}y ==> x{a}y x{b}y\n n = expand(n[0], false).map(embrace);\n if (n.length === 1) {\n var post = m.post.length\n ? expand(m.post, false)\n : [''];\n return post.map(function(p) {\n return m.pre + n[0] + p;\n });\n }\n }\n }\n\n // at this point, n is the parts, and we know it's not a comma set\n // with a single entry.\n\n // no need to expand pre, since it is guaranteed to be free of brace-sets\n var pre = m.pre;\n var post = m.post.length\n ? expand(m.post, false)\n : [''];\n\n var N;\n\n if (isSequence) {\n var x = numeric(n[0]);\n var y = numeric(n[1]);\n var width = Math.max(n[0].length, n[1].length)\n var incr = n.length == 3\n ? Math.abs(numeric(n[2]))\n : 1;\n var test = lte;\n var reverse = y < x;\n if (reverse) {\n incr *= -1;\n test = gte;\n }\n var pad = n.some(isPadded);\n\n N = [];\n\n for (var i = x; test(i, y); i += incr) {\n var c;\n if (isAlphaSequence) {\n c = String.fromCharCode(i);\n if (c === '\\\\')\n c = '';\n } else {\n c = String(i);\n if (pad) {\n var need = width - c.length;\n if (need > 0) {\n var z = new Array(need + 1).join('0');\n if (i < 0)\n c = '-' + z + c.slice(1);\n else\n c = z + c;\n }\n }\n }\n N.push(c);\n }\n } else {\n N = concatMap(n, function(el) { return expand(el, false) });\n }\n\n for (var j = 0; j < N.length; j++) {\n for (var k = 0; k < post.length; k++) {\n var expansion = pre + N[j] + post[k];\n if (!isTop || isSequence || expansion)\n expansions.push(expansion);\n }\n }\n\n return expansions;\n}\n\n","/*jshint node:true */\n'use strict';\nvar Buffer = require('buffer').Buffer; // browserify\nvar SlowBuffer = require('buffer').SlowBuffer;\n\nmodule.exports = bufferEq;\n\nfunction bufferEq(a, b) {\n\n // shortcutting on type is necessary for correctness\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n return false;\n }\n\n // buffer sizes should be well-known information, so despite this\n // shortcutting, it doesn't leak any information about the *contents* of the\n // buffers.\n if (a.length !== b.length) {\n return false;\n }\n\n var c = 0;\n for (var i = 0; i < a.length; i++) {\n /*jshint bitwise:false */\n c |= a[i] ^ b[i]; // XOR\n }\n return c === 0;\n}\n\nbufferEq.install = function() {\n Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) {\n return bufferEq(this, that);\n };\n};\n\nvar origBufEqual = Buffer.prototype.equal;\nvar origSlowBufEqual = SlowBuffer.prototype.equal;\nbufferEq.restore = function() {\n Buffer.prototype.equal = origBufEqual;\n SlowBuffer.prototype.equal = origSlowBufEqual;\n};\n","'use strict';\n\nvar GetIntrinsic = require('get-intrinsic');\n\nvar callBind = require('./');\n\nvar $indexOf = callBind(GetIntrinsic('String.prototype.indexOf'));\n\nmodule.exports = function callBoundIntrinsic(name, allowMissing) {\n\tvar intrinsic = GetIntrinsic(name, !!allowMissing);\n\tif (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {\n\t\treturn callBind(intrinsic);\n\t}\n\treturn intrinsic;\n};\n","'use strict';\n\nvar bind = require('function-bind');\nvar GetIntrinsic = require('get-intrinsic');\n\nvar $apply = GetIntrinsic('%Function.prototype.apply%');\nvar $call = GetIntrinsic('%Function.prototype.call%');\nvar $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply);\n\nvar $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true);\nvar $defineProperty = GetIntrinsic('%Object.defineProperty%', true);\nvar $max = GetIntrinsic('%Math.max%');\n\nif ($defineProperty) {\n\ttry {\n\t\t$defineProperty({}, 'a', { value: 1 });\n\t} catch (e) {\n\t\t// IE 8 has a broken defineProperty\n\t\t$defineProperty = null;\n\t}\n}\n\nmodule.exports = function callBind(originalFunction) {\n\tvar func = $reflectApply(bind, $call, arguments);\n\tif ($gOPD && $defineProperty) {\n\t\tvar desc = $gOPD(func, 'length');\n\t\tif (desc.configurable) {\n\t\t\t// original length, plus the receiver, minus any additional arguments (after the receiver)\n\t\t\t$defineProperty(\n\t\t\t\tfunc,\n\t\t\t\t'length',\n\t\t\t\t{ value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) }\n\t\t\t);\n\t\t}\n\t}\n\treturn func;\n};\n\nvar applyBind = function applyBind() {\n\treturn $reflectApply(bind, $apply, arguments);\n};\n\nif ($defineProperty) {\n\t$defineProperty(module.exports, 'apply', { value: applyBind });\n} else {\n\tmodule.exports.apply = applyBind;\n}\n","module.exports = function (xs, fn) {\n var res = [];\n for (var i = 0; i < xs.length; i++) {\n var x = fn(xs[i], i);\n if (isArray(x)) res.push.apply(res, x);\n else res.push(x);\n }\n return res;\n};\n\nvar isArray = Array.isArray || function (xs) {\n return Object.prototype.toString.call(xs) === '[object Array]';\n};\n","/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug');\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => enableOverride === null ? createDebug.enabled(namespace) : enableOverride,\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tlet i;\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/);\n\t\tconst len = split.length;\n\n\t\tfor (i = 0; i < len; i++) {\n\t\t\tif (!split[i]) {\n\t\t\t\t// ignore empty strings\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tnamespaces = split[i].replace(/\\*/g, '.*?');\n\n\t\t\tif (namespaces[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(new RegExp('^' + namespaces + '$'));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names.map(toNamespace),\n\t\t\t...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tif (name[name.length - 1] === '*') {\n\t\t\treturn true;\n\t\t}\n\n\t\tlet i;\n\t\tlet len;\n\n\t\tfor (i = 0, len = createDebug.skips.length; i < len; i++) {\n\t\t\tif (createDebug.skips[i].test(name)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (i = 0, len = createDebug.names.length; i < len; i++) {\n\t\t\tif (createDebug.names[i].test(name)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Convert regexp to namespace\n\t*\n\t* @param {RegExp} regxep\n\t* @return {String} namespace\n\t* @api private\n\t*/\n\tfunction toNamespace(regexp) {\n\t\treturn regexp.toString()\n\t\t\t.substring(2, regexp.toString().length - 2)\n\t\t\t.replace(/\\.\\*\\?$/, '*');\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n","/**\n * Detect Electron renderer / nwjs process, which is node, but we should\n * treat as a browser.\n */\n\nif (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {\n\tmodule.exports = require('./browser.js');\n} else {\n\tmodule.exports = require('./node.js');\n}\n","/**\n * Module dependencies.\n */\n\nconst tty = require('tty');\nconst util = require('util');\n\n/**\n * This is the Node.js implementation of `debug()`.\n */\n\nexports.init = init;\nexports.log = log;\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.destroy = util.deprecate(\n\t() => {},\n\t'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'\n);\n\n/**\n * Colors.\n */\n\nexports.colors = [6, 2, 3, 4, 5, 1];\n\ntry {\n\t// Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)\n\t// eslint-disable-next-line import/no-extraneous-dependencies\n\tconst supportsColor = require('supports-color');\n\n\tif (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {\n\t\texports.colors = [\n\t\t\t20,\n\t\t\t21,\n\t\t\t26,\n\t\t\t27,\n\t\t\t32,\n\t\t\t33,\n\t\t\t38,\n\t\t\t39,\n\t\t\t40,\n\t\t\t41,\n\t\t\t42,\n\t\t\t43,\n\t\t\t44,\n\t\t\t45,\n\t\t\t56,\n\t\t\t57,\n\t\t\t62,\n\t\t\t63,\n\t\t\t68,\n\t\t\t69,\n\t\t\t74,\n\t\t\t75,\n\t\t\t76,\n\t\t\t77,\n\t\t\t78,\n\t\t\t79,\n\t\t\t80,\n\t\t\t81,\n\t\t\t92,\n\t\t\t93,\n\t\t\t98,\n\t\t\t99,\n\t\t\t112,\n\t\t\t113,\n\t\t\t128,\n\t\t\t129,\n\t\t\t134,\n\t\t\t135,\n\t\t\t148,\n\t\t\t149,\n\t\t\t160,\n\t\t\t161,\n\t\t\t162,\n\t\t\t163,\n\t\t\t164,\n\t\t\t165,\n\t\t\t166,\n\t\t\t167,\n\t\t\t168,\n\t\t\t169,\n\t\t\t170,\n\t\t\t171,\n\t\t\t172,\n\t\t\t173,\n\t\t\t178,\n\t\t\t179,\n\t\t\t184,\n\t\t\t185,\n\t\t\t196,\n\t\t\t197,\n\t\t\t198,\n\t\t\t199,\n\t\t\t200,\n\t\t\t201,\n\t\t\t202,\n\t\t\t203,\n\t\t\t204,\n\t\t\t205,\n\t\t\t206,\n\t\t\t207,\n\t\t\t208,\n\t\t\t209,\n\t\t\t214,\n\t\t\t215,\n\t\t\t220,\n\t\t\t221\n\t\t];\n\t}\n} catch (error) {\n\t// Swallow - we only care if `supports-color` is available; it doesn't have to be.\n}\n\n/**\n * Build up the default `inspectOpts` object from the environment variables.\n *\n * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js\n */\n\nexports.inspectOpts = Object.keys(process.env).filter(key => {\n\treturn /^debug_/i.test(key);\n}).reduce((obj, key) => {\n\t// Camel-case\n\tconst prop = key\n\t\t.substring(6)\n\t\t.toLowerCase()\n\t\t.replace(/_([a-z])/g, (_, k) => {\n\t\t\treturn k.toUpperCase();\n\t\t});\n\n\t// Coerce string value into JS value\n\tlet val = process.env[key];\n\tif (/^(yes|on|true|enabled)$/i.test(val)) {\n\t\tval = true;\n\t} else if (/^(no|off|false|disabled)$/i.test(val)) {\n\t\tval = false;\n\t} else if (val === 'null') {\n\t\tval = null;\n\t} else {\n\t\tval = Number(val);\n\t}\n\n\tobj[prop] = val;\n\treturn obj;\n}, {});\n\n/**\n * Is stdout a TTY? Colored output is enabled when `true`.\n */\n\nfunction useColors() {\n\treturn 'colors' in exports.inspectOpts ?\n\t\tBoolean(exports.inspectOpts.colors) :\n\t\ttty.isatty(process.stderr.fd);\n}\n\n/**\n * Adds ANSI color escape codes if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\tconst {namespace: name, useColors} = this;\n\n\tif (useColors) {\n\t\tconst c = this.color;\n\t\tconst colorCode = '\\u001B[3' + (c < 8 ? c : '8;5;' + c);\n\t\tconst prefix = ` ${colorCode};1m${name} \\u001B[0m`;\n\n\t\targs[0] = prefix + args[0].split('\\n').join('\\n' + prefix);\n\t\targs.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\\u001B[0m');\n\t} else {\n\t\targs[0] = getDate() + name + ' ' + args[0];\n\t}\n}\n\nfunction getDate() {\n\tif (exports.inspectOpts.hideDate) {\n\t\treturn '';\n\t}\n\treturn new Date().toISOString() + ' ';\n}\n\n/**\n * Invokes `util.format()` with the specified arguments and writes to stderr.\n */\n\nfunction log(...args) {\n\treturn process.stderr.write(util.format(...args) + '\\n');\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\tif (namespaces) {\n\t\tprocess.env.DEBUG = namespaces;\n\t} else {\n\t\t// If you set a process.env field to null or undefined, it gets cast to the\n\t\t// string 'null' or 'undefined'. Just delete instead.\n\t\tdelete process.env.DEBUG;\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n\treturn process.env.DEBUG;\n}\n\n/**\n * Init logic for `debug` instances.\n *\n * Create a new `inspectOpts` object in case `useColors` is set\n * differently for a particular `debug` instance.\n */\n\nfunction init(debug) {\n\tdebug.inspectOpts = {};\n\n\tconst keys = Object.keys(exports.inspectOpts);\n\tfor (let i = 0; i < keys.length; i++) {\n\t\tdebug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %o to `util.inspect()`, all on a single line.\n */\n\nformatters.o = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts)\n\t\t.split('\\n')\n\t\t.map(str => str.trim())\n\t\t.join(' ');\n};\n\n/**\n * Map %O to `util.inspect()`, allowing multiple lines if needed.\n */\n\nformatters.O = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts);\n};\n","var util = require('util');\n\nmodule.exports = (util && util.debuglog) || debuglog;\n\nvar debugs = {};\nvar debugEnviron = process.env.NODE_DEBUG || '';\n\nfunction debuglog(set) {\n set = set.toUpperCase();\n if (!debugs[set]) {\n if (new RegExp('\\\\b' + set + '\\\\b', 'i').test(debugEnviron)) {\n var pid = process.pid;\n debugs[set] = function() {\n var msg = util.format.apply(exports, arguments);\n console.error('%s %d: %s', set, pid, msg);\n };\n } else {\n debugs[set] = function() {};\n }\n }\n return debugs[set];\n};\n","'use strict';\n\nvar keys = require('object-keys');\nvar hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol';\n\nvar toStr = Object.prototype.toString;\nvar concat = Array.prototype.concat;\nvar origDefineProperty = Object.defineProperty;\n\nvar isFunction = function (fn) {\n\treturn typeof fn === 'function' && toStr.call(fn) === '[object Function]';\n};\n\nvar arePropertyDescriptorsSupported = function () {\n\tvar obj = {};\n\ttry {\n\t\torigDefineProperty(obj, 'x', { enumerable: false, value: obj });\n\t\t// eslint-disable-next-line no-unused-vars, no-restricted-syntax\n\t\tfor (var _ in obj) { // jscs:ignore disallowUnusedVariables\n\t\t\treturn false;\n\t\t}\n\t\treturn obj.x === obj;\n\t} catch (e) { /* this is IE 8. */\n\t\treturn false;\n\t}\n};\nvar supportsDescriptors = origDefineProperty && arePropertyDescriptorsSupported();\n\nvar defineProperty = function (object, name, value, predicate) {\n\tif (name in object && (!isFunction(predicate) || !predicate())) {\n\t\treturn;\n\t}\n\tif (supportsDescriptors) {\n\t\torigDefineProperty(object, name, {\n\t\t\tconfigurable: true,\n\t\t\tenumerable: false,\n\t\t\tvalue: value,\n\t\t\twritable: true\n\t\t});\n\t} else {\n\t\tobject[name] = value;\n\t}\n};\n\nvar defineProperties = function (object, map) {\n\tvar predicates = arguments.length > 2 ? arguments[2] : {};\n\tvar props = keys(map);\n\tif (hasSymbols) {\n\t\tprops = concat.call(props, Object.getOwnPropertySymbols(map));\n\t}\n\tfor (var i = 0; i < props.length; i += 1) {\n\t\tdefineProperty(object, props[i], map[props[i]], predicates[props[i]]);\n\t}\n};\n\ndefineProperties.supportsDescriptors = !!supportsDescriptors;\n\nmodule.exports = defineProperties;\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nclass Deprecation extends Error {\n constructor(message) {\n super(message); // Maintains proper stack trace (only available on V8)\n\n /* istanbul ignore next */\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n\n this.name = 'Deprecation';\n }\n\n}\n\nexports.Deprecation = Deprecation;\n","var wrappy = require('wrappy')\nmodule.exports = wrappy(dezalgo)\n\nvar asap = require('asap')\n\nfunction dezalgo (cb) {\n var sync = true\n asap(function () {\n sync = false\n })\n\n return function zalgoSafe() {\n var args = arguments\n var me = this\n if (sync)\n asap(function() {\n cb.apply(me, args)\n })\n else\n cb.apply(me, args)\n }\n}\n","'use strict';\n\nvar Buffer = require('safe-buffer').Buffer;\n\nvar getParamBytesForAlg = require('./param-bytes-for-alg');\n\nvar MAX_OCTET = 0x80,\n\tCLASS_UNIVERSAL = 0,\n\tPRIMITIVE_BIT = 0x20,\n\tTAG_SEQ = 0x10,\n\tTAG_INT = 0x02,\n\tENCODED_TAG_SEQ = (TAG_SEQ | PRIMITIVE_BIT) | (CLASS_UNIVERSAL << 6),\n\tENCODED_TAG_INT = TAG_INT | (CLASS_UNIVERSAL << 6);\n\nfunction base64Url(base64) {\n\treturn base64\n\t\t.replace(/=/g, '')\n\t\t.replace(/\\+/g, '-')\n\t\t.replace(/\\//g, '_');\n}\n\nfunction signatureAsBuffer(signature) {\n\tif (Buffer.isBuffer(signature)) {\n\t\treturn signature;\n\t} else if ('string' === typeof signature) {\n\t\treturn Buffer.from(signature, 'base64');\n\t}\n\n\tthrow new TypeError('ECDSA signature must be a Base64 string or a Buffer');\n}\n\nfunction derToJose(signature, alg) {\n\tsignature = signatureAsBuffer(signature);\n\tvar paramBytes = getParamBytesForAlg(alg);\n\n\t// the DER encoded param should at most be the param size, plus a padding\n\t// zero, since due to being a signed integer\n\tvar maxEncodedParamLength = paramBytes + 1;\n\n\tvar inputLength = signature.length;\n\n\tvar offset = 0;\n\tif (signature[offset++] !== ENCODED_TAG_SEQ) {\n\t\tthrow new Error('Could not find expected \"seq\"');\n\t}\n\n\tvar seqLength = signature[offset++];\n\tif (seqLength === (MAX_OCTET | 1)) {\n\t\tseqLength = signature[offset++];\n\t}\n\n\tif (inputLength - offset < seqLength) {\n\t\tthrow new Error('\"seq\" specified length of \"' + seqLength + '\", only \"' + (inputLength - offset) + '\" remaining');\n\t}\n\n\tif (signature[offset++] !== ENCODED_TAG_INT) {\n\t\tthrow new Error('Could not find expected \"int\" for \"r\"');\n\t}\n\n\tvar rLength = signature[offset++];\n\n\tif (inputLength - offset - 2 < rLength) {\n\t\tthrow new Error('\"r\" specified length of \"' + rLength + '\", only \"' + (inputLength - offset - 2) + '\" available');\n\t}\n\n\tif (maxEncodedParamLength < rLength) {\n\t\tthrow new Error('\"r\" specified length of \"' + rLength + '\", max of \"' + maxEncodedParamLength + '\" is acceptable');\n\t}\n\n\tvar rOffset = offset;\n\toffset += rLength;\n\n\tif (signature[offset++] !== ENCODED_TAG_INT) {\n\t\tthrow new Error('Could not find expected \"int\" for \"s\"');\n\t}\n\n\tvar sLength = signature[offset++];\n\n\tif (inputLength - offset !== sLength) {\n\t\tthrow new Error('\"s\" specified length of \"' + sLength + '\", expected \"' + (inputLength - offset) + '\"');\n\t}\n\n\tif (maxEncodedParamLength < sLength) {\n\t\tthrow new Error('\"s\" specified length of \"' + sLength + '\", max of \"' + maxEncodedParamLength + '\" is acceptable');\n\t}\n\n\tvar sOffset = offset;\n\toffset += sLength;\n\n\tif (offset !== inputLength) {\n\t\tthrow new Error('Expected to consume entire buffer, but \"' + (inputLength - offset) + '\" bytes remain');\n\t}\n\n\tvar rPadding = paramBytes - rLength,\n\t\tsPadding = paramBytes - sLength;\n\n\tvar dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength);\n\n\tfor (offset = 0; offset < rPadding; ++offset) {\n\t\tdst[offset] = 0;\n\t}\n\tsignature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength);\n\n\toffset = paramBytes;\n\n\tfor (var o = offset; offset < o + sPadding; ++offset) {\n\t\tdst[offset] = 0;\n\t}\n\tsignature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength);\n\n\tdst = dst.toString('base64');\n\tdst = base64Url(dst);\n\n\treturn dst;\n}\n\nfunction countPadding(buf, start, stop) {\n\tvar padding = 0;\n\twhile (start + padding < stop && buf[start + padding] === 0) {\n\t\t++padding;\n\t}\n\n\tvar needsSign = buf[start + padding] >= MAX_OCTET;\n\tif (needsSign) {\n\t\t--padding;\n\t}\n\n\treturn padding;\n}\n\nfunction joseToDer(signature, alg) {\n\tsignature = signatureAsBuffer(signature);\n\tvar paramBytes = getParamBytesForAlg(alg);\n\n\tvar signatureBytes = signature.length;\n\tif (signatureBytes !== paramBytes * 2) {\n\t\tthrow new TypeError('\"' + alg + '\" signatures must be \"' + paramBytes * 2 + '\" bytes, saw \"' + signatureBytes + '\"');\n\t}\n\n\tvar rPadding = countPadding(signature, 0, paramBytes);\n\tvar sPadding = countPadding(signature, paramBytes, signature.length);\n\tvar rLength = paramBytes - rPadding;\n\tvar sLength = paramBytes - sPadding;\n\n\tvar rsBytes = 1 + 1 + rLength + 1 + 1 + sLength;\n\n\tvar shortLength = rsBytes < MAX_OCTET;\n\n\tvar dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes);\n\n\tvar offset = 0;\n\tdst[offset++] = ENCODED_TAG_SEQ;\n\tif (shortLength) {\n\t\t// Bit 8 has value \"0\"\n\t\t// bits 7-1 give the length.\n\t\tdst[offset++] = rsBytes;\n\t} else {\n\t\t// Bit 8 of first octet has value \"1\"\n\t\t// bits 7-1 give the number of additional length octets.\n\t\tdst[offset++] = MAX_OCTET\t| 1;\n\t\t// length, base 256\n\t\tdst[offset++] = rsBytes & 0xff;\n\t}\n\tdst[offset++] = ENCODED_TAG_INT;\n\tdst[offset++] = rLength;\n\tif (rPadding < 0) {\n\t\tdst[offset++] = 0;\n\t\toffset += signature.copy(dst, offset, 0, paramBytes);\n\t} else {\n\t\toffset += signature.copy(dst, offset, rPadding, paramBytes);\n\t}\n\tdst[offset++] = ENCODED_TAG_INT;\n\tdst[offset++] = sLength;\n\tif (sPadding < 0) {\n\t\tdst[offset++] = 0;\n\t\tsignature.copy(dst, offset, paramBytes);\n\t} else {\n\t\tsignature.copy(dst, offset, paramBytes + sPadding);\n\t}\n\n\treturn dst;\n}\n\nmodule.exports = {\n\tderToJose: derToJose,\n\tjoseToDer: joseToDer\n};\n","'use strict';\n\nfunction getParamSize(keySize) {\n\tvar result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1);\n\treturn result;\n}\n\nvar paramBytesForAlg = {\n\tES256: getParamSize(256),\n\tES384: getParamSize(384),\n\tES512: getParamSize(521)\n};\n\nfunction getParamBytesForAlg(alg) {\n\tvar paramBytes = paramBytesForAlg[alg];\n\tif (paramBytes) {\n\t\treturn paramBytes;\n\t}\n\n\tthrow new Error('Unknown algorithm \"' + alg + '\"');\n}\n\nmodule.exports = getParamBytesForAlg;\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nfunction _extends() {\n _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n };\n\n return _extends.apply(this, arguments);\n}\n\nfunction _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n subClass.__proto__ = superClass;\n}\n\nfunction _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n}\n\nfunction _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n\n return _setPrototypeOf(o, p);\n}\n\nfunction _isNativeReflectConstruct() {\n if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n if (Reflect.construct.sham) return false;\n if (typeof Proxy === \"function\") return true;\n\n try {\n Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));\n return true;\n } catch (e) {\n return false;\n }\n}\n\nfunction _construct(Parent, args, Class) {\n if (_isNativeReflectConstruct()) {\n _construct = Reflect.construct;\n } else {\n _construct = function _construct(Parent, args, Class) {\n var a = [null];\n a.push.apply(a, args);\n var Constructor = Function.bind.apply(Parent, a);\n var instance = new Constructor();\n if (Class) _setPrototypeOf(instance, Class.prototype);\n return instance;\n };\n }\n\n return _construct.apply(null, arguments);\n}\n\nfunction _isNativeFunction(fn) {\n return Function.toString.call(fn).indexOf(\"[native code]\") !== -1;\n}\n\nfunction _wrapNativeSuper(Class) {\n var _cache = typeof Map === \"function\" ? new Map() : undefined;\n\n _wrapNativeSuper = function _wrapNativeSuper(Class) {\n if (Class === null || !_isNativeFunction(Class)) return Class;\n\n if (typeof Class !== \"function\") {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n\n if (typeof _cache !== \"undefined\") {\n if (_cache.has(Class)) return _cache.get(Class);\n\n _cache.set(Class, Wrapper);\n }\n\n function Wrapper() {\n return _construct(Class, arguments, _getPrototypeOf(this).constructor);\n }\n\n Wrapper.prototype = Object.create(Class.prototype, {\n constructor: {\n value: Wrapper,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n return _setPrototypeOf(Wrapper, Class);\n };\n\n return _wrapNativeSuper(Class);\n}\n\nfunction _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n}\n\n// Surprisingly involved error subclassing\n// See https://stackoverflow.com/questions/41102060/typescript-extending-error-class\nvar EnvError = /*#__PURE__*/function (_TypeError) {\n _inheritsLoose(EnvError, _TypeError);\n\n function EnvError(message) {\n var _this;\n\n _this = _TypeError.call(this, message) || this;\n Object.setPrototypeOf(_assertThisInitialized(_this), (this instanceof EnvError ? this.constructor : void 0).prototype);\n Error.captureStackTrace(_assertThisInitialized(_this), EnvError);\n _this.name = _this.constructor.name;\n return _this;\n }\n\n return EnvError;\n}( /*#__PURE__*/_wrapNativeSuper(TypeError));\nvar EnvMissingError = /*#__PURE__*/function (_ReferenceError) {\n _inheritsLoose(EnvMissingError, _ReferenceError);\n\n function EnvMissingError(message) {\n var _this2;\n\n _this2 = _ReferenceError.call(this, message) || this;\n Object.setPrototypeOf(_assertThisInitialized(_this2), (this instanceof EnvMissingError ? this.constructor : void 0).prototype);\n Error.captureStackTrace(_assertThisInitialized(_this2), EnvMissingError);\n _this2.name = _this2.constructor.name;\n return _this2;\n }\n\n return EnvMissingError;\n}( /*#__PURE__*/_wrapNativeSuper(ReferenceError));\n\nvar _process, _process$versions;\n\nvar isNode = !!(typeof process === 'object' && ((_process = process) == null ? void 0 : (_process$versions = _process.versions) == null ? void 0 : _process$versions.node));\n\nvar colorWith = function colorWith(colorCode) {\n return function (str) {\n return isNode ? \"\\x1B[\" + colorCode + \"m\" + str + \"\\x1B[0m\" : str;\n };\n};\n\nvar colors = {\n blue: /*#__PURE__*/colorWith('34'),\n white: /*#__PURE__*/colorWith('37'),\n yellow: /*#__PURE__*/colorWith('33')\n};\nvar RULE = /*#__PURE__*/colors.white('================================');\n\nvar defaultReporter = function defaultReporter(_ref) {\n var _ref$errors = _ref.errors,\n errors = _ref$errors === void 0 ? {} : _ref$errors;\n if (!Object.keys(errors).length) return;\n var missingVarsOutput = [];\n var invalidVarsOutput = [];\n\n for (var _i = 0, _Object$entries = Object.entries(errors); _i < _Object$entries.length; _i++) {\n var _Object$entries$_i = _Object$entries[_i],\n k = _Object$entries$_i[0],\n err = _Object$entries$_i[1];\n\n if (err instanceof EnvMissingError) {\n missingVarsOutput.push(\" \" + colors.blue(k) + \": \" + (err.message || '(required)'));\n } else invalidVarsOutput.push(\" \" + colors.blue(k) + \": \" + ((err == null ? void 0 : err.message) || '(invalid format)'));\n } // Prepend \"header\" output for each section of the output:\n\n\n if (invalidVarsOutput.length) {\n invalidVarsOutput.unshift(\" \" + colors.yellow('Invalid') + \" environment variables:\");\n }\n\n if (missingVarsOutput.length) {\n missingVarsOutput.unshift(\" \" + colors.yellow('Missing') + \" environment variables:\");\n }\n\n var output = [RULE, invalidVarsOutput.sort().join('\\n'), missingVarsOutput.sort().join('\\n'), colors.yellow('\\n Exiting with error code 1'), RULE].filter(function (x) {\n return !!x;\n }).join('\\n');\n console.error(output);\n\n if (isNode) {\n process.exit(1);\n } else {\n throw new TypeError('Environment validation failed');\n }\n};\n\nvar testOnlySymbol = /*#__PURE__*/Symbol('envalid - test only');\n/**\r\n * Validate a single env var, given a spec object\r\n *\r\n * @throws EnvError - If validation is unsuccessful\r\n * @return - The cleaned value\r\n */\n\nfunction validateVar(_ref) {\n var spec = _ref.spec,\n name = _ref.name,\n rawValue = _ref.rawValue;\n\n if (typeof spec._parse !== 'function') {\n throw new EnvError(\"Invalid spec for \\\"\" + name + \"\\\"\");\n }\n\n var value = spec._parse(rawValue);\n\n if (spec.choices) {\n if (!Array.isArray(spec.choices)) {\n throw new TypeError(\"\\\"choices\\\" must be an array (in spec for \\\"\" + name + \"\\\")\");\n } else if (!spec.choices.includes(value)) {\n throw new EnvError(\"Value \\\"\" + value + \"\\\" not in choices [\" + spec.choices + \"]\");\n }\n }\n\n if (value == null) throw new EnvError(\"Invalid value for env var \\\"\" + name + \"\\\"\");\n return value;\n} // Format a string error message for when a required env var is missing\n\n\nfunction formatSpecDescription(spec) {\n var egText = spec.example ? \" (eg. \\\"\" + spec.example + \"\\\")\" : '';\n var docsText = spec.docs ? \". See \" + spec.docs : '';\n return \"\" + spec.desc + egText + docsText;\n}\n\nvar readRawEnvValue = function readRawEnvValue(env, k) {\n return env[k];\n};\n\nvar isTestOnlySymbol = function isTestOnlySymbol(value) {\n return value === testOnlySymbol;\n};\n/**\r\n * Perform the central validation/sanitization logic on the full environment object\r\n */\n\n\nfunction getSanitizedEnv(environment, specs, options) {\n var _options2;\n\n if (options === void 0) {\n options = {};\n }\n\n var cleanedEnv = {};\n var errors = {};\n var varKeys = Object.keys(specs);\n var rawNodeEnv = readRawEnvValue(environment, 'NODE_ENV');\n\n for (var _i = 0, _varKeys = varKeys; _i < _varKeys.length; _i++) {\n var _readRawEnvValue;\n\n var k = _varKeys[_i];\n var spec = specs[k]; // Use devDefault values only if NODE_ENV was explicitly set, and isn't 'production'\n\n var usingDevDefault = rawNodeEnv && rawNodeEnv !== 'production' && spec.hasOwnProperty('devDefault');\n var devDefaultValue = usingDevDefault ? spec.devDefault : undefined;\n var rawValue = (_readRawEnvValue = readRawEnvValue(environment, k)) != null ? _readRawEnvValue : devDefaultValue === undefined ? spec[\"default\"] : devDefaultValue; // Default values can be anything falsy (including an explicitly set undefined), without\n // triggering validation errors:\n\n var usingFalsyDefault = spec.hasOwnProperty('default') && spec[\"default\"] === rawValue || usingDevDefault && devDefaultValue === rawValue;\n\n try {\n if (isTestOnlySymbol(rawValue)) {\n throw new EnvMissingError(formatSpecDescription(spec));\n }\n\n if (rawValue === undefined) {\n if (!usingFalsyDefault) {\n throw new EnvMissingError(formatSpecDescription(spec));\n }\n } else {\n cleanedEnv[k] = validateVar({\n name: k,\n spec: spec,\n rawValue: rawValue\n });\n }\n } catch (err) {\n var _options;\n\n if (((_options = options) == null ? void 0 : _options.reporter) === null) throw err;\n errors[k] = err;\n }\n }\n\n var reporter = ((_options2 = options) == null ? void 0 : _options2.reporter) || defaultReporter;\n reporter({\n errors: errors,\n env: cleanedEnv\n });\n return cleanedEnv;\n}\n\nvar strictProxyMiddleware = function strictProxyMiddleware(envObj, rawEnv) {\n var inspectables = ['length', 'inspect', 'hasOwnProperty', Symbol.toStringTag, Symbol.iterator, // For jest\n 'asymmetricMatch', 'nodeType', // For libs that use `then` checks to see if objects are Promises (see #74):\n 'then', // For usage with TypeScript esModuleInterop flag\n '__esModule'];\n var inspectSymbolStrings = ['Symbol(util.inspect.custom)', 'Symbol(nodejs.util.inspect.custom)'];\n return new Proxy(envObj, {\n get: function get(target, name) {\n // These checks are needed because calling console.log on a\n // proxy that throws crashes the entire process. This permits access on\n // the necessary properties for `console.log(envObj)`, `envObj.length`,\n // `envObj.hasOwnProperty('string')` to work.\n if (inspectables.includes(name) || inspectSymbolStrings.includes(name.toString())) {\n // @ts-expect-error TS doesn't like symbol types as indexers\n return target[name];\n }\n\n var varExists = target.hasOwnProperty(name);\n\n if (!varExists) {\n if (typeof rawEnv === 'object' && (rawEnv == null ? void 0 : rawEnv.hasOwnProperty == null ? void 0 : rawEnv.hasOwnProperty(name))) {\n throw new ReferenceError(\"[envalid] Env var \" + name + \" was accessed but not validated. This var is set in the environment; please add an envalid validator for it.\");\n }\n\n throw new ReferenceError(\"[envalid] Env var not found: \" + name);\n }\n\n return target[name];\n },\n set: function set(_target, name) {\n throw new TypeError(\"[envalid] Attempt to mutate environment value: \" + name);\n }\n });\n};\nvar accessorMiddleware = function accessorMiddleware(envObj, rawEnv) {\n // Attach is{Prod/Dev/Test} properties for more readable NODE_ENV checks\n // Note that isDev and isProd are just aliases to isDevelopment and isProduction\n // @ts-ignore attempt to read NODE_ENV even if it's not in the spec\n var computedNodeEnv = envObj.NODE_ENV || rawEnv.NODE_ENV; // If NODE_ENV is not set, assume production\n\n var isProd = !computedNodeEnv || computedNodeEnv === 'production';\n Object.defineProperties(envObj, {\n isDevelopment: {\n value: computedNodeEnv === 'development'\n },\n isDev: {\n value: computedNodeEnv === 'development'\n },\n isProduction: {\n value: isProd\n },\n isProd: {\n value: isProd\n },\n isTest: {\n value: computedNodeEnv === 'test'\n }\n });\n return envObj;\n};\nvar applyDefaultMiddleware = function applyDefaultMiddleware(cleanedEnv, rawEnv) {\n // Note: Ideally we would declare the default middlewares in an array and apply them in series with\n // a generic pipe() function. However, a generically typed variadic pipe() appears to not be possible\n // in TypeScript as of 4.x, so we just manually apply them below. See\n // https://github.com/microsoft/TypeScript/pull/39094#issuecomment-647042984\n return strictProxyMiddleware(accessorMiddleware(cleanedEnv, rawEnv), rawEnv);\n};\n\n/**\r\n * Returns a sanitized, immutable environment object. _Only_ the env vars\r\n * specified in the `validators` parameter will be accessible on the returned\r\n * object.\r\n * @param environment An object containing your env vars (eg. process.env).\r\n * @param specs An object that specifies the format of required vars.\r\n * @param options An object that specifies options for cleanEnv.\r\n */\n\nfunction cleanEnv(environment, specs, options) {\n if (options === void 0) {\n options = {};\n }\n\n var cleaned = getSanitizedEnv(environment, specs, options);\n return Object.freeze(applyDefaultMiddleware(cleaned, environment));\n}\n/**\r\n * Returns a sanitized, immutable environment object, and passes it through a custom\r\n * applyMiddleware function before being frozen. Most users won't need the flexibility of custom\r\n * middleware; prefer cleanEnv() unless you're sure you need it\r\n *\r\n * @param environment An object containing your env vars (eg. process.env).\r\n * @param specs An object that specifies the format of required vars.\r\n * @param applyMiddleware A function that applies transformations to the cleaned env object\r\n * @param options An object that specifies options for cleanEnv.\r\n */\n\nfunction customCleanEnv(environment, specs, applyMiddleware, options) {\n if (options === void 0) {\n options = {};\n }\n\n var cleaned = getSanitizedEnv(environment, specs, options);\n return Object.freeze(applyMiddleware(cleaned, environment));\n}\n/**\r\n * Utility function for providing default values only when NODE_ENV=test\r\n *\r\n * For more context, see https://github.com/af/envalid/issues/32\r\n */\n\nvar testOnly = function testOnly(defaultValueForTests) {\n return testOnlySymbol; // T is not strictly correct, but prevents type errors during usage\n};\n\nvar isFQDN = function isFQDN(input) {\n if (!input.length) return false;\n var parts = input.split('.');\n\n for (var part, i = 0; i < parts.length; i++) {\n part = parts[i];\n if (!/^[a-z\\u00a1-\\uffff0-9-]+$/i.test(part)) return false;\n if (/[\\uff01-\\uff5e]/.test(part)) return false; // disallow full-width chars\n\n if (part[0] === '-' || part[part.length - 1] === '-') return false;\n }\n\n return true;\n}; // \"best effort\" regex-based IP address check\n// If you want a more exhaustive check, create your own custom validator, perhaps wrapping this\n// implementation (the source of the ipv4 regex below): https://github.com/validatorjs/validator.js/blob/master/src/lib/isIP.js\n\n\nvar ipv4Regex = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/;\nvar ipv6Regex = /([a-f0-9]+:+)+[a-f0-9]+/;\n\nvar isIP = function isIP(input) {\n if (!input.length) return false;\n return ipv4Regex.test(input) || ipv6Regex.test(input);\n};\n\nvar EMAIL_REGEX = /^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$/; // intentionally non-exhaustive\n\nvar makeValidator = function makeValidator(parseFn) {\n return function (spec) {\n return _extends({}, spec, {\n _parse: parseFn\n });\n };\n}; // The reason for the function wrapper is to enable the type parameter\n// that enables better type inference. For more context, check out the following PR:\n// https://github.com/af/envalid/pull/118\n\nfunction bool(spec) {\n return makeValidator(function (input) {\n switch (input) {\n case true:\n case 'true':\n case 't':\n case '1':\n return true;\n\n case false:\n case 'false':\n case 'f':\n case '0':\n return false;\n\n default:\n throw new EnvError(\"Invalid bool input: \\\"\" + input + \"\\\"\");\n }\n })(spec);\n}\nfunction num(spec) {\n return makeValidator(function (input) {\n var coerced = +input;\n if (Number.isNaN(coerced)) throw new EnvError(\"Invalid number input: \\\"\" + input + \"\\\"\");\n return coerced;\n })(spec);\n}\nfunction str(spec) {\n return makeValidator(function (input) {\n if (typeof input === 'string') return input;\n throw new EnvError(\"Not a string: \\\"\" + input + \"\\\"\");\n })(spec);\n}\nfunction email(spec) {\n return makeValidator(function (x) {\n if (EMAIL_REGEX.test(x)) return x;\n throw new EnvError(\"Invalid email address: \\\"\" + x + \"\\\"\");\n })(spec);\n}\nfunction host(spec) {\n return makeValidator(function (input) {\n if (!isFQDN(input) && !isIP(input)) {\n throw new EnvError(\"Invalid host (domain or ip): \\\"\" + input + \"\\\"\");\n }\n\n return input;\n })(spec);\n}\nfunction port(spec) {\n return makeValidator(function (input) {\n var coerced = +input;\n\n if (Number.isNaN(coerced) || \"\" + coerced !== \"\" + input || coerced % 1 !== 0 || coerced < 1 || coerced > 65535) {\n throw new EnvError(\"Invalid port input: \\\"\" + input + \"\\\"\");\n }\n\n return coerced;\n })(spec);\n}\nfunction url(spec) {\n return makeValidator(function (x) {\n try {\n new URL(x);\n return x;\n } catch (e) {\n throw new EnvError(\"Invalid url: \\\"\" + x + \"\\\"\");\n }\n })(spec);\n} // It's recommended that you provide an explicit type parameter for json validation\n// if you're using TypeScript. Otherwise the output will be typed as `any`. For example:\n//\n// cleanEnv({\n// MY_VAR: json<{ foo: number }>({ default: { foo: 123 } }),\n// })\n\nfunction json(spec) {\n return makeValidator(function (x) {\n try {\n return JSON.parse(x);\n } catch (e) {\n throw new EnvError(\"Invalid json: \\\"\" + x + \"\\\"\");\n }\n })(spec);\n}\n\nexports.EnvError = EnvError;\nexports.EnvMissingError = EnvMissingError;\nexports.accessorMiddleware = accessorMiddleware;\nexports.applyDefaultMiddleware = applyDefaultMiddleware;\nexports.bool = bool;\nexports.cleanEnv = cleanEnv;\nexports.customCleanEnv = customCleanEnv;\nexports.email = email;\nexports.host = host;\nexports.json = json;\nexports.makeValidator = makeValidator;\nexports.num = num;\nexports.port = port;\nexports.str = str;\nexports.strictProxyMiddleware = strictProxyMiddleware;\nexports.testOnly = testOnly;\nexports.url = url;\n//# sourceMappingURL=envalid.cjs.development.js.map\n","\"use strict\";function e(){return(e=Object.assign||function(e){for(var t=1;t65535)throw new f('Invalid port input: \"'+e+'\"');return t}))(e)},exports.str=function(e){return S((function(e){if(\"string\"==typeof e)return e;throw new f('Not a string: \"'+e+'\"')}))(e)},exports.strictProxyMiddleware=x,exports.testOnly=function(e){return y},exports.url=function(e){return S((function(e){try{return new URL(e),e}catch(t){throw new f('Invalid url: \"'+e+'\"')}}))(e)};\n//# sourceMappingURL=envalid.cjs.production.min.js.map\n","\n'use strict'\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./envalid.cjs.production.min.js')\n} else {\n module.exports = require('./envalid.cjs.development.js')\n}\n","'use strict';\n\nvar GetIntrinsic = require('get-intrinsic');\n\nvar $TypeError = GetIntrinsic('%TypeError%');\n\nvar DefineOwnProperty = require('../helpers/DefineOwnProperty');\n\nvar FromPropertyDescriptor = require('./FromPropertyDescriptor');\nvar OrdinaryGetOwnProperty = require('./OrdinaryGetOwnProperty');\nvar IsDataDescriptor = require('./IsDataDescriptor');\nvar IsExtensible = require('./IsExtensible');\nvar IsPropertyKey = require('./IsPropertyKey');\nvar SameValue = require('./SameValue');\nvar Type = require('./Type');\n\n// https://ecma-international.org/ecma-262/6.0/#sec-createdataproperty\n\nmodule.exports = function CreateDataProperty(O, P, V) {\n\tif (Type(O) !== 'Object') {\n\t\tthrow new $TypeError('Assertion failed: Type(O) is not Object');\n\t}\n\tif (!IsPropertyKey(P)) {\n\t\tthrow new $TypeError('Assertion failed: IsPropertyKey(P) is not true');\n\t}\n\tvar oldDesc = OrdinaryGetOwnProperty(O, P);\n\tvar extensible = !oldDesc || IsExtensible(O);\n\tvar immutable = oldDesc && (!oldDesc['[[Writable]]'] || !oldDesc['[[Configurable]]']);\n\tif (immutable || !extensible) {\n\t\treturn false;\n\t}\n\treturn DefineOwnProperty(\n\t\tIsDataDescriptor,\n\t\tSameValue,\n\t\tFromPropertyDescriptor,\n\t\tO,\n\t\tP,\n\t\t{\n\t\t\t'[[Configurable]]': true,\n\t\t\t'[[Enumerable]]': true,\n\t\t\t'[[Value]]': V,\n\t\t\t'[[Writable]]': true\n\t\t}\n\t);\n};\n","'use strict';\n\nvar assertRecord = require('../helpers/assertRecord');\n\nvar Type = require('./Type');\n\n// https://ecma-international.org/ecma-262/6.0/#sec-frompropertydescriptor\n\nmodule.exports = function FromPropertyDescriptor(Desc) {\n\tif (typeof Desc === 'undefined') {\n\t\treturn Desc;\n\t}\n\n\tassertRecord(Type, 'Property Descriptor', 'Desc', Desc);\n\n\tvar obj = {};\n\tif ('[[Value]]' in Desc) {\n\t\tobj.value = Desc['[[Value]]'];\n\t}\n\tif ('[[Writable]]' in Desc) {\n\t\tobj.writable = Desc['[[Writable]]'];\n\t}\n\tif ('[[Get]]' in Desc) {\n\t\tobj.get = Desc['[[Get]]'];\n\t}\n\tif ('[[Set]]' in Desc) {\n\t\tobj.set = Desc['[[Set]]'];\n\t}\n\tif ('[[Enumerable]]' in Desc) {\n\t\tobj.enumerable = Desc['[[Enumerable]]'];\n\t}\n\tif ('[[Configurable]]' in Desc) {\n\t\tobj.configurable = Desc['[[Configurable]]'];\n\t}\n\treturn obj;\n};\n","'use strict';\n\nvar GetIntrinsic = require('get-intrinsic');\n\nvar $Array = GetIntrinsic('%Array%');\n\n// eslint-disable-next-line global-require\nvar toStr = !$Array.isArray && require('call-bind/callBound')('Object.prototype.toString');\n\n// https://ecma-international.org/ecma-262/6.0/#sec-isarray\n\nmodule.exports = $Array.isArray || function IsArray(argument) {\n\treturn toStr(argument) === '[object Array]';\n};\n","'use strict';\n\n// http://ecma-international.org/ecma-262/5.1/#sec-9.11\n\nmodule.exports = require('is-callable');\n","'use strict';\n\nvar has = require('has');\n\nvar assertRecord = require('../helpers/assertRecord');\n\nvar Type = require('./Type');\n\n// https://ecma-international.org/ecma-262/6.0/#sec-isdatadescriptor\n\nmodule.exports = function IsDataDescriptor(Desc) {\n\tif (typeof Desc === 'undefined') {\n\t\treturn false;\n\t}\n\n\tassertRecord(Type, 'Property Descriptor', 'Desc', Desc);\n\n\tif (!has(Desc, '[[Value]]') && !has(Desc, '[[Writable]]')) {\n\t\treturn false;\n\t}\n\n\treturn true;\n};\n","'use strict';\n\nvar GetIntrinsic = require('get-intrinsic');\n\nvar $Object = GetIntrinsic('%Object%');\n\nvar isPrimitive = require('../helpers/isPrimitive');\n\nvar $preventExtensions = $Object.preventExtensions;\nvar $isExtensible = $Object.isExtensible;\n\n// https://ecma-international.org/ecma-262/6.0/#sec-isextensible-o\n\nmodule.exports = $preventExtensions\n\t? function IsExtensible(obj) {\n\t\treturn !isPrimitive(obj) && $isExtensible(obj);\n\t}\n\t: function IsExtensible(obj) {\n\t\treturn !isPrimitive(obj);\n\t};\n","'use strict';\n\n// https://ecma-international.org/ecma-262/6.0/#sec-ispropertykey\n\nmodule.exports = function IsPropertyKey(argument) {\n\treturn typeof argument === 'string' || typeof argument === 'symbol';\n};\n","'use strict';\n\nvar GetIntrinsic = require('get-intrinsic');\n\nvar $match = GetIntrinsic('%Symbol.match%', true);\n\nvar hasRegExpMatcher = require('is-regex');\n\nvar ToBoolean = require('./ToBoolean');\n\n// https://ecma-international.org/ecma-262/6.0/#sec-isregexp\n\nmodule.exports = function IsRegExp(argument) {\n\tif (!argument || typeof argument !== 'object') {\n\t\treturn false;\n\t}\n\tif ($match) {\n\t\tvar isRegExp = argument[$match];\n\t\tif (typeof isRegExp !== 'undefined') {\n\t\t\treturn ToBoolean(isRegExp);\n\t\t}\n\t}\n\treturn hasRegExpMatcher(argument);\n};\n","'use strict';\n\nvar GetIntrinsic = require('get-intrinsic');\n\nvar $gOPD = require('../helpers/getOwnPropertyDescriptor');\nvar $TypeError = GetIntrinsic('%TypeError%');\n\nvar callBound = require('call-bind/callBound');\n\nvar $isEnumerable = callBound('Object.prototype.propertyIsEnumerable');\n\nvar has = require('has');\n\nvar IsArray = require('./IsArray');\nvar IsPropertyKey = require('./IsPropertyKey');\nvar IsRegExp = require('./IsRegExp');\nvar ToPropertyDescriptor = require('./ToPropertyDescriptor');\nvar Type = require('./Type');\n\n// https://ecma-international.org/ecma-262/6.0/#sec-ordinarygetownproperty\n\nmodule.exports = function OrdinaryGetOwnProperty(O, P) {\n\tif (Type(O) !== 'Object') {\n\t\tthrow new $TypeError('Assertion failed: O must be an Object');\n\t}\n\tif (!IsPropertyKey(P)) {\n\t\tthrow new $TypeError('Assertion failed: P must be a Property Key');\n\t}\n\tif (!has(O, P)) {\n\t\treturn void 0;\n\t}\n\tif (!$gOPD) {\n\t\t// ES3 / IE 8 fallback\n\t\tvar arrayLength = IsArray(O) && P === 'length';\n\t\tvar regexLastIndex = IsRegExp(O) && P === 'lastIndex';\n\t\treturn {\n\t\t\t'[[Configurable]]': !(arrayLength || regexLastIndex),\n\t\t\t'[[Enumerable]]': $isEnumerable(O, P),\n\t\t\t'[[Value]]': O[P],\n\t\t\t'[[Writable]]': true\n\t\t};\n\t}\n\treturn ToPropertyDescriptor($gOPD(O, P));\n};\n","'use strict';\n\nmodule.exports = require('../5/CheckObjectCoercible');\n","'use strict';\n\nvar $isNaN = require('../helpers/isNaN');\n\n// http://ecma-international.org/ecma-262/5.1/#sec-9.12\n\nmodule.exports = function SameValue(x, y) {\n\tif (x === y) { // 0 === -0, but they are not identical.\n\t\tif (x === 0) { return 1 / x === 1 / y; }\n\t\treturn true;\n\t}\n\treturn $isNaN(x) && $isNaN(y);\n};\n","'use strict';\n\n// http://ecma-international.org/ecma-262/5.1/#sec-9.2\n\nmodule.exports = function ToBoolean(value) { return !!value; };\n","'use strict';\n\nvar GetIntrinsic = require('get-intrinsic');\n\nvar $Object = GetIntrinsic('%Object%');\n\nvar RequireObjectCoercible = require('./RequireObjectCoercible');\n\n// https://ecma-international.org/ecma-262/6.0/#sec-toobject\n\nmodule.exports = function ToObject(value) {\n\tRequireObjectCoercible(value);\n\treturn $Object(value);\n};\n","'use strict';\n\nvar has = require('has');\n\nvar GetIntrinsic = require('get-intrinsic');\n\nvar $TypeError = GetIntrinsic('%TypeError%');\n\nvar Type = require('./Type');\nvar ToBoolean = require('./ToBoolean');\nvar IsCallable = require('./IsCallable');\n\n// https://ecma-international.org/ecma-262/5.1/#sec-8.10.5\n\nmodule.exports = function ToPropertyDescriptor(Obj) {\n\tif (Type(Obj) !== 'Object') {\n\t\tthrow new $TypeError('ToPropertyDescriptor requires an object');\n\t}\n\n\tvar desc = {};\n\tif (has(Obj, 'enumerable')) {\n\t\tdesc['[[Enumerable]]'] = ToBoolean(Obj.enumerable);\n\t}\n\tif (has(Obj, 'configurable')) {\n\t\tdesc['[[Configurable]]'] = ToBoolean(Obj.configurable);\n\t}\n\tif (has(Obj, 'value')) {\n\t\tdesc['[[Value]]'] = Obj.value;\n\t}\n\tif (has(Obj, 'writable')) {\n\t\tdesc['[[Writable]]'] = ToBoolean(Obj.writable);\n\t}\n\tif (has(Obj, 'get')) {\n\t\tvar getter = Obj.get;\n\t\tif (typeof getter !== 'undefined' && !IsCallable(getter)) {\n\t\t\tthrow new $TypeError('getter must be a function');\n\t\t}\n\t\tdesc['[[Get]]'] = getter;\n\t}\n\tif (has(Obj, 'set')) {\n\t\tvar setter = Obj.set;\n\t\tif (typeof setter !== 'undefined' && !IsCallable(setter)) {\n\t\t\tthrow new $TypeError('setter must be a function');\n\t\t}\n\t\tdesc['[[Set]]'] = setter;\n\t}\n\n\tif ((has(desc, '[[Get]]') || has(desc, '[[Set]]')) && (has(desc, '[[Value]]') || has(desc, '[[Writable]]'))) {\n\t\tthrow new $TypeError('Invalid property descriptor. Cannot both specify accessors and a value or writable attribute');\n\t}\n\treturn desc;\n};\n","'use strict';\n\nvar ES5Type = require('../5/Type');\n\n// https://ecma-international.org/ecma-262/11.0/#sec-ecmascript-data-types-and-values\n\nmodule.exports = function Type(x) {\n\tif (typeof x === 'symbol') {\n\t\treturn 'Symbol';\n\t}\n\tif (typeof x === 'bigint') {\n\t\treturn 'BigInt';\n\t}\n\treturn ES5Type(x);\n};\n","'use strict';\n\nvar GetIntrinsic = require('get-intrinsic');\n\nvar $TypeError = GetIntrinsic('%TypeError%');\n\n// http://ecma-international.org/ecma-262/5.1/#sec-9.10\n\nmodule.exports = function CheckObjectCoercible(value, optMessage) {\n\tif (value == null) {\n\t\tthrow new $TypeError(optMessage || ('Cannot call method on ' + value));\n\t}\n\treturn value;\n};\n","'use strict';\n\n// https://ecma-international.org/ecma-262/5.1/#sec-8\n\nmodule.exports = function Type(x) {\n\tif (x === null) {\n\t\treturn 'Null';\n\t}\n\tif (typeof x === 'undefined') {\n\t\treturn 'Undefined';\n\t}\n\tif (typeof x === 'function' || typeof x === 'object') {\n\t\treturn 'Object';\n\t}\n\tif (typeof x === 'number') {\n\t\treturn 'Number';\n\t}\n\tif (typeof x === 'boolean') {\n\t\treturn 'Boolean';\n\t}\n\tif (typeof x === 'string') {\n\t\treturn 'String';\n\t}\n};\n","'use strict';\n\nvar GetIntrinsic = require('get-intrinsic');\n\nvar $defineProperty = GetIntrinsic('%Object.defineProperty%', true);\n\nif ($defineProperty) {\n\ttry {\n\t\t$defineProperty({}, 'a', { value: 1 });\n\t} catch (e) {\n\t\t// IE 8 has a broken defineProperty\n\t\t$defineProperty = null;\n\t}\n}\n\nvar callBound = require('call-bind/callBound');\n\nvar $isEnumerable = callBound('Object.prototype.propertyIsEnumerable');\n\n// eslint-disable-next-line max-params\nmodule.exports = function DefineOwnProperty(IsDataDescriptor, SameValue, FromPropertyDescriptor, O, P, desc) {\n\tif (!$defineProperty) {\n\t\tif (!IsDataDescriptor(desc)) {\n\t\t\t// ES3 does not support getters/setters\n\t\t\treturn false;\n\t\t}\n\t\tif (!desc['[[Configurable]]'] || !desc['[[Writable]]']) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// fallback for ES3\n\t\tif (P in O && $isEnumerable(O, P) !== !!desc['[[Enumerable]]']) {\n\t\t\t// a non-enumerable existing property\n\t\t\treturn false;\n\t\t}\n\n\t\t// property does not exist at all, or exists but is enumerable\n\t\tvar V = desc['[[Value]]'];\n\t\t// eslint-disable-next-line no-param-reassign\n\t\tO[P] = V; // will use [[Define]]\n\t\treturn SameValue(O[P], V);\n\t}\n\t$defineProperty(O, P, FromPropertyDescriptor(desc));\n\treturn true;\n};\n","'use strict';\n\nvar GetIntrinsic = require('get-intrinsic');\n\nvar $TypeError = GetIntrinsic('%TypeError%');\nvar $SyntaxError = GetIntrinsic('%SyntaxError%');\n\nvar has = require('has');\n\nvar predicates = {\n\t// https://ecma-international.org/ecma-262/6.0/#sec-property-descriptor-specification-type\n\t'Property Descriptor': function isPropertyDescriptor(Type, Desc) {\n\t\tif (Type(Desc) !== 'Object') {\n\t\t\treturn false;\n\t\t}\n\t\tvar allowed = {\n\t\t\t'[[Configurable]]': true,\n\t\t\t'[[Enumerable]]': true,\n\t\t\t'[[Get]]': true,\n\t\t\t'[[Set]]': true,\n\t\t\t'[[Value]]': true,\n\t\t\t'[[Writable]]': true\n\t\t};\n\n\t\tfor (var key in Desc) { // eslint-disable-line\n\t\t\tif (has(Desc, key) && !allowed[key]) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tvar isData = has(Desc, '[[Value]]');\n\t\tvar IsAccessor = has(Desc, '[[Get]]') || has(Desc, '[[Set]]');\n\t\tif (isData && IsAccessor) {\n\t\t\tthrow new $TypeError('Property Descriptors may not be both accessor and data descriptors');\n\t\t}\n\t\treturn true;\n\t}\n};\n\nmodule.exports = function assertRecord(Type, recordType, argumentName, value) {\n\tvar predicate = predicates[recordType];\n\tif (typeof predicate !== 'function') {\n\t\tthrow new $SyntaxError('unknown record type: ' + recordType);\n\t}\n\tif (!predicate(Type, value)) {\n\t\tthrow new $TypeError(argumentName + ' must be a ' + recordType);\n\t}\n};\n","'use strict';\n\nvar GetIntrinsic = require('get-intrinsic');\n\nvar $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%');\nif ($gOPD) {\n\ttry {\n\t\t$gOPD([], 'length');\n\t} catch (e) {\n\t\t// IE 8 has a broken gOPD\n\t\t$gOPD = null;\n\t}\n}\n\nmodule.exports = $gOPD;\n","'use strict';\n\nmodule.exports = Number.isNaN || function isNaN(a) {\n\treturn a !== a;\n};\n","'use strict';\n\nmodule.exports = function isPrimitive(value) {\n\treturn value === null || (typeof value !== 'function' && typeof value !== 'object');\n};\n","'use strict';\n\nvar hasOwn = Object.prototype.hasOwnProperty;\nvar toStr = Object.prototype.toString;\nvar defineProperty = Object.defineProperty;\nvar gOPD = Object.getOwnPropertyDescriptor;\n\nvar isArray = function isArray(arr) {\n\tif (typeof Array.isArray === 'function') {\n\t\treturn Array.isArray(arr);\n\t}\n\n\treturn toStr.call(arr) === '[object Array]';\n};\n\nvar isPlainObject = function isPlainObject(obj) {\n\tif (!obj || toStr.call(obj) !== '[object Object]') {\n\t\treturn false;\n\t}\n\n\tvar hasOwnConstructor = hasOwn.call(obj, 'constructor');\n\tvar hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');\n\t// Not own constructor property must be Object\n\tif (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {\n\t\treturn false;\n\t}\n\n\t// Own properties are enumerated firstly, so to speed up,\n\t// if last one is own, then all properties are own.\n\tvar key;\n\tfor (key in obj) { /**/ }\n\n\treturn typeof key === 'undefined' || hasOwn.call(obj, key);\n};\n\n// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target\nvar setProperty = function setProperty(target, options) {\n\tif (defineProperty && options.name === '__proto__') {\n\t\tdefineProperty(target, options.name, {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\tvalue: options.newValue,\n\t\t\twritable: true\n\t\t});\n\t} else {\n\t\ttarget[options.name] = options.newValue;\n\t}\n};\n\n// Return undefined instead of __proto__ if '__proto__' is not an own property\nvar getProperty = function getProperty(obj, name) {\n\tif (name === '__proto__') {\n\t\tif (!hasOwn.call(obj, name)) {\n\t\t\treturn void 0;\n\t\t} else if (gOPD) {\n\t\t\t// In early versions of node, obj['__proto__'] is buggy when obj has\n\t\t\t// __proto__ as an own property. Object.getOwnPropertyDescriptor() works.\n\t\t\treturn gOPD(obj, name).value;\n\t\t}\n\t}\n\n\treturn obj[name];\n};\n\nmodule.exports = function extend() {\n\tvar options, name, src, copy, copyIsArray, clone;\n\tvar target = arguments[0];\n\tvar i = 1;\n\tvar length = arguments.length;\n\tvar deep = false;\n\n\t// Handle a deep copy situation\n\tif (typeof target === 'boolean') {\n\t\tdeep = target;\n\t\ttarget = arguments[1] || {};\n\t\t// skip the boolean and the target\n\t\ti = 2;\n\t}\n\tif (target == null || (typeof target !== 'object' && typeof target !== 'function')) {\n\t\ttarget = {};\n\t}\n\n\tfor (; i < length; ++i) {\n\t\toptions = arguments[i];\n\t\t// Only deal with non-null/undefined values\n\t\tif (options != null) {\n\t\t\t// Extend the base object\n\t\t\tfor (name in options) {\n\t\t\t\tsrc = getProperty(target, name);\n\t\t\t\tcopy = getProperty(options, name);\n\n\t\t\t\t// Prevent never-ending loop\n\t\t\t\tif (target !== copy) {\n\t\t\t\t\t// Recurse if we're merging plain objects or arrays\n\t\t\t\t\tif (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {\n\t\t\t\t\t\tif (copyIsArray) {\n\t\t\t\t\t\t\tcopyIsArray = false;\n\t\t\t\t\t\t\tclone = src && isArray(src) ? src : [];\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tclone = src && isPlainObject(src) ? src : {};\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Never move original objects, clone them\n\t\t\t\t\t\tsetProperty(target, { name: name, newValue: extend(deep, clone, copy) });\n\n\t\t\t\t\t// Don't bring in undefined values\n\t\t\t\t\t} else if (typeof copy !== 'undefined') {\n\t\t\t\t\t\tsetProperty(target, { name: name, newValue: copy });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return the modified object\n\treturn target;\n};\n","(function(l){function m(){}function k(a,c){a=void 0===a?\"utf-8\":a;c=void 0===c?{fatal:!1}:c;if(-1===r.indexOf(a.toLowerCase()))throw new RangeError(\"Failed to construct 'TextDecoder': The encoding label provided ('\"+a+\"') is invalid.\");if(c.fatal)throw Error(\"Failed to construct 'TextDecoder': the 'fatal' option is unsupported.\");}function t(a){return Buffer.from(a.buffer,a.byteOffset,a.byteLength).toString(\"utf-8\")}function u(a){var c=URL.createObjectURL(new Blob([a],{type:\"text/plain;charset=UTF-8\"}));\ntry{var f=new XMLHttpRequest;f.open(\"GET\",c,!1);f.send();return f.responseText}catch(e){return q(a)}finally{URL.revokeObjectURL(c)}}function q(a){for(var c=0,f=Math.min(65536,a.length+1),e=new Uint16Array(f),h=[],d=0;;){var b=c=f-1){h.push(String.fromCharCode.apply(null,e.subarray(0,d)));if(!b)return h.join(\"\");a=a.subarray(c);d=c=0}b=a[c++];if(0===(b&128))e[d++]=b;else if(192===(b&224)){var g=a[c++]&63;e[d++]=(b&31)<<6|g}else if(224===(b&240)){g=a[c++]&63;var n=a[c++]&63;e[d++]=\n(b&31)<<12|g<<6|n}else if(240===(b&248)){g=a[c++]&63;n=a[c++]&63;var v=a[c++]&63;b=(b&7)<<18|g<<12|n<<6|v;65535>>10&1023|55296,b=56320|b&1023);e[d++]=b}}}if(l.TextEncoder&&l.TextDecoder)return!1;var r=[\"utf-8\",\"utf8\",\"unicode-1-1-utf-8\"];Object.defineProperty(m.prototype,\"encoding\",{value:\"utf-8\"});m.prototype.encode=function(a,c){c=void 0===c?{stream:!1}:c;if(c.stream)throw Error(\"Failed to encode: the 'stream' option is unsupported.\");c=0;for(var f=a.length,e=0,h=Math.max(32,\nf+(f>>>1)+7),d=new Uint8Array(h>>>3<<3);c=b){if(c=b)continue}e+4>d.length&&(h+=8,h*=1+c/a.length*2,h=h>>>3<<3,g=new Uint8Array(h),g.set(d),d=g);if(0===(b&4294967168))d[e++]=b;else{if(0===(b&4294965248))d[e++]=b>>>6&31|192;else if(0===(b&4294901760))d[e++]=b>>>12&15|224,d[e++]=b>>>6&63|128;else if(0===(b&4292870144))d[e++]=b>>>18&7|240,d[e++]=b>>>12&\n63|128,d[e++]=b>>>6&63|128;else continue;d[e++]=b&63|128}}return d.slice?d.slice(0,e):d.subarray(0,e)};Object.defineProperty(k.prototype,\"encoding\",{value:\"utf-8\"});Object.defineProperty(k.prototype,\"fatal\",{value:!1});Object.defineProperty(k.prototype,\"ignoreBOM\",{value:!1});var p=q;\"function\"===typeof Buffer&&Buffer.from?p=t:\"function\"===typeof Blob&&\"function\"===typeof URL&&\"function\"===typeof URL.createObjectURL&&(p=u);k.prototype.decode=function(a,c){c=void 0===c?{stream:!1}:c;if(c.stream)throw Error(\"Failed to decode: the 'stream' option is unsupported.\");\na=a instanceof Uint8Array?a:a.buffer instanceof ArrayBuffer?new Uint8Array(a.buffer):new Uint8Array(a);return p(a)};l.TextEncoder=m;l.TextDecoder=k})(\"undefined\"!==typeof window?window:\"undefined\"!==typeof global?global:this);\n","module.exports = realpath\nrealpath.realpath = realpath\nrealpath.sync = realpathSync\nrealpath.realpathSync = realpathSync\nrealpath.monkeypatch = monkeypatch\nrealpath.unmonkeypatch = unmonkeypatch\n\nvar fs = require('fs')\nvar origRealpath = fs.realpath\nvar origRealpathSync = fs.realpathSync\n\nvar version = process.version\nvar ok = /^v[0-5]\\./.test(version)\nvar old = require('./old.js')\n\nfunction newError (er) {\n return er && er.syscall === 'realpath' && (\n er.code === 'ELOOP' ||\n er.code === 'ENOMEM' ||\n er.code === 'ENAMETOOLONG'\n )\n}\n\nfunction realpath (p, cache, cb) {\n if (ok) {\n return origRealpath(p, cache, cb)\n }\n\n if (typeof cache === 'function') {\n cb = cache\n cache = null\n }\n origRealpath(p, cache, function (er, result) {\n if (newError(er)) {\n old.realpath(p, cache, cb)\n } else {\n cb(er, result)\n }\n })\n}\n\nfunction realpathSync (p, cache) {\n if (ok) {\n return origRealpathSync(p, cache)\n }\n\n try {\n return origRealpathSync(p, cache)\n } catch (er) {\n if (newError(er)) {\n return old.realpathSync(p, cache)\n } else {\n throw er\n }\n }\n}\n\nfunction monkeypatch () {\n fs.realpath = realpath\n fs.realpathSync = realpathSync\n}\n\nfunction unmonkeypatch () {\n fs.realpath = origRealpath\n fs.realpathSync = origRealpathSync\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nvar pathModule = require('path');\nvar isWindows = process.platform === 'win32';\nvar fs = require('fs');\n\n// JavaScript implementation of realpath, ported from node pre-v6\n\nvar DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);\n\nfunction rethrow() {\n // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and\n // is fairly slow to generate.\n var callback;\n if (DEBUG) {\n var backtrace = new Error;\n callback = debugCallback;\n } else\n callback = missingCallback;\n\n return callback;\n\n function debugCallback(err) {\n if (err) {\n backtrace.message = err.message;\n err = backtrace;\n missingCallback(err);\n }\n }\n\n function missingCallback(err) {\n if (err) {\n if (process.throwDeprecation)\n throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs\n else if (!process.noDeprecation) {\n var msg = 'fs: missing callback ' + (err.stack || err.message);\n if (process.traceDeprecation)\n console.trace(msg);\n else\n console.error(msg);\n }\n }\n }\n}\n\nfunction maybeCallback(cb) {\n return typeof cb === 'function' ? cb : rethrow();\n}\n\nvar normalize = pathModule.normalize;\n\n// Regexp that finds the next partion of a (partial) path\n// result is [base_with_slash, base], e.g. ['somedir/', 'somedir']\nif (isWindows) {\n var nextPartRe = /(.*?)(?:[\\/\\\\]+|$)/g;\n} else {\n var nextPartRe = /(.*?)(?:[\\/]+|$)/g;\n}\n\n// Regex to find the device root, including trailing slash. E.g. 'c:\\\\'.\nif (isWindows) {\n var splitRootRe = /^(?:[a-zA-Z]:|[\\\\\\/]{2}[^\\\\\\/]+[\\\\\\/][^\\\\\\/]+)?[\\\\\\/]*/;\n} else {\n var splitRootRe = /^[\\/]*/;\n}\n\nexports.realpathSync = function realpathSync(p, cache) {\n // make p is absolute\n p = pathModule.resolve(p);\n\n if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {\n return cache[p];\n }\n\n var original = p,\n seenLinks = {},\n knownHard = {};\n\n // current character position in p\n var pos;\n // the partial path so far, including a trailing slash if any\n var current;\n // the partial path without a trailing slash (except when pointing at a root)\n var base;\n // the partial path scanned in the previous round, with slash\n var previous;\n\n start();\n\n function start() {\n // Skip over roots\n var m = splitRootRe.exec(p);\n pos = m[0].length;\n current = m[0];\n base = m[0];\n previous = '';\n\n // On windows, check that the root exists. On unix there is no need.\n if (isWindows && !knownHard[base]) {\n fs.lstatSync(base);\n knownHard[base] = true;\n }\n }\n\n // walk down the path, swapping out linked pathparts for their real\n // values\n // NB: p.length changes.\n while (pos < p.length) {\n // find the next part\n nextPartRe.lastIndex = pos;\n var result = nextPartRe.exec(p);\n previous = current;\n current += result[0];\n base = previous + result[1];\n pos = nextPartRe.lastIndex;\n\n // continue if not a symlink\n if (knownHard[base] || (cache && cache[base] === base)) {\n continue;\n }\n\n var resolvedLink;\n if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {\n // some known symbolic link. no need to stat again.\n resolvedLink = cache[base];\n } else {\n var stat = fs.lstatSync(base);\n if (!stat.isSymbolicLink()) {\n knownHard[base] = true;\n if (cache) cache[base] = base;\n continue;\n }\n\n // read the link if it wasn't read before\n // dev/ino always return 0 on windows, so skip the check.\n var linkTarget = null;\n if (!isWindows) {\n var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);\n if (seenLinks.hasOwnProperty(id)) {\n linkTarget = seenLinks[id];\n }\n }\n if (linkTarget === null) {\n fs.statSync(base);\n linkTarget = fs.readlinkSync(base);\n }\n resolvedLink = pathModule.resolve(previous, linkTarget);\n // track this, if given a cache.\n if (cache) cache[base] = resolvedLink;\n if (!isWindows) seenLinks[id] = linkTarget;\n }\n\n // resolve the link, then start over\n p = pathModule.resolve(resolvedLink, p.slice(pos));\n start();\n }\n\n if (cache) cache[original] = p;\n\n return p;\n};\n\n\nexports.realpath = function realpath(p, cache, cb) {\n if (typeof cb !== 'function') {\n cb = maybeCallback(cache);\n cache = null;\n }\n\n // make p is absolute\n p = pathModule.resolve(p);\n\n if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {\n return process.nextTick(cb.bind(null, null, cache[p]));\n }\n\n var original = p,\n seenLinks = {},\n knownHard = {};\n\n // current character position in p\n var pos;\n // the partial path so far, including a trailing slash if any\n var current;\n // the partial path without a trailing slash (except when pointing at a root)\n var base;\n // the partial path scanned in the previous round, with slash\n var previous;\n\n start();\n\n function start() {\n // Skip over roots\n var m = splitRootRe.exec(p);\n pos = m[0].length;\n current = m[0];\n base = m[0];\n previous = '';\n\n // On windows, check that the root exists. On unix there is no need.\n if (isWindows && !knownHard[base]) {\n fs.lstat(base, function(err) {\n if (err) return cb(err);\n knownHard[base] = true;\n LOOP();\n });\n } else {\n process.nextTick(LOOP);\n }\n }\n\n // walk down the path, swapping out linked pathparts for their real\n // values\n function LOOP() {\n // stop if scanned past end of path\n if (pos >= p.length) {\n if (cache) cache[original] = p;\n return cb(null, p);\n }\n\n // find the next part\n nextPartRe.lastIndex = pos;\n var result = nextPartRe.exec(p);\n previous = current;\n current += result[0];\n base = previous + result[1];\n pos = nextPartRe.lastIndex;\n\n // continue if not a symlink\n if (knownHard[base] || (cache && cache[base] === base)) {\n return process.nextTick(LOOP);\n }\n\n if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {\n // known symbolic link. no need to stat again.\n return gotResolvedLink(cache[base]);\n }\n\n return fs.lstat(base, gotStat);\n }\n\n function gotStat(err, stat) {\n if (err) return cb(err);\n\n // if not a symlink, skip to the next path part\n if (!stat.isSymbolicLink()) {\n knownHard[base] = true;\n if (cache) cache[base] = base;\n return process.nextTick(LOOP);\n }\n\n // stat & read the link if not read before\n // call gotTarget as soon as the link target is known\n // dev/ino always return 0 on windows, so skip the check.\n if (!isWindows) {\n var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);\n if (seenLinks.hasOwnProperty(id)) {\n return gotTarget(null, seenLinks[id], base);\n }\n }\n fs.stat(base, function(err) {\n if (err) return cb(err);\n\n fs.readlink(base, function(err, target) {\n if (!isWindows) seenLinks[id] = target;\n gotTarget(err, target);\n });\n });\n }\n\n function gotTarget(err, target, base) {\n if (err) return cb(err);\n\n var resolvedLink = pathModule.resolve(previous, target);\n if (cache) cache[base] = resolvedLink;\n gotResolvedLink(resolvedLink);\n }\n\n function gotResolvedLink(resolvedLink) {\n // resolve the link, then start over\n p = pathModule.resolve(resolvedLink, p.slice(pos));\n start();\n }\n};\n","'use strict';\n\n/* eslint no-invalid-this: 1 */\n\nvar ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';\nvar slice = Array.prototype.slice;\nvar toStr = Object.prototype.toString;\nvar funcType = '[object Function]';\n\nmodule.exports = function bind(that) {\n var target = this;\n if (typeof target !== 'function' || toStr.call(target) !== funcType) {\n throw new TypeError(ERROR_MESSAGE + target);\n }\n var args = slice.call(arguments, 1);\n\n var bound;\n var binder = function () {\n if (this instanceof bound) {\n var result = target.apply(\n this,\n args.concat(slice.call(arguments))\n );\n if (Object(result) === result) {\n return result;\n }\n return this;\n } else {\n return target.apply(\n that,\n args.concat(slice.call(arguments))\n );\n }\n };\n\n var boundLength = Math.max(0, target.length - args.length);\n var boundArgs = [];\n for (var i = 0; i < boundLength; i++) {\n boundArgs.push('$' + i);\n }\n\n bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);\n\n if (target.prototype) {\n var Empty = function Empty() {};\n Empty.prototype = target.prototype;\n bound.prototype = new Empty();\n Empty.prototype = null;\n }\n\n return bound;\n};\n","'use strict';\n\nvar implementation = require('./implementation');\n\nmodule.exports = Function.prototype.bind || implementation;\n","\"use strict\";\n// Copyright 2018 Google LLC\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.GaxiosError = void 0;\n/* eslint-disable @typescript-eslint/no-explicit-any */\nclass GaxiosError extends Error {\n constructor(message, options, response) {\n super(message);\n this.response = response;\n this.config = options;\n this.code = response.status.toString();\n }\n}\nexports.GaxiosError = GaxiosError;\n//# sourceMappingURL=common.js.map","\"use strict\";\n// Copyright 2018 Google LLC\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Gaxios = void 0;\nconst extend_1 = __importDefault(require(\"extend\"));\nconst node_fetch_1 = __importDefault(require(\"node-fetch\"));\nconst querystring_1 = __importDefault(require(\"querystring\"));\nconst is_stream_1 = __importDefault(require(\"is-stream\"));\nconst common_1 = require(\"./common\");\nconst retry_1 = require(\"./retry\");\n/* eslint-disable @typescript-eslint/no-explicit-any */\nconst fetch = hasFetch() ? window.fetch : node_fetch_1.default;\nfunction hasWindow() {\n return typeof window !== 'undefined' && !!window;\n}\nfunction hasFetch() {\n return hasWindow() && !!window.fetch;\n}\nlet HttpsProxyAgent;\nfunction loadProxy() {\n const proxy = process.env.HTTPS_PROXY ||\n process.env.https_proxy ||\n process.env.HTTP_PROXY ||\n process.env.http_proxy;\n if (proxy) {\n HttpsProxyAgent = require('https-proxy-agent');\n }\n return proxy;\n}\nloadProxy();\nfunction skipProxy(url) {\n var _a;\n const noProxyEnv = (_a = process.env.NO_PROXY) !== null && _a !== void 0 ? _a : process.env.no_proxy;\n if (!noProxyEnv) {\n return false;\n }\n const noProxyUrls = noProxyEnv.split(',');\n const parsedURL = new URL(url);\n return !!noProxyUrls.find(url => {\n if (url.startsWith('*.') || url.startsWith('.')) {\n url = url.replace('*', '');\n return parsedURL.hostname.endsWith(url);\n }\n else {\n return url === parsedURL.origin || url === parsedURL.hostname;\n }\n });\n}\n// Figure out if we should be using a proxy. Only if it's required, load\n// the https-proxy-agent module as it adds startup cost.\nfunction getProxy(url) {\n // If there is a match between the no_proxy env variables and the url, then do not proxy\n if (skipProxy(url)) {\n return undefined;\n // If there is not a match between the no_proxy env variables and the url, check to see if there should be a proxy\n }\n else {\n return loadProxy();\n }\n}\nclass Gaxios {\n /**\n * The Gaxios class is responsible for making HTTP requests.\n * @param defaults The default set of options to be used for this instance.\n */\n constructor(defaults) {\n this.agentCache = new Map();\n this.defaults = defaults || {};\n }\n /**\n * Perform an HTTP request with the given options.\n * @param opts Set of HTTP options that will be used for this HTTP request.\n */\n async request(opts = {}) {\n opts = this.validateOpts(opts);\n return this._request(opts);\n }\n async _defaultAdapter(opts) {\n const fetchImpl = opts.fetchImplementation || fetch;\n const res = (await fetchImpl(opts.url, opts));\n const data = await this.getResponseData(opts, res);\n return this.translateResponse(opts, res, data);\n }\n /**\n * Internal, retryable version of the `request` method.\n * @param opts Set of HTTP options that will be used for this HTTP request.\n */\n async _request(opts = {}) {\n try {\n let translatedResponse;\n if (opts.adapter) {\n translatedResponse = await opts.adapter(opts, this._defaultAdapter.bind(this));\n }\n else {\n translatedResponse = await this._defaultAdapter(opts);\n }\n if (!opts.validateStatus(translatedResponse.status)) {\n throw new common_1.GaxiosError(`Request failed with status code ${translatedResponse.status}`, opts, translatedResponse);\n }\n return translatedResponse;\n }\n catch (e) {\n const err = e;\n err.config = opts;\n const { shouldRetry, config } = await retry_1.getRetryConfig(e);\n if (shouldRetry && config) {\n err.config.retryConfig.currentRetryAttempt = config.retryConfig.currentRetryAttempt;\n return this._request(err.config);\n }\n throw err;\n }\n }\n async getResponseData(opts, res) {\n switch (opts.responseType) {\n case 'stream':\n return res.body;\n case 'json': {\n let data = await res.text();\n try {\n data = JSON.parse(data);\n }\n catch (_a) {\n // continue\n }\n return data;\n }\n case 'arraybuffer':\n return res.arrayBuffer();\n case 'blob':\n return res.blob();\n default:\n return res.text();\n }\n }\n /**\n * Validates the options, and merges them with defaults.\n * @param opts The original options passed from the client.\n */\n validateOpts(options) {\n const opts = extend_1.default(true, {}, this.defaults, options);\n if (!opts.url) {\n throw new Error('URL is required.');\n }\n // baseUrl has been deprecated, remove in 2.0\n const baseUrl = opts.baseUrl || opts.baseURL;\n if (baseUrl) {\n opts.url = baseUrl + opts.url;\n }\n opts.paramsSerializer = opts.paramsSerializer || this.paramsSerializer;\n if (opts.params && Object.keys(opts.params).length > 0) {\n let additionalQueryParams = opts.paramsSerializer(opts.params);\n if (additionalQueryParams.startsWith('?')) {\n additionalQueryParams = additionalQueryParams.slice(1);\n }\n const prefix = opts.url.includes('?') ? '&' : '?';\n opts.url = opts.url + prefix + additionalQueryParams;\n }\n if (typeof options.maxContentLength === 'number') {\n opts.size = options.maxContentLength;\n }\n if (typeof options.maxRedirects === 'number') {\n opts.follow = options.maxRedirects;\n }\n opts.headers = opts.headers || {};\n if (opts.data) {\n if (is_stream_1.default.readable(opts.data)) {\n opts.body = opts.data;\n }\n else if (typeof opts.data === 'object') {\n opts.body = JSON.stringify(opts.data);\n // Allow the user to specifiy their own content type,\n // such as application/json-patch+json; for historical reasons this\n // content type must currently be a json type, as we are relying on\n // application/x-www-form-urlencoded (which is incompatible with\n // upstream GCP APIs) being rewritten to application/json.\n //\n // TODO: refactor upstream dependencies to stop relying on this\n // side-effect.\n if (!opts.headers['Content-Type'] ||\n !opts.headers['Content-Type'].includes('json')) {\n opts.headers['Content-Type'] = 'application/json';\n }\n }\n else {\n opts.body = opts.data;\n }\n }\n opts.validateStatus = opts.validateStatus || this.validateStatus;\n opts.responseType = opts.responseType || 'json';\n if (!opts.headers['Accept'] && opts.responseType === 'json') {\n opts.headers['Accept'] = 'application/json';\n }\n opts.method = opts.method || 'GET';\n const proxy = getProxy(opts.url);\n if (proxy) {\n if (this.agentCache.has(proxy)) {\n opts.agent = this.agentCache.get(proxy);\n }\n else {\n opts.agent = new HttpsProxyAgent(proxy);\n this.agentCache.set(proxy, opts.agent);\n }\n }\n return opts;\n }\n /**\n * By default, throw for any non-2xx status code\n * @param status status code from the HTTP response\n */\n validateStatus(status) {\n return status >= 200 && status < 300;\n }\n /**\n * Encode a set of key/value pars into a querystring format (?foo=bar&baz=boo)\n * @param params key value pars to encode\n */\n paramsSerializer(params) {\n return querystring_1.default.stringify(params);\n }\n translateResponse(opts, res, data) {\n // headers need to be converted from a map to an obj\n const headers = {};\n res.headers.forEach((value, key) => {\n headers[key] = value;\n });\n return {\n config: opts,\n data: data,\n headers,\n status: res.status,\n statusText: res.statusText,\n // XMLHttpRequestLike\n request: {\n responseURL: res.url,\n },\n };\n }\n}\nexports.Gaxios = Gaxios;\n//# sourceMappingURL=gaxios.js.map","\"use strict\";\n// Copyright 2018 Google LLC\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.request = exports.instance = exports.Gaxios = void 0;\nconst gaxios_1 = require(\"./gaxios\");\nObject.defineProperty(exports, \"Gaxios\", { enumerable: true, get: function () { return gaxios_1.Gaxios; } });\nvar common_1 = require(\"./common\");\nObject.defineProperty(exports, \"GaxiosError\", { enumerable: true, get: function () { return common_1.GaxiosError; } });\n/**\n * The default instance used when the `request` method is directly\n * invoked.\n */\nexports.instance = new gaxios_1.Gaxios();\n/**\n * Make an HTTP request using the given options.\n * @param opts Options for the request\n */\nasync function request(opts) {\n return exports.instance.request(opts);\n}\nexports.request = request;\n//# sourceMappingURL=index.js.map","\"use strict\";\n// Copyright 2018 Google LLC\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getRetryConfig = void 0;\nasync function getRetryConfig(err) {\n var _a;\n let config = getConfig(err);\n if (!err || !err.config || (!config && !err.config.retry)) {\n return { shouldRetry: false };\n }\n config = config || {};\n config.currentRetryAttempt = config.currentRetryAttempt || 0;\n config.retry =\n config.retry === undefined || config.retry === null ? 3 : config.retry;\n config.httpMethodsToRetry = config.httpMethodsToRetry || [\n 'GET',\n 'HEAD',\n 'PUT',\n 'OPTIONS',\n 'DELETE',\n ];\n config.noResponseRetries =\n config.noResponseRetries === undefined || config.noResponseRetries === null\n ? 2\n : config.noResponseRetries;\n // If this wasn't in the list of status codes where we want\n // to automatically retry, return.\n const retryRanges = [\n // https://en.wikipedia.org/wiki/List_of_HTTP_status_codes\n // 1xx - Retry (Informational, request still processing)\n // 2xx - Do not retry (Success)\n // 3xx - Do not retry (Redirect)\n // 4xx - Do not retry (Client errors)\n // 429 - Retry (\"Too Many Requests\")\n // 5xx - Retry (Server errors)\n [100, 199],\n [429, 429],\n [500, 599],\n ];\n config.statusCodesToRetry = config.statusCodesToRetry || retryRanges;\n // Put the config back into the err\n err.config.retryConfig = config;\n // Determine if we should retry the request\n const shouldRetryFn = config.shouldRetry || shouldRetryRequest;\n if (!(await shouldRetryFn(err))) {\n return { shouldRetry: false, config: err.config };\n }\n // Calculate time to wait with exponential backoff.\n // If this is the first retry, look for a configured retryDelay.\n const retryDelay = config.currentRetryAttempt ? 0 : (_a = config.retryDelay) !== null && _a !== void 0 ? _a : 100;\n // Formula: retryDelay + ((2^c - 1 / 2) * 1000)\n const delay = retryDelay + ((Math.pow(2, config.currentRetryAttempt) - 1) / 2) * 1000;\n // We're going to retry! Incremenent the counter.\n err.config.retryConfig.currentRetryAttempt += 1;\n // Create a promise that invokes the retry after the backOffDelay\n const backoff = new Promise(resolve => {\n setTimeout(resolve, delay);\n });\n // Notify the user if they added an `onRetryAttempt` handler\n if (config.onRetryAttempt) {\n config.onRetryAttempt(err);\n }\n // Return the promise in which recalls Gaxios to retry the request\n await backoff;\n return { shouldRetry: true, config: err.config };\n}\nexports.getRetryConfig = getRetryConfig;\n/**\n * Determine based on config if we should retry the request.\n * @param err The GaxiosError passed to the interceptor.\n */\nfunction shouldRetryRequest(err) {\n const config = getConfig(err);\n // node-fetch raises an AbortError if signaled:\n // https://github.com/bitinn/node-fetch#request-cancellation-with-abortsignal\n if (err.name === 'AbortError') {\n return false;\n }\n // If there's no config, or retries are disabled, return.\n if (!config || config.retry === 0) {\n return false;\n }\n // Check if this error has no response (ETIMEDOUT, ENOTFOUND, etc)\n if (!err.response &&\n (config.currentRetryAttempt || 0) >= config.noResponseRetries) {\n return false;\n }\n // Only retry with configured HttpMethods.\n if (!err.config.method ||\n config.httpMethodsToRetry.indexOf(err.config.method.toUpperCase()) < 0) {\n return false;\n }\n // If this wasn't in the list of status codes where we want\n // to automatically retry, return.\n if (err.response && err.response.status) {\n let isInRange = false;\n for (const [min, max] of config.statusCodesToRetry) {\n const status = err.response.status;\n if (status >= min && status <= max) {\n isInRange = true;\n break;\n }\n }\n if (!isInRange) {\n return false;\n }\n }\n // If we are out of retry attempts, return\n config.currentRetryAttempt = config.currentRetryAttempt || 0;\n if (config.currentRetryAttempt >= config.retry) {\n return false;\n }\n return true;\n}\n/**\n * Acquire the raxConfig object from an GaxiosError if available.\n * @param err The Gaxios error with a config object.\n */\nfunction getConfig(err) {\n if (err && err.config && err.config.retryConfig) {\n return err.config.retryConfig;\n }\n return;\n}\n//# sourceMappingURL=retry.js.map","\"use strict\";\n/**\n * Copyright 2018 Google LLC\n *\n * Distributed under MIT license.\n * See file LICENSE for detail or copy at https://opensource.org/licenses/MIT\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.requestTimeout = exports.resetIsAvailableCache = exports.isAvailable = exports.project = exports.instance = exports.HEADERS = exports.HEADER_VALUE = exports.HEADER_NAME = exports.SECONDARY_HOST_ADDRESS = exports.HOST_ADDRESS = exports.BASE_PATH = void 0;\nconst gaxios_1 = require(\"gaxios\");\nconst jsonBigint = require('json-bigint'); // eslint-disable-line\nexports.BASE_PATH = '/computeMetadata/v1';\nexports.HOST_ADDRESS = 'http://169.254.169.254';\nexports.SECONDARY_HOST_ADDRESS = 'http://metadata.google.internal.';\nexports.HEADER_NAME = 'Metadata-Flavor';\nexports.HEADER_VALUE = 'Google';\nexports.HEADERS = Object.freeze({ [exports.HEADER_NAME]: exports.HEADER_VALUE });\n/**\n * Returns the base URL while taking into account the GCE_METADATA_HOST\n * environment variable if it exists.\n *\n * @returns The base URL, e.g., http://169.254.169.254/computeMetadata/v1.\n */\nfunction getBaseUrl(baseUrl) {\n if (!baseUrl) {\n baseUrl =\n process.env.GCE_METADATA_IP ||\n process.env.GCE_METADATA_HOST ||\n exports.HOST_ADDRESS;\n }\n // If no scheme is provided default to HTTP:\n if (!/^https?:\\/\\//.test(baseUrl)) {\n baseUrl = `http://${baseUrl}`;\n }\n return new URL(exports.BASE_PATH, baseUrl).href;\n}\n// Accepts an options object passed from the user to the API. In previous\n// versions of the API, it referred to a `Request` or an `Axios` request\n// options object. Now it refers to an object with very limited property\n// names. This is here to help ensure users don't pass invalid options when\n// they upgrade from 0.4 to 0.5 to 0.8.\nfunction validate(options) {\n Object.keys(options).forEach(key => {\n switch (key) {\n case 'params':\n case 'property':\n case 'headers':\n break;\n case 'qs':\n throw new Error(\"'qs' is not a valid configuration option. Please use 'params' instead.\");\n default:\n throw new Error(`'${key}' is not a valid configuration option.`);\n }\n });\n}\nasync function metadataAccessor(type, options, noResponseRetries = 3, fastFail = false) {\n options = options || {};\n if (typeof options === 'string') {\n options = { property: options };\n }\n let property = '';\n if (typeof options === 'object' && options.property) {\n property = '/' + options.property;\n }\n validate(options);\n try {\n const requestMethod = fastFail ? fastFailMetadataRequest : gaxios_1.request;\n const res = await requestMethod({\n url: `${getBaseUrl()}/${type}${property}`,\n headers: Object.assign({}, exports.HEADERS, options.headers),\n retryConfig: { noResponseRetries },\n params: options.params,\n responseType: 'text',\n timeout: requestTimeout(),\n });\n // NOTE: node.js converts all incoming headers to lower case.\n if (res.headers[exports.HEADER_NAME.toLowerCase()] !== exports.HEADER_VALUE) {\n throw new Error(`Invalid response from metadata service: incorrect ${exports.HEADER_NAME} header.`);\n }\n else if (!res.data) {\n throw new Error('Invalid response from the metadata service');\n }\n if (typeof res.data === 'string') {\n try {\n return jsonBigint.parse(res.data);\n }\n catch (_a) {\n /* ignore */\n }\n }\n return res.data;\n }\n catch (e) {\n if (e.response && e.response.status !== 200) {\n e.message = `Unsuccessful response status code. ${e.message}`;\n }\n throw e;\n }\n}\nasync function fastFailMetadataRequest(options) {\n const secondaryOptions = {\n ...options,\n url: options.url.replace(getBaseUrl(), getBaseUrl(exports.SECONDARY_HOST_ADDRESS)),\n };\n // We race a connection between DNS/IP to metadata server. There are a couple\n // reasons for this:\n //\n // 1. the DNS is slow in some GCP environments; by checking both, we might\n // detect the runtime environment signficantly faster.\n // 2. we can't just check the IP, which is tarpitted and slow to respond\n // on a user's local machine.\n //\n // Additional logic has been added to make sure that we don't create an\n // unhandled rejection in scenarios where a failure happens sometime\n // after a success.\n //\n // Note, however, if a failure happens prior to a success, a rejection should\n // occur, this is for folks running locally.\n //\n let responded = false;\n const r1 = gaxios_1.request(options)\n .then(res => {\n responded = true;\n return res;\n })\n .catch(err => {\n if (responded) {\n return r2;\n }\n else {\n responded = true;\n throw err;\n }\n });\n const r2 = gaxios_1.request(secondaryOptions)\n .then(res => {\n responded = true;\n return res;\n })\n .catch(err => {\n if (responded) {\n return r1;\n }\n else {\n responded = true;\n throw err;\n }\n });\n return Promise.race([r1, r2]);\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction instance(options) {\n return metadataAccessor('instance', options);\n}\nexports.instance = instance;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction project(options) {\n return metadataAccessor('project', options);\n}\nexports.project = project;\n/*\n * How many times should we retry detecting GCP environment.\n */\nfunction detectGCPAvailableRetries() {\n return process.env.DETECT_GCP_RETRIES\n ? Number(process.env.DETECT_GCP_RETRIES)\n : 0;\n}\n/**\n * Determine if the metadata server is currently available.\n */\nlet cachedIsAvailableResponse;\nasync function isAvailable() {\n try {\n // If a user is instantiating several GCP libraries at the same time,\n // this may result in multiple calls to isAvailable(), to detect the\n // runtime environment. We use the same promise for each of these calls\n // to reduce the network load.\n if (cachedIsAvailableResponse === undefined) {\n cachedIsAvailableResponse = metadataAccessor('instance', undefined, detectGCPAvailableRetries(), \n // If the default HOST_ADDRESS has been overridden, we should not\n // make an effort to try SECONDARY_HOST_ADDRESS (as we are likely in\n // a non-GCP environment):\n !(process.env.GCE_METADATA_IP || process.env.GCE_METADATA_HOST));\n }\n await cachedIsAvailableResponse;\n return true;\n }\n catch (err) {\n if (process.env.DEBUG_AUTH) {\n console.info(err);\n }\n if (err.type === 'request-timeout') {\n // If running in a GCP environment, metadata endpoint should return\n // within ms.\n return false;\n }\n if (err.response && err.response.status === 404) {\n return false;\n }\n else {\n if (!(err.response && err.response.status === 404) &&\n // A warning is emitted if we see an unexpected err.code, or err.code\n // is not populated:\n (!err.code ||\n ![\n 'EHOSTDOWN',\n 'EHOSTUNREACH',\n 'ENETUNREACH',\n 'ENOENT',\n 'ENOTFOUND',\n 'ECONNREFUSED',\n ].includes(err.code))) {\n let code = 'UNKNOWN';\n if (err.code)\n code = err.code;\n process.emitWarning(`received unexpected error = ${err.message} code = ${code}`, 'MetadataLookupWarning');\n }\n // Failure to resolve the metadata service means that it is not available.\n return false;\n }\n }\n}\nexports.isAvailable = isAvailable;\n/**\n * reset the memoized isAvailable() lookup.\n */\nfunction resetIsAvailableCache() {\n cachedIsAvailableResponse = undefined;\n}\nexports.resetIsAvailableCache = resetIsAvailableCache;\nfunction requestTimeout() {\n // In testing, we were able to reproduce behavior similar to\n // https://github.com/googleapis/google-auth-library-nodejs/issues/798\n // by making many concurrent network requests. Requests do not actually fail,\n // rather they take significantly longer to complete (and we hit our\n // default 3000ms timeout).\n //\n // This logic detects a GCF environment, using the documented environment\n // variables K_SERVICE and FUNCTION_NAME:\n // https://cloud.google.com/functions/docs/env-var and, in a GCF environment\n // eliminates timeouts (by setting the value to 0 to disable).\n return process.env.K_SERVICE || process.env.FUNCTION_NAME ? 0 : 3000;\n}\nexports.requestTimeout = requestTimeout;\n//# sourceMappingURL=index.js.map","'use strict';\n\n/* globals\n\tAggregateError,\n\tAtomics,\n\tFinalizationRegistry,\n\tSharedArrayBuffer,\n\tWeakRef,\n*/\n\nvar undefined;\n\nvar $SyntaxError = SyntaxError;\nvar $Function = Function;\nvar $TypeError = TypeError;\n\n// eslint-disable-next-line consistent-return\nvar getEvalledConstructor = function (expressionSyntax) {\n\ttry {\n\t\t// eslint-disable-next-line no-new-func\n\t\treturn Function('\"use strict\"; return (' + expressionSyntax + ').constructor;')();\n\t} catch (e) {}\n};\n\nvar $gOPD = Object.getOwnPropertyDescriptor;\nif ($gOPD) {\n\ttry {\n\t\t$gOPD({}, '');\n\t} catch (e) {\n\t\t$gOPD = null; // this is IE 8, which has a broken gOPD\n\t}\n}\n\nvar throwTypeError = function () {\n\tthrow new $TypeError();\n};\nvar ThrowTypeError = $gOPD\n\t? (function () {\n\t\ttry {\n\t\t\t// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties\n\t\t\targuments.callee; // IE 8 does not throw here\n\t\t\treturn throwTypeError;\n\t\t} catch (calleeThrows) {\n\t\t\ttry {\n\t\t\t\t// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')\n\t\t\t\treturn $gOPD(arguments, 'callee').get;\n\t\t\t} catch (gOPDthrows) {\n\t\t\t\treturn throwTypeError;\n\t\t\t}\n\t\t}\n\t}())\n\t: throwTypeError;\n\nvar hasSymbols = require('has-symbols')();\n\nvar getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto\n\nvar asyncGenFunction = getEvalledConstructor('async function* () {}');\nvar asyncGenFunctionPrototype = asyncGenFunction ? asyncGenFunction.prototype : undefined;\nvar asyncGenPrototype = asyncGenFunctionPrototype ? asyncGenFunctionPrototype.prototype : undefined;\n\nvar TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array);\n\nvar INTRINSICS = {\n\t'%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError,\n\t'%Array%': Array,\n\t'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,\n\t'%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined,\n\t'%AsyncFromSyncIteratorPrototype%': undefined,\n\t'%AsyncFunction%': getEvalledConstructor('async function () {}'),\n\t'%AsyncGenerator%': asyncGenFunctionPrototype,\n\t'%AsyncGeneratorFunction%': asyncGenFunction,\n\t'%AsyncIteratorPrototype%': asyncGenPrototype ? getProto(asyncGenPrototype) : undefined,\n\t'%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,\n\t'%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt,\n\t'%Boolean%': Boolean,\n\t'%DataView%': typeof DataView === 'undefined' ? undefined : DataView,\n\t'%Date%': Date,\n\t'%decodeURI%': decodeURI,\n\t'%decodeURIComponent%': decodeURIComponent,\n\t'%encodeURI%': encodeURI,\n\t'%encodeURIComponent%': encodeURIComponent,\n\t'%Error%': Error,\n\t'%eval%': eval, // eslint-disable-line no-eval\n\t'%EvalError%': EvalError,\n\t'%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,\n\t'%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,\n\t'%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry,\n\t'%Function%': $Function,\n\t'%GeneratorFunction%': getEvalledConstructor('function* () {}'),\n\t'%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,\n\t'%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,\n\t'%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,\n\t'%isFinite%': isFinite,\n\t'%isNaN%': isNaN,\n\t'%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined,\n\t'%JSON%': typeof JSON === 'object' ? JSON : undefined,\n\t'%Map%': typeof Map === 'undefined' ? undefined : Map,\n\t'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()),\n\t'%Math%': Math,\n\t'%Number%': Number,\n\t'%Object%': Object,\n\t'%parseFloat%': parseFloat,\n\t'%parseInt%': parseInt,\n\t'%Promise%': typeof Promise === 'undefined' ? undefined : Promise,\n\t'%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,\n\t'%RangeError%': RangeError,\n\t'%ReferenceError%': ReferenceError,\n\t'%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,\n\t'%RegExp%': RegExp,\n\t'%Set%': typeof Set === 'undefined' ? undefined : Set,\n\t'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()),\n\t'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,\n\t'%String%': String,\n\t'%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined,\n\t'%Symbol%': hasSymbols ? Symbol : undefined,\n\t'%SyntaxError%': $SyntaxError,\n\t'%ThrowTypeError%': ThrowTypeError,\n\t'%TypedArray%': TypedArray,\n\t'%TypeError%': $TypeError,\n\t'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,\n\t'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,\n\t'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,\n\t'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,\n\t'%URIError%': URIError,\n\t'%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,\n\t'%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef,\n\t'%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet\n};\n\nvar LEGACY_ALIASES = {\n\t'%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],\n\t'%ArrayPrototype%': ['Array', 'prototype'],\n\t'%ArrayProto_entries%': ['Array', 'prototype', 'entries'],\n\t'%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],\n\t'%ArrayProto_keys%': ['Array', 'prototype', 'keys'],\n\t'%ArrayProto_values%': ['Array', 'prototype', 'values'],\n\t'%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],\n\t'%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],\n\t'%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],\n\t'%BooleanPrototype%': ['Boolean', 'prototype'],\n\t'%DataViewPrototype%': ['DataView', 'prototype'],\n\t'%DatePrototype%': ['Date', 'prototype'],\n\t'%ErrorPrototype%': ['Error', 'prototype'],\n\t'%EvalErrorPrototype%': ['EvalError', 'prototype'],\n\t'%Float32ArrayPrototype%': ['Float32Array', 'prototype'],\n\t'%Float64ArrayPrototype%': ['Float64Array', 'prototype'],\n\t'%FunctionPrototype%': ['Function', 'prototype'],\n\t'%Generator%': ['GeneratorFunction', 'prototype'],\n\t'%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],\n\t'%Int8ArrayPrototype%': ['Int8Array', 'prototype'],\n\t'%Int16ArrayPrototype%': ['Int16Array', 'prototype'],\n\t'%Int32ArrayPrototype%': ['Int32Array', 'prototype'],\n\t'%JSONParse%': ['JSON', 'parse'],\n\t'%JSONStringify%': ['JSON', 'stringify'],\n\t'%MapPrototype%': ['Map', 'prototype'],\n\t'%NumberPrototype%': ['Number', 'prototype'],\n\t'%ObjectPrototype%': ['Object', 'prototype'],\n\t'%ObjProto_toString%': ['Object', 'prototype', 'toString'],\n\t'%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],\n\t'%PromisePrototype%': ['Promise', 'prototype'],\n\t'%PromiseProto_then%': ['Promise', 'prototype', 'then'],\n\t'%Promise_all%': ['Promise', 'all'],\n\t'%Promise_reject%': ['Promise', 'reject'],\n\t'%Promise_resolve%': ['Promise', 'resolve'],\n\t'%RangeErrorPrototype%': ['RangeError', 'prototype'],\n\t'%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],\n\t'%RegExpPrototype%': ['RegExp', 'prototype'],\n\t'%SetPrototype%': ['Set', 'prototype'],\n\t'%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],\n\t'%StringPrototype%': ['String', 'prototype'],\n\t'%SymbolPrototype%': ['Symbol', 'prototype'],\n\t'%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],\n\t'%TypedArrayPrototype%': ['TypedArray', 'prototype'],\n\t'%TypeErrorPrototype%': ['TypeError', 'prototype'],\n\t'%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],\n\t'%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],\n\t'%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],\n\t'%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],\n\t'%URIErrorPrototype%': ['URIError', 'prototype'],\n\t'%WeakMapPrototype%': ['WeakMap', 'prototype'],\n\t'%WeakSetPrototype%': ['WeakSet', 'prototype']\n};\n\nvar bind = require('function-bind');\nvar hasOwn = require('has');\nvar $concat = bind.call(Function.call, Array.prototype.concat);\nvar $spliceApply = bind.call(Function.apply, Array.prototype.splice);\nvar $replace = bind.call(Function.call, String.prototype.replace);\nvar $strSlice = bind.call(Function.call, String.prototype.slice);\n\n/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */\nvar rePropName = /[^%.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|%$))/g;\nvar reEscapeChar = /\\\\(\\\\)?/g; /** Used to match backslashes in property paths. */\nvar stringToPath = function stringToPath(string) {\n\tvar first = $strSlice(string, 0, 1);\n\tvar last = $strSlice(string, -1);\n\tif (first === '%' && last !== '%') {\n\t\tthrow new $SyntaxError('invalid intrinsic syntax, expected closing `%`');\n\t} else if (last === '%' && first !== '%') {\n\t\tthrow new $SyntaxError('invalid intrinsic syntax, expected opening `%`');\n\t}\n\tvar result = [];\n\t$replace(string, rePropName, function (match, number, quote, subString) {\n\t\tresult[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;\n\t});\n\treturn result;\n};\n/* end adaptation */\n\nvar getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {\n\tvar intrinsicName = name;\n\tvar alias;\n\tif (hasOwn(LEGACY_ALIASES, intrinsicName)) {\n\t\talias = LEGACY_ALIASES[intrinsicName];\n\t\tintrinsicName = '%' + alias[0] + '%';\n\t}\n\n\tif (hasOwn(INTRINSICS, intrinsicName)) {\n\t\tvar value = INTRINSICS[intrinsicName];\n\t\tif (typeof value === 'undefined' && !allowMissing) {\n\t\t\tthrow new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');\n\t\t}\n\n\t\treturn {\n\t\t\talias: alias,\n\t\t\tname: intrinsicName,\n\t\t\tvalue: value\n\t\t};\n\t}\n\n\tthrow new $SyntaxError('intrinsic ' + name + ' does not exist!');\n};\n\nmodule.exports = function GetIntrinsic(name, allowMissing) {\n\tif (typeof name !== 'string' || name.length === 0) {\n\t\tthrow new $TypeError('intrinsic name must be a non-empty string');\n\t}\n\tif (arguments.length > 1 && typeof allowMissing !== 'boolean') {\n\t\tthrow new $TypeError('\"allowMissing\" argument must be a boolean');\n\t}\n\n\tvar parts = stringToPath(name);\n\tvar intrinsicBaseName = parts.length > 0 ? parts[0] : '';\n\n\tvar intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);\n\tvar intrinsicRealName = intrinsic.name;\n\tvar value = intrinsic.value;\n\tvar skipFurtherCaching = false;\n\n\tvar alias = intrinsic.alias;\n\tif (alias) {\n\t\tintrinsicBaseName = alias[0];\n\t\t$spliceApply(parts, $concat([0, 1], alias));\n\t}\n\n\tfor (var i = 1, isOwn = true; i < parts.length; i += 1) {\n\t\tvar part = parts[i];\n\t\tvar first = $strSlice(part, 0, 1);\n\t\tvar last = $strSlice(part, -1);\n\t\tif (\n\t\t\t(\n\t\t\t\t(first === '\"' || first === \"'\" || first === '`')\n\t\t\t\t|| (last === '\"' || last === \"'\" || last === '`')\n\t\t\t)\n\t\t\t&& first !== last\n\t\t) {\n\t\t\tthrow new $SyntaxError('property names with quotes must have matching quotes');\n\t\t}\n\t\tif (part === 'constructor' || !isOwn) {\n\t\t\tskipFurtherCaching = true;\n\t\t}\n\n\t\tintrinsicBaseName += '.' + part;\n\t\tintrinsicRealName = '%' + intrinsicBaseName + '%';\n\n\t\tif (hasOwn(INTRINSICS, intrinsicRealName)) {\n\t\t\tvalue = INTRINSICS[intrinsicRealName];\n\t\t} else if (value != null) {\n\t\t\tif (!(part in value)) {\n\t\t\t\tif (!allowMissing) {\n\t\t\t\t\tthrow new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');\n\t\t\t\t}\n\t\t\t\treturn void undefined;\n\t\t\t}\n\t\t\tif ($gOPD && (i + 1) >= parts.length) {\n\t\t\t\tvar desc = $gOPD(value, part);\n\t\t\t\tisOwn = !!desc;\n\n\t\t\t\t// By convention, when a data property is converted to an accessor\n\t\t\t\t// property to emulate a data property that does not suffer from\n\t\t\t\t// the override mistake, that accessor's getter is marked with\n\t\t\t\t// an `originalValue` property. Here, when we detect this, we\n\t\t\t\t// uphold the illusion by pretending to see that original data\n\t\t\t\t// property, i.e., returning the value rather than the getter\n\t\t\t\t// itself.\n\t\t\t\tif (isOwn && 'get' in desc && !('originalValue' in desc.get)) {\n\t\t\t\t\tvalue = desc.get;\n\t\t\t\t} else {\n\t\t\t\t\tvalue = value[part];\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tisOwn = hasOwn(value, part);\n\t\t\t\tvalue = value[part];\n\t\t\t}\n\n\t\t\tif (isOwn && !skipFurtherCaching) {\n\t\t\t\tINTRINSICS[intrinsicRealName] = value;\n\t\t\t}\n\t\t}\n\t}\n\treturn value;\n};\n","exports.alphasort = alphasort\nexports.alphasorti = alphasorti\nexports.setopts = setopts\nexports.ownProp = ownProp\nexports.makeAbs = makeAbs\nexports.finish = finish\nexports.mark = mark\nexports.isIgnored = isIgnored\nexports.childrenIgnored = childrenIgnored\n\nfunction ownProp (obj, field) {\n return Object.prototype.hasOwnProperty.call(obj, field)\n}\n\nvar path = require(\"path\")\nvar minimatch = require(\"minimatch\")\nvar isAbsolute = require(\"path-is-absolute\")\nvar Minimatch = minimatch.Minimatch\n\nfunction alphasorti (a, b) {\n return a.toLowerCase().localeCompare(b.toLowerCase())\n}\n\nfunction alphasort (a, b) {\n return a.localeCompare(b)\n}\n\nfunction setupIgnores (self, options) {\n self.ignore = options.ignore || []\n\n if (!Array.isArray(self.ignore))\n self.ignore = [self.ignore]\n\n if (self.ignore.length) {\n self.ignore = self.ignore.map(ignoreMap)\n }\n}\n\n// ignore patterns are always in dot:true mode.\nfunction ignoreMap (pattern) {\n var gmatcher = null\n if (pattern.slice(-3) === '/**') {\n var gpattern = pattern.replace(/(\\/\\*\\*)+$/, '')\n gmatcher = new Minimatch(gpattern, { dot: true })\n }\n\n return {\n matcher: new Minimatch(pattern, { dot: true }),\n gmatcher: gmatcher\n }\n}\n\nfunction setopts (self, pattern, options) {\n if (!options)\n options = {}\n\n // base-matching: just use globstar for that.\n if (options.matchBase && -1 === pattern.indexOf(\"/\")) {\n if (options.noglobstar) {\n throw new Error(\"base matching requires globstar\")\n }\n pattern = \"**/\" + pattern\n }\n\n self.silent = !!options.silent\n self.pattern = pattern\n self.strict = options.strict !== false\n self.realpath = !!options.realpath\n self.realpathCache = options.realpathCache || Object.create(null)\n self.follow = !!options.follow\n self.dot = !!options.dot\n self.mark = !!options.mark\n self.nodir = !!options.nodir\n if (self.nodir)\n self.mark = true\n self.sync = !!options.sync\n self.nounique = !!options.nounique\n self.nonull = !!options.nonull\n self.nosort = !!options.nosort\n self.nocase = !!options.nocase\n self.stat = !!options.stat\n self.noprocess = !!options.noprocess\n self.absolute = !!options.absolute\n\n self.maxLength = options.maxLength || Infinity\n self.cache = options.cache || Object.create(null)\n self.statCache = options.statCache || Object.create(null)\n self.symlinks = options.symlinks || Object.create(null)\n\n setupIgnores(self, options)\n\n self.changedCwd = false\n var cwd = process.cwd()\n if (!ownProp(options, \"cwd\"))\n self.cwd = cwd\n else {\n self.cwd = path.resolve(options.cwd)\n self.changedCwd = self.cwd !== cwd\n }\n\n self.root = options.root || path.resolve(self.cwd, \"/\")\n self.root = path.resolve(self.root)\n if (process.platform === \"win32\")\n self.root = self.root.replace(/\\\\/g, \"/\")\n\n // TODO: is an absolute `cwd` supposed to be resolved against `root`?\n // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test')\n self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd)\n if (process.platform === \"win32\")\n self.cwdAbs = self.cwdAbs.replace(/\\\\/g, \"/\")\n self.nomount = !!options.nomount\n\n // disable comments and negation in Minimatch.\n // Note that they are not supported in Glob itself anyway.\n options.nonegate = true\n options.nocomment = true\n\n self.minimatch = new Minimatch(pattern, options)\n self.options = self.minimatch.options\n}\n\nfunction finish (self) {\n var nou = self.nounique\n var all = nou ? [] : Object.create(null)\n\n for (var i = 0, l = self.matches.length; i < l; i ++) {\n var matches = self.matches[i]\n if (!matches || Object.keys(matches).length === 0) {\n if (self.nonull) {\n // do like the shell, and spit out the literal glob\n var literal = self.minimatch.globSet[i]\n if (nou)\n all.push(literal)\n else\n all[literal] = true\n }\n } else {\n // had matches\n var m = Object.keys(matches)\n if (nou)\n all.push.apply(all, m)\n else\n m.forEach(function (m) {\n all[m] = true\n })\n }\n }\n\n if (!nou)\n all = Object.keys(all)\n\n if (!self.nosort)\n all = all.sort(self.nocase ? alphasorti : alphasort)\n\n // at *some* point we statted all of these\n if (self.mark) {\n for (var i = 0; i < all.length; i++) {\n all[i] = self._mark(all[i])\n }\n if (self.nodir) {\n all = all.filter(function (e) {\n var notDir = !(/\\/$/.test(e))\n var c = self.cache[e] || self.cache[makeAbs(self, e)]\n if (notDir && c)\n notDir = c !== 'DIR' && !Array.isArray(c)\n return notDir\n })\n }\n }\n\n if (self.ignore.length)\n all = all.filter(function(m) {\n return !isIgnored(self, m)\n })\n\n self.found = all\n}\n\nfunction mark (self, p) {\n var abs = makeAbs(self, p)\n var c = self.cache[abs]\n var m = p\n if (c) {\n var isDir = c === 'DIR' || Array.isArray(c)\n var slash = p.slice(-1) === '/'\n\n if (isDir && !slash)\n m += '/'\n else if (!isDir && slash)\n m = m.slice(0, -1)\n\n if (m !== p) {\n var mabs = makeAbs(self, m)\n self.statCache[mabs] = self.statCache[abs]\n self.cache[mabs] = self.cache[abs]\n }\n }\n\n return m\n}\n\n// lotta situps...\nfunction makeAbs (self, f) {\n var abs = f\n if (f.charAt(0) === '/') {\n abs = path.join(self.root, f)\n } else if (isAbsolute(f) || f === '') {\n abs = f\n } else if (self.changedCwd) {\n abs = path.resolve(self.cwd, f)\n } else {\n abs = path.resolve(f)\n }\n\n if (process.platform === 'win32')\n abs = abs.replace(/\\\\/g, '/')\n\n return abs\n}\n\n\n// Return true, if pattern ends with globstar '**', for the accompanying parent directory.\n// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents\nfunction isIgnored (self, path) {\n if (!self.ignore.length)\n return false\n\n return self.ignore.some(function(item) {\n return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path))\n })\n}\n\nfunction childrenIgnored (self, path) {\n if (!self.ignore.length)\n return false\n\n return self.ignore.some(function(item) {\n return !!(item.gmatcher && item.gmatcher.match(path))\n })\n}\n","// Approach:\n//\n// 1. Get the minimatch set\n// 2. For each pattern in the set, PROCESS(pattern, false)\n// 3. Store matches per-set, then uniq them\n//\n// PROCESS(pattern, inGlobStar)\n// Get the first [n] items from pattern that are all strings\n// Join these together. This is PREFIX.\n// If there is no more remaining, then stat(PREFIX) and\n// add to matches if it succeeds. END.\n//\n// If inGlobStar and PREFIX is symlink and points to dir\n// set ENTRIES = []\n// else readdir(PREFIX) as ENTRIES\n// If fail, END\n//\n// with ENTRIES\n// If pattern[n] is GLOBSTAR\n// // handle the case where the globstar match is empty\n// // by pruning it out, and testing the resulting pattern\n// PROCESS(pattern[0..n] + pattern[n+1 .. $], false)\n// // handle other cases.\n// for ENTRY in ENTRIES (not dotfiles)\n// // attach globstar + tail onto the entry\n// // Mark that this entry is a globstar match\n// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)\n//\n// else // not globstar\n// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)\n// Test ENTRY against pattern[n]\n// If fails, continue\n// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])\n//\n// Caveat:\n// Cache all stats and readdirs results to minimize syscall. Since all\n// we ever care about is existence and directory-ness, we can just keep\n// `true` for files, and [children,...] for directories, or `false` for\n// things that don't exist.\n\nmodule.exports = glob\n\nvar fs = require('fs')\nvar rp = require('fs.realpath')\nvar minimatch = require('minimatch')\nvar Minimatch = minimatch.Minimatch\nvar inherits = require('inherits')\nvar EE = require('events').EventEmitter\nvar path = require('path')\nvar assert = require('assert')\nvar isAbsolute = require('path-is-absolute')\nvar globSync = require('./sync.js')\nvar common = require('./common.js')\nvar alphasort = common.alphasort\nvar alphasorti = common.alphasorti\nvar setopts = common.setopts\nvar ownProp = common.ownProp\nvar inflight = require('inflight')\nvar util = require('util')\nvar childrenIgnored = common.childrenIgnored\nvar isIgnored = common.isIgnored\n\nvar once = require('once')\n\nfunction glob (pattern, options, cb) {\n if (typeof options === 'function') cb = options, options = {}\n if (!options) options = {}\n\n if (options.sync) {\n if (cb)\n throw new TypeError('callback provided to sync glob')\n return globSync(pattern, options)\n }\n\n return new Glob(pattern, options, cb)\n}\n\nglob.sync = globSync\nvar GlobSync = glob.GlobSync = globSync.GlobSync\n\n// old api surface\nglob.glob = glob\n\nfunction extend (origin, add) {\n if (add === null || typeof add !== 'object') {\n return origin\n }\n\n var keys = Object.keys(add)\n var i = keys.length\n while (i--) {\n origin[keys[i]] = add[keys[i]]\n }\n return origin\n}\n\nglob.hasMagic = function (pattern, options_) {\n var options = extend({}, options_)\n options.noprocess = true\n\n var g = new Glob(pattern, options)\n var set = g.minimatch.set\n\n if (!pattern)\n return false\n\n if (set.length > 1)\n return true\n\n for (var j = 0; j < set[0].length; j++) {\n if (typeof set[0][j] !== 'string')\n return true\n }\n\n return false\n}\n\nglob.Glob = Glob\ninherits(Glob, EE)\nfunction Glob (pattern, options, cb) {\n if (typeof options === 'function') {\n cb = options\n options = null\n }\n\n if (options && options.sync) {\n if (cb)\n throw new TypeError('callback provided to sync glob')\n return new GlobSync(pattern, options)\n }\n\n if (!(this instanceof Glob))\n return new Glob(pattern, options, cb)\n\n setopts(this, pattern, options)\n this._didRealPath = false\n\n // process each pattern in the minimatch set\n var n = this.minimatch.set.length\n\n // The matches are stored as {: true,...} so that\n // duplicates are automagically pruned.\n // Later, we do an Object.keys() on these.\n // Keep them as a list so we can fill in when nonull is set.\n this.matches = new Array(n)\n\n if (typeof cb === 'function') {\n cb = once(cb)\n this.on('error', cb)\n this.on('end', function (matches) {\n cb(null, matches)\n })\n }\n\n var self = this\n this._processing = 0\n\n this._emitQueue = []\n this._processQueue = []\n this.paused = false\n\n if (this.noprocess)\n return this\n\n if (n === 0)\n return done()\n\n var sync = true\n for (var i = 0; i < n; i ++) {\n this._process(this.minimatch.set[i], i, false, done)\n }\n sync = false\n\n function done () {\n --self._processing\n if (self._processing <= 0) {\n if (sync) {\n process.nextTick(function () {\n self._finish()\n })\n } else {\n self._finish()\n }\n }\n }\n}\n\nGlob.prototype._finish = function () {\n assert(this instanceof Glob)\n if (this.aborted)\n return\n\n if (this.realpath && !this._didRealpath)\n return this._realpath()\n\n common.finish(this)\n this.emit('end', this.found)\n}\n\nGlob.prototype._realpath = function () {\n if (this._didRealpath)\n return\n\n this._didRealpath = true\n\n var n = this.matches.length\n if (n === 0)\n return this._finish()\n\n var self = this\n for (var i = 0; i < this.matches.length; i++)\n this._realpathSet(i, next)\n\n function next () {\n if (--n === 0)\n self._finish()\n }\n}\n\nGlob.prototype._realpathSet = function (index, cb) {\n var matchset = this.matches[index]\n if (!matchset)\n return cb()\n\n var found = Object.keys(matchset)\n var self = this\n var n = found.length\n\n if (n === 0)\n return cb()\n\n var set = this.matches[index] = Object.create(null)\n found.forEach(function (p, i) {\n // If there's a problem with the stat, then it means that\n // one or more of the links in the realpath couldn't be\n // resolved. just return the abs value in that case.\n p = self._makeAbs(p)\n rp.realpath(p, self.realpathCache, function (er, real) {\n if (!er)\n set[real] = true\n else if (er.syscall === 'stat')\n set[p] = true\n else\n self.emit('error', er) // srsly wtf right here\n\n if (--n === 0) {\n self.matches[index] = set\n cb()\n }\n })\n })\n}\n\nGlob.prototype._mark = function (p) {\n return common.mark(this, p)\n}\n\nGlob.prototype._makeAbs = function (f) {\n return common.makeAbs(this, f)\n}\n\nGlob.prototype.abort = function () {\n this.aborted = true\n this.emit('abort')\n}\n\nGlob.prototype.pause = function () {\n if (!this.paused) {\n this.paused = true\n this.emit('pause')\n }\n}\n\nGlob.prototype.resume = function () {\n if (this.paused) {\n this.emit('resume')\n this.paused = false\n if (this._emitQueue.length) {\n var eq = this._emitQueue.slice(0)\n this._emitQueue.length = 0\n for (var i = 0; i < eq.length; i ++) {\n var e = eq[i]\n this._emitMatch(e[0], e[1])\n }\n }\n if (this._processQueue.length) {\n var pq = this._processQueue.slice(0)\n this._processQueue.length = 0\n for (var i = 0; i < pq.length; i ++) {\n var p = pq[i]\n this._processing--\n this._process(p[0], p[1], p[2], p[3])\n }\n }\n }\n}\n\nGlob.prototype._process = function (pattern, index, inGlobStar, cb) {\n assert(this instanceof Glob)\n assert(typeof cb === 'function')\n\n if (this.aborted)\n return\n\n this._processing++\n if (this.paused) {\n this._processQueue.push([pattern, index, inGlobStar, cb])\n return\n }\n\n //console.error('PROCESS %d', this._processing, pattern)\n\n // Get the first [n] parts of pattern that are all strings.\n var n = 0\n while (typeof pattern[n] === 'string') {\n n ++\n }\n // now n is the index of the first one that is *not* a string.\n\n // see if there's anything else\n var prefix\n switch (n) {\n // if not, then this is rather simple\n case pattern.length:\n this._processSimple(pattern.join('/'), index, cb)\n return\n\n case 0:\n // pattern *starts* with some non-trivial item.\n // going to readdir(cwd), but not include the prefix in matches.\n prefix = null\n break\n\n default:\n // pattern has some string bits in the front.\n // whatever it starts with, whether that's 'absolute' like /foo/bar,\n // or 'relative' like '../baz'\n prefix = pattern.slice(0, n).join('/')\n break\n }\n\n var remain = pattern.slice(n)\n\n // get the list of entries.\n var read\n if (prefix === null)\n read = '.'\n else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {\n if (!prefix || !isAbsolute(prefix))\n prefix = '/' + prefix\n read = prefix\n } else\n read = prefix\n\n var abs = this._makeAbs(read)\n\n //if ignored, skip _processing\n if (childrenIgnored(this, read))\n return cb()\n\n var isGlobStar = remain[0] === minimatch.GLOBSTAR\n if (isGlobStar)\n this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb)\n else\n this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb)\n}\n\nGlob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {\n var self = this\n this._readdir(abs, inGlobStar, function (er, entries) {\n return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)\n })\n}\n\nGlob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {\n\n // if the abs isn't a dir, then nothing can match!\n if (!entries)\n return cb()\n\n // It will only match dot entries if it starts with a dot, or if\n // dot is set. Stuff like @(.foo|.bar) isn't allowed.\n var pn = remain[0]\n var negate = !!this.minimatch.negate\n var rawGlob = pn._glob\n var dotOk = this.dot || rawGlob.charAt(0) === '.'\n\n var matchedEntries = []\n for (var i = 0; i < entries.length; i++) {\n var e = entries[i]\n if (e.charAt(0) !== '.' || dotOk) {\n var m\n if (negate && !prefix) {\n m = !e.match(pn)\n } else {\n m = e.match(pn)\n }\n if (m)\n matchedEntries.push(e)\n }\n }\n\n //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)\n\n var len = matchedEntries.length\n // If there are no matched entries, then nothing matches.\n if (len === 0)\n return cb()\n\n // if this is the last remaining pattern bit, then no need for\n // an additional stat *unless* the user has specified mark or\n // stat explicitly. We know they exist, since readdir returned\n // them.\n\n if (remain.length === 1 && !this.mark && !this.stat) {\n if (!this.matches[index])\n this.matches[index] = Object.create(null)\n\n for (var i = 0; i < len; i ++) {\n var e = matchedEntries[i]\n if (prefix) {\n if (prefix !== '/')\n e = prefix + '/' + e\n else\n e = prefix + e\n }\n\n if (e.charAt(0) === '/' && !this.nomount) {\n e = path.join(this.root, e)\n }\n this._emitMatch(index, e)\n }\n // This was the last one, and no stats were needed\n return cb()\n }\n\n // now test all matched entries as stand-ins for that part\n // of the pattern.\n remain.shift()\n for (var i = 0; i < len; i ++) {\n var e = matchedEntries[i]\n var newPattern\n if (prefix) {\n if (prefix !== '/')\n e = prefix + '/' + e\n else\n e = prefix + e\n }\n this._process([e].concat(remain), index, inGlobStar, cb)\n }\n cb()\n}\n\nGlob.prototype._emitMatch = function (index, e) {\n if (this.aborted)\n return\n\n if (isIgnored(this, e))\n return\n\n if (this.paused) {\n this._emitQueue.push([index, e])\n return\n }\n\n var abs = isAbsolute(e) ? e : this._makeAbs(e)\n\n if (this.mark)\n e = this._mark(e)\n\n if (this.absolute)\n e = abs\n\n if (this.matches[index][e])\n return\n\n if (this.nodir) {\n var c = this.cache[abs]\n if (c === 'DIR' || Array.isArray(c))\n return\n }\n\n this.matches[index][e] = true\n\n var st = this.statCache[abs]\n if (st)\n this.emit('stat', e, st)\n\n this.emit('match', e)\n}\n\nGlob.prototype._readdirInGlobStar = function (abs, cb) {\n if (this.aborted)\n return\n\n // follow all symlinked directories forever\n // just proceed as if this is a non-globstar situation\n if (this.follow)\n return this._readdir(abs, false, cb)\n\n var lstatkey = 'lstat\\0' + abs\n var self = this\n var lstatcb = inflight(lstatkey, lstatcb_)\n\n if (lstatcb)\n fs.lstat(abs, lstatcb)\n\n function lstatcb_ (er, lstat) {\n if (er && er.code === 'ENOENT')\n return cb()\n\n var isSym = lstat && lstat.isSymbolicLink()\n self.symlinks[abs] = isSym\n\n // If it's not a symlink or a dir, then it's definitely a regular file.\n // don't bother doing a readdir in that case.\n if (!isSym && lstat && !lstat.isDirectory()) {\n self.cache[abs] = 'FILE'\n cb()\n } else\n self._readdir(abs, false, cb)\n }\n}\n\nGlob.prototype._readdir = function (abs, inGlobStar, cb) {\n if (this.aborted)\n return\n\n cb = inflight('readdir\\0'+abs+'\\0'+inGlobStar, cb)\n if (!cb)\n return\n\n //console.error('RD %j %j', +inGlobStar, abs)\n if (inGlobStar && !ownProp(this.symlinks, abs))\n return this._readdirInGlobStar(abs, cb)\n\n if (ownProp(this.cache, abs)) {\n var c = this.cache[abs]\n if (!c || c === 'FILE')\n return cb()\n\n if (Array.isArray(c))\n return cb(null, c)\n }\n\n var self = this\n fs.readdir(abs, readdirCb(this, abs, cb))\n}\n\nfunction readdirCb (self, abs, cb) {\n return function (er, entries) {\n if (er)\n self._readdirError(abs, er, cb)\n else\n self._readdirEntries(abs, entries, cb)\n }\n}\n\nGlob.prototype._readdirEntries = function (abs, entries, cb) {\n if (this.aborted)\n return\n\n // if we haven't asked to stat everything, then just\n // assume that everything in there exists, so we can avoid\n // having to stat it a second time.\n if (!this.mark && !this.stat) {\n for (var i = 0; i < entries.length; i ++) {\n var e = entries[i]\n if (abs === '/')\n e = abs + e\n else\n e = abs + '/' + e\n this.cache[e] = true\n }\n }\n\n this.cache[abs] = entries\n return cb(null, entries)\n}\n\nGlob.prototype._readdirError = function (f, er, cb) {\n if (this.aborted)\n return\n\n // handle errors, and cache the information\n switch (er.code) {\n case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205\n case 'ENOTDIR': // totally normal. means it *does* exist.\n var abs = this._makeAbs(f)\n this.cache[abs] = 'FILE'\n if (abs === this.cwdAbs) {\n var error = new Error(er.code + ' invalid cwd ' + this.cwd)\n error.path = this.cwd\n error.code = er.code\n this.emit('error', error)\n this.abort()\n }\n break\n\n case 'ENOENT': // not terribly unusual\n case 'ELOOP':\n case 'ENAMETOOLONG':\n case 'UNKNOWN':\n this.cache[this._makeAbs(f)] = false\n break\n\n default: // some unusual error. Treat as failure.\n this.cache[this._makeAbs(f)] = false\n if (this.strict) {\n this.emit('error', er)\n // If the error is handled, then we abort\n // if not, we threw out of here\n this.abort()\n }\n if (!this.silent)\n console.error('glob error', er)\n break\n }\n\n return cb()\n}\n\nGlob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {\n var self = this\n this._readdir(abs, inGlobStar, function (er, entries) {\n self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb)\n })\n}\n\n\nGlob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {\n //console.error('pgs2', prefix, remain[0], entries)\n\n // no entries means not a dir, so it can never have matches\n // foo.txt/** doesn't match foo.txt\n if (!entries)\n return cb()\n\n // test without the globstar, and with every child both below\n // and replacing the globstar.\n var remainWithoutGlobStar = remain.slice(1)\n var gspref = prefix ? [ prefix ] : []\n var noGlobStar = gspref.concat(remainWithoutGlobStar)\n\n // the noGlobStar pattern exits the inGlobStar state\n this._process(noGlobStar, index, false, cb)\n\n var isSym = this.symlinks[abs]\n var len = entries.length\n\n // If it's a symlink, and we're in a globstar, then stop\n if (isSym && inGlobStar)\n return cb()\n\n for (var i = 0; i < len; i++) {\n var e = entries[i]\n if (e.charAt(0) === '.' && !this.dot)\n continue\n\n // these two cases enter the inGlobStar state\n var instead = gspref.concat(entries[i], remainWithoutGlobStar)\n this._process(instead, index, true, cb)\n\n var below = gspref.concat(entries[i], remain)\n this._process(below, index, true, cb)\n }\n\n cb()\n}\n\nGlob.prototype._processSimple = function (prefix, index, cb) {\n // XXX review this. Shouldn't it be doing the mounting etc\n // before doing stat? kinda weird?\n var self = this\n this._stat(prefix, function (er, exists) {\n self._processSimple2(prefix, index, er, exists, cb)\n })\n}\nGlob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {\n\n //console.error('ps2', prefix, exists)\n\n if (!this.matches[index])\n this.matches[index] = Object.create(null)\n\n // If it doesn't exist, then just mark the lack of results\n if (!exists)\n return cb()\n\n if (prefix && isAbsolute(prefix) && !this.nomount) {\n var trail = /[\\/\\\\]$/.test(prefix)\n if (prefix.charAt(0) === '/') {\n prefix = path.join(this.root, prefix)\n } else {\n prefix = path.resolve(this.root, prefix)\n if (trail)\n prefix += '/'\n }\n }\n\n if (process.platform === 'win32')\n prefix = prefix.replace(/\\\\/g, '/')\n\n // Mark this as a match\n this._emitMatch(index, prefix)\n cb()\n}\n\n// Returns either 'DIR', 'FILE', or false\nGlob.prototype._stat = function (f, cb) {\n var abs = this._makeAbs(f)\n var needDir = f.slice(-1) === '/'\n\n if (f.length > this.maxLength)\n return cb()\n\n if (!this.stat && ownProp(this.cache, abs)) {\n var c = this.cache[abs]\n\n if (Array.isArray(c))\n c = 'DIR'\n\n // It exists, but maybe not how we need it\n if (!needDir || c === 'DIR')\n return cb(null, c)\n\n if (needDir && c === 'FILE')\n return cb()\n\n // otherwise we have to stat, because maybe c=true\n // if we know it exists, but not what it is.\n }\n\n var exists\n var stat = this.statCache[abs]\n if (stat !== undefined) {\n if (stat === false)\n return cb(null, stat)\n else {\n var type = stat.isDirectory() ? 'DIR' : 'FILE'\n if (needDir && type === 'FILE')\n return cb()\n else\n return cb(null, type, stat)\n }\n }\n\n var self = this\n var statcb = inflight('stat\\0' + abs, lstatcb_)\n if (statcb)\n fs.lstat(abs, statcb)\n\n function lstatcb_ (er, lstat) {\n if (lstat && lstat.isSymbolicLink()) {\n // If it's a symlink, then treat it as the target, unless\n // the target does not exist, then treat it as a file.\n return fs.stat(abs, function (er, stat) {\n if (er)\n self._stat2(f, abs, null, lstat, cb)\n else\n self._stat2(f, abs, er, stat, cb)\n })\n } else {\n self._stat2(f, abs, er, lstat, cb)\n }\n }\n}\n\nGlob.prototype._stat2 = function (f, abs, er, stat, cb) {\n if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {\n this.statCache[abs] = false\n return cb()\n }\n\n var needDir = f.slice(-1) === '/'\n this.statCache[abs] = stat\n\n if (abs.slice(-1) === '/' && stat && !stat.isDirectory())\n return cb(null, false, stat)\n\n var c = true\n if (stat)\n c = stat.isDirectory() ? 'DIR' : 'FILE'\n this.cache[abs] = this.cache[abs] || c\n\n if (needDir && c === 'FILE')\n return cb()\n\n return cb(null, c, stat)\n}\n","module.exports = globSync\nglobSync.GlobSync = GlobSync\n\nvar fs = require('fs')\nvar rp = require('fs.realpath')\nvar minimatch = require('minimatch')\nvar Minimatch = minimatch.Minimatch\nvar Glob = require('./glob.js').Glob\nvar util = require('util')\nvar path = require('path')\nvar assert = require('assert')\nvar isAbsolute = require('path-is-absolute')\nvar common = require('./common.js')\nvar alphasort = common.alphasort\nvar alphasorti = common.alphasorti\nvar setopts = common.setopts\nvar ownProp = common.ownProp\nvar childrenIgnored = common.childrenIgnored\nvar isIgnored = common.isIgnored\n\nfunction globSync (pattern, options) {\n if (typeof options === 'function' || arguments.length === 3)\n throw new TypeError('callback provided to sync glob\\n'+\n 'See: https://github.com/isaacs/node-glob/issues/167')\n\n return new GlobSync(pattern, options).found\n}\n\nfunction GlobSync (pattern, options) {\n if (!pattern)\n throw new Error('must provide pattern')\n\n if (typeof options === 'function' || arguments.length === 3)\n throw new TypeError('callback provided to sync glob\\n'+\n 'See: https://github.com/isaacs/node-glob/issues/167')\n\n if (!(this instanceof GlobSync))\n return new GlobSync(pattern, options)\n\n setopts(this, pattern, options)\n\n if (this.noprocess)\n return this\n\n var n = this.minimatch.set.length\n this.matches = new Array(n)\n for (var i = 0; i < n; i ++) {\n this._process(this.minimatch.set[i], i, false)\n }\n this._finish()\n}\n\nGlobSync.prototype._finish = function () {\n assert(this instanceof GlobSync)\n if (this.realpath) {\n var self = this\n this.matches.forEach(function (matchset, index) {\n var set = self.matches[index] = Object.create(null)\n for (var p in matchset) {\n try {\n p = self._makeAbs(p)\n var real = rp.realpathSync(p, self.realpathCache)\n set[real] = true\n } catch (er) {\n if (er.syscall === 'stat')\n set[self._makeAbs(p)] = true\n else\n throw er\n }\n }\n })\n }\n common.finish(this)\n}\n\n\nGlobSync.prototype._process = function (pattern, index, inGlobStar) {\n assert(this instanceof GlobSync)\n\n // Get the first [n] parts of pattern that are all strings.\n var n = 0\n while (typeof pattern[n] === 'string') {\n n ++\n }\n // now n is the index of the first one that is *not* a string.\n\n // See if there's anything else\n var prefix\n switch (n) {\n // if not, then this is rather simple\n case pattern.length:\n this._processSimple(pattern.join('/'), index)\n return\n\n case 0:\n // pattern *starts* with some non-trivial item.\n // going to readdir(cwd), but not include the prefix in matches.\n prefix = null\n break\n\n default:\n // pattern has some string bits in the front.\n // whatever it starts with, whether that's 'absolute' like /foo/bar,\n // or 'relative' like '../baz'\n prefix = pattern.slice(0, n).join('/')\n break\n }\n\n var remain = pattern.slice(n)\n\n // get the list of entries.\n var read\n if (prefix === null)\n read = '.'\n else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {\n if (!prefix || !isAbsolute(prefix))\n prefix = '/' + prefix\n read = prefix\n } else\n read = prefix\n\n var abs = this._makeAbs(read)\n\n //if ignored, skip processing\n if (childrenIgnored(this, read))\n return\n\n var isGlobStar = remain[0] === minimatch.GLOBSTAR\n if (isGlobStar)\n this._processGlobStar(prefix, read, abs, remain, index, inGlobStar)\n else\n this._processReaddir(prefix, read, abs, remain, index, inGlobStar)\n}\n\n\nGlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {\n var entries = this._readdir(abs, inGlobStar)\n\n // if the abs isn't a dir, then nothing can match!\n if (!entries)\n return\n\n // It will only match dot entries if it starts with a dot, or if\n // dot is set. Stuff like @(.foo|.bar) isn't allowed.\n var pn = remain[0]\n var negate = !!this.minimatch.negate\n var rawGlob = pn._glob\n var dotOk = this.dot || rawGlob.charAt(0) === '.'\n\n var matchedEntries = []\n for (var i = 0; i < entries.length; i++) {\n var e = entries[i]\n if (e.charAt(0) !== '.' || dotOk) {\n var m\n if (negate && !prefix) {\n m = !e.match(pn)\n } else {\n m = e.match(pn)\n }\n if (m)\n matchedEntries.push(e)\n }\n }\n\n var len = matchedEntries.length\n // If there are no matched entries, then nothing matches.\n if (len === 0)\n return\n\n // if this is the last remaining pattern bit, then no need for\n // an additional stat *unless* the user has specified mark or\n // stat explicitly. We know they exist, since readdir returned\n // them.\n\n if (remain.length === 1 && !this.mark && !this.stat) {\n if (!this.matches[index])\n this.matches[index] = Object.create(null)\n\n for (var i = 0; i < len; i ++) {\n var e = matchedEntries[i]\n if (prefix) {\n if (prefix.slice(-1) !== '/')\n e = prefix + '/' + e\n else\n e = prefix + e\n }\n\n if (e.charAt(0) === '/' && !this.nomount) {\n e = path.join(this.root, e)\n }\n this._emitMatch(index, e)\n }\n // This was the last one, and no stats were needed\n return\n }\n\n // now test all matched entries as stand-ins for that part\n // of the pattern.\n remain.shift()\n for (var i = 0; i < len; i ++) {\n var e = matchedEntries[i]\n var newPattern\n if (prefix)\n newPattern = [prefix, e]\n else\n newPattern = [e]\n this._process(newPattern.concat(remain), index, inGlobStar)\n }\n}\n\n\nGlobSync.prototype._emitMatch = function (index, e) {\n if (isIgnored(this, e))\n return\n\n var abs = this._makeAbs(e)\n\n if (this.mark)\n e = this._mark(e)\n\n if (this.absolute) {\n e = abs\n }\n\n if (this.matches[index][e])\n return\n\n if (this.nodir) {\n var c = this.cache[abs]\n if (c === 'DIR' || Array.isArray(c))\n return\n }\n\n this.matches[index][e] = true\n\n if (this.stat)\n this._stat(e)\n}\n\n\nGlobSync.prototype._readdirInGlobStar = function (abs) {\n // follow all symlinked directories forever\n // just proceed as if this is a non-globstar situation\n if (this.follow)\n return this._readdir(abs, false)\n\n var entries\n var lstat\n var stat\n try {\n lstat = fs.lstatSync(abs)\n } catch (er) {\n if (er.code === 'ENOENT') {\n // lstat failed, doesn't exist\n return null\n }\n }\n\n var isSym = lstat && lstat.isSymbolicLink()\n this.symlinks[abs] = isSym\n\n // If it's not a symlink or a dir, then it's definitely a regular file.\n // don't bother doing a readdir in that case.\n if (!isSym && lstat && !lstat.isDirectory())\n this.cache[abs] = 'FILE'\n else\n entries = this._readdir(abs, false)\n\n return entries\n}\n\nGlobSync.prototype._readdir = function (abs, inGlobStar) {\n var entries\n\n if (inGlobStar && !ownProp(this.symlinks, abs))\n return this._readdirInGlobStar(abs)\n\n if (ownProp(this.cache, abs)) {\n var c = this.cache[abs]\n if (!c || c === 'FILE')\n return null\n\n if (Array.isArray(c))\n return c\n }\n\n try {\n return this._readdirEntries(abs, fs.readdirSync(abs))\n } catch (er) {\n this._readdirError(abs, er)\n return null\n }\n}\n\nGlobSync.prototype._readdirEntries = function (abs, entries) {\n // if we haven't asked to stat everything, then just\n // assume that everything in there exists, so we can avoid\n // having to stat it a second time.\n if (!this.mark && !this.stat) {\n for (var i = 0; i < entries.length; i ++) {\n var e = entries[i]\n if (abs === '/')\n e = abs + e\n else\n e = abs + '/' + e\n this.cache[e] = true\n }\n }\n\n this.cache[abs] = entries\n\n // mark and cache dir-ness\n return entries\n}\n\nGlobSync.prototype._readdirError = function (f, er) {\n // handle errors, and cache the information\n switch (er.code) {\n case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205\n case 'ENOTDIR': // totally normal. means it *does* exist.\n var abs = this._makeAbs(f)\n this.cache[abs] = 'FILE'\n if (abs === this.cwdAbs) {\n var error = new Error(er.code + ' invalid cwd ' + this.cwd)\n error.path = this.cwd\n error.code = er.code\n throw error\n }\n break\n\n case 'ENOENT': // not terribly unusual\n case 'ELOOP':\n case 'ENAMETOOLONG':\n case 'UNKNOWN':\n this.cache[this._makeAbs(f)] = false\n break\n\n default: // some unusual error. Treat as failure.\n this.cache[this._makeAbs(f)] = false\n if (this.strict)\n throw er\n if (!this.silent)\n console.error('glob error', er)\n break\n }\n}\n\nGlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {\n\n var entries = this._readdir(abs, inGlobStar)\n\n // no entries means not a dir, so it can never have matches\n // foo.txt/** doesn't match foo.txt\n if (!entries)\n return\n\n // test without the globstar, and with every child both below\n // and replacing the globstar.\n var remainWithoutGlobStar = remain.slice(1)\n var gspref = prefix ? [ prefix ] : []\n var noGlobStar = gspref.concat(remainWithoutGlobStar)\n\n // the noGlobStar pattern exits the inGlobStar state\n this._process(noGlobStar, index, false)\n\n var len = entries.length\n var isSym = this.symlinks[abs]\n\n // If it's a symlink, and we're in a globstar, then stop\n if (isSym && inGlobStar)\n return\n\n for (var i = 0; i < len; i++) {\n var e = entries[i]\n if (e.charAt(0) === '.' && !this.dot)\n continue\n\n // these two cases enter the inGlobStar state\n var instead = gspref.concat(entries[i], remainWithoutGlobStar)\n this._process(instead, index, true)\n\n var below = gspref.concat(entries[i], remain)\n this._process(below, index, true)\n }\n}\n\nGlobSync.prototype._processSimple = function (prefix, index) {\n // XXX review this. Shouldn't it be doing the mounting etc\n // before doing stat? kinda weird?\n var exists = this._stat(prefix)\n\n if (!this.matches[index])\n this.matches[index] = Object.create(null)\n\n // If it doesn't exist, then just mark the lack of results\n if (!exists)\n return\n\n if (prefix && isAbsolute(prefix) && !this.nomount) {\n var trail = /[\\/\\\\]$/.test(prefix)\n if (prefix.charAt(0) === '/') {\n prefix = path.join(this.root, prefix)\n } else {\n prefix = path.resolve(this.root, prefix)\n if (trail)\n prefix += '/'\n }\n }\n\n if (process.platform === 'win32')\n prefix = prefix.replace(/\\\\/g, '/')\n\n // Mark this as a match\n this._emitMatch(index, prefix)\n}\n\n// Returns either 'DIR', 'FILE', or false\nGlobSync.prototype._stat = function (f) {\n var abs = this._makeAbs(f)\n var needDir = f.slice(-1) === '/'\n\n if (f.length > this.maxLength)\n return false\n\n if (!this.stat && ownProp(this.cache, abs)) {\n var c = this.cache[abs]\n\n if (Array.isArray(c))\n c = 'DIR'\n\n // It exists, but maybe not how we need it\n if (!needDir || c === 'DIR')\n return c\n\n if (needDir && c === 'FILE')\n return false\n\n // otherwise we have to stat, because maybe c=true\n // if we know it exists, but not what it is.\n }\n\n var exists\n var stat = this.statCache[abs]\n if (!stat) {\n var lstat\n try {\n lstat = fs.lstatSync(abs)\n } catch (er) {\n if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {\n this.statCache[abs] = false\n return false\n }\n }\n\n if (lstat && lstat.isSymbolicLink()) {\n try {\n stat = fs.statSync(abs)\n } catch (er) {\n stat = lstat\n }\n } else {\n stat = lstat\n }\n }\n\n this.statCache[abs] = stat\n\n var c = true\n if (stat)\n c = stat.isDirectory() ? 'DIR' : 'FILE'\n\n this.cache[abs] = this.cache[abs] || c\n\n if (needDir && c === 'FILE')\n return false\n\n return c\n}\n\nGlobSync.prototype._mark = function (p) {\n return common.mark(this, p)\n}\n\nGlobSync.prototype._makeAbs = function (f) {\n return common.makeAbs(this, f)\n}\n","\"use strict\";\n// Copyright 2012 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AuthClient = void 0;\nconst events_1 = require(\"events\");\nconst transporters_1 = require(\"../transporters\");\nclass AuthClient extends events_1.EventEmitter {\n constructor() {\n super(...arguments);\n this.transporter = new transporters_1.DefaultTransporter();\n this.credentials = {};\n }\n /**\n * Sets the auth credentials.\n */\n setCredentials(credentials) {\n this.credentials = credentials;\n }\n /**\n * Append additional headers, e.g., x-goog-user-project, shared across the\n * classes inheriting AuthClient. This method should be used by any method\n * that overrides getRequestMetadataAsync(), which is a shared helper for\n * setting request information in both gRPC and HTTP API calls.\n *\n * @param headers objedcdt to append additional headers to.\n */\n addSharedMetadataHeaders(headers) {\n // quota_project_id, stored in application_default_credentials.json, is set in\n // the x-goog-user-project header, to indicate an alternate account for\n // billing and quota:\n if (!headers['x-goog-user-project'] && // don't override a value the user sets.\n this.quotaProjectId) {\n headers['x-goog-user-project'] = this.quotaProjectId;\n }\n return headers;\n }\n}\nexports.AuthClient = AuthClient;\n//# sourceMappingURL=authclient.js.map","\"use strict\";\n// Copyright 2013 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Compute = void 0;\nconst arrify = require(\"arrify\");\nconst gcpMetadata = require(\"gcp-metadata\");\nconst oauth2client_1 = require(\"./oauth2client\");\nclass Compute extends oauth2client_1.OAuth2Client {\n /**\n * Google Compute Engine service account credentials.\n *\n * Retrieve access token from the metadata server.\n * See: https://developers.google.com/compute/docs/authentication\n */\n constructor(options = {}) {\n super(options);\n // Start with an expired refresh token, which will automatically be\n // refreshed before the first API call is made.\n this.credentials = { expiry_date: 1, refresh_token: 'compute-placeholder' };\n this.serviceAccountEmail = options.serviceAccountEmail || 'default';\n this.scopes = arrify(options.scopes);\n }\n /**\n * Refreshes the access token.\n * @param refreshToken Unused parameter\n */\n async refreshTokenNoCache(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n refreshToken) {\n const tokenPath = `service-accounts/${this.serviceAccountEmail}/token`;\n let data;\n try {\n const instanceOptions = {\n property: tokenPath,\n };\n if (this.scopes.length > 0) {\n instanceOptions.params = {\n scopes: this.scopes.join(','),\n };\n }\n data = await gcpMetadata.instance(instanceOptions);\n }\n catch (e) {\n e.message = `Could not refresh access token: ${e.message}`;\n this.wrapError(e);\n throw e;\n }\n const tokens = data;\n if (data && data.expires_in) {\n tokens.expiry_date = new Date().getTime() + data.expires_in * 1000;\n delete tokens.expires_in;\n }\n this.emit('tokens', tokens);\n return { tokens, res: null };\n }\n /**\n * Fetches an ID token.\n * @param targetAudience the audience for the fetched ID token.\n */\n async fetchIdToken(targetAudience) {\n const idTokenPath = `service-accounts/${this.serviceAccountEmail}/identity` +\n `?format=full&audience=${targetAudience}`;\n let idToken;\n try {\n const instanceOptions = {\n property: idTokenPath,\n };\n idToken = await gcpMetadata.instance(instanceOptions);\n }\n catch (e) {\n e.message = `Could not fetch ID token: ${e.message}`;\n throw e;\n }\n return idToken;\n }\n wrapError(e) {\n const res = e.response;\n if (res && res.status) {\n e.code = res.status.toString();\n if (res.status === 403) {\n e.message =\n 'A Forbidden error was returned while attempting to retrieve an access ' +\n 'token for the Compute Engine built-in service account. This may be because the Compute ' +\n 'Engine instance does not have the correct permission scopes specified: ' +\n e.message;\n }\n else if (res.status === 404) {\n e.message =\n 'A Not Found error was returned while attempting to retrieve an access' +\n 'token for the Compute Engine built-in service account. This may be because the Compute ' +\n 'Engine instance does not have any permission scopes specified: ' +\n e.message;\n }\n }\n }\n}\nexports.Compute = Compute;\n//# sourceMappingURL=computeclient.js.map","\"use strict\";\n// Copyright 2018 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getEnv = exports.clear = exports.GCPEnv = void 0;\nconst gcpMetadata = require(\"gcp-metadata\");\nvar GCPEnv;\n(function (GCPEnv) {\n GCPEnv[\"APP_ENGINE\"] = \"APP_ENGINE\";\n GCPEnv[\"KUBERNETES_ENGINE\"] = \"KUBERNETES_ENGINE\";\n GCPEnv[\"CLOUD_FUNCTIONS\"] = \"CLOUD_FUNCTIONS\";\n GCPEnv[\"COMPUTE_ENGINE\"] = \"COMPUTE_ENGINE\";\n GCPEnv[\"NONE\"] = \"NONE\";\n})(GCPEnv = exports.GCPEnv || (exports.GCPEnv = {}));\nlet envPromise;\nfunction clear() {\n envPromise = undefined;\n}\nexports.clear = clear;\nasync function getEnv() {\n if (envPromise) {\n return envPromise;\n }\n envPromise = getEnvMemoized();\n return envPromise;\n}\nexports.getEnv = getEnv;\nasync function getEnvMemoized() {\n let env = GCPEnv.NONE;\n if (isAppEngine()) {\n env = GCPEnv.APP_ENGINE;\n }\n else if (isCloudFunction()) {\n env = GCPEnv.CLOUD_FUNCTIONS;\n }\n else if (await isComputeEngine()) {\n if (await isKubernetesEngine()) {\n env = GCPEnv.KUBERNETES_ENGINE;\n }\n else {\n env = GCPEnv.COMPUTE_ENGINE;\n }\n }\n else {\n env = GCPEnv.NONE;\n }\n return env;\n}\nfunction isAppEngine() {\n return !!(process.env.GAE_SERVICE || process.env.GAE_MODULE_NAME);\n}\nfunction isCloudFunction() {\n return !!(process.env.FUNCTION_NAME || process.env.FUNCTION_TARGET);\n}\nasync function isKubernetesEngine() {\n try {\n await gcpMetadata.instance('attributes/cluster-name');\n return true;\n }\n catch (e) {\n return false;\n }\n}\nasync function isComputeEngine() {\n return gcpMetadata.isAvailable();\n}\n//# sourceMappingURL=envDetect.js.map","\"use strict\";\n// Copyright 2019 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.GoogleAuth = exports.CLOUD_SDK_CLIENT_ID = void 0;\nconst child_process_1 = require(\"child_process\");\nconst fs = require(\"fs\");\nconst gcpMetadata = require(\"gcp-metadata\");\nconst os = require(\"os\");\nconst path = require(\"path\");\nconst crypto_1 = require(\"../crypto/crypto\");\nconst transporters_1 = require(\"../transporters\");\nconst computeclient_1 = require(\"./computeclient\");\nconst idtokenclient_1 = require(\"./idtokenclient\");\nconst envDetect_1 = require(\"./envDetect\");\nconst jwtclient_1 = require(\"./jwtclient\");\nconst refreshclient_1 = require(\"./refreshclient\");\nexports.CLOUD_SDK_CLIENT_ID = '764086051850-6qr4p6gpi6hn506pt8ejuq83di341hur.apps.googleusercontent.com';\nclass GoogleAuth {\n constructor(opts) {\n /**\n * Caches a value indicating whether the auth layer is running on Google\n * Compute Engine.\n * @private\n */\n this.checkIsGCE = undefined;\n // To save the contents of the JSON credential file\n this.jsonContent = null;\n this.cachedCredential = null;\n opts = opts || {};\n this._cachedProjectId = opts.projectId || null;\n this.keyFilename = opts.keyFilename || opts.keyFile;\n this.scopes = opts.scopes;\n this.jsonContent = opts.credentials || null;\n this.clientOptions = opts.clientOptions;\n }\n // Note: this properly is only public to satisify unit tests.\n // https://github.com/Microsoft/TypeScript/issues/5228\n get isGCE() {\n return this.checkIsGCE;\n }\n getProjectId(callback) {\n if (callback) {\n this.getProjectIdAsync().then(r => callback(null, r), callback);\n }\n else {\n return this.getProjectIdAsync();\n }\n }\n getProjectIdAsync() {\n if (this._cachedProjectId) {\n return Promise.resolve(this._cachedProjectId);\n }\n // In implicit case, supports three environments. In order of precedence,\n // the implicit environments are:\n // - GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variable\n // - GOOGLE_APPLICATION_CREDENTIALS JSON file\n // - Cloud SDK: `gcloud config config-helper --format json`\n // - GCE project ID from metadata server)\n if (!this._getDefaultProjectIdPromise) {\n // TODO: refactor the below code so that it doesn't mix and match\n // promises and async/await.\n this._getDefaultProjectIdPromise = new Promise(\n // eslint-disable-next-line no-async-promise-executor\n async (resolve, reject) => {\n try {\n const projectId = this.getProductionProjectId() ||\n (await this.getFileProjectId()) ||\n (await this.getDefaultServiceProjectId()) ||\n (await this.getGCEProjectId());\n this._cachedProjectId = projectId;\n if (!projectId) {\n throw new Error('Unable to detect a Project Id in the current environment. \\n' +\n 'To learn more about authentication and Google APIs, visit: \\n' +\n 'https://cloud.google.com/docs/authentication/getting-started');\n }\n resolve(projectId);\n }\n catch (e) {\n reject(e);\n }\n });\n }\n return this._getDefaultProjectIdPromise;\n }\n getApplicationDefault(optionsOrCallback = {}, callback) {\n let options;\n if (typeof optionsOrCallback === 'function') {\n callback = optionsOrCallback;\n }\n else {\n options = optionsOrCallback;\n }\n if (callback) {\n this.getApplicationDefaultAsync(options).then(r => callback(null, r.credential, r.projectId), callback);\n }\n else {\n return this.getApplicationDefaultAsync(options);\n }\n }\n async getApplicationDefaultAsync(options = {}) {\n // If we've already got a cached credential, just return it.\n if (this.cachedCredential) {\n return {\n credential: this.cachedCredential,\n projectId: await this.getProjectIdAsync(),\n };\n }\n let credential;\n let projectId;\n // Check for the existence of a local environment variable pointing to the\n // location of the credential file. This is typically used in local\n // developer scenarios.\n credential = await this._tryGetApplicationCredentialsFromEnvironmentVariable(options);\n if (credential) {\n if (credential instanceof jwtclient_1.JWT) {\n credential.defaultScopes = this.defaultScopes;\n credential.scopes = this.scopes;\n }\n this.cachedCredential = credential;\n projectId = await this.getProjectId();\n return { credential, projectId };\n }\n // Look in the well-known credential file location.\n credential = await this._tryGetApplicationCredentialsFromWellKnownFile(options);\n if (credential) {\n if (credential instanceof jwtclient_1.JWT) {\n credential.defaultScopes = this.defaultScopes;\n credential.scopes = this.scopes;\n }\n this.cachedCredential = credential;\n projectId = await this.getProjectId();\n return { credential, projectId };\n }\n // Determine if we're running on GCE.\n let isGCE;\n try {\n isGCE = await this._checkIsGCE();\n }\n catch (e) {\n e.message = `Unexpected error determining execution environment: ${e.message}`;\n throw e;\n }\n if (!isGCE) {\n // We failed to find the default credentials. Bail out with an error.\n throw new Error('Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.');\n }\n // For GCE, just return a default ComputeClient. It will take care of\n // the rest.\n options.scopes = this.scopes || this.defaultScopes;\n this.cachedCredential = new computeclient_1.Compute(options);\n projectId = await this.getProjectId();\n return { projectId, credential: this.cachedCredential };\n }\n /**\n * Determines whether the auth layer is running on Google Compute Engine.\n * @returns A promise that resolves with the boolean.\n * @api private\n */\n async _checkIsGCE() {\n if (this.checkIsGCE === undefined) {\n this.checkIsGCE = await gcpMetadata.isAvailable();\n }\n return this.checkIsGCE;\n }\n /**\n * Attempts to load default credentials from the environment variable path..\n * @returns Promise that resolves with the OAuth2Client or null.\n * @api private\n */\n async _tryGetApplicationCredentialsFromEnvironmentVariable(options) {\n const credentialsPath = process.env['GOOGLE_APPLICATION_CREDENTIALS'] ||\n process.env['google_application_credentials'];\n if (!credentialsPath || credentialsPath.length === 0) {\n return null;\n }\n try {\n return this._getApplicationCredentialsFromFilePath(credentialsPath, options);\n }\n catch (e) {\n e.message = `Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${e.message}`;\n throw e;\n }\n }\n /**\n * Attempts to load default credentials from a well-known file location\n * @return Promise that resolves with the OAuth2Client or null.\n * @api private\n */\n async _tryGetApplicationCredentialsFromWellKnownFile(options) {\n // First, figure out the location of the file, depending upon the OS type.\n let location = null;\n if (this._isWindows()) {\n // Windows\n location = process.env['APPDATA'];\n }\n else {\n // Linux or Mac\n const home = process.env['HOME'];\n if (home) {\n location = path.join(home, '.config');\n }\n }\n // If we found the root path, expand it.\n if (location) {\n location = path.join(location, 'gcloud', 'application_default_credentials.json');\n if (!fs.existsSync(location)) {\n location = null;\n }\n }\n // The file does not exist.\n if (!location) {\n return null;\n }\n // The file seems to exist. Try to use it.\n const client = await this._getApplicationCredentialsFromFilePath(location, options);\n return client;\n }\n /**\n * Attempts to load default credentials from a file at the given path..\n * @param filePath The path to the file to read.\n * @returns Promise that resolves with the OAuth2Client\n * @api private\n */\n async _getApplicationCredentialsFromFilePath(filePath, options = {}) {\n // Make sure the path looks like a string.\n if (!filePath || filePath.length === 0) {\n throw new Error('The file path is invalid.');\n }\n // Make sure there is a file at the path. lstatSync will throw if there is\n // nothing there.\n try {\n // Resolve path to actual file in case of symlink. Expect a thrown error\n // if not resolvable.\n filePath = fs.realpathSync(filePath);\n if (!fs.lstatSync(filePath).isFile()) {\n throw new Error();\n }\n }\n catch (err) {\n err.message = `The file at ${filePath} does not exist, or it is not a file. ${err.message}`;\n throw err;\n }\n // Now open a read stream on the file, and parse it.\n const readStream = fs.createReadStream(filePath);\n return this.fromStream(readStream, options);\n }\n /**\n * Create a credentials instance using the given input options.\n * @param json The input object.\n * @param options The JWT or UserRefresh options for the client\n * @returns JWT or UserRefresh Client with data\n */\n fromJSON(json, options) {\n let client;\n if (!json) {\n throw new Error('Must pass in a JSON object containing the Google auth settings.');\n }\n options = options || {};\n if (json.type === 'authorized_user') {\n client = new refreshclient_1.UserRefreshClient(options);\n }\n else {\n options.scopes = this.scopes;\n client = new jwtclient_1.JWT(options);\n client.defaultScopes = this.defaultScopes;\n }\n client.fromJSON(json);\n return client;\n }\n /**\n * Return a JWT or UserRefreshClient from JavaScript object, caching both the\n * object used to instantiate and the client.\n * @param json The input object.\n * @param options The JWT or UserRefresh options for the client\n * @returns JWT or UserRefresh Client with data\n */\n _cacheClientFromJSON(json, options) {\n let client;\n // create either a UserRefreshClient or JWT client.\n options = options || {};\n if (json.type === 'authorized_user') {\n client = new refreshclient_1.UserRefreshClient(options);\n }\n else {\n options.scopes = this.scopes;\n client = new jwtclient_1.JWT(options);\n client.defaultScopes = this.defaultScopes;\n }\n client.fromJSON(json);\n // cache both raw data used to instantiate client and client itself.\n this.jsonContent = json;\n this.cachedCredential = client;\n return this.cachedCredential;\n }\n fromStream(inputStream, optionsOrCallback = {}, callback) {\n let options = {};\n if (typeof optionsOrCallback === 'function') {\n callback = optionsOrCallback;\n }\n else {\n options = optionsOrCallback;\n }\n if (callback) {\n this.fromStreamAsync(inputStream, options).then(r => callback(null, r), callback);\n }\n else {\n return this.fromStreamAsync(inputStream, options);\n }\n }\n fromStreamAsync(inputStream, options) {\n return new Promise((resolve, reject) => {\n if (!inputStream) {\n throw new Error('Must pass in a stream containing the Google auth settings.');\n }\n let s = '';\n inputStream\n .setEncoding('utf8')\n .on('error', reject)\n .on('data', chunk => (s += chunk))\n .on('end', () => {\n try {\n try {\n const data = JSON.parse(s);\n const r = this._cacheClientFromJSON(data, options);\n return resolve(r);\n }\n catch (err) {\n // If we failed parsing this.keyFileName, assume that it\n // is a PEM or p12 certificate:\n if (!this.keyFilename)\n throw err;\n const client = new jwtclient_1.JWT({\n ...this.clientOptions,\n keyFile: this.keyFilename,\n });\n this.cachedCredential = client;\n return resolve(client);\n }\n }\n catch (err) {\n return reject(err);\n }\n });\n });\n }\n /**\n * Create a credentials instance using the given API key string.\n * @param apiKey The API key string\n * @param options An optional options object.\n * @returns A JWT loaded from the key\n */\n fromAPIKey(apiKey, options) {\n options = options || {};\n const client = new jwtclient_1.JWT(options);\n client.fromAPIKey(apiKey);\n return client;\n }\n /**\n * Determines whether the current operating system is Windows.\n * @api private\n */\n _isWindows() {\n const sys = os.platform();\n if (sys && sys.length >= 3) {\n if (sys.substring(0, 3).toLowerCase() === 'win') {\n return true;\n }\n }\n return false;\n }\n /**\n * Run the Google Cloud SDK command that prints the default project ID\n */\n async getDefaultServiceProjectId() {\n return new Promise(resolve => {\n child_process_1.exec('gcloud config config-helper --format json', (err, stdout) => {\n if (!err && stdout) {\n try {\n const projectId = JSON.parse(stdout).configuration.properties.core\n .project;\n resolve(projectId);\n return;\n }\n catch (e) {\n // ignore errors\n }\n }\n resolve(null);\n });\n });\n }\n /**\n * Loads the project id from environment variables.\n * @api private\n */\n getProductionProjectId() {\n return (process.env['GCLOUD_PROJECT'] ||\n process.env['GOOGLE_CLOUD_PROJECT'] ||\n process.env['gcloud_project'] ||\n process.env['google_cloud_project']);\n }\n /**\n * Loads the project id from the GOOGLE_APPLICATION_CREDENTIALS json file.\n * @api private\n */\n async getFileProjectId() {\n if (this.cachedCredential) {\n // Try to read the project ID from the cached credentials file\n return this.cachedCredential.projectId;\n }\n // Ensure the projectId is loaded from the keyFile if available.\n if (this.keyFilename) {\n const creds = await this.getClient();\n if (creds && creds.projectId) {\n return creds.projectId;\n }\n }\n // Try to load a credentials file and read its project ID\n const r = await this._tryGetApplicationCredentialsFromEnvironmentVariable();\n if (r) {\n return r.projectId;\n }\n else {\n return null;\n }\n }\n /**\n * Gets the Compute Engine project ID if it can be inferred.\n */\n async getGCEProjectId() {\n try {\n const r = await gcpMetadata.project('project-id');\n return r;\n }\n catch (e) {\n // Ignore any errors\n return null;\n }\n }\n getCredentials(callback) {\n if (callback) {\n this.getCredentialsAsync().then(r => callback(null, r), callback);\n }\n else {\n return this.getCredentialsAsync();\n }\n }\n async getCredentialsAsync() {\n await this.getClient();\n if (this.jsonContent) {\n const credential = {\n client_email: this.jsonContent.client_email,\n private_key: this.jsonContent.private_key,\n };\n return credential;\n }\n const isGCE = await this._checkIsGCE();\n if (!isGCE) {\n throw new Error('Unknown error.');\n }\n // For GCE, return the service account details from the metadata server\n // NOTE: The trailing '/' at the end of service-accounts/ is very important!\n // The GCF metadata server doesn't respect querystring params if this / is\n // not included.\n const data = await gcpMetadata.instance({\n property: 'service-accounts/',\n params: { recursive: 'true' },\n });\n if (!data || !data.default || !data.default.email) {\n throw new Error('Failure from metadata server.');\n }\n return { client_email: data.default.email };\n }\n /**\n * Automatically obtain a client based on the provided configuration. If no\n * options were passed, use Application Default Credentials.\n */\n async getClient(options) {\n if (options) {\n throw new Error('Passing options to getClient is forbidden in v5.0.0. Use new GoogleAuth(opts) instead.');\n }\n if (!this.cachedCredential) {\n if (this.jsonContent) {\n this._cacheClientFromJSON(this.jsonContent, this.clientOptions);\n }\n else if (this.keyFilename) {\n const filePath = path.resolve(this.keyFilename);\n const stream = fs.createReadStream(filePath);\n await this.fromStreamAsync(stream, this.clientOptions);\n }\n else {\n await this.getApplicationDefaultAsync(this.clientOptions);\n }\n }\n return this.cachedCredential;\n }\n /**\n * Creates a client which will fetch an ID token for authorization.\n * @param targetAudience the audience for the fetched ID token.\n * @returns IdTokenClient for making HTTP calls authenticated with ID tokens.\n */\n async getIdTokenClient(targetAudience) {\n const client = await this.getClient();\n if (!('fetchIdToken' in client)) {\n throw new Error('Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.');\n }\n return new idtokenclient_1.IdTokenClient({ targetAudience, idTokenProvider: client });\n }\n /**\n * Automatically obtain application default credentials, and return\n * an access token for making requests.\n */\n async getAccessToken() {\n const client = await this.getClient();\n return (await client.getAccessToken()).token;\n }\n /**\n * Obtain the HTTP headers that will provide authorization for a given\n * request.\n */\n async getRequestHeaders(url) {\n const client = await this.getClient();\n return client.getRequestHeaders(url);\n }\n /**\n * Obtain credentials for a request, then attach the appropriate headers to\n * the request options.\n * @param opts Axios or Request options on which to attach the headers\n */\n async authorizeRequest(opts) {\n opts = opts || {};\n const url = opts.url || opts.uri;\n const client = await this.getClient();\n const headers = await client.getRequestHeaders(url);\n opts.headers = Object.assign(opts.headers || {}, headers);\n return opts;\n }\n /**\n * Automatically obtain application default credentials, and make an\n * HTTP request using the given options.\n * @param opts Axios request options for the HTTP request.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async request(opts) {\n const client = await this.getClient();\n return client.request(opts);\n }\n /**\n * Determine the compute environment in which the code is running.\n */\n getEnv() {\n return envDetect_1.getEnv();\n }\n /**\n * Sign the given data with the current private key, or go out\n * to the IAM API to sign it.\n * @param data The data to be signed.\n */\n async sign(data) {\n const client = await this.getClient();\n const crypto = crypto_1.createCrypto();\n if (client instanceof jwtclient_1.JWT && client.key) {\n const sign = await crypto.sign(client.key, data);\n return sign;\n }\n const projectId = await this.getProjectId();\n if (!projectId) {\n throw new Error('Cannot sign data without a project ID.');\n }\n const creds = await this.getCredentials();\n if (!creds.client_email) {\n throw new Error('Cannot sign data without `client_email`.');\n }\n const url = `https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${creds.client_email}:signBlob`;\n const res = await this.request({\n method: 'POST',\n url,\n data: {\n payload: crypto.encodeBase64StringUtf8(data),\n },\n });\n return res.data.signedBlob;\n }\n}\nexports.GoogleAuth = GoogleAuth;\n/**\n * Export DefaultTransporter as a static property of the class.\n */\nGoogleAuth.DefaultTransporter = transporters_1.DefaultTransporter;\n//# sourceMappingURL=googleauth.js.map","\"use strict\";\n// Copyright 2014 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.IAMAuth = void 0;\nclass IAMAuth {\n /**\n * IAM credentials.\n *\n * @param selector the iam authority selector\n * @param token the token\n * @constructor\n */\n constructor(selector, token) {\n this.selector = selector;\n this.token = token;\n this.selector = selector;\n this.token = token;\n }\n /**\n * Acquire the HTTP headers required to make an authenticated request.\n */\n getRequestHeaders() {\n return {\n 'x-goog-iam-authority-selector': this.selector,\n 'x-goog-iam-authorization-token': this.token,\n };\n }\n}\nexports.IAMAuth = IAMAuth;\n//# sourceMappingURL=iam.js.map","\"use strict\";\n// Copyright 2020 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.IdTokenClient = void 0;\nconst oauth2client_1 = require(\"./oauth2client\");\nclass IdTokenClient extends oauth2client_1.OAuth2Client {\n /**\n * Google ID Token client\n *\n * Retrieve access token from the metadata server.\n * See: https://developers.google.com/compute/docs/authentication\n */\n constructor(options) {\n super();\n this.targetAudience = options.targetAudience;\n this.idTokenProvider = options.idTokenProvider;\n }\n async getRequestMetadataAsync(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n url) {\n if (!this.credentials.id_token ||\n (this.credentials.expiry_date || 0) < Date.now()) {\n const idToken = await this.idTokenProvider.fetchIdToken(this.targetAudience);\n this.credentials = {\n id_token: idToken,\n expiry_date: this.getIdTokenExpiryDate(idToken),\n };\n }\n const headers = {\n Authorization: 'Bearer ' + this.credentials.id_token,\n };\n return { headers };\n }\n getIdTokenExpiryDate(idToken) {\n const payloadB64 = idToken.split('.')[1];\n if (payloadB64) {\n const payload = JSON.parse(Buffer.from(payloadB64, 'base64').toString('ascii'));\n return payload.exp * 1000;\n }\n }\n}\nexports.IdTokenClient = IdTokenClient;\n//# sourceMappingURL=idtokenclient.js.map","\"use strict\";\n// Copyright 2015 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.JWTAccess = void 0;\nconst jws = require(\"jws\");\nconst LRU = require(\"lru-cache\");\nconst DEFAULT_HEADER = {\n alg: 'RS256',\n typ: 'JWT',\n};\nclass JWTAccess {\n /**\n * JWTAccess service account credentials.\n *\n * Create a new access token by using the credential to create a new JWT token\n * that's recognized as the access token.\n *\n * @param email the service account email address.\n * @param key the private key that will be used to sign the token.\n * @param keyId the ID of the private key used to sign the token.\n */\n constructor(email, key, keyId, eagerRefreshThresholdMillis) {\n this.cache = new LRU({\n max: 500,\n maxAge: 60 * 60 * 1000,\n });\n this.email = email;\n this.key = key;\n this.keyId = keyId;\n this.eagerRefreshThresholdMillis = eagerRefreshThresholdMillis !== null && eagerRefreshThresholdMillis !== void 0 ? eagerRefreshThresholdMillis : 5 * 60 * 1000;\n }\n /**\n * Get a non-expired access token, after refreshing if necessary.\n *\n * @param url The URI being authorized.\n * @param additionalClaims An object with a set of additional claims to\n * include in the payload.\n * @returns An object that includes the authorization header.\n */\n getRequestHeaders(url, additionalClaims) {\n // Return cached authorization headers, unless we are within\n // eagerRefreshThresholdMillis ms of them expiring:\n const cachedToken = this.cache.get(url);\n const now = Date.now();\n if (cachedToken &&\n cachedToken.expiration - now > this.eagerRefreshThresholdMillis) {\n return cachedToken.headers;\n }\n const iat = Math.floor(Date.now() / 1000);\n const exp = JWTAccess.getExpirationTime(iat);\n // The payload used for signed JWT headers has:\n // iss == sub == \n // aud == \n const defaultClaims = {\n iss: this.email,\n sub: this.email,\n aud: url,\n exp,\n iat,\n };\n // if additionalClaims are provided, ensure they do not collide with\n // other required claims.\n if (additionalClaims) {\n for (const claim in defaultClaims) {\n if (additionalClaims[claim]) {\n throw new Error(`The '${claim}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`);\n }\n }\n }\n const header = this.keyId\n ? { ...DEFAULT_HEADER, kid: this.keyId }\n : DEFAULT_HEADER;\n const payload = Object.assign(defaultClaims, additionalClaims);\n // Sign the jwt and add it to the cache\n const signedJWT = jws.sign({ header, payload, secret: this.key });\n const headers = { Authorization: `Bearer ${signedJWT}` };\n this.cache.set(url, {\n expiration: exp * 1000,\n headers,\n });\n return headers;\n }\n /**\n * Returns an expiration time for the JWT token.\n *\n * @param iat The issued at time for the JWT.\n * @returns An expiration time for the JWT.\n */\n static getExpirationTime(iat) {\n const exp = iat + 3600; // 3600 seconds = 1 hour\n return exp;\n }\n /**\n * Create a JWTAccess credentials instance using the given input options.\n * @param json The input object.\n */\n fromJSON(json) {\n if (!json) {\n throw new Error('Must pass in a JSON object containing the service account auth settings.');\n }\n if (!json.client_email) {\n throw new Error('The incoming JSON object does not contain a client_email field');\n }\n if (!json.private_key) {\n throw new Error('The incoming JSON object does not contain a private_key field');\n }\n // Extract the relevant information from the json key file.\n this.email = json.client_email;\n this.key = json.private_key;\n this.keyId = json.private_key_id;\n this.projectId = json.project_id;\n }\n fromStream(inputStream, callback) {\n if (callback) {\n this.fromStreamAsync(inputStream).then(() => callback(), callback);\n }\n else {\n return this.fromStreamAsync(inputStream);\n }\n }\n fromStreamAsync(inputStream) {\n return new Promise((resolve, reject) => {\n if (!inputStream) {\n reject(new Error('Must pass in a stream containing the service account auth settings.'));\n }\n let s = '';\n inputStream\n .setEncoding('utf8')\n .on('data', chunk => (s += chunk))\n .on('error', reject)\n .on('end', () => {\n try {\n const data = JSON.parse(s);\n this.fromJSON(data);\n resolve();\n }\n catch (err) {\n reject(err);\n }\n });\n });\n }\n}\nexports.JWTAccess = JWTAccess;\n//# sourceMappingURL=jwtaccess.js.map","\"use strict\";\n// Copyright 2013 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.JWT = void 0;\nconst gtoken_1 = require(\"gtoken\");\nconst jwtaccess_1 = require(\"./jwtaccess\");\nconst oauth2client_1 = require(\"./oauth2client\");\nclass JWT extends oauth2client_1.OAuth2Client {\n constructor(optionsOrEmail, keyFile, key, scopes, subject, keyId) {\n const opts = optionsOrEmail && typeof optionsOrEmail === 'object'\n ? optionsOrEmail\n : { email: optionsOrEmail, keyFile, key, keyId, scopes, subject };\n super({\n eagerRefreshThresholdMillis: opts.eagerRefreshThresholdMillis,\n forceRefreshOnFailure: opts.forceRefreshOnFailure,\n });\n this.email = opts.email;\n this.keyFile = opts.keyFile;\n this.key = opts.key;\n this.keyId = opts.keyId;\n this.scopes = opts.scopes;\n this.subject = opts.subject;\n this.additionalClaims = opts.additionalClaims;\n this.credentials = { refresh_token: 'jwt-placeholder', expiry_date: 1 };\n }\n /**\n * Creates a copy of the credential with the specified scopes.\n * @param scopes List of requested scopes or a single scope.\n * @return The cloned instance.\n */\n createScoped(scopes) {\n return new JWT({\n email: this.email,\n keyFile: this.keyFile,\n key: this.key,\n keyId: this.keyId,\n scopes,\n subject: this.subject,\n additionalClaims: this.additionalClaims,\n });\n }\n /**\n * Obtains the metadata to be sent with the request.\n *\n * @param url the URI being authorized.\n */\n async getRequestMetadataAsync(url) {\n if (!this.apiKey && !this.hasUserScopes() && url) {\n if (this.additionalClaims &&\n this.additionalClaims.target_audience) {\n const { tokens } = await this.refreshToken();\n return {\n headers: this.addSharedMetadataHeaders({\n Authorization: `Bearer ${tokens.id_token}`,\n }),\n };\n }\n else {\n // no scopes have been set, but a uri has been provided. Use JWTAccess\n // credentials.\n if (!this.access) {\n this.access = new jwtaccess_1.JWTAccess(this.email, this.key, this.keyId, this.eagerRefreshThresholdMillis);\n }\n const headers = await this.access.getRequestHeaders(url, this.additionalClaims);\n return { headers: this.addSharedMetadataHeaders(headers) };\n }\n }\n else if (this.hasAnyScopes() || this.apiKey) {\n return super.getRequestMetadataAsync(url);\n }\n else {\n // If no audience, apiKey, or scopes are provided, we should not attempt\n // to populate any headers:\n return { headers: {} };\n }\n }\n /**\n * Fetches an ID token.\n * @param targetAudience the audience for the fetched ID token.\n */\n async fetchIdToken(targetAudience) {\n // Create a new gToken for fetching an ID token\n const gtoken = new gtoken_1.GoogleToken({\n iss: this.email,\n sub: this.subject,\n scope: this.scopes || this.defaultScopes,\n keyFile: this.keyFile,\n key: this.key,\n additionalClaims: { target_audience: targetAudience },\n });\n await gtoken.getToken({\n forceRefresh: true,\n });\n if (!gtoken.idToken) {\n throw new Error('Unknown error: Failed to fetch ID token');\n }\n return gtoken.idToken;\n }\n /**\n * Determine if there are currently scopes available.\n */\n hasUserScopes() {\n if (!this.scopes) {\n return false;\n }\n return this.scopes.length > 0;\n }\n /**\n * Are there any default or user scopes defined.\n */\n hasAnyScopes() {\n if (this.scopes && this.scopes.length > 0)\n return true;\n if (this.defaultScopes && this.defaultScopes.length > 0)\n return true;\n return false;\n }\n authorize(callback) {\n if (callback) {\n this.authorizeAsync().then(r => callback(null, r), callback);\n }\n else {\n return this.authorizeAsync();\n }\n }\n async authorizeAsync() {\n const result = await this.refreshToken();\n if (!result) {\n throw new Error('No result returned');\n }\n this.credentials = result.tokens;\n this.credentials.refresh_token = 'jwt-placeholder';\n this.key = this.gtoken.key;\n this.email = this.gtoken.iss;\n return result.tokens;\n }\n /**\n * Refreshes the access token.\n * @param refreshToken ignored\n * @private\n */\n async refreshTokenNoCache(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n refreshToken) {\n const gtoken = this.createGToken();\n const token = await gtoken.getToken({\n forceRefresh: this.isTokenExpiring(),\n });\n const tokens = {\n access_token: token.access_token,\n token_type: 'Bearer',\n expiry_date: gtoken.expiresAt,\n id_token: gtoken.idToken,\n };\n this.emit('tokens', tokens);\n return { res: null, tokens };\n }\n /**\n * Create a gToken if it doesn't already exist.\n */\n createGToken() {\n if (!this.gtoken) {\n this.gtoken = new gtoken_1.GoogleToken({\n iss: this.email,\n sub: this.subject,\n scope: this.scopes || this.defaultScopes,\n keyFile: this.keyFile,\n key: this.key,\n additionalClaims: this.additionalClaims,\n });\n }\n return this.gtoken;\n }\n /**\n * Create a JWT credentials instance using the given input options.\n * @param json The input object.\n */\n fromJSON(json) {\n if (!json) {\n throw new Error('Must pass in a JSON object containing the service account auth settings.');\n }\n if (!json.client_email) {\n throw new Error('The incoming JSON object does not contain a client_email field');\n }\n if (!json.private_key) {\n throw new Error('The incoming JSON object does not contain a private_key field');\n }\n // Extract the relevant information from the json key file.\n this.email = json.client_email;\n this.key = json.private_key;\n this.keyId = json.private_key_id;\n this.projectId = json.project_id;\n this.quotaProjectId = json.quota_project_id;\n }\n fromStream(inputStream, callback) {\n if (callback) {\n this.fromStreamAsync(inputStream).then(() => callback(), callback);\n }\n else {\n return this.fromStreamAsync(inputStream);\n }\n }\n fromStreamAsync(inputStream) {\n return new Promise((resolve, reject) => {\n if (!inputStream) {\n throw new Error('Must pass in a stream containing the service account auth settings.');\n }\n let s = '';\n inputStream\n .setEncoding('utf8')\n .on('error', reject)\n .on('data', chunk => (s += chunk))\n .on('end', () => {\n try {\n const data = JSON.parse(s);\n this.fromJSON(data);\n resolve();\n }\n catch (e) {\n reject(e);\n }\n });\n });\n }\n /**\n * Creates a JWT credentials instance using an API Key for authentication.\n * @param apiKey The API Key in string form.\n */\n fromAPIKey(apiKey) {\n if (typeof apiKey !== 'string') {\n throw new Error('Must provide an API Key string.');\n }\n this.apiKey = apiKey;\n }\n /**\n * Using the key or keyFile on the JWT client, obtain an object that contains\n * the key and the client email.\n */\n async getCredentials() {\n if (this.key) {\n return { private_key: this.key, client_email: this.email };\n }\n else if (this.keyFile) {\n const gtoken = this.createGToken();\n const creds = await gtoken.getCredentials(this.keyFile);\n return { private_key: creds.privateKey, client_email: creds.clientEmail };\n }\n throw new Error('A key or a keyFile must be provided to getCredentials.');\n }\n}\nexports.JWT = JWT;\n//# sourceMappingURL=jwtclient.js.map","\"use strict\";\n// Copyright 2014 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.LoginTicket = void 0;\nclass LoginTicket {\n /**\n * Create a simple class to extract user ID from an ID Token\n *\n * @param {string} env Envelope of the jwt\n * @param {TokenPayload} pay Payload of the jwt\n * @constructor\n */\n constructor(env, pay) {\n this.envelope = env;\n this.payload = pay;\n }\n getEnvelope() {\n return this.envelope;\n }\n getPayload() {\n return this.payload;\n }\n /**\n * Create a simple class to extract user ID from an ID Token\n *\n * @return The user ID\n */\n getUserId() {\n const payload = this.getPayload();\n if (payload && payload.sub) {\n return payload.sub;\n }\n return null;\n }\n /**\n * Returns attributes from the login ticket. This can contain\n * various information about the user session.\n *\n * @return The envelope and payload\n */\n getAttributes() {\n return { envelope: this.getEnvelope(), payload: this.getPayload() };\n }\n}\nexports.LoginTicket = LoginTicket;\n//# sourceMappingURL=loginticket.js.map","\"use strict\";\n// Copyright 2019 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.OAuth2Client = exports.CertificateFormat = exports.CodeChallengeMethod = void 0;\nconst querystring = require(\"querystring\");\nconst stream = require(\"stream\");\nconst formatEcdsa = require(\"ecdsa-sig-formatter\");\nconst crypto_1 = require(\"../crypto/crypto\");\nconst authclient_1 = require(\"./authclient\");\nconst loginticket_1 = require(\"./loginticket\");\nvar CodeChallengeMethod;\n(function (CodeChallengeMethod) {\n CodeChallengeMethod[\"Plain\"] = \"plain\";\n CodeChallengeMethod[\"S256\"] = \"S256\";\n})(CodeChallengeMethod = exports.CodeChallengeMethod || (exports.CodeChallengeMethod = {}));\nvar CertificateFormat;\n(function (CertificateFormat) {\n CertificateFormat[\"PEM\"] = \"PEM\";\n CertificateFormat[\"JWK\"] = \"JWK\";\n})(CertificateFormat = exports.CertificateFormat || (exports.CertificateFormat = {}));\nclass OAuth2Client extends authclient_1.AuthClient {\n constructor(optionsOrClientId, clientSecret, redirectUri) {\n super();\n this.certificateCache = {};\n this.certificateExpiry = null;\n this.certificateCacheFormat = CertificateFormat.PEM;\n this.refreshTokenPromises = new Map();\n const opts = optionsOrClientId && typeof optionsOrClientId === 'object'\n ? optionsOrClientId\n : { clientId: optionsOrClientId, clientSecret, redirectUri };\n this._clientId = opts.clientId;\n this._clientSecret = opts.clientSecret;\n this.redirectUri = opts.redirectUri;\n this.eagerRefreshThresholdMillis =\n opts.eagerRefreshThresholdMillis || 5 * 60 * 1000;\n this.forceRefreshOnFailure = !!opts.forceRefreshOnFailure;\n }\n /**\n * Generates URL for consent page landing.\n * @param opts Options.\n * @return URL to consent page.\n */\n generateAuthUrl(opts = {}) {\n if (opts.code_challenge_method && !opts.code_challenge) {\n throw new Error('If a code_challenge_method is provided, code_challenge must be included.');\n }\n opts.response_type = opts.response_type || 'code';\n opts.client_id = opts.client_id || this._clientId;\n opts.redirect_uri = opts.redirect_uri || this.redirectUri;\n // Allow scopes to be passed either as array or a string\n if (opts.scope instanceof Array) {\n opts.scope = opts.scope.join(' ');\n }\n const rootUrl = OAuth2Client.GOOGLE_OAUTH2_AUTH_BASE_URL_;\n return rootUrl + '?' + querystring.stringify(opts);\n }\n generateCodeVerifier() {\n // To make the code compatible with browser SubtleCrypto we need to make\n // this method async.\n throw new Error('generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.');\n }\n /**\n * Convenience method to automatically generate a code_verifier, and its\n * resulting SHA256. If used, this must be paired with a S256\n * code_challenge_method.\n *\n * For a full example see:\n * https://github.com/googleapis/google-auth-library-nodejs/blob/master/samples/oauth2-codeVerifier.js\n */\n async generateCodeVerifierAsync() {\n // base64 encoding uses 6 bits per character, and we want to generate128\n // characters. 6*128/8 = 96.\n const crypto = crypto_1.createCrypto();\n const randomString = crypto.randomBytesBase64(96);\n // The valid characters in the code_verifier are [A-Z]/[a-z]/[0-9]/\n // \"-\"/\".\"/\"_\"/\"~\". Base64 encoded strings are pretty close, so we're just\n // swapping out a few chars.\n const codeVerifier = randomString\n .replace(/\\+/g, '~')\n .replace(/=/g, '_')\n .replace(/\\//g, '-');\n // Generate the base64 encoded SHA256\n const unencodedCodeChallenge = await crypto.sha256DigestBase64(codeVerifier);\n // We need to use base64UrlEncoding instead of standard base64\n const codeChallenge = unencodedCodeChallenge\n .split('=')[0]\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_');\n return { codeVerifier, codeChallenge };\n }\n getToken(codeOrOptions, callback) {\n const options = typeof codeOrOptions === 'string' ? { code: codeOrOptions } : codeOrOptions;\n if (callback) {\n this.getTokenAsync(options).then(r => callback(null, r.tokens, r.res), e => callback(e, null, e.response));\n }\n else {\n return this.getTokenAsync(options);\n }\n }\n async getTokenAsync(options) {\n const url = OAuth2Client.GOOGLE_OAUTH2_TOKEN_URL_;\n const values = {\n code: options.code,\n client_id: options.client_id || this._clientId,\n client_secret: this._clientSecret,\n redirect_uri: options.redirect_uri || this.redirectUri,\n grant_type: 'authorization_code',\n code_verifier: options.codeVerifier,\n };\n const res = await this.transporter.request({\n method: 'POST',\n url,\n data: querystring.stringify(values),\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n });\n const tokens = res.data;\n if (res.data && res.data.expires_in) {\n tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000;\n delete tokens.expires_in;\n }\n this.emit('tokens', tokens);\n return { tokens, res };\n }\n /**\n * Refreshes the access token.\n * @param refresh_token Existing refresh token.\n * @private\n */\n async refreshToken(refreshToken) {\n if (!refreshToken) {\n return this.refreshTokenNoCache(refreshToken);\n }\n // If a request to refresh using the same token has started,\n // return the same promise.\n if (this.refreshTokenPromises.has(refreshToken)) {\n return this.refreshTokenPromises.get(refreshToken);\n }\n const p = this.refreshTokenNoCache(refreshToken).then(r => {\n this.refreshTokenPromises.delete(refreshToken);\n return r;\n }, e => {\n this.refreshTokenPromises.delete(refreshToken);\n throw e;\n });\n this.refreshTokenPromises.set(refreshToken, p);\n return p;\n }\n async refreshTokenNoCache(refreshToken) {\n if (!refreshToken) {\n throw new Error('No refresh token is set.');\n }\n const url = OAuth2Client.GOOGLE_OAUTH2_TOKEN_URL_;\n const data = {\n refresh_token: refreshToken,\n client_id: this._clientId,\n client_secret: this._clientSecret,\n grant_type: 'refresh_token',\n };\n // request for new token\n const res = await this.transporter.request({\n method: 'POST',\n url,\n data: querystring.stringify(data),\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n });\n const tokens = res.data;\n // TODO: de-duplicate this code from a few spots\n if (res.data && res.data.expires_in) {\n tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000;\n delete tokens.expires_in;\n }\n this.emit('tokens', tokens);\n return { tokens, res };\n }\n refreshAccessToken(callback) {\n if (callback) {\n this.refreshAccessTokenAsync().then(r => callback(null, r.credentials, r.res), callback);\n }\n else {\n return this.refreshAccessTokenAsync();\n }\n }\n async refreshAccessTokenAsync() {\n const r = await this.refreshToken(this.credentials.refresh_token);\n const tokens = r.tokens;\n tokens.refresh_token = this.credentials.refresh_token;\n this.credentials = tokens;\n return { credentials: this.credentials, res: r.res };\n }\n getAccessToken(callback) {\n if (callback) {\n this.getAccessTokenAsync().then(r => callback(null, r.token, r.res), callback);\n }\n else {\n return this.getAccessTokenAsync();\n }\n }\n async getAccessTokenAsync() {\n const shouldRefresh = !this.credentials.access_token || this.isTokenExpiring();\n if (shouldRefresh) {\n if (!this.credentials.refresh_token) {\n throw new Error('No refresh token is set.');\n }\n const r = await this.refreshAccessTokenAsync();\n if (!r.credentials || (r.credentials && !r.credentials.access_token)) {\n throw new Error('Could not refresh access token.');\n }\n return { token: r.credentials.access_token, res: r.res };\n }\n else {\n return { token: this.credentials.access_token };\n }\n }\n /**\n * The main authentication interface. It takes an optional url which when\n * present is the endpoint being accessed, and returns a Promise which\n * resolves with authorization header fields.\n *\n * In OAuth2Client, the result has the form:\n * { Authorization: 'Bearer ' }\n * @param url The optional url being authorized\n */\n async getRequestHeaders(url) {\n const headers = (await this.getRequestMetadataAsync(url)).headers;\n return headers;\n }\n async getRequestMetadataAsync(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n url) {\n const thisCreds = this.credentials;\n if (!thisCreds.access_token && !thisCreds.refresh_token && !this.apiKey) {\n throw new Error('No access, refresh token or API key is set.');\n }\n if (thisCreds.access_token && !this.isTokenExpiring()) {\n thisCreds.token_type = thisCreds.token_type || 'Bearer';\n const headers = {\n Authorization: thisCreds.token_type + ' ' + thisCreds.access_token,\n };\n return { headers: this.addSharedMetadataHeaders(headers) };\n }\n if (this.apiKey) {\n return { headers: { 'X-Goog-Api-Key': this.apiKey } };\n }\n let r = null;\n let tokens = null;\n try {\n r = await this.refreshToken(thisCreds.refresh_token);\n tokens = r.tokens;\n }\n catch (err) {\n const e = err;\n if (e.response &&\n (e.response.status === 403 || e.response.status === 404)) {\n e.message = `Could not refresh access token: ${e.message}`;\n }\n throw e;\n }\n const credentials = this.credentials;\n credentials.token_type = credentials.token_type || 'Bearer';\n tokens.refresh_token = credentials.refresh_token;\n this.credentials = tokens;\n const headers = {\n Authorization: credentials.token_type + ' ' + tokens.access_token,\n };\n return { headers: this.addSharedMetadataHeaders(headers), res: r.res };\n }\n /**\n * Generates an URL to revoke the given token.\n * @param token The existing token to be revoked.\n */\n static getRevokeTokenUrl(token) {\n const parameters = querystring.stringify({ token });\n return `${OAuth2Client.GOOGLE_OAUTH2_REVOKE_URL_}?${parameters}`;\n }\n revokeToken(token, callback) {\n const opts = {\n url: OAuth2Client.getRevokeTokenUrl(token),\n method: 'POST',\n };\n if (callback) {\n this.transporter\n .request(opts)\n .then(r => callback(null, r), callback);\n }\n else {\n return this.transporter.request(opts);\n }\n }\n revokeCredentials(callback) {\n if (callback) {\n this.revokeCredentialsAsync().then(res => callback(null, res), callback);\n }\n else {\n return this.revokeCredentialsAsync();\n }\n }\n async revokeCredentialsAsync() {\n const token = this.credentials.access_token;\n this.credentials = {};\n if (token) {\n return this.revokeToken(token);\n }\n else {\n throw new Error('No access token to revoke.');\n }\n }\n request(opts, callback) {\n if (callback) {\n this.requestAsync(opts).then(r => callback(null, r), e => {\n return callback(e, e.response);\n });\n }\n else {\n return this.requestAsync(opts);\n }\n }\n async requestAsync(opts, retry = false) {\n let r2;\n try {\n const r = await this.getRequestMetadataAsync(opts.url);\n opts.headers = opts.headers || {};\n if (r.headers && r.headers['x-goog-user-project']) {\n opts.headers['x-goog-user-project'] = r.headers['x-goog-user-project'];\n }\n if (r.headers && r.headers.Authorization) {\n opts.headers.Authorization = r.headers.Authorization;\n }\n if (this.apiKey) {\n opts.headers['X-Goog-Api-Key'] = this.apiKey;\n }\n r2 = await this.transporter.request(opts);\n }\n catch (e) {\n const res = e.response;\n if (res) {\n const statusCode = res.status;\n // Retry the request for metadata if the following criteria are true:\n // - We haven't already retried. It only makes sense to retry once.\n // - The response was a 401 or a 403\n // - The request didn't send a readableStream\n // - An access_token and refresh_token were available, but either no\n // expiry_date was available or the forceRefreshOnFailure flag is set.\n // The absent expiry_date case can happen when developers stash the\n // access_token and refresh_token for later use, but the access_token\n // fails on the first try because it's expired. Some developers may\n // choose to enable forceRefreshOnFailure to mitigate time-related\n // errors.\n const mayRequireRefresh = this.credentials &&\n this.credentials.access_token &&\n this.credentials.refresh_token &&\n (!this.credentials.expiry_date || this.forceRefreshOnFailure);\n const isReadableStream = res.config.data instanceof stream.Readable;\n const isAuthErr = statusCode === 401 || statusCode === 403;\n if (!retry && isAuthErr && !isReadableStream && mayRequireRefresh) {\n await this.refreshAccessTokenAsync();\n return this.requestAsync(opts, true);\n }\n }\n throw e;\n }\n return r2;\n }\n verifyIdToken(options, callback) {\n // This function used to accept two arguments instead of an options object.\n // Check the types to help users upgrade with less pain.\n // This check can be removed after a 2.0 release.\n if (callback && typeof callback !== 'function') {\n throw new Error('This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.');\n }\n if (callback) {\n this.verifyIdTokenAsync(options).then(r => callback(null, r), callback);\n }\n else {\n return this.verifyIdTokenAsync(options);\n }\n }\n async verifyIdTokenAsync(options) {\n if (!options.idToken) {\n throw new Error('The verifyIdToken method requires an ID Token');\n }\n const response = await this.getFederatedSignonCertsAsync();\n const login = await this.verifySignedJwtWithCertsAsync(options.idToken, response.certs, options.audience, OAuth2Client.ISSUERS_, options.maxExpiry);\n return login;\n }\n /**\n * Obtains information about the provisioned access token. Especially useful\n * if you want to check the scopes that were provisioned to a given token.\n *\n * @param accessToken Required. The Access Token for which you want to get\n * user info.\n */\n async getTokenInfo(accessToken) {\n const { data } = await this.transporter.request({\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n Authorization: `Bearer ${accessToken}`,\n },\n url: OAuth2Client.GOOGLE_TOKEN_INFO_URL,\n });\n const info = Object.assign({\n expiry_date: new Date().getTime() + data.expires_in * 1000,\n scopes: data.scope.split(' '),\n }, data);\n delete info.expires_in;\n delete info.scope;\n return info;\n }\n getFederatedSignonCerts(callback) {\n if (callback) {\n this.getFederatedSignonCertsAsync().then(r => callback(null, r.certs, r.res), callback);\n }\n else {\n return this.getFederatedSignonCertsAsync();\n }\n }\n async getFederatedSignonCertsAsync() {\n const nowTime = new Date().getTime();\n const format = crypto_1.hasBrowserCrypto()\n ? CertificateFormat.JWK\n : CertificateFormat.PEM;\n if (this.certificateExpiry &&\n nowTime < this.certificateExpiry.getTime() &&\n this.certificateCacheFormat === format) {\n return { certs: this.certificateCache, format };\n }\n let res;\n let url;\n switch (format) {\n case CertificateFormat.PEM:\n url = OAuth2Client.GOOGLE_OAUTH2_FEDERATED_SIGNON_PEM_CERTS_URL_;\n break;\n case CertificateFormat.JWK:\n url = OAuth2Client.GOOGLE_OAUTH2_FEDERATED_SIGNON_JWK_CERTS_URL_;\n break;\n default:\n throw new Error(`Unsupported certificate format ${format}`);\n }\n try {\n res = await this.transporter.request({ url });\n }\n catch (e) {\n e.message = `Failed to retrieve verification certificates: ${e.message}`;\n throw e;\n }\n const cacheControl = res ? res.headers['cache-control'] : undefined;\n let cacheAge = -1;\n if (cacheControl) {\n const pattern = new RegExp('max-age=([0-9]*)');\n const regexResult = pattern.exec(cacheControl);\n if (regexResult && regexResult.length === 2) {\n // Cache results with max-age (in seconds)\n cacheAge = Number(regexResult[1]) * 1000; // milliseconds\n }\n }\n let certificates = {};\n switch (format) {\n case CertificateFormat.PEM:\n certificates = res.data;\n break;\n case CertificateFormat.JWK:\n for (const key of res.data.keys) {\n certificates[key.kid] = key;\n }\n break;\n default:\n throw new Error(`Unsupported certificate format ${format}`);\n }\n const now = new Date();\n this.certificateExpiry =\n cacheAge === -1 ? null : new Date(now.getTime() + cacheAge);\n this.certificateCache = certificates;\n this.certificateCacheFormat = format;\n return { certs: certificates, format, res };\n }\n getIapPublicKeys(callback) {\n if (callback) {\n this.getIapPublicKeysAsync().then(r => callback(null, r.pubkeys, r.res), callback);\n }\n else {\n return this.getIapPublicKeysAsync();\n }\n }\n async getIapPublicKeysAsync() {\n let res;\n const url = OAuth2Client.GOOGLE_OAUTH2_IAP_PUBLIC_KEY_URL_;\n try {\n res = await this.transporter.request({ url });\n }\n catch (e) {\n e.message = `Failed to retrieve verification certificates: ${e.message}`;\n throw e;\n }\n return { pubkeys: res.data, res };\n }\n verifySignedJwtWithCerts() {\n // To make the code compatible with browser SubtleCrypto we need to make\n // this method async.\n throw new Error('verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.');\n }\n /**\n * Verify the id token is signed with the correct certificate\n * and is from the correct audience.\n * @param jwt The jwt to verify (The ID Token in this case).\n * @param certs The array of certs to test the jwt against.\n * @param requiredAudience The audience to test the jwt against.\n * @param issuers The allowed issuers of the jwt (Optional).\n * @param maxExpiry The max expiry the certificate can be (Optional).\n * @return Returns a promise resolving to LoginTicket on verification.\n */\n async verifySignedJwtWithCertsAsync(jwt, certs, requiredAudience, issuers, maxExpiry) {\n const crypto = crypto_1.createCrypto();\n if (!maxExpiry) {\n maxExpiry = OAuth2Client.MAX_TOKEN_LIFETIME_SECS_;\n }\n const segments = jwt.split('.');\n if (segments.length !== 3) {\n throw new Error('Wrong number of segments in token: ' + jwt);\n }\n const signed = segments[0] + '.' + segments[1];\n let signature = segments[2];\n let envelope;\n let payload;\n try {\n envelope = JSON.parse(crypto.decodeBase64StringUtf8(segments[0]));\n }\n catch (err) {\n err.message = `Can't parse token envelope: ${segments[0]}': ${err.message}`;\n throw err;\n }\n if (!envelope) {\n throw new Error(\"Can't parse token envelope: \" + segments[0]);\n }\n try {\n payload = JSON.parse(crypto.decodeBase64StringUtf8(segments[1]));\n }\n catch (err) {\n err.message = `Can't parse token payload '${segments[0]}`;\n throw err;\n }\n if (!payload) {\n throw new Error(\"Can't parse token payload: \" + segments[1]);\n }\n if (!Object.prototype.hasOwnProperty.call(certs, envelope.kid)) {\n // If this is not present, then there's no reason to attempt verification\n throw new Error('No pem found for envelope: ' + JSON.stringify(envelope));\n }\n const cert = certs[envelope.kid];\n if (envelope.alg === 'ES256') {\n signature = formatEcdsa.joseToDer(signature, 'ES256').toString('base64');\n }\n const verified = await crypto.verify(cert, signed, signature);\n if (!verified) {\n throw new Error('Invalid token signature: ' + jwt);\n }\n if (!payload.iat) {\n throw new Error('No issue time in token: ' + JSON.stringify(payload));\n }\n if (!payload.exp) {\n throw new Error('No expiration time in token: ' + JSON.stringify(payload));\n }\n const iat = Number(payload.iat);\n if (isNaN(iat))\n throw new Error('iat field using invalid format');\n const exp = Number(payload.exp);\n if (isNaN(exp))\n throw new Error('exp field using invalid format');\n const now = new Date().getTime() / 1000;\n if (exp >= now + maxExpiry) {\n throw new Error('Expiration time too far in future: ' + JSON.stringify(payload));\n }\n const earliest = iat - OAuth2Client.CLOCK_SKEW_SECS_;\n const latest = exp + OAuth2Client.CLOCK_SKEW_SECS_;\n if (now < earliest) {\n throw new Error('Token used too early, ' +\n now +\n ' < ' +\n earliest +\n ': ' +\n JSON.stringify(payload));\n }\n if (now > latest) {\n throw new Error('Token used too late, ' +\n now +\n ' > ' +\n latest +\n ': ' +\n JSON.stringify(payload));\n }\n if (issuers && issuers.indexOf(payload.iss) < 0) {\n throw new Error('Invalid issuer, expected one of [' +\n issuers +\n '], but got ' +\n payload.iss);\n }\n // Check the audience matches if we have one\n if (typeof requiredAudience !== 'undefined' && requiredAudience !== null) {\n const aud = payload.aud;\n let audVerified = false;\n // If the requiredAudience is an array, check if it contains token\n // audience\n if (requiredAudience.constructor === Array) {\n audVerified = requiredAudience.indexOf(aud) > -1;\n }\n else {\n audVerified = aud === requiredAudience;\n }\n if (!audVerified) {\n throw new Error('Wrong recipient, payload audience != requiredAudience');\n }\n }\n return new loginticket_1.LoginTicket(envelope, payload);\n }\n /**\n * Returns true if a token is expired or will expire within\n * eagerRefreshThresholdMillismilliseconds.\n * If there is no expiry time, assumes the token is not expired or expiring.\n */\n isTokenExpiring() {\n const expiryDate = this.credentials.expiry_date;\n return expiryDate\n ? expiryDate <= new Date().getTime() + this.eagerRefreshThresholdMillis\n : false;\n }\n}\nexports.OAuth2Client = OAuth2Client;\nOAuth2Client.GOOGLE_TOKEN_INFO_URL = 'https://oauth2.googleapis.com/tokeninfo';\n/**\n * The base URL for auth endpoints.\n */\nOAuth2Client.GOOGLE_OAUTH2_AUTH_BASE_URL_ = 'https://accounts.google.com/o/oauth2/v2/auth';\n/**\n * The base endpoint for token retrieval.\n */\nOAuth2Client.GOOGLE_OAUTH2_TOKEN_URL_ = 'https://oauth2.googleapis.com/token';\n/**\n * The base endpoint to revoke tokens.\n */\nOAuth2Client.GOOGLE_OAUTH2_REVOKE_URL_ = 'https://oauth2.googleapis.com/revoke';\n/**\n * Google Sign on certificates in PEM format.\n */\nOAuth2Client.GOOGLE_OAUTH2_FEDERATED_SIGNON_PEM_CERTS_URL_ = 'https://www.googleapis.com/oauth2/v1/certs';\n/**\n * Google Sign on certificates in JWK format.\n */\nOAuth2Client.GOOGLE_OAUTH2_FEDERATED_SIGNON_JWK_CERTS_URL_ = 'https://www.googleapis.com/oauth2/v3/certs';\n/**\n * Google Sign on certificates in JWK format.\n */\nOAuth2Client.GOOGLE_OAUTH2_IAP_PUBLIC_KEY_URL_ = 'https://www.gstatic.com/iap/verify/public_key';\n/**\n * Clock skew - five minutes in seconds\n */\nOAuth2Client.CLOCK_SKEW_SECS_ = 300;\n/**\n * Max Token Lifetime is one day in seconds\n */\nOAuth2Client.MAX_TOKEN_LIFETIME_SECS_ = 86400;\n/**\n * The allowed oauth token issuers.\n */\nOAuth2Client.ISSUERS_ = [\n 'accounts.google.com',\n 'https://accounts.google.com',\n];\n//# sourceMappingURL=oauth2client.js.map","\"use strict\";\n// Copyright 2015 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.UserRefreshClient = void 0;\nconst oauth2client_1 = require(\"./oauth2client\");\nclass UserRefreshClient extends oauth2client_1.OAuth2Client {\n constructor(optionsOrClientId, clientSecret, refreshToken, eagerRefreshThresholdMillis, forceRefreshOnFailure) {\n const opts = optionsOrClientId && typeof optionsOrClientId === 'object'\n ? optionsOrClientId\n : {\n clientId: optionsOrClientId,\n clientSecret,\n refreshToken,\n eagerRefreshThresholdMillis,\n forceRefreshOnFailure,\n };\n super({\n clientId: opts.clientId,\n clientSecret: opts.clientSecret,\n eagerRefreshThresholdMillis: opts.eagerRefreshThresholdMillis,\n forceRefreshOnFailure: opts.forceRefreshOnFailure,\n });\n this._refreshToken = opts.refreshToken;\n this.credentials.refresh_token = opts.refreshToken;\n }\n /**\n * Refreshes the access token.\n * @param refreshToken An ignored refreshToken..\n * @param callback Optional callback.\n */\n async refreshTokenNoCache(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n refreshToken) {\n return super.refreshTokenNoCache(this._refreshToken);\n }\n /**\n * Create a UserRefreshClient credentials instance using the given input\n * options.\n * @param json The input object.\n */\n fromJSON(json) {\n if (!json) {\n throw new Error('Must pass in a JSON object containing the user refresh token');\n }\n if (json.type !== 'authorized_user') {\n throw new Error('The incoming JSON object does not have the \"authorized_user\" type');\n }\n if (!json.client_id) {\n throw new Error('The incoming JSON object does not contain a client_id field');\n }\n if (!json.client_secret) {\n throw new Error('The incoming JSON object does not contain a client_secret field');\n }\n if (!json.refresh_token) {\n throw new Error('The incoming JSON object does not contain a refresh_token field');\n }\n this._clientId = json.client_id;\n this._clientSecret = json.client_secret;\n this._refreshToken = json.refresh_token;\n this.credentials.refresh_token = json.refresh_token;\n this.quotaProjectId = json.quota_project_id;\n }\n fromStream(inputStream, callback) {\n if (callback) {\n this.fromStreamAsync(inputStream).then(() => callback(), callback);\n }\n else {\n return this.fromStreamAsync(inputStream);\n }\n }\n async fromStreamAsync(inputStream) {\n return new Promise((resolve, reject) => {\n if (!inputStream) {\n return reject(new Error('Must pass in a stream containing the user refresh token.'));\n }\n let s = '';\n inputStream\n .setEncoding('utf8')\n .on('error', reject)\n .on('data', chunk => (s += chunk))\n .on('end', () => {\n try {\n const data = JSON.parse(s);\n this.fromJSON(data);\n return resolve();\n }\n catch (err) {\n return reject(err);\n }\n });\n });\n }\n}\nexports.UserRefreshClient = UserRefreshClient;\n//# sourceMappingURL=refreshclient.js.map","\"use strict\";\n// Copyright 2019 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n/* global window */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.BrowserCrypto = void 0;\n// This file implements crypto functions we need using in-browser\n// SubtleCrypto interface `window.crypto.subtle`.\nconst base64js = require(\"base64-js\");\n// Not all browsers support `TextEncoder`. The following `require` will\n// provide a fast UTF8-only replacement for those browsers that don't support\n// text encoding natively.\n// eslint-disable-next-line node/no-unsupported-features/node-builtins\nif (typeof process === 'undefined' && typeof TextEncoder === 'undefined') {\n require('fast-text-encoding');\n}\nclass BrowserCrypto {\n constructor() {\n if (typeof window === 'undefined' ||\n window.crypto === undefined ||\n window.crypto.subtle === undefined) {\n throw new Error(\"SubtleCrypto not found. Make sure it's an https:// website.\");\n }\n }\n async sha256DigestBase64(str) {\n // SubtleCrypto digest() method is async, so we must make\n // this method async as well.\n // To calculate SHA256 digest using SubtleCrypto, we first\n // need to convert an input string to an ArrayBuffer:\n // eslint-disable-next-line node/no-unsupported-features/node-builtins\n const inputBuffer = new TextEncoder().encode(str);\n // Result is ArrayBuffer as well.\n const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer);\n return base64js.fromByteArray(new Uint8Array(outputBuffer));\n }\n randomBytesBase64(count) {\n const array = new Uint8Array(count);\n window.crypto.getRandomValues(array);\n return base64js.fromByteArray(array);\n }\n static padBase64(base64) {\n // base64js requires padding, so let's add some '='\n while (base64.length % 4 !== 0) {\n base64 += '=';\n }\n return base64;\n }\n async verify(pubkey, data, signature) {\n const algo = {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' },\n };\n // eslint-disable-next-line node/no-unsupported-features/node-builtins\n const dataArray = new TextEncoder().encode(data);\n const signatureArray = base64js.toByteArray(BrowserCrypto.padBase64(signature));\n const cryptoKey = await window.crypto.subtle.importKey('jwk', pubkey, algo, true, ['verify']);\n // SubtleCrypto's verify method is async so we must make\n // this method async as well.\n const result = await window.crypto.subtle.verify(algo, cryptoKey, signatureArray, dataArray);\n return result;\n }\n async sign(privateKey, data) {\n const algo = {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' },\n };\n // eslint-disable-next-line node/no-unsupported-features/node-builtins\n const dataArray = new TextEncoder().encode(data);\n const cryptoKey = await window.crypto.subtle.importKey('jwk', privateKey, algo, true, ['sign']);\n // SubtleCrypto's sign method is async so we must make\n // this method async as well.\n const result = await window.crypto.subtle.sign(algo, cryptoKey, dataArray);\n return base64js.fromByteArray(new Uint8Array(result));\n }\n decodeBase64StringUtf8(base64) {\n const uint8array = base64js.toByteArray(BrowserCrypto.padBase64(base64));\n // eslint-disable-next-line node/no-unsupported-features/node-builtins\n const result = new TextDecoder().decode(uint8array);\n return result;\n }\n encodeBase64StringUtf8(text) {\n // eslint-disable-next-line node/no-unsupported-features/node-builtins\n const uint8array = new TextEncoder().encode(text);\n const result = base64js.fromByteArray(uint8array);\n return result;\n }\n}\nexports.BrowserCrypto = BrowserCrypto;\n//# sourceMappingURL=crypto.js.map","\"use strict\";\n// Copyright 2019 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n/* global window */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.hasBrowserCrypto = exports.createCrypto = void 0;\nconst crypto_1 = require(\"./browser/crypto\");\nconst crypto_2 = require(\"./node/crypto\");\nfunction createCrypto() {\n if (hasBrowserCrypto()) {\n return new crypto_1.BrowserCrypto();\n }\n return new crypto_2.NodeCrypto();\n}\nexports.createCrypto = createCrypto;\nfunction hasBrowserCrypto() {\n return (typeof window !== 'undefined' &&\n typeof window.crypto !== 'undefined' &&\n typeof window.crypto.subtle !== 'undefined');\n}\nexports.hasBrowserCrypto = hasBrowserCrypto;\n//# sourceMappingURL=crypto.js.map","\"use strict\";\n// Copyright 2019 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.NodeCrypto = void 0;\nconst crypto = require(\"crypto\");\nclass NodeCrypto {\n async sha256DigestBase64(str) {\n return crypto.createHash('sha256').update(str).digest('base64');\n }\n randomBytesBase64(count) {\n return crypto.randomBytes(count).toString('base64');\n }\n async verify(pubkey, data, signature) {\n const verifier = crypto.createVerify('sha256');\n verifier.update(data);\n verifier.end();\n return verifier.verify(pubkey, signature, 'base64');\n }\n async sign(privateKey, data) {\n const signer = crypto.createSign('RSA-SHA256');\n signer.update(data);\n signer.end();\n return signer.sign(privateKey, 'base64');\n }\n decodeBase64StringUtf8(base64) {\n return Buffer.from(base64, 'base64').toString('utf-8');\n }\n encodeBase64StringUtf8(text) {\n return Buffer.from(text, 'utf-8').toString('base64');\n }\n}\nexports.NodeCrypto = NodeCrypto;\n//# sourceMappingURL=crypto.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.GoogleAuth = exports.auth = void 0;\n// Copyright 2017 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nconst googleauth_1 = require(\"./auth/googleauth\");\nObject.defineProperty(exports, \"GoogleAuth\", { enumerable: true, get: function () { return googleauth_1.GoogleAuth; } });\nvar computeclient_1 = require(\"./auth/computeclient\");\nObject.defineProperty(exports, \"Compute\", { enumerable: true, get: function () { return computeclient_1.Compute; } });\nvar envDetect_1 = require(\"./auth/envDetect\");\nObject.defineProperty(exports, \"GCPEnv\", { enumerable: true, get: function () { return envDetect_1.GCPEnv; } });\nvar iam_1 = require(\"./auth/iam\");\nObject.defineProperty(exports, \"IAMAuth\", { enumerable: true, get: function () { return iam_1.IAMAuth; } });\nvar idtokenclient_1 = require(\"./auth/idtokenclient\");\nObject.defineProperty(exports, \"IdTokenClient\", { enumerable: true, get: function () { return idtokenclient_1.IdTokenClient; } });\nvar jwtaccess_1 = require(\"./auth/jwtaccess\");\nObject.defineProperty(exports, \"JWTAccess\", { enumerable: true, get: function () { return jwtaccess_1.JWTAccess; } });\nvar jwtclient_1 = require(\"./auth/jwtclient\");\nObject.defineProperty(exports, \"JWT\", { enumerable: true, get: function () { return jwtclient_1.JWT; } });\nvar oauth2client_1 = require(\"./auth/oauth2client\");\nObject.defineProperty(exports, \"CodeChallengeMethod\", { enumerable: true, get: function () { return oauth2client_1.CodeChallengeMethod; } });\nObject.defineProperty(exports, \"OAuth2Client\", { enumerable: true, get: function () { return oauth2client_1.OAuth2Client; } });\nvar loginticket_1 = require(\"./auth/loginticket\");\nObject.defineProperty(exports, \"LoginTicket\", { enumerable: true, get: function () { return loginticket_1.LoginTicket; } });\nvar refreshclient_1 = require(\"./auth/refreshclient\");\nObject.defineProperty(exports, \"UserRefreshClient\", { enumerable: true, get: function () { return refreshclient_1.UserRefreshClient; } });\nvar transporters_1 = require(\"./transporters\");\nObject.defineProperty(exports, \"DefaultTransporter\", { enumerable: true, get: function () { return transporters_1.DefaultTransporter; } });\nconst auth = new googleauth_1.GoogleAuth();\nexports.auth = auth;\n//# sourceMappingURL=index.js.map","\"use strict\";\n// Copyright 2017 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.validate = void 0;\n// Accepts an options object passed from the user to the API. In the\n// previous version of the API, it referred to a `Request` options object.\n// Now it refers to an Axiox Request Config object. This is here to help\n// ensure users don't pass invalid options when they upgrade from 0.x to 1.x.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction validate(options) {\n const vpairs = [\n { invalid: 'uri', expected: 'url' },\n { invalid: 'json', expected: 'data' },\n { invalid: 'qs', expected: 'params' },\n ];\n for (const pair of vpairs) {\n if (options[pair.invalid]) {\n const e = `'${pair.invalid}' is not a valid configuration option. Please use '${pair.expected}' instead. This library is using Axios for requests. Please see https://github.com/axios/axios to learn more about the valid request options.`;\n throw new Error(e);\n }\n }\n}\nexports.validate = validate;\n//# sourceMappingURL=options.js.map","\"use strict\";\n// Copyright 2019 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DefaultTransporter = void 0;\nconst gaxios_1 = require(\"gaxios\");\nconst options_1 = require(\"./options\");\n// eslint-disable-next-line @typescript-eslint/no-var-requires\nconst pkg = require('../../package.json');\nconst PRODUCT_NAME = 'google-api-nodejs-client';\nclass DefaultTransporter {\n /**\n * Configures request options before making a request.\n * @param opts GaxiosOptions options.\n * @return Configured options.\n */\n configure(opts = {}) {\n opts.headers = opts.headers || {};\n if (typeof window === 'undefined') {\n // set transporter user agent if not in browser\n const uaValue = opts.headers['User-Agent'];\n if (!uaValue) {\n opts.headers['User-Agent'] = DefaultTransporter.USER_AGENT;\n }\n else if (!uaValue.includes(`${PRODUCT_NAME}/`)) {\n opts.headers['User-Agent'] = `${uaValue} ${DefaultTransporter.USER_AGENT}`;\n }\n // track google-auth-library-nodejs version:\n const authVersion = `auth/${pkg.version}`;\n if (opts.headers['x-goog-api-client'] &&\n !opts.headers['x-goog-api-client'].includes(authVersion)) {\n opts.headers['x-goog-api-client'] = `${opts.headers['x-goog-api-client']} ${authVersion}`;\n }\n else if (!opts.headers['x-goog-api-client']) {\n const nodeVersion = process.version.replace(/^v/, '');\n opts.headers['x-goog-api-client'] = `gl-node/${nodeVersion} ${authVersion}`;\n }\n }\n return opts;\n }\n request(opts, callback) {\n // ensure the user isn't passing in request-style options\n opts = this.configure(opts);\n try {\n options_1.validate(opts);\n }\n catch (e) {\n if (callback) {\n return callback(e);\n }\n else {\n throw e;\n }\n }\n if (callback) {\n gaxios_1.request(opts).then(r => {\n callback(null, r);\n }, e => {\n callback(this.processError(e));\n });\n }\n else {\n return gaxios_1.request(opts).catch(e => {\n throw this.processError(e);\n });\n }\n }\n /**\n * Changes the error to include details from the body.\n */\n processError(e) {\n const res = e.response;\n const err = e;\n const body = res ? res.data : null;\n if (res && body && body.error && res.status !== 200) {\n if (typeof body.error === 'string') {\n err.message = body.error;\n err.code = res.status.toString();\n }\n else if (Array.isArray(body.error.errors)) {\n err.message = body.error.errors\n .map((err2) => err2.message)\n .join('\\n');\n err.code = body.error.code;\n err.errors = body.error.errors;\n }\n else {\n err.message = body.error.message;\n err.code = body.error.code || res.status;\n }\n }\n else if (res && res.status >= 400) {\n // Consider all 4xx and 5xx responses errors.\n err.message = body;\n err.code = res.status.toString();\n }\n return err;\n }\n}\nexports.DefaultTransporter = DefaultTransporter;\n/**\n * Default user agent.\n */\nDefaultTransporter.USER_AGENT = `${PRODUCT_NAME}/${pkg.version}`;\n//# sourceMappingURL=transporters.js.map","'use strict';\n\nconst arrify = value => {\n\tif (value === null || value === undefined) {\n\t\treturn [];\n\t}\n\n\tif (Array.isArray(value)) {\n\t\treturn value;\n\t}\n\n\tif (typeof value === 'string') {\n\t\treturn [value];\n\t}\n\n\tif (typeof value[Symbol.iterator] === 'function') {\n\t\treturn [...value];\n\t}\n\n\treturn [value];\n};\n\nmodule.exports = arrify;\n","\"use strict\";\n/**\n * Copyright 2018 Google LLC\n *\n * Distributed under MIT license.\n * See file LICENSE for detail or copy at https://opensource.org/licenses/MIT\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getPem = void 0;\nconst fs = require(\"fs\");\nconst forge = require(\"node-forge\");\nconst util_1 = require(\"util\");\nconst readFile = util_1.promisify(fs.readFile);\nfunction getPem(filename, callback) {\n if (callback) {\n getPemAsync(filename)\n .then(pem => callback(null, pem))\n .catch(err => callback(err, null));\n }\n else {\n return getPemAsync(filename);\n }\n}\nexports.getPem = getPem;\nfunction getPemAsync(filename) {\n return readFile(filename, { encoding: 'base64' }).then(keyp12 => {\n return convertToPem(keyp12);\n });\n}\n/**\n * Converts a P12 in base64 encoding to a pem.\n * @param p12base64 String containing base64 encoded p12.\n * @returns a string containing the pem.\n */\nfunction convertToPem(p12base64) {\n const p12Der = forge.util.decode64(p12base64);\n const p12Asn1 = forge.asn1.fromDer(p12Der);\n const p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1, 'notasecret');\n const bags = p12.getBags({ friendlyName: 'privatekey' });\n if (bags.friendlyName) {\n const privateKey = bags.friendlyName[0].key;\n const pem = forge.pki.privateKeyToPem(privateKey);\n return pem.replace(/\\r\\n/g, '\\n');\n }\n else {\n throw new Error('Unable to get friendly name.');\n }\n}\n//# sourceMappingURL=index.js.map","var $jscomp=$jscomp||{};$jscomp.scope={};$jscomp.findInternal=function(a,b,c){a instanceof String&&(a=String(a));for(var d=a.length,e=0;e=e}},\"es6\",\"es3\");$jscomp.polyfill(\"Array.prototype.find\",function(a){return a?a:function(a,c){return $jscomp.findInternal(this,a,c).v}},\"es6\",\"es3\");\n$jscomp.polyfill(\"String.prototype.startsWith\",function(a){return a?a:function(a,c){var b=$jscomp.checkStringArgs(this,a,\"startsWith\");a+=\"\";var e=b.length,f=a.length;c=Math.max(0,Math.min(c|0,b.length));for(var g=0;g=f}},\"es6\",\"es3\");\n$jscomp.polyfill(\"String.prototype.repeat\",function(a){return a?a:function(a){var b=$jscomp.checkStringArgs(this,null,\"repeat\");if(0>a||1342177279>>=1)b+=b;return d}},\"es6\",\"es3\");var COMPILED=!0,goog=goog||{};goog.global=this||self;goog.isDef=function(a){return void 0!==a};goog.isString=function(a){return\"string\"==typeof a};goog.isBoolean=function(a){return\"boolean\"==typeof a};\ngoog.isNumber=function(a){return\"number\"==typeof a};goog.exportPath_=function(a,b,c){a=a.split(\".\");c=c||goog.global;a[0]in c||\"undefined\"==typeof c.execScript||c.execScript(\"var \"+a[0]);for(var d;a.length&&(d=a.shift());)!a.length&&goog.isDef(b)?c[d]=b:c=c[d]&&c[d]!==Object.prototype[d]?c[d]:c[d]={}};\ngoog.define=function(a,b){if(!COMPILED){var c=goog.global.CLOSURE_UNCOMPILED_DEFINES,d=goog.global.CLOSURE_DEFINES;c&&void 0===c.nodeType&&Object.prototype.hasOwnProperty.call(c,a)?b=c[a]:d&&void 0===d.nodeType&&Object.prototype.hasOwnProperty.call(d,a)&&(b=d[a])}return b};goog.FEATURESET_YEAR=2012;goog.DEBUG=!0;goog.LOCALE=\"en\";goog.TRUSTED_SITE=!0;goog.STRICT_MODE_COMPATIBLE=!1;goog.DISALLOW_TEST_ONLY_CODE=COMPILED&&!goog.DEBUG;goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING=!1;\ngoog.provide=function(a){if(goog.isInModuleLoader_())throw Error(\"goog.provide cannot be used within a module.\");if(!COMPILED&&goog.isProvided_(a))throw Error('Namespace \"'+a+'\" already declared.');goog.constructNamespace_(a)};goog.constructNamespace_=function(a,b){if(!COMPILED){delete goog.implicitNamespaces_[a];for(var c=a;(c=c.substring(0,c.lastIndexOf(\".\")))&&!goog.getObjectByName(c);)goog.implicitNamespaces_[c]=!0}goog.exportPath_(a,b)};\ngoog.getScriptNonce=function(a){if(a&&a!=goog.global)return goog.getScriptNonce_(a.document);null===goog.cspNonce_&&(goog.cspNonce_=goog.getScriptNonce_(goog.global.document));return goog.cspNonce_};goog.NONCE_PATTERN_=/^[\\w+/_-]+[=]{0,2}$/;goog.cspNonce_=null;goog.getScriptNonce_=function(a){return(a=a.querySelector&&a.querySelector(\"script[nonce]\"))&&(a=a.nonce||a.getAttribute(\"nonce\"))&&goog.NONCE_PATTERN_.test(a)?a:\"\"};goog.VALID_MODULE_RE_=/^[a-zA-Z_$][a-zA-Z0-9._$]*$/;\ngoog.module=function(a){if(!goog.isString(a)||!a||-1==a.search(goog.VALID_MODULE_RE_))throw Error(\"Invalid module identifier\");if(!goog.isInGoogModuleLoader_())throw Error(\"Module \"+a+\" has been loaded incorrectly. Note, modules cannot be loaded as normal scripts. They require some kind of pre-processing step. You're likely trying to load a module via a script tag or as a part of a concatenated bundle without rewriting the module. For more info see: https://github.com/google/closure-library/wiki/goog.module:-an-ES6-module-like-alternative-to-goog.provide.\");\nif(goog.moduleLoaderState_.moduleName)throw Error(\"goog.module may only be called once per module.\");goog.moduleLoaderState_.moduleName=a;if(!COMPILED){if(goog.isProvided_(a))throw Error('Namespace \"'+a+'\" already declared.');delete goog.implicitNamespaces_[a]}};goog.module.get=function(a){return goog.module.getInternal_(a)};\ngoog.module.getInternal_=function(a){if(!COMPILED){if(a in goog.loadedModules_)return goog.loadedModules_[a].exports;if(!goog.implicitNamespaces_[a])return a=goog.getObjectByName(a),null!=a?a:null}return null};goog.ModuleType={ES6:\"es6\",GOOG:\"goog\"};goog.moduleLoaderState_=null;goog.isInModuleLoader_=function(){return goog.isInGoogModuleLoader_()||goog.isInEs6ModuleLoader_()};goog.isInGoogModuleLoader_=function(){return!!goog.moduleLoaderState_&&goog.moduleLoaderState_.type==goog.ModuleType.GOOG};\ngoog.isInEs6ModuleLoader_=function(){if(goog.moduleLoaderState_&&goog.moduleLoaderState_.type==goog.ModuleType.ES6)return!0;var a=goog.global.$jscomp;return a?\"function\"!=typeof a.getCurrentModulePath?!1:!!a.getCurrentModulePath():!1};\ngoog.module.declareLegacyNamespace=function(){if(!COMPILED&&!goog.isInGoogModuleLoader_())throw Error(\"goog.module.declareLegacyNamespace must be called from within a goog.module\");if(!COMPILED&&!goog.moduleLoaderState_.moduleName)throw Error(\"goog.module must be called prior to goog.module.declareLegacyNamespace.\");goog.moduleLoaderState_.declareLegacyNamespace=!0};\ngoog.declareModuleId=function(a){if(!COMPILED){if(!goog.isInEs6ModuleLoader_())throw Error(\"goog.declareModuleId may only be called from within an ES6 module\");if(goog.moduleLoaderState_&&goog.moduleLoaderState_.moduleName)throw Error(\"goog.declareModuleId may only be called once per module.\");if(a in goog.loadedModules_)throw Error('Module with namespace \"'+a+'\" already exists.');}if(goog.moduleLoaderState_)goog.moduleLoaderState_.moduleName=a;else{var b=goog.global.$jscomp;if(!b||\"function\"!=typeof b.getCurrentModulePath)throw Error('Module with namespace \"'+\na+'\" has been loaded incorrectly.');b=b.require(b.getCurrentModulePath());goog.loadedModules_[a]={exports:b,type:goog.ModuleType.ES6,moduleId:a}}};goog.setTestOnly=function(a){if(goog.DISALLOW_TEST_ONLY_CODE)throw a=a||\"\",Error(\"Importing test-only code into non-debug environment\"+(a?\": \"+a:\".\"));};goog.forwardDeclare=function(a){};\nCOMPILED||(goog.isProvided_=function(a){return a in goog.loadedModules_||!goog.implicitNamespaces_[a]&&goog.isDefAndNotNull(goog.getObjectByName(a))},goog.implicitNamespaces_={\"goog.module\":!0});goog.getObjectByName=function(a,b){a=a.split(\".\");b=b||goog.global;for(var c=0;c>>0);goog.uidCounter_=0;goog.getHashCode=goog.getUid;\ngoog.removeHashCode=goog.removeUid;goog.cloneObject=function(a){var b=goog.typeOf(a);if(\"object\"==b||\"array\"==b){if(\"function\"===typeof a.clone)return a.clone();b=\"array\"==b?[]:{};for(var c in a)b[c]=goog.cloneObject(a[c]);return b}return a};goog.bindNative_=function(a,b,c){return a.call.apply(a.bind,arguments)};\ngoog.bindJs_=function(a,b,c){if(!a)throw Error();if(2{\"use strict\";class X{constructor(){if(new.target!=String)throw 1;this.x=42}}let q=Reflect.construct(X,[],String);if(q.x!=42||!(q instanceof String))throw 1;for(const a of[2,3]){if(a==2)continue;function f(z={a}){let a=0;return z.a}{function f(){return 0;}}return f()==3}})()')});\na(\"es7\",function(){return b(\"2 ** 2 == 4\")});a(\"es8\",function(){return b(\"async () => 1, true\")});a(\"es9\",function(){return b(\"({...rest} = {}), true\")});a(\"es_next\",function(){return!1});return{target:c,map:d}},goog.Transpiler.prototype.needsTranspile=function(a,b){if(\"always\"==goog.TRANSPILE)return!0;if(\"never\"==goog.TRANSPILE)return!1;if(!this.requiresTranspilation_){var c=this.createRequiresTranspilation_();this.requiresTranspilation_=c.map;this.transpilationTarget_=this.transpilationTarget_||\nc.target}if(a in this.requiresTranspilation_)return this.requiresTranspilation_[a]?!0:!goog.inHtmlDocument_()||\"es6\"!=b||\"noModule\"in goog.global.document.createElement(\"script\")?!1:!0;throw Error(\"Unknown language mode: \"+a);},goog.Transpiler.prototype.transpile=function(a,b){return goog.transpile_(a,b,this.transpilationTarget_)},goog.transpiler_=new goog.Transpiler,goog.protectScriptTag_=function(a){return a.replace(/<\\/(SCRIPT)/ig,\"\\\\x3c/$1\")},goog.DebugLoader_=function(){this.dependencies_={};\nthis.idToPath_={};this.written_={};this.loadingDeps_=[];this.depsToLoad_=[];this.paused_=!1;this.factory_=new goog.DependencyFactory(goog.transpiler_);this.deferredCallbacks_={};this.deferredQueue_=[]},goog.DebugLoader_.prototype.bootstrap=function(a,b){function c(){d&&(goog.global.setTimeout(d,0),d=null)}var d=b;if(a.length){b=[];for(var e=0;e\\x3c/script>\";b.write(goog.TRUSTED_TYPES_POLICY_?goog.TRUSTED_TYPES_POLICY_.createHTML(d):d)}else{var e=b.createElement(\"script\");e.defer=goog.Dependency.defer_;e.async=!1;e.type=\"text/javascript\";(d=goog.getScriptNonce())&&e.setAttribute(\"nonce\",d);goog.DebugLoader_.IS_OLD_IE_?\n(a.pause(),e.onreadystatechange=function(){if(\"loaded\"==e.readyState||\"complete\"==e.readyState)a.loaded(),a.resume()}):e.onload=function(){e.onload=null;a.loaded()};e.src=goog.TRUSTED_TYPES_POLICY_?goog.TRUSTED_TYPES_POLICY_.createScriptURL(this.path):this.path;b.head.appendChild(e)}}else goog.logToConsole_(\"Cannot use default debug loader outside of HTML documents.\"),\"deps.js\"==this.relativePath?(goog.logToConsole_(\"Consider setting CLOSURE_IMPORT_SCRIPT before loading base.js, or setting CLOSURE_NO_DEPS to true.\"),\na.loaded()):a.pause()},goog.Es6ModuleDependency=function(a,b,c,d,e){goog.Dependency.call(this,a,b,c,d,e)},goog.inherits(goog.Es6ModuleDependency,goog.Dependency),goog.Es6ModuleDependency.prototype.load=function(a){function b(a,b){a=b?'